repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
53 values
size
stringlengths
2
6
content
stringlengths
73
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
977
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
androidx/androidx
compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/lower/decoys/AbstractDecoysLowering.kt
3
3809
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.compiler.plugins.kotlin.lower.decoys import androidx.compose.compiler.plugins.kotlin.ComposeFqNames import androidx.compose.compiler.plugins.kotlin.ModuleMetrics import androidx.compose.compiler.plugins.kotlin.lower.AbstractComposeLowering import androidx.compose.compiler.plugins.kotlin.lower.includeFileNameInExceptionTrace import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.backend.common.serialization.signature.IdSignatureSerializer import org.jetbrains.kotlin.ir.declarations.IrConstructor import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin import org.jetbrains.kotlin.ir.declarations.IrFile import org.jetbrains.kotlin.ir.declarations.IrFunction import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction import org.jetbrains.kotlin.ir.types.IrSimpleType import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.util.DeepCopySymbolRemapper import org.jetbrains.kotlin.ir.util.hasAnnotation import org.jetbrains.kotlin.ir.util.isEnumClass import org.jetbrains.kotlin.ir.util.isLocal import org.jetbrains.kotlin.ir.util.parentAsClass abstract class AbstractDecoysLowering( pluginContext: IrPluginContext, symbolRemapper: DeepCopySymbolRemapper, metrics: ModuleMetrics, override val signatureBuilder: IdSignatureSerializer, ) : AbstractComposeLowering( context = pluginContext, symbolRemapper = symbolRemapper, metrics = metrics ), DecoyTransformBase { override fun visitFile(declaration: IrFile): IrFile { includeFileNameInExceptionTrace(declaration) { var file: IrFile = declaration // since kotlin 1.6.0-RC2 signatureBuilder needs to "know" fileSignature available // within inFile scope. It's necessary to ensure signatures calc for private top level // decoys. signatureBuilder.inFile(file = declaration.symbol) { file = super.visitFile(declaration) } return file } } protected fun IrFunction.shouldBeRemapped(): Boolean = !isLocalFunction() && !isEnumConstructor() && (hasComposableAnnotation() || hasComposableParameter()) private fun IrFunction.isLocalFunction(): Boolean = origin == IrDeclarationOrigin.LOCAL_FUNCTION_FOR_LAMBDA || (isLocal && (this is IrSimpleFunction && !overridesComposable())) private fun IrSimpleFunction.overridesComposable() = overriddenSymbols.any { it.owner.isDecoy() || it.owner.shouldBeRemapped() } private fun IrFunction.hasComposableParameter() = valueParameters.any { it.type.hasComposable() } || extensionReceiverParameter?.type?.hasComposable() == true private fun IrFunction.isEnumConstructor() = this is IrConstructor && parentAsClass.isEnumClass private fun IrType.hasComposable(): Boolean { if (hasAnnotation(ComposeFqNames.Composable)) { return true } return when (this) { is IrSimpleType -> arguments.any { (it as? IrType)?.hasComposable() == true } else -> false } } }
apache-2.0
f408fccd72499d822516595d690f9fec
39.967742
98
0.732738
4.731677
false
false
false
false
pbauerochse/youtrack-worklog-viewer
application/src/main/java/de/pbauerochse/worklogviewer/fx/components/plugins/PluginDetailPopupContent.kt
1
1473
package de.pbauerochse.worklogviewer.fx.components.plugins import de.pbauerochse.worklogviewer.WorklogViewer import de.pbauerochse.worklogviewer.plugins.WorklogViewerPlugin import de.pbauerochse.worklogviewer.setHref import javafx.fxml.FXML import javafx.fxml.FXMLLoader import javafx.fxml.Initializable import javafx.scene.control.Hyperlink import javafx.scene.control.Label import javafx.scene.layout.VBox import java.net.URL import java.util.* /** * Displays basic information about the plugin */ class PluginDetailPopupContent(private val plugin: WorklogViewerPlugin) : VBox(), Initializable { @FXML private lateinit var pluginNameLabel: Label @FXML private lateinit var pluginVersionLabel: Label @FXML private lateinit var pluginVendorLink: Hyperlink @FXML private lateinit var pluginDescriptionLabel: Label init { val loader = FXMLLoader(WorklogViewer::class.java.getResource("/fx/views/plugin-details.fxml")) loader.setRoot(this) loader.setController(this) loader.load<PluginDetailPopupContent>() } override fun initialize(p0: URL?, p1: ResourceBundle?) { pluginNameLabel.text = plugin.name pluginVersionLabel.text = plugin.version.toString() pluginVendorLink.text = plugin.author.name pluginDescriptionLabel.text = plugin.description plugin.author.website?.let { pluginVendorLink.setHref(it.toExternalForm()) } } }
mit
78fd9a10fab387e51248eefd4186e04c
29.081633
103
0.745418
4.546296
false
false
false
false
inorichi/tachiyomi-extensions
src/all/toomics/src/eu/kanade/tachiyomi/extension/all/toomics/ToomicsGlobal.kt
1
6700
package eu.kanade.tachiyomi.extension.all.toomics import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.Headers import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import org.jsoup.nodes.Document import org.jsoup.nodes.Element import rx.Observable import java.net.URLDecoder import java.text.ParseException import java.text.SimpleDateFormat import java.util.concurrent.TimeUnit abstract class ToomicsGlobal( private val siteLang: String, private val dateFormat: SimpleDateFormat, override val lang: String = siteLang, displayName: String = "" ) : ParsedHttpSource() { override val name = "Toomics (Only free chapters)" + (if (displayName.isNotEmpty()) " ($displayName)" else "") override val baseUrl = "https://global.toomics.com" override val supportsLatest = true override val client: OkHttpClient = super.client.newBuilder() .connectTimeout(1, TimeUnit.MINUTES) .readTimeout(1, TimeUnit.MINUTES) .writeTimeout(1, TimeUnit.MINUTES) .build() override fun headersBuilder(): Headers.Builder = Headers.Builder() .add("Referer", "$baseUrl/$siteLang") .add("User-Agent", USER_AGENT) override fun popularMangaRequest(page: Int): Request { return GET("$baseUrl/$siteLang/webtoon/favorite", headers) } // ToomicsGlobal does not have a popular list, so use recommended instead. override fun popularMangaSelector(): String = "li > div.visual" override fun popularMangaFromElement(element: Element): SManga = SManga.create().apply { title = element.select("h4[class$=title]").first().ownText() // sometimes href contains "/ab/on" at the end and redirects to a chapter instead of manga setUrlWithoutDomain(element.select("a").attr("href").removeSuffix("/ab/on")) thumbnail_url = element.select("img").attr("src") } override fun popularMangaNextPageSelector(): String? = null override fun latestUpdatesRequest(page: Int): Request { return GET("$baseUrl/$siteLang/webtoon/new_comics", headers) } override fun latestUpdatesSelector(): String = popularMangaSelector() override fun latestUpdatesFromElement(element: Element): SManga = popularMangaFromElement(element) override fun latestUpdatesNextPageSelector(): String? = null override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val newHeaders = headersBuilder() .add("Content-Type", "application/x-www-form-urlencoded") .build() val rbody = RequestBody.create(null, "toonData=$query&offset=0&limit=20") return POST("$baseUrl/$siteLang/webtoon/ajax_search", newHeaders, rbody) } override fun searchMangaSelector(): String = "div.recently_list ul li" override fun searchMangaFromElement(element: Element): SManga = SManga.create().apply { title = element.select("a div.search_box dl dt span.title").text() thumbnail_url = element.select("div.search_box p.img img").attr("abs:src") // When the family mode is off, the url is encoded and is available in the onclick. element.select("a:not([href^=javascript])").let { if (it != null) { setUrlWithoutDomain(it.attr("href")) } else { val toonId = element.select("a").attr("onclick") .substringAfter("Base.setDisplay('A', '") .substringBefore("'") .let { url -> URLDecoder.decode(url, "UTF-8") } .substringAfter("?toon=") .substringBefore("&") url = "/$siteLang/webtoon/episode/toon/$toonId" } } } override fun searchMangaNextPageSelector(): String? = null override fun mangaDetailsParse(document: Document): SManga = SManga.create().apply { val header = document.select("#glo_contents header.ep-cover_ch div.title_content") title = header.select("h1").text() author = header.select("p.type_box span.writer").text() artist = header.select("p.type_box span.writer").text() genre = header.select("p.type_box span.type").text().replace("/", ",") description = header.select("h2").text() thumbnail_url = document.select("head meta[property='og:image']").attr("content") } override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> { return super.fetchChapterList(manga) .map { it.reversed() } } // coin-type1 - free chapter, coin-type6 - already read chapter override fun chapterListSelector(): String = "li.normal_ep:has(.coin-type1, .coin-type6)" override fun chapterFromElement(element: Element): SChapter = SChapter.create().apply { val num = element.select("div.cell-num").text() val numText = if (num.isNotEmpty()) "$num - " else "" name = numText + element.select("div.cell-title strong")?.first()?.ownText() chapter_number = num.toFloatOrNull() ?: -1f date_upload = parseChapterDate(element.select("div.cell-time time").text()!!) scanlator = "Toomics" url = element.select("a").attr("onclick") .substringAfter("href='") .substringBefore("'") } override fun pageListParse(document: Document): List<Page> { if (document.select("div.section_age_verif").isNotEmpty()) throw Exception("Verify age via WebView") val url = document.select("head meta[property='og:url']").attr("content") return document.select("div[id^=load_image_] img") .mapIndexed { i, el -> Page(i, url, el.attr("data-src")) } } override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not used") override fun imageRequest(page: Page): Request { val newHeaders = headers.newBuilder() .set("Referer", page.url) .build() return GET(page.imageUrl!!, newHeaders) } private fun parseChapterDate(date: String): Long { return try { dateFormat.parse(date)?.time ?: 0L } catch (e: ParseException) { 0L } } companion object { private const val USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36" } }
apache-2.0
145750ee2334eb36312d30f81af8f915
38.880952
156
0.656567
4.342191
false
false
false
false
Incrementive/splay
src/main/kotlin/com/incrementive/splay/Pile.kt
1
1462
package com.incrementive.splay import com.incrementive.splay.Splay.none import com.incrementive.splay.Splay.right import java.util.* class Pile(val name: String, private val splay: Splay = none, private val visibleTo: Set<Player>, deck: Set<Card> = emptySet()) { val cardCount get() = cards.size private val cards = deck.toMutableList() fun draw() = cards.removeAt(cards.lastIndex) fun take(index: Int) = cards.removeAt(index) fun place(card: Card) = cards.add(card) fun render(player: Player) = "$name: Card count: $cardCount" + if (cards.isEmpty()) "" else ", " + when (player) { in visibleTo -> when (splay) { none -> "Top Card: " + cards.last() right -> "Cards: " + cards.joinToString(separator = " ") } else -> "cards not visible" } override fun equals(other: Any?) = other is Pile && name == other.name && splay == other.splay && visibleTo == other.visibleTo && cards == other.cards override fun hashCode() = Objects.hash(name, splay, visibleTo, cards) override fun toString(): String { return "Pile(name='$name', splay=$splay, visibleTo=$visibleTo, cards=$cards)" } }
mit
1af4b744439eb9d16a7485863bf8ea6b
31.511111
129
0.518468
4.28739
false
false
false
false
Benestar/focus-android
app/src/main/java/org/mozilla/focus/shortcut/IconGenerator.kt
1
5074
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.shortcut import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.net.Uri import android.os.Build import android.support.annotation.VisibleForTesting import android.support.v4.content.ContextCompat import android.util.TypedValue import org.mozilla.focus.R import org.mozilla.focus.utils.UrlUtils class IconGenerator { companion object { private val TEXT_SIZE_DP = 36f private val DEFAULT_ICON_CHAR = "?" /** * Use the given raw website icon and generate a launcher icon from it. If the given icon is null * or too small then an icon will be generated based on the website's URL. The icon will be drawn * on top of a generic launcher icon shape that we provide. */ @JvmStatic fun generateLauncherIcon(context: Context, url: String?) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { generateAdaptiveLauncherIcon(context, url) } else { generateLauncherIconPreOreo(context, url) } /* * This method needs to be separate from generateAdaptiveLauncherIcon so that we can generate * the pre-Oreo icon to display in the Add To Home screen Dialog */ @JvmStatic fun generateLauncherIconPreOreo(context: Context, url: String?): Bitmap { val options = BitmapFactory.Options() options.inMutable = true val shape = BitmapFactory.decodeResource(context.resources, R.drawable.ic_homescreen_shape, options) return drawCharacterOnBitmap(context, url, shape) } /** * Generates a launcher icon for versions of Android that support Adaptive Icons (Oreo+): * https://developer.android.com/guide/practices/ui_guidelines/icon_design_adaptive.html */ private fun generateAdaptiveLauncherIcon(context: Context, url: String?): Bitmap { val res = context.resources val adaptiveIconDimen = res.getDimensionPixelSize(R.dimen.adaptive_icon_drawable_dimen) val bitmap = Bitmap.createBitmap(adaptiveIconDimen, adaptiveIconDimen, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) // Adaptive Icons have two layers: a background that fills the canvas and // a foreground that's centered. First, we draw the background... canvas.drawColor(ContextCompat.getColor(context, R.color.add_to_homescreen_icon_background)) // Then draw the foreground return drawCharacterOnBitmap(context, url, bitmap) } private fun drawCharacterOnBitmap(context: Context, url: String?, bitmap: Bitmap): Bitmap { val canvas = Canvas(bitmap) val paint = Paint() val character = getRepresentativeCharacter(url) val textSize = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, TEXT_SIZE_DP, context.resources.displayMetrics) paint.color = Color.WHITE paint.textAlign = Paint.Align.CENTER paint.textSize = textSize paint.isAntiAlias = true canvas.drawText(character, canvas.width / 2.0f, canvas.height / 2.0f - (paint.descent() + paint.ascent()) / 2.0f, paint) return bitmap } /** * Get a representative character for the given URL. * * For example this method will return "f" for "http://m.facebook.com/foobar". */ @VisibleForTesting internal fun getRepresentativeCharacter(url: String?): String { val firstChar = getRepresentativeSnippet(url)?.find { it.isLetterOrDigit() }?.toUpperCase() return (firstChar ?: DEFAULT_ICON_CHAR).toString() } /** * Get the representative part of the URL. Usually this is the host (without common prefixes). * * @return the representative snippet or null if one could not be found. */ private fun getRepresentativeSnippet(url: String?): String? { if (url == null || url.isEmpty()) return null val uri = Uri.parse(url) val snippet = if (!uri.host.isNullOrEmpty()) { uri.host // cached by Uri class. } else if (!uri.path.isNullOrEmpty()) { // The uri may not have a host for e.g. file:// uri uri.path // cached by Uri class. } else { return null } // Strip common prefixes that we do not want to use to determine the representative characters return UrlUtils.stripCommonSubdomains(snippet) } } }
mpl-2.0
bc5badf78f59026865ffdbc8d2ce5e06
39.592
120
0.636184
4.711235
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/wheelchair_access/AddWheelchairAccessOutside.kt
1
1082
package de.westnordost.streetcomplete.quests.wheelchair_access import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.meta.updateWithCheckDate import de.westnordost.streetcomplete.data.osm.osmquest.OsmFilterQuestType import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder class AddWheelchairAccessOutside : OsmFilterQuestType<WheelchairAccess>() { override val elementFilter = """ nodes, ways, relations with leisure = dog_park and (!wheelchair or wheelchair older today -8 years) """ override val commitMessage = "Add wheelchair access to outside places" override val wikiLink = "Key:wheelchair" override val icon = R.drawable.ic_quest_toilets_wheelchair override fun getTitle(tags: Map<String, String>) = R.string.quest_wheelchairAccess_outside_title override fun createForm() = AddWheelchairAccessOutsideForm() override fun applyAnswerTo(answer: WheelchairAccess, changes: StringMapChangesBuilder) { changes.updateWithCheckDate("wheelchair", answer.osmValue) } }
gpl-3.0
05adc9065abce5f54f8dc813522d1a3e
42.28
100
0.780961
5.009259
false
false
false
false
kamontat/CheckIDNumberA
app/src/main/java/com/kamontat/checkidnumber/model/Pool.kt
1
1762
package com.kamontat.checkidnumber.model import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.TextView import java.io.Serializable import java.util.* /** * @author kamontat * * * @version 1.0 * * * @since Thu 11/May/2017 - 9:20 PM */ class Pool(context: Context) : ArrayAdapter<IDNumber>(context, android.R.layout.two_line_list_item, android.R.id.text1), Serializable { private var idNumbers: ArrayList<IDNumber> = ArrayList<IDNumber>() override fun add(`object`: IDNumber?) { super.add(`object`) `object`?.let { idNumbers.add(it) } } override fun remove(`object`: IDNumber?) { super.remove(`object`) idNumbers.remove(`object`) } override fun clear() { super.clear() idNumbers.clear() } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var view = convertView if (view == null) view = LayoutInflater.from(context).inflate(android.R.layout.two_line_list_item, parent, false) val textView1 = view!!.findViewById(android.R.id.text1) as TextView val textView2 = view.findViewById(android.R.id.text2) as TextView val idNumber = getItem(position) ?: return super.getView(position, view, parent) textView1.text = idNumber.getId() textView2.text = String.format(Locale.ENGLISH, "Status: %s", idNumber.status.toString()) textView2.setTextColor(idNumber.status.getColor(context.resources)) return super.getView(position, view, parent) } fun getIDNumbers(): Array<IDNumber> { return idNumbers.toTypedArray() } }
mit
6d90d9e7d61cf430dd3c2fa2ef8550b0
28.864407
135
0.677072
3.813853
false
false
false
false
Exaltead/SceneClassifier
SceneClassifier/app/src/main/java/com/exaltead/sceneclassifier/ui/ClassificationFragment.kt
1
1640
package com.exaltead.sceneclassifier.ui import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.exaltead.sceneclassifier.R import com.exaltead.sceneclassifier.classification.ClassificationResult import kotlinx.android.synthetic.main.classification_fragment.view.* class ClassificationFragment: Fragment() { private lateinit var adapter: ClassificationAdapter private lateinit var viewModel: ClassificationViewModel override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View { viewModel = ViewModelProviders.of(activity).get(ClassificationViewModel::class.java) val view = inflater!!.inflate(R.layout.classification_fragment, container, false) adapter = ClassificationAdapter(this.context, R.layout.classification_view) view.classifications.adapter = adapter viewModel.data.observe(this, Observer {t -> updateListing(t)} ) startListUpdate() return view } override fun onPause() { super.onPause() endListUpdate() } private fun updateListing(newListing: List<ClassificationResult>?){ adapter.setContentAndNotify(newListing) } private fun startListUpdate(){ val parent = activity as MainActivity parent.startClassification() } private fun endListUpdate(){ val parent = activity as MainActivity parent.endClassification() } }
gpl-3.0
c632e126cf7fcfb69a8bf1826f074dc9
32.489796
116
0.746951
4.781341
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/DataLayerListenerServiceMobileHelper.kt
1
2889
package info.nightscout.androidaps.plugins.general.wear.wearintegration import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.IBinder import info.nightscout.androidaps.interfaces.NotificationHolder import javax.inject.Inject import javax.inject.Singleton /* This code replaces following val alarm = Intent(context, DataLayerListenerServiceMobile::class.java) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(alarm) else context.startService(alarm) it fails randomly with error Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{e317f7e u0 info.nightscout.nsclient/info.nightscout.androidaps.services.DataLayerListenerServiceMobile} */ @Singleton class DataLayerListenerServiceMobileHelper @Inject constructor( private val notificationHolder: NotificationHolder ) { fun startService(context: Context) { val connection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName?, service: IBinder?) { // The binder of the service that returns the instance that is created. val binder: DataLayerListenerServiceMobile.LocalBinder = service as DataLayerListenerServiceMobile.LocalBinder val dataLayerListenerServiceMobile: DataLayerListenerServiceMobile = binder.getService() context.startForegroundService(Intent(context, DataLayerListenerServiceMobile::class.java)) // This is the key: Without waiting Android Framework to call this method // inside Service.onCreate(), immediately call here to post the notification. dataLayerListenerServiceMobile.startForeground(notificationHolder.notificationID, notificationHolder.notification) // Release the connection to prevent leaks. context.unbindService(this) } override fun onServiceDisconnected(name: ComponentName?) { } } try { context.bindService(Intent(context, DataLayerListenerServiceMobile::class.java), connection, Context.BIND_AUTO_CREATE) } catch (ignored: RuntimeException) { // This is probably a broadcast receiver context even though we are calling getApplicationContext(). // Just call startForegroundService instead since we cannot bind a service to a // broadcast receiver context. The service also have to call startForeground in // this case. context.startForegroundService(Intent(context, DataLayerListenerServiceMobile::class.java)) } } fun stopService(context: Context) { context.stopService(Intent(context, DataLayerListenerServiceMobile::class.java)) } }
agpl-3.0
113e82738a661cf814ecb8ab37d685ed
45.612903
199
0.731741
5.450943
false
false
false
false
Heiner1/AndroidAPS
danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetExtendedBolusStart.kt
1
1240
package info.nightscout.androidaps.danar.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.shared.logging.LTag class MsgSetExtendedBolusStart( injector: HasAndroidInjector, private var amount: Double, private var halfhours: Byte ) : MessageBase(injector) { init { setCommand(0x0407) aapsLogger.debug(LTag.PUMPBTCOMM, "New message") // HARDCODED LIMITS if (halfhours < 1) halfhours = 1 if (halfhours > 16) halfhours = 16 amount = constraintChecker.applyBolusConstraints(Constraint(amount)).value() addParamInt((amount * 100).toInt()) addParamByte(halfhours) aapsLogger.debug(LTag.PUMPBTCOMM, "Set extended bolus start: " + (amount * 100).toInt() / 100.0 + "U halfhours: " + halfhours.toInt()) } override fun handleMessage(bytes: ByteArray) { val result = intFromBuff(bytes, 0, 1) if (result != 1) { failed = true aapsLogger.debug(LTag.PUMPBTCOMM, "Set extended bolus start result: $result FAILED!!!") } else { aapsLogger.debug(LTag.PUMPBTCOMM, "Set extended bolus start result: $result") } } }
agpl-3.0
d94240cb1829d6e9c07f073e1739fc59
34.457143
142
0.664516
4.305556
false
false
false
false
bloopletech/stories-app
app/src/main/java/net/bloople/stories/DatabaseHelper.kt
1
3414
package net.bloople.stories import android.content.Context import android.database.sqlite.SQLiteDatabase import java.io.FileInputStream import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.io.OutputStream internal object DatabaseHelper { private const val DB_NAME = "books" private lateinit var database: SQLiteDatabase private fun obtainDatabase(context: Context): SQLiteDatabase { val db = context.applicationContext.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null) loadSchema(db) return db } private fun loadSchema(db: SQLiteDatabase) { db.execSQL( "CREATE TABLE IF NOT EXISTS books ( " + "_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "path TEXT, " + "title TEXT, " + "mtime INT DEFAULT 0, " + "size INTEGER DEFAULT 0, " + "last_opened_at INTEGER DEFAULT 0, " + "last_read_position INTEGER DEFAULT 0" + ")" ) if(!hasColumn(db, "books", "starred")) { db.execSQL("ALTER TABLE books ADD COLUMN starred INT DEFAULT 0") } if(!hasColumn(db, "books", "opened_count")) { db.execSQL("ALTER TABLE books ADD COLUMN opened_count INTEGER") db.execSQL("UPDATE books SET opened_count=0") } } @JvmStatic @Synchronized fun instance(context: Context): SQLiteDatabase { if (!::database.isInitialized) { database = obtainDatabase(context) } return database } @JvmStatic @Synchronized fun deleteDatabase(context: Context) { context.applicationContext.deleteDatabase(DB_NAME) database = obtainDatabase(context) } @JvmStatic @Synchronized fun exportDatabase(context: Context, outputStream: OutputStream) { val path = instance(context).use { it.path } database = obtainDatabase(context) var inputStream: InputStream? = null try { inputStream = FileInputStream(path) val buffer = ByteArray(1024) var length: Int while(inputStream.read(buffer).also { length = it } > 0) { outputStream.write(buffer, 0, length) } } finally { inputStream?.close() outputStream.close() } } @JvmStatic @Synchronized fun importDatabase(context: Context, inputStream: InputStream) { val path = instance(context).use { it.path } database = obtainDatabase(context) var outputStream: OutputStream? = null try { outputStream = FileOutputStream(path) val buffer = ByteArray(1024) var length: Int while(inputStream.read(buffer).also { length = it } > 0) { outputStream.write(buffer, 0, length) } } finally { inputStream.close() outputStream?.close() } } private fun hasColumn(db: SQLiteDatabase, tableName: String, columnName: String): Boolean { db.rawQuery("PRAGMA table_info($tableName)", null).use { while (it.moveToNext()) { if (it.getString(it.getColumnIndex("name")).equals(columnName)) { return true } } } return false } }
mit
618ef8f026c09bfc7a44687f6a6391ad
29.491071
101
0.586702
4.815233
false
false
false
false
TeamMeanMachine/meanlib
src/main/kotlin/org/team2471/frc/lib/units/Angle.kt
1
1826
package org.team2471.frc.lib.units import kotlin.math.IEEErem inline class Angle(val asDegrees: Double) { operator fun plus(other: Angle) = Angle(asDegrees + other.asDegrees) operator fun minus(other: Angle) = Angle(asDegrees - other.asDegrees) operator fun times(factor: Double) = Angle(asDegrees * factor) operator fun div(factor: Double) = Angle(asDegrees / factor) operator fun rem(other: Angle) = Angle(asDegrees % other.asDegrees) operator fun unaryPlus() = this operator fun unaryMinus() = Angle(-asDegrees) operator fun compareTo(other: Angle) = asDegrees.compareTo(other.asDegrees) override fun toString() = "$asDegrees degrees" fun sin() = Angle.sin(this) fun cos() = Angle.cos(this) fun tan() = Angle.tan(this) fun wrap() = Angle(asDegrees.IEEErem(360.0)) companion object { @JvmStatic fun sin(angle: Angle) = Math.sin(angle.asRadians) @JvmStatic fun cos(angle: Angle) = Math.cos(angle.asRadians) @JvmStatic fun tan(angle: Angle) = Math.tan(angle.asRadians) @JvmStatic fun asin(value: Double) = Angle(Math.toDegrees(Math.asin(value))) @JvmStatic fun acos(value: Double) = Angle(Math.toDegrees(Math.acos(value))) @JvmStatic fun atan(value: Double) = Angle(Math.toDegrees(Math.atan(value))) @JvmStatic fun atan2(y: Double, x: Double) = Angle(Math.toDegrees(Math.atan2(y, x))) @JvmStatic fun atan2(y: Length, x: Length) = Angle(Math.toDegrees(Math.atan2(y.asInches, x.asInches))) } } // constructors inline val Number.radians get() = Angle(Math.toDegrees(this.toDouble())) inline val Number.degrees get() = Angle(this.toDouble()) // destructors inline val Angle.asRadians get() = Math.toRadians(asDegrees)
unlicense
a8768df2a1fc70793db8ea93a8b7f1de
27.53125
99
0.663746
3.601578
false
false
false
false
onoderis/failchat
src/main/kotlin/failchat/ws/server/WsMessageDispatcher.kt
2
1735
package failchat.ws.server import com.fasterxml.jackson.databind.ObjectMapper import failchat.util.enumMap import io.ktor.http.cio.websocket.Frame import io.ktor.http.cio.websocket.readText import io.ktor.websocket.DefaultWebSocketServerSession import kotlinx.coroutines.channels.consumeEach import mu.KLogging class WsMessageDispatcher( private val objectMapper: ObjectMapper, handlers: List<WsMessageHandler> ) { private companion object : KLogging() private val handlers: Map<InboundWsMessage.Type, WsMessageHandler> = handlers .map { it.expectedType to it } .toMap(enumMap<InboundWsMessage.Type, WsMessageHandler>()) suspend fun handleWebSocket(session: DefaultWebSocketServerSession) { session.incoming.consumeEach { frame -> if (frame !is Frame.Text) { logger.warn("Non textual frame received: {}", frame) return@consumeEach } val frameText = frame.readText() logger.debug("Message received from a web socket client: {}", frameText) val parsedMessage = objectMapper.readTree(frameText) val typeString: String = parsedMessage.get("type").asText() val type = InboundWsMessage.Type.from(typeString) ?: run { logger.warn("Message received with unknown type '{}'", typeString) return@consumeEach } handlers[type] ?.handle(InboundWsMessage(type, parsedMessage.get("content"), session)) ?: logger.warn("Message consumer not found for a message with a type '{}'. Message: {}", type, frameText) } } }
gpl-3.0
cee7b58fa0fe4ab6c0d800e166d08ca7
36.717391
125
0.63804
4.985632
false
false
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/util/Position.kt
1
674
package com.bajdcc.util /** * 位置 * * @author bajdcc */ class Position : Cloneable { /** * 列号 */ var column = 0 /** * 行号 */ var line = 0 constructor() constructor(obj: Position) { column = obj.column line = obj.line } constructor(column: Int, line: Int) { this.column = column this.line = line } override fun toString(): String { return "$line,$column" } public override fun clone(): Any { return super.clone() } fun different(obj: Position): Boolean { return this.line != obj.line || this.column != obj.column } }
mit
d909fbfdce5e53e90c1a7a8e89dc24c8
14.761905
65
0.519637
3.871345
false
false
false
false
AcornUI/Acorn
acornui-core/src/main/kotlin/com/acornui/collection/cacheUtils.kt
1
4867
/* * Copyright 2019 Poly Forest, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.acornui.collection inline fun <K, V> MutableMap<K, V>.cached(key: K, value: V, update: () -> Unit) { if (this[key] == value) return update() this[key] = value } // Boolean inline fun <K> MutableMap<K, BooleanArray>.cached1(key: K, value1: Boolean, update: () -> Unit) { val arr = this.getOrPut(key) { BooleanArray(1) } if (arr[0] == value1) return update() arr[0] = value1 } inline fun <K> MutableMap<K, BooleanArray>.cached2(key: K, value1: Boolean, value2: Boolean, update: () -> Unit) { val arr = this.getOrPut(key) { BooleanArray(2) } if (arr[0] == value1 && arr[1] == value2) return update() arr[0] = value1 arr[1] = value2 } inline fun <K> MutableMap<K, BooleanArray>.cached3(key: K, value1: Boolean, value2: Boolean, value3: Boolean, update: () -> Unit) { val arr = this.getOrPut(key) { BooleanArray(3) } if (arr[0] == value1 && arr[1] == value2 && arr[2] == value3) return update() arr[0] = value1 arr[1] = value2 arr[2] = value3 } inline fun <K> MutableMap<K, BooleanArray>.cached4(key: K, value1: Boolean, value2: Boolean, value3: Boolean, value4: Boolean, update: () -> Unit) { val arr = this.getOrPut(key) { BooleanArray(4) } if (arr[0] == value1 && arr[1] == value2 && arr[2] == value3 && arr[3] == value4) return update() arr[0] = value1 arr[1] = value2 arr[2] = value3 arr[3] = value4 } inline fun <K> MutableMap<K, BooleanArray>.cached(key: K, value: BooleanArray, update: () -> Unit) { val arr = this.getOrPut(key) { BooleanArray(value.size) } if (arr.contentEquals(value)) return update() value.copyInto(arr) } // Int inline fun <K> MutableMap<K, IntArray>.cached1(key: K, value1: Int, update: () -> Unit) { val arr = this.getOrPut(key) { IntArray(1) } if (arr[0] == value1) return update() arr[0] = value1 } inline fun <K> MutableMap<K, IntArray>.cached2(key: K, value1: Int, value2: Int, update: () -> Unit) { val arr = this.getOrPut(key) { IntArray(2) } if (arr[0] == value1 && arr[1] == value2) return update() arr[0] = value1 arr[1] = value2 } inline fun <K> MutableMap<K, IntArray>.cached3(key: K, value1: Int, value2: Int, value3: Int, update: () -> Unit) { val arr = this.getOrPut(key) { IntArray(3) } if (arr[0] == value1 && arr[1] == value2 && arr[2] == value3) return update() arr[0] = value1 arr[1] = value2 arr[2] = value3 } inline fun <K> MutableMap<K, IntArray>.cached4(key: K, value1: Int, value2: Int, value3: Int, value4: Int, update: () -> Unit) { val arr = this.getOrPut(key) { IntArray(4) } if (arr[0] == value1 && arr[1] == value2 && arr[2] == value3 && arr[3] == value4) return update() arr[0] = value1 arr[1] = value2 arr[2] = value3 arr[3] = value4 } inline fun <K> MutableMap<K, IntArray>.cached(key: K, value: IntArray, update: () -> Unit) { val arr = this.getOrPut(key) { IntArray(value.size) } if (arr.contentEquals(value)) return update() value.copyInto(arr) } // Double inline fun <K> MutableMap<K, DoubleArray>.cached1(key: K, value1: Double, update: () -> Unit) { val arr = this.getOrPut(key) { DoubleArray(1) } if (arr[0] == value1) return update() arr[0] = value1 } inline fun <K> MutableMap<K, DoubleArray>.cached2(key: K, value1: Double, value2: Double, update: () -> Unit) { val arr = this.getOrPut(key) { DoubleArray(2) } if (arr[0] == value1 && arr[1] == value2) return update() arr[0] = value1 arr[1] = value2 } inline fun <K> MutableMap<K, DoubleArray>.cached3(key: K, value1: Double, value2: Double, value3: Double, update: () -> Unit) { val arr = this.getOrPut(key) { DoubleArray(3) } if (arr[0] == value1 && arr[1] == value2 && arr[2] == value3) return update() arr[0] = value1 arr[1] = value2 arr[2] = value3 } inline fun <K> MutableMap<K, DoubleArray>.cached4(key: K, value1: Double, value2: Double, value3: Double, value4: Double, update: () -> Unit) { val arr = this.getOrPut(key) { DoubleArray(4) } if (arr[0] == value1 && arr[1] == value2 && arr[2] == value3 && arr[3] == value4) return update() arr[0] = value1 arr[1] = value2 arr[2] = value3 arr[3] = value4 } inline fun <K> MutableMap<K, DoubleArray>.cached(key: K, value: DoubleArray, update: () -> Unit) { val arr = this.getOrPut(key) { DoubleArray(value.size) } if (arr.contentEquals(value)) return update() value.copyInto(arr) }
apache-2.0
d9dd918ff3178b1856e1a4c82d2df61a
31.026316
148
0.651325
2.762202
false
false
false
false
TomsUsername/Phoenix
src/main/kotlin/phoenix/bot/pogo/nRnMK9r/Main.kt
1
6333
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package phoenix.bot.pogo.nRnMK9r import com.google.common.util.concurrent.AtomicDouble import phoenix.bot.pogo.api.PoGoApiImpl import phoenix.bot.pogo.api.auth.CredentialProvider import phoenix.bot.pogo.api.auth.GoogleAutoCredentialProvider import phoenix.bot.pogo.api.auth.PtcCredentialProvider import phoenix.bot.pogo.api.util.SystemTimeImpl import phoenix.bot.pogo.nRnMK9r.services.BotService import phoenix.bot.pogo.nRnMK9r.util.Log import phoenix.bot.pogo.nRnMK9r.util.credentials.GoogleAutoCredentials import phoenix.bot.pogo.nRnMK9r.util.credentials.GoogleCredentials import phoenix.bot.pogo.nRnMK9r.util.credentials.PtcCredentials import phoenix.bot.pogo.nRnMK9r.util.directions.getAltitude import okhttp3.Credentials import okhttp3.OkHttpClient import org.springframework.boot.SpringApplication import java.io.File import java.io.FileInputStream import java.io.FileNotFoundException import java.net.InetSocketAddress import java.net.Proxy import java.nio.file.Paths import java.util.* import java.util.logging.LogManager import javax.swing.text.rtf.RTFEditorKit val time = SystemTimeImpl() fun getAuth(settings: Settings, http: OkHttpClient): CredentialProvider { val credentials = settings.credentials val auth = if (credentials is GoogleCredentials) { Log.red("Google User Credential Provider is deprecated; Use google-auto") System.exit(1) null } else if (credentials is GoogleAutoCredentials) { GoogleAutoCredentialProvider(http, credentials.username, credentials.password, time) } else if (credentials is PtcCredentials) { PtcCredentialProvider(http, credentials.username, credentials.password, time) } else { throw IllegalStateException("Unknown credentials: ${credentials.javaClass}") } return auth!! } fun main(args: Array<String>) { LogManager.getLogManager().reset() SpringApplication.run(PokemonGoBotApplication::class.java, *args) } fun loadProperties(filename: String): Properties { val properties = Properties() Log.green("Trying to read ${Paths.get(filename).toAbsolutePath()}") var failed = false try { FileInputStream(filename).use { try { properties.load(it) } catch (e: Exception) { failed = true } } } catch (e: FileNotFoundException) { throw e } if (failed) { FileInputStream(filename).use { val rtfParser = RTFEditorKit() val document = rtfParser.createDefaultDocument() rtfParser.read(it.reader(), document, 0) val text = document.getText(0, document.length) properties.load(text.byteInputStream()) Log.red("Config file encoded as Rich Text Format (RTF)!") } } return properties } fun startDefaultBot(http: OkHttpClient, service: BotService) { var properties: Properties? = null val attemptFilenames = arrayOf("config.properties", "config.properties.txt", "config.properties.rtf") val dir = File(System.getProperty("java.class.path")).absoluteFile.parentFile var filename = "" fileLoop@ for (path in arrayOf(Paths.get("").toAbsolutePath(), dir)) { for (attemptFilename in attemptFilenames) { try { filename = attemptFilename properties = loadProperties("${path.toString()}/$filename") break@fileLoop } catch (e: FileNotFoundException) { Log.red("$filename file not found") } } } if (properties == null) { Log.red("No config files found. Exiting.") System.exit(1) return } else { val settings = SettingsParser(properties).createSettingsFromProperties() service.addBot(startBot(settings, http)) } } fun startBot(settings: Settings, http: OkHttpClient): Bot { var proxyHttp: OkHttpClient? = null if (!settings.proxyServer.equals("") && settings.proxyPort > 0) { Log.normal("Setting up proxy server for bot ${settings.name}: ${settings.proxyServer}:${settings.proxyPort}") val proxyType: Proxy.Type if (settings.proxyType.equals("HTTP")) proxyType = Proxy.Type.HTTP else if (settings.proxyType.equals("SOCKS")) proxyType = Proxy.Type.SOCKS else proxyType = Proxy.Type.DIRECT proxyHttp = http.newBuilder() .proxy(Proxy(proxyType, InetSocketAddress(settings.proxyServer, settings.proxyPort))) .proxyAuthenticator { route, response -> response.request().newBuilder() .header("Proxy-Authorization", Credentials.basic(settings.proxyUsername, settings.proxyPassword)) .build() } .build() } Log.normal("Logging in to game server...") val auth = if (proxyHttp == null) { getAuth(settings, http) } else { getAuth(settings, proxyHttp) } val api = if (proxyHttp == null) PoGoApiImpl(http, auth, time) else PoGoApiImpl(proxyHttp, auth, time) val lat = AtomicDouble(settings.latitude) val lng = AtomicDouble(settings.longitude) if (settings.saveLocationOnShutdown && settings.savedLatitude != 0.0 && settings.savedLongitude != 0.0) { lat.set(settings.savedLatitude) lng.set(settings.savedLongitude) Log.normal("Loaded last saved location (${settings.savedLatitude}, ${settings.savedLongitude})") } api.setLocation(lat.get(), lng.get(), 0.0) api.start() Log.normal("Logged in successfully") print("Getting profile data from pogo server") while (!api.initialized) { print(".") Thread.sleep(1000) } println(".") Thread.sleep(1000) val bot = Bot(api, settings) bot.start() return bot }
gpl-3.0
cc079047384629a159c750d6113583cd
32.157068
125
0.658614
4.334702
false
false
false
false
ingokegel/intellij-community
platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/watcher/RootsChangeWatcher.kt
1
13087
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.ide.impl.legacyBridge.watcher import com.google.common.io.Files import com.intellij.ide.highlighter.ModuleFileType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.service import com.intellij.openapi.components.stateStore import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.impl.getModuleNameByFilePath import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.roots.impl.storage.ClasspathStorage import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.* import com.intellij.openapi.vfs.newvfs.events.* import com.intellij.project.stateStore import com.intellij.serviceContainer.AlreadyDisposedException import com.intellij.util.containers.CollectionFactory import com.intellij.util.containers.ContainerUtil import com.intellij.util.io.URLUtil import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.getInstance import com.intellij.workspaceModel.ide.impl.legacyBridge.project.ProjectRootManagerBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.project.ProjectRootsChangeListener import com.intellij.workspaceModel.ide.impl.legacyBridge.project.ProjectRootsChangeListener.Companion.shouldFireRootsChanged import com.intellij.workspaceModel.ide.impl.legacyBridge.watcher.VirtualFileUrlWatcher.Companion.calculateAffectedEntities import com.intellij.workspaceModel.storage.EntityChange import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleId import com.intellij.workspaceModel.storage.bridgeEntities.api.modifyEntity import com.intellij.workspaceModel.storage.impl.indices.VirtualFileIndex import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import java.nio.file.Path import java.nio.file.Paths private val LOG = logger<RootsChangeWatcher>() /** * Provides rootsChanged events if roots validity was changed. */ @Service(Service.Level.PROJECT) private class RootsChangeWatcher(private val project: Project) { private val moduleManager by lazy(LazyThreadSafetyMode.NONE) { ModuleManager.getInstance(project) } private val projectFilePaths = CollectionFactory.createFilePathSet() private val virtualFileManager = VirtualFileUrlManager.getInstance(project) private val virtualFileUrlWatcher = VirtualFileUrlWatcher.getInstance(project) private val changedUrlsList = ContainerUtil.createConcurrentList<Pair<String, String>>() private val changedModuleStorePaths = ContainerUtil.createConcurrentList<Pair<Module, Path>>() init { val store = project.stateStore val projectFilePath = store.projectFilePath if (Project.DIRECTORY_STORE_FOLDER != projectFilePath.parent.fileName?.toString()) { projectFilePaths.add(VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(projectFilePath.toString()))) projectFilePaths.add(VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(store.workspacePath.toString()))) } } class RootsChangeWatcherDelegator : AsyncFileListener { override fun prepareChange(events: List<VFileEvent>): AsyncFileListener.ChangeApplier? { val appliers = ProjectManager.getInstance().openProjects.mapNotNull { try { it.service<RootsChangeWatcher>().prepareChange(events) } catch (ignore: AlreadyDisposedException) { // ignore disposed project null } } return when { appliers.isEmpty() -> null appliers.size == 1 -> appliers.first() else -> { object : AsyncFileListener.ChangeApplier { override fun beforeVfsChange() { for (applier in appliers) { applier.beforeVfsChange() } } override fun afterVfsChange() { for (applier in appliers) { applier.afterVfsChange() } } } } } } } private fun prepareChange(events: List<VFileEvent>): AsyncFileListener.ChangeApplier { val entityChanges = EntityChangeStorage() changedUrlsList.clear() changedModuleStorePaths.clear() val entityStorage = WorkspaceModel.getInstance(project).entityStorage.current for (event in events) { when (event) { is VFileDeleteEvent -> calculateEntityChangesIfNeeded(entityChanges, entityStorage, virtualFileManager.fromUrl(event.file.url), true) is VFileCreateEvent -> { val parentUrl = event.parent.url val protocolEnd = parentUrl.indexOf(URLUtil.SCHEME_SEPARATOR) val url = if (protocolEnd != -1) { parentUrl.substring(0, protocolEnd) + URLUtil.SCHEME_SEPARATOR + event.path } else { VfsUtilCore.pathToUrl(event.path) } val virtualFileUrl = virtualFileManager.fromUrl(url) calculateEntityChangesIfNeeded(entityChanges, entityStorage, virtualFileUrl, false) if (url.startsWith(URLUtil.FILE_PROTOCOL) && (event.isDirectory || event.childName.endsWith(".jar"))) { //if a new directory or a new jar file is created, we may have roots pointing to files under it with jar protocol val suffix = if (event.isDirectory) "" else URLUtil.JAR_SEPARATOR val jarFileUrl = URLUtil.JAR_PROTOCOL + URLUtil.SCHEME_SEPARATOR + VfsUtil.urlToPath(url) + suffix val jarVirtualFileUrl = virtualFileManager.fromUrl(jarFileUrl) calculateEntityChangesIfNeeded(entityChanges, entityStorage, jarVirtualFileUrl, false) } } is VFileCopyEvent -> calculateEntityChangesIfNeeded(entityChanges, entityStorage, virtualFileManager.fromUrl(VfsUtilCore.pathToUrl(event.path)), false) is VFilePropertyChangeEvent, is VFileMoveEvent -> { if (event is VFilePropertyChangeEvent) propertyChanged(event) val (oldUrl, newUrl) = getUrls(event) ?: continue if (oldUrl != newUrl) { calculateEntityChangesIfNeeded(entityChanges, entityStorage, virtualFileManager.fromUrl(oldUrl), true) calculateEntityChangesIfNeeded(entityChanges, entityStorage, virtualFileManager.fromUrl(newUrl), false) changedUrlsList.add(Pair(oldUrl, newUrl)) } } } } return object : AsyncFileListener.ChangeApplier { override fun beforeVfsChange() { changedUrlsList.forEach { (oldUrl, newUrl) -> virtualFileUrlWatcher.onVfsChange(oldUrl, newUrl) } fireRootsChangeEvent(true, entityChanges) } override fun afterVfsChange() { changedUrlsList.forEach { (oldUrl, newUrl) -> updateModuleName(oldUrl, newUrl) } changedModuleStorePaths.forEach { (module, path) -> module.stateStore.setPath(path) ClasspathStorage.modulePathChanged(module) } if (changedModuleStorePaths.isNotEmpty()) moduleManager.incModificationCount() fireRootsChangeEvent(entityChangesStorage = entityChanges) } } } private fun getIncludingJarDirectory(storage: EntityStorage, virtualFileUrl: VirtualFileUrl): VirtualFileUrl? { val indexedJarDirectories = (storage.getVirtualFileUrlIndex() as VirtualFileIndex).getIndexedJarDirectories() var parentVirtualFileUrl: VirtualFileUrl? = virtualFileUrl while (parentVirtualFileUrl != null && parentVirtualFileUrl !in indexedJarDirectories) { parentVirtualFileUrl = virtualFileManager.getParentVirtualUrl(parentVirtualFileUrl) } return if (parentVirtualFileUrl != null && parentVirtualFileUrl in indexedJarDirectories) parentVirtualFileUrl else null } private fun calculateEntityChangesIfNeeded(entityChanges: EntityChangeStorage, storage: EntityStorage, virtualFileUrl: VirtualFileUrl, allRootsWereRemoved: Boolean) { val includingJarDirectory = getIncludingJarDirectory(storage, virtualFileUrl) if (includingJarDirectory != null) { val entities = if (allRootsWereRemoved) emptyList() else storage.getVirtualFileUrlIndex().findEntitiesByUrl(includingJarDirectory).toList() entityChanges.addAll(entities.map { pair -> pair.first }) return } val affectedEntities = mutableListOf<EntityWithVirtualFileUrl>() calculateAffectedEntities(storage, virtualFileUrl, affectedEntities) virtualFileUrl.subTreeFileUrls.forEach { fileUrl -> calculateAffectedEntities(storage, fileUrl, affectedEntities) } if (affectedEntities.any { it.propertyName != "entitySource" && shouldFireRootsChanged(it.entity, project) } || virtualFileUrl.url in projectFilePaths) { val changes = if (allRootsWereRemoved) emptyList() else affectedEntities.map { it.entity } entityChanges.addAll(changes) } } private fun isRootChangeForbidden(): Boolean { if (project.isDisposed) return true val projectRootManager = ProjectRootManager.getInstance(project) if (projectRootManager !is ProjectRootManagerBridge) return true return projectRootManager.isFiringEvent() } private fun fireRootsChangeEvent(beforeRootsChanged: Boolean = false, entityChangesStorage: EntityChangeStorage) { ApplicationManager.getApplication().assertWriteAccessAllowed() val indexingInfo = entityChangesStorage.createIndexingInfo() if (indexingInfo != null && !isRootChangeForbidden()) { val projectRootManager = ProjectRootManager.getInstance(project) as ProjectRootManagerBridge if (beforeRootsChanged) projectRootManager.rootsChanged.beforeRootsChanged() else { if (LOG.isTraceEnabled) { LOG.trace("Roots changed: changed urls = $changedUrlsList, changed module store paths = $changedModuleStorePaths") } projectRootManager.rootsChanged.rootsChanged(indexingInfo) } } } private fun updateModuleName(oldUrl: String, newUrl: String) { if (!oldUrl.isImlFile() || !newUrl.isImlFile()) return val oldModuleName = getModuleNameByFilePath(oldUrl) val newModuleName = getModuleNameByFilePath(newUrl) if (oldModuleName == newModuleName) return val workspaceModel = WorkspaceModel.getInstance(project) val moduleEntity = workspaceModel.entityStorage.current.resolve(ModuleId(oldModuleName)) ?: return workspaceModel.updateProjectModel { diff -> diff.modifyEntity(moduleEntity) { this.name = newModuleName } } } private fun propertyChanged(event: VFilePropertyChangeEvent) { if (!event.file.isDirectory || event.requestor is StateStorage || event.propertyName != VirtualFile.PROP_NAME) return val parentPath = event.file.parent?.path ?: return val newAncestorPath = "$parentPath/${event.newValue}" val oldAncestorPath = "$parentPath/${event.oldValue}" for (module in moduleManager.modules) { if (!module.isLoaded || module.isDisposed) continue val moduleFilePath = module.moduleFilePath if (FileUtil.isAncestor(oldAncestorPath, moduleFilePath, true)) { changedModuleStorePaths.add( Pair(module, Paths.get(newAncestorPath, FileUtil.getRelativePath(oldAncestorPath, moduleFilePath, '/')))) } } } private fun String.isImlFile() = Files.getFileExtension(this) == ModuleFileType.DEFAULT_EXTENSION /** Update stored urls after folder movement */ private fun getUrls(event: VFileEvent): Pair<String, String>? { val oldUrl: String val newUrl: String when (event) { is VFilePropertyChangeEvent -> { oldUrl = VfsUtilCore.pathToUrl(event.oldPath) newUrl = VfsUtilCore.pathToUrl(event.newPath) } is VFileMoveEvent -> { oldUrl = VfsUtilCore.pathToUrl(event.oldPath) newUrl = VfsUtilCore.pathToUrl(event.newPath) } else -> return null } return oldUrl to newUrl } } private class EntityChangeStorage { private var entities: MutableList<WorkspaceEntity>? = null private fun initChanges(): MutableList<WorkspaceEntity> = entities ?: (mutableListOf<WorkspaceEntity>().also { entities = it }) fun addAll(addedEntities: Collection<WorkspaceEntity>) { initChanges().addAll(addedEntities) } fun createIndexingInfo() = entities?.let { ProjectRootsChangeListener.WorkspaceEventRescanningInfo(it.map { entity -> EntityChange.Added(entity) }, false) } }
apache-2.0
449d12e61c20636ccf81953749a06c80
45.24735
129
0.730878
5.106126
false
false
false
false
benjamin-bader/thrifty
thrifty-schema/src/main/kotlin/com/microsoft/thrifty/schema/ServiceType.kt
1
6178
/* * Thrifty * * Copyright (c) Microsoft Corporation * * 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 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.schema import com.microsoft.thrifty.schema.parser.ServiceElement import com.microsoft.thrifty.schema.parser.TypeElement import java.util.ArrayDeque import java.util.LinkedHashMap /** * Represents a `service` defined in a .thrift file. */ class ServiceType : UserType { /** * The methods defined by this service. */ val methods: List<ServiceMethod> private val extendsServiceType: TypeElement? /** * The type of the service that this service extends, or null if this does * not extend any other service. */ // This is intentionally too broad - it is not legal for a service to extend // a non-service type, but if we've parsed that we need to keep the invalid // state long enough to catch it during link validation. var extendsService: ThriftType? = null private set internal constructor(element: ServiceElement, namespaces: Map<NamespaceScope, String>) : super(UserElementMixin(element, namespaces)) { this.extendsServiceType = element.extendsService this.methods = element.functions.map { ServiceMethod(it, namespaces) } } private constructor(builder: Builder) : super(builder.mixin) { this.methods = builder.methods this.extendsServiceType = builder.extendsServiceType this.extendsService = builder.extendsService } override val isService: Boolean = true override fun <T> accept(visitor: ThriftType.Visitor<T>): T = visitor.visitService(this) override fun withAnnotations(annotations: Map<String, String>): ThriftType { return toBuilder() .annotations(mergeAnnotations(this.annotations, annotations)) .build() } /** * Creates a [Builder] initialized with this service's values. */ fun toBuilder(): Builder = Builder(this) internal fun link(linker: Linker) { for (method in methods) { method.link(linker) } if (this.extendsServiceType != null) { this.extendsService = linker.resolveType(extendsServiceType) } } internal fun validate(linker: Linker) { // Validate the following properties: // 1. If the service extends a type, that the type is itself a service // 2. The service contains no duplicate methods, including those inherited from base types. // 3. All service methods themselves are valid. val methodsByName = LinkedHashMap<String, ServiceMethod>() val hierarchy = ArrayDeque<ServiceType>() if (extendsService != null) { if (!extendsService!!.isService) { linker.addError(location, "Base type '" + extendsService!!.name + "' is not a service") } } // Assume base services have already been validated var baseType = extendsService while (baseType != null) { if (!baseType.isService) { break } val svc = baseType as ServiceType hierarchy.add(svc) baseType = svc.extendsService } while (!hierarchy.isEmpty()) { // Process from most- to least-derived services; that way, if there // is a name conflict, we'll report the conflict with the least-derived // class. val svc = hierarchy.remove() for (serviceMethod in svc.methods) { // Add the base-type method names to the map. In this case, // we don't care about duplicates because the base types have // already been validated and we have already reported that error. methodsByName[serviceMethod.name] = serviceMethod } } for (method in methods) { val conflictingMethod = methodsByName.put(method.name, method) if (conflictingMethod != null) { methodsByName[conflictingMethod.name] = conflictingMethod linker.addError(method.location, "Duplicate method; '" + method.name + "' conflicts with another method declared at " + conflictingMethod.location) } } for (method in methods) { method.validate(linker) } } /** * An object that can create new [ServiceType] instances. */ class Builder internal constructor(type: ServiceType) : UserType.UserTypeBuilder<ServiceType, Builder>(type) { internal var methods: List<ServiceMethod> = type.methods internal val extendsServiceType: TypeElement? = type.extendsServiceType internal var extendsService: ThriftType? = type.extendsService init { this.methods = type.methods this.extendsService = type.extendsService } /** * Use the given [methods] for the service under construction. */ fun methods(methods: List<ServiceMethod>): Builder = apply { this.methods = methods } /** * Use the given [base type][extendsService] for the service under * construction. */ fun extendsService(extendsService: ThriftType?): Builder = apply { this.extendsService = extendsService } /** * Creates a new [ServiceType] instance. */ override fun build(): ServiceType { return ServiceType(this) } } }
apache-2.0
a18742a273bd6e3f4da2be160d8b5a67
33.707865
139
0.6337
4.837901
false
false
false
false
GunoH/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/PackageSearchUI.kt
2
16665
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.project.DumbAwareAction import com.intellij.ui.ExperimentalUI import com.intellij.ui.Gray import com.intellij.ui.JBColor import com.intellij.util.ui.* import com.intellij.util.ui.components.BorderLayoutPanel import com.jetbrains.packagesearch.intellij.plugin.ui.components.BrowsableLinkLabel import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScalableUnits import com.jetbrains.packagesearch.intellij.plugin.ui.util.ScaledPixels import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled import org.jetbrains.annotations.Nls import java.awt.* import java.awt.event.ActionEvent import javax.swing.* object PackageSearchUI { internal object Colors { val border = JBColor.border() val separator = JBUI.CurrentTheme.CustomFrameDecorations.separatorForeground() private val mainBackground: Color = JBColor.namedColor("Plugins.background", UIUtil.getListBackground()) val infoLabelForeground: Color = JBColor.namedColor("Label.infoForeground", JBColor(Gray._120, Gray._135)) val headerBackground = mainBackground val sectionHeaderBackground = JBColor.namedColor("Plugins.SectionHeader.background", 0xF7F7F7, 0x3C3F41) val panelBackground get() = if (isNewUI) JBColor.namedColor("Panel.background") else mainBackground interface StatefulColor { fun background(isSelected: Boolean, isHover: Boolean): Color fun foreground(isSelected: Boolean, isHover: Boolean): Color } object PackagesTable : StatefulColor { override fun background(isSelected: Boolean, isHover: Boolean) = when { isSelected -> tableSelectedBackground isHover -> tableHoverBackground else -> tableBackground } override fun foreground(isSelected: Boolean, isHover: Boolean) = when { isSelected -> tableSelectedForeground else -> tableForeground } private val tableBackground = JBColor.namedColor("Table.background") private val tableForeground = JBColor.namedColor("Table.foreground") private val tableHoverBackground get() = color( propertyName = "PackageSearch.SearchResult.hoverBackground", newUILight = 0x2C3341, newUIDark = 0xDBE1EC, oldUILight = 0xF2F5F9, oldUIDark = 0x4C5052 ) private val tableSelectedBackground = JBColor.namedColor("Table.selectionBackground") private val tableSelectedForeground = JBColor.namedColor("Table.selectionForeground") object SearchResult : StatefulColor { override fun background(isSelected: Boolean, isHover: Boolean) = when { isSelected -> searchResultSelectedBackground isHover -> searchResultHoverBackground else -> searchResultBackground } override fun foreground(isSelected: Boolean, isHover: Boolean) = when { isSelected -> searchResultSelectedForeground else -> searchResultForeground } private val searchResultBackground get() = color( propertyName = "PackageSearch.SearchResult.background", newUILight = 0xE8EEFA, newUIDark = 0x1C2433, oldUILight = 0xE4FAFF, oldUIDark = 0x3F4749 ) private val searchResultForeground = tableForeground private val searchResultSelectedBackground = tableSelectedBackground private val searchResultSelectedForeground = tableSelectedForeground private val searchResultHoverBackground get() = color( propertyName = "PackageSearch.SearchResult.hoverBackground", newUILight = 0xDBE1EC, newUIDark = 0x2C3341, oldUILight = 0xF2F5F9, oldUIDark = 0x4C5052 ) object Tag : StatefulColor { override fun background(isSelected: Boolean, isHover: Boolean) = when { isSelected -> searchResultTagSelectedBackground isHover -> searchResultTagHoverBackground else -> searchResultTagBackground } override fun foreground(isSelected: Boolean, isHover: Boolean) = when { isSelected -> searchResultTagSelectedForeground else -> searchResultTagForeground } private val searchResultTagBackground get() = color( propertyName = "PackageSearch.SearchResult.PackageTag.background", newUILight = 0xD5DBE6, newUIDark = 0x2E3643, oldUILight = 0xD2E6EB, oldUIDark = 0x4E5658 ) private val searchResultTagForeground get() = color( propertyName = "PackageSearch.SearchResult.PackageTag.foreground", newUILight = 0x000000, newUIDark = 0xDFE1E5, oldUILight = 0x000000, oldUIDark = 0x8E8F8F ) private val searchResultTagHoverBackground get() = color( propertyName = "PackageSearch.SearchResult.PackageTag.hoverBackground", newUILight = 0xC9CFD9, newUIDark = 0x3D4350, oldUILight = 0xBFD0DB, oldUIDark = 0x55585B ) private val searchResultTagSelectedBackground get() = color( propertyName = "PackageSearch.SearchResult.PackageTag.selectedBackground", newUILight = 0xA0BDF8, newUIDark = 0x375FAD, oldUILight = 0x4395E2, oldUIDark = 0x2F65CA ) private val searchResultTagSelectedForeground get() = color( propertyName = "PackageSearch.SearchResult.PackageTag.selectedForeground", newUILight = 0x000000, newUIDark = 0x1E1F22, oldUILight = 0xFFFFFF, oldUIDark = 0xBBBBBB ) } } object Tag : StatefulColor { override fun background(isSelected: Boolean, isHover: Boolean) = when { isSelected -> tagSelectedBackground isHover -> tagHoverBackground else -> tagBackground } override fun foreground(isSelected: Boolean, isHover: Boolean) = when { isSelected -> tagSelectedForeground else -> tagForeground } private val tagBackground get() = color( propertyName = "PackageSearch.PackageTag.background", newUILight = 0xDFE1E5, newUIDark = 0x43454A, oldUILight = 0xEBEBEB, oldUIDark = 0x4C4E50 ) private val tagForeground get() = color( propertyName = "PackageSearch.PackageTag.foreground", newUILight = 0x5A5D6B, newUIDark = 0x9DA0A8, oldUILight = 0x000000, oldUIDark = 0x9C9C9C ) private val tagHoverBackground get() = color( propertyName = "PackageSearch.PackageTag.hoverBackground", newUILight = 0xF7F8FA, newUIDark = 0x4A4C4E, oldUILight = 0xC9D2DB, oldUIDark = 0x55585B ) private val tagSelectedBackground get() = color( propertyName = "PackageSearch.PackageTag.selectedBackground", newUILight = 0x88ADF7, newUIDark = 0x43454A, oldUILight = 0x4395E2, oldUIDark = 0x2F65CA ) private val tagSelectedForeground get() = color( propertyName = "PackageSearch.PackageTag.selectedForeground", newUILight = 0x000000, newUIDark = 0x9DA0A8, oldUILight = 0xFFFFFF, oldUIDark = 0xBBBBBB ) } } object InfoBanner { val background = JBUI.CurrentTheme.Banner.INFO_BACKGROUND val border = JBUI.CurrentTheme.Banner.INFO_BORDER_COLOR } private fun color( propertyName: String? = null, newUILight: Int, newUIDark: Int, oldUILight: Int, oldUIDark: Int ) = if (propertyName != null) { JBColor.namedColor( propertyName, if (isNewUI) newUILight else oldUILight, if (isNewUI) newUIDark else oldUIDark ) } else { JBColor( if (isNewUI) newUILight else oldUILight, if (isNewUI) newUIDark else oldUIDark ) } } internal val mediumHeaderHeight = JBValue.Float(30f) internal val smallHeaderHeight = JBValue.Float(24f) val isNewUI get() = ExperimentalUI.isNewUI() @Suppress("MagicNumber") // Thanks, Swing internal fun headerPanel(init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() { init { border = JBEmptyBorder(2, 0, 2, 12) init() } override fun getBackground() = Colors.headerBackground } internal fun cardPanel(cards: List<JPanel> = emptyList(), backgroundColor: Color = Colors.panelBackground, init: JPanel.() -> Unit) = object : JPanel() { init { layout = CardLayout() cards.forEach { add(it) } init() } override fun getBackground() = backgroundColor } internal fun borderPanel(backgroundColor: Color = Colors.panelBackground, init: BorderLayoutPanel.() -> Unit) = object : BorderLayoutPanel() { init { init() } override fun getBackground() = backgroundColor } internal fun boxPanel(axis: Int = BoxLayout.Y_AXIS, backgroundColor: Color = Colors.panelBackground, init: JPanel.() -> Unit) = object : JPanel() { init { layout = BoxLayout(this, axis) init() } override fun getBackground() = backgroundColor } internal fun flowPanel(backgroundColor: Color = Colors.panelBackground, init: JPanel.() -> Unit) = object : JPanel() { init { layout = FlowLayout(FlowLayout.LEFT) init() } override fun getBackground() = backgroundColor } fun checkBox(@Nls title: String, init: JCheckBox.() -> Unit = {}) = object : JCheckBox(title) { init { init() } override fun getBackground() = Colors.panelBackground } fun textField(init: JTextField.() -> Unit): JTextField = JTextField().apply { init() } internal fun menuItem(@Nls title: String, icon: Icon?, handler: () -> Unit): JMenuItem { if (icon != null) { return JMenuItem(title, icon).apply { addActionListener { handler() } } } return JMenuItem(title).apply { addActionListener { handler() } } } fun createLabel(@Nls text: String? = null, init: JLabel.() -> Unit = {}) = JLabel().apply { font = StartupUiUtil.getLabelFont() if (text != null) this.text = text init() } internal fun createLabelWithLink(init: BrowsableLinkLabel.() -> Unit = {}) = BrowsableLinkLabel().apply { font = StartupUiUtil.getLabelFont() init() } private fun getTextColorPrimary(isSelected: Boolean = false): Color = when { isSelected -> JBColor.lazy { NamedColorUtil.getListSelectionForeground(true) } else -> JBColor.lazy { UIUtil.getListForeground() } } internal fun getTextColorSecondary(isSelected: Boolean = false): Color = when { isSelected -> getTextColorPrimary(true) else -> Colors.infoLabelForeground } internal fun setHeight(component: JComponent, @ScalableUnits height: Int, keepWidth: Boolean = false) { setHeightPreScaled(component, height.scaled(), keepWidth) } internal fun setHeightPreScaled(component: JComponent, @ScaledPixels height: Int, keepWidth: Boolean = false) { component.apply { preferredSize = Dimension(if (keepWidth) preferredSize.width else 0, height) minimumSize = Dimension(if (keepWidth) minimumSize.width else 0, height) maximumSize = Dimension(if (keepWidth) maximumSize.width else Int.MAX_VALUE, height) } } internal fun verticalScrollPane(c: Component) = object : JScrollPane( VerticalScrollPanelWrapper(c), VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_NEVER ) { init { border = BorderFactory.createEmptyBorder() viewport.background = Colors.panelBackground } } internal fun overrideKeyStroke(c: JComponent, stroke: String, action: () -> Unit) = overrideKeyStroke(c, stroke, stroke, action) internal fun overrideKeyStroke(c: JComponent, key: String, stroke: String, action: () -> Unit) { val inputMap = c.getInputMap(JComponent.WHEN_FOCUSED) inputMap.put(KeyStroke.getKeyStroke(stroke), key) c.actionMap.put( key, object : AbstractAction() { override fun actionPerformed(arg: ActionEvent) { action() } } ) } private class VerticalScrollPanelWrapper(content: Component) : JPanel(), Scrollable { init { layout = BoxLayout(this, BoxLayout.Y_AXIS) add(content) } override fun getPreferredScrollableViewportSize(): Dimension = preferredSize override fun getScrollableUnitIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 10 override fun getScrollableBlockIncrement(visibleRect: Rectangle, orientation: Int, direction: Int) = 100 override fun getScrollableTracksViewportWidth() = true override fun getScrollableTracksViewportHeight() = false override fun getBackground() = Colors.panelBackground } } internal class ComponentActionWrapper(private val myComponentCreator: () -> JComponent) : DumbAwareAction(), CustomComponentAction { override fun createCustomComponent(presentation: Presentation, place: String) = myComponentCreator() override fun actionPerformed(e: AnActionEvent) { // No-op } } internal fun JComponent.updateAndRepaint() { invalidate() repaint() }
apache-2.0
e1f53b490a8a838faf182a0f8004c9e4
39.156627
137
0.573837
5.720906
false
false
false
false
GunoH/intellij-community
plugins/devkit/devkit-core/src/inspections/RegistryPropertiesAnnotator.kt
3
6352
// 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.idea.devkit.inspections import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo import com.intellij.codeInsight.intention.preview.IntentionPreviewUtils import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.lang.annotation.HighlightSeverity import com.intellij.lang.properties.psi.PropertiesFile import com.intellij.lang.properties.psi.impl.PropertyImpl import com.intellij.lang.properties.psi.impl.PropertyKeyImpl import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.util.IncorrectOperationException import com.intellij.util.PsiNavigateUtil import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.idea.devkit.DevKitBundle import org.jetbrains.idea.devkit.util.PsiUtil import java.util.* /** * Highlights key in `registry.properties` without matching `key.description` entry + corresponding quickfix. */ class RegistryPropertiesAnnotator : Annotator { override fun annotate(element: PsiElement, holder: AnnotationHolder) { if (element !is PropertyKeyImpl) return val file = holder.currentAnnotationSession.file if (!isRegistryPropertiesFile(file)) { return } val propertyName = element.text if (isImplicitUsageKey(propertyName)) { return } val groupName = propertyName.substringBefore('.').lowercase(Locale.getDefault()) if (PLUGIN_GROUP_NAMES.contains(groupName) || propertyName.startsWith("editor.config.")) { holder.newAnnotation(HighlightSeverity.ERROR, DevKitBundle.message("registry.properties.annotator.plugin.keys.use.ep")) .withFix(ShowEPDeclarationIntention(propertyName)).create() } val propertiesFile = file as PropertiesFile val descriptionProperty = propertiesFile.findPropertyByKey(propertyName + DESCRIPTION_SUFFIX) if (descriptionProperty == null) { holder.newAnnotation(HighlightSeverity.WARNING, DevKitBundle.message("registry.properties.annotator.key.no.description.key", propertyName)) .withFix(AddDescriptionKeyIntention(propertyName)).create() } } private class ShowEPDeclarationIntention(private val propertyName: String) : IntentionAction { override fun startInWriteAction(): Boolean = false override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo { return IntentionPreviewInfo.EMPTY } override fun getFamilyName(): String = DevKitBundle.message("registry.properties.annotator.show.ep.family.name") override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean = true override fun getText(): String = DevKitBundle.message("registry.properties.annotator.show.ep.name", propertyName) override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { val propertiesFile = file as PropertiesFile val defaultValue = propertiesFile.findPropertyByKey(propertyName)!!.value val description = propertiesFile.findPropertyByKey(propertyName + DESCRIPTION_SUFFIX)?.value @NonNls var restartRequiredText = "" if (propertiesFile.findPropertyByKey(propertyName + RESTART_REQUIRED_SUFFIX) != null) { restartRequiredText = "restartRequired=\"true\"" } val epText = """ <registryKey key="${propertyName}" defaultValue="${defaultValue}" ${restartRequiredText} description="${description}"/> """.trimIndent() Messages.showMultilineInputDialog(project, DevKitBundle.message("registry.properties.annotator.show.ep.message"), DevKitBundle.message("registry.properties.annotator.show.ep.title"), epText, null, null) } } private class AddDescriptionKeyIntention(private val myPropertyName: String) : IntentionAction { @Nls override fun getText(): String = DevKitBundle.message("registry.properties.annotator.add.description.text", myPropertyName) @Nls override fun getFamilyName(): String = DevKitBundle.message("registry.properties.annotator.add.description.family.name") override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean = true @Throws(IncorrectOperationException::class) override fun invoke(project: Project, editor: Editor, file: PsiFile) { val propertiesFile = file as PropertiesFile val originalProperty = propertiesFile.findPropertyByKey(myPropertyName) as PropertyImpl? val descriptionProperty = propertiesFile.addPropertyAfter(myPropertyName + DESCRIPTION_SUFFIX, "Description", originalProperty) val valueNode = (descriptionProperty.psiElement as PropertyImpl).valueNode!! if (!IntentionPreviewUtils.isPreviewElement(valueNode.psi) ) { PsiNavigateUtil.navigate(valueNode.psi) } } override fun startInWriteAction(): Boolean = true } companion object { @NonNls private val PLUGIN_GROUP_NAMES = setOf( "appcode", "cidr", "clion", "cvs", "git", "github", "svn", "hg4idea", "tfs", "dart", "markdown", "java", "javac", "uast", "junit4", "dsm", "js", "javascript", "typescript", "nodejs", "eslint", "jest", "ruby", "rubymine", "groovy", "grails", "python", "php", "kotlin" ) @NonNls private const val REGISTRY_PROPERTIES_FILENAME = "registry.properties" @NonNls const val DESCRIPTION_SUFFIX = ".description" @NonNls const val RESTART_REQUIRED_SUFFIX = ".restartRequired" @JvmStatic fun isImplicitUsageKey(keyName: String): Boolean = StringUtil.endsWith(keyName, DESCRIPTION_SUFFIX) || StringUtil.endsWith(keyName, RESTART_REQUIRED_SUFFIX) @JvmStatic fun isRegistryPropertiesFile(psiFile: PsiFile): Boolean = PsiUtil.isIdeaProject(psiFile.project) && psiFile.name == REGISTRY_PROPERTIES_FILENAME } }
apache-2.0
11801e889caa2cc8dddc8d3aa1b5181b
41.353333
133
0.731266
4.812121
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ui/charts/BarChart.kt
2
4496
// 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.ui.charts import java.awt.Graphics2D import java.awt.Rectangle import java.awt.geom.Area import java.lang.Double.min import javax.swing.SwingConstants import kotlin.math.abs import kotlin.math.max class BarDataset<T: Number>: Dataset<T>() { var stacked: Boolean = false var values: Iterable<T> get() = data set(value) { data = value } var showValues : ((T) -> String)? = null init { fillColor = lineColor } companion object { @JvmStatic fun <T: Number> of(vararg values: T): BarDataset<T> = BarDataset<T>().apply { data = values.toList() } } } abstract class BarChart<T: Number>: GridChartWrapper<Int, T>() { var datasets: List<BarDataset<T>> = mutableListOf() override val ranges: Grid<Int, T> = Grid() var gap: Int = 10 var space: Int = -1 override fun paintComponent(g: Graphics2D) { val xy = findMinMax() if (xy.isInitialized) { val datasetCount = getDatasetCount() val grid = g.create(margins.left, margins.top, gridWidth, gridHeight) as Graphics2D paintGrid(grid, g, xy) var index = 0 datasets.forEach { dataset -> dataset.paintDataset(index, datasetCount, grid, xy) if (!dataset.stacked) { index++ } } grid.dispose() } } private fun getDatasetCount() = datasets.map { if (it.stacked) 0 else 1 }.sum() override fun findMinMax() = if (ranges.isInitialized) ranges else ranges * (ranges + MinMax()).apply { datasets.forEach { it.data.forEachIndexed { i, v -> process(i, v) } } } protected abstract fun BarDataset<T>.paintDataset(datasetIndex: Int, datasetCount: Int, g: Graphics2D, xy: MinMax<Int, T>) } class HorizontalBarChart<T: Number> : BarChart<T>() { override fun BarDataset<T>.paintDataset(datasetIndex: Int, datasetCount: Int, g: Graphics2D, xy: MinMax<Int, T>) { assert(xy.xMin == 0) { "Int value must start with 0" } val columns = xy.xMax + 1 val max = max(xy.yMax.toDouble(), 0.0) val min = min(xy.yMin.toDouble(), 0.0) if (max == min) { return } val cb = g.clipBounds val z = cb.height / (max - min) val axis = (z * abs(min)).toInt() data.forEachIndexed { column, value -> var h = (value.toDouble() * z).toInt() var y = cb.height - h - axis val groupW = cb.width / columns - gap val groupX = column * cb.width / columns + gap / 2 val space = if (space < 0) max(1, groupW / 10) else space val w = max(1, (groupW - space * (datasetCount - 1)) / datasetCount) val x = groupX + datasetIndex * w + space * datasetIndex if (h < 0) { y += h h = abs(h) } lineColor?.let { g.paint = lineColor g.drawRect(x, y, w, h) } fillColor?.let { g.paint = it g.fillRect(x, y, w, h) } if (stacked) { val area = Area(g.clip) area.subtract(Area(Rectangle(x, y, w, h))) g.clip = area } showValues?.let { toString -> val str = toString(value) val bounds = g.fontMetrics.getStringBounds(str, g) g.drawString(str, x + (w - bounds.width.toInt()) / 2, y - 5) } } } override fun findGridLineX(gl: GridLine<Int, T, *>, x: Int): Double { return gridWidth * ((x + 1).toDouble() - gl.xy.xMin.toDouble()) / (gl.xy.xMax.toDouble() - gl.xy.xMin.toDouble() + 1) } override fun findY(xy: MinMax<Int, T>, y: T): Double { val isRanged = xy.yMin.toDouble() <= 0.0 && 0.0 <= xy.yMax.toDouble() val yMin = if (isRanged || xy.yMin.toDouble() < 0) xy.yMin.toDouble() else 0.0 val yMax = if (isRanged || xy.yMax.toDouble() > 0) xy.yMax.toDouble() else 0.0 val height = height - (margins.top + margins.bottom) return height - height * (y.toDouble() - yMin) / (yMax - yMin) } override fun findGridLabelOffset(line: GridLine<*, *, *>, g: Graphics2D): Coordinates<Double, Double> { val onLineAlignment = super.findGridLabelOffset(line, g) if (line.orientation == SwingConstants.VERTICAL) { val width = width - (margins.left + margins.right) val columnWidth = width / (line.xy.xMax.toDouble() - line.xy.xMin.toDouble() + 1) return (onLineAlignment.x + columnWidth / 2) to onLineAlignment.y } else { return onLineAlignment } } }
apache-2.0
74c72e997f0258d19fc84a8e4942fcfe
29.385135
158
0.612544
3.447853
false
false
false
false
GunoH/intellij-community
platform/vcs-tests/testSrc/com/intellij/openapi/vcs/changes/committed/VcsDirtyScopeManagerTest.kt
12
6893
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.committed import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service import com.intellij.openapi.vcs.AbstractVcs import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.runInEdtAndWait import com.intellij.vcs.test.VcsPlatformTest import com.intellij.vcsUtil.VcsUtil.getFilePath /** * @see VcsDirtyScopeTest */ class VcsDirtyScopeManagerTest : VcsPlatformTest() { private lateinit var dirtyScopeManager: VcsDirtyScopeManagerImpl private lateinit var vcs: MockAbstractVcs private lateinit var basePath: FilePath override fun setUp() { super.setUp() dirtyScopeManager = VcsDirtyScopeManagerImpl.getInstanceImpl(project) vcs = MockAbstractVcs(project) basePath = getFilePath(projectRoot) disableVcsDirtyScopeVfsListener() disableChangeListManager() vcsManager.registerVcs(vcs) vcsManager.waitForInitialized() registerRootMapping(projectRoot) } override fun getDebugLogCategories() = super.getDebugLogCategories().plus("#com.intellij.openapi.vcs.changes") fun `test simple case`() { val file = createFile(projectRoot, "file.txt") dirtyScopeManager.fileDirty(file) val invalidated = retrieveDirtyScopes() assertTrue(invalidated.isFileDirty(file)) val scope = assertOneScope(invalidated) assertTrue(scope.dirtyFiles.contains(file)) } fun `test recursively dirty directory makes files under it dirty`() { val dir = createDir(projectRoot, "dir") val file = createFile(dir, "file.txt") dirtyScopeManager.dirDirtyRecursively(dir) val invalidated = retrieveDirtyScopes() assertTrue(invalidated.isFileDirty(file)) val scope = assertOneScope(invalidated) assertTrue(scope.recursivelyDirtyDirectories.contains(dir)) assertFalse(scope.dirtyFiles.contains(file)) } fun `test dirty files from different roots`() { val otherRoot = createSubRoot(testRoot, "otherRoot") val file = createFile(projectRoot, "file.txt") val subFile = createFile(otherRoot, "other.txt") dirtyScopeManager.filePathsDirty(listOf(file), listOf(otherRoot)) val invalidated = retrieveDirtyScopes() assertDirtiness(invalidated, file, subFile) val scope = assertOneScope(invalidated) assertTrue(scope.recursivelyDirtyDirectories.contains(otherRoot)) assertTrue(scope.dirtyFiles.contains(file)) } fun `test mark everything dirty should mark dirty all roots`() { val subRoot = createSubRoot(projectRoot, "subroot") val file = createFile(projectRoot, "file.txt") val subFile = createFile(subRoot, "sub.txt") dirtyScopeManager.markEverythingDirty() val invalidated = retrieveDirtyScopes() assertDirtiness(invalidated, file, basePath, subRoot, subFile) } // this is already implicitly checked in several other tests, but better to have it explicit fun `test all roots from a single vcs belong to a single scope`() { val otherRoot = createSubRoot(testRoot, "otherRoot") val file = createFile(projectRoot, "file.txt") val subFile = createFile(otherRoot, "other.txt") dirtyScopeManager.filePathsDirty(listOf(), listOf(basePath, otherRoot)) val invalidated = retrieveDirtyScopes() val scope = assertOneScope(invalidated) assertDirtiness(invalidated, file, subFile) assertTrue(scope.recursivelyDirtyDirectories.contains(basePath)) assertTrue(scope.recursivelyDirtyDirectories.contains(otherRoot)) } fun `test marking file outside of any VCS root dirty has no effect`() { val file = createFile(testRoot, "outside.txt") dirtyScopeManager.fileDirty(file) val invalidated = retrieveDirtyScopes() assertTrue(invalidated.isEmpty()) assertFalse(invalidated.isEverythingDirty) } fun `test mark files from different VCSs dirty produce two dirty scopes`() { val basePath = getFilePath(projectRoot) val subRoot = createDir(projectRoot, "othervcs") val otherVcs = MockAbstractVcs(project, "otherVCS") vcsManager.registerVcs(otherVcs) registerRootMapping(subRoot.virtualFile!!, otherVcs) dirtyScopeManager.filePathsDirty(null, listOf(basePath, subRoot)) val invalidated = retrieveDirtyScopes() val scopes = invalidated.scopes assertEquals(2, scopes.size) val mainVcsScope = scopes.find { it.vcs.name == vcs.name }!! assertTrue(mainVcsScope.recursivelyDirtyDirectories.contains(basePath)) val otherVcsScope = scopes.find { it.vcs.name == otherVcs.name }!! assertTrue(otherVcsScope.recursivelyDirtyDirectories.contains(subRoot)) } private fun retrieveDirtyScopes(): VcsInvalidated { val scopes = dirtyScopeManager.retrieveScopes()!! dirtyScopeManager.changesProcessed() return scopes } private fun disableVcsDirtyScopeVfsListener() { project.service<VcsDirtyScopeVfsListener>().setForbid(true) } private fun disableChangeListManager() { (ChangeListManager.getInstance(project) as ChangeListManagerImpl).forceStopInTestMode() } private fun createSubRoot(parent: VirtualFile, name: String): FilePath { val dir = createDir(parent, name) registerRootMapping(dir.virtualFile!!) return dir } private fun registerRootMapping(root: VirtualFile) { registerRootMapping(root, vcs) } private fun registerRootMapping(root: VirtualFile, vcs: AbstractVcs) { vcsManager.setDirectoryMapping(root.path, vcs.name) dirtyScopeManager.retrieveScopes() // ignore the dirty event after adding the mapping dirtyScopeManager.changesProcessed() } private fun createFile(parentDir: FilePath, name: String): FilePath { return createFile(parentDir.virtualFile!!, name, false) } private fun createFile(parentDir: VirtualFile, name: String): FilePath { return createFile(parentDir, name, false) } private fun createDir(parentDir: VirtualFile, name: String): FilePath { return createFile(parentDir, name, true) } private fun createFile(parentDir: VirtualFile, name: String, dir: Boolean): FilePath { var file: VirtualFile? = null runInEdtAndWait { ApplicationManager.getApplication().runWriteAction { file = if (dir) parentDir.createChildDirectory(this, name) else parentDir.createChildData(this, name) } } return getFilePath(file!!) } private fun assertOneScope(invalidated: VcsInvalidated): VcsDirtyScope { assertEquals(1, invalidated.scopes.size) return invalidated.scopes.first() } private fun assertDirtiness(invalidated: VcsInvalidated, vararg dirty: FilePath) { dirty.forEach { assertTrue("File $it is not dirty", invalidated.isFileDirty(it)) } } }
apache-2.0
caf4db3fbe9461729514f6831eb5df18
34.715026
140
0.752357
4.796799
false
true
false
false
GunoH/intellij-community
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/ScriptRelatedModuleNameFile.kt
4
1085
// 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 import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.idea.core.util.* import java.io.DataInputStream import java.io.DataOutputStream @Service class ScriptRelatedModuleNameFile: AbstractFileAttributePropertyService<String>( name = "kotlin-script-moduleName", version = 1, read = DataInputStream::readString, write = DataOutputStream::writeString ) { companion object { operator fun get(project: Project, file: VirtualFile): String? { return project.service<ScriptRelatedModuleNameFile>()[file] } operator fun set(project: Project, file: VirtualFile, newValue: String?) { project.service<ScriptRelatedModuleNameFile>()[file] = newValue } } }
apache-2.0
5c07d83df2103fdf310029b4bc65e7a1
36.448276
158
0.748387
4.35743
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/trace/impl/interpret/ValuesOrder.kt
4
949
// 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.debugger.sequence.trace.impl.interpret import com.intellij.debugger.streams.trace.TraceElement import com.intellij.debugger.streams.trace.TraceInfo import com.intellij.debugger.streams.wrapper.StreamCall class ValuesOrder( private val call: StreamCall, private val before: Map<Int, TraceElement>, private val after: Map<Int, TraceElement> ) : TraceInfo { override fun getValuesOrderBefore(): Map<Int, TraceElement> = before override fun getCall(): StreamCall = call override fun getValuesOrderAfter(): Map<Int, TraceElement> = after override fun getDirectTrace(): MutableMap<TraceElement, MutableList<TraceElement>>? = null override fun getReverseTrace(): MutableMap<TraceElement, MutableList<TraceElement>>? = null }
apache-2.0
b5839303eb3437b5f363ff3208f596af
40.304348
158
0.774499
4.434579
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildNullableEntityImpl.kt
2
9417
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToOneParent import com.intellij.workspaceModel.storage.impl.updateOneToOneParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ChildNullableEntityImpl(val dataSource: ChildNullableEntityData) : ChildNullableEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentNullableEntity::class.java, ChildNullableEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } override val childData: String get() = dataSource.childData override val parentEntity: ParentNullableEntity get() = snapshot.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this)!! override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: ChildNullableEntityData?) : ModifiableWorkspaceEntityBase<ChildNullableEntity, ChildNullableEntityData>( result), ChildNullableEntity.Builder { constructor() : this(ChildNullableEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ChildNullableEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isChildDataInitialized()) { error("Field ChildNullableEntity#childData should be initialized") } if (_diff != null) { if (_diff.extractOneToOneParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field ChildNullableEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field ChildNullableEntity#parentEntity should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ChildNullableEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.childData != dataSource.childData) this.childData = dataSource.childData if (parents != null) { val parentEntityNew = parents.filterIsInstance<ParentNullableEntity>().single() if ((this.parentEntity as WorkspaceEntityBase).id != (parentEntityNew as WorkspaceEntityBase).id) { this.parentEntity = parentEntityNew } } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var childData: String get() = getEntityData().childData set(value) { checkModificationAllowed() getEntityData(true).childData = value changedProperty.add("childData") } override var parentEntity: ParentNullableEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentNullableEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentNullableEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override fun getEntityClass(): Class<ChildNullableEntity> = ChildNullableEntity::class.java } } class ChildNullableEntityData : WorkspaceEntityData<ChildNullableEntity>() { lateinit var childData: String fun isChildDataInitialized(): Boolean = ::childData.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ChildNullableEntity> { val modifiable = ChildNullableEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): ChildNullableEntity { return getCached(snapshot) { val entity = ChildNullableEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ChildNullableEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ChildNullableEntity(childData, entitySource) { this.parentEntity = parents.filterIsInstance<ParentNullableEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(ParentNullableEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ChildNullableEntityData if (this.entitySource != other.entitySource) return false if (this.childData != other.childData) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ChildNullableEntityData if (this.childData != other.childData) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + childData.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + childData.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
b3b6495a970f2f9986e07548cfce8508
36.369048
157
0.697781
5.362756
false
false
false
false
jk1/intellij-community
platform/projectModel-api/src/com/intellij/openapi/diagnostic/logger.kt
1
1770
/* * Copyright 2000-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 com.intellij.openapi.diagnostic import com.intellij.openapi.progress.ProcessCanceledException import kotlin.reflect.KProperty import kotlin.reflect.jvm.javaGetter inline fun <reified T : Any> logger(): Logger = Logger.getInstance(T::class.java) fun logger(category: String): Logger = Logger.getInstance(category) /** * Get logger instance to be used in Kotlin package methods. Usage: * ``` * private val LOG: Logger get() = logger(::LOG) // define at top level of the file containing the function * ``` * In Kotlin 1.1 even simpler declaration will be possible: * ``` * private val LOG: Logger = logger(::LOG) * ``` * Notice explicit type declaration which can't be skipped in this case. */ fun logger(field: KProperty<Logger>): Logger = Logger.getInstance(field.javaGetter!!.declaringClass) inline fun Logger.debug(e: Exception? = null, lazyMessage: () -> String) { if (isDebugEnabled) { debug(lazyMessage(), e) } } inline fun <T> Logger.runAndLogException(runnable: () -> T): T? { try { return runnable() } catch (e: ProcessCanceledException) { return null } catch (e: Throwable) { error(e) return null } }
apache-2.0
62264e88df0fbe3a7d53328e517cc15f
30.625
108
0.715254
3.96861
false
false
false
false
marius-m/wt4
remote/src/test/java/lt/markmerkk/worklogs/JiraWorklogInteractorMapRemoteToLocalWorklogTest.kt
1
5005
package lt.markmerkk.worklogs import lt.markmerkk.JiraMocks import lt.markmerkk.Mocks import lt.markmerkk.TimeProviderTest import lt.markmerkk.entities.Log import lt.markmerkk.entities.Ticket import lt.markmerkk.entities.TicketCode import org.assertj.core.api.Assertions import org.joda.time.Duration import org.junit.Assert.* import org.junit.Test class JiraWorklogInteractorMapRemoteToLocalWorklogTest { private val timeProvider = TimeProviderTest() private val now = timeProvider.now() @Test fun valid() { // Assemble val inputTicket = Mocks.createTicket( code = "DEV-123", ) // Act val result = JiraWorklogInteractor.mapRemoteToLocalWorklog( timeProvider = timeProvider, fetchTime = now, ticket = inputTicket, remoteWorkLog = JiraMocks.mockWorklog( timeProvider = timeProvider, started = now, comment = "comment1", durationTimeSpent = Duration.standardMinutes(10), ) ) // Assert Assertions.assertThat(result).isEqualTo( Mocks.createLog( id = 0, timeProvider = timeProvider, code = "DEV-123", comment = "comment1", author = "name", remoteData = Mocks.createRemoteData( timeProvider = timeProvider, remoteId = 73051, url = "https://jira.ito.lt/rest/api/2/issue/31463/worklog/73051", ) ) ) } @Test fun noComment() { // Assemble val inputTicket = Mocks.createTicket( code = "DEV-123", ) // Act val result = JiraWorklogInteractor.mapRemoteToLocalWorklog( timeProvider = timeProvider, fetchTime = now, ticket = inputTicket, remoteWorkLog = JiraMocks.mockWorklog( timeProvider = timeProvider, started = now, comment = "", durationTimeSpent = Duration.standardMinutes(10), ) ) // Assert Assertions.assertThat(result).isEqualTo( Mocks.createLog( id = 0, timeProvider = timeProvider, code = "DEV-123", comment = "", author = "name", remoteData = Mocks.createRemoteData( timeProvider = timeProvider, remoteId = 73051, url = "https://jira.ito.lt/rest/api/2/issue/31463/worklog/73051", ) ) ) } @Test fun nullComment() { // Assemble val inputTicket = Mocks.createTicket( code = "DEV-123", ) // Act val result = JiraWorklogInteractor.mapRemoteToLocalWorklog( timeProvider = timeProvider, fetchTime = now, ticket = inputTicket, remoteWorkLog = JiraMocks.mockWorklog( timeProvider = timeProvider, started = now, comment = null, durationTimeSpent = Duration.standardMinutes(10), ) ) // Assert Assertions.assertThat(result).isEqualTo( Mocks.createLog( id = 0, timeProvider = timeProvider, code = "DEV-123", comment = "", author = "name", remoteData = Mocks.createRemoteData( timeProvider = timeProvider, remoteId = 73051, url = "https://jira.ito.lt/rest/api/2/issue/31463/worklog/73051", ) ) ) } @Test fun nullAuthor() { // Assemble val inputTicket = Mocks.createTicket( code = "DEV-123", ) // Act val result = JiraWorklogInteractor.mapRemoteToLocalWorklog( timeProvider = timeProvider, fetchTime = now, ticket = inputTicket, remoteWorkLog = JiraMocks.mockWorklog( timeProvider = timeProvider, author = null, started = now, comment = "comment1", durationTimeSpent = Duration.standardMinutes(10), ) ) // Assert Assertions.assertThat(result).isEqualTo( Mocks.createLog( id = 0, timeProvider = timeProvider, code = "DEV-123", comment = "comment1", author = "", remoteData = Mocks.createRemoteData( timeProvider = timeProvider, remoteId = 73051, url = "https://jira.ito.lt/rest/api/2/issue/31463/worklog/73051", ) ) ) } }
apache-2.0
b1b463ba47b1a73ea55852e950d406be
28.976048
85
0.502098
5.273973
false
false
false
false
CzBiX/v2ex-android
app/src/main/kotlin/com/czbix/v2ex/util/GsonUtils.kt
1
1947
package com.czbix.v2ex.util import com.google.gson.FieldNamingStrategy import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.reflect.TypeToken import java.io.Reader import java.lang.reflect.Field import java.util.regex.Pattern private class AndroidFieldNamingStrategy : FieldNamingStrategy { override fun translateName(f: Field): String { if (f.name.startsWith("m")) { return handleWords(f.name.substring(1)) } else { return f.name } } private fun handleWords(fieldName: String): String { val words = UPPERCASE_PATTERN.split(fieldName) val sb = StringBuilder() for (word in words) { if (sb.length > 0) { sb.append(JSON_WORD_DELIMITER) } sb.append(word.toLowerCase()) } return sb.toString() } companion object { private val JSON_WORD_DELIMITER = "_" private val UPPERCASE_PATTERN = Pattern.compile("(?=\\p{Lu})") } } val GSON: Gson = GsonBuilder().apply { setFieldNamingStrategy(AndroidFieldNamingStrategy()) }.create() inline fun <reified T : Any> String.fromJson(): T { return GSON.fromJson(this, T::class.java) } @Suppress("UNUSED_PARAMETER") inline fun <reified T : Any> String.fromJson(isGenericType: Boolean): T { return GSON.fromJson(this, object : TypeToken<T>(){}.type) } inline fun <reified T : Any> Reader.fromJson(): T { return GSON.fromJson(this, T::class.java) } @Suppress("UNUSED_PARAMETER") inline fun <reified T : Any> Reader.fromJson(isGenericType: Boolean): T { return GSON.fromJson(this, object : TypeToken<T>(){}.type) } inline fun <reified T : Any> T.toJson(): String { return GSON.toJson(this, T::class.java) } @Suppress("UNUSED_PARAMETER") inline fun <reified T : Any> T.toJson(isGenericType: Boolean): String { return GSON.toJson(this, object : TypeToken<T>(){}.type) }
apache-2.0
40c004ed36471af5ac7358b4190c2605
27.217391
73
0.658963
3.765957
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-plugins/ktor-server-thymeleaf/jvm/src/io/ktor/server/thymeleaf/Thymeleaf.kt
1
2109
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.thymeleaf import io.ktor.http.* import io.ktor.http.content.* import io.ktor.server.application.* import org.thymeleaf.* import org.thymeleaf.context.* import java.util.* /** * A response content handled by the [io.ktor.server.thymeleaf.Thymeleaf] plugin. * * @param template name that is resolved by Thymeleaf * @param model to be passed during template rendering * @param etag value for the `E-Tag` header (optional) * @param contentType of response (optional, `text/html` with UTF-8 character encoding by default) * @param locale object represents a specific geographical, political, or cultural region * @param fragments names from the [template] that is resolved by Thymeleaf */ public class ThymeleafContent( public val template: String, public val model: Map<String, Any>, public val etag: String? = null, public val contentType: ContentType = ContentType.Text.Html.withCharset(Charsets.UTF_8), public val locale: Locale = Locale.getDefault(), public val fragments: Set<String> = setOf() ) /** * A plugin that allows you to use Thymeleaf templates as views within your application. * Provides the ability to respond with [ThymeleafContent]. * You can learn more from [Thymeleaf](https://ktor.io/docs/thymeleaf.html). */ public val Thymeleaf: ApplicationPlugin<TemplateEngine> = createApplicationPlugin( "Thymeleaf", ::TemplateEngine ) { fun process(content: ThymeleafContent): OutgoingContent = with(content) { val context = Context(locale).apply { setVariables(model) } val result = TextContent( text = pluginConfig.process(template, fragments, context), contentType ) if (etag != null) { result.versions += EntityTagVersion(etag) } return result } onCallRespond { _, body -> if (body !is ThymeleafContent) return@onCallRespond transformBody { process(body) } } }
apache-2.0
a1086f80f059a272982ff717f4d08079
33.57377
119
0.698435
4.151575
false
false
false
false
evanchooly/kobalt
src/main/kotlin/com/beust/kobalt/plugin/kotlin/KotlinPlugin.kt
1
8256
package com.beust.kobalt.plugin.kotlin import com.beust.kobalt.TaskResult import com.beust.kobalt.Variant import com.beust.kobalt.api.* import com.beust.kobalt.api.annotation.Directive import com.beust.kobalt.internal.BaseJvmPlugin import com.beust.kobalt.internal.JvmCompilerPlugin import com.beust.kobalt.internal.KobaltSettings import com.beust.kobalt.maven.DependencyManager import com.beust.kobalt.maven.dependency.FileDependency import com.beust.kobalt.misc.KFiles import com.beust.kobalt.misc.KobaltExecutors import com.beust.kobalt.misc.log import com.beust.kobalt.misc.warn import java.io.File import javax.inject.Inject import javax.inject.Singleton @Singleton class KotlinPlugin @Inject constructor(val executors: KobaltExecutors, val dependencyManager: DependencyManager, val settings: KobaltSettings, override val configActor: ConfigActor<KotlinConfig>) : BaseJvmPlugin<KotlinConfig>(configActor), IDocContributor, IClasspathContributor, ICompilerContributor, IBuildConfigContributor { companion object { const val PLUGIN_NAME = "Kotlin" } override val name = PLUGIN_NAME override fun accept(project: Project) = hasSourceFiles(project) // IBuildConfigContributor private fun hasSourceFiles(project: Project) = KFiles.findSourceFiles(project.directory, project.sourceDirectories, listOf("kt")).size > 0 override fun affinity(project: Project) = if (hasSourceFiles(project)) 1 else 0 // IDocContributor override fun affinity(project: Project, context: KobaltContext) = if (project.sourceDirectories.any { it.contains("kotlin") }) 2 else 0 override fun generateDoc(project: Project, context: KobaltContext, info: CompilerActionInfo) : TaskResult { return TaskResult() } // ICompilerFlagsContributor override fun flagsFor(project: Project, context: KobaltContext, currentFlags: List<String>, suffixesBeingCompiled: List<String>) : List<String> { val args = (configurationFor(project)?.compilerArgs ?: listOf<String>()) + "-no-stdlib" return maybeCompilerArgs(compiler.sourceSuffixes, suffixesBeingCompiled, args) } // override fun generateDoc(project: Project, context: KobaltContext, info: CompilerActionInfo) : TaskResult { // val configs = dokkaConfigurations[project.name] // val classpath = context.dependencyManager.calculateDependencies(project, context) // val buildDir = project.buildDirectory // val classpathList = classpath.map { it.jarFile.get().absolutePath } + listOf(buildDir) // var success = true // configs.forEach { config -> // if (!config.skip) { // val outputDir = buildDir + "/" + // if (config.outputDir.isBlank()) "doc" else config.outputDir // // val gen = DokkaGenerator( // KobaltDokkaLogger { success = false }, // classpathList, // project.sourceDirectories.filter { File(it).exists() }.toList(), // config.samplesDirs, // config.includeDirs, // config.moduleName, // outputDir, // config.outputFormat, // config.sourceLinks.map { SourceLinkDefinition(it.dir, it.url, it.urlSuffix) } // ) // gen.generate() // log(2, "Documentation generated in $outputDir") // } else { // log(2, "skip is true, not generating the documentation") // } // } // return TaskResult(success) // } private fun compilePrivate(project: Project, cpList: List<IClasspathDependency>, sources: List<String>, outputDirectory: File, compilerArgs: List<String>): TaskResult { return kotlinCompilePrivate { classpath(cpList.map { it.jarFile.get().absolutePath }) sourceFiles(sources) compilerArgs(compilerArgs) output = outputDirectory }.compile(project, context) } private fun getKotlinCompilerJar(name: String): String { val id = "org.jetbrains.kotlin:$name:${settings.kobaltCompilerVersion}" val dep = dependencyManager.create(id) val result = dep.jarFile.get().absolutePath return result } // IClasspathContributor override fun classpathEntriesFor(project: Project?, context: KobaltContext): List<IClasspathDependency> = if (project == null || accept(project)) { // All Kotlin projects automatically get the Kotlin runtime added to their class path listOf(getKotlinCompilerJar("kotlin-stdlib"), getKotlinCompilerJar("kotlin-runtime")) .map { FileDependency(it) } } else { emptyList() } // ICompilerContributor val compiler = object: ICompiler { override val sourceSuffixes = listOf("kt") /** The Kotlin compiler should run before the Java one */ override val priority: Int get() = ICompiler.DEFAULT_PRIORITY - 5 override val sourceDirectory = "kotlin" /** kotlinc can be passed directories */ override val canCompileDirectories = true override fun compile(project: Project, context: KobaltContext, info: CompilerActionInfo): TaskResult { val result = if (info.sourceFiles.size > 0) { compilePrivate(project, info.dependencies, info.sourceFiles, info.outputDir, info.compilerArgs) } else { warn("Couldn't find any source files") TaskResult() } lp(project, "Compilation " + if (result.success) "succeeded" else "failed") if (! result.success && result.errorMessage != null) { error(result.errorMessage!!) } return result } } override fun compilersFor(project: Project, context: KobaltContext) = arrayListOf(compiler) // private val dokkaConfigurations = ArrayListMultimap.create<String, DokkaConfig>() // // fun addDokkaConfiguration(project: Project, dokkaConfig: DokkaConfig) { // dokkaConfigurations.put(project.name, dokkaConfig) // } protected fun lp(project: Project, s: String) { log(2, "${project.name}: $s") } override val buildConfigSuffix = "kt" override fun generateBuildConfig(project: Project, context: KobaltContext, packageName: String, variant: Variant, buildConfigs: List<BuildConfig>): String { return KotlinBuildConfig().generateBuildConfig(project, context, packageName, variant, buildConfigs) } } /** * @param project: the list of projects that need to be built before this one. */ @Directive fun kotlinProject(vararg projects: Project, init: Project.() -> Unit): Project { return Project().apply { warn("kotlinProject{} is deprecated, please use project{}") init() (Kobalt.findPlugin(JvmCompilerPlugin.PLUGIN_NAME) as JvmCompilerPlugin) .addDependentProjects(this, projects.toList()) } } class KotlinConfig(val project: Project) { val compilerArgs = arrayListOf<String>() fun args(vararg options: String) = compilerArgs.addAll(options) } @Directive fun Project.kotlinCompiler(init: KotlinConfig.() -> Unit) = let { val config = KotlinConfig(it) config.init() (Kobalt.findPlugin(KotlinPlugin.PLUGIN_NAME) as KotlinPlugin).addConfiguration(this, config) } //class SourceLinkMapItem { // var dir: String = "" // var url: String = "" // var urlSuffix: String? = null //} // //class DokkaConfig( // var samplesDirs: List<String> = emptyList(), // var includeDirs: List<String> = emptyList(), // var outputDir: String = "", // var outputFormat: String = "html", // var sourceLinks : ArrayList<SourceLinkMapItem> = arrayListOf<SourceLinkMapItem>(), // var moduleName: String = "", // var skip: Boolean = false) { // // fun sourceLinks(init: SourceLinkMapItem.() -> Unit) // = sourceLinks.add(SourceLinkMapItem().apply { init() }) //}
apache-2.0
98fe0890e69abd07ebd485ace95babcb
39.07767
135
0.64765
4.609715
false
true
false
false
cfieber/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/ResumeExecutionHandlerTest.kt
1
2587
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spinnaker.orca.ExecutionStatus.* import com.netflix.spinnaker.orca.fixture.pipeline import com.netflix.spinnaker.orca.fixture.stage import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.q.ResumeExecution import com.netflix.spinnaker.orca.q.ResumeStage import com.netflix.spinnaker.q.Queue import com.nhaarman.mockito_kotlin.* import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP import org.jetbrains.spek.subject.SubjectSpek object ResumeExecutionHandlerTest : SubjectSpek<ResumeExecutionHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() subject(GROUP) { ResumeExecutionHandler(queue, repository) } fun resetMocks() = reset(queue, repository) describe("resuming a paused execution") { val pipeline = pipeline { application = "spinnaker" status = PAUSED stage { refId = "1" status = SUCCEEDED } stage { refId = "2a" requisiteStageRefIds = listOf("1") status = PAUSED } stage { refId = "2b" requisiteStageRefIds = listOf("1") status = PAUSED } stage { refId = "3" requisiteStageRefIds = listOf("2a", "2b") status = NOT_STARTED } } val message = ResumeExecution(pipeline.type, pipeline.id, pipeline.application) beforeGroup { whenever(repository.retrieve(pipeline.type, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("resumes all paused stages") { verify(queue).push(ResumeStage(message, pipeline.stageByRef("2a").id)) verify(queue).push(ResumeStage(message, pipeline.stageByRef("2b").id)) verifyNoMoreInteractions(queue) } } })
apache-2.0
521e65482a5c6277ad1a368ec4783463
29.435294
83
0.703518
4.220228
false
false
false
false
iSoron/uhabits
uhabits-android/src/androidTest/java/org/isoron/uhabits/widgets/TargetWidgetTest.kt
1
2214
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.widgets import android.widget.FrameLayout import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import org.isoron.uhabits.BaseViewTest import org.isoron.uhabits.R import org.isoron.uhabits.core.models.Frequency import org.isoron.uhabits.core.models.Habit import org.isoron.uhabits.core.models.PaletteColor import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @MediumTest class TargetWidgetTest : BaseViewTest() { init { // TODO: fix rendering differences across APIs similarityCutoff = 0.00025 } private lateinit var habit: Habit private lateinit var view: FrameLayout override fun setUp() { super.setUp() setTheme(R.style.WidgetTheme) prefs.widgetOpacity = 255 habit = fixtures.createLongNumericalHabit().apply { color = PaletteColor(11) frequency = Frequency.WEEKLY recompute() } val widget = TargetWidget(targetContext, 0, habit) view = convertToView(widget, 400, 400) } @Test fun testIsInstalled() { assertWidgetProviderIsInstalled(TargetWidgetProvider::class.java) } @Test @Throws(Exception::class) fun testRender() { assertRenders(view, PATH + "render.png") } companion object { private const val PATH = "widgets/TargetWidget/" } }
gpl-3.0
370b693f87195e1b0498fb26828547e6
31.544118
78
0.710348
4.263969
false
true
false
false
mdanielwork/intellij-community
platform/platform-api/src/com/intellij/ide/browsers/BrowserLauncher.kt
6
2159
/* * Copyright 2000-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 com.intellij.ide.browsers import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.project.Project import com.intellij.util.ArrayUtil import java.io.File import java.net.URI abstract class BrowserLauncher { companion object { @JvmStatic val instance: BrowserLauncher get() = ServiceManager.getService(BrowserLauncher::class.java) } abstract fun open(url: String) fun browse(uri: URI): Unit = browse(uri, null) fun browse(uri: URI, project: Project?) { browse(uri.toString(), project = project) } abstract fun browse(file: File) fun browse(url: String, browser: WebBrowser?) { browse(url, browser, null) } abstract fun browse(url: String, browser: WebBrowser? = null, project: Project? = null) fun browseUsingPath(url: String?, browserPath: String? = null, browser: WebBrowser? = null, project: Project? = null, additionalParameters: Array<String> = ArrayUtil.EMPTY_STRING_ARRAY): Boolean { return browseUsingPath(url, browserPath, browser, project, false, additionalParameters) } abstract fun browseUsingPath(url: String?, browserPath: String? = null, browser: WebBrowser? = null, project: Project? = null, openInNewWindow: Boolean = false, additionalParameters: Array<String> = ArrayUtil.EMPTY_STRING_ARRAY): Boolean }
apache-2.0
7bc73eafb5c139dbd84070ea1e59596e
33.83871
107
0.658175
4.583864
false
false
false
false
iSoron/uhabits
uhabits-android/src/main/java/org/isoron/uhabits/notifications/SnoozeDelayPickerActivity.kt
1
4099
/* * Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]> * * This file is part of Loop Habit Tracker. * * Loop Habit Tracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Loop Habit Tracker is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.isoron.uhabits.notifications import android.app.AlertDialog import android.content.ContentUris import android.os.Bundle import android.text.format.DateFormat import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemClickListener import androidx.fragment.app.FragmentActivity import com.android.datetimepicker.time.RadialPickerLayout import com.android.datetimepicker.time.TimePickerDialog import org.isoron.platform.gui.toInt import org.isoron.uhabits.HabitsApplication import org.isoron.uhabits.R import org.isoron.uhabits.activities.AndroidThemeSwitcher import org.isoron.uhabits.core.models.Habit import org.isoron.uhabits.core.ui.ThemeSwitcher.Companion.THEME_LIGHT import org.isoron.uhabits.receivers.ReminderController import org.isoron.uhabits.utils.SystemUtils import java.util.Calendar class SnoozeDelayPickerActivity : FragmentActivity(), OnItemClickListener { private var habit: Habit? = null private var reminderController: ReminderController? = null private var dialog: AlertDialog? = null private var androidColor: Int = 0 override fun onCreate(bundle: Bundle?) { super.onCreate(bundle) val intent = intent if (intent == null) finish() val app = applicationContext as HabitsApplication val appComponent = app.component val themeSwitcher = AndroidThemeSwitcher(this, appComponent.preferences) if (themeSwitcher.getSystemTheme() == THEME_LIGHT) { setTheme(R.style.BaseDialog) } else { setTheme(R.style.BaseDialogDark) } val data = intent.data if (data == null) { finish() } else { habit = appComponent.habitList.getById(ContentUris.parseId(data)) } if (habit == null) finish() androidColor = themeSwitcher.currentTheme.color(habit!!.color).toInt() reminderController = appComponent.reminderController dialog = AlertDialog.Builder(this) .setTitle(R.string.select_snooze_delay) .setItems(R.array.snooze_picker_names, null) .create() dialog!!.listView.onItemClickListener = this dialog!!.setOnDismissListener { finish() } dialog!!.show() SystemUtils.unlockScreen(this) } private fun showTimePicker() { val calendar = Calendar.getInstance() val dialog = TimePickerDialog.newInstance( { view: RadialPickerLayout?, hour: Int, minute: Int -> reminderController!!.onSnoozeTimePicked(habit, hour, minute) finish() }, calendar[Calendar.HOUR_OF_DAY], calendar[Calendar.MINUTE], DateFormat.is24HourFormat(this), androidColor ) dialog.show(supportFragmentManager, "timePicker") } override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) { val snoozeValues = resources.getIntArray(R.array.snooze_picker_values) if (snoozeValues[position] >= 0) { reminderController!!.onSnoozeDelayPicked(habit!!, snoozeValues[position]) finish() } else showTimePicker() } override fun finish() { super.finish() overridePendingTransition(0, 0) } }
gpl-3.0
97401d5fc922cec050569aaafb038a67
38.028571
92
0.695217
4.589026
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/arch/api/internal/ServerURLVersionRedirectionInterceptor.kt
1
2595
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.arch.api.internal import java.io.IOException import okhttp3.Interceptor import okhttp3.Response import org.hisp.dhis.android.core.arch.api.authentication.internal.PasswordAndCookieAuthenticator.Companion.LOCATION_KEY internal class ServerURLVersionRedirectionInterceptor : Interceptor { @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() var response = chain.proceed(request) var redirects = 0 while (response.isRedirect && redirects <= MaxRedirects) { val location = response.header(LOCATION_KEY) location?.let { ServerURLWrapper.setServerUrl(it) } response.close() val redirectReq = DynamicServerURLInterceptor.transformRequest(request) response = chain.proceed(redirectReq) redirects++ } return response } companion object { const val MaxRedirects = 20 } }
bsd-3-clause
aedc7c3032160a3b881f28e24202a30f
44.526316
120
0.739499
4.650538
false
false
false
false
Kennyc1012/DashWeatherExtension
data-gps/src/main/java/com/kennyc/dashweather/data_gps/GPSLocationRepository.kt
1
3005
package com.kennyc.dashweather.data_gps import android.annotation.SuppressLint import android.content.Context import android.location.Geocoder import android.os.Looper import android.text.format.DateUtils import com.google.android.gms.location.* import com.kennyc.dashweather.data.LocationRepository import com.kennyc.dashweather.data.model.WeatherLocation import io.reactivex.rxjava3.core.Maybe import io.reactivex.rxjava3.core.Observable import java.util.* class GPSLocationRepository(context: Context) : LocationRepository { private val client = LocationServices.getFusedLocationProviderClient(context) private val geocoder = Geocoder(context, Locale.getDefault()) @SuppressLint("MissingPermission") override fun getLastKnownLocation(): Maybe<WeatherLocation> { return Maybe.create { emitter -> client.lastLocation.addOnFailureListener { emitter.onError(it) }.addOnSuccessListener { if (it != null) { emitter.onSuccess(WeatherLocation(it.latitude, it.longitude)) } else { emitter.onError(NullPointerException("No Location found")) } } } } override fun getLocationName(lat: Double, lon: Double): Maybe<String> { val address = geocoder.getFromLocation(lat, lon, 1) return if (address != null && address.isNotEmpty()) { address[0].run { "$locality, $adminArea" }.let { Maybe.just(it) } } else { Maybe.empty() } } @SuppressLint("MissingPermission") override fun requestLocationUpdates(): Observable<WeatherLocation> { return Observable.create { emitter -> val request = LocationRequest.create() .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY) .setExpirationDuration(DateUtils.MINUTE_IN_MILLIS) .setNumUpdates(1) val cb = object : LocationCallback() { override fun onLocationResult(result: LocationResult?) { when (result) { null -> throw NullPointerException("No location received from updates") else -> { val location = result.locations[0] emitter.onNext(WeatherLocation(location.latitude, location.longitude)) } } client.removeLocationUpdates(this) } override fun onLocationAvailability(availability: LocationAvailability) { if (!availability.isLocationAvailable) { emitter.onError(IllegalStateException("Location not available")) client.removeLocationUpdates(this) } } } client.requestLocationUpdates(request, cb, Looper.getMainLooper()) } } }
apache-2.0
80faebefc5ce795175937f2246ba229a
36.111111
98
0.603328
5.503663
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/wordSelection/KotlinWordSelectionFilter.kt
6
1186
// 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.editor.wordSelection import com.intellij.openapi.util.Condition import com.intellij.psi.PsiElement import org.jetbrains.kotlin.KtNodeTypes.BLOCK import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.kdoc.parser.KDocElementTypes import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtContainerNode class KotlinWordSelectionFilter : Condition<PsiElement> { override fun value(e: PsiElement): Boolean { if (e.language != KotlinLanguage.INSTANCE) return true if (KotlinListSelectioner.canSelect(e)) return false if (KotlinCodeBlockSelectioner.canSelect(e)) return false val elementType = e.node.elementType if (elementType == KtTokens.REGULAR_STRING_PART || elementType == KtTokens.ESCAPE_SEQUENCE) return true if (e is KtContainerNode) return false return when (e.node.elementType) { BLOCK, KDocElementTypes.KDOC_SECTION -> false else -> true } } }
apache-2.0
12ee5206a9d9a970476200e477492aea
38.533333
158
0.742833
4.376384
false
false
false
false
fwcd/kotlin-language-server
server/src/main/kotlin/org/javacs/kt/position/Position.kt
1
4015
package org.javacs.kt.position import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.eclipse.lsp4j.Location import org.eclipse.lsp4j.Position import org.eclipse.lsp4j.Range import org.javacs.kt.LOG import org.javacs.kt.util.toPath import org.jetbrains.kotlin.descriptors.SourceFile import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithSource import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi import org.jetbrains.kotlin.resolve.source.PsiSourceFile import kotlin.math.max fun extractRange(content: String, range: Range) = content.substring( offset(content, range.start), offset(content, range.end) ) fun offset(content: String, position: Position) = offset(content, position.line, position.character) /** * Convert from 0-based line and column to 0-based offset */ fun offset(content: String, line: Int, char: Int): Int { assert(!content.contains('\r')) val reader = content.reader() var offset = 0 var lineOffset = 0 while (lineOffset < line) { val nextChar = reader.read() if (nextChar == -1) throw RuntimeException("Reached end of file before reaching line $line") if (nextChar.toChar() == '\n') lineOffset++ offset++ } var charOffset = 0 while (charOffset < char) { val nextChar = reader.read() if (nextChar == -1) throw RuntimeException("Reached end of file before reaching char $char") charOffset++ offset++ } return offset } fun position(content: String, offset: Int): Position { val reader = content.reader() var line = 0 var char = 0 var find = 0 while (find < offset) { val nextChar = reader.read() if (nextChar == -1) throw RuntimeException("Reached end of file before reaching offset $offset") find++ char++ if (nextChar.toChar() == '\n') { line++ char = 0 } } return Position(line, char) } fun range(content: String, range: TextRange) = Range(position(content, range.startOffset), position(content, range.endOffset)) fun location(declaration: DeclarationDescriptor): Location? { val psiLocation = declaration.findPsi()?.let(::location) if (psiLocation != null) return psiLocation if (declaration is DeclarationDescriptorWithSource) { val sourceFile = declaration.source.containingFile when (sourceFile) { is PsiSourceFile -> { val file = sourceFile.psiFile.toURIString() return Location(file, Range(Position(0, 0), Position(0, 0))) } SourceFile.NO_SOURCE_FILE -> Unit // If no source file is present, do nothing else -> LOG.info("Source type of {} not recognized", sourceFile) } } else { LOG.info("{} does not have a source", declaration) } return null } val Position.isZero: Boolean get() = (line == 0) && (character == 0) val Range.isZero: Boolean get() = start.isZero && end.isZero fun location(expr: PsiElement): Location? { val content = try { expr.containingFile?.text } catch (e: NullPointerException) { null } val file = expr.containingFile.toURIString() return content?.let { Location(file, range(it, expr.textRange)) } } fun PsiFile.toURIString() = toPath().toUri().toString() /** * Region that has been changed */ fun changedRegion(oldContent: String, newContent: String): Pair<TextRange, TextRange>? { if (oldContent == newContent) return null val prefix = oldContent.commonPrefixWith(newContent).length val suffix = oldContent.commonSuffixWith(newContent).length val oldEnd = max(oldContent.length - suffix, prefix) val newEnd = max(newContent.length - suffix, prefix) return Pair(TextRange(prefix, oldEnd), TextRange(prefix, newEnd)) }
mit
cbca64b4d831f95f3744294b468e3b42
28.306569
92
0.663014
4.199791
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedLambdaExpressionBodyInspection.kt
3
4205
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInsight.FileModificationService import com.intellij.codeInspection.LocalQuickFixOnPsiElement import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiFile import org.jetbrains.kotlin.builtins.isFunctionType import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.tower.NewResolvedCallImpl import org.jetbrains.kotlin.resolve.calls.tower.NewVariableAsFunctionResolvedCallImpl import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.utils.addToStdlib.safeAs class UnusedLambdaExpressionBodyInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return callExpressionVisitor(fun(expression) { val context = expression.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL_WITH_CFA) if (context == BindingContext.EMPTY || expression.isUsedAsExpression(context)) { return } val resolvedCall = expression.getResolvedCall(context) ?: return val descriptor = resolvedCall.resultingDescriptor.let { if (resolvedCall is NewResolvedCallImpl || resolvedCall is NewVariableAsFunctionResolvedCallImpl) it.original else it } if (!descriptor.returnsFunction()) { return } val function = descriptor.source.getPsi() as? KtFunction ?: return if (function.hasBlockBody() || function.bodyExpression !is KtLambdaExpression) { return } holder.registerProblem( expression, KotlinBundle.message("unused.return.value.of.a.function.with.lambda.expression.body"), RemoveEqTokenFromFunctionDeclarationFix(function) ) }) } private fun CallableDescriptor.returnsFunction() = returnType?.isFunctionType ?: false class RemoveEqTokenFromFunctionDeclarationFix(function: KtFunction) : LocalQuickFixOnPsiElement(function) { override fun getText(): String = KotlinBundle.message("remove.token.from.function.declaration") override fun getFamilyName(): String = name override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) { val function = startElement as? KtFunction ?: return if (!FileModificationService.getInstance().preparePsiElementForWrite(function)) { return } function.replaceBlockExpressionWithLambdaBody(function.bodyExpression?.safeAs<KtLambdaExpression>()?.bodyExpression) } } companion object { fun KtDeclarationWithBody.replaceBlockExpressionWithLambdaBody(lambdaBody: KtBlockExpression?) { equalsToken?.let { token -> val ktPsiFactory = KtPsiFactory(project) val lambdaBodyRange = lambdaBody?.allChildren val newBlockBody: KtBlockExpression = if (lambdaBodyRange?.isEmpty == false) { ktPsiFactory.createDeclarationByPattern<KtNamedFunction>("fun foo() {$0}", lambdaBodyRange).bodyBlockExpression!! } else { ktPsiFactory.createBlock("") } bodyExpression?.delete() token.replace(newBlockBody) } } } }
apache-2.0
4bafe5706f0be667af4d917e8d637ad0
45.733333
158
0.714863
5.591755
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/appsync/src/main/kotlin/com/example/appsync/DeleteApiKey.kt
1
1731
// snippet-sourcedescription:[DeleteApiKey.kt demonstrates how to delete a unique key.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[AWS AppSync] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.example.appsync // snippet-start:[appsync.kotlin.del_key.import] import aws.sdk.kotlin.services.appsync.AppSyncClient import aws.sdk.kotlin.services.appsync.model.DeleteApiKeyRequest import kotlin.system.exitProcess // snippet-end:[appsync.kotlin.del_key.import] /** * Before running this Kotlin code example, set up your development environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <apiId> <keyId> Where: apiId - The Id of the API. (You can get this value from the AWS Management Console.) keyId - The Id of the key to delete. """ if (args.size != 2) { println(usage) exitProcess(1) } val apiId = args[0] val keyId = args[1] deleteKey(keyId, apiId) } // snippet-start:[appsync.kotlin.del_key.main] suspend fun deleteKey(keyIdVal: String?, apiIdVal: String?) { val apiKeyRequest = DeleteApiKeyRequest { apiId = apiIdVal id = keyIdVal } AppSyncClient { region = "us-east-1" }.use { appClient -> appClient.deleteApiKey(apiKeyRequest) println("$keyIdVal key was deleted.") } } // snippet-end:[appsync.kotlin.del_key.main]
apache-2.0
89311dedbc9af71b3f3775c5c9a002ab
27.338983
108
0.65569
3.804396
false
false
false
false
airbnb/epoxy
kotlinsample/src/main/java/com/airbnb/epoxy/kotlinsample/models/ManualLayoutParamsView.kt
1
821
package com.airbnb.epoxy.kotlinsample.models import android.content.Context import android.util.AttributeSet import android.view.ViewGroup import androidx.appcompat.widget.AppCompatTextView import com.airbnb.epoxy.ModelView import com.airbnb.epoxy.TextProp @ModelView(autoLayout = ModelView.Size.MANUAL) class ManualLayoutParamsView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : AppCompatTextView(context, attrs, defStyle) { init { layoutParams = ViewGroup.MarginLayoutParams( ViewGroup.MarginLayoutParams.MATCH_PARENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT ).apply { setMargins(50, 50, 50, 50) } } @TextProp fun setTitle(title: CharSequence?) { text = title } }
apache-2.0
654935076ce57c73c2829c678b2a23ef
26.366667
55
0.71011
4.510989
false
false
false
false
deso88/TinyGit
src/main/kotlin/hamburg/remme/tinygit/gui/component/CalendarChart.kt
1
6964
package hamburg.remme.tinygit.gui.component import hamburg.remme.tinygit.atStartOfWeek import hamburg.remme.tinygit.dayOfWeekFormat import hamburg.remme.tinygit.daysFromOrigin import hamburg.remme.tinygit.gui.builder.addClass import hamburg.remme.tinygit.gui.builder.label import javafx.animation.Interpolator import javafx.animation.KeyFrame import javafx.animation.KeyValue import javafx.animation.Timeline import javafx.scene.layout.Pane import javafx.scene.shape.LineTo import javafx.scene.shape.MoveTo import javafx.scene.shape.Path import javafx.scene.shape.Rectangle import javafx.util.Duration import java.time.DayOfWeek import java.time.LocalDate import kotlin.math.roundToInt private const val DEFAULT_STYLE_CLASS = "calendar" private const val AXIS_STYLE_CLASS = "axis" private const val TICK_STYLE_CLASS = "tick" private const val SHAPE_STYLE_CLASS = "shape" private const val RECT_STYLE_CLASS = "rectangle-color" private const val TICK_MARK_LENGTH = 5.0 private const val TICK_MARK_GAP = 2.0 /** * @todo: find abstraction between this and [HistogramChart], especially tick marks and axes */ class CalendarChart(title: String) : Chart(title) { private val tickMarks = mutableListOf<TickMark<LocalDate>>() private val dowMarks = mutableListOf<TickMark<DayOfWeek>>() private val data = mutableListOf<Data>() private val rectangles get() = data.map { it.node } private val plotContent = object : Pane() { override fun layoutChildren() { } } private val plotContentClip = Rectangle() private val xAxis = Path().addClass(AXIS_STYLE_CLASS) var lowerBound: LocalDate get() = throw RuntimeException("Write-only property.") set(value) { lowerBoundX = value.daysFromOrigin } var upperBound: LocalDate get() = throw RuntimeException("Write-only property.") set(value) { upperBoundX = value.daysFromOrigin } private var lowerBoundX = 0L private var upperBoundX = 100L init { addClass(DEFAULT_STYLE_CLASS) plotContentClip.isManaged = false plotContentClip.isSmooth = false plotContent.clip = plotContentClip plotContent.isManaged = false chartChildren.addAll(plotContent, xAxis) setDowMarks(DayOfWeek.values().map { TickMark(dayOfWeekFormat.format(it), it) }) } fun setData(data: List<Data>) { // Remove old rectangles first plotContent.children -= rectangles // Get highest y-value val maxY = data.map { it.yValue }.max()?.toDouble() ?: 0.0 // Set new reference list this.data.clear() this.data += data this.data.forEach { it.createNode((it.yValue / maxY * 4).roundToInt()) } // Add new rectangles plotContent.children += rectangles // Finally request chart layout requestChartLayout() } fun setTickMarks(tickMarks: List<TickMark<LocalDate>>) { // Remove old labels chartChildren -= this.tickMarks.map { it.label } // Set new reference list this.tickMarks.clear() this.tickMarks += tickMarks // Add new labels chartChildren += this.tickMarks.map { it.label } } private fun setDowMarks(tickMarks: List<TickMark<DayOfWeek>>) { // Remove old labels chartChildren -= this.dowMarks.map { it.label } // Set new reference list this.dowMarks.clear() this.dowMarks += tickMarks // Add new labels chartChildren += this.dowMarks.map { it.label } } override fun layoutChartChildren(width: Double, height: Double) { val labelWidth = dowMarks.map { it.label.prefWidth(height) }.max() ?: 0.0 val labelHeight = tickMarks.map { it.label.prefHeight(width) }.max() ?: 0.0 val yAxisWidth = snapSizeX(TICK_MARK_LENGTH + labelWidth) val xAxisHeight = snapSizeY(TICK_MARK_LENGTH + TICK_MARK_GAP + labelHeight) val contentWidth = width - yAxisWidth val contentHeight = height - xAxisHeight val stepX = contentWidth / (upperBoundX - lowerBoundX) val stepY = contentHeight / 7 xAxis.elements.clear() tickMarks.forEach { val value = Math.max(0, it.value.atStartOfWeek().daysFromOrigin - lowerBoundX) var x = snapPositionX(value * stepX + yAxisWidth) val w = snapSizeX(it.label.prefWidth(contentHeight)) val h = snapSizeY(it.label.prefHeight(contentWidth)) xAxis.elements.addAll(MoveTo(x, height - xAxisHeight), LineTo(x, height - xAxisHeight + TICK_MARK_LENGTH)) x -= if (x + w > width) w - 4.0 else 4.0 it.label.resizeRelocate(x, height - xAxisHeight + TICK_MARK_LENGTH + TICK_MARK_GAP, w, h) } dowMarks.forEach { val y = snapPositionY(it.value.value * stepY - stepY / 2) val w = snapSizeX(it.label.prefWidth(contentHeight)) val h = snapSizeY(it.label.prefHeight(contentWidth)) it.label.resizeRelocate(yAxisWidth - w - TICK_MARK_LENGTH, y - h / 2, w, h) } plotContentClip.x = 0.0 plotContentClip.y = 0.0 plotContentClip.width = contentWidth plotContentClip.height = contentHeight plotContent.resizeRelocate(yAxisWidth, 0.0, contentWidth, contentHeight) layoutPlotChildren(contentWidth, contentHeight) } private fun layoutPlotChildren(width: Double, height: Double) { val stepX = width / (upperBoundX - lowerBoundX) val stepY = height / 7 val timeline = Timeline() data.forEach { val rect = it.node as Rectangle if (!it.wasAnimated) { rect.opacity = 0.0 timeline.keyFrames += KeyFrame(Duration.millis(500.0 + 500.0 * it.index), KeyValue(rect.opacityProperty(), 1.0, Interpolator.EASE_OUT)) it.wasAnimated = true } val adjustedDate = it.xValue.atStartOfWeek() val x = (adjustedDate.daysFromOrigin - lowerBoundX) * stepX val y = it.xValue.dayOfWeek.ordinal * stepY val w = stepX * 7 val h = stepY rect.x = snapPositionX(x) + 1 rect.y = snapPositionY(y) + 1 rect.width = snapSizeX(w) - 2 rect.height = snapSizeY(h) - 2 } if (timeline.keyFrames.isNotEmpty()) timeline.play() } class TickMark<out T>(val name: String, val value: T) { val label = label { addClass(TICK_STYLE_CLASS) text = name } } class Data(val xValue: LocalDate, val yValue: Int) { var node: Rectangle? = null var wasAnimated = false var index = 0 fun createNode(index: Int) { this.index = index node = Rectangle().apply { addClass(SHAPE_STYLE_CLASS, "$RECT_STYLE_CLASS$index") } } } }
bsd-3-clause
375f8aefe4553b2ee6a3507a51e8d2c9
35.846561
118
0.637277
4.106132
false
false
false
false
paplorinc/intellij-community
plugins/terminal/src/org/jetbrains/plugins/terminal/action/TerminalSessionContextMenuActionBase.kt
4
886
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.terminal.action import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowContextMenuActionBase import com.intellij.openapi.wm.impl.ToolWindowImpl import com.intellij.ui.content.Content import org.jetbrains.plugins.terminal.TerminalToolWindowFactory abstract class TerminalSessionContextMenuActionBase : ToolWindowContextMenuActionBase() { override fun update(e: AnActionEvent, activeToolWindow: ToolWindow, selectedContent: Content?) { val id = (activeToolWindow as ToolWindowImpl).id e.presentation.isEnabledAndVisible = e.project != null && id == TerminalToolWindowFactory.TOOL_WINDOW_ID && selectedContent != null } }
apache-2.0
9ff9bc1b5aeaf4364abc9e91f01544c9
54.4375
140
0.818284
4.54359
false
false
false
false
suchoX/Addect
app/src/main/java/com/crimson/addect/feature/startscreen/StartScreenActivity.kt
1
2118
package com.crimson.addect.feature.startscreen import android.app.AlertDialog import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.Window import android.view.WindowManager import com.crimson.addect.R import com.crimson.addect.dagger.component.ActivityComponent import com.crimson.addect.databinding.StartScreenActivityBinding import com.crimson.addect.feature.base.BaseActivity import com.crimson.addect.utils.SharedPrefs import com.crimson.addect.utils.Constants import javax.inject.Inject class StartScreenActivity : BaseActivity<StartScreenActivityBinding, StartScreenViewModel>(), StartscreenView { private val RATING_DIALOG_MAX_FREQUENCY = 10 @Inject lateinit var sharedPrefs: SharedPrefs override fun layoutId(): Int = R.layout.activity_start_screen override fun onComponentCreated(activityComponent: ActivityComponent) { activityComponent.inject(this) showRatingDialog() } fun showRatingDialog() { if (sharedPrefs.showRatingDialog()) { val count = sharedPrefs.getRatingCount() if (count == RATING_DIALOG_MAX_FREQUENCY) { val builder: AlertDialog.Builder = AlertDialog.Builder(this) builder.setMessage(R.string.like_us) .setCancelable(true) .setPositiveButton(R.string.rate, { _, _ -> val uri = Uri.parse(Constants.APP_MARKET_LINK) val goToMarket = Intent(Intent.ACTION_VIEW, uri) try { startActivity(goToMarket) } catch (e: ActivityNotFoundException) { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse( Constants.APP_URL_LINK))) } sharedPrefs.setShowRatingDialog(false) }) .setNegativeButton(R.string.cancel, { _, _ -> }) .create() val alertDialog: AlertDialog = builder.create() alertDialog.show() sharedPrefs.setRatingCount(0) } else { sharedPrefs.setRatingCount(count + 1) } } } }
apache-2.0
8db4badae05282cd1ed5e0570115ef90
33.16129
111
0.68508
4.644737
false
false
false
false
paplorinc/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInspection/Java9ModuleExportsPackageToItselfTest.kt
15
3504
/* * Copyright 2000-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 com.intellij.java.codeInspection import com.intellij.codeInspection.InspectionsBundle import com.intellij.codeInspection.java19modules.Java9ModuleExportsPackageToItselfInspection import com.intellij.java.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor import org.intellij.lang.annotations.Language /** * @author Pavel.Dolgov */ class Java9ModuleExportsPackageToItselfTest : LightJava9ModulesCodeInsightFixtureTestCase() { private val message = InspectionsBundle.message("inspection.module.exports.package.to.itself")!! private val fix1 = InspectionsBundle.message("exports.to.itself.delete.statement.fix")!! private val fix2 = InspectionsBundle.message("exports.to.itself.delete.module.ref.fix", "M")!! override fun setUp() { super.setUp() myFixture.enableInspections(Java9ModuleExportsPackageToItselfInspection()) addFile("module-info.java", "module M2 { }", MultiModuleJava9ProjectDescriptor.ModuleDescriptor.M2) addFile("module-info.java", "module M4 { }", MultiModuleJava9ProjectDescriptor.ModuleDescriptor.M4) addFile("pkg/main/C.java", "package pkg.main; public class C {}") } fun testNoSelfModule() { highlight("module M {\n exports pkg.main to M2, M4;\n opens pkg.main to M2, M4;\n}") } fun testOnlySelfExport() { highlight("module M { exports pkg.main to <warning descr=\"$message\">M</warning>; }") fix("module M { exports pkg.main to <caret>M; }", "module M {\n}") } fun testOnlySelfOpen() { highlight("module M { opens pkg.main to <warning descr=\"$message\">M</warning>; }") fix("module M { opens pkg.main to <caret>M; }", "module M {\n}") } fun testOnlySelfModuleWithComments() { fix("module M { exports pkg.main to /*a*/ <caret>M /*b*/; }", "module M { /*a*/ /*b*/\n}") } fun testSelfModuleInList() { highlight("module M { exports pkg.main to M2, <warning descr=\"$message\">M</warning>, M4; }") fix("module M { exports pkg.main to M2, <caret>M , M4; }", "module M { exports pkg.main to M2, M4; }") } fun testSelfModuleInListWithComments() { fix("module M { exports pkg.main to M2, /*a*/ <caret>M /*b*/,/*c*/ M4; }", "module M { exports pkg.main to M2, /*a*/ /*b*//*c*/ M4; }") } private fun highlight(text: String) { myFixture.configureByText("module-info.java", text) myFixture.checkHighlighting() } private fun fix(textBefore: String, @Language("JAVA") textAfter: String) { myFixture.configureByText("module-info.java", textBefore) val action = myFixture.filterAvailableIntentions(fix1).firstOrNull() ?: myFixture.filterAvailableIntentions(fix2).first() myFixture.launchAction(action) myFixture.checkHighlighting() // no warning myFixture.checkResult("module-info.java", textAfter, false) } }
apache-2.0
18e11b715142f5a34909e80cfb198e33
39.287356
125
0.711187
3.986348
false
true
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/utils/IconManager.kt
2
5746
/* * 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.utils object IconManager { private const val PREFIX = "fas fa-" //TODO far fa- ??? const val DEFAULT_ICON = PREFIX + "play" const val DANGER = "text-danger" const val DISABLED = "text-disabled" private const val NORMAL = "text-normal" const val OK = "text-ok" const val WARN = "text-warn" /* Merge with configuration values*/ private val word2Icon = mapOf( "About" to "info-circle", "Actions" to "ellipsis-v", "All" to "asterisk", "Basic" to "minus-circle", "Blobs" to "cloud", "Burger" to "bars", "Chart" to "magic", "Close" to "times", "Collections" to "list", "Compare" to "balance-scale", "Configuration" to "wrench", "Connect" to "plug", "Console" to "terminal", "Create" to "plus", "Css" to "css3", "Dates" to "calendar", "Debug" to "bug", "Delete" to "trash", "Demo" to "eye", "Details" to "info-circle", "Described" to "tag", "Diagram" to "project-diagram", "Download" to "download", "Factory" to "industry", "Featured" to "keyboard", "Featured Types" to "keyboard", "Edit" to "pencil", "Error Handling" to "bug", "Error" to "bug", "Event" to "bolt", "Example" to "book", "Experimental" to "flask", "Export" to "file-export", "Facet" to "gem", "Find" to "search", "Hidden" to "ban", "Hierarchy" to "sitemap", "History" to "history", "Hsql" to "database", "Import" to "file-import", "Causeway" to "ankh", "JEE/CDI" to "jedi", "List" to "list", "Location" to "map-marker", "Log" to "history", "Logout" to "user-times", "Manager" to "manager", "Map" to "map", "Me" to "user", "Message" to "envelope", "More" to "plus-circle", "Named" to "book", "Notification" to "bell", "Notifications" to "bell", "Object" to "cube", "Objects" to "cubes", "OK" to "check", "Open" to "book", "Other" to "asterisk", "Pin" to "map-pin", "Primitives" to "hashtag", "Properties" to "indent", "Prototyping" to "object-group", "Queen" to "chess-queen", "Replay" to "fast-forward", "Run" to "rocket", "Save" to "file", "Security" to "lock", "Simple" to "cubes", "Strings" to "font", "Switch" to "power-off", "Target" to "bullseye", "Tab" to "folder", "Terminal" to "terminal", "Test" to "check", "Text" to "font", "Times" to "clock", "Toast" to "bread-slice", //comment-alt-plus/minus/exclamation "Toolbar" to "step-backward", "Tooltips" to "comment-alt", "Temporal" to "clock", "Tenancy" to "lock", "Trees" to "tree", "Types" to "typewriter", "Undo" to "undo", "Unknown" to "question", "Visualize" to "eye", "Wikipedia" to "wikipedia-w", "World" to "plane", "Xml" to "code" ) @OptIn(ExperimentalStdlibApi::class) fun find(query: String): String { if (query.startsWith("fa")) return query val actionTitle = StringUtils.deCamel(query) val mixedCaseList = actionTitle.split(" ") for (w in mixedCaseList) { val hit = word2Icon[w] if (hit != null) { return PREFIX + hit } } return DEFAULT_ICON } fun findStyleFor(actionName: String): String { return when (actionName) { "delete" -> DANGER "undo" -> WARN "save" -> OK else -> NORMAL } } /* causeway.reflector.facet.cssClassFa.patterns new.*:fa-plus, add.*:fa-plus-square, create.*:fa-plus, update.*:fa-edit, delete.*:fa-trash, save.*:fa-floppy-o, change.*:fa-edit, edit.*:fa-pencil-square-o, maintain.*:fa-edit, remove.*:fa-minus-square, copy.*:fa-copy, move.*:fa-exchange, first.*:fa-star, find.*:fa-search, lookup.*:fa-search, search.*:fa-search, view.*:fa-search, clear.*:fa-remove, previous.*:fa-step-backward, next.*:fa-step-forward, list.*:fa-list, all.*:fa-list, download.*:fa-download, upload.*:fa-upload, export.*:fa-download, switch.*:fa-exchange, import.*:fa-upload, execute.*:fa-bolt, run.*:fa-bolt, calculate.*:fa-calculator, verify.*:fa-check-circle, refresh.*:fa-refresh, install.*:fa-wrench, stop.*:fa-stop, terminate.*:fa-stop, cancel.*:fa-stop, discard.*:fa-trash-o, pause.*:fa-pause, suspend.*:fa-pause, resume.*:fa-play, renew.*:fa-repeat, reset.*:fa-repeat, categorise.*:fa-folder-open-o, assign.*:fa-hand-o-right, approve.*:fa-thumbs-o-up, decline.*:fa-thumbs-o-down */ }
apache-2.0
2b7f9cb0ffcfe12559e030fad2b53991
28.316327
70
0.569962
3.426357
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/AbstractPropertyActionCreateCallableFromUsageFix.kt
2
1668
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.crossLanguage import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.PropertyInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable.CreateCallableFromUsageFixBase import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtElement abstract class AbstractPropertyActionCreateCallableFromUsageFix( targetContainer: KtElement, val classOrFileName: String? ) : CreateCallableFromUsageFixBase<KtElement>(targetContainer, false) { protected abstract val propertyInfo: PropertyInfo? override val callableInfo: PropertyInfo? get() = propertyInfo override val calculatedText: String get() { val propertyInfo = callableInfos.first() as PropertyInfo return buildString { append(KotlinBundle.message("text.add")) if (propertyInfo.isLateinitPreferred || propertyInfo.modifierList?.hasModifier(KtTokens.LATEINIT_KEYWORD) == true) { append("lateinit ") } else if (propertyInfo.isConst) { append("const ") } append(if (propertyInfo.writable) "var" else "val") append(KotlinBundle.message("property.0.to.1", propertyInfo.name, classOrFileName.toString())) } } override fun getFamilyName(): String = KotlinBundle.message("add.property") }
apache-2.0
0c5be0c2fc6f86ad628bf198ab61f4a5
45.361111
158
0.709233
5.069909
false
false
false
false
google/iosched
shared/src/test/java/com/google/samples/apps/iosched/test/util/FakePreferenceStorage.kt
1
4077
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.test.util import com.google.samples.apps.iosched.shared.data.prefs.PreferenceStorage import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow class FakePreferenceStorage( onboardingCompleted: Boolean = false, notificationsPreferenceShown: Boolean = false, preferToReceiveNotifications: Boolean = false, myLocationOptedIn: Boolean = false, preferConferenceTimeZone: Boolean = true, sendUsageStatistics: Boolean = false, selectedFilters: String = "", selectedTheme: String = "", codelabsInfoShown: Boolean = true, var snackbarIsStopped: Boolean = false, var scheduleUiHintsShown: Boolean = false, ) : PreferenceStorage { private val _onboardingCompleted = MutableStateFlow(onboardingCompleted) override val onboardingCompleted: Flow<Boolean> = _onboardingCompleted private val _notificationsPreferenceShown = MutableStateFlow(notificationsPreferenceShown) override val notificationsPreferenceShown = _notificationsPreferenceShown private val _preferToReceiveNotifications = MutableStateFlow(preferToReceiveNotifications) override val preferToReceiveNotifications = _preferToReceiveNotifications private val _myLocationOptedIn = MutableStateFlow(myLocationOptedIn) override val myLocationOptedIn = _myLocationOptedIn private val _sendUsageStatistics = MutableStateFlow(sendUsageStatistics) override val sendUsageStatistics = _sendUsageStatistics private val _preferConferenceTimeZone = MutableStateFlow(preferConferenceTimeZone) override val preferConferenceTimeZone = _preferConferenceTimeZone private val _selectedFilters = MutableStateFlow(selectedFilters) override val selectedFilters = _selectedFilters private val _selectedTheme = MutableStateFlow(selectedTheme) override val selectedTheme = _selectedTheme private val _codelabsInfoShown = MutableStateFlow(codelabsInfoShown) override val codelabsInfoShown = _codelabsInfoShown override suspend fun completeOnboarding(complete: Boolean) { _onboardingCompleted.value = complete } override suspend fun areScheduleUiHintsShown() = scheduleUiHintsShown override suspend fun showScheduleUiHints(show: Boolean) { scheduleUiHintsShown = show } override suspend fun showNotificationsPreference(show: Boolean) { _notificationsPreferenceShown.value = show } override suspend fun preferToReceiveNotifications(prefer: Boolean) { _preferToReceiveNotifications.value = prefer } override suspend fun optInMyLocation(optIn: Boolean) { _myLocationOptedIn.value = optIn } override suspend fun stopSnackbar(stop: Boolean) { snackbarIsStopped = stop } override suspend fun isSnackbarStopped(): Boolean { return snackbarIsStopped } override suspend fun sendUsageStatistics(send: Boolean) { _sendUsageStatistics.value = send } override suspend fun preferConferenceTimeZone(preferConferenceTimeZone: Boolean) { _preferConferenceTimeZone.value = preferConferenceTimeZone } override suspend fun selectFilters(filters: String) { _selectedFilters.value = filters } override suspend fun selectTheme(theme: String) { _selectedTheme.value = theme } override suspend fun showCodelabsInfo(show: Boolean) { _codelabsInfoShown.value = show } }
apache-2.0
c25cccfe07a460b35cbfda1c68f5cef3
34.763158
86
0.755703
5.09625
false
false
false
false
java-graphics/assimp
src/main/kotlin/assimp/format/collada/ColladaParser.kt
1
96196
package assimp.format.collada import assimp.* import glm_.* import glm_.func.rad import glm_.mat4x4.Mat4 import glm_.vec3.Vec3 import java.io.File import java.io.FileReader import java.net.URI import java.util.* import javax.xml.namespace.QName import javax.xml.stream.XMLEventReader import javax.xml.stream.XMLInputFactory import javax.xml.stream.events.Characters import javax.xml.stream.events.EndElement import javax.xml.stream.events.StartElement import javax.xml.stream.events.XMLEvent import kotlin.collections.set import assimp.format.collada.PrimitiveType as Pt /** * Created by elect on 23/01/2017. */ typealias DataLibrary = SortedMap<String, Data> typealias AccessorLibrary = SortedMap<String, Accessor> typealias MeshLibrary = SortedMap<String, Mesh> typealias NodeLibrary = SortedMap<String, Node> typealias ImageLibrary = SortedMap<String, Image> typealias EffectLibrary = SortedMap<String, Effect> typealias MaterialLibrary = SortedMap<String, Material> typealias LightLibrary = SortedMap<String, Light> typealias CameraLibrary = SortedMap<String, Camera> typealias ControllerLibrary = SortedMap<String, Controller> typealias AnimationLibrary = SortedMap<String, Animation> typealias AnimationClipLibrary = ArrayList<Pair<String, ArrayList<String>>> typealias ChannelMap = MutableMap<String, AnimationChannel> /** Parser helper class for the Collada loader. * * Does all the XML reading and builds data structures from it, * but leaves the resolving of all the references to the loader. */ class ColladaParser(pFile: IOStream) { /** Filename, for a verbose error message */ var mFileName = pFile /** XML reader, member for everyday use */ val reader: XMLEventReader lateinit var event: XMLEvent lateinit var element: StartElement lateinit var endElement: EndElement /** All data arrays found in the file by ID. Might be referred to by actually everyone. Collada, you are a steaming * pile of indirection. */ var mDataLibrary: DataLibrary = sortedMapOf() /** Same for accessors which define how the data in a data array is accessed. */ var mAccessorLibrary: AccessorLibrary = sortedMapOf() /** Mesh library: mesh by ID */ var mMeshLibrary: MeshLibrary = sortedMapOf() /** node library: root node of the hierarchy part by ID */ var mNodeLibrary: NodeLibrary = sortedMapOf() /** Image library: stores texture properties by ID */ var mImageLibrary: ImageLibrary = sortedMapOf() /** Effect library: surface attributes by ID */ var mEffectLibrary: EffectLibrary = sortedMapOf() /** Material library: surface material by ID */ var mMaterialLibrary: MaterialLibrary = sortedMapOf() /** Light library: surface light by ID */ var mLightLibrary: LightLibrary = sortedMapOf() /** Camera library: surface material by ID */ var mCameraLibrary: CameraLibrary = sortedMapOf() /** Controller library: joint controllers by ID */ var mControllerLibrary: ControllerLibrary = sortedMapOf() /** Animation library: animation references by ID */ var mAnimationLibrary: AnimationLibrary = sortedMapOf() /** Animation clip library: clip animation references by ID */ var mAnimationClipLibrary: AnimationClipLibrary = ArrayList() /** Pointer to the root node. Don't delete, it just points to one of the nodes in the node library. */ var mRootNode: Node? = null /** Root animation container */ var mAnims = Animation() /** Size unit: how large compared to a meter */ var mUnitSize = 1f var mUpDirection = UpDirection.Y /** Which is the up vector */ enum class UpDirection { X, Y, Z } /** Collada file format version. We assume the newest file format by default */ var mFormat = FormatVersion._1_5_n init { //val file = File(pFile) // open the file //if (!file.exists()) throw Exception("Failed to open file: $pFile") // val dbFactory = DocumentBuilderFactory.newInstance() // val dBuilder = dbFactory.newDocumentBuilder() // val doc = dBuilder.parse(file) // doc.getDocumentElement().normalize() // // val traversal = doc as DocumentTraversal // // val walker = traversal.createTreeWalker( // doc.getDocumentElement(), // NodeFilter.SHOW_ELEMENT, null, true) // // var n = walker.nextNode() // while(n!=null) { // println(n.nodeName) // n = n.nextSibling // } // generate a XML reader for it val factory = XMLInputFactory.newInstance() reader = factory.createXMLEventReader(pFile.reader()) // start reading readContents() } /** Read bool from text contents of current element */ fun readBoolFromTextContent() = with(getTextContent().trimStart()) { startsWith("true") || get(0) == '1' } /** Read float from text contents of current element */ fun readFloatFromTextContent() = getTextContent().trimStart().split("\\s+".toRegex())[0].f /** Reads the contents of the file */ fun readContents() { while (reader.read()) // if(event.isAttribute) println("attribute") // if(event.isCharacters) println("characters ${event.asCharacters()}") // if(event.isEndDocument) println("endDocument") // if(event.isEndElement) println("endElement: ${event.asEndElement().name.localPart}") // if(event.isEntityReference) println("entityReference") // if(event.isNamespace) println("namespace") // if(event.isProcessingInstruction) println("processingInstruction") // if(event.isStartDocument) println("startDocument") // if(event.isStartElement) println("startElement: ${event.asStartElement().name.localPart}") // handle the root element "COLLADA" if (event is StartElement) if (element.name_ == "COLLADA") { element["version"]?.let { when { // check for 'version' attribute it.startsWith("1.5") -> { mFormat = FormatVersion._1_5_n logger.debug { "Collada schema version is 1.5.n" } } it.startsWith("1.4") -> { mFormat = FormatVersion._1_4_n logger.debug { "Collada schema version is 1.4.n" } } it.startsWith("1.3") -> { mFormat = FormatVersion._1_3_n logger.debug { "Collada schema version is 1.3.n" } } } } readStructure() } else { logger.debug { "Ignoring global element ${element.name_}>." } skipElement() } else Unit // skip everything else silently } /** Reads the structure of the file */ fun readStructure() { while (reader.read()) if (event is StartElement) // beginning of elements when (element.name_) { "asset" -> readAssetInfo() "library_animations" -> readAnimationLibrary() "library_animation_clips" -> readAnimationClipLibrary() "library_controllers" -> readControllerLibrary() "library_images" -> readImageLibrary() "library_materials" -> readMaterialLibrary() "library_effects" -> readEffectLibrary() "library_geometries" -> readGeometryLibrary() "library_visual_scenes" -> readSceneLibrary() "library_lights" -> readLightLibrary() "library_cameras" -> readCameraLibrary() "library_nodes" -> readSceneNode(null) // some hacking to reuse this piece of code "scene" -> readScene() else -> skipElement() } else if (event is EndElement) break postProcessRootAnimations() } /** Reads asset informations such as coordinate system informations and legal blah */ fun readAssetInfo() { if (isEmptyElement()) return while (reader.read()) when (event) { is StartElement -> when (element.name_) { "unit" -> { mUnitSize = (element["meter"] ?: "1").f // read unit data from the element's attributes consume() // consume the trailing stuff } "up_axis" -> { mUpDirection = when (getTextContent()) { // read content, strip whitespace, compare "X_UP" -> UpDirection.X "Y_UP" -> UpDirection.Y else -> UpDirection.Z } testClosing("up_axis") // check element end } else -> skipElement() } is EndElement -> { if (endElement.name_ != "asset") throw Exception("Expected end of <asset> element.") return } } } /** Reads the animation clips */ fun readAnimationClipLibrary() { if (isEmptyElement()) return while (reader.read()) if (event is StartElement) if (element.name_ == "animation_clip") { // optional name given as an attribute val animName = element["name"] ?: element["id"] ?: "animation_${mAnimationClipLibrary.size}" val clip = Pair(animName, ArrayList<String>()) while (reader.read()) if (event is StartElement) if (element.name_ == "instance_animation") element["url"]?.let { url -> if (url[0] != '#') throw Exception("Unknown reference format") clip.second.add(url.removePrefix("#")) } else skipElement() // ignore the rest else if (event is EndElement) { if (endElement.name_ != "animation_clip") throw Exception("Expected end of <animation_clip> element.") break } if (clip.second.isNotEmpty()) mAnimationClipLibrary.add(clip) } else skipElement() // ignore the rest else if (event is EndElement) { if (endElement.name_ != "library_animation_clips") throw Exception("Expected end of <library_animation_clips> element.") break } } /** Re-build animations from animation clip library, if present, otherwise combine single-channel animations */ fun postProcessRootAnimations() { if (mAnimationClipLibrary.isNotEmpty()) { val temp = Animation() mAnimationClipLibrary.forEach { val clip = Animation(mName = it.first) temp.mSubAnims.add(clip) it.second.forEach { animationID -> mAnimationLibrary[animationID]?.collectChannelsRecursively(clip.mChannels) } } mAnims = temp } else mAnims.combineSingleChannelAnimations() } /** Reads the animation library */ fun readAnimationLibrary() { if (isEmptyElement()) return while (reader.read()) if (event is StartElement) if (element.name_ == "animation") // delegate the reading. Depending on the inner elements it will be a container or a anim channel readAnimation(mAnims) else skipElement() // ignore the rest else if (event is EndElement) { if (endElement.name_ != "library_animations") throw Exception("Expected end of <library_animations> element.") break } } /** Reads an animation into the given parent structure */ fun readAnimation(pParent: Animation?) { /* an <animation> element may be a container for grouping sub-elements or an animation channel this is the channel collection by ID, in case it has channels */ val channels: ChannelMap = mutableMapOf() var anim: Animation? = null // this is the anim container in case we're a container val animName = element["name"] ?: element["id"] ?: "animation" // optional name given as an attribute val animID = element["id"] while (reader.read()) if (event is StartElement) when (element.name_) { "animation" -> { // we have subanimations if (anim == null) { // create container from our element anim = Animation(mName = animName) pParent!!.mSubAnims.add(anim) } readAnimation(anim) // recurse into the subelement } "source" -> readSource() // possible animation data - we'll never know. Better store it "sampler" -> { // read the ID to assign the corresponding collada channel afterwards. val id = element["id"]!! channels[id] = AnimationChannel().also { readAnimationSampler(it) // have it read into a channel } } "channel" -> { /* the binding element whose whole purpose is to provide the target to animate Thanks, Collada! A directly posted information would have been too simple, I guess. Better add another indirection to that! Can't have enough of those. */ var sourceId = element["source"]!! if (sourceId[0] == '#') sourceId = sourceId.removePrefix("#") channels[sourceId]?.let { cit -> cit.mTarget = element["target"]!! } consume() } else -> skipElement() // ignore the rest } else if (event is EndElement) { if (endElement.name_ != "animation") throw Exception("Expected end of <animation> element.") break } if (channels.isNotEmpty()) { // it turned out to have channels - add them /* FIXME: Is this essentially doing the same as "single-anim-node" codepath in ColladaLoader::StoreAnimations? For now, this has been deferred to after all animations and all clips have been read. Due to handling of <library_animation_clips> this cannot be done here, as the channel owner is lost, and some exporters make up animations by referring to multiple single-channel animations from an <instance_animation>. */ /* // special filtering for stupid exporters packing each channel into a separate animation if( channels.size() == 1) pParent->channels.pushBack( channels.begin()->second); else { */ if (anim == null) { // else create the animation, if not done yet, and store the channels anim = Animation(mName = animName) pParent!!.mSubAnims.add(anim) } anim.mChannels.addAll(channels.values) animID?.let { mAnimationLibrary[animID] = anim } // } } } /** Reads an animation sampler into the given anim channel */ fun readAnimationSampler(pChannel: AnimationChannel) { while (reader.read()) if (event is StartElement) if (element.name_ == "input") { val semantic = element["semantic"]!! var source = element["source"]!! if (source[0] != '#') throw Exception("Unsupported URL format") source = source.removePrefix("#") when (semantic) { "INPUT" -> pChannel.mSourceTimes = source "OUTPUT" -> pChannel.mSourceValues = source "IN_TANGENT" -> pChannel.mInTanValues = source "OUT_TANGENT" -> pChannel.mOutTanValues = source "INTERPOLATION" -> pChannel.mInterpolationValues = source } consume() } else skipElement() // ignore the rest else if (event is EndElement) { if (endElement.name_ != "sampler") throw Exception("Expected end of <sampler> element.") break } } /** Reads the skeleton controller library */ fun readControllerLibrary() { if (isEmptyElement()) return while ((reader.read())) if (event is StartElement) if (element.name_ == "controller") { // read ID. Ask the spec if it's necessary or optional... you might be surprised. val id = element["id"]!! mControllerLibrary[id] = Controller() // create an entry and store it in the library under its ID readController(mControllerLibrary[id]!!) // read on from there } else skipElement() // ignore the rest else if (event is EndElement) { if (endElement.name_ != "library_controllers") throw Exception("Expected end of <library_controllers> element.") break } } /** Reads a controller into the given mesh structure */ fun readController(pController: Controller) { // initial values pController.mType = ControllerType.Skin pController.mMethod = MorphMethod.Normalized while (reader.read()) if (event is StartElement) when (element.name_) { // two types of controllers: "skin" and "morph". Only the first one is relevant, we skip the other "morph" -> { pController.mType = ControllerType.Morph pController.mMeshId = element["source"]!!.substring(1) element["method"]?.let { if (it == "RELATIVE") pController.mMethod = MorphMethod.Relative } } /* read the mesh it refers to. According to the spec this could also be another controller, but I refuse to implement every single idea they've come up with */ "skin" -> pController.mMeshId = element["source"]!!.substring(1) "bind_shape_matrix" -> { // content is 16 floats to define a matrix... it seems to be important for some models val content = getTextContent() // read the 16 floats pController.mBindShapeMatrix = content.words.map { it.f }.toFloatArray() testClosing("bind_shape_matrix") } "source" -> readSource() // data array - we have specialists to handle this "joints" -> readControllerJoints(pController) "vertex_weights" -> readControllerWeights(pController) "targets" -> { while (reader.read()) if (event is StartElement) { if (element.name_ == "input") { val semantics = element["semantic"]!! val source = element["source"]!! if (semantics == "MORPH_TARGET") pController.mMorphTarget = source.substring(1) else if (semantics == "MORPH_WEIGHT") pController.mMorphWeight = source.substring(1) } } else if (event is EndElement) if (endElement.name_ == "targets") break else throw Exception("Expected end of <targets> element.") } else -> skipElement() // ignore the rest } else if (event is EndElement) { if (endElement.name_ == "controller") break else if (endElement.name_ != "skin" && endElement.name_ != "morph") throw Exception("Expected end of <controller> element.") } } /** Reads the joint definitions for the given controller */ fun readControllerJoints(pController: Controller) { while (reader.read()) if (event is StartElement) // Input channels for joint data. Two possible semantics: "JOINT" and "INV_BIND_MATRIX" if (element.name_ == "input") { val semantic = element["semantic"]!! var source = element["source"]!! // local URLS always start with a '#'. We don't support global URLs if (source[0] != '#') throw Exception("Unsupported URL format in $source in source attribute of <joints> data <input> element") source = source.removePrefix("#") when (semantic) { // parse source URL to corresponding source "JOINT" -> pController.mJointNameSource = source "INV_BIND_MATRIX" -> pController.mJointOffsetMatrixSource = source else -> throw Exception("Unknown semantic $semantic in <joints> data <input> element") } consume() // skip inner data, if present } else skipElement() // ignore the rest else if (event is EndElement) { if (endElement.name_ != "joints") throw Exception("Expected end of <joints> element.") break } } /** Reads the joint weights for the given controller */ fun readControllerWeights(controller: Controller) { val vertexCount = element["count"]!!.i // read vertex count from attributes and resize the array accordingly controller.weightCounts = LongArray(vertexCount) while (reader.read()) if (event is StartElement) when (element.name_) { // Input channels for weight data. Two possible semantics: "JOINT" and "WEIGHT" "input" -> if (vertexCount > 0) { val channel = InputChannel() val semantic = element["semantic"]!! val source = element["source"]!! element["offset"]?.let { channel.mOffset = it.i } // local URLS always start with a '#'. We don't support global URLs if (source[0] != '#') throw Exception("Unsupported URL format in $source in source attribute of <vertex_weights> data <input> element") channel.mAccessor = source.removePrefix("#") // parse source URL to corresponding source when (semantic) { "JOINT" -> controller.mWeightInputJoints = channel "WEIGHT" -> controller.mWeightInputWeights = channel else -> throw Exception("Unknown semantic $semantic in <vertex_weights> data <input> element") } consume() // skip inner data, if present } "vcount" -> if (vertexCount > 0) { val ints = getTextContent().words.map { it.i } // read weight count per vertex var numWeights = 0 for (i in 0 until controller.weightCounts.size) { if (i == ints.size) throw Exception("Out of data while reading <vcount>") val int = ints[i] controller.weightCounts[i] = int.toLong() numWeights += int } testClosing("vcount") controller.weights = Array(numWeights, { Pair(0L, 0L) }).toCollection(ArrayList()) // reserve weight count } "v" -> if (vertexCount > 0) { val ints = getTextContent().words.map { it.i } // read JointIndex - WeightIndex pairs var p = 0 controller.weights.replaceAll { Pair(ints[p++].L, ints[p++].L) } testClosing("v") } else -> skipElement() // ignore the rest } else if (event is EndElement) { if (endElement.name_ != "vertex_weights") throw Exception("Expected end of <vertex_weights> element.") break } } /** Reads the image library contents */ fun readImageLibrary() { if (isEmptyElement()) return while (reader.read()) if (event is StartElement) if (element.name_ == "image") { // read ID. Another entry which is "optional" by design but obligatory in reality val id = element["id"]!! mImageLibrary[id] = Image() // create an entry and store it in the library under its ID readImage(mImageLibrary[id]!!) // read on from there } else skipElement() // ignore the rest else if (event is EndElement) { if (endElement.name_ != "library_images") throw Exception("Expected end of <library_images> element.") break } } /** Reads an image entry into the given image */ fun readImage(pImage: Image) { while (reader.read()) if (event is StartElement) // Need to run different code paths here, depending on the Collada XSD version if (element.name_ == "image") skipElement() else if (element.name_ == "init_from") { if (mFormat == FormatVersion._1_4_n) { if (!isEmptyElement()) { // FIX: C4D exporter writes empty <init_from/> tags // element content is filename - hopefully testTextContent()?.let { pImage.mFileName = it } testClosing("init_from") } if (pImage.mFileName.isEmpty()) pImage.mFileName = "unknown_texture" } else if (mFormat == FormatVersion._1_5_n) { /* make sure we skip over mip and array initializations, which we don't support, but which could confuse the loader if they're not skipped. But in Kotlin we don't need ^^ TODO check */ element["array_index"]?.let { if (it.i > 0) { logger.warn { "Collada: Ignoring texture array index" } // continue } } element["mip_index"]?.let { if (it.i > 0) { logger.warn { "Collada: Ignoring MIP map layer" } // continue } } // TODO: correctly jump over cube and volume maps? } } else if (mFormat == FormatVersion._1_5_n) { if (element.name_ == "ref") { testTextContent()?.let { pImage.mFileName = it } // element content is filename - hopefully testClosing("ref") } else if (element.name_ == "hex" && pImage.mFileName.isNotEmpty()) { val format = element["format"] // embedded image. get format if (format == null) System.err.println("Collada: Unknown image file format") else pImage.mEmbeddedFormat = format val data = getTextContent() // hexadecimal-encoded binary octets. First of all, find the required buffer size to reserve enough storage. pImage.mImageData = hexStringToByteArray(data) testClosing("hex") } } else skipElement() // ignore the rest else if (event is EndElement && endElement.name_ == "image") break } /** Reads the material library */ fun readMaterialLibrary() { if (isEmptyElement()) return val names = mutableMapOf<String, Int>() while (reader.read()) if (event is StartElement) if (element.name_ == "material") { // read ID. By now you probably know my opinion about this "specification" val id = element["id"]!! var name = element["name"] ?: "" mMaterialLibrary[id] = Material() // create an entry and store it in the library under its ID if (name.isNotEmpty()) { if (names.contains(name)) { val nextId = names.keys.sorted().indexOf(name) + 1 val nextName = names.keys.sorted()[nextId] name += " " + names[nextName] } else names[name] = 0 mMaterialLibrary[id]!!.mName = name } readMaterial(mMaterialLibrary[id]!!) } else skipElement() // ignore the rest else if (event is EndElement) { if (endElement.name_ != "library_materials") throw Exception("Expected end of <library_materials> element.") break } } /** Reads the light library */ fun readLightLibrary() { if (isEmptyElement()) return while (reader.read()) { if (event is StartElement) { if (element.name_ == "light") { // read ID. By now you probably know my opinion about this "specification" val id = element["id"]!! val light = Light() // create an entry and store it in the library under its ID mLightLibrary[id] = Light() readLight(light) } else skipElement() // ignore the rest } else if (event is EndElement) { if (endElement.name_ != "library_lights") throw Exception("Expected end of <library_lights> element.") break } } } /** Reads the camera library */ fun readCameraLibrary() { if (isEmptyElement()) return while (reader.read()) if (event is StartElement) if (element.name_ == "camera") { // read ID. By now you probably know my opinion about this "specification" val id = element["id"]!! // create an entry and store it in the library under its ID val cam = Camera() mCameraLibrary[id] = cam element["name"]?.let { cam.mName = it } readCamera(cam) } else skipElement() // ignore the rest else if (event is EndElement) { if (endElement.name_ != "library_cameras") throw Exception("Expected end of <library_cameras> element.") break } } /** Reads a material entry into the given material */ fun readMaterial(pMaterial: Material) { while (reader.read()) if (event is StartElement) when (element.name_) { "material" -> skipElement() "instance_effect" -> { // referred effect by URL with(element["url"]!!) { if (get(0) != '#') throw Exception("Unknown reference format") pMaterial.mEffect = substring(1) } skipElement() } else -> skipElement() // ignore the rest } else if (event is EndElement) { if (endElement.name_ != "material") throw Exception("Expected end of <material> element.") break } } /** Reads a light entry into the given light */ fun readLight(pLight: Light) { while (reader.read()) if (event is StartElement) { when (element.name_) { "light" -> skipElement() "spot" -> pLight.mType = AiLightSourceType.SPOT "ambient" -> pLight.mType = AiLightSourceType.AMBIENT "directional" -> pLight.mType = AiLightSourceType.DIRECTIONAL "point" -> pLight.mType = AiLightSourceType.POINT "color" -> { val floats = getTextContent().words.map { it.f } // text content contains 3 floats pLight.mColor = AiColor3D(floats) testClosing("color") } "constant_attenuation" -> { pLight.mAttConstant = readFloatFromTextContent() testClosing("constant_attenuation") } "linear_attenuation" -> { pLight.mAttLinear = readFloatFromTextContent() testClosing("linear_attenuation") } "quadratic_attenuation" -> { pLight.mAttQuadratic = readFloatFromTextContent() testClosing("quadratic_attenuation") } "falloff_angle" -> { pLight.mFalloffAngle = readFloatFromTextContent() testClosing("falloff_angle") } "falloff_exponent" -> { pLight.mFalloffExponent = readFloatFromTextContent() testClosing("falloff_exponent") } // FCOLLADA extensions // ------------------------------------------------------- "outer_cone" -> { pLight.mOuterAngle = readFloatFromTextContent() testClosing("outer_cone") } // ... and this one is even deprecated "penumbra_angle" -> { pLight.mPenumbraAngle = readFloatFromTextContent() testClosing("penumbra_angle") } "intensity" -> { pLight.mIntensity = readFloatFromTextContent() testClosing("intensity") } "falloff" -> { pLight.mOuterAngle = readFloatFromTextContent() testClosing("falloff") } "hotspot_beam" -> { pLight.mFalloffAngle = readFloatFromTextContent() testClosing("hotspot_beam") } // OpenCOLLADA extensions // ------------------------------------------------------- "decay_falloff" -> { pLight.mOuterAngle = readFloatFromTextContent() testClosing("decay_falloff") } } } else if (event is EndElement && endElement.name_ == "light") break } /** Reads a camera entry into the given light */ fun readCamera(pCamera: Camera) { while (reader.read()) if (event is StartElement) when (element.name_) { "camera" -> skipElement() "orthographic" -> pCamera.mOrtho = true "xfov", "xmag" -> { pCamera.mHorFov = readFloatFromTextContent() testClosing(if (pCamera.mOrtho) "xmag" else "xfov") } "yfov", "ymag" -> { pCamera.mVerFov = readFloatFromTextContent() testClosing(if (pCamera.mOrtho) "ymag" else "yfov") } "aspect_ratio" -> { pCamera.mAspect = readFloatFromTextContent() testClosing("aspect_ratio") } "znear" -> { pCamera.mZNear = readFloatFromTextContent() testClosing("znear") } "zfar" -> { pCamera.mZFar = readFloatFromTextContent() testClosing("zfar") } } else if (event is EndElement && endElement.name_ == "camera") break } /** Reads the effect library */ fun readEffectLibrary() { if (isEmptyElement()) return while (reader.read()) if (event is StartElement) if (element.name_ == "effect") { // read ID. Do I have to repeat my ranting about "optional" attributes? val id = element["id"]!! mEffectLibrary[id] = Effect() // create an entry and store it in the library under its ID readEffect(mEffectLibrary[id]!!) // read on from there } else skipElement() // ignore the rest else if (event is EndElement) { if (endElement.name_ != "library_effects") throw Exception("Expected end of <library_effects> element.") break } } /** Reads an effect entry into the given effect */ fun readEffect(pEffect: Effect) { while (reader.read()) // for the moment we don't support any other type of effect. if (event is StartElement) if (element.name_ == "profile_COMMON") readEffectProfileCommon(pEffect) else skipElement() else if (event is EndElement) { if (endElement.name_ != "effect") throw Exception("Expected end of <effect> element.") break } } /** Reads an COMMON effect profile */ fun readEffectProfileCommon(pEffect: Effect) { while (reader.read()) if (event is StartElement) when (element.name_) { "newparam" -> { val sid = element["sid"]!! // save ID pEffect.mParams[sid] = EffectParam() readEffectParam(pEffect.mParams[sid]!!) } "technique", "extra" -> Unit // just syntactic sugar "image" -> if (mFormat == FormatVersion._1_4_n) { // read ID. Another entry which is "optional" by design but obligatory in reality val id = element["id"]!! mImageLibrary[id] = Image() // create an entry and store it in the library under its ID readImage(mImageLibrary[id]!!) // read on from there } /* Shading modes */ "phong" -> pEffect.mShadeType = ShadeType.Phong "constant" -> pEffect.mShadeType = ShadeType.Constant "lambert" -> pEffect.mShadeType = ShadeType.Lambert "blinn" -> pEffect.mShadeType = ShadeType.Blinn /* Color + texture properties */ "emission" -> readEffectColor(pEffect.mEmissive, pEffect.mTexEmissive) "ambient" -> readEffectColor(pEffect.mAmbient, pEffect.mTexAmbient) "diffuse" -> readEffectColor(pEffect.mDiffuse, pEffect.mTexDiffuse) "specular" -> readEffectColor(pEffect.mSpecular, pEffect.mTexSpecular) "reflective" -> readEffectColor(pEffect.mReflective, pEffect.mTexReflective) "transparent" -> { pEffect.mHasTransparency = true val opaque = element["opaque"] ?: "" if (opaque == "RGB_ZERO" || opaque == "RGB_ONE") pEffect.mRGBTransparency = true // In RGB_ZERO mode, the transparency is interpreted in reverse, go figure... if (opaque == "RGB_ZERO" || opaque == "A_ZERO") pEffect.mInvertTransparency = true readEffectColor(pEffect.mTransparent, pEffect.mTexTransparent) } "shininess" -> pEffect.mShininess = readEffectFloat(pEffect.mShininess) "reflectivity" -> pEffect.mReflectivity = readEffectFloat(pEffect.mReflectivity) /* Single scalar properties */ "transparency" -> pEffect.mTransparency = readEffectFloat(pEffect.mTransparency) "index_of_refraction" -> pEffect.mRefractIndex = readEffectFloat(pEffect.mRefractIndex) // GOOGLEEARTH/OKINO extensions // ------------------------------------------------------- "double_sided" -> pEffect.mDoubleSided = readBoolFromTextContent() // FCOLLADA extensions // ------------------------------------------------------- "bump" -> readEffectColor(AiColor4D(), pEffect.mTexBump) // MAX3D extensions // ------------------------------------------------------- "wireframe" -> { pEffect.mWireframe = readBoolFromTextContent() testClosing("wireframe") } "faceted" -> { pEffect.mFaceted = readBoolFromTextContent() testClosing("faceted") } else -> skipElement() // ignore the rest } else if (event is EndElement && endElement.name_ == "profile_COMMON") break } /** Read texture wrapping + UV transform settings from a profile==Maya chunk */ fun readSamplerProperties(oSampler: Sampler) { if (isEmptyElement()) return while (reader.read()) if (event is StartElement) when (element.name_) { // MAYA extensions // ------------------------------------------------------- "wrapU" -> { oSampler.mWrapU = readBoolFromTextContent() testClosing("wrapU") } "wrapV" -> { oSampler.mWrapV = readBoolFromTextContent() testClosing("wrapV") } "mirrorU" -> { oSampler.mMirrorU = readBoolFromTextContent() testClosing("mirrorU") } "mirrorV" -> { oSampler.mMirrorV = readBoolFromTextContent() testClosing("mirrorV") } "repeatU" -> { oSampler.mTransform.scaling.x = readFloatFromTextContent() testClosing("repeatU") } "repeatV" -> { oSampler.mTransform.scaling.y = readFloatFromTextContent() testClosing("repeatV") } "offsetU" -> { oSampler.mTransform.translation.x = readFloatFromTextContent() testClosing("offsetU") } "offsetV" -> { oSampler.mTransform.translation.y = readFloatFromTextContent() testClosing("offsetV") } "rotateUV" -> { oSampler.mTransform.rotation = readFloatFromTextContent() testClosing("rotateUV") } "blend_mode" -> { /* http://www.feelingsoftware.com/content/view/55/72/lang,en/ NONE, OVER, IN, OUT, ADD, SUBTRACT, MULTIPLY, DIFFERENCE, LIGHTEN, DARKEN, SATURATE, DESATURATE and ILLUMINATE */ when (getTextContent().words[0]) { "ADD" -> oSampler.mOp = AiTexture.Op.add "SUBTRACT" -> oSampler.mOp = AiTexture.Op.subtract "MULTIPLY" -> oSampler.mOp = AiTexture.Op.multiply else -> System.out.println("Collada: Unsupported MAYA texture blend mode") } testClosing("blend_mode") } // OKINO extensions // ------------------------------------------------------- "weighting" -> { oSampler.mWeighting = readFloatFromTextContent() testClosing("weighting") } "mix_with_previous_layer" -> { oSampler.mMixWithPrevious = readFloatFromTextContent() testClosing("mix_with_previous_layer") } // MAX3D extensions // ------------------------------------------------------- "amount" -> { oSampler.mWeighting = readFloatFromTextContent() testClosing("amount") } } else if (event is EndElement && endElement.name_ == "technique") break } /** Reads an effect entry containing a color or a texture defining that color */ fun readEffectColor(pColor: AiColor4D, pSampler: Sampler) { if (isEmptyElement()) return val curElem = element.name_ // Save current element name while (reader.read()) if (event is StartElement) when (element.name_) { "color" -> { val floats = getTextContent().words.map { it.f } // text content contains 4 floats pColor put floats testClosing("color") } "texture" -> { pSampler.mName = element["texture"]!! // get name of source texture/sampler /* get name of UV source channel. Specification demands it to be there, but some exporters don't write it. It will be the default UV channel in case it's missing. */ element["texcoord"]?.let { pSampler.mUVChannel = it } //SkipElement(); // as we've read texture, the color needs to be 1,1,1,1 pColor put 1f } "technique" -> { val profile = element["profile"] /* Some extensions are quite useful ... ReadSamplerProperties processes several extensions in MAYA, OKINO and MAX3D profiles. */ if (profile == "MAYA" || profile == "MAX3D" || profile == "OKINO") readSamplerProperties(pSampler) // get more information on this sampler else skipElement() } "extra" -> skipElement() // ignore the rest } else if (event is EndElement && endElement.name_ == curElem) break } /** Reads an effect entry containing a float */ fun readEffectFloat(pFloat: Float): Float { var result = pFloat while (reader.read()) if (event is StartElement) if (element.name_ == "float") { result = getTextContent().words[0].f // text content contains a single floats testClosing("float") } else skipElement() else if (event is EndElement) break return result } /** Reads an effect parameter specification of any kind */ fun readEffectParam(pParam: EffectParam) { while (reader.read()) if (event is StartElement) when (element.name_) { "surface" -> { testOpening("init_from") // image ID given inside <init_from> tags val content = getTextContent() pParam.mType = ParamType.Surface pParam.mReference = content testClosing("init_from") skipElement("surface") // don't care for remaining stuff } "sampler2D" -> when (mFormat) { FormatVersion._1_4_n, FormatVersion._1_3_n -> { testOpening("source") // surface ID is given inside <source> tags val content = getTextContent() pParam.mType = ParamType.Sampler pParam.mReference = content testClosing("source") skipElement("sampler2D") // don't care for remaining stuff } else -> { testOpening("instance_image") // surface ID is given inside <instance_image> tags val url = element["url"]!! if (url[0] != '#') throw Exception("Unsupported URL format in instance_image") url.substring(1) pParam.mType = ParamType.Sampler pParam.mReference = url skipElement("sampler2D") } } else -> skipElement() // ignore unknown element } else if (event is EndElement) break } /** Reads the geometry library contents */ fun readGeometryLibrary() { if (isEmptyElement()) return while (reader.read()) if (event is StartElement) if (element.name_ == "geometry") { // read ID. Another entry which is "optional" by design but obligatory in reality val id = element["id"]!! // TODO: (thom) support SIDs // ai_assert( TestAttribute( "sid") == -1); val mesh = Mesh() // create a mesh and store it in the library under its ID mMeshLibrary[id] = mesh element["name"]?.let { mesh.mName = it } // read the mesh name if it exists readGeometry(mesh) // read on from there } else skipElement() // ignore the rest else if (event is EndElement) { if (endElement.name_ != "library_geometries") throw Exception("Expected end of <library_geometries> element.") break } } /** Reads a geometry from the geometry library. */ fun readGeometry(pMesh: Mesh) { if (isEmptyElement()) return while (reader.read()) if (event is StartElement) if (element.name_ == "mesh") readMesh(pMesh) // read on from there else skipElement() // ignore the rest else if (event is EndElement) { if (endElement.name_ != "geometry") throw Exception("Expected end of <geometry> element.") break } } /** Reads a mesh from the geometry library */ fun readMesh(pMesh: Mesh) { if (isEmptyElement()) return w@ while (reader.read()) if (event is StartElement) when (element.name_) { "source" -> readSource() // we have professionals dealing with this "vertices" -> readVertexData(pMesh) // read per-vertex mesh data "triangles", "lines", "linestrips", "polygons", "polylist", "trifans", "tristrips" -> readIndexData(pMesh) // read per-index mesh data and faces setup else -> skipElement() // ignore the rest } else if (event is EndElement) when (endElement.name_) { "technique_common" -> Unit // end of another meaningless element - read over it "mesh" -> break@w else -> throw Exception("Expected end of <mesh> element.") } } /** Reads a source element */ fun readSource() { val sourceID = element["id"]!! w@ while (reader.read()) if (event is StartElement) when (element.name_) { "float_array", "IDREF_array", "Name_array" -> readDataArray() "technique_common" -> Unit // I don't care for your profiles "accessor" -> readAccessor(sourceID) else -> skipElement() // ignore the rest } else if (event is EndElement) when (endElement.name_) { "source" -> break@w // end of <source> - we're done "technique_common" -> Unit // end of another meaningless element - read over it // everything else should be punished else -> throw Exception("Expected end of <source> element.") } } /** Reads a data array holding a number of floats, and stores it in the global library */ fun readDataArray() { val elmName = element.name_ val isStringArray = elmName == "IDREF_array" || elmName == "Name_array" val isEmptyElement = isEmptyElement() // read attributes val id = element["id"]!! val count = element["count"]!!.i // read values and store inside an array in the data library mDataLibrary[id] = Data(mIsStringArray = isStringArray) val data = mDataLibrary[id]!! // some exporters write empty data arrays, but we need to conserve them anyways because others might reference them testTextContent()?.let { content -> if (isStringArray) { val strings = content.words if (strings.size < count) throw Exception("Expected more values while reading IDREF_array contents.") data.mStrings.addAll(strings) } else { val ints = content.words.map { it.f } if (ints.size < count) throw Exception("Expected more values while reading float_array contents.") data.values.addAll(ints) } } // test for closing tag if (!isEmptyElement) testClosing(elmName) } /** Reads an accessor and stores it in the global library */ fun readAccessor(pID: String) { // read accessor attributes val source = element["source"]!! if (source[0] != '#') throw Exception("Unknown reference format in url $source in source attribute of <accessor> element.") // store in the library under the given ID mAccessorLibrary[pID] = Accessor().apply { count = element["count"]!!.L offset = element["offset"]?.i ?: 0 stride = element["stride"]?.L ?: 1L this.source = source.removePrefix("#") } // ignore the leading '#' val acc = mAccessorLibrary[pID]!! while (reader.read()) // and read the components if (event is StartElement) if (element.name_ == "param") { // read data param val name = element["name"] ?: "" if (name.isNotEmpty()) // analyse for common type components and store it's sub-offset in the corresponding field when (name) { /* Cartesian coordinates */ "X" -> acc.mSubOffset[0] = acc.mParams.size.L "Y" -> acc.mSubOffset[1] = acc.mParams.size.L "Z" -> acc.mSubOffset[2] = acc.mParams.size.L /* RGBA colors */ "R" -> acc.mSubOffset[0] = acc.mParams.size.L "G" -> acc.mSubOffset[1] = acc.mParams.size.L "B" -> acc.mSubOffset[2] = acc.mParams.size.L "A" -> acc.mSubOffset[3] = acc.mParams.size.L /* UVWQ (STPQ) texture coordinates */ "S" -> acc.mSubOffset[0] = acc.mParams.size.L "T" -> acc.mSubOffset[1] = acc.mParams.size.L "P" -> acc.mSubOffset[2] = acc.mParams.size.L // else if( name == "Q") acc.mSubOffset[3] = acc.mParams.size(); /* 4D uv coordinates are not supported in Assimp */ /* Generic extra data, interpreted as UV data, too*/ "U" -> acc.mSubOffset[0] = acc.mParams.size.L "V" -> acc.mSubOffset[1] = acc.mParams.size.L //else // DefaultLogger::get()->warn( format() << "Unknown accessor parameter \"" << name << "\". Ignoring data channel." ); } // read data type element["type"]?.let { /* for the moment we only distinguish between a 4x4 matrix and anything else. TODO: (thom) I don't have a spec here at work. Check if there are other multi-value types which should be tested for here. */ acc.size += if (it == "float4x4") 16 else 1 } acc.mParams.add(name) skipElement() // skip remaining stuff of this element, if any } else throw Exception("Unexpected sub element <${element.name_}> in tag <accessor>") else if (event is EndElement) { if (endElement.name_ != "accessor") throw Exception("Expected end of <accessor> element.") break } } /** Reads input declarations of per-vertex mesh data into the given mesh */ fun readVertexData(pMesh: Mesh) { /* extract the ID of the <vertices> element. Not that we care, but to catch strange referencing schemes we should warn about */ pMesh.mVertexID = element["id"]!! while (reader.read()) // a number of <input> elements if (event is StartElement) if (element.name_ == "input") readInputChannel(pMesh.mPerVertexData) else throw Exception("Unexpected sub element <${element.name_}> in tag <vertices>") else if (event is EndElement) { if (endElement.name_ != "vertices") throw Exception("Expected end of <vertices> element.") break } } /** Reads input declarations of per-index mesh data into the given mesh */ private fun readIndexData(pMesh: Mesh) { val vcount = ArrayList<Int>() val perIndexData = ArrayList<InputChannel>() val numPrimitives = element["count"]!!.i // read primitive count from the attribute /* some mesh types (e.g. tristrips) don't specify primitive count upfront, so we need to sum up the actual number of primitives while we read the <p>-tags */ var actualPrimitives = 0 val subgroup = SubMesh() // material subgroup element["material"]?.let { subgroup.mMaterial = it } // distinguish between polys and triangles val elementName = element.name_ val primType = when (elementName) { "lines" -> Pt.Lines "linestrips" -> Pt.LineStrip "polygons" -> Pt.Polygon "polylist" -> Pt.Polylist "triangles" -> Pt.Triangles "trifans" -> Pt.TriFans "tristrips" -> Pt.TriStrips else -> Pt.Invalid } assert(primType != Pt.Invalid) /* also a number of <input> elements, but in addition a <p> primitive collection and probably index counts for all primitives */ while (reader.read()) if (event is StartElement) when (element.name_) { "input" -> readInputChannel(perIndexData) "vcount" -> { if (!isEmptyElement()) { if (numPrimitives > 0) { // It is possible to define a mesh without any primitives // case <polylist> - specifies the number of indices for each polygon val ints = getTextContent().words.map { it.ui.v } if (numPrimitives > ints.size) throw Exception("Expected more values while reading <vcount> contents.") vcount.addAll(ints) } testClosing("vcount") } } "p" -> // now here the actual fun starts - these are the indices to construct the mesh data from if (!isEmptyElement()) actualPrimitives += readPrimitives(pMesh, perIndexData, numPrimitives, vcount, primType) "extra" -> skipElement("extra") "ph" -> skipElement("ph") else -> throw Exception("Unexpected sub element <${element.name_}> in tag <$elementName>") } else if (event is EndElement) { if (endElement.name_ != elementName) throw Exception("Expected end of <$elementName> element.") break } if (ASSIMP.DEBUG) if (primType != Pt.TriFans && primType != Pt.TriStrips && primType != Pt.LineStrip && primType != Pt.Lines) /* this is ONLY to workaround a bug in SketchUp 15.3.331 where it writes the wrong 'count' when it writes out the 'lines'. */ assert(actualPrimitives == numPrimitives) // only when we're done reading all <p> tags (and thus know the final vertex count) can we commit the submesh subgroup.mNumFaces = actualPrimitives pMesh.mSubMeshes.add(subgroup) } /** Reads a single input channel element and stores it in the given array, if valid */ fun readInputChannel(poChannels: ArrayList<InputChannel>) { val channel = InputChannel() // read semantic val semantic = element["semantic"]!! channel.mType = getTypeForSemantic(semantic) // read source val source = element["source"]!! if (source[0] != '#') throw Exception("Unknown reference format in url \"$source\" in source attribute of <input> element.") channel.mAccessor = source.substring(1) // skipping the leading #, hopefully the remaining text is the accessor ID only // read index offset, if per-index <input> element["offset"]?.let { channel.mOffset = it.i } // read set if texture coordinates if (channel.mType == InputType.Texcoord || channel.mType == InputType.Color) element["set"]?.let { val attrSet = it.i if (attrSet < 0) throw Exception("Invalid index \"$attrSet\" in set attribute of <input> element ") channel.mIndex = attrSet } // store, if valid type if (channel.mType != InputType.Invalid) poChannels.add(channel) // skip remaining stuff of this element, if any skipElement() } /** Reads a <p> primitive index list and assembles the mesh data into the given mesh */ fun readPrimitives(pMesh: Mesh, pPerIndexChannels: ArrayList<InputChannel>, pNumPrimitives: Int, pVCount: ArrayList<Int>, pPrimType: Pt): Int { var numPrimitives = pNumPrimitives // determine number of indices coming per vertex find the offset index for all per-vertex channels var numOffsets = 1 var perVertexOffset = 0xffffffff.i // invalid value pPerIndexChannels.forEach { numOffsets = glm.max(numOffsets, it.mOffset + 1) if (it.mType == InputType.Vertex) perVertexOffset = it.mOffset } // determine the expected number of indices val expectedPointCount = when (pPrimType) { Pt.Polylist -> pVCount.sum() Pt.Lines -> 2 * numPrimitives Pt.Triangles -> 3 * numPrimitives else -> 0 // other primitive types don't state the index count upfront... we need to guess } // and read all indices into a temporary array val indices = ArrayList<Int>() if (numPrimitives > 0) // It is possible to not contain any indices indices.addAll(getTextContent().words.map { it.i }) // complain if the index count doesn't fit if (expectedPointCount > 0 && indices.size != expectedPointCount * numOffsets) if (pPrimType == Pt.Lines) { // HACK: We just fix this number since SketchUp 15.3.331 writes the wrong 'count' for 'lines' System.out.println("Expected different index count in <p> element, ${indices.size} instead of ${expectedPointCount * numOffsets}.") numPrimitives = (indices.size / numOffsets) / 2 } else throw Exception("Expected different index count in <p> element.") else if (expectedPointCount == 0 && (indices.size % numOffsets) != 0) throw Exception("Expected different index count in <p> element.") // find the data for all sources pMesh.mPerVertexData.filter { it.resolved == null }.forEach { input -> // find accessor input.resolved = mAccessorLibrary[input.mAccessor]!! // resolve accessor's data pointer as well, if necessary val acc = input.resolved!! if (acc.mData == null) acc.mData = mDataLibrary[acc.source] } // and the same for the per-index channels pPerIndexChannels.filter { it.resolved == null }.filter { // ignore vertex pointer, it doesn't refer to an accessor if (it.mType == InputType.Vertex) { // warn if the vertex channel does not refer to the <vertices> element in the same mesh if (it.mAccessor != pMesh.mVertexID) throw Exception("Unsupported vertex referencing scheme.") false } else true }.forEach { // find accessor it.resolved = mAccessorLibrary[it.mAccessor] // resolve accessor's data pointer as well, if necessary val acc = it.resolved!! if (acc.mData == null) acc.mData = mDataLibrary[acc.source] } // For continued primitives, the given count does not come all in one <p>, but only one primitive per <p> if (pPrimType == Pt.TriFans || pPrimType == Pt.Polygon) numPrimitives = 1 // For continued primitives, the given count is actually the number of <p>'s inside the parent tag if (pPrimType == Pt.TriStrips) { val numberOfVertices = indices.size / numOffsets numPrimitives = numberOfVertices - 2 } if (pPrimType == Pt.LineStrip) { val numberOfVertices = indices.size / numOffsets numPrimitives = numberOfVertices - 1 } var polylistStartVertex = 0 for (currentPrimitive in 0 until numPrimitives) { // determine number of points for this primitive val numPoints: Int when (pPrimType) { Pt.Lines -> { numPoints = 2 for (currentVertex in 0 until numPoints) copyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices) } Pt.LineStrip -> { numPoints = 2 for (currentVertex in 0 until numPoints) copyVertex(currentVertex, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices) } Pt.Triangles -> { numPoints = 3 for (currentVertex in 0 until numPoints) copyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices) } Pt.TriStrips -> { numPoints = 3 readPrimTriStrips(numOffsets, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices) } Pt.Polylist -> { numPoints = pVCount[currentPrimitive] for (currentVertex in 0 until numPoints) copyVertex(polylistStartVertex + currentVertex, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, 0, indices) polylistStartVertex += numPoints } Pt.TriFans, Pt.Polygon -> { numPoints = indices.size / numOffsets for (currentVertex in 0 until numPoints) copyVertex(currentVertex, numOffsets, numPoints, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices) } else -> throw Exception("Unsupported primitive type.") // LineStrip is not supported due to expected index unmangling } // store the face size to later reconstruct the face from pMesh.mFaceSize.add(numPoints) } // if I ever get my hands on that guy who invented this steaming pile of indirection... testClosing("p") return numPrimitives } /** @note This function willn't work correctly if both PerIndex and PerVertex channels have same channels. * For example if TEXCOORD present in both <vertices> and <polylist> tags this function will create wrong uv * coordinates. * It's not clear from COLLADA documentation is this allowed or not. For now only exporter fixed to avoid such * behavior */ fun copyVertex(currentVertex: Int, numOffsets: Int, numPoints: Int, perVertexOffset: Int, pMesh: Mesh, pPerIndexChannels: ArrayList<InputChannel>, currentPrimitive: Int, indices: ArrayList<Int>) { // calculate the base offset of the vertex whose attributes we ant to copy val baseOffset = currentPrimitive * numOffsets * numPoints + currentVertex * numOffsets // don't overrun the boundaries of the index list val maxIndexRequested = baseOffset + numOffsets - 1 assert(maxIndexRequested < indices.size) // extract per-vertex channels using the global per-vertex offset pMesh.mPerVertexData.forEach { extractDataObjectFromChannel(it, indices[baseOffset + perVertexOffset], pMesh) } // and extract per-index channels using there specified offset pPerIndexChannels.forEach { extractDataObjectFromChannel(it, indices[baseOffset + it.mOffset], pMesh) } // store the vertex-data index for later assignment of bone vertex weights pMesh.mFacePosIndices.add(indices[baseOffset + perVertexOffset]) } /** Reads one triangle of a tristrip into the mesh */ fun readPrimTriStrips(numOffsets: Int, perVertexOffset: Int, pMesh: Mesh, pPerIndexChannels: ArrayList<InputChannel>, currentPrimitive: Int, indices: ArrayList<Int>) = if (currentPrimitive % 2 != 0) { //odd tristrip triangles need their indices mangled, to preserve winding direction copyVertex(1, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices) copyVertex(0, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices) copyVertex(2, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices) } else {//for non tristrips or even tristrip triangles copyVertex(0, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices) copyVertex(1, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices) copyVertex(2, numOffsets, 1, perVertexOffset, pMesh, pPerIndexChannels, currentPrimitive, indices) } /** Extracts a single object from an input channel and stores it in the appropriate mesh data array */ fun extractDataObjectFromChannel(input: InputChannel, pLocalIndex: Int, pMesh: Mesh) { // ignore vertex referrer - we handle them that separate if (input.mType == InputType.Vertex) return val acc = input.resolved!! if (pLocalIndex >= acc.count) throw Exception("Invalid data index ($pLocalIndex/${acc.count}) in primitive specification") // get a pointer to the start of the data object referred to by the accessor and the local index val offset = acc.offset + pLocalIndex * acc.stride // assemble according to the accessors component sub-offset list. We don't care, yet, what kind of object exactly we're extracting here val obj = FloatArray(4, { acc.mData!!.values[(offset + acc.mSubOffset[it]).i] }) // now we reinterpret it according to the type we're reading here when (input.mType) { InputType.Position -> // ignore all position streams except 0 - there can be only one position if (input.mIndex == 0) pMesh.mPositions.add(AiVector3D(obj)) else logger.error { "Collada: just one vertex position stream supported" } InputType.Normal -> { // pad to current vertex count if necessary while (pMesh.mNormals.size < pMesh.mPositions.size - 1) pMesh.mNormals.add(AiVector3D(0, 1, 0)) // ignore all normal streams except 0 - there can be only one normal if (input.mIndex == 0) pMesh.mNormals.add(AiVector3D(obj)) else logger.error { "Collada: just one vertex normal stream supported" } } InputType.Tangent -> { // pad to current vertex count if necessary while (pMesh.mTangents.size < pMesh.mPositions.size - 1) pMesh.mTangents.add(AiVector3D(1, 0, 0)) // ignore all tangent streams except 0 - there can be only one tangent if (input.mIndex == 0) pMesh.mTangents.add(AiVector3D(obj)) else logger.error { "Collada: just one vertex tangent stream supported" } } InputType.Bitangent -> { // pad to current vertex count if necessary while (pMesh.mBitangents.size < pMesh.mPositions.size - 1) pMesh.mBitangents.add(AiVector3D(0, 0, 1)) // ignore all bitangent streams except 0 - there can be only one bitangent if (input.mIndex == 0) pMesh.mBitangents.add(AiVector3D(obj)) else logger.error { "Collada: just one vertex bitangent stream supported" } } InputType.Texcoord -> { // up to 4 texture coord sets are fine, ignore the others if (input.mIndex < AI_MAX_NUMBER_OF_TEXTURECOORDS) { // pad to current vertex count if necessary while (input.mIndex >= pMesh.mTexCoords.size) pMesh.mTexCoords.add(arrayListOf()) val comps = when { 0L != acc.mSubOffset[2] || 0L != acc.mSubOffset[3] -> 3 /* hack ... consider cleaner solution */ else -> 2 } while (pMesh.mTexCoords[input.mIndex].size < pMesh.mPositions.size - 1) pMesh.mTexCoords[input.mIndex].add(FloatArray(comps)) pMesh.mTexCoords[input.mIndex].add(FloatArray(comps, { obj[it] })) pMesh.mNumUVComponents[input.mIndex] = comps } else logger.error { "Collada: too many texture coordinate sets. Skipping." } } InputType.Color -> { // up to 4 color sets are fine, ignore the others if (input.mIndex < AI_MAX_NUMBER_OF_COLOR_SETS) { // pad to current vertex count if necessary while (pMesh.mColors[input.mIndex].size < pMesh.mPositions.size - 1) pMesh.mColors[input.mIndex].add(AiColor4D(0, 0, 0, 1)) val result = AiColor4D(0, 0, 0, 1) for (i in 0 until input.resolved!!.size.i) result[i] = obj[(input.resolved!!.mSubOffset[i]).i] pMesh.mColors[input.mIndex].add(result) } else logger.error { "Collada: too many vertex color sets. Skipping." } } // IT_Invalid and IT_Vertex else -> throw Exception("shouldn't ever get here") } } /** Reads the library of node hierarchies and scene parts */ fun readSceneLibrary() { if (isEmptyElement()) return while (reader.read()) if (event is StartElement) { // a visual scene - generate root node under its ID and let ReadNode() do the recursive work if (element.name_ == "visual_scene") { // read ID. Is optional according to the spec, but how on earth should a scene_instance refer to it then? val attrID = element["id"]!! // read name if given. val attrName = element["name"] ?: "unnamed" // create a node and store it in the library under its ID val node = Node(mID = attrID, mName = attrName) mNodeLibrary[node.mID] = node readSceneNode(node) } else skipElement() // ignore the rest } else if (event is EndElement) { if (endElement.name_ == "library_visual_scenes") //ThrowException( "Expected end of \"library_visual_scenes\" element."); break } } /** Reads a scene node's contents including children and stores it in the given node */ fun readSceneNode(pNode: Node?) { // quit immediately on <bla/> elements if (isEmptyElement()) return while (reader.read()) if (event is StartElement) { if (element.name_ == "node") { val child = Node() element["id"]?.let { child.mID = it } element["sid"]?.let { child.mSID = it } element["name"]?.let { child.mName = it } // TODO: (thom) support SIDs // ai_assert( TestAttribute( "sid") == -1); if (pNode != null) { pNode.mChildren.add(child) child.mParent = pNode } else // no parent node given, probably called from <library_nodes> element. // create new node in node library mNodeLibrary[child.mID] = child // read on recursively from there readSceneNode(child) continue } // For any further stuff we need a valid node to work on else if (pNode == null) continue when (element.name_) { "lookat" -> readNodeTransformation(pNode, TransformType.LOOKAT) "matrix" -> readNodeTransformation(pNode, TransformType.MATRIX) "rotate" -> readNodeTransformation(pNode, TransformType.ROTATE) "scale" -> readNodeTransformation(pNode, TransformType.SCALE) "skew" -> readNodeTransformation(pNode, TransformType.SKEW) "translate" -> readNodeTransformation(pNode, TransformType.TRANSLATE) "render" -> if (pNode.mParent == null && pNode.mPrimaryCamera.isEmpty()) /* ... scene evaluation or, in other Words, postprocessing pipeline, or, again in other words, a turing-complete description how to render a Collada scene. The only thing that is interesting for us is the primary camera. */ element["camera_node"]?.let { if (it[0] != '#') System.err.println("Collada: Unresolved reference format of camera") else pNode.mPrimaryCamera = it.substring(1) } "instance_node" -> // find the node in the library element["url"]?.let { if (it[0] != '#') System.err.println("Collada: Unresolved reference format of node") else { pNode.mNodeInstances.add(NodeInstance()) pNode.mNodeInstances.last().mNode = it.substring(1) } } "instance_geometry", "instance_controller" -> readNodeGeometry(pNode) // Reference to a mesh or controller, with possible material associations "instance_light" -> { val url = element["url"] // Reference to a light, name given in 'url' attribute if (url == null) System.err.println("Collada: Expected url attribute in <instance_light> element") else { if (url[0] != '#') throw Exception("Unknown reference format in <instance_light> element") pNode.mLights.add(LightInstance()) pNode.mLights.last().mLight = url.substring(1) } testClosing("instance_light") } "instance_camera" -> { // Reference to a camera, name given in 'url' attribute val url = element["url"] if (url == null) System.err.println("Collada: Expected url attribute in <instance_camera> element") else { if (url[0] != '#') throw Exception("Unknown reference format in <instance_camera> element") pNode.mCameras.add(CameraInstance()) pNode.mCameras.last().mCamera = url.substring(1) } testClosing("instance_camera") } else -> skipElement() // skip everything else for the moment } } else if (event is EndElement) break } /** Reads a node transformation entry of the given type and adds it to the given node's transformation list. */ fun readNodeTransformation(pNode: Node, pType: TransformType) { if (isEmptyElement()) return val tagName = element.name_ val tf = Transform(mType = pType) // read SID element["sid"]?.let { tf.mID = it } // how many parameters to read per transformation type val floats = getTextContent().words.map { it.f } // read as many parameters and store in the transformation tf.f = when (pType) { TransformType.LOOKAT -> floatArrayOf( floats[0], floats[3], floats[6], floats[1], floats[4], floats[7], floats[2], floats[5], floats[8]) TransformType.ROTATE -> FloatArray(4) { floats[it] } TransformType.TRANSLATE -> FloatArray(3) { floats[it] } TransformType.SCALE -> FloatArray(3) { floats[it] } TransformType.SKEW -> TODO() TransformType.MATRIX -> floatArrayOf( floats[0], floats[4], floats[8], floats[12], floats[1], floats[5], floats[9], floats[13], floats[2], floats[6], floats[10], floats[14], floats[3], floats[7], floats[11], floats[15]) } // place the transformation at the queue of the node pNode.mTransforms.add(tf) // and consume the closing tag testClosing(tagName) } /** Processes bind_vertex_input and bind elements */ fun readMaterialVertexInputBinding(tbl: SemanticMappingTable) { while (reader.read()) if (event is StartElement) when (element.name_) { "bind_vertex_input" -> { val vn = InputSemanticMapEntry() // effect semantic val s = element["semantic"]!! // input semantic vn.mType = getTypeForSemantic(element["input_semantic"]!!) // index of input set element["input_set"]?.let { vn.mSet = it.i } tbl.mMap[s] = vn } "bind" -> System.out.println("Collada: Found unsupported <bind> element") } else if (event is EndElement && endElement.name_ == "instance_material") break } /** Reads a mesh reference in a node and adds it to the node's mesh list */ fun readNodeGeometry(pNode: Node) { // referred mesh is given as an attribute of the <instance_geometry> element val url = element["url"]!! if (url[0] != '#') throw Exception("Unknown reference format") val instance = MeshInstance(mMeshOrController = url.substring(1)) // skipping the leading # if (!isEmptyElement()) { // read material associations. Ignore additional elements in between while (reader.read()) if (event is StartElement) { if (element.name_ == "instance_material") { // read ID of the geometry subgroup and the target material val group = element["symbol"]!! var urlMat = element["target"]!! val s = SemanticMappingTable() if (urlMat[0] == '#') urlMat = urlMat.substring(1) s.mMatName = urlMat // resolve further material details + THIS UGLY AND NASTY semantic mapping stuff if (!isEmptyElement()) readMaterialVertexInputBinding(s) // store the association instance.mMaterials[group] = s } } else if (event is EndElement) if (endElement.name_ == "instance_geometry" || endElement.name_ == "instance_controller") break } // store it pNode.mMeshes.add(instance) } /** Reads the collada scene */ fun readScene() { if (isEmptyElement()) return while (reader.read()) if (event is StartElement) if (element.name_ == "instance_visual_scene") { // should be the first and only occurrence mRootNode?.let { throw Exception("Invalid scene containing multiple root nodes in <instance_visual_scene> element") } // read the url of the scene to instance. Should be of format "#some_name" val url = element["url"]!! if (url[0] != '#') throw Exception("Unknown reference format in <instance_visual_scene> element") // find the referred scene, skip the leading # val sit = mNodeLibrary[url.substring(1)] ?: throw Exception("Unable to resolve visual_scene reference \"$url\" in <instance_visual_scene> element.") mRootNode = sit } else skipElement() else if (event is EndElement) break } /** Calculates the resulting transformation fromm all the given transform steps */ fun calculateResultTransform(pTransforms: ArrayList<Transform>): Mat4 { val res = Mat4() pTransforms.forEach { tf -> when (tf.mType) { TransformType.LOOKAT -> { val pos = AiVector3D(tf.f) val dstPos = AiVector3D(tf.f, 3) val up = AiVector3D(tf.f, 6).normalizeAssign() val dir = (dstPos - pos).normalizeAssign() val right = (dir cross up).normalizeAssign() res *= Mat4( right, 0f, up, 0f, -dir, 0f, pos, 1f) } TransformType.ROTATE -> { val angle = tf.f[3].rad val axis = AiVector3D(tf.f) if (axis != Vec3()) res.rotateAssign(angle, axis) } TransformType.TRANSLATE -> res.translateAssign(AiVector3D(tf.f)) TransformType.SCALE -> res *= Mat4(tf.f[0], tf.f[1], tf.f[2]) TransformType.SKEW -> assert(false) // TODO: (thom) TransformType.MATRIX -> res *= Mat4(tf.f) } } return res } /** Determines the input data type for the given semantic string */ fun getTypeForSemantic(semantic: String) = when (semantic) { "" -> { System.err.println("Vertex input type is empty.") InputType.Invalid } "POSITION" -> InputType.Position "TEXCOORD" -> InputType.Texcoord "NORMAL" -> InputType.Normal "COLOR" -> InputType.Color "VERTEX" -> InputType.Vertex "BINORMAL", "TEXBINORMAL" -> InputType.Bitangent "TANGENT", "TEXTANGENT" -> InputType.Tangent else -> { System.err.println("Unknown vertex input type $semantic. Ignoring.") InputType.Invalid } } /** Reads the text contents of an element, throws an exception if not given. Skips leading whitespace. */ fun getTextContent() = testTextContent() ?: throw Exception("Invalid contents in element.") /** Reads the text contents of an element, returns NULL if not given. Skips leading whitespace. */ fun testTextContent(): String? { // present node should be the beginning of an element if (!event.isStartElement || isEmptyElement()) return null // read contents of the element if (!reader.read() || !event.isCharacters) return null return StringBuilder(event.asCharacters().data).apply { while (reader.peek().isCharacters) { reader.read() append(event.asCharacters().data) } }.toString().trimStart() // skip leading whitespace } /** Returns if an element is an empty element, like <foo /> */ fun isEmptyElement() = when { reader.peek().isEndElement && element.name_ == reader.peek().asEndElement().name_ -> { reader.nextEvent() true } else -> false } /** Skips all data until the end node of the current element */ fun skipElement() { // nothing to skip if it's an </element> if (event.isEndElement) return // reroute skipElement(element.name_) } /** Skips all data until the end node of the given element */ fun skipElement(pElement: String) { while (reader.read()) if (event is EndElement && endElement.name_ == pElement) break } /** Tests for an opening element of the given name, throws an exception if not found */ fun testOpening(pName: String) { // read element start if (!reader.read()) throw Exception("Unexpected end of file while beginning of <$pName> element.") // whitespace in front is ok, just read again if found if (event is Characters && !reader.read()) throw Exception("Unexpected end of file while reading beginning of <$pName> element.") if (event !is StartElement || element.name_ != pName) throw Exception("Expected start of <$pName> element.") } /** Tests for the closing tag of the given element, throws an exception if not found */ fun testClosing(pName: String) { // check if we're already on the closing tag and return right away if (event.isEndElement && endElement.name_ == pName) return // if not, read some more if (!reader.read()) throw Exception("Unexpected end of file while reading end of <$pName> element.") // whitespace in front is ok, just read again if found if (event is Characters && !reader.read()) throw Exception("Unexpected end of file while reading end of <$pName> element.") // but this has the be the closing tag, or we're lost if (event !is EndElement || endElement.name_ != pName) throw Exception("Expected end of <$pName> element.") } operator fun StartElement.get(string: String) = getAttributeByName(QName(string))?.value val StartElement.name_ get() = name.localPart val EndElement.name_ get() = name.localPart fun XMLEventReader.read(): Boolean { if (hasNext()) { event = nextEvent() if (event.isStartElement) element = event.asStartElement() else if (event.isEndElement) endElement = event.asEndElement() return true } return false } fun hexStringToByteArray(s: String): ByteArray { val len = s.length val data = ByteArray(len / 2, { 0 }) for (i in 0 until len step 2) data[i / 2] = ((Character.digit(s[i], 16) shl 4) + Character.digit(s[i + 1], 16)).b return data } fun consume() { if (!isEmptyElement()) skipElement() } /** Finds the item in the given library by its reference, throws if not found */ fun <T> resolveLibraryReference(pLibrary: SortedMap<String, T>, pURL: String): T = pLibrary[pURL] ?: throw Exception("Unable to resolve library reference \"$pURL\".") }
bsd-3-clause
e2fa2ed53ea21bd55c7b794fa1adf69b
50.83028
163
0.52102
4.977028
false
false
false
false
benoitletondor/EasyBudget
Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/view/report/base/MonthlyReportBaseActivity.kt
1
5786
/* * Copyright 2022 Benoit LETONDOR * * 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.benoitletondor.easybudgetapp.view.report.base import android.os.Bundle import android.view.MenuItem import android.view.View import androidx.activity.viewModels import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentPagerAdapter import androidx.lifecycle.lifecycleScope import androidx.viewpager.widget.ViewPager import com.benoitletondor.easybudgetapp.databinding.ActivityMonthlyReportBinding import com.benoitletondor.easybudgetapp.helper.BaseActivity import com.benoitletondor.easybudgetapp.helper.getMonthTitle import com.benoitletondor.easybudgetapp.helper.launchCollect import com.benoitletondor.easybudgetapp.helper.removeButtonBorder import com.benoitletondor.easybudgetapp.view.report.MonthlyReportFragment import dagger.hilt.android.AndroidEntryPoint import java.time.LocalDate /** * Activity that displays monthly report * * @author Benoit LETONDOR */ @AndroidEntryPoint class MonthlyReportBaseActivity : BaseActivity<ActivityMonthlyReportBinding>(), ViewPager.OnPageChangeListener { private val viewModel: MonthlyReportBaseViewModel by viewModels() private var ignoreNextPageSelectedEvent: Boolean = false override fun createBinding(): ActivityMonthlyReportBinding = ActivityMonthlyReportBinding.inflate(layoutInflater) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setSupportActionBar(binding.toolbar) supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) binding.monthlyReportPreviousMonthButton.text = "<" binding.monthlyReportNextMonthButton.text = ">" binding.monthlyReportPreviousMonthButton.setOnClickListener { viewModel.onPreviousMonthButtonClicked() } binding.monthlyReportNextMonthButton.setOnClickListener { viewModel.onNextMonthButtonClicked() } binding.monthlyReportPreviousMonthButton.removeButtonBorder() binding.monthlyReportNextMonthButton.removeButtonBorder() var loadedDates: List<LocalDate> = emptyList() lifecycleScope.launchCollect(viewModel.stateFlow) { state -> when(state) { is MonthlyReportBaseViewModel.State.Loaded -> { binding.monthlyReportProgressBar.visibility = View.GONE binding.monthlyReportContent.visibility = View.VISIBLE if (state.dates != loadedDates) { loadedDates = state.dates configureViewPager(state.dates) } if( !ignoreNextPageSelectedEvent ) { binding.monthlyReportViewPager.setCurrentItem(state.selectedPosition.position, true) } ignoreNextPageSelectedEvent = false binding.monthlyReportMonthTitleTv.text = state.selectedPosition.date.getMonthTitle(this) // Last and first available month val isFirstMonth = state.selectedPosition.position == 0 binding.monthlyReportNextMonthButton.isEnabled = !state.selectedPosition.latest binding.monthlyReportPreviousMonthButton.isEnabled = !isFirstMonth } MonthlyReportBaseViewModel.State.Loading -> { binding.monthlyReportProgressBar.visibility = View.VISIBLE binding.monthlyReportContent.visibility = View.GONE } } } } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { finish() return true } return super.onOptionsItemSelected(item) } /** * Configure the [.pager] adapter and listener. */ private fun configureViewPager(dates: List<LocalDate>) { binding.monthlyReportViewPager.removeOnPageChangeListener(this) binding.monthlyReportViewPager.offscreenPageLimit = 0 binding.monthlyReportViewPager.adapter = object : FragmentPagerAdapter(supportFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) { override fun getItem(position: Int): Fragment { return MonthlyReportFragment.newInstance(dates[position]) } override fun getCount(): Int { return dates.size } } binding.monthlyReportViewPager.addOnPageChangeListener(this) } // ------------------------------------------> override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} override fun onPageSelected(position: Int) { ignoreNextPageSelectedEvent = true viewModel.onPageSelected(position) } override fun onPageScrollStateChanged(state: Int) {} companion object { /** * Extra to add the the launch intent to specify that user comes from the notification (used to * show not the current month but the last one) */ const val FROM_NOTIFICATION_EXTRA = "fromNotif" } }
apache-2.0
0f08b1f4e3a24f5d0a45717461dc398f
36.816993
143
0.687694
5.479167
false
false
false
false
walkingice/MomoDict
app/src/main/java/org/zeroxlab/momodict/ui/DictListFragment.kt
1
4024
package org.zeroxlab.momodict.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.lifecycle.coroutineScope import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import org.zeroxlab.momodict.Controller import org.zeroxlab.momodict.R import org.zeroxlab.momodict.model.Book import org.zeroxlab.momodict.widget.BookRowPresenter import org.zeroxlab.momodict.widget.SelectorAdapter import org.zeroxlab.momodict.widget.SelectorAdapter.Type import kotlinx.android.synthetic.main.fragment_dictionaries_list.btn_1 as mBtnImport import kotlinx.android.synthetic.main.fragment_dictionaries_list.list as mList class DictListFragment : Fragment() { lateinit var mCtrl: Controller lateinit var mAdapter: SelectorAdapter private var coroutineScope: CoroutineScope? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mCtrl = Controller(requireActivity()) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { coroutineScope = viewLifecycleOwner.lifecycle.coroutineScope return inflater.inflate(R.layout.fragment_dictionaries_list, container, false) } override fun onDestroyView() { super.onDestroyView() coroutineScope = null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mBtnImport.setOnClickListener { onImportClicked() } mList.let { val decoration = DividerItemDecoration( context, (it.layoutManager as LinearLayoutManager).orientation ) it.addItemDecoration(decoration) val map = HashMap<Type, SelectorAdapter.Presenter<*>>() val listener = View.OnClickListener { v -> onRemoveBookClicked(v) } map[Type.A] = BookRowPresenter(listener) it.adapter = SelectorAdapter(map).also { adapter -> mAdapter = adapter reloadBooks() } } } private fun onRemoveBookClicked(v: View) { val tag: Book = v.tag as Book val finishCb = fun(success: Boolean) { if (success) { reloadBooks() } else { Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show() } } AlertDialog.Builder(requireActivity()) .setTitle("Remove") .setMessage("To remove ${tag.bookName} ?") .setPositiveButton("Remove") { _, _ -> coroutineScope?.launch { val success = mCtrl.removeBook(tag.bookName) finishCb(success) } } .setNegativeButton(android.R.string.cancel) { _, _ -> // do nothing on canceling } .create() .show() } private fun reloadBooks() { mAdapter.clear() coroutineScope?.launch { val books = mCtrl.getBooks() books.forEach { book -> mAdapter.addItem(book, Type.A) } mAdapter.notifyDataSetChanged() } } private fun onImportClicked() { val listener = activity as? FragmentListener ?: return listener.onNotified(this, FragmentListener.TYPE.VIEW_ACTION, OPEN_IMPORT_FRAGMENT) } companion object { const val OPEN_IMPORT_FRAGMENT = "ask_to_pick_file" fun newInstance(): DictListFragment { return DictListFragment().apply { val bundle = Bundle() arguments = bundle } } } }
mit
c5cb4561491953cf146c757dedd4ed09
32.256198
90
0.640408
5.004975
false
false
false
false
exponent/exponent
android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/components/gesturehandler/react/RNGestureHandlerEvent.kt
2
1993
package versioned.host.exp.exponent.modules.api.components.gesturehandler.react import androidx.core.util.Pools import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.WritableMap import com.facebook.react.uimanager.events.Event import com.facebook.react.uimanager.events.RCTEventEmitter import versioned.host.exp.exponent.modules.api.components.gesturehandler.GestureHandler class RNGestureHandlerEvent private constructor() : Event<RNGestureHandlerEvent>() { private var extraData: WritableMap? = null private var coalescingKey: Short = 0 private fun <T : GestureHandler<T>> init( handler: T, dataExtractor: RNGestureHandlerEventDataExtractor<T>?, ) { super.init(handler.view!!.id) extraData = createEventData(handler, dataExtractor) coalescingKey = handler.eventCoalescingKey } override fun onDispose() { extraData = null EVENTS_POOL.release(this) } override fun getEventName() = EVENT_NAME override fun canCoalesce() = true override fun getCoalescingKey() = coalescingKey override fun dispatch(rctEventEmitter: RCTEventEmitter) { rctEventEmitter.receiveEvent(viewTag, EVENT_NAME, extraData) } companion object { const val EVENT_NAME = "onGestureHandlerEvent" private const val TOUCH_EVENTS_POOL_SIZE = 7 // magic private val EVENTS_POOL = Pools.SynchronizedPool<RNGestureHandlerEvent>(TOUCH_EVENTS_POOL_SIZE) fun <T : GestureHandler<T>> obtain( handler: T, dataExtractor: RNGestureHandlerEventDataExtractor<T>?, ): RNGestureHandlerEvent = (EVENTS_POOL.acquire() ?: RNGestureHandlerEvent()).apply { init(handler, dataExtractor) } fun <T : GestureHandler<T>> createEventData( handler: T, dataExtractor: RNGestureHandlerEventDataExtractor<T>? ): WritableMap = Arguments.createMap().apply { dataExtractor?.extractEventData(handler, this) putInt("handlerTag", handler.tag) putInt("state", handler.state) } } }
bsd-3-clause
155f0b85a8c645e307dbc75231000467
32.779661
99
0.741094
4.50905
false
false
false
false
smmribeiro/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookEditorAppearanceProvider.kt
7
921
package org.jetbrains.plugins.notebooks.visualization import com.intellij.openapi.editor.Editor import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.util.Key private const val ID = "org.jetbrains.plugins.notebooks.editor.notebookEditorAppearanceProvider" private val key = Key.create<NotebookEditorAppearance>(NotebookEditorAppearance::class.java.name) interface NotebookEditorAppearanceProvider { fun create(editor: Editor): NotebookEditorAppearance? companion object { private val EP_NAME = ExtensionPointName.create<NotebookEditorAppearanceProvider>(ID) fun create(editor: Editor): NotebookEditorAppearance? = EP_NAME.extensions.asSequence().mapNotNull { it.create(editor) }.firstOrNull() fun install(editor: Editor) { key.set(editor, create(editor)!!) } } } val Editor.notebookAppearance: NotebookEditorAppearance get() = key.get(this)!!
apache-2.0
f31ea3cac38d2f9470dd49e1c3069cdc
30.758621
97
0.786102
4.323944
false
false
false
false
android/compose-samples
JetLagged/app/src/main/java/com/example/jetlagged/ui/theme/Color.kt
1
1141
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetlagged.ui.theme import androidx.compose.ui.graphics.Color val Lilac = Color(0xFFCCB6DC) val Yellow = Color(0xFFFFCB66) val YellowVariant = Color(0xFFFFDE9F) val Coral = Color(0xFFF3A397) val White = Color(0xFFFFFFFF) val MintGreen = Color(0xFFACD6B8) val DarkGray = Color(0xFF2B2B2D) val DarkCoral = Color(0xFFF7A374) val DarkYellow = Color(0xFFFFCE6F) val Yellow_Awake = Color(0xFFffeac1) val Yellow_Rem = Color(0xFFffdd9a) val Yellow_Light = Color(0xFFffcb66) val Yellow_Deep = Color(0xFFff973c)
apache-2.0
7b2614efbf98ad7d7be6dc3f9f3199c8
32.558824
75
0.763365
3.278736
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/versions/OutdatedKotlinRuntimeChecker.kt
3
1778
// 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.versions import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.LibraryOrderEntry import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.libraries.Library import com.intellij.util.text.VersionComparatorUtil import org.jetbrains.kotlin.idea.framework.JavaRuntimeDetectionUtil import org.jetbrains.kotlin.idea.framework.JsLibraryStdDetectionUtil fun findKotlinRuntimeLibrary(module: Module, predicate: (Library, Project) -> Boolean = ::isKotlinRuntime): Library? { val orderEntries = ModuleRootManager.getInstance(module).orderEntries.filterIsInstance<LibraryOrderEntry>() return orderEntries.asSequence() .mapNotNull { it.library } .firstOrNull { predicate(it, module.project) } } private fun isKotlinRuntime(library: Library, project: Project) = isKotlinJavaRuntime(library) || isKotlinJsRuntime(library, project) private fun isKotlinJavaRuntime(library: Library) = JavaRuntimeDetectionUtil.getRuntimeJar(library.getFiles(OrderRootType.CLASSES).asList()) != null private fun isKotlinJsRuntime(library: Library, project: Project) = JsLibraryStdDetectionUtil.hasJsStdlibJar(library, project) fun isRuntimeOutdated(libraryVersion: String?, runtimeVersion: String): Boolean { return libraryVersion == null || libraryVersion.startsWith("internal-") != runtimeVersion.startsWith("internal-") || VersionComparatorUtil.compare(runtimeVersion.substringBefore("-release-"), libraryVersion) > 0 }
apache-2.0
d2192983f2e5a4deedb0a690898acb5d
52.878788
158
0.802025
4.678947
false
false
false
false
KaratsuFr/kyori
src/main/kotlin/fr/netsah/photoServ/pojo/Photo.kt
1
1118
package fr.netsah.photoServ.pojo import com.drew.imaging.ImageMetadataReader import org.bson.types.ObjectId import java.io.File import java.time.LocalDateTime import javax.imageio.ImageIO /** * Basic store representation of a photo: * </br>- upload date * </br>- data * </br>- meta information */ data class Photo(var _id: ObjectId?=null, val dateUpload: LocalDateTime = LocalDateTime.now(), val owner: String, val binImg: ByteArray, var metadata: Map<String,String>) { companion object Helper { fun build(f: File,owner: String): Photo { // check if img if (ImageIO.read(f) == null) { throw RuntimeException("The file ${f.absoluteFile} could not be opened as an image") } val metadataFile = ImageMetadataReader.readMetadata(f) val metadata = HashMap<String,String>() metadataFile.directories .flatMap { it.tags } .forEach { metadata.put(it.tagName, it.description) } return Photo(binImg = f.readBytes(), metadata = metadata,owner = owner) } } }
mit
0f22e8b58c715ae376f85cfd41e28a91
33.9375
172
0.634168
4.187266
false
false
false
false
alibaba/p3c
idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/component/AliProjectComponent.kt
1
5436
/* * Copyright 1999-2017 Alibaba Group. * * 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.alibaba.p3c.idea.component import com.alibaba.p3c.idea.compatible.inspection.Inspections import com.alibaba.p3c.idea.config.P3cConfig import com.alibaba.p3c.idea.i18n.P3cBundle import com.alibaba.p3c.idea.inspection.AliPmdInspectionInvoker import com.alibaba.p3c.idea.pmd.SourceCodeProcessor import com.alibaba.p3c.idea.util.withLockNotInline import com.alibaba.p3c.pmd.I18nResources import com.alibaba.smartfox.idea.common.component.AliBaseProjectComponent import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileAdapter import com.intellij.openapi.vfs.VirtualFileEvent import com.intellij.openapi.vfs.VirtualFileListener import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.VirtualFileMoveEvent import com.intellij.psi.PsiManager import net.sourceforge.pmd.RuleViolation import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.locks.ReentrantReadWriteLock /** * @author caikang * @date 2016/12/13 */ class AliProjectComponent( private val project: Project, val p3cConfig: P3cConfig ) : AliBaseProjectComponent { private val listener: VirtualFileListener private val javaExtension = ".java" private val velocityExtension = ".vm" private val lock = ReentrantReadWriteLock() private val readLock = lock.readLock() private val writeLock = lock.writeLock() private val fileContexts = ConcurrentHashMap<String, FileContext>() init { listener = object : VirtualFileAdapter() { override fun contentsChanged(event: VirtualFileEvent) { val path = getFilePath(event) ?: return PsiManager.getInstance(project).findFile(event.file) ?: return if (!p3cConfig.ruleCacheEnable) { AliPmdInspectionInvoker.refreshFileViolationsCache(event.file) } if (!p3cConfig.astCacheEnable) { SourceCodeProcessor.invalidateCache(path) } SourceCodeProcessor.invalidUserTrigger(path) fileContexts[path]?.ruleViolations = null } override fun fileDeleted(event: VirtualFileEvent) { val path = getFilePath(event) path?.let { SourceCodeProcessor.invalidateCache(it) removeFileContext(it) } super.fileDeleted(event) } override fun fileMoved(event: VirtualFileMoveEvent) { val path = getFilePath(event) path?.let { SourceCodeProcessor.invalidateCache(it) removeFileContext(it) } super.fileMoved(event) } private fun getFilePath(event: VirtualFileEvent): String? { val path = event.file.canonicalPath if (path == null || !(path.endsWith(javaExtension) || path.endsWith(velocityExtension))) { return null } return path } } } override fun initComponent() { I18nResources.changeLanguage(p3cConfig.locale) val analyticsGroup = ActionManager.getInstance().getAction(analyticsGroupId) analyticsGroup.templatePresentation.text = P3cBundle.getMessage(analyticsGroupText) } override fun projectOpened() { Inspections.addCustomTag(project, "date") VirtualFileManager.getInstance().addVirtualFileListener(listener) } override fun projectClosed() { VirtualFileManager.getInstance().removeVirtualFileListener(listener) } companion object { val analyticsGroupId = "com.alibaba.p3c.analytics.action_group" val analyticsGroupText = "$analyticsGroupId.text" } data class FileContext( val lock: ReentrantReadWriteLock, var ruleViolations: Map<String, List<RuleViolation>>? = null ) fun removeFileContext(path: String) { fileContexts.remove(path) } fun getFileContext(virtualFile: VirtualFile?): FileContext? { val file = virtualFile?.canonicalPath ?: return null val result = readLock.withLockNotInline { fileContexts[file] } if (result != null) { return result } return writeLock.withLockNotInline { val finalContext = fileContexts[file] if (finalContext != null) { return@withLockNotInline finalContext } val lock = ReentrantReadWriteLock() FileContext( lock = lock ).also { fileContexts[file] = it } } } }
apache-2.0
8a13ccb889e83425fd20b35ae0e4eaea
35.24
106
0.659676
4.76007
false
false
false
false
jotomo/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/activities/EnterPinActivity.kt
1
4402
package info.nightscout.androidaps.danars.activities import android.os.Bundle import android.util.Base64 import info.nightscout.androidaps.activities.NoSplashAppCompatActivity import info.nightscout.androidaps.danars.DanaRSPlugin import info.nightscout.androidaps.danars.R import info.nightscout.androidaps.danars.databinding.DanarsEnterPinActivityBinding import info.nightscout.androidaps.danars.services.BLEComm import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.hexStringToByteArray import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.textValidator.DefaultEditTextValidator import info.nightscout.androidaps.utils.textValidator.EditTextValidator import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject import kotlin.experimental.xor class EnterPinActivity : NoSplashAppCompatActivity() { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var danaRSPlugin: DanaRSPlugin @Inject lateinit var sp: SP @Inject lateinit var bleComm: BLEComm private val disposable = CompositeDisposable() private lateinit var binding: DanarsEnterPinActivityBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DanarsEnterPinActivityBinding.inflate(layoutInflater) setContentView(binding.root) val p1 = DefaultEditTextValidator(binding.rsV3Pin1, this) .setTestErrorString(resourceHelper.gs(R.string.error_mustbe12hexadidits), this) .setCustomRegexp(resourceHelper.gs(R.string.twelvehexanumber), this) .setTestType(EditTextValidator.TEST_REGEXP, this) val p2 = DefaultEditTextValidator(binding.rsV3Pin2, this) .setTestErrorString(resourceHelper.gs(R.string.error_mustbe8hexadidits), this) .setCustomRegexp(resourceHelper.gs(R.string.eighthexanumber), this) .setTestType(EditTextValidator.TEST_REGEXP, this) binding.okcancel.ok.setOnClickListener { if (p1.testValidity(false) && p2.testValidity(false)) { val result = checkPairingCheckSum( binding.rsV3Pin1.text.toString().hexStringToByteArray(), binding.rsV3Pin2.text.toString().substring(0..5).hexStringToByteArray(), binding.rsV3Pin2.text.toString().substring(6..7).hexStringToByteArray()) if (result) { bleComm.finishV3Pairing() finish() } else OKDialog.show(this, resourceHelper.gs(R.string.error), resourceHelper.gs(R.string.invalidinput)) } } binding.okcancel.cancel.setOnClickListener { finish() } } override fun onResume() { super.onResume() disposable.add(rxBus .toObservable(EventPumpStatusChanged::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ if (it.status == EventPumpStatusChanged.Status.DISCONNECTED) finish() }) { fabricPrivacy.logException(it) } ) } override fun onPause() { super.onPause() disposable.clear() } private fun checkPairingCheckSum(pairingKey: ByteArray, randomPairingKey: ByteArray, checksum: ByteArray): Boolean { // pairingKey ByteArray(6) // randomPairingKey ByteArray(3) // checksum ByteArray(1) var pairingKeyCheckSum: Byte = 0 for (i in pairingKey.indices) pairingKeyCheckSum = pairingKeyCheckSum xor pairingKey[i] sp.putString(resourceHelper.gs(R.string.key_danars_v3_pairingkey) + danaRSPlugin.mDeviceName, Base64.encodeToString(pairingKey, Base64.DEFAULT)) for (i in randomPairingKey.indices) pairingKeyCheckSum = pairingKeyCheckSum xor randomPairingKey[i] sp.putString(resourceHelper.gs(R.string.key_danars_v3_randompairingkey) + danaRSPlugin.mDeviceName, Base64.encodeToString(randomPairingKey, Base64.DEFAULT)) return checksum[0] == pairingKeyCheckSum } }
agpl-3.0
ec5b7e633fbef7ac9a0a3a09f21d1c19
43.464646
164
0.729214
4.491837
false
true
false
false
tensorflow/examples
lite/examples/model_personalization/android/app/src/main/java/org/tensorflow/lite/examples/modelpersonalization/TransferLearningHelper.kt
1
13159
/* * Copyright 2022 The TensorFlow Authors. 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 org.tensorflow.lite.examples.modelpersonalization import android.content.Context import android.graphics.Bitmap import android.os.Handler import android.os.Looper import android.os.SystemClock import android.util.Log import org.tensorflow.lite.DataType import org.tensorflow.lite.Interpreter import org.tensorflow.lite.support.common.FileUtil import org.tensorflow.lite.support.common.ops.NormalizeOp import org.tensorflow.lite.support.image.ImageProcessor import org.tensorflow.lite.support.image.TensorImage import org.tensorflow.lite.support.image.ops.ResizeOp import org.tensorflow.lite.support.image.ops.ResizeWithCropOrPadOp import org.tensorflow.lite.support.image.ops.Rot90Op import org.tensorflow.lite.support.label.Category import org.tensorflow.lite.support.label.TensorLabel import org.tensorflow.lite.support.tensorbuffer.TensorBuffer import java.io.IOException import java.nio.FloatBuffer import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import kotlin.math.max import kotlin.math.min class TransferLearningHelper( var numThreads: Int = 2, val context: Context, val classifierListener: ClassifierListener? ) { private var interpreter: Interpreter? = null private val trainingSamples: MutableList<TrainingSample> = mutableListOf() private var executor: ExecutorService? = null //This lock guarantees that only one thread is performing training and //inference at any point in time. private val lock = Any() private var targetWidth: Int = 0 private var targetHeight: Int = 0 private val handler = Handler(Looper.getMainLooper()) init { if (setupModelPersonalization()) { targetWidth = interpreter!!.getInputTensor(0).shape()[2] targetHeight = interpreter!!.getInputTensor(0).shape()[1] } else { classifierListener?.onError("TFLite failed to init.") } } fun close() { executor?.shutdownNow() executor = null interpreter = null } fun pauseTraining() { executor?.shutdownNow() } private fun setupModelPersonalization(): Boolean { val options = Interpreter.Options() options.numThreads = numThreads return try { val modelFile = FileUtil.loadMappedFile(context, "model.tflite") interpreter = Interpreter(modelFile, options) true } catch (e: IOException) { classifierListener?.onError( "Model personalization failed to " + "initialize. See error logs for details" ) Log.e(TAG, "TFLite failed to load model with error: " + e.message) false } } // Process input image and add the output into list samples which are // ready for training. fun addSample(image: Bitmap, className: String, rotation: Int) { synchronized(lock) { if (interpreter == null) { setupModelPersonalization() } processInputImage(image, rotation)?.let { tensorImage -> val bottleneck = loadBottleneck(tensorImage) trainingSamples.add( TrainingSample( bottleneck, encoding(classes.getValue(className)) ) ) } } } // Start training process fun startTraining() { if (interpreter == null) { setupModelPersonalization() } // Create new thread for training process. executor = Executors.newSingleThreadExecutor() val trainBatchSize = getTrainBatchSize() if (trainingSamples.size < trainBatchSize) { throw RuntimeException( String.format( "Too few samples to start training: need %d, got %d", trainBatchSize, trainingSamples.size ) ) } executor?.execute { synchronized(lock) { var avgLoss: Float // Keep training until the helper pause or close. while (executor?.isShutdown == false) { var totalLoss = 0f var numBatchesProcessed = 0 // Shuffle training samples to reduce overfitting and // variance. trainingSamples.shuffle() trainingBatches(trainBatchSize) .forEach { trainingSamples -> val trainingBatchBottlenecks = MutableList(trainBatchSize) { FloatArray( BOTTLENECK_SIZE ) } val trainingBatchLabels = MutableList(trainBatchSize) { FloatArray( classes.size ) } // Copy a training sample list into two different // input training lists. trainingSamples.forEachIndexed { index, trainingSample -> trainingBatchBottlenecks[index] = trainingSample.bottleneck trainingBatchLabels[index] = trainingSample.label } val loss = training( trainingBatchBottlenecks, trainingBatchLabels ) totalLoss += loss numBatchesProcessed++ } // Calculate the average loss after training all batches. avgLoss = totalLoss / numBatchesProcessed handler.post { classifierListener?.onLossResults(avgLoss) } } } } } // Runs one training step with the given bottleneck batches and labels // and return the loss number. private fun training( bottlenecks: MutableList<FloatArray>, labels: MutableList<FloatArray> ): Float { val inputs: MutableMap<String, Any> = HashMap() inputs[TRAINING_INPUT_BOTTLENECK_KEY] = bottlenecks.toTypedArray() inputs[TRAINING_INPUT_LABELS_KEY] = labels.toTypedArray() val outputs: MutableMap<String, Any> = HashMap() val loss = FloatBuffer.allocate(1) outputs[TRAINING_OUTPUT_KEY] = loss interpreter?.runSignature(inputs, outputs, TRAINING_KEY) return loss.get(0) } // Invokes inference on the given image batches. fun classify(bitmap: Bitmap, rotation: Int) { processInputImage(bitmap, rotation)?.let { image -> synchronized(lock) { if (interpreter == null) { setupModelPersonalization() } // Inference time is the difference between the system time at the start and finish of the // process var inferenceTime = SystemClock.uptimeMillis() val inputs: MutableMap<String, Any> = HashMap() inputs[INFERENCE_INPUT_KEY] = image.buffer val outputs: MutableMap<String, Any> = HashMap() val output = TensorBuffer.createFixedSize( intArrayOf(1, 4), DataType.FLOAT32 ) outputs[INFERENCE_OUTPUT_KEY] = output.buffer interpreter?.runSignature(inputs, outputs, INFERENCE_KEY) val tensorLabel = TensorLabel(classes.keys.toList(), output) val result = tensorLabel.categoryList inferenceTime = SystemClock.uptimeMillis() - inferenceTime classifierListener?.onResults(result, inferenceTime) } } } // Loads the bottleneck feature from the given image array. private fun loadBottleneck(image: TensorImage): FloatArray { val inputs: MutableMap<String, Any> = HashMap() inputs[LOAD_BOTTLENECK_INPUT_KEY] = image.buffer val outputs: MutableMap<String, Any> = HashMap() val bottleneck = Array(1) { FloatArray(BOTTLENECK_SIZE) } outputs[LOAD_BOTTLENECK_OUTPUT_KEY] = bottleneck interpreter?.runSignature(inputs, outputs, LOAD_BOTTLENECK_KEY) return bottleneck[0] } // Preprocess the image and convert it into a TensorImage for classification. private fun processInputImage( image: Bitmap, imageRotation: Int ): TensorImage? { val height = image.height val width = image.width val cropSize = min(height, width) val imageProcessor = ImageProcessor.Builder() .add(Rot90Op(-imageRotation / 90)) .add(ResizeWithCropOrPadOp(cropSize, cropSize)) .add( ResizeOp( targetHeight, targetWidth, ResizeOp.ResizeMethod.BILINEAR ) ) .add(NormalizeOp(0f, 255f)) .build() val tensorImage = TensorImage(DataType.FLOAT32) tensorImage.load(image) return imageProcessor.process(tensorImage) } // encode the classes name to float array private fun encoding(id: Int): FloatArray { val classEncoded = FloatArray(4) { 0f } classEncoded[id] = 1f return classEncoded } // Training model expected batch size. private fun getTrainBatchSize(): Int { return min( max( /* at least one sample needed */1, trainingSamples.size), EXPECTED_BATCH_SIZE ) } // Constructs an iterator that iterates over training sample batches. private fun trainingBatches(trainBatchSize: Int): Iterator<List<TrainingSample>> { return object : Iterator<List<TrainingSample>> { private var nextIndex = 0 override fun hasNext(): Boolean { return nextIndex < trainingSamples.size } override fun next(): List<TrainingSample> { val fromIndex = nextIndex val toIndex: Int = nextIndex + trainBatchSize nextIndex = toIndex return if (toIndex >= trainingSamples.size) { // To keep batch size consistent, last batch may include some elements from the // next-to-last batch. trainingSamples.subList( trainingSamples.size - trainBatchSize, trainingSamples.size ) } else { trainingSamples.subList(fromIndex, toIndex) } } } } interface ClassifierListener { fun onError(error: String) fun onResults(results: List<Category>?, inferenceTime: Long) fun onLossResults(lossNumber: Float) } companion object { const val CLASS_ONE = "1" const val CLASS_TWO = "2" const val CLASS_THREE = "3" const val CLASS_FOUR = "4" private val classes = mapOf( CLASS_ONE to 0, CLASS_TWO to 1, CLASS_THREE to 2, CLASS_FOUR to 3 ) private const val LOAD_BOTTLENECK_INPUT_KEY = "feature" private const val LOAD_BOTTLENECK_OUTPUT_KEY = "bottleneck" private const val LOAD_BOTTLENECK_KEY = "load" private const val TRAINING_INPUT_BOTTLENECK_KEY = "bottleneck" private const val TRAINING_INPUT_LABELS_KEY = "label" private const val TRAINING_OUTPUT_KEY = "loss" private const val TRAINING_KEY = "train" private const val INFERENCE_INPUT_KEY = "feature" private const val INFERENCE_OUTPUT_KEY = "output" private const val INFERENCE_KEY = "infer" private const val BOTTLENECK_SIZE = 1 * 7 * 7 * 1280 private const val EXPECTED_BATCH_SIZE = 20 private const val TAG = "ModelPersonalizationHelper" } data class TrainingSample(val bottleneck: FloatArray, val label: FloatArray) }
apache-2.0
2a0471560808d3ffa17135e233e7a0f0
35.859944
106
0.577096
5.037902
false
false
false
false
tsagi/JekyllForAndroid
app/src/main/java/gr/tsagi/jekyllforandroid/app/data/PostsProvider.kt
2
12529
package gr.tsagi.jekyllforandroid.app.data import android.content.ContentProvider import android.content.ContentValues import android.content.UriMatcher import android.database.Cursor import android.database.sqlite.SQLiteQueryBuilder import android.net.Uri import gr.tsagi.jekyllforandroid.app.data.PostsContract.PostEntry /** \* Created with IntelliJ IDEA. \* User: jchanghong \* Date: 8/8/14 \* Time: 19:48 \*/ class PostsProvider : ContentProvider() { private var mOpenHelper: PostsDbHelper? = null private fun getPostWithCategoryAndTags(uri: Uri, projection: Array<String>, sortOrder: String): Cursor { val id = PostEntry.getIdFromUri(uri) val selectionArgs: Array<String> val selection: String = sPostSelection selectionArgs = arrayOf(id) return sParametersQueryBuilder.query(mOpenHelper!!.readableDatabase, projection, selection, selectionArgs, null, null, sortOrder ) } private fun sPostsByStatus(uri: Uri, projection: Array<String>, sortOrder: String): Cursor { var status = PostEntry.getStatusFromUri(uri) if (status == "published") status = "0" else status = "1" val selectionArgs: Array<String> val selection: String = sPostStatusSelection selectionArgs = arrayOf(status) return mOpenHelper!!.readableDatabase.query( PostEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder ) } override fun onCreate(): Boolean { mOpenHelper = PostsDbHelper(context) return true } override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? { // Here's the switch statement that, given a URI, will determine what kind of request it is, // and query the database accordingly. var retCursor: Cursor? = null when (sUriMatcher.match(uri)) { // "posts/*" POST_STATUS -> { retCursor = sPostsByStatus(uri, projection!!, sortOrder!!) } // "posts/*/*" POST_ID -> { retCursor = getPostWithCategoryAndTags(uri, projection!!, sortOrder!!) }// dumpCursor(retCursor); // "post" POST -> { retCursor = mOpenHelper!!.readableDatabase.query( PostEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder ) } // "tag" TAG -> { }// retCursor = mOpenHelper.getReadableDatabase().query( // TagEntry.TABLE_NAME, // projection, // selection, // selectionArgs, // null, // null, // sortOrder // ); // "category" CATEGORY -> { }// retCursor = mOpenHelper.getReadableDatabase().query( // CategoryEntry.TABLE_NAME, // projection, // selection, // selectionArgs, // null, // null, // sortOrder // ); else -> throw UnsupportedOperationException("Unknown uri: " + uri) } // dumpCursor(retCursor); retCursor!!.setNotificationUri(context!!.contentResolver, uri) return retCursor } override fun getType(uri: Uri): String? { // Use the Uri Matcher to determine what kind of URI this is. val match = sUriMatcher.match(uri) when (match) { POST_ID -> return PostEntry.CONTENT_TYPE POST -> return PostEntry.CONTENT_TYPE // TAG, // return TagEntry.CONTENT_TYPE; // CATEGORY, // return CategoryEntry.CONTENT_TYPE; else -> { throw UnsupportedOperationException("Unknown uri: " + uri) } } } override fun insert(uri: Uri, values: ContentValues?): Uri? { val db = mOpenHelper!!.writableDatabase val match = sUriMatcher.match(uri) var returnUri: Uri? = null when (match) { POST -> { val _id = db.insert(PostEntry.TABLE_NAME, null, values) if (_id > 0) returnUri = PostEntry.buildPostUri(_id) else throw android.database.SQLException("Failed to insert row into " + uri) } TAG -> { }// long _id = db.insert(TagEntry.TABLE_NAME, null, values); // if ( _id > 0 ) // returnUri = TagEntry.buildTagUri(_id); // else // throw new android.database.SQLException("Failed to insert row into " + uri); CATEGORY -> { }// long _id = db.insert(CategoryEntry.TABLE_NAME, null, values); // if ( _id > 0 ) // returnUri = CategoryEntry.buildCategoryUri(_id); // else // throw new android.database.SQLException("Failed to insert row into " + uri); else -> throw UnsupportedOperationException("Unknown uri: " + uri) } context!!.contentResolver.notifyChange(uri, null) return returnUri } override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int { val db = mOpenHelper!!.writableDatabase val match = sUriMatcher.match(uri) var rowsDeleted = 0 when (match) { POST -> rowsDeleted = db.delete( PostEntry.TABLE_NAME, selection, selectionArgs) TAG -> { } CATEGORY -> { } else -> throw UnsupportedOperationException("Unknown uri: " + uri) }// rowsDeleted = db.delete( // TagEntry.TABLE_NAME, selection, selectionArgs); // rowsDeleted = db.delete( // CategoryEntry.TABLE_NAME, selection, selectionArgs); // Because a null deletes all rows if (selection == null || rowsDeleted != 0) { context!!.contentResolver.notifyChange(uri, null) } return rowsDeleted } override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int { val db = mOpenHelper!!.writableDatabase val match = sUriMatcher.match(uri) var rowsUpdated = 0 when (match) { POST -> rowsUpdated = db.update(PostEntry.TABLE_NAME, values, selection, selectionArgs) TAG -> { } CATEGORY -> { } else -> throw UnsupportedOperationException("Unknown uri: " + uri) }// rowsUpdated = db.update(TagEntry.TABLE_NAME, values, selection, // selectionArgs); // rowsUpdated = db.update(CategoryEntry.TABLE_NAME, values, selection, // selectionArgs); if (rowsUpdated != 0) { context!!.contentResolver.notifyChange(uri, null) } return rowsUpdated } override fun bulkInsert(uri: Uri, values: Array<ContentValues>): Int { val db = mOpenHelper!!.writableDatabase val match = sUriMatcher.match(uri) var returnCount: Int when (match) { POST -> { db.beginTransaction() returnCount = 0 try { values .asSequence() .map { db.insert(PostEntry.TABLE_NAME, null, it) } .filter { it != -1L } .forEach { returnCount++ } db.setTransactionSuccessful() } finally { db.endTransaction() } context!!.contentResolver.notifyChange(uri, null) return returnCount } TAG -> { db.beginTransaction() returnCount = 0 try { for (value in values) { // long _id = db.insert(TagEntry.TABLE_NAME, null, value); // if (_id != -1) { // returnCount++; // } } db.setTransactionSuccessful() } finally { db.endTransaction() } context!!.contentResolver.notifyChange(uri, null) return returnCount } CATEGORY -> { db.beginTransaction() returnCount = 0 try { for (value in values) { // long _id = db.insert(CategoryEntry.TABLE_NAME, null, value); // if (_id != -1) { // returnCount++; // } } db.setTransactionSuccessful() } finally { db.endTransaction() } context!!.contentResolver.notifyChange(uri, null) return returnCount } else -> return super.bulkInsert(uri, values) } } companion object { private val LOG_TAG = PostsProvider::class.java.simpleName // THe URI Matcher is used by this content provider. private val sUriMatcher = buildUriMatcher() private val POST = 100 private val POST_ID = 101 private val POST_STATUS = 102 private val CATEGORY = 200 private val CATEGORY_PER_POST = 201 private val TAG = 300 private val sParametersQueryBuilder: SQLiteQueryBuilder = SQLiteQueryBuilder() // TODO: select tags.tagname as tagname from posts cross join tags where posts // .id=5; init { sParametersQueryBuilder.tables = PostEntry.TABLE_NAME } private val sPostSelection = PostEntry.TABLE_NAME + "." + PostEntry.COLUMN_POST_ID + " = ? " private val sPostStatusSelection = PostEntry.TABLE_NAME + "." + PostEntry.COLUMN_DRAFT + " = ? " private fun buildUriMatcher(): UriMatcher { // I know what you're thinking. Why create a UriMatcher when you can use regular // expressions instead? Because you're not crazy, that's why. // All paths added to the UriMatcher have a corresponding code to return when a match is // found. The code passed into the constructor represents the code to return for the root // URI. It's common to use NO_MATCH as the code for this case. val matcher = UriMatcher(UriMatcher.NO_MATCH) val authority = PostsContract.CONTENT_AUTHORITY // For each type of URI you want to add, create a corresponding code. matcher.addURI(authority, PostsContract.PATH_POSTS, POST) matcher.addURI(authority, PostsContract.PATH_POSTS + "/*", POST_STATUS) matcher.addURI(authority, PostsContract.PATH_POSTS + "/*/*", POST_ID) matcher.addURI(authority, PostsContract.PATH_TAGS, TAG) matcher.addURI(authority, PostsContract.PATH_CATEGORIES, CATEGORY) matcher.addURI(authority, PostsContract.PATH_CATEGORIES + "/$", CATEGORY_PER_POST) return matcher } } }
gpl-2.0
1ce8c7fa7a328e53a5cb7b08fad62346
37.669753
115
0.495091
5.377253
false
false
false
false
jwren/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/highlighter/renderersUtil.kt
1
5435
// 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.highlighter.renderersUtil import com.google.common.html.HtmlEscapers import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.diagnostics.rendering.RenderingContext import org.jetbrains.kotlin.diagnostics.rendering.SmartTypeRenderer import org.jetbrains.kotlin.diagnostics.rendering.asRenderer import org.jetbrains.kotlin.idea.KotlinIdeaAnalysisBundle import org.jetbrains.kotlin.renderer.ClassifierNamePolicy import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.renderer.RenderingFormat import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.util.hasTypeMismatchErrorOnParameter import org.jetbrains.kotlin.resolve.calls.util.hasUnmappedArguments import org.jetbrains.kotlin.resolve.calls.components.hasDefaultValue import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.types.error.ErrorUtils private const val RED_TEMPLATE = "<font color=red><b>%s</b></font>" private const val STRONG_TEMPLATE = "<b>%s</b>" fun renderStrong(o: Any): String = STRONG_TEMPLATE.format(o) fun renderError(o: Any): String = RED_TEMPLATE.format(o) fun renderStrong(o: Any, error: Boolean): String = (if (error) RED_TEMPLATE else STRONG_TEMPLATE).format(o) private val HTML_FOR_UNINFERRED_TYPE_PARAMS: DescriptorRenderer = DescriptorRenderer.withOptions { uninferredTypeParameterAsName = true modifiers = emptySet() classifierNamePolicy = ClassifierNamePolicy.SHORT textFormat = RenderingFormat.HTML } fun renderResolvedCall(resolvedCall: ResolvedCall<*>, context: RenderingContext): String { val typeRenderer = SmartTypeRenderer(HTML_FOR_UNINFERRED_TYPE_PARAMS) val descriptorRenderer = HTML_FOR_UNINFERRED_TYPE_PARAMS.asRenderer() val stringBuilder = StringBuilder("") val indent = "&nbsp;&nbsp;" fun append(any: Any): StringBuilder = stringBuilder.append(any) fun renderParameter(parameter: ValueParameterDescriptor): String { val varargElementType = parameter.varargElementType val parameterType = varargElementType ?: parameter.type val renderedParameter = (if (varargElementType != null) "<b>vararg</b> " else "") + typeRenderer.render(parameterType, context) + if (parameter.hasDefaultValue()) " = ..." else "" return if (resolvedCall.hasTypeMismatchErrorOnParameter(parameter)) renderError(renderedParameter) else renderedParameter } fun appendTypeParametersSubstitution() { val parametersToArgumentsMap = resolvedCall.typeArguments fun TypeParameterDescriptor.isInferred(): Boolean { val typeArgument = parametersToArgumentsMap[this] ?: return false return !ErrorUtils.isUninferredTypeVariable(typeArgument) } val typeParameters = resolvedCall.candidateDescriptor.typeParameters val (inferredTypeParameters, notInferredTypeParameters) = typeParameters.partition(TypeParameterDescriptor::isInferred) append("<br/>$indent<i>${KotlinIdeaAnalysisBundle.message("type.parameters.where")}</i> ") if (notInferredTypeParameters.isNotEmpty()) { append(notInferredTypeParameters.joinToString { typeParameter -> renderError(typeParameter.name) }) append("<i> ${KotlinIdeaAnalysisBundle.message("cannot.be.inferred")}</i>") if (inferredTypeParameters.isNotEmpty()) { append("; ") } } val typeParameterToTypeArgumentMap = resolvedCall.typeArguments if (inferredTypeParameters.isNotEmpty()) { append(inferredTypeParameters.joinToString { typeParameter -> "${typeParameter.name} = ${typeRenderer.render(typeParameterToTypeArgumentMap[typeParameter]!!, context)}" }) } } val resultingDescriptor = resolvedCall.resultingDescriptor val receiverParameter = resultingDescriptor.extensionReceiverParameter if (receiverParameter != null) { append(typeRenderer.render(receiverParameter.type, context)).append(".") } append(HtmlEscapers.htmlEscaper().escape(resultingDescriptor.name.asString())).append("(") append(resultingDescriptor.valueParameters.joinToString(transform = ::renderParameter)) append(if (resolvedCall.hasUnmappedArguments()) renderError(")") else ")") if (resolvedCall.candidateDescriptor.typeParameters.isNotEmpty()) { appendTypeParametersSubstitution() append(KotlinIdeaAnalysisBundle.message("i.for.i.br.0", indent)) // candidate descriptor is not in context of the rest of the message append(descriptorRenderer.render(resolvedCall.candidateDescriptor, RenderingContext.of(resolvedCall.candidateDescriptor))) } else { append(" <i>${KotlinIdeaAnalysisBundle.message("defined.in")}</i> ") val containingDeclaration = resultingDescriptor.containingDeclaration val fqName = DescriptorUtils.getFqName(containingDeclaration) append(if (fqName.isRoot) KotlinIdeaAnalysisBundle.message("root.package") else fqName.asString()) } return stringBuilder.toString() }
apache-2.0
48bdfa31246b97b05e675e3422f7e60d
49.794393
158
0.747194
5.013838
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FailedEditorPane.kt
1
6881
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.fileEditor.impl import com.intellij.icons.AllIcons import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsContexts.DialogMessage import com.intellij.ui.components.JBLabel import com.intellij.ui.components.Link import com.intellij.util.ui.JBUI import com.intellij.util.ui.StartupUiUtil import com.intellij.util.ui.UIUtil import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import javax.swing.Icon import javax.swing.JPanel import javax.swing.JTextPane import javax.swing.SwingConstants import javax.swing.border.EmptyBorder import javax.swing.text.SimpleAttributeSet import javax.swing.text.StyleConstants /** * Draws ui for failed state of editor. * * @param message 'message' is wrapped and supports multi-line, * please TRY to make your message short. * For example, "Invalid Xml file" instead of " XML parsing error at line 0... (and three more pages of text)" * * if you STILL want to put a big message , then go to our designers for a consultation. * They will probably offer a more elegant solution (it always turned out this way) * * @param showErrorIcon allows you to enable or disable error icon before text. Other icons not allowed here * * @param wrapMode enables or disables multiline support * * @param init builder, where you can add action buttons for the editor * * * @return Jpanel with failed editor ui * */ fun failedEditorPane(@DialogMessage message: String, showErrorIcon: Boolean, wrapMode: MultilineWrapMode = MultilineWrapMode.Auto, init: FailedEditorBuilder.() -> Unit): JPanel { val builder = FailedEditorBuilder(message, if (showErrorIcon) AllIcons.General.Error else null) builder.init() return builder.draw(wrapMode) } enum class MultilineWrapMode { /** * Disable multiline support (use it for small texts) */ DoNotWrap, /** * Enable multiline support and text-wrapping witch may be confusing for small texts */ Wrap, /** * Enables or disable multiline support depends on size of a text */ Auto } class FailedEditorBuilder internal constructor(@DialogMessage val message: String, val icon: Icon?) { private val myButtons = mutableListOf<Pair<String, () -> Unit>>() /** * Adds Link at the bottom of the text * * @param text Text of link * * @param action Action of link */ fun link(@NlsContexts.LinkLabel text: String, action: () -> Unit) { myButtons.add(Pair(text, action)) } /** * Adds Link at the bottom of the text that * opens tab in target editor */ fun linkThatNavigatesToEditor(@NlsContexts.LinkLabel text: String, editorProviderId: String, project: Project, editor: FileEditor) = link(text) { editor.tryOpenTab(project, editorProviderId) } /** * Adds Link at the bottom of the text that * opens text tab in target editor */ fun linkThatNavigatesToTextEditor(@NlsContexts.LinkLabel text: String, project: Project, editor: FileEditor) = linkThatNavigatesToEditor(text, "text-editor", project, editor) /** * Opens tab in target editor */ private fun FileEditor.tryOpenTab(project: Project, editorProviderId: String): Boolean { val impl = FileEditorManager.getInstance(project) as? FileEditorManagerImpl ?: return false for (window in impl.windows) { for (composite in window.allComposites) { for (tab in composite.allEditors) { if (tab == this) { //move focus to current window window.setAsCurrentWindow(true) //select editor window.setSelectedComposite(composite, true) //open tab composite.fileEditorManager.setSelectedEditor(composite.file, editorProviderId) return true } } } } return false } internal fun draw(wrapMode: MultilineWrapMode): JPanel = JPanel(MigLayout("flowy, aligny 47%, alignx 50%, ins 0, gap 0")).apply { border = EmptyBorder(UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP) val wrap = when (wrapMode) { MultilineWrapMode.Wrap -> true MultilineWrapMode.DoNotWrap -> false else -> { val maxButtonSize = if (myButtons.any()) myButtons.maxOf { it.first.length } else 0 (message.length > maxButtonSize && message.length > 65) || message.contains('\n') || message.contains('\r') } } if (wrap) drawMessagePane() else //draw label otherwise to avoid wrapping on resize drawLabel() for ((text, action) in myButtons) { add(Link(text, null, action), "alignx center, gapbottom ${UIUtil.DEFAULT_VGAP}") } } private fun JPanel.drawLabel() { add(JBLabel(icon).apply { text = message if (icon != null) { this.border = EmptyBorder(0, 0, 0, UIUtil.DEFAULT_HGAP + iconTextGap) } }, "alignx center, gapbottom ${getGapAfterMessage()}") } private fun JPanel.drawMessagePane() { val messageTextPane = JTextPane().apply { isFocusable = false isEditable = false border = null font = StartupUiUtil.getLabelFont() background = UIUtil.getLabelBackground() val centerAttribute = SimpleAttributeSet() StyleConstants.setAlignment(centerAttribute, StyleConstants.ALIGN_CENTER) styledDocument.insertString(0, message, centerAttribute) styledDocument.setParagraphAttributes(0, styledDocument.length, centerAttribute, false) text = message } if (icon != null) { // in case of icon - wrap icon and text pane // [icon] [gap] [text] [gap+icon size] // text has to be aligned as if there is no icon val iconAndText = JPanel(BorderLayout()).apply { val iconTextGap = JBUI.scale(4) add(JBLabel(icon).apply { verticalAlignment = SwingConstants.TOP }, BorderLayout.LINE_START) messageTextPane.border = EmptyBorder(0, iconTextGap, 0, UIUtil.DEFAULT_HGAP + iconTextGap) add(messageTextPane, BorderLayout.CENTER) } add(iconAndText, "alignx center, gapbottom ${UIUtil.DEFAULT_VGAP + 1}") } else { // if there is only one action link - then gap is usual // but if there is more than one action link - gap is increased add(messageTextPane, "alignx center, gapbottom ${getGapAfterMessage()}") } } private fun getGapAfterMessage() = if (myButtons.count() > 1) UIUtil.DEFAULT_VGAP + 1; else UIUtil.DEFAULT_VGAP }
apache-2.0
d4a2125e81bec59c9242e7fa7b4dc0c8
33.752525
134
0.682604
4.279229
false
false
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/optimizations/CallGraphBuilder.kt
2
9208
/* * 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 org.jetbrains.kotlin.backend.konan.optimizations import org.jetbrains.kotlin.backend.common.pop import org.jetbrains.kotlin.backend.common.push import org.jetbrains.kotlin.backend.konan.DirectedGraph import org.jetbrains.kotlin.backend.konan.DirectedGraphNode import org.jetbrains.kotlin.backend.konan.Context internal class CallGraphNode(val graph: CallGraph, val symbol: DataFlowIR.FunctionSymbol.Declared) : DirectedGraphNode<DataFlowIR.FunctionSymbol.Declared> { override val key get() = symbol override val directEdges: List<DataFlowIR.FunctionSymbol.Declared> by lazy { graph.directEdges[symbol]!!.callSites .filter { !it.isVirtual } .map { it.actualCallee } .filterIsInstance<DataFlowIR.FunctionSymbol.Declared>() .filter { graph.directEdges.containsKey(it) } } override val reversedEdges: List<DataFlowIR.FunctionSymbol.Declared> by lazy { graph.reversedEdges[symbol]!! } class CallSite(val call: DataFlowIR.Node.Call, val isVirtual: Boolean, val actualCallee: DataFlowIR.FunctionSymbol) val callSites = mutableListOf<CallSite>() } internal class CallGraph(val directEdges: Map<DataFlowIR.FunctionSymbol.Declared, CallGraphNode>, val reversedEdges: Map<DataFlowIR.FunctionSymbol.Declared, MutableList<DataFlowIR.FunctionSymbol.Declared>>, val rootExternalFunctions: List<DataFlowIR.FunctionSymbol>) : DirectedGraph<DataFlowIR.FunctionSymbol.Declared, CallGraphNode> { override val nodes get() = directEdges.values override fun get(key: DataFlowIR.FunctionSymbol.Declared) = directEdges[key]!! fun addEdge(caller: DataFlowIR.FunctionSymbol.Declared, callSite: CallGraphNode.CallSite) { directEdges[caller]!!.callSites += callSite } fun addReversedEdge(caller: DataFlowIR.FunctionSymbol.Declared, callee: DataFlowIR.FunctionSymbol.Declared) { reversedEdges[callee]!!.add(caller) } } internal class CallGraphBuilder( val context: Context, val moduleDFG: ModuleDFG, val externalModulesDFG: ExternalModulesDFG, val devirtualizationAnalysisResult: Devirtualization.AnalysisResult, val nonDevirtualizedCallSitesUnfoldFactor: Int ) { private val devirtualizedCallSites = devirtualizationAnalysisResult.devirtualizedCallSites private fun DataFlowIR.FunctionSymbol.resolved(): DataFlowIR.FunctionSymbol { if (this is DataFlowIR.FunctionSymbol.External) return externalModulesDFG.publicFunctions[this.hash] ?: this return this } private val directEdges = mutableMapOf<DataFlowIR.FunctionSymbol.Declared, CallGraphNode>() private val reversedEdges = mutableMapOf<DataFlowIR.FunctionSymbol.Declared, MutableList<DataFlowIR.FunctionSymbol.Declared>>() private val externalRootFunctions = mutableListOf<DataFlowIR.FunctionSymbol>() private val callGraph = CallGraph(directEdges, reversedEdges, externalRootFunctions) private data class HandleFunctionParams(val caller: DataFlowIR.FunctionSymbol.Declared?, val calleeFunction: DataFlowIR.Function) private val functionStack = mutableListOf<HandleFunctionParams>() fun build(): CallGraph { val rootSet = Devirtualization.computeRootSet(context, moduleDFG, externalModulesDFG) for (symbol in rootSet) { val function = moduleDFG.functions[symbol] if (function == null) externalRootFunctions.add(symbol) else functionStack.push(HandleFunctionParams(null, function)) } while (functionStack.isNotEmpty()) { val (caller, calleeFunction) = functionStack.pop() val callee = calleeFunction.symbol as DataFlowIR.FunctionSymbol.Declared val gotoCallee = !directEdges.containsKey(callee) if (gotoCallee) addNode(callee) if (caller != null) callGraph.addReversedEdge(caller, callee) if (gotoCallee) handleFunction(callee, calleeFunction) } return callGraph } private fun addNode(symbol: DataFlowIR.FunctionSymbol.Declared) { directEdges[symbol] = CallGraphNode(callGraph, symbol) reversedEdges[symbol] = mutableListOf() } private inline fun DataFlowIR.FunctionBody.forEachCallSite(block: (DataFlowIR.Node.Call) -> Unit): Unit = forEachNonScopeNode { node -> when (node) { is DataFlowIR.Node.Call -> block(node) is DataFlowIR.Node.Singleton -> node.constructor?.let { block(DataFlowIR.Node.Call(it, emptyList(), node.type, null)) } is DataFlowIR.Node.ArrayRead -> block(DataFlowIR.Node.Call( callee = node.callee, arguments = listOf(node.array, node.index), returnType = node.type, irCallSite = null) ) is DataFlowIR.Node.ArrayWrite -> block(DataFlowIR.Node.Call( callee = node.callee, arguments = listOf(node.array, node.index, node.value), returnType = moduleDFG.symbolTable.mapType(context.irBuiltIns.unitType), irCallSite = null) ) is DataFlowIR.Node.FunctionReference -> block(DataFlowIR.Node.Call( callee = node.symbol, arguments = emptyList(), returnType = node.symbol.returnParameter.type, irCallSite = null )) else -> { } } } private fun staticCall(caller: DataFlowIR.FunctionSymbol.Declared, call: DataFlowIR.Node.Call, callee: DataFlowIR.FunctionSymbol) { val resolvedCallee = callee.resolved() val callSite = CallGraphNode.CallSite(call, false, resolvedCallee) val function = moduleDFG.functions[resolvedCallee] callGraph.addEdge(caller, callSite) if (function != null) functionStack.push(HandleFunctionParams(caller, function)) } private fun handleFunction(symbol: DataFlowIR.FunctionSymbol.Declared, function: DataFlowIR.Function) { val body = function.body body.forEachCallSite { call -> val devirtualizedCallSite = (call as? DataFlowIR.Node.VirtualCall)?.let { devirtualizedCallSites[it] } when { call !is DataFlowIR.Node.VirtualCall -> staticCall(symbol, call, call.callee) devirtualizedCallSite != null -> { devirtualizedCallSite.possibleCallees.forEach { staticCall(symbol, call, it.callee) } } call.receiverType == DataFlowIR.Type.Virtual -> { // Skip callsite. This can only be for invocations Any's methods on instances of ObjC classes. } else -> { // Callsite has not been devirtualized - conservatively assume the worst: // any inheritor of the receiver type is possible here. val typeHierarchy = devirtualizationAnalysisResult.typeHierarchy val allPossibleCallees = mutableListOf<DataFlowIR.FunctionSymbol>() typeHierarchy.inheritorsOf(call.receiverType as DataFlowIR.Type.Declared).forEachBit { val receiverType = typeHierarchy.allTypes[it] if (receiverType.isAbstract) return@forEachBit // TODO: Unconservative way - when we can use it? //.filter { devirtualizationAnalysisResult.instantiatingClasses.contains(it) } val actualCallee = when (call) { is DataFlowIR.Node.VtableCall -> receiverType.vtable[call.calleeVtableIndex] is DataFlowIR.Node.ItableCall -> receiverType.itable[call.calleeHash]!! else -> error("Unreachable") } allPossibleCallees.add(actualCallee) } if (allPossibleCallees.size <= nonDevirtualizedCallSitesUnfoldFactor) allPossibleCallees.forEach { staticCall(symbol, call, it) } else { val callSite = CallGraphNode.CallSite(call, true, call.callee) callGraph.addEdge(symbol, callSite) } } } } } }
apache-2.0
16ebd088dbe29af268356ad4d7a51337
44.81592
135
0.608927
5.419659
false
false
false
false
androidx/androidx
buildSrc/private/src/main/kotlin/androidx/build/dackka/GenerateMetadataTask.kt
3
3898
/* * 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.build.dackka import com.google.gson.Gson import com.google.gson.GsonBuilder import java.io.File import java.io.FileWriter import java.util.zip.ZipFile import org.gradle.api.DefaultTask import org.gradle.api.artifacts.component.ComponentArtifactIdentifier import org.gradle.api.artifacts.component.ModuleComponentIdentifier import org.gradle.api.file.RegularFileProperty import org.gradle.api.provider.ListProperty import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import org.gradle.internal.component.external.model.DefaultModuleComponentIdentifier @CacheableTask abstract class GenerateMetadataTask : DefaultTask() { /** * List of artifacts to convert to JSON */ @Input abstract fun getArtifactIds(): ListProperty<ComponentArtifactIdentifier> /** * List of files corresponding to artifacts in [getArtifactIds] */ @InputFiles @PathSensitive(PathSensitivity.NONE) abstract fun getArtifactFiles(): ListProperty<File> /** * Location of the generated JSON file */ @get:OutputFile abstract val destinationFile: RegularFileProperty @TaskAction fun generate() { val entries = arrayListOf<MetadataEntry>() val artifactIds = getArtifactIds().get() val artifactFiles = getArtifactFiles().get() for (i in 0 until artifactIds.size) { val id = artifactIds[i] val file = artifactFiles[i] // Only process artifact if it can be cast to ModuleComponentIdentifier. // // In practice, metadata is generated only for docs-public and not docs-tip-of-tree // (where id.componentIdentifier is DefaultProjectComponentIdentifier). if (id.componentIdentifier !is DefaultModuleComponentIdentifier) continue // Created https://github.com/gradle/gradle/issues/21415 to track surfacing // group / module / version in ComponentIdentifier val componentId = (id.componentIdentifier as ModuleComponentIdentifier) // Fetch the list of files contained in the .jar file val fileList = ZipFile(file).entries().toList().map { it.name } val entry = MetadataEntry( groupId = componentId.group, artifactId = componentId.module, releaseNotesUrl = generateReleaseNotesUrl(componentId.group), jarContents = fileList ) entries.add(entry) } val gson = if (DEBUG) { GsonBuilder().setPrettyPrinting().create() } else { Gson() } val writer = FileWriter(destinationFile.get().toString()) gson.toJson(entries, writer) writer.close() } private fun generateReleaseNotesUrl(groupId: String): String { val library = groupId.removePrefix("androidx.").replace(".", "-") return "https://developer.android.com/jetpack/androidx/releases/$library" } companion object { private const val DEBUG = false } }
apache-2.0
240a664032171a736a561275a2f94875
34.436364
95
0.691124
4.673861
false
false
false
false
kamerok/Orny
app/src/main/kotlin/com/kamer/orny/presentation/main/MainViewModelImpl.kt
1
922
package com.kamer.orny.presentation.main import android.arch.lifecycle.MutableLiveData import com.kamer.orny.interaction.main.MainInteractor import com.kamer.orny.presentation.core.BaseViewModel import timber.log.Timber import javax.inject.Inject class MainViewModelImpl @Inject constructor( val mainRouter: MainRouter, val interactor: MainInteractor ) : BaseViewModel(), MainViewModel { override val updateProgressStream = MutableLiveData<Boolean>().apply { value = false } init { interactor .updatePage() .disposeOnDestroy() .doOnSubscribe { updateProgressStream.value = true } .doFinally { updateProgressStream.value = false } .subscribe({}, { Timber.e(it) }) } override fun addExpense() = mainRouter.openAddExpenseScreen() override fun openSettings() = mainRouter.openSettingsScreen() }
apache-2.0
9c362b6f35e485ddc47bd6af93e03de6
29.766667
90
0.691974
4.930481
false
false
false
false
Yusspy/Jolt-Sphere
core/src/org/joltsphere/misc/EllipseFixture.kt
1
5684
package org.joltsphere.misc import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.physics.box2d.Body import com.badlogic.gdx.physics.box2d.FixtureDef import com.badlogic.gdx.physics.box2d.PolygonShape class EllipseFixture { companion object { private var hW: Float = 0.toFloat() private var hH: Float = 0.toFloat() /**Creates an ellipse, this is a convenience method that creates a fixture defintion based off of the paramaters. */ fun createEllipseFixtures(body: Body, density: Float, restitution: Float, friction: Float, halfWidth: Float, halfHeight: Float, userData: String): Body { val fdef = FixtureDef() fdef.restitution = restitution fdef.density = density fdef.friction = friction return createEllipseFixtures(body, fdef, halfWidth, halfHeight, userData) } /**Creates four fixtures in the shape of an ellipse based off of these paramaters */ fun createEllipseFixtures(body: Body, fdef: FixtureDef, halfWidth: Float, halfHeight: Float, userData: String): Body { // if the ellipse is long and skinny, then for approximation, the ellipse is rotated then rotated back var shouldRotate = false if (halfWidth > halfHeight) { hW = halfWidth hH = halfHeight } else { hH = halfWidth hW = halfHeight shouldRotate = true } val poly = PolygonShape() val perimeter = (2.0 * Math.PI * Math.sqrt((Math.pow(hW.toDouble(), 2.0) + Math.pow(hH.toDouble(), 2.0)) / 2f)).toFloat() // perimeter of the ellipse val faceLength = perimeter / 4f / 6f // splits into 4 quadrants, then into 6 faces val v = arrayOfNulls<Vector2>(8) // max 8 vertices in a box2d polygon v[0] = Vector2(0f, 0f) // sets first point at center v[1] = Vector2(hW, 0f) // set the second point on half the width var prevX = hW var prevY = 0f // previous point on ellipse in loop var x = 0f var y = 0f for (i in 1..5) { // for the next 5 points val dtl = 10f // detail of calculations val iterationSize = faceLength / dtl // the x axis iteration length, set to face length because it will not exceed the hypotenuse val tinyIterationSize = iterationSize / dtl // once large scale iteration finds an approximated point, the tiny iteration loop does it again to be more precise // this algorithim would take the approximation power requirement down from dtl^2 to dtl*2 which is pretty great var prevTempX = 0f var j = 1 while (j <= dtl) { val currentW = iterationSize * j // gets current width of triangle val currentH = ellipseFunction(prevX - currentW) - prevY // current height of face triangle if (Math.hypot(currentW.toDouble(), currentH.toDouble()) > faceLength) break // discontinues all code within this for loop prevTempX = prevX - currentW // the coordinates of this iteration, if still looping j++ } var n = 1 while (n <= dtl) { val currentW = prevX - prevTempX + tinyIterationSize * n // gets current precise width of the face triangle val currentH = ellipseFunction(prevTempX - tinyIterationSize * n) - prevY // current precise height of the face triangle if (Math.hypot(currentW.toDouble(), currentH.toDouble()) > faceLength) break // hypotenuse of imaginary triangle has exceeded facelength, so it can stop now x = prevX - currentW y = ellipseFunction(x) // sets the coordinates of the new face every loop n++ } prevX = x prevY = y // set the new starting point for the next vertex approximation v[i + 1] = Vector2(x, y) } v[7] = Vector2(0f, hH) if (shouldRotate) { // rotates all the vectors back to their appropriate loacation for (i in 0..7) { v[i] = Vector2(v[i]!!.rotate90(1)) } } poly.set(v) fdef.shape = poly body.createFixture(fdef).userData = userData // top right fixture for (i in 0..7) { v[i] = Vector2(v[i]!!.x * -1, v[i]!!.y) // flips each vector across the x axis } poly.set(v) fdef.shape = poly body.createFixture(fdef).userData = userData // top left fixture for (i in 0..7) { v[i] = Vector2(v[i]!!.x, v[i]!!.y * -1) // flips the previous fixture across the y axis } poly.set(v) fdef.shape = poly body.createFixture(fdef).userData = userData // bottom left fixture for (i in 0..7) { v[i] = Vector2(v[i]!!.x * -1, v[i]!!.y) // flips the previous vector across the x axis } poly.set(v) fdef.shape = poly body.createFixture(fdef).userData = userData // bottom right fixture poly.dispose() return body } private fun ellipseFunction(x: Float): Float { return Math.sqrt(Math.pow(hH.toDouble(), 2.0) * (1 - Math.pow(x.toDouble(), 2.0) / Math.pow(hW.toDouble(), 2.0))).toFloat() // function for half an ellipse } } }
agpl-3.0
26d8309b0987e20cfcd5bc74c54bdec2
45.219512
176
0.564215
4.241791
false
false
false
false
androidx/androidx
camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/adapter/SupportedSurfaceCombination.kt
3
40688
/* * 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.adapter import android.content.Context import android.graphics.Point import android.graphics.SurfaceTexture import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.params.StreamConfigurationMap import android.hardware.display.DisplayManager import android.media.CamcorderProfile import android.media.MediaRecorder import android.os.Build import android.util.Rational import android.util.Size import android.view.Display import android.view.Surface import androidx.annotation.RequiresApi import androidx.camera.camera2.pipe.CameraMetadata import androidx.camera.core.AspectRatio import androidx.camera.core.Logger import androidx.camera.core.impl.AttachedSurfaceInfo import androidx.camera.core.impl.CamcorderProfileProxy import androidx.camera.core.impl.ImageFormatConstants import androidx.camera.core.impl.ImageOutputConfig import androidx.camera.core.impl.SurfaceCombination import androidx.camera.core.impl.SurfaceConfig import androidx.camera.core.impl.SurfaceSizeDefinition import androidx.camera.core.impl.UseCaseConfig import androidx.camera.core.impl.utils.AspectRatioUtil import androidx.camera.core.impl.utils.AspectRatioUtil.CompareAspectRatiosByMappingAreaInFullFovAspectRatioSpace import androidx.camera.core.impl.utils.AspectRatioUtil.hasMatchingAspectRatio import androidx.camera.core.impl.utils.CameraOrientationUtil import androidx.camera.core.impl.utils.CompareSizesByArea import androidx.camera.core.internal.utils.SizeUtil import androidx.camera.core.internal.utils.SizeUtil.RESOLUTION_1080P import androidx.camera.core.internal.utils.SizeUtil.RESOLUTION_480P import androidx.camera.core.internal.utils.SizeUtil.RESOLUTION_VGA import androidx.core.util.Preconditions import java.util.Arrays import java.util.Collections /** * Camera device supported surface configuration combinations * * <p>{@link android.hardware.camera2.CameraDevice#createCaptureSession} defines the default * guaranteed stream combinations for different hardware level devices. It defines what combination * of surface configuration type and size pairs can be supported for different hardware level camera * devices. This structure is used to store a list of surface combinations that are guaranteed to * support for this camera device. */ @Suppress("DEPRECATION") @RequiresApi(21) // TODO(b/243963130): Remove and replace with annotation on package-info.java // TODO(b/200306659): Remove and replace with annotation on package-info.java class SupportedSurfaceCombination( context: Context, cameraMetadata: CameraMetadata, cameraId: String, camcorderProfileProviderAdapter: CamcorderProfileProviderAdapter ) { private val cameraMetadata = cameraMetadata private val cameraId = cameraId private val camcorderProfileProviderAdapter = camcorderProfileProviderAdapter private val hardwareLevel = cameraMetadata[CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL] ?: CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY private val isSensorLandscapeResolution = isSensorLandscapeResolution(cameraMetadata) private val surfaceCombinations: MutableList<SurfaceCombination> = ArrayList() private val outputSizesCache: MutableMap<Int, Array<Size>> = HashMap() private var isRawSupported = false private var isBurstCaptureSupported = false internal lateinit var surfaceSizeDefinition: SurfaceSizeDefinition private val displayManager: DisplayManager = (context.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager) private val activeArraySize = cameraMetadata[CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE] init { checkCapabilities() generateSupportedCombinationList() generateSurfaceSizeDefinition() } /** * Check whether the input surface configuration list is under the capability of any combination * of this object. * * @param surfaceConfigList the surface configuration list to be compared * @return the check result that whether it could be supported */ fun checkSupported(surfaceConfigList: List<SurfaceConfig>): Boolean { for (surfaceCombination in surfaceCombinations) { if (surfaceCombination.isSupported(surfaceConfigList)) { return true } } return false } /** * Transform to a SurfaceConfig object with image format and size info * * @param imageFormat the image format info for the surface configuration object * @param size the size info for the surface configuration object * @return new [SurfaceConfig] object */ fun transformSurfaceConfig(imageFormat: Int, size: Size): SurfaceConfig { return SurfaceConfig.transformSurfaceConfig(imageFormat, size, surfaceSizeDefinition) } /** * Finds the suggested resolutions of the newly added UseCaseConfig. * * @param existingSurfaces the existing surfaces. * @param newUseCaseConfigs newly added UseCaseConfig. * @return the suggested resolutions, which is a mapping from UseCaseConfig to the suggested * resolution. * @throws IllegalArgumentException if the suggested solution for newUseCaseConfigs cannot be * found. This may be due to no available output size or no * available surface combination. */ fun getSuggestedResolutions( existingSurfaces: List<AttachedSurfaceInfo>, newUseCaseConfigs: List<UseCaseConfig<*>> ): Map<UseCaseConfig<*>, Size> { refreshPreviewSize() val surfaceConfigs: MutableList<SurfaceConfig> = ArrayList() for (scc in existingSurfaces) { surfaceConfigs.add(scc.surfaceConfig) } // Use the small size (640x480) for new use cases to check whether there is any possible // supported combination first for (useCaseConfig in newUseCaseConfigs) { surfaceConfigs.add( SurfaceConfig.transformSurfaceConfig( useCaseConfig.inputFormat, RESOLUTION_VGA, surfaceSizeDefinition ) ) } if (!checkSupported(surfaceConfigs)) { throw java.lang.IllegalArgumentException( "No supported surface combination is found for camera device - Id : " + cameraId + ". May be attempting to bind too many use cases. " + "Existing surfaces: " + existingSurfaces + " New configs: " + newUseCaseConfigs ) } // Get the index order list by the use case priority for finding stream configuration val useCasesPriorityOrder: List<Int> = getUseCasesPriorityOrder( newUseCaseConfigs ) val supportedOutputSizesList: MutableList<List<Size>> = ArrayList() // Collect supported output sizes for all use cases for (index in useCasesPriorityOrder) { val supportedOutputSizes: List<Size> = getSupportedOutputSizes( newUseCaseConfigs[index] ) supportedOutputSizesList.add(supportedOutputSizes) } // Get all possible size arrangements val allPossibleSizeArrangements: List<List<Size>> = getAllPossibleSizeArrangements( supportedOutputSizesList ) var suggestedResolutionsMap: Map<UseCaseConfig<*>, Size>? = null // Transform use cases to SurfaceConfig list and find the first (best) workable combination for (possibleSizeList in allPossibleSizeArrangements) { // Attach SurfaceConfig of original use cases since it will impact the new use cases val surfaceConfigList: MutableList<SurfaceConfig> = ArrayList() for (sc in existingSurfaces) { surfaceConfigList.add(sc.surfaceConfig) } // Attach SurfaceConfig of new use cases for (i in possibleSizeList.indices) { val size = possibleSizeList[i] val newUseCase = newUseCaseConfigs[useCasesPriorityOrder[i]] surfaceConfigList.add( SurfaceConfig.transformSurfaceConfig( newUseCase.inputFormat, size, surfaceSizeDefinition ) ) } // Check whether the SurfaceConfig combination can be supported if (checkSupported(surfaceConfigList)) { suggestedResolutionsMap = HashMap() for (useCaseConfig in newUseCaseConfigs) { suggestedResolutionsMap.put( useCaseConfig, possibleSizeList[useCasesPriorityOrder.indexOf( newUseCaseConfigs.indexOf(useCaseConfig) )] ) } break } } if (suggestedResolutionsMap == null) { throw java.lang.IllegalArgumentException( "No supported surface combination is found for camera device - Id : " + cameraId + " and Hardware level: " + hardwareLevel + ". May be the specified resolution is too large and not supported." + " Existing surfaces: " + existingSurfaces + " New configs: " + newUseCaseConfigs ) } return suggestedResolutionsMap } // Utility classes and methods: // ********************************************************************************************* /** * Refresh Preview Size based on current display configurations. */ private fun refreshPreviewSize() { val previewSize: Size = calculatePreviewSize() surfaceSizeDefinition = SurfaceSizeDefinition.create( surfaceSizeDefinition.analysisSize, previewSize, surfaceSizeDefinition.recordSize ) } /** * Check the device's available capabilities. */ private fun checkCapabilities() { val availableCapabilities: IntArray? = cameraMetadata.get<IntArray>(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES) availableCapabilities?.apply { isRawSupported = contains(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW) isBurstCaptureSupported = contains(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_BURST_CAPTURE) } } /** * Generate the supported combination list from guaranteed configurations tables. */ private fun generateSupportedCombinationList() { surfaceCombinations.addAll( GuaranteedConfigurationsUtil.generateSupportedCombinationList( hardwareLevel, isRawSupported, isBurstCaptureSupported ) ) // TODO(b/246609101): ExtraSupportedSurfaceCombinationsQuirk is supposed to be here to add additional // surface combinations to the list } /** * Generation the size definition for VGA, PREVIEW, and RECORD. */ private fun generateSurfaceSizeDefinition() { val vgaSize = Size(640, 480) val previewSize: Size = calculatePreviewSize() val recordSize: Size = getRecordSize() surfaceSizeDefinition = SurfaceSizeDefinition.create(vgaSize, previewSize, recordSize) } /** * RECORD refers to the camera device's maximum supported recording resolution, as determined by * CamcorderProfile. */ private fun getRecordSize(): Size { val cameraId: Int = try { this.cameraId.toInt() } catch (e: NumberFormatException) { // The camera Id is not an integer because the camera may be a removable device. Use // StreamConfigurationMap to determine the RECORD size. return getRecordSizeFromStreamConfigurationMap() } var profile: CamcorderProfileProxy? = null if (camcorderProfileProviderAdapter.hasProfile(cameraId)) { profile = camcorderProfileProviderAdapter.get(cameraId) } return if (profile != null) { Size(profile.videoFrameWidth, profile.videoFrameHeight) } else getRecordSizeByHasProfile() } /** * Obtains the stream configuration map from camera meta data. */ private fun getStreamConfigurationMap(): StreamConfigurationMap { return cameraMetadata[CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP] ?: throw IllegalArgumentException("Cannot retrieve SCALER_STREAM_CONFIGURATION_MAP") } /** * Return the maximum supported video size for cameras using data from the stream * configuration map. * * @return Maximum supported video size. */ private fun getRecordSizeFromStreamConfigurationMap(): Size { val map: StreamConfigurationMap = getStreamConfigurationMap() val videoSizeArr = map.getOutputSizes( MediaRecorder::class.java ) ?: return RESOLUTION_480P Arrays.sort(videoSizeArr, CompareSizesByArea(true)) for (size in videoSizeArr) { // Returns the largest supported size under 1080P if (size.width <= RESOLUTION_1080P.width && size.height <= RESOLUTION_1080P.height ) { return size } } return RESOLUTION_480P } /** * Return the maximum supported video size for cameras by * [CamcorderProfile.hasProfile]. * * @return Maximum supported video size. */ private fun getRecordSizeByHasProfile(): Size { var recordSize: Size = RESOLUTION_480P var profile: CamcorderProfileProxy? = null // Check whether 4KDCI, 2160P, 2K, 1080P, 720P, 480P (sorted by size) are supported by // CamcorderProfile if (camcorderProfileProviderAdapter.hasProfile(CamcorderProfile.QUALITY_4KDCI)) { profile = camcorderProfileProviderAdapter.get(CamcorderProfile.QUALITY_4KDCI) } else if (camcorderProfileProviderAdapter.hasProfile(CamcorderProfile.QUALITY_2160P)) { profile = camcorderProfileProviderAdapter.get(CamcorderProfile.QUALITY_2160P) } else if (camcorderProfileProviderAdapter.hasProfile(CamcorderProfile.QUALITY_2K)) { profile = camcorderProfileProviderAdapter.get(CamcorderProfile.QUALITY_2K) } else if (camcorderProfileProviderAdapter.hasProfile(CamcorderProfile.QUALITY_1080P)) { profile = camcorderProfileProviderAdapter.get(CamcorderProfile.QUALITY_1080P) } else if (camcorderProfileProviderAdapter.hasProfile(CamcorderProfile.QUALITY_720P)) { profile = camcorderProfileProviderAdapter.get(CamcorderProfile.QUALITY_720P) } else if (camcorderProfileProviderAdapter.hasProfile(CamcorderProfile.QUALITY_480P)) { profile = camcorderProfileProviderAdapter.get(CamcorderProfile.QUALITY_480P) } if (profile != null) { recordSize = Size(profile.videoFrameWidth, profile.videoFrameHeight) } return recordSize } /** * Check if the size obtained from sensor info indicates landscape mode. */ private fun isSensorLandscapeResolution(cameraMetadata: CameraMetadata): Boolean { val pixelArraySize: Size? = cameraMetadata.get<Size>(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE) // Make the default value is true since usually the sensor resolution is landscape. return if (pixelArraySize != null) pixelArraySize.width >= pixelArraySize.height else true } /** * Calculates the size for preview. If the max size is larger than 1080p, use 1080p. */ @SuppressWarnings("deprecation") /* getRealSize */ private fun calculatePreviewSize(): Size { val displaySize = Point() val display: Display = getMaxSizeDisplay() 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 > RESOLUTION_1080P.width * RESOLUTION_1080P.height ) { displayViewSize = RESOLUTION_1080P } // TODO(b/245619094): Use ExtraCroppingQuirk to potentially override this with select // resolution return displayViewSize } /** * Retrieves the display which has the max size among all displays. */ private fun getMaxSizeDisplay(): Display { val displays: Array<Display> = displayManager.displays if (displays.size == 1) { return displays[0] } var maxDisplay: Display? = null var maxDisplaySize = -1 for (display: Display in displays) { if (display.state != Display.STATE_OFF) { val displaySize = Point() display.getRealSize(displaySize) if (displaySize.x * displaySize.y > maxDisplaySize) { maxDisplaySize = displaySize.x * displaySize.y maxDisplay = display } } } if (maxDisplay == null) { throw IllegalArgumentException( "No display can be found from the input display manager!" ) } return maxDisplay } /** * Once the stream resource is occupied by one use case, it will impact the other use cases. * Therefore, we need to define the priority for stream resource usage. For the use cases * with the higher priority, we will try to find the best one for them in priority as * possible. */ private fun getUseCasesPriorityOrder(newUseCaseConfigs: List<UseCaseConfig<*>>): List<Int> { val priorityOrder: MutableList<Int> = ArrayList() val priorityValueList: MutableList<Int> = ArrayList() for (config in newUseCaseConfigs) { val priority = config.getSurfaceOccupancyPriority(0) if (!priorityValueList.contains(priority)) { priorityValueList.add(priority) } } priorityValueList.sort() // Reverse the priority value list in descending order since larger value means higher // priority priorityValueList.reverse() for (priorityValue in priorityValueList) { for (config in newUseCaseConfigs) { if (priorityValue == config.getSurfaceOccupancyPriority(0)) { priorityOrder.add(newUseCaseConfigs.indexOf(config)) } } } return priorityOrder } /** * Get max supported output size for specific image format * * @param imageFormat the image format info * @return the max supported output size for the image format */ internal fun getMaxOutputSizeByFormat(imageFormat: Int): Size { val outputSizes = getAllOutputSizesByFormat(imageFormat) return Collections.max(listOf(*outputSizes), CompareSizesByArea()) } /** * Get all output sizes for a given image format. */ private fun doGetAllOutputSizesByFormat(imageFormat: Int): Array<Size> { val map: StreamConfigurationMap = getStreamConfigurationMap() val outputSizes = if (Build.VERSION.SDK_INT < 23 && imageFormat == ImageFormatConstants.INTERNAL_DEFINED_IMAGE_FORMAT_PRIVATE ) { // This is a little tricky that 0x22 that is internal defined in // StreamConfigurationMap.java to be equal to ImageFormat.PRIVATE that is public // after Android level 23 but not public in Android L. Use {@link SurfaceTexture} // or {@link MediaCodec} will finally mapped to 0x22 in StreamConfigurationMap to // retrieve the output sizes information. map.getOutputSizes(SurfaceTexture::class.java) } else { map.getOutputSizes(imageFormat) } // TODO(b/244477758): Exclude problematic sizes // Sort the output sizes. The Comparator result must be reversed to have a descending order // result. Arrays.sort(outputSizes, CompareSizesByArea(true)) return outputSizes } /** * Retrieves the output size associated with the given format. */ private fun getAllOutputSizesByFormat(imageFormat: Int): Array<Size> { var outputs: Array<Size>? = outputSizesCache[imageFormat] if (outputs == null) { outputs = doGetAllOutputSizesByFormat(imageFormat) outputSizesCache[imageFormat] = outputs } return outputs } /** * Retrieves the sorted customized supported resolutions from the given config */ private fun getCustomizedSupportSizesFromConfig( imageFormat: Int, config: ImageOutputConfig ): Array<Size>? { var outputSizes: Array<Size>? = null // Try to retrieve customized supported resolutions from config. val formatResolutionsPairList = config.getSupportedResolutions(null) if (formatResolutionsPairList != null) { for (formatResolutionPair in formatResolutionsPairList) { if (formatResolutionPair.first == imageFormat) { outputSizes = formatResolutionPair.second break } } } if (outputSizes != null) { // TODO(b/244477758): Exclude problematic sizes // Sort the output sizes. The Comparator result must be reversed to have a descending // order result. Arrays.sort(outputSizes, CompareSizesByArea(true)) } return outputSizes } /** * Flips the size if rotation is needed. */ private fun flipSizeByRotation(size: Size?, targetRotation: Int): Size? { var outputSize = size // Calibrates the size with the display and sensor rotation degrees values. if (size != null && isRotationNeeded(targetRotation)) { outputSize = Size(/* width= */size.height, /* height= */size.width) } return outputSize } /** * Determines whether rotation needs to be done on target rotation. */ private fun isRotationNeeded(targetRotation: Int): Boolean { val sensorOrientation: Int? = cameraMetadata[CameraCharacteristics.SENSOR_ORIENTATION] Preconditions.checkNotNull( sensorOrientation, "Camera HAL in bad state, unable to " + "retrieve the SENSOR_ORIENTATION" ) val relativeRotationDegrees = CameraOrientationUtil.surfaceRotationToDegrees(targetRotation) // Currently this assumes that a back-facing camera is always opposite to the screen. // This may not be the case for all devices, so in the future we may need to handle that // scenario. val lensFacing: Int? = cameraMetadata[CameraCharacteristics.LENS_FACING] Preconditions.checkNotNull( lensFacing, "Camera HAL in bad state, unable to retrieve the " + "LENS_FACING" ) val isOppositeFacingScreen = CameraCharacteristics.LENS_FACING_BACK == lensFacing val sensorRotationDegrees = CameraOrientationUtil.getRelativeImageRotation( relativeRotationDegrees, sensorOrientation!!, isOppositeFacingScreen ) return sensorRotationDegrees == 90 || sensorRotationDegrees == 270 } /** * Obtains the target size from ImageOutputConfig. */ private fun getTargetSize(imageOutputConfig: ImageOutputConfig): Size? { val targetRotation = imageOutputConfig.getTargetRotation(Surface.ROTATION_0) // Calibrate targetSize by the target rotation value. var targetSize = imageOutputConfig.getTargetResolution(null) targetSize = flipSizeByRotation(targetSize, targetRotation) return targetSize } /** * Returns the aspect ratio group key of the target size when grouping the input resolution * candidate list. * * The resolution candidate list will be grouped with mod 16 consideration. Therefore, we * also need to consider the mod 16 factor to find which aspect ratio of group the target size * might be put in. So that sizes of the group will be selected to use in the highest priority. */ private fun getAspectRatioGroupKeyOfTargetSize( targetSize: Size?, resolutionCandidateList: List<Size> ): Rational? { if (targetSize == null) { return null } val aspectRatios = getResolutionListGroupingAspectRatioKeys( resolutionCandidateList ) aspectRatios.forEach { if (hasMatchingAspectRatio(targetSize, it)) { return it } } return Rational(targetSize.width, targetSize.height) } /** * Returns the grouping aspect ratio keys of the input resolution list. * * Some sizes might be mod16 case. When grouping, those sizes will be grouped into an * existing aspect ratio group if the aspect ratio can match by the mod16 rule. */ private fun getResolutionListGroupingAspectRatioKeys( resolutionCandidateList: List<Size> ): List<Rational> { val aspectRatios: MutableList<Rational> = mutableListOf() // Adds the default 4:3 and 16:9 items first to avoid their mod16 sizes to create // additional items. aspectRatios.add(AspectRatioUtil.ASPECT_RATIO_4_3) aspectRatios.add(AspectRatioUtil.ASPECT_RATIO_16_9) // Tries to find the aspect ratio which the target size belongs to. resolutionCandidateList.forEach { size -> val newRatio = Rational(size.width, size.height) var aspectRatioFound = aspectRatios.contains(newRatio) // The checking size might be a mod16 size which can be mapped to an existing aspect // ratio group. if (!aspectRatioFound) { var hasMatchingAspectRatio = false aspectRatios.forEach loop@{ aspectRatio -> if (hasMatchingAspectRatio(size, aspectRatio)) { hasMatchingAspectRatio = true return@loop } } if (!hasMatchingAspectRatio) { aspectRatios.add(newRatio) } } } return aspectRatios } /** * Returns the target aspect ratio value corrected by quirks. * * The final aspect ratio is determined by the following order: * 1. The aspect ratio returned by TargetAspectRatio quirk (not implemented yet). * 2. The use case's original aspect ratio if TargetAspectRatio quirk returns RATIO_ORIGINAL * and the use case has target aspect ratio setting. * 3. The aspect ratio of use case's target size setting if TargetAspectRatio quirk returns * RATIO_ORIGINAL and the use case has no target aspect ratio but has target size setting. * * @param imageOutputConfig the image output config of the use case. * @param resolutionCandidateList the resolution candidate list which will be used to * determine the aspect ratio by target size when target * aspect ratio setting is not set. */ private fun getTargetAspectRatio( imageOutputConfig: ImageOutputConfig, resolutionCandidateList: List<Size> ): Rational? { var outputRatio: Rational? = null // TODO(b/245622117) Get the corrected aspect ratio from quirks instead of always using // TargetAspectRatio.RATIO_ORIGINAL if (imageOutputConfig.hasTargetAspectRatio()) { when (@AspectRatio.Ratio val aspectRatio = imageOutputConfig.targetAspectRatio) { AspectRatio.RATIO_4_3 -> outputRatio = if (isSensorLandscapeResolution) AspectRatioUtil.ASPECT_RATIO_4_3 else AspectRatioUtil.ASPECT_RATIO_3_4 AspectRatio.RATIO_16_9 -> outputRatio = if (isSensorLandscapeResolution) AspectRatioUtil.ASPECT_RATIO_16_9 else AspectRatioUtil.ASPECT_RATIO_9_16 else -> Logger.e( TAG, "Undefined target aspect ratio: $aspectRatio" ) } } else { // The legacy resolution API will use the aspect ratio of the target size to // be the fallback target aspect ratio value when the use case has no target // aspect ratio setting. val targetSize = getTargetSize(imageOutputConfig) if (targetSize != null) { outputRatio = getAspectRatioGroupKeyOfTargetSize( targetSize, resolutionCandidateList ) } } return outputRatio } /** * Removes unnecessary sizes by target size. * * * If the target resolution is set, a size that is equal to or closest to the target * resolution will be selected. If the list includes more than one size equal to or larger * than the target resolution, only one closest size needs to be kept. The other larger sizes * can be removed so that they won't be selected to use. * * @param supportedSizesList The list should have been sorted in descending order. * @param targetSize The target size used to remove unnecessary sizes. */ private fun removeSupportedSizesByTargetSize( supportedSizesList: MutableList<Size>?, targetSize: Size ) { if (supportedSizesList == null || supportedSizesList.isEmpty()) { return } var indexBigEnough = -1 val removeSizes: MutableList<Size> = ArrayList() // Get the index of the item that is equal to or closest to the target size. for (i in supportedSizesList.indices) { val outputSize = supportedSizesList[i] if (outputSize.width >= targetSize.width && outputSize.height >= targetSize.height) { // New big enough item closer to the target size is found. Adding the previous // one into the sizes list that will be removed. if (indexBigEnough >= 0) { removeSizes.add(supportedSizesList[indexBigEnough]) } indexBigEnough = i } else { break } } // Remove the unnecessary items that are larger than the item closest to the target size. supportedSizesList.removeAll(removeSizes) } /** * Groups sizes together according to their aspect ratios. */ private fun groupSizesByAspectRatio(sizes: List<Size>): Map<Rational, MutableList<Size>> { val aspectRatioSizeListMap: MutableMap<Rational, MutableList<Size>> = mutableMapOf() val aspectRatioKeys = getResolutionListGroupingAspectRatioKeys(sizes) aspectRatioKeys.forEach { aspectRatioSizeListMap[it] = mutableListOf() } sizes.forEach { size -> aspectRatioSizeListMap.keys.forEach { aspectRatio -> // Put the size into all groups that is matched in mod16 condition since a size // may match multiple aspect ratio in mod16 algorithm. if (hasMatchingAspectRatio(size, aspectRatio)) { aspectRatioSizeListMap[aspectRatio]?.add(size) } } } return aspectRatioSizeListMap } /** * Obtains the supported sizes for a given user case. */ internal fun getSupportedOutputSizes(config: UseCaseConfig<*>): List<Size> { val imageFormat = config.inputFormat val imageOutputConfig = config as ImageOutputConfig var outputSizes: Array<Size>? = getCustomizedSupportSizesFromConfig(imageFormat, imageOutputConfig) if (outputSizes == null) { outputSizes = getAllOutputSizesByFormat(imageFormat) } val outputSizeCandidates: MutableList<Size> = ArrayList() var maxSize = imageOutputConfig.getMaxResolution(null) val maxOutputSizeByFormat: Size = getMaxOutputSizeByFormat(imageFormat) // Set maxSize as the max resolution setting or the max supported output size for the // image format, whichever is smaller. if (maxSize == null || SizeUtil.getArea(maxOutputSizeByFormat) < SizeUtil.getArea(maxSize) ) { maxSize = maxOutputSizeByFormat } // Sort the output sizes. The Comparator result must be reversed to have a descending order // result. Arrays.sort(outputSizes, CompareSizesByArea(true)) var targetSize: Size? = getTargetSize(imageOutputConfig) var minSize = RESOLUTION_VGA val defaultSizeArea = SizeUtil.getArea(RESOLUTION_VGA) val maxSizeArea = SizeUtil.getArea(maxSize) // When maxSize is smaller than 640x480, set minSize as 0x0. It means the min size bound // will be ignored. Otherwise, set the minimal size according to min(DEFAULT_SIZE, // TARGET_RESOLUTION). if (maxSizeArea < defaultSizeArea) { minSize = SizeUtil.RESOLUTION_ZERO } else if (targetSize != null && SizeUtil.getArea(targetSize) < defaultSizeArea) { minSize = targetSize } // Filter out the ones that exceed the maximum size and the minimum size. The output // sizes candidates list won't have duplicated items. for (outputSize: Size in outputSizes) { if (SizeUtil.getArea(outputSize) <= SizeUtil.getArea(maxSize) && SizeUtil.getArea(outputSize) >= SizeUtil.getArea(minSize!!) && !outputSizeCandidates.contains(outputSize) ) { outputSizeCandidates.add(outputSize) } } if (outputSizeCandidates.isEmpty()) { throw java.lang.IllegalArgumentException( "Can not get supported output size under supported maximum for the format: " + imageFormat ) } val aspectRatio: Rational? = getTargetAspectRatio(imageOutputConfig, outputSizeCandidates) // Check the default resolution if the target resolution is not set targetSize = targetSize ?: imageOutputConfig.getDefaultResolution(null) var supportedResolutions: MutableList<Size> = ArrayList() var aspectRatioSizeListMap: Map<Rational, MutableList<Size>> if (aspectRatio == null) { // If no target aspect ratio is set, all sizes can be added to the result list // directly. No need to sort again since the source list has been sorted previously. supportedResolutions.addAll(outputSizeCandidates) // If the target resolution is set, use it to remove unnecessary larger sizes. targetSize?.let { removeSupportedSizesByTargetSize(supportedResolutions, it) } } else { // Rearrange the supported size to put the ones with the same aspect ratio in the front // of the list and put others in the end from large to small. Some low end devices may // not able to get an supported resolution that match the preferred aspect ratio. // Group output sizes by aspect ratio. aspectRatioSizeListMap = groupSizesByAspectRatio(outputSizeCandidates) // If the target resolution is set, use it to remove unnecessary larger sizes. if (targetSize != null) { // Remove unnecessary larger sizes from each aspect ratio size list for (key: Rational? in aspectRatioSizeListMap.keys) { removeSupportedSizesByTargetSize(aspectRatioSizeListMap[key], targetSize) } } // Sort the aspect ratio key set by the target aspect ratio. val aspectRatios: List<Rational?> = ArrayList(aspectRatioSizeListMap.keys) val fullFovRatio = if (activeArraySize != null) { Rational(activeArraySize.width(), activeArraySize.height()) } else { null } Collections.sort( aspectRatios, CompareAspectRatiosByMappingAreaInFullFovAspectRatioSpace( aspectRatio, fullFovRatio ) ) // Put available sizes into final result list by aspect ratio distance to target ratio. for (rational: Rational? in aspectRatios) { for (size: Size in aspectRatioSizeListMap[rational]!!) { // A size may exist in multiple groups in mod16 condition. Keep only one in // the final list. if (!supportedResolutions.contains(size)) { supportedResolutions.add(size) } } } } // TODO(b/245619094): Use ExtraCroppingQuirk to insert selected resolutions return supportedResolutions } /** * Given all supported output sizes, lists out all possible size arrangements. */ private fun getAllPossibleSizeArrangements( supportedOutputSizesList: List<List<Size>> ): List<MutableList<Size>> { var totalArrangementsCount = 1 for (supportedOutputSizes in supportedOutputSizesList) { totalArrangementsCount *= supportedOutputSizes.size } // If totalArrangementsCount is 0 means that there may some problem to get // supportedOutputSizes // for some use case require(totalArrangementsCount != 0) { "Failed to find supported resolutions." } val allPossibleSizeArrangements: MutableList<MutableList<Size>> = ArrayList() // Initialize allPossibleSizeArrangements for the following operations for (i in 0 until totalArrangementsCount) { val sizeList: MutableList<Size> = ArrayList() allPossibleSizeArrangements.add(sizeList) } /* * Try to list out all possible arrangements by attaching all possible size of each column * in sequence. We have generated supportedOutputSizesList by the priority order for * different use cases. And the supported outputs sizes for each use case are also arranged * from large to small. Therefore, the earlier size arrangement in the result list will be * the better one to choose if finally it won't exceed the camera device's stream * combination capability. */ var currentRunCount = totalArrangementsCount var nextRunCount = currentRunCount / supportedOutputSizesList[0].size for (currentIndex in supportedOutputSizesList.indices) { val supportedOutputSizes = supportedOutputSizesList[currentIndex] for (i in 0 until totalArrangementsCount) { val surfaceConfigList = allPossibleSizeArrangements[i] surfaceConfigList.add( supportedOutputSizes[i % currentRunCount / nextRunCount] ) } if (currentIndex < supportedOutputSizesList.size - 1) { currentRunCount = nextRunCount nextRunCount = currentRunCount / supportedOutputSizesList[currentIndex + 1].size } } return allPossibleSizeArrangements } companion object { private const val TAG = "SupportedSurfaceCombination" } }
apache-2.0
c4b1e9707c74a3b3fe04d342ca03f85a
42.42476
112
0.650806
5.276618
false
true
false
false
shogo4405/HaishinKit.java
haishinkit/src/main/java/com/haishinkit/graphics/gles/GlKernel.kt
1
10958
package com.haishinkit.graphics.gles import android.content.res.AssetManager import android.opengl.EGL14 import android.opengl.EGLConfig import android.opengl.GLES11Ext import android.opengl.GLES20 import android.util.Size import android.view.Surface import com.haishinkit.graphics.ImageOrientation import com.haishinkit.graphics.ResampleFilter import com.haishinkit.graphics.VideoGravity import com.haishinkit.graphics.filter.DefaultVideoEffect import com.haishinkit.graphics.filter.VideoEffect import com.haishinkit.lang.Utilize import com.haishinkit.util.aspectRatio import com.haishinkit.util.swap import javax.microedition.khronos.opengles.GL10 internal class GlKernel( override var utilizable: Boolean = false ) : Utilize { var surface: Surface? = null set(value) { field = value inputSurfaceWindow.setSurface(value) } var imageOrientation: ImageOrientation = ImageOrientation.UP set(value) { field = value invalidateLayout = true } var videoGravity: VideoGravity = VideoGravity.RESIZE_ASPECT_FILL set(value) { field = value invalidateLayout = true } var extent: Size = Size(0, 0) set(value) { field = value invalidateLayout = true } var resampleFilter: ResampleFilter = ResampleFilter.NEAREST var surfaceRotation: Int = Surface.ROTATION_0 set(value) { field = value invalidateLayout = true } var expectedOrientationSynchronize = true var videoEffect: VideoEffect = DefaultVideoEffect() set(value) { field = value program = shaderLoader.createProgram(videoEffect.name) } var assetManager: AssetManager? = null set(value) { field = value shaderLoader.assetManager = assetManager program = shaderLoader.createProgram(videoEffect.name) } private val inputSurfaceWindow: GlWindowSurface = GlWindowSurface() private val vertexBuffer = GlUtil.createFloatBuffer(VERTECES) private val texCoordBuffer = GlUtil.createFloatBuffer(TEX_COORDS_ROTATION_0) private var invalidateLayout = true private var display = EGL14.EGL_NO_DISPLAY set(value) { field = value inputSurfaceWindow.display = value } private var context = EGL14.EGL_NO_CONTEXT set(value) { field = value inputSurfaceWindow.context = value } private val shaderLoader by lazy { val shaderLoader = GlShaderLoader() shaderLoader.assetManager = assetManager shaderLoader } private var program: GlShaderLoader.Program? = null set(value) { field?.dispose() field = value } override fun setUp() { if (utilizable) return display = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY) if (display === EGL14.EGL_NO_DISPLAY) { throw RuntimeException() } val version = IntArray(2) if (!EGL14.eglInitialize(display, version, 0, version, 1)) { throw RuntimeException() } val config = chooseConfig() ?: return inputSurfaceWindow.config = config context = EGL14.eglCreateContext( display, config, EGL14.EGL_NO_CONTEXT, CONTEXT_ATTRIBUTES, 0 ) GlUtil.checkGlError("eglCreateContext") EGL14.eglMakeCurrent(display, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, context) GLES20.glTexParameteri( GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GL10.GL_TEXTURE_MIN_FILTER, resampleFilter.glValue ) GLES20.glTexParameteri( GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GL10.GL_TEXTURE_MAG_FILTER, resampleFilter.glValue ) GLES20.glTexParameteri( GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE ) GLES20.glTexParameteri( GLES11Ext.GL_TEXTURE_EXTERNAL_OES, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE ) utilizable = true } override fun tearDown() { if (!utilizable) return program = null utilizable = false } fun render(textureId: Int, textureSize: Size, timestamp: Long) { if (invalidateLayout) { layout(textureSize) invalidateLayout = false } val program = program ?: return GLES20.glUseProgram(program.id) GLES20.glVertexAttribPointer( program.texCoordHandle, 2, GLES20.GL_FLOAT, false, 0, texCoordBuffer ) GLES20.glVertexAttribPointer( program.positionHandle, 3, GLES20.GL_FLOAT, false, 0, vertexBuffer ) GlUtil.checkGlError("glVertexAttribPointer") GLES20.glUniform1i(program.textureHandle, 0) GlUtil.checkGlError("glUniform1i") GLES20.glActiveTexture(GLES20.GL_TEXTURE0) GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureId) GlUtil.checkGlError("glBindTexture") GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4) GLES20.glUseProgram(0) GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0) inputSurfaceWindow.setPresentationTime(timestamp) inputSurfaceWindow.swapBuffers() } private fun layout(newTextureSize: Size) { var swapped = if (extent.width < extent.height) { newTextureSize.height < newTextureSize.width } else { newTextureSize.width < newTextureSize.height } var degrees = when (imageOrientation) { ImageOrientation.UP -> 0 ImageOrientation.DOWN -> 180 ImageOrientation.LEFT -> 270 ImageOrientation.RIGHT -> 90 ImageOrientation.UP_MIRRORED -> 0 ImageOrientation.DOWN_MIRRORED -> 180 ImageOrientation.LEFT_MIRRORED -> 270 ImageOrientation.RIGHT_MIRRORED -> 90 } if (expectedOrientationSynchronize) { degrees += when (surfaceRotation) { 0 -> 0 1 -> 90 2 -> 180 3 -> 270 else -> 0 } } else { swapped = false } if (degrees.rem(180) == 0 && (imageOrientation == ImageOrientation.RIGHT || imageOrientation == ImageOrientation.RIGHT_MIRRORED)) { degrees += 180 } when (degrees.rem(360)) { 0 -> texCoordBuffer.put(TEX_COORDS_ROTATION_0) 90 -> texCoordBuffer.put(TEX_COORDS_ROTATION_90) 180 -> texCoordBuffer.put(TEX_COORDS_ROTATION_180) 270 -> texCoordBuffer.put(TEX_COORDS_ROTATION_270) } texCoordBuffer.position(0) val textureSize = newTextureSize.swap(swapped) when (videoGravity) { VideoGravity.RESIZE -> { GLES20.glViewport( 0, 0, extent.width, extent.height ) } VideoGravity.RESIZE_ASPECT -> { val xRatio = extent.width.toFloat() / textureSize.width.toFloat() val yRatio = extent.height.toFloat() / textureSize.height.toFloat() if (yRatio < xRatio) { GLES20.glViewport( ((extent.width - textureSize.width * yRatio) / 2).toInt(), 0, (textureSize.width * yRatio).toInt(), extent.height ) } else { GLES20.glViewport( 0, ((extent.height - textureSize.height * xRatio) / 2).toInt(), extent.width, (textureSize.height * xRatio).toInt() ) } } VideoGravity.RESIZE_ASPECT_FILL -> { val iRatio = extent.aspectRatio val fRatio = textureSize.aspectRatio if (iRatio < fRatio) { GLES20.glViewport( ((extent.width - extent.height * fRatio) / 2).toInt(), 0, (extent.height * fRatio).toInt(), extent.height ) } else { GLES20.glViewport( 0, ((extent.height - extent.width / fRatio) / 2).toInt(), extent.width, (extent.width / fRatio).toInt() ) } } } } private fun chooseConfig(): EGLConfig? { val attributes: IntArray = CONFIG_ATTRIBUTES_WITH_CONTEXT val configs: Array<EGLConfig?> = arrayOfNulls(1) val numConfigs = IntArray(1) if (!EGL14.eglChooseConfig( display, attributes, 0, configs, 0, configs.size, numConfigs, 0 ) ) { return null } return configs[0] } companion object { private const val EGL_RECORDABLE_ANDROID: Int = 0x3142 private val CONTEXT_ATTRIBUTES = intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL14.EGL_NONE) private val CONFIG_ATTRIBUTES_WITH_CONTEXT = intArrayOf( EGL14.EGL_RED_SIZE, 8, EGL14.EGL_GREEN_SIZE, 8, EGL14.EGL_BLUE_SIZE, 8, EGL14.EGL_ALPHA_SIZE, 8, EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT, EGL_RECORDABLE_ANDROID, 1, EGL14.EGL_NONE ) private val VERTECES = floatArrayOf( -1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f ) private val TEX_COORDS_ROTATION_0 = floatArrayOf( 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f ) private val TEX_COORDS_ROTATION_90 = floatArrayOf( 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f ) private val TEX_COORDS_ROTATION_180 = floatArrayOf( 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f ) private val TEX_COORDS_ROTATION_270 = floatArrayOf( 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f ) } }
bsd-3-clause
cad9c866539a24e56e3d23dcea0ad584
30.67052
139
0.538237
4.436437
false
true
false
false
GunoH/intellij-community
plugins/settings-sync/src/com/intellij/settingsSync/plugins/SettingsSyncPluginInstallerImpl.kt
1
4106
package com.intellij.settingsSync.plugins import com.intellij.ide.plugins.marketplace.MarketplaceRequests import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.updateSettings.impl.PluginDownloader import com.intellij.settingsSync.NOTIFICATION_GROUP import com.intellij.settingsSync.SettingsSyncBundle import com.intellij.util.Consumer import com.intellij.util.concurrency.annotations.RequiresBackgroundThread internal class SettingsSyncPluginInstallerImpl(private val notifyErrors: Boolean) : SettingsSyncPluginInstaller { companion object { val LOG = logger<SettingsSyncPluginInstallerImpl>() } @RequiresBackgroundThread override fun installPlugins(pluginsToInstall: List<PluginId>) { if (pluginsToInstall.isEmpty() || ApplicationManager.getApplication().isUnitTestMode // Register TestPluginManager in Unit Test Mode ) return ApplicationManager.getApplication().invokeAndWait { val prepareRunnable = PrepareInstallationRunnable(pluginsToInstall, notifyErrors) if (ProgressManager.getInstance().runProcessWithProgressSynchronously( prepareRunnable, SettingsSyncBundle.message("installing.plugins.indicator"), true, null)) { installCollected(prepareRunnable.getInstallers()) } } } private fun installCollected(installers: List<PluginDownloader>) { var isRestartNeeded = false installers.forEach { if (!it.installDynamically(null)) { isRestartNeeded = true } LOG.info("Installed plugin ID: " + it.id.idString) } if (isRestartNeeded) notifyRestartNeeded() } private fun notifyRestartNeeded() { val notification = NotificationGroupManager.getInstance().getNotificationGroup(NOTIFICATION_GROUP) .createNotification(SettingsSyncBundle.message("plugins.sync.restart.notification.title"), SettingsSyncBundle.message("plugins.sync.restart.notification.message"), NotificationType.INFORMATION) notification.addAction(NotificationAction.create( SettingsSyncBundle.message("plugins.sync.restart.notification.action", ApplicationNamesInfo.getInstance().fullProductName), Consumer { val app = ApplicationManager.getApplication() as ApplicationEx app.restart(true) })) notification.notify(null) } private class PrepareInstallationRunnable(val pluginIds: List<PluginId>, val notifyErrors: Boolean) : Runnable { private val collectedInstallers = ArrayList<PluginDownloader>() override fun run() { val indicator = ProgressManager.getInstance().progressIndicator pluginIds.forEach { prepareToInstall(it, indicator) indicator.checkCanceled() } } private fun prepareToInstall(pluginId: PluginId, indicator: ProgressIndicator) { val descriptor = MarketplaceRequests.getInstance().getLastCompatiblePluginUpdate(pluginId, indicator = indicator) if (descriptor != null) { val downloader = PluginDownloader.createDownloader(descriptor) if (downloader.prepareToInstall(indicator)) { collectedInstallers.add(downloader) } } else { val message = SettingsSyncBundle.message("install.plugin.failed.no.compatible.notification.error.message", pluginId ) LOG.info(message) if (notifyErrors) { NotificationGroupManager.getInstance().getNotificationGroup(NOTIFICATION_GROUP) .createNotification("", message, NotificationType.ERROR) .notify(null) } } } fun getInstallers() = collectedInstallers } }
apache-2.0
92ee8312997226985fcb8d58e9ce143c
40.908163
129
0.754262
5.402632
false
false
false
false
GunoH/intellij-community
plugins/git4idea/tests/git4idea/rebase/GitSingleRepoRebaseTest.kt
12
22254
// 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 git4idea.rebase import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.vcs.Executor import com.intellij.openapi.vcs.Executor.overwrite import com.intellij.openapi.vcs.Executor.touch import com.intellij.openapi.vcs.ui.CommitMessage import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.util.LineSeparator import com.intellij.vcsUtil.VcsUtil import git4idea.branch.GitBranchUiHandler import git4idea.branch.GitBranchWorker import git4idea.branch.GitRebaseParams import git4idea.config.GitVersionSpecialty import git4idea.i18n.GitBundle import git4idea.rebase.interactive.dialog.GitInteractiveRebaseDialog import git4idea.repo.GitRepository import git4idea.test.* import junit.framework.TestCase import org.junit.Assume import org.mockito.Mockito import org.mockito.Mockito.`when` class GitSingleRepoRebaseTest : GitRebaseBaseTest() { private lateinit var repo: GitRepository override fun setUp() { super.setUp() repo = createRepository(projectPath) } fun `test simple case`() { repo.`diverge feature and master`() ensureUpToDateAndRebaseOnMaster() assertSuccessfulRebaseNotification("Rebased feature on master") repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) } fun `test up-to-date`() { repo.`place feature above master`() ensureUpToDateAndRebaseOnMaster() assertSuccessfulRebaseNotification("Rebased feature on master") repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) } fun test_ff() { repo.`place feature below master`() ensureUpToDateAndRebaseOnMaster() assertSuccessfulRebaseNotification("Rebased feature on master") repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) } fun `test conflict resolver is shown`() { repo.`prepare simple conflict`() `do nothing on merge`() ensureUpToDateAndRebaseOnMaster() `assert merge dialog was shown`() } fun `test fail on 2nd commit should show notification with proposal to abort`() { repo.`make rebase fail on 2nd commit`() ensureUpToDateAndRebaseOnMaster() `assert unknown error notification with link to abort`() } fun `test multiple conflicts`() { build { master { 0("c.txt") 1("c.txt") } feature(0) { 2("c.txt") 3("c.txt") } } var conflicts = 0 vcsHelper.onMerge { conflicts++ repo.assertConflict("c.txt") repo.resolveConflicts() } keepCommitMessageAfterConflict() ensureUpToDateAndRebaseOnMaster() assertEquals("Incorrect number of conflicting patches", 2, conflicts) repo.`assert feature rebased on master`() assertSuccessfulRebaseNotification("Rebased feature on master") } fun `test continue rebase after resolving all conflicts`() { repo.`prepare simple conflict`() vcsHelper.onMerge { repo.resolveConflicts() } keepCommitMessageAfterConflict() ensureUpToDateAndRebaseOnMaster() assertSuccessfulRebaseNotification("Rebased feature on master") repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) } fun `test warning notification if conflicts were not resolved`() { repo.`prepare simple conflict`() `do nothing on merge`() ensureUpToDateAndRebaseOnMaster() `assert conflict not resolved notification`() repo.assertRebaseInProgress() } fun `test skip if user decides to skip`() { repo.`prepare simple conflict`() `do nothing on merge`() ensureUpToDateAndRebaseOnMaster() GitRebaseUtils.skipRebase(project) assertSuccessfulRebaseNotification("Rebased feature on master") repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) } fun `test rebase failed for unknown reason`() { repo.`diverge feature and master`() git.setShouldRebaseFail { true } ensureUpToDateAndRebaseOnMaster() `assert unknown error notification`() } fun `test propose to abort when rebase failed after continue`() { repo.`prepare simple conflict`() `do nothing on merge`() ensureUpToDateAndRebaseOnMaster() repo.`assert feature not rebased on master`() repo.assertRebaseInProgress() repo.resolveConflicts() git.setShouldRebaseFail { true } GitRebaseUtils.continueRebase(project) `assert unknown error notification with link to abort`(true) repo.`assert feature not rebased on master`() repo.assertRebaseInProgress() } fun `test local changes auto-saved initially`() { repo.`diverge feature and master`() val localChange = LocalChange(repo, "new.txt").generate() refresh() updateChangeListManager() object : GitTestingRebaseProcess(project, simpleParams("master"), repo) { override fun getDirtyRoots(repositories: Collection<GitRepository>): Collection<GitRepository> { return listOf(repo) } }.rebase() assertSuccessfulRebaseNotification("Rebased feature on master") assertRebased(repo, "feature", "master") assertNoRebaseInProgress(repo) localChange.verify() } fun `test local changes are saved even if not detected initially`() { repo.`diverge feature and master`() val localChange = LocalChange(repo, "new.txt").generate() refresh() updateChangeListManager() object : GitTestingRebaseProcess(project, simpleParams("master"), repo) { override fun getDirtyRoots(repositories: Collection<GitRepository>): Collection<GitRepository> { return emptyList() } }.rebase() assertSuccessfulRebaseNotification("Rebased feature on master") assertRebased(repo, "feature", "master") assertNoRebaseInProgress(repo) localChange.verify() } fun `test local changes are not restored in case of error even if nothing was rebased`() { repo.`diverge feature and master`() LocalChange(repo, "new.txt", "content").generate() git.setShouldRebaseFail { true } ensureUpToDateAndRebaseOnMaster() assertErrorNotification("Rebase failed", """ $UNKNOWN_ERROR_TEXT<br/> $LOCAL_CHANGES_WARNING """) assertNoRebaseInProgress(repo) repo.assertNoLocalChanges() assertFalse(file("new.txt").exists()) } fun `test critical error should show notification and not restore local changes`() { repo.`diverge feature and master`() LocalChange(repo, "new.txt", "content").generate() git.setShouldRebaseFail { true } ensureUpToDateAndRebaseOnMaster() `assert unknown error notification with link to stash`() repo.assertNoLocalChanges() } fun `test successful retry from notification on critical error restores local changes`() { repo.`diverge feature and master`() val localChange = LocalChange(repo, "new.txt", "content").generate() var attempt = 0 git.setShouldRebaseFail { attempt == 0 } ensureUpToDateAndRebaseOnMaster() attempt++ vcsNotifier.lastNotification GitRebaseUtils.continueRebase(project) assertNoRebaseInProgress(repo) repo.`assert feature rebased on master`() localChange.verify() } fun `test local changes are restored after successful abort`() { repo.`prepare simple conflict`() val localChange = LocalChange(repo, "new.txt", "content").generate() `do nothing on merge`() dialogManager.onMessage { Messages.YES } ensureUpToDateAndRebaseOnMaster() `assert conflict not resolved notification with link to stash`() GitRebaseUtils.abort(project, EmptyProgressIndicator()) assertNoRebaseInProgress(repo) repo.`assert feature not rebased on master`() localChange.verify() } fun `test local changelists are restored after successful abort`() { touch("file.txt", "1\n2\n3\n4\n5\n") touch("file1.txt", "content") touch("file2.txt", "content") touch("file3.txt", "content") repo.addCommit("initial") repo.`prepare simple conflict`() val testChangelist1 = changeListManager.addChangeList("TEST_1", null) val testChangelist2 = changeListManager.addChangeList("TEST_2", null) val file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(Executor.child("file.txt"))!! withPartialTracker(file, "1A\n2\n3A\n4\n5A\n") { document, tracker -> val ranges = tracker.getRanges()!! TestCase.assertEquals(3, ranges.size) tracker.moveToChangelist(ranges[1], testChangelist1) tracker.moveToChangelist(ranges[2], testChangelist2) } overwrite("file1.txt", "new content") overwrite("file2.txt", "new content") overwrite("file3.txt", "new content") VfsUtil.markDirtyAndRefresh(false, false, true, repo.root) changeListManager.ensureUpToDate() changeListManager.moveChangesTo(testChangelist1, changeListManager.getChange(VcsUtil.getFilePath(repo.root, "file2.txt"))!!) changeListManager.moveChangesTo(testChangelist2, changeListManager.getChange(VcsUtil.getFilePath(repo.root, "file3.txt"))!!) `do nothing on merge`() dialogManager.onMessage { Messages.YES } ensureUpToDateAndRebaseOnMaster() `assert conflict not resolved notification with link to stash`() GitRebaseUtils.abort(project, EmptyProgressIndicator()) assertNoRebaseInProgress(repo) repo.`assert feature not rebased on master`() val changelists = changeListManager.changeLists assertEquals(3, changelists.size) for (changeList in changelists) { assertTrue("${changeList.name} - ${changeList.changes}", changeList.changes.size == 2) } } fun `test local changelists are restored after successful rebase`() { touch("file.txt", "1\n2\n3\n4\n5\n") touch("file1.txt", "content") touch("file2.txt", "content") touch("file3.txt", "content") repo.addCommit("initial") repo.`diverge feature and master`() val testChangelist1 = changeListManager.addChangeList("TEST_1", null) val testChangelist2 = changeListManager.addChangeList("TEST_2", null) val file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(Executor.child("file.txt"))!! withPartialTracker(file, "1A\n2\n3A\n4\n5A\n") { document, tracker -> val ranges = tracker.getRanges()!! TestCase.assertEquals(3, ranges.size) tracker.moveToChangelist(ranges[1], testChangelist1) tracker.moveToChangelist(ranges[2], testChangelist2) } overwrite("file1.txt", "new content") overwrite("file2.txt", "new content") overwrite("file3.txt", "new content") VfsUtil.markDirtyAndRefresh(false, false, true, repo.root) changeListManager.ensureUpToDate() changeListManager.moveChangesTo(testChangelist1, changeListManager.getChange(VcsUtil.getFilePath(repo.root, "file2.txt"))!!) changeListManager.moveChangesTo(testChangelist2, changeListManager.getChange(VcsUtil.getFilePath(repo.root, "file3.txt"))!!) ensureUpToDateAndRebaseOnMaster() assertSuccessfulRebaseNotification("Rebased feature on master") assertNoRebaseInProgress(repo) repo.`assert feature rebased on master`() val changelists = changeListManager.changeLists assertEquals(3, changelists.size) for (changeList in changelists) { assertTrue("${changeList.name} - ${changeList.changes}", changeList.changes.size == 2) } } fun `test local changelists are restored after successful rebase with resolved conflict`() { touch("file.txt", "1\n2\n3\n4\n5\n") touch("file1.txt", "content") touch("file2.txt", "content") touch("file3.txt", "content") repo.addCommit("initial") repo.`prepare simple conflict`() val testChangelist1 = changeListManager.addChangeList("TEST_1", null) val testChangelist2 = changeListManager.addChangeList("TEST_2", null) val file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(Executor.child("file.txt"))!! withPartialTracker(file, "1A\n2\n3A\n4\n5A\n") { document, tracker -> val ranges = tracker.getRanges()!! TestCase.assertEquals(3, ranges.size) tracker.moveToChangelist(ranges[1], testChangelist1) tracker.moveToChangelist(ranges[2], testChangelist2) } overwrite("file1.txt", "new content") overwrite("file2.txt", "new content") overwrite("file3.txt", "new content") VfsUtil.markDirtyAndRefresh(false, false, true, repo.root) changeListManager.ensureUpToDate() changeListManager.moveChangesTo(testChangelist1, changeListManager.getChange(VcsUtil.getFilePath(repo.root, "file2.txt"))!!) changeListManager.moveChangesTo(testChangelist2, changeListManager.getChange(VcsUtil.getFilePath(repo.root, "file3.txt"))!!) vcsHelper.onMerge { repo.resolveConflicts() } keepCommitMessageAfterConflict() ensureUpToDateAndRebaseOnMaster() assertSuccessfulRebaseNotification("Rebased feature on master") repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) val changelists = changeListManager.changeLists assertEquals(3, changelists.size) for (changeList in changelists) { assertTrue("${changeList.name} - ${changeList.changes}", changeList.changes.size == 2) } } fun `test local changes are not restored after failed abort`() { repo.`prepare simple conflict`() LocalChange(repo, "new.txt", "content").generate() `do nothing on merge`() dialogManager.onMessage { Messages.YES } ensureUpToDateAndRebaseOnMaster() `assert conflict not resolved notification with link to stash`() git.setShouldRebaseFail { true } GitRebaseUtils.abort(project, EmptyProgressIndicator()) repo.assertRebaseInProgress() repo.`assert feature not rebased on master`() repo.assertConflict("c.txt") assertErrorNotification(GitBundle.message("rebase.abort.notification.failed.title"), """ unknown error<br/> $LOCAL_CHANGES_WARNING """) } // git rebase --continue should be either called from a commit dialog, either from the GitRebaseProcess. // both should prepare the working tree themselves by adding all necessary changes to the index. fun `test local changes in the conflicting file should lead to error on continue rebase`() { repo.`prepare simple conflict`() `do nothing on merge`() ensureUpToDateAndRebaseOnMaster() repo.assertConflict("c.txt") //manually resolve conflicts repo.resolveConflicts() file("c.txt").append("more changes after resolving") // forget to git add afterwards GitRebaseUtils.continueRebase(project) `assert error about unstaged file before continue rebase`("c.txt") repo.`assert feature not rebased on master`() repo.assertRebaseInProgress() } fun `test local changes in some other file should lead to error on continue rebase`() { build { master { 0("d.txt") 1("c.txt") 2("c.txt") } feature(1) { 3("c.txt") } } `do nothing on merge`() ensureUpToDateAndRebaseOnMaster() repo.assertConflict("c.txt") //manually resolve conflicts repo.resolveConflicts() // add more changes to some other file file("d.txt").append("more changes after resolving") GitRebaseUtils.continueRebase(project) `assert error about unstaged file before continue rebase`("d.txt") repo.`assert feature not rebased on master`() repo.assertRebaseInProgress() } fun `test unresolved conflict should lead to conflict resolver with continue rebase`() { repo.`prepare simple conflict`() `do nothing on merge`() keepCommitMessageAfterConflict() ensureUpToDateAndRebaseOnMaster() repo.assertConflict("c.txt") vcsHelper.onMerge { repo.resolveConflicts() } GitRebaseUtils.continueRebase(project) assertSuccessfulRebaseNotification("Rebased feature on master") repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) } fun `test skipped commit`() { build { master { 0("c.txt", "base") 1("c.txt", "\nmaster") } feature(0) { 2("c.txt", "feature", "commit to be skipped") 3() } } vcsHelper.onMerge { file("c.txt").write("base\nmaster") repo.resolveConflicts() } ensureUpToDateAndRebaseOnMaster() assertRebased(repo, "feature", "master") assertNoRebaseInProgress(repo) assertSuccessfulRebaseNotification("Rebased feature on master") } fun `test interactive rebase stopped for editing`() { build { master { 0() 1() } feature(1) { 2() 3() } } git.setInteractiveRebaseEditor (TestGitImpl.InteractiveRebaseEditor({ it.lines().mapIndexed { i, s -> if (i != 0) s else s.replace("pick", "edit") }.joinToString(LineSeparator.getSystemLineSeparator().separatorString) }, null)) refresh() updateChangeListManager() rebaseInteractively() assertSuccessfulNotification("Rebase stopped for editing", "") assertEquals("The repository must be in the 'SUSPENDED' state", repo, repositoryManager.ongoingRebaseSpec!!.ongoingRebase) GitRebaseUtils.continueRebase(project) assertSuccessfulRebaseNotification("Rebased feature on master") repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) } // IDEA-140568 fun `test git help comments are ignored when parsing interactive rebase`() { makeCommit("initial.txt") repo.update() val initialMessage = "Wrong message" val commit = file("a").create("initial").addCommit(initialMessage).details() git("config core.commentChar $") var receivedEntries: List<GitRebaseEntry>? = null val rebaseEditor = GitAutomaticRebaseEditor(project, commit.root, entriesEditor = { list -> receivedEntries = list list }, plainTextEditor = { it }) refresh() updateChangeListManager() GitTestingRebaseProcess(project, GitRebaseParams.editCommits(vcs.version, "HEAD^", rebaseEditor, false), repo).rebase() assertNotNull("Didn't get any rebase entries", receivedEntries) assertEquals("Rebase entries parsed incorrectly", listOf(GitRebaseEntry.Action.PICK), receivedEntries!!.map { it.action }) } // IDEA-176455 fun `test reword during interactive rebase writes commit message correctly`() { Assume.assumeTrue("Not testing: not possible to fix in Git prior to 1.8.2: ${vcs.version}", GitVersionSpecialty.KNOWS_CORE_COMMENT_CHAR.existsIn(vcs.version)) // IDEA-182044 makeCommit("initial.txt") repo.update() val initialMessage = "Wrong message" file("a").create("initial").addCommit(initialMessage).details() val newMessage = """ Subject #body starting with a hash """.trimIndent() git.setInteractiveRebaseEditor (TestGitImpl.InteractiveRebaseEditor({ it.lines().mapIndexed { i, s -> if (i != 0) s else s.replace("pick", "reword") }.joinToString(LineSeparator.getSystemLineSeparator().separatorString) }, null)) var receivedMessage : String? = null dialogManager.onDialog(GitUnstructuredEditor::class.java) { receivedMessage = it.text val field = GitUnstructuredEditor::class.java.getDeclaredField("myTextEditor") field.isAccessible = true val commitMessage = field.get (it) as CommitMessage commitMessage.text = newMessage 0 } refresh() updateChangeListManager() rebaseInteractively("HEAD^") assertEquals("Initial message is incorrect", initialMessage, receivedMessage) assertLastMessage(newMessage) } fun `test cancel in interactive rebase should show no error notification`() { repo.`diverge feature and master`() dialogManager.onDialog(GitInteractiveRebaseDialog::class.java) { DialogWrapper.CANCEL_EXIT_CODE } rebaseInteractively() assertNoErrorNotification() assertNoRebaseInProgress(repo) repo.`assert feature not rebased on master`() } fun `test cancel in noop case should show no error notification`() { build { master { 0() 1() } feature(0) {} } dialogManager.onMessage { Messages.CANCEL } rebaseInteractively() assertNoErrorNotification() assertNoRebaseInProgress(repo) repo.`assert feature not rebased on master`() } private fun rebaseInteractively(revision: String = "master") { GitTestingRebaseProcess(project, GitRebaseParams(vcs.version, null, null, revision, true, false), repo).rebase() } fun `test checkout with rebase`() { repo.`diverge feature and master`() checkCheckoutAndRebase { "Checked out feature and rebased it on master" } } private fun checkCheckoutAndRebase(expectedNotification: () -> String) { repo.git("checkout master") refresh() updateChangeListManager() val uiHandler = Mockito.mock(GitBranchUiHandler::class.java) `when`(uiHandler.progressIndicator).thenReturn(EmptyProgressIndicator()) GitBranchWorker(project, git, uiHandler).rebaseOnCurrent(listOf(repo), "feature") assertSuccessfulRebaseNotification(expectedNotification()) repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) } private fun build(f: RepoBuilder.() -> Unit) { build(repo, f) } private fun ensureUpToDateAndRebaseOnMaster() { refresh() updateChangeListManager() GitTestingRebaseProcess(project, simpleParams("master"), repo).rebase() } private fun simpleParams(newBase: String): GitRebaseParams { return GitRebaseParams(vcs.version, newBase) } internal fun file(path: String) = repo.file(path) }
apache-2.0
52a886d7ee39dcfef007ac59f9a020b3
30.476662
140
0.69601
4.807518
false
true
false
false
ronaldosanches/McCabe-Thiele-for-Android-Kotlin
app/src/main/java/com/ronaldosanches/Chart.kt
1
18919
package com.ronaldosanches.mccabethiele import android.graphics.Color import android.os.Bundle import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.util.Log import com.github.mikephil.charting.components.Description import com.github.mikephil.charting.components.LegendEntry import com.github.mikephil.charting.components.XAxis import com.github.mikephil.charting.components.YAxis import com.github.mikephil.charting.data.Entry import com.github.mikephil.charting.data.LineData import com.github.mikephil.charting.data.LineDataSet import com.github.mikephil.charting.interfaces.datasets.ILineDataSet import com.github.mikephil.charting.utils.EntryXComparator import kotlinx.android.synthetic.main.mccabethiele_chart.* import java.util.* /** * Created by ronaldo sanches on 06/09/2017. */ class Chart : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.mccabethiele_chart) //########## 0 ########## //defining variables //adding value from the intent to variables val relativevolatility: Float = intent.getFloatExtra("value_relativevolatility",2.5f) val feedmolefraction: Float = intent.getFloatExtra("value_feedmolefraction",0.6f) val distillatemolefraction: Float = intent.getFloatExtra("value_distillatemolefraction",0.9f) val bottomsmolefraction: Float = intent.getFloatExtra("value_bottomsmolefraction",0.2f) val refluxratio: Float = intent.getFloatExtra("value_refluxratio",2f) val feedquality: Float = intent.getFloatExtra("value_feedquality",1.4f) Log.i("intent","intent value received") Log.i("intent","value_relativevolatility: " + relativevolatility) //defining data arraylists val data_45degree = ArrayList<Entry>() val data_qline = ArrayList<Entry>() val data_retification = ArrayList<Entry>() val data_stripping = ArrayList<Entry>() val data_theoreticalplates = ArrayList<Entry>() val data_xb = ArrayList<Entry>() val data_xd = ArrayList<Entry>() val data_xf = ArrayList<Entry>() val data_equilibriumcurve = ArrayList<Entry>() //########## 1 ########## // making the 45 degree line //it goes from (0,0) to (1,1) data_45degree.add(Entry(0f,0f)) data_45degree.add(Entry(1f,1f)) Log.i("part 1","data_45degree: " + data_45degree.toString()) //########## 2 ########## //making the equilibrium curve var partialvalue: Float for (count: Int in 0..100) { // y = a*x/(1+x*(a-1)) partialvalue = (relativevolatility*((count.toFloat())/100))/(1+((count.toFloat())/100)*(relativevolatility-1)) data_equilibriumcurve.add(Entry((count.toFloat())/100 , partialvalue)) } Log.i("part 2","data_equilibriumcurve " + data_equilibriumcurve.toString()) //########## 3 ########## //making the lines for bottoms mole fraction (xb), //distilled mole fraction (xd) and feed mole fraction (xf) data_xb.add(Entry(bottomsmolefraction,bottomsmolefraction)) data_xb.add(Entry(bottomsmolefraction,0f)) data_xd.add(Entry(distillatemolefraction,distillatemolefraction)) data_xd.add(Entry(distillatemolefraction,0f)) data_xf.add(Entry(feedmolefraction,feedmolefraction)) data_xf.add(Entry(feedmolefraction,0f)) //########## 4 ########## //creating each LineDataSet val dataSet_qline = LineDataSet(data_qline, resources.getString(R.string.qline)) val dataSet_retificationline = LineDataSet(data_retification, resources.getString(R.string.retificationline)) val dataSet_strippingline = LineDataSet(data_stripping, resources.getString(R.string.strippingline)) val dataSet_theoreticalplates = LineDataSet(data_theoreticalplates, resources.getString(R.string.theoreticalplates)) val dataSet_xbline = LineDataSet(data_xb, resources.getString(R.string.bottommoleefraction)) val dataSet_xdline = LineDataSet(data_xd, resources.getString(R.string.distilledmolefraction)) val dataSet_xfline = LineDataSet(data_xf, resources.getString(R.string.feedmolefraction)) //adding 45degree line and equilibrium curve val dataSet_45degree = LineDataSet(data_45degree,resources.getString(R.string.line45degree)) val dataSet_equilibriumcurve = LineDataSet(data_equilibriumcurve,resources.getString(R.string.equilibriumcurve)) //not sure this is necessary dataSet_45degree.axisDependency = YAxis.AxisDependency.LEFT dataSet_equilibriumcurve.axisDependency = YAxis.AxisDependency.LEFT //########## 5 ########## //changing style changestyle1(dataSet_equilibriumcurve,5f, Color.BLACK,false) changestyle1(dataSet_45degree,3f, Color.BLACK,false) changestyle1(dataSet_qline,5f, ContextCompat.getColor(this,R.color.color_qline),false) changestyle1(dataSet_retificationline,3f,ContextCompat.getColor(this,R.color.color_retificationline),false) changestyle1(dataSet_strippingline,3f,ContextCompat.getColor(this,R.color.color_strippingline),false) changestyle1(dataSet_theoreticalplates,3f,ContextCompat.getColor(this,R.color.color_theoreticalplates),false) changestyle1(dataSet_xbline,3f,Color.BLACK,true) changestyle1(dataSet_xdline,3f,Color.BLACK,true) changestyle1(dataSet_xfline,3f,Color.BLACK,true) dataSet_theoreticalplates.cubicIntensity = 0f //check if this is necessary //######## 6 ########## //creating line collection val line_collection = ArrayList<ILineDataSet>() //########## 7 ########## //finding the values for the q-line //the equation for the q-line // f_1 = (q*x-xf)/(q-1) // this line is defined for: //(x1_qline,y1_qline) and (x3_qline,y3_qline) //in (x1_qline,y1_qline) the line is touching the 45 degree line and x1 = xf //so (x1_qline,y1_qline) = (xf,xf) //and xf = feedmolefraction val x1_qline: Float = feedmolefraction val y1_qline: Float = feedmolefraction data_qline.add(Entry(x1_qline,y1_qline)) //the second point for the qline is going to be defined after finding the intersection //between the q-line and the rectifying line using one point of each and their slope //########## 8 ########## //finding the line for the rectifying section //the initial point is in the 45 degree line and starts at x1_rectifying = xd = y1_rectifying //xd = distilledmolefraction val x1_rectifying: Float = distillatemolefraction val y1_rectifying: Float = distillatemolefraction data_retification.add(Entry(x1_rectifying,y1_rectifying)) //the slope for the q-line can be calculated by q/(q-1) where q = feedquality //and the slope for the rectifying line is R/(R+1) //since you can calculate the slope for both lines and the initial points are already //calculated you can find the intersection point through the following equation // for the q-line // m1 = (y1-y)/(x1-x) //m1*x1-x*m1 = y1-y //y = y1-m1*x1 + x*m1 //for the rectifying line //m2 = (y2-y)/(x2-x) //m2*x2-x*m2 = y2 - y //y = y2 - m2*x2 + x*m2 //also y = y //y1 - m1*x1 + x*m1 = y2 - m2*x2 + x*m2 //[(y1-y2) + (m2*x2 - m1*x1)]/(m2-m1) = x (intersection point) val m_qline: Float = feedquality/(feedquality-1) val m_rectifying: Float = refluxratio/(refluxratio+1) val x2_rectifying: Float = ((y1_qline-y1_rectifying)+(m_rectifying*x1_rectifying-m_qline*x1_qline))/(m_rectifying-m_qline) //the equation for the rectifying section is // y2_rectifying = (R*x2_rectifying+xd)/(R+1) val y2_rectifying: Float = (refluxratio * x2_rectifying + distillatemolefraction) / (refluxratio + 1) data_retification.add(Entry(x2_rectifying,y2_rectifying)) Log.i("part 8","data_retification: " + data_retification.toString()) //########## 8.5 ########### //adding the second value for the qline val x2_qline = x2_rectifying val y2_qline = y2_rectifying data_qline.add(Entry(x2_qline, y2_qline)) //########## 9 ########## //stripping section of the operating line //(x1,y1) is in the 45 degree line so xb = x1_stripping = y1_stripping // xb = bottomsmolefraction val x1_stripping: Float = bottomsmolefraction val y1_stripping: Float = bottomsmolefraction data_stripping.add(Entry(x1_stripping,y1_stripping)) //the same point of interception between the q-line and rectifying line is also //the point where the stripping line meets the other two lines val x2_stripping: Float = x2_rectifying val y2_stripping: Float = y2_rectifying data_stripping.add(Entry(x2_stripping,y2_stripping)) //########## 10 ########## //adding the line for theoretical plates //the first point is where the rectifying section line start data_theoreticalplates.add(Entry(x1_rectifying,y1_rectifying)) Log.i("part 10","data_theoreticalplates: " + data_theoreticalplates.toString()) //it is also the first point for iteration var tpx: Float = x1_rectifying var tpy: Float = y1_rectifying var tpi: Int = 0 //this iteration keeps going until the last value of x is smaller than //the limit of x for the rectifying section line Log.i("part 10","start iteration for theoretical plates") Log.i("part 10","tpx: " + tpx.toString()) while (tpx > x2_rectifying && tpi <= 200) { //the line eather moves the x axis or the y axis //this is the reason for the next if if (tpi%2 == 0) { tpx = tpy / (relativevolatility - tpy * relativevolatility + tpy) } else { tpy = (refluxratio * tpx + distillatemolefraction) / (refluxratio + 1) } //adding the data data_theoreticalplates.add(Entry(tpx,tpy)) //Log.i("part 10","adding data: " + data_theoreticalplates.toString()) //Log.i("part 10","tpi: " + tpi.toString()) tpi++ } Log.i("part 10","end of while") Log.i("part 10","tpi: " + tpi.toString()) Log.i("part 10","tpx: " + tpx.toString()) //adding the feeding stage val feedingstage: Int = (tpi-1)/2 + 1 //from this point on the theoretical plates line is going to be //over the stripping line //the last iteration was over the x axis so the next one should be over y //finding the line parameters for the stripping line // val m_strippingline = (y2_stripping - bottomsmolefraction) / (x2_stripping - bottomsmolefraction) val b_strippingline = bottomsmolefraction - bottomsmolefraction * m_strippingline Log.i("part 10","m_strippingline: " + m_strippingline.toString()) Log.i("part 10","second loop") //adicionando os valores //while the value of x is greater than the composition of bottoms while (tpx > bottomsmolefraction && tpi<=200) { if (tpi % 2 == 0) { tpx = tpy / (relativevolatility - tpy * relativevolatility + tpy) } else { tpy = m_strippingline * tpx + b_strippingline } data_theoreticalplates.add(Entry(tpx,tpy)) tpi++ } //after the last iteration on x gotta do one more in y tpy = tpx data_theoreticalplates.add(Entry(tpx,tpy)) tpi++ Log.i("part 10","end of 2nd loop") Log.i("part 10","tpx: " + tpx.toString()) Log.i("part 10","tpy: " + tpy.toString()) //########## 11 ########## //sorting collections to avoid weird behavior on the chart Collections.sort(data_theoreticalplates, EntryXComparator()) Collections.sort(data_retification, EntryXComparator()) Collections.sort(data_stripping, EntryXComparator()) //########## 12 ########## //sorting the entry for (i in 0..data_theoreticalplates.size - 2) { if (data_theoreticalplates.get(i).getX() == data_theoreticalplates.get(i + 1).getX() && data_theoreticalplates.get(i).getY() > data_theoreticalplates.get(i + 1).getY()) { val entrytempsort = ArrayList<Entry>(1) entrytempsort.add(0, data_theoreticalplates.get(i)) data_theoreticalplates.set(i, data_theoreticalplates.get(i + 1)) data_theoreticalplates.set(i + 1, entrytempsort[0]) } } //########## 13 ########## //setting other style for datasets //this adds color under the lines of theoretical plates dataSet_theoreticalplates.setMode(LineDataSet.Mode.LINEAR) changestyle2(dataSet_theoreticalplates,ContextCompat.getColor(this, R.color.color_shadowtheoreticalplates),false) changestyle2(dataSet_retificationline,ContextCompat.getColor(this,R.color.color_background),true) changestyle2(dataSet_strippingline,ContextCompat.getColor(this,R.color.color_background),true) val data_coverunwantedshadow = ArrayList<Entry>() //minor adjustment //without this the chart will be tinted wrongly between the last line //of the theoretical plate and the bottoms mole fraction line data_coverunwantedshadow.add(Entry(0f,0f)) data_coverunwantedshadow.add(Entry(bottomsmolefraction,bottomsmolefraction)) val dataSet_coverunwantedshadow = LineDataSet(data_coverunwantedshadow, "") changestyle1(dataSet_coverunwantedshadow,3f,Color.BLACK,false) changestyle2(dataSet_coverunwantedshadow,ContextCompat.getColor(this,R.color.color_background),true) //########## 14 ########## //adding data to line_collection, linedata and starting chart //this first one will only be added if there's less than 100 theoretical plates if (tpi<200) line_collection.add(dataSet_theoreticalplates) //this won't be added if there's more than 100 plates line_collection.add(dataSet_equilibriumcurve) line_collection.add(dataSet_retificationline) line_collection.add(dataSet_strippingline) line_collection.add(dataSet_qline) line_collection.add(dataSet_45degree) line_collection.add(dataSet_xbline) line_collection.add(dataSet_xdline) line_collection.add(dataSet_xfline) line_collection.add(dataSet_coverunwantedshadow) //creating linedata val lineData = LineData(line_collection) //commiting data to chart chart_mccabethiele.data = lineData //########## 15 ########## //changing the axis chart_mccabethiele.getAxisRight().setEnabled(false) chart_mccabethiele.axisLeft.setDrawGridLines(false) chart_mccabethiele.getAxisLeft().setTextSize(12f) chart_mccabethiele.getXAxis().setDrawGridLines(false) chart_mccabethiele.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM) chart_mccabethiele.getXAxis().setTextSize(12f) chart_mccabethiele.setDrawBorders(true) chart_mccabethiele.setBorderWidth(1f) //push the range of the chart to be from 0 to 1 chart_mccabethiele.getXAxis().setAxisMaximum(1f) chart_mccabethiele.getXAxis().setAxisMinimum(0f) chart_mccabethiele.getXAxis().setLabelCount(6, true) chart_mccabethiele.getAxisLeft().setAxisMaximum(1f) chart_mccabethiele.getAxisLeft().setAxisMinimum(0f) chart_mccabethiele.getAxisLeft().setLabelCount(6, true) //changing the axis description val chart_description = Description() chart_description.text = "" chart_mccabethiele.setDescription(chart_description) //custom subtitles for retificationline, strippingline and qline val chart_subtitle = chart_mccabethiele.getLegend() val legend_entry = ArrayList<LegendEntry>() val legendentry_retificationline = LegendEntry() legendentry_retificationline.formColor = dataSet_retificationline.getColor() legendentry_retificationline.label = dataSet_retificationline.getLabel() val legendentry_strippingline = LegendEntry() legendentry_strippingline.formColor = dataSet_strippingline.getColor() legendentry_strippingline.label = dataSet_strippingline.getLabel() val legendentry_qline = LegendEntry() legendentry_qline.formColor = dataSet_qline.getColor() legendentry_qline.label = dataSet_qline.getLabel() legend_entry.add(legendentry_retificationline) legend_entry.add(legendentry_strippingline) legend_entry.add(legendentry_qline) chart_subtitle.setCustom(legend_entry) //restart the values of the char chart_mccabethiele.invalidate() //########## 16 ########## //adding data to report if(tpi>=200) { tvamountoftheoreticalplates.setText(" > 100") tvamountoftheoreticalplates.setTextColor(Color.RED) tvfeedstage.setText(" ---") tvfeedstage.setTextColor(Color.RED) } else { tvamountoftheoreticalplates.setText(" " + (tpi/2).toString()) tvfeedstage.setText(" " + feedingstage.toString()) } } private fun changestyle1(linedataset: LineDataSet, line_width: Float,color: Int, dashedline: Boolean) { linedataset.setColor(color) linedataset.lineWidth = line_width linedataset.setDrawValues(false) linedataset.setDrawCircles(false) if(dashedline) { linedataset.enableDashedLine(2f,3f,2f) } } private fun changestyle2(dataset: LineDataSet, color: Int, fillopacity: Boolean) { dataset.setDrawFilled(true) dataset.fillColor = color if(fillopacity) dataset.fillAlpha = 255 } }
mit
2c7e3f66e36ec7635c64513c58ea54f6
39.671806
130
0.631006
3.668606
false
false
false
false
siosio/intellij-community
python/python-psi-impl/src/com/jetbrains/python/inspections/PyProtocolInspection.kt
1
6338
// 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.inspections import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.util.containers.isNullOrEmpty import com.jetbrains.python.PyNames import com.jetbrains.python.PyPsiBundle import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.codeInsight.typing.inspectProtocolSubclass import com.jetbrains.python.codeInsight.typing.isProtocol import com.jetbrains.python.psi.* import com.jetbrains.python.psi.PyKnownDecoratorUtil.KnownDecorator.* import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.resolve.PyResolveUtil import com.jetbrains.python.psi.resolve.RatedResolveResult import com.jetbrains.python.psi.types.PyClassLikeType import com.jetbrains.python.psi.types.PyClassType import com.jetbrains.python.psi.types.PyTypeChecker class PyProtocolInspection : PyInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor = Visitor( holder, session) private class Visitor(holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) { override fun visitPyClass(node: PyClass) { super.visitPyClass(node) val type = myTypeEvalContext.getType(node) as? PyClassType ?: return val superClassTypes = type.getSuperClassTypes(myTypeEvalContext) checkCompatibility(type, superClassTypes) checkProtocolBases(type, superClassTypes) } override fun visitPyCallExpression(node: PyCallExpression) { super.visitPyCallExpression(node) checkRuntimeProtocolInIsInstance(node) checkNewTypeWithProtocols(node) } private fun checkCompatibility(type: PyClassType, superClassTypes: List<PyClassLikeType?>) { superClassTypes .asSequence() .filterIsInstance<PyClassType>() .filter { isProtocol(it, myTypeEvalContext) } .forEach { protocol -> inspectProtocolSubclass(protocol, type, myTypeEvalContext).forEach { val subclassElements = it.second if (!subclassElements.isNullOrEmpty()) { checkMemberCompatibility(it.first, subclassElements!!, type, protocol) } } } } private fun checkProtocolBases(type: PyClassType, superClassTypes: List<PyClassLikeType?>) { if (!isProtocol(type, myTypeEvalContext)) return val correctBase: (PyClassLikeType?) -> Boolean = { if (it == null) true else { val classQName = it.classQName classQName == PyTypingTypeProvider.PROTOCOL || classQName == PyTypingTypeProvider.PROTOCOL_EXT || it is PyClassType && isProtocol(it, myTypeEvalContext) } } if (!superClassTypes.all(correctBase)) { registerProblem(type.pyClass.nameIdentifier, PyPsiBundle.message("INSP.protocol.all.bases.protocol.must.be.protocols")) } } private fun checkRuntimeProtocolInIsInstance(node: PyCallExpression) { if (node.isCalleeText(PyNames.ISINSTANCE, PyNames.ISSUBCLASS)) { val base = node.arguments.getOrNull(1) ?: return if (base is PyReferenceExpression) { val qNames = PyResolveUtil.resolveImportedElementQNameLocally(base).asSequence().map { it.toString() } if (qNames.any { it == PyTypingTypeProvider.PROTOCOL || it == PyTypingTypeProvider.PROTOCOL_EXT }) { registerProblem(base, PyPsiBundle.message("INSP.protocol.only.runtime.checkable.protocols.can.be.used.with.instance.class.checks"), GENERIC_ERROR) return } } val type = myTypeEvalContext.getType(base) if ( type is PyClassType && isProtocol(type, myTypeEvalContext) && !PyKnownDecoratorUtil.getKnownDecorators(type.pyClass, myTypeEvalContext).any { it == TYPING_RUNTIME_CHECKABLE || it == TYPING_RUNTIME_CHECKABLE_EXT || it == TYPING_RUNTIME || it == TYPING_RUNTIME_EXT } ) { registerProblem(base, PyPsiBundle.message("INSP.protocol.only.runtime.checkable.protocols.can.be.used.with.instance.class.checks"), GENERIC_ERROR) } } } private fun checkNewTypeWithProtocols(node: PyCallExpression) { val resolveContext = PyResolveContext.defaultContext(myTypeEvalContext) node .multiResolveCalleeFunction(resolveContext) .firstOrNull { it.qualifiedName == PyTypingTypeProvider.NEW_TYPE } ?.let { val base = node.arguments.getOrNull(1) if (base != null) { val type = myTypeEvalContext.getType(base) if (type is PyClassLikeType && isProtocol(type, myTypeEvalContext)) { registerProblem(base, PyPsiBundle.message("INSP.protocol.newtype.cannot.be.used.with.protocol.classes")) } } } } private fun checkMemberCompatibility(protocolElement: PyTypedElement, subclassElements: List<RatedResolveResult>, type: PyClassType, protocol: PyClassType) { val expectedMemberType = myTypeEvalContext.getType(protocolElement) subclassElements .asSequence() .map { it.element } .filterIsInstance<PyTypedElement>() .filter { it.containingFile == type.pyClass.containingFile } .filterNot { PyTypeChecker.match(expectedMemberType, myTypeEvalContext.getType(it), myTypeEvalContext) } .forEach { val place = if (it is PsiNameIdentifierOwner) it.nameIdentifier else it registerProblem(place, PyPsiBundle.message("INSP.protocol.element.type.incompatible.with.protocol", it.name, protocol.name)) } } } }
apache-2.0
902cfb389f58ccfa91ef669e4f84fc9c
41.824324
140
0.683496
5.02617
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/AnyWithStringConcatenationConversion.kt
2
1415
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.nj2k.conversions import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.RecursiveApplicableConversionBase import org.jetbrains.kotlin.nj2k.callOn import org.jetbrains.kotlin.nj2k.parenthesizeIfCompoundExpression import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.types.isStringType class AnyWithStringConcatenationConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKBinaryExpression) return recurse(element) if (element.operator.token == JKOperatorToken.PLUS && element.right.calculateType(typeFactory)?.isStringType() == true && element.left.calculateType(typeFactory)?.isStringType() == false ) { return recurse( JKBinaryExpression( element::left.detached().parenthesizeIfCompoundExpression() .callOn(symbolProvider.provideMethodSymbol("kotlin.Any.toString")), element::right.detached(), element.operator ).withFormattingFrom(element) ) } return recurse(element) } }
apache-2.0
bd0200d9f866590978bb11c8e86c71f4
46.2
122
0.70318
4.930314
false
false
false
false
GunoH/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/PrefixTreeMap.kt
2
5616
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.util import com.intellij.util.containers.FList import java.util.* import kotlin.collections.component1 import kotlin.collections.component2 /** * Map for fast finding values by the prefix of their keys */ internal class PrefixTreeMap<K, V> : Map<List<K>, V> { /** * Gets all descendant entries for [key] * * @return descendant entries, [emptyList] if [key] not found */ fun getAllDescendants(key: List<K>) = root.getAllDescendants(key.toFList()).toSet() /** * Gets all ancestor entries for [key] * * @return ancestor entries, [emptyList] if [key] not found */ fun getAllAncestors(key: List<K>) = root.getAllAncestors(key.toFList()).toList() fun getAllDescendantKeys(key: List<K>) = root.getAllDescendants(key.toFList()).map { it.key }.toSet() fun getAllDescendantValues(key: List<K>) = root.getAllDescendants(key.toFList()).map { it.value }.toSet() fun getAllAncestorKeys(key: List<K>) = root.getAllAncestors(key.toFList()).map { it.key }.toList() fun getAllAncestorValues(key: List<K>) = root.getAllAncestors(key.toFList()).map { it.value }.toList() private val root = Node() override val size get() = root.size override val keys get() = root.getEntries().map { it.key }.toSet() override val values: List<V> get() = valueSequence.toList() val valueSequence: Sequence<V> get() = root.getEntries().map { it.value } override val entries get() = root.getEntries().toSet() override fun get(key: List<K>) = root.get(key.toFList())?.value?.getOrNull() override fun containsKey(key: List<K>) = root.containsKey(key.toFList()) override fun containsValue(value: V) = root.getEntries().any { it.value == value } override fun isEmpty() = root.isEmpty operator fun set(path: List<K>, value: V) = root.put(path.toFList(), value).getOrNull() fun remove(path: List<K>) = root.remove(path.toFList()).getOrNull() private inner class Node { private val children = LinkedHashMap<K, Node>() val isLeaf get() = children.isEmpty() val isEmpty get() = isLeaf && !value.isPresent var size: Int = 0 private set var value = Value.empty<V>() private set private fun calculateCurrentSize() = children.values.sumOf { it.size } + if (value.isPresent) 1 else 0 private fun getAndSet(value: Value<V>) = this.value.also { this.value = value size = calculateCurrentSize() } fun put(path: FList<K>, value: V): Value<V> { val (head, tail) = path val child = children.getOrPut(head) { Node() } val previousValue = when { tail.isEmpty() -> child.getAndSet(Value.of(value)) else -> child.put(tail, value) } size = calculateCurrentSize() return previousValue } fun remove(path: FList<K>): Value<V> { val (head, tail) = path val child = children[head] ?: return Value.EMPTY val value = when { tail.isEmpty() -> child.getAndSet(Value.EMPTY) else -> child.remove(tail) } if (child.isEmpty) children.remove(head) size = calculateCurrentSize() return value } fun containsKey(path: FList<K>): Boolean { val (head, tail) = path val child = children[head] ?: return false return when { tail.isEmpty() -> child.value.isPresent else -> child.containsKey(tail) } } fun get(path: FList<K>): Node? { val (head, tail) = path val child = children[head] ?: return null return when { tail.isEmpty() -> child else -> child.get(tail) } } fun getEntries(): Sequence<Map.Entry<FList<K>, V>> { return sequence { if (value.isPresent) { yield(AbstractMap.SimpleImmutableEntry(FList.emptyList(), value.get())) } for ((key, child) in children) { for ((path, value) in child.getEntries()) { yield(AbstractMap.SimpleImmutableEntry(path.prepend(key), value)) } } } } fun getAllAncestors(path: FList<K>): Sequence<Map.Entry<FList<K>, V>> { return sequence { if (value.isPresent) { yield(java.util.Map.entry(FList.emptyList(), value.get())) } if (path.isEmpty()) return@sequence val (head, tail) = path val child = children[head] ?: return@sequence for ((relative, value) in child.getAllAncestors(tail)) { yield(java.util.Map.entry(relative.prepend(head), value)) } } } fun getAllDescendants(path: FList<K>): Sequence<MutableMap.MutableEntry<List<K>, V>> { return root.get(path)?.getEntries()?.map { java.util.Map.entry(path + it.key, it.value) } ?: emptySequence() } } private class Value<out T : Any?> private constructor(val isPresent: Boolean, private val value: Any?) { fun get(): T { @Suppress("UNCHECKED_CAST") if (isPresent) { return value as T } throw NoSuchElementException("No value present") } fun getOrNull() = if (isPresent) get() else null companion object { val EMPTY = Value<Nothing>(false, null) fun <T> empty() = EMPTY as Value<T> fun <T> of(value: T) = Value<T>(true, value) } } companion object { private operator fun <E> FList<E>.component1() = head private operator fun <E> FList<E>.component2() = tail private fun <E> List<E>.toFList() = FList.createFromReversed(asReversed()) } }
apache-2.0
680d9c1e3e77296973457f13aef2b554
31.656977
140
0.62963
3.846575
false
false
false
false
sksamuel/ktest
kotest-framework/kotest-framework-api/src/jvmMain/kotlin/io/kotest/core/config/AbstractProjectConfig.kt
1
7788
package io.kotest.core.config import io.kotest.common.ExperimentalKotest import io.kotest.core.test.TestNameCase import io.kotest.core.extensions.Extension import io.kotest.core.filter.Filter import io.kotest.core.spec.SpecExecutionOrder import io.kotest.core.listeners.Listener import io.kotest.core.spec.IsolationMode import io.kotest.core.test.AssertionMode import io.kotest.core.test.TestCaseOrder import io.kotest.core.listeners.ProjectListener import io.kotest.core.test.DuplicateTestNameMode import io.kotest.core.test.TestCaseConfig import kotlin.reflect.KClass import kotlin.time.Duration /** * Project-wide configuration. Extensions returned by an * instance of this class will be applied to all [Spec] and [TestCase]s. * * Create an object that is derived from this class and place it in your classpath. * It will be detected at runtime and the options specified here will be used to set * global configuration. */ abstract class AbstractProjectConfig { /** * List of project wide [Extension] instances. */ open fun extensions(): List<Extension> = emptyList() /** * List of project wide [Listener] instances. */ open fun listeners(): List<Listener> = emptyList() /** * List of project wide [Filter] instances. */ open fun filters(): List<Filter> = emptyList() /** * Override this function and return an instance of [SpecExecutionOrder] which will * be used to sort specs before execution. * * Implementations are currently: * - [LexicographicSpecSorter] * - [FailureFirstSpecExecutionOrder] * - [RandomSpecExecutionOrder] * * Note: This has no effect on non-JVM targets. */ open val specExecutionOrder: SpecExecutionOrder? = null /** * The [IsolationMode] set here will be applied if the isolation mode in a spec is null. */ open val isolationMode: IsolationMode? = null /** * A global timeout that is applied to all tests if not null. * Tests which define their own timeout will override this. */ open val timeout: Duration? = null /** * A global invocation timeout that is applied to all tests if not null. * Tests which define their own timeout will override this. * The value here is in millis */ open val invocationTimeout: Long? = null /** * The parallelism factor determines how many threads are used to launch tests. * * The tests inside the same spec are always executed using the same thread, to ensure * that callbacks all operate on the same thread. In other words, a spec is sticky * with regards to the execution thread. * * Increasing this value to k > 1, means that k threads are created, allowing different * specs to execute on different threads. For n specs, if you set this value to k, then * on average, each thread will service n/k specs. * * The thread choosen for a particular thread can be determined by the ThreadAllocationExtension, * which by default chooses in a round robin fashion. * * An alternative way to enable this is the system property kotest.framework.parallelism * which will always (if defined) take priority over the value here. * * Note: For backwards compatibility, setting this value to > 1 will implicitly set * [specConcurrentDispatch] to true unless that value has been explicitly set to false. */ open val parallelism: Int? = null /** * When set to true, failed specs are written to a file called spec_failures. * This file is used on subsequent test runs to run the failed specs first. * * To enable this feature, set this to true, or set the system property * 'kotest.write.specfailures=true' */ open val writeSpecFailureFile: Boolean? = null /** * Sets the order of top level tests in a spec. * The value set here will be used unless overriden in a [Spec]. * The value in a [Spec] is always taken in preference to the value here. * Nested tests will always be executed in discovery order. * * If this function returns null then the default of Sequential * will be used. */ open val testCaseOrder: TestCaseOrder? = null /** * Override this value and set it to true if you want all tests to behave as if they * were operating in an [assertSoftly] block. */ open val globalAssertSoftly: Boolean? = null /** * Override this value and set it to false if you want to disable autoscanning of extensions * and listeners. */ open val autoScanEnabled: Boolean? = null /** * Override this value with a list of classes for which @autoscan is disabled. */ open val autoScanIgnoredClasses: List<KClass<*>> = emptyList() /** * Override this value and set it to true if you want the build to be marked as failed * if there was one or more tests that were disabled/ignored. */ open val failOnIgnoredTests: Boolean = false /** * Override this value and set it to true if you want the build to be marked as failed * if no tests were executed. */ open val failOnEmptyTestSuite: Boolean? = null @ExperimentalKotest open val concurrentSpecs: Int? = null @ExperimentalKotest open val concurrentTests: Int? = null /** * Override this value to set a global [AssertionMode]. * If a [Spec] sets an assertion mode, then the spec will override. */ open val assertionMode: AssertionMode? = null /** * Any [TestCaseConfig] set here is used as the default for tests, unless overriden in a spec, * or in a test itself. In other words the order is test -> spec -> project config default -> kotest default */ open val defaultTestCaseConfig: TestCaseConfig? = null /** * Some specs have DSLs that include "prefix" words in the test name. * For example, when using ExpectSpec like this: * * expect("this test 1") { * feature("this test 2") { * } * } * * Will result in: * * Expect: this test 1 * Feature: this test 2 * * From 4.2, this feature can be disabled by setting this value to false. * Then the output of the previous test would be: * * this test 1 * this test 2 */ open val includeTestScopePrefixes: Boolean? = null /** * The casing of the tests' names can be adjusted using different strategies. It affects tests' * prefixes (I.e.: Given, When, Then) and tests' titles. * * This setting's options are defined in [TestNameCase]. Check the previous enum for the * available options and examples. */ open val testNameCase: TestNameCase? = null open val testNameRemoveWhitespace: Boolean? = null open val testNameAppendTags: Boolean? = null /** * Controls what to do when a duplicated test name is discovered. * See possible settings in [DuplicateTestNameMode]. */ open val duplicateTestNameMode: DuplicateTestNameMode? = null /** * Executed before the first test of the project, but after the * [ProjectListener.beforeProject] methods. */ open suspend fun beforeProject() {} /** * Executed before the first test of the project, but after the * [ProjectListener.beforeProject] methods. */ @Deprecated(message = "use beforeProject", replaceWith = ReplaceWith("beforeProject")) open fun beforeAll() {} /** * Executed after the last test of the project, but before the * [ProjectListener.afterProject] methods. */ open suspend fun afterProject() {} /** * Executed after the last test of the project, but before the * [ProjectListener.afterProject] methods. */ @Deprecated(message = "use afterProject", replaceWith = ReplaceWith("afterProject")) open fun afterAll() {} }
mit
1fe129e21de4e8d2526b08f522d97dc6
33.008734
111
0.690421
4.427516
false
true
false
false
mikepenz/MaterialDrawer
materialdrawer/src/main/java/com/mikepenz/materialdrawer/model/BaseDrawerItem.kt
1
1399
package com.mikepenz.materialdrawer.model import android.content.Context import android.content.res.ColorStateList import androidx.recyclerview.widget.RecyclerView import com.mikepenz.materialdrawer.holder.ImageHolder import com.mikepenz.materialdrawer.holder.StringHolder import com.mikepenz.materialdrawer.model.interfaces.* import com.mikepenz.materialdrawer.util.getPrimaryDrawerIconColor /** * An abstract [IDrawerItem] implementation providing the base properties with their default value */ abstract class BaseDrawerItem<T, VH : RecyclerView.ViewHolder> : AbstractDrawerItem<T, VH>(), Nameable, NameableColor, Iconable, SelectIconable, Tagable { override var icon: ImageHolder? = null override var iconColor: ColorStateList? = null override var selectedIcon: ImageHolder? = null override var name: StringHolder? = null override var textColor: ColorStateList? = null override var isIconTinted = false /** Allows to set the 'level' of this item */ var level = 1 @Deprecated("Please consider to replace with the actual property setter") fun withLevel(level: Int): T { this.level = level return this as T } /** * helper method to decide for the correct color * * @param ctx * @return */ open fun getIconColor(ctx: Context): ColorStateList { return ctx.getPrimaryDrawerIconColor() } }
apache-2.0
53c2c0330d6096f1405d1bf2f2388d27
33.975
154
0.736955
4.63245
false
false
false
false
Bambooin/trime
app/src/main/java/com/osfans/trime/ime/text/ComputedCandidate.kt
2
1344
package com.osfans.trime.ime.text import android.graphics.Rect /** * Data class describing a computed candidate item. * * @property geometry The geometry of the computed candidate, used to position and size the item correctly when * being drawn on a canvas. */ sealed class ComputedCandidate(val geometry: Rect) { /** * Computed word candidate, used for suggestions provided by the librime backend. * * @property word The word this computed candidate item represents. Used in the callback to provide which word * should be filled out. */ class Word( val word: String, val comment: String?, geometry: Rect ) : ComputedCandidate(geometry) { override fun toString(): String { return "Word { word=\"$word\", comment=\"$comment\", geometry=$geometry }" } } /** * Computed word candidate, used for clipboard paste suggestions. * * @property arrow The page button text this computed candidate item represents. Used in the callback to * provide which page button should be filled out. */ class Symbol( val arrow: String, geometry: Rect ) : ComputedCandidate(geometry) { override fun toString(): String { return "Symbol { arrow=$arrow, geometry=$geometry }" } } }
gpl-3.0
ed3b103a40b8aa09d63b7a97ccea19fb
31
114
0.645089
4.715789
false
false
false
false
serorigundam/numeri3
app/src/main/kotlin/net/ketc/numeri/domain/service/TweetsDisplayService.kt
1
4765
package net.ketc.numeri.domain.service import net.ketc.numeri.domain.entity.* import net.ketc.numeri.util.copy import net.ketc.numeri.util.ormlite.Transaction import net.ketc.numeri.util.ormlite.delete import net.ketc.numeri.util.ormlite.transaction import java.util.* interface TweetsDisplayService { fun createGroup(name: String): TweetsDisplayGroup fun createDisplay(group: TweetsDisplayGroup, twitterClient: TwitterClient, foreignId: Long, type: TweetsDisplayType, name: String): TweetsDisplay fun removeGroup(group: TweetsDisplayGroup) fun remove(tweetsDisplay: TweetsDisplay) fun getAllGroup(): List<TweetsDisplayGroup> fun getDisplays(group: TweetsDisplayGroup): List<TweetsDisplay> fun replace(to: TweetsDisplay, by: TweetsDisplay) } class TweetsDisplayServiceImpl : TweetsDisplayService { private val displaysMap = LinkedHashMap<TweetsDisplayGroup, MutableList<TweetsDisplay>>() init { transaction { val groupDao = dao(TweetsDisplayGroup::class) val groups = groupDao.queryForAll() groups.forEach { group -> val tweetsDisplayDao = dao(TweetsDisplay::class) val tweetsDisplayList = tweetsDisplayDao.queryBuilder() .orderBy("order", true) .where() .eq("group_id", group.id) .query() displaysMap.put(group, tweetsDisplayList) } } } override fun createGroup(name: String) = transaction { val dao = dao(TweetsDisplayGroup::class) val group = TweetsDisplayGroup(name = name) dao.create(group) displaysMap.put(group, ArrayList()) return@transaction group } override fun createDisplay(group: TweetsDisplayGroup, twitterClient: TwitterClient, foreignId: Long, type: TweetsDisplayType, name: String): TweetsDisplay = transaction { checkExistence(group) val display = createTweetsDisplay(twitterClient.toClientToken(), group, foreignId, type, name) val dao = dao(TweetsDisplay::class) display.order = dao.count { it.group.id == group.id } displaysMap[group]!!.add(display) dao.create(display) display } override fun removeGroup(group: TweetsDisplayGroup): Unit = transaction { displaysMap[group] ?: throw GroupDoesNotExistWasSpecifiedException(group) val displayDao = dao(TweetsDisplay::class) displayDao.delete { eq("group_id", group.id) } val groupDao = dao(TweetsDisplayGroup::class) groupDao.delete(group) displaysMap.remove(group) } override fun remove(tweetsDisplay: TweetsDisplay): Unit = transaction { val group = tweetsDisplay.group val displays = displaysMap[group] ?: throw GroupDoesNotExistWasSpecifiedException(group) if (!displays.remove(tweetsDisplay)) { throw DisplayDoesNotExistWasSpecifiedException() } val deleteDisplayOrder = tweetsDisplay.order val updatedDisplay = displays.filter { it.order > deleteDisplayOrder } .mapIndexed { i, tweetsDisplay -> tweetsDisplay.apply { order = deleteDisplayOrder + i } } val dao = dao(TweetsDisplay::class) updatedDisplay.forEach { dao.update(it) } dao.delete(tweetsDisplay) } override fun getAllGroup(): List<TweetsDisplayGroup> { return displaysMap.map { it.key } } override fun getDisplays(group: TweetsDisplayGroup): List<TweetsDisplay> { return displaysMap[group]?.copy() ?: throw GroupDoesNotExistWasSpecifiedException(group) } override fun replace(to: TweetsDisplay, by: TweetsDisplay): Unit = transaction { if (to.group.id != by.group.id) throw IllegalArgumentException() val temp = to.order to.order = by.order by.order = temp val displays = displaysMap[to.group] ?: throw GroupDoesNotExistWasSpecifiedException(to.group) displays.first { it.id == to.id }.order = to.order displays.first { it.id == by.id }.order = by.order displays.sortBy { it.order } val dao = dao(TweetsDisplay::class) dao.update(to) dao.update(by) } private fun Transaction.checkExistence(group: TweetsDisplayGroup) { val groupDao = dao(TweetsDisplayGroup::class) groupDao.queryForId(group.id) ?: throw GroupDoesNotExistWasSpecifiedException(group) } } class GroupDoesNotExistWasSpecifiedException(group: TweetsDisplayGroup) : IllegalArgumentException("group[$group] that does not exist was specified") class DisplayDoesNotExistWasSpecifiedException : IllegalArgumentException("display that does not exist was specified")
mit
aac886c1c6ea36f29930b2ce2f71dd2b
39.735043
174
0.680588
4.351598
false
false
false
false
cnsgcu/KotlinKoans
src/iv_properties/_32_Properties_.kt
1
515
package iv_properties import util.* class PropertyExample() { var counter = 0 var propertyWithCounter: Int? = null set(value) { counter++ field = value } } fun todoTask32(): Nothing = TODO( """ Task 32. Add a custom setter to PropertyExample.propertyWithCounter so that the 'counter' property is incremented every time 'propertyWithCounter' is assigned to. """, documentation = doc32(), references = { PropertyExample() } )
mit
ab330f54f352484aa6ed079e247d5056
22.409091
94
0.613592
4.557522
false
false
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/lists/SgListItemAdapter.kt
1
9647
package com.battlelancer.seriesguide.lists import android.content.Context import android.graphics.drawable.Drawable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat import com.battlelancer.seriesguide.R import com.battlelancer.seriesguide.databinding.ItemShowBinding import com.battlelancer.seriesguide.provider.SeriesGuideContract.ListItemTypes import com.battlelancer.seriesguide.lists.database.SgListItemWithDetails import com.battlelancer.seriesguide.provider.SgRoomDatabase import com.battlelancer.seriesguide.settings.DisplaySettings import com.battlelancer.seriesguide.shows.overview.SeasonTools import com.battlelancer.seriesguide.shows.tools.ShowStatus import com.battlelancer.seriesguide.util.ImageTools import com.battlelancer.seriesguide.util.TextTools import com.battlelancer.seriesguide.util.TimeTools import java.util.Date class SgListItemAdapter( private val context: Context, private val onItemClickListener: OnItemClickListener ) : ListAdapter<SgListItemWithDetails, SgListItemViewHolder>(DIFF_CALLBACK) { private val drawableStar = VectorDrawableCompat .create(context.resources, R.drawable.ic_star_black_24dp, context.theme)!! private val drawableStarZero = VectorDrawableCompat .create(context.resources, R.drawable.ic_star_border_black_24dp, context.theme)!! override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SgListItemViewHolder { return SgListItemViewHolder( ItemShowBinding.inflate( LayoutInflater.from(parent.context), parent, false ), onItemClickListener, drawableStar, drawableStarZero ) } override fun onBindViewHolder(holder: SgListItemViewHolder, position: Int) { holder.bindTo(getItem(position), context) } companion object { val DIFF_CALLBACK = object : DiffUtil.ItemCallback<SgListItemWithDetails>() { override fun areItemsTheSame( oldItem: SgListItemWithDetails, newItem: SgListItemWithDetails ): Boolean = oldItem.id == newItem.id override fun areContentsTheSame( oldItem: SgListItemWithDetails, newItem: SgListItemWithDetails ): Boolean = oldItem == newItem } } interface OnItemClickListener { fun onItemClick(anchor: View, item: SgListItemWithDetails) fun onMenuClick(anchor: View, item: SgListItemWithDetails) fun onFavoriteClick(showId: Long, isFavorite: Boolean) } } class SgListItemViewHolder( private val binding: ItemShowBinding, onItemClickListener: SgListItemAdapter.OnItemClickListener, private val drawableStar: Drawable, private val drawableStarZero: Drawable ) : RecyclerView.ViewHolder(binding.root) { var item: SgListItemWithDetails? = null init { // item binding.root.setOnClickListener { view -> item?.let { onItemClickListener.onItemClick(view, it) } } // favorite star binding.favoritedLabel.setOnClickListener { item?.let { onItemClickListener.onFavoriteClick(it.showId, !it.favorite) } } // context menu binding.imageViewShowsContextMenu.setOnClickListener { view -> item?.let { onItemClickListener.onMenuClick(view, it) } } } fun bindTo(item: SgListItemWithDetails?, context: Context) { this.item = item if (item == null) { binding.seriesname.text = null binding.favoritedLabel.setImageDrawable(null) return } // show title binding.seriesname.text = item.title // favorite label binding.favoritedLabel.apply { setImageDrawable(if (item.favorite) drawableStar else drawableStarZero) contentDescription = context.getString( if (item.favorite) { R.string.context_unfavorite } else { R.string.context_favorite } ) } // poster ImageTools.loadShowPosterResizeCrop(context, binding.showposter, item.posterSmall) // network, regular day and time, or type for legacy season/episode if (item.type == ListItemTypes.TMDB_SHOW || item.type == ListItemTypes.TVDB_SHOW) { // show details val time = item.releaseTimeOrDefault val weekDay = item.releaseWeekDayOrDefault val network = item.network val releaseTimeShow: Date? = if (time != -1) { TimeTools.getShowReleaseDateTime( context, time, weekDay, item.releaseTimeZone, item.releaseCountry, network ) } else { null } binding.textViewShowsTimeAndNetwork.text = TextTools.networkAndTime(context, releaseTimeShow, weekDay, network) // next episode info val fieldValue: String? = item.nextText if (fieldValue.isNullOrEmpty()) { // display show status if there is no next episode binding.episodetime.text = ShowStatus.getStatus(context, item.statusOrUnknown) binding.TextViewShowListNextEpisode.text = null } else { binding.TextViewShowListNextEpisode.text = fieldValue val releaseTimeEpisode = TimeTools.applyUserOffset(context, item.nextAirdateMs) val displayExactDate = DisplaySettings.isDisplayExactDate(context) val dateTime = if (displayExactDate) { TimeTools.formatToLocalDateShort(context, releaseTimeEpisode) } else { TimeTools.formatToLocalRelativeTime(context, releaseTimeEpisode) } if (TimeTools.isSameWeekDay(releaseTimeEpisode, releaseTimeShow, weekDay)) { // just display date binding.episodetime.text = dateTime } else { // display date and explicitly day binding.episodetime.text = context.getString( R.string.format_date_and_day, dateTime, TimeTools.formatToLocalDay(releaseTimeEpisode) ) } } // remaining count setRemainingCount(item.unwatchedCount) } else if (item.type == ListItemTypes.SEASON) { binding.textViewShowsTimeAndNetwork.setText(R.string.season) binding.episodetime.text = null binding.textViewShowsRemaining.visibility = View.GONE // Note: Running query in adapter, but it's for legacy items, so fine for now. val sesaonTvdbId: Int = item.itemRefId.toIntOrNull() ?: 0 val seasonNumbersOrNull = SgRoomDatabase.getInstance(context).sgSeason2Helper() .getSeasonNumbersByTvdbId(sesaonTvdbId) if (seasonNumbersOrNull != null) { binding.TextViewShowListNextEpisode.text = SeasonTools.getSeasonString( context, seasonNumbersOrNull.number ) } else { binding.TextViewShowListNextEpisode.setText(R.string.unknown) } } else if (item.type == ListItemTypes.EPISODE) { binding.textViewShowsTimeAndNetwork.setText(R.string.episode) binding.textViewShowsRemaining.visibility = View.GONE // Note: Running query in adapter, but it's for legacy items, so fine for now. val episodeTvdbId: Int = item.itemRefId.toIntOrNull() ?: 0 val helper = SgRoomDatabase.getInstance(context).sgEpisode2Helper() val episodeIdOrZero = helper.getEpisodeIdByTvdbId(episodeTvdbId) val episodeInfo = if (episodeIdOrZero > 0) { helper.getEpisodeInfo(episodeIdOrZero) } else null if (episodeInfo != null) { binding.TextViewShowListNextEpisode.text = TextTools.getNextEpisodeString( context, episodeInfo.season, episodeInfo.episodenumber, episodeInfo.title ) val releaseTime = episodeInfo.firstReleasedMs if (releaseTime != -1L) { // "in 15 mins (Fri)" val actualRelease = TimeTools.applyUserOffset(context, releaseTime) binding.episodetime.text = context.getString( R.string.format_date_and_day, TimeTools.formatToLocalRelativeTime(context, actualRelease), TimeTools.formatToLocalDay(actualRelease) ) } } else { binding.TextViewShowListNextEpisode.setText(R.string.unknown) binding.episodetime.text = null } } } private fun setRemainingCount(unwatched: Int) { val textView = binding.textViewShowsRemaining textView.text = TextTools.getRemainingEpisodes(textView.resources, unwatched) if (unwatched > 0) { textView.visibility = View.VISIBLE } else { textView.visibility = View.GONE } } }
apache-2.0
34f320e87fee8bac26fb75a1484cdc58
40.051064
95
0.63201
5.104233
false
false
false
false
VerifAPS/verifaps-lib
lang/src/main/kotlin/edu/kit/iti/formal/automation/st/HccPrinter.kt
1
15593
package edu.kit.iti.formal.automation.st import edu.kit.iti.formal.automation.VariableScope import edu.kit.iti.formal.automation.datatypes.* import edu.kit.iti.formal.automation.datatypes.values.Value import edu.kit.iti.formal.automation.il.IlPrinter import edu.kit.iti.formal.automation.operators.Operators import edu.kit.iti.formal.automation.scope.Scope import edu.kit.iti.formal.automation.st.ast.* import edu.kit.iti.formal.util.CodeWriter import edu.kit.iti.formal.util.joinInto import edu.kit.iti.formal.util.meta open class HccPrinter(sb: CodeWriter = CodeWriter(), noPreamble: Boolean = false) : StructuredTextPrinter(sb) { init { if (!noPreamble) { sb.print(""" int nondet_int() { int i; return i; } int nondet_bool() { return nondet_int()?0:1; } int nondet_enum() { return nondet_int(); } """.trimIndent()) } } override fun visit(empty: EMPTY_EXPRESSION) { sb.print("/* empty expression */") } override fun visit(enumerationTypeDeclaration: EnumerationTypeDeclaration) { super.visit(enumerationTypeDeclaration) } override fun visit(stringTypeDeclaration: StringTypeDeclaration) { sb.printf("string") } override fun visit(exitStatement: ExitStatement) { sb.printf("break;") } override fun visit(binaryExpression: BinaryExpression) { if (binaryExpression.operator == Operators.POWER) { sb.printf("pow( ") binaryExpression.leftExpr.accept(this) sb.printf(", ") binaryExpression.rightExpr.accept(this) sb.append(')') } else { sb.append('(') binaryExpression.leftExpr.accept(this) when (binaryExpression.operator) { Operators.MOD -> sb.printf(" % ") Operators.AND -> sb.printf(" && ") Operators.OR -> sb.printf(" || ") Operators.XOR -> sb.printf(" ^ ") Operators.EQUALS -> sb.printf(" == ") Operators.NOT_EQUALS -> sb.printf(" != ") else -> sb.printf(" ${binaryExpression.operator.symbol} ") } binaryExpression.rightExpr.accept(this) sb.append(')') } } override fun visit(assignmentStatement: AssignmentStatement) { sb.nl() assignmentStatement.location.accept(this) sb.printf(" = ") assignmentStatement.expression.accept(this) sb.printf(";") } override fun visit(init: IdentifierInitializer) { sb.printf("THERE").printf(init.value!!) } override fun visit(repeatStatement: RepeatStatement) { sb.nl() sb.printf("do {").increaseIndent() repeatStatement.statements.accept(this) sb.decreaseIndent().nl().printf("} while ( ") repeatStatement.condition.accept(this) sb.printf(" )") } override fun visit(whileStatement: WhileStatement) { sb.nl() sb.printf("while( ") whileStatement.condition.accept(this) sb.printf(" ) {").increaseIndent() whileStatement.statements.accept(this) sb.decreaseIndent().nl() sb.printf("}") } override fun visit(unaryExpression: UnaryExpression) { when (unaryExpression.operator) { Operators.NOT -> sb.printf("!") else -> sb.printf(unaryExpression.operator.symbol) } unaryExpression.expression.accept(this) } override fun visit(caseStatement: CaseStatement) { sb.nl().printf("switch( ") caseStatement.expression.accept(this) sb.printf(" )").increaseIndent().nl().printf("{").nl() for (c in caseStatement.cases) { c.accept(this) sb.nl() //TODO "break;" ? } if (caseStatement.elseCase.size > 0) { sb.nl().printf("default: ") caseStatement.elseCase.accept(this) } sb.nl().decreaseIndent().appendIdent().printf("}") } override fun visit(programDeclaration: ProgramDeclaration) { printComment(programDeclaration.comment) sb.printf("/* program ").printf(programDeclaration.name).printf(" */").nl() sb.printf("void main(void) {").increaseIndent() programDeclaration.scope.accept(this) sb.nl() if (!programDeclaration.actions.isEmpty()) { programDeclaration.actions.forEach { v -> v.accept(this) } sb.nl() } printBody(programDeclaration) sb.decreaseIndent().nl().printf("}").nl().printf("/* end program */").nl() } override fun visit(forStatement: ForStatement) { sb.nl() sb.printf("for( int ").printf(forStatement.variable) sb.printf(" = ") forStatement.start.accept(this) sb.printf("; ").printf(forStatement.variable) sb.printf(" < ") forStatement.stop.accept(this) sb.printf("; ").printf(forStatement.variable).printf("++) {").increaseIndent() forStatement.statements.accept(this) sb.decreaseIndent().nl() sb.printf("}") } override fun visit(functionDeclaration: FunctionDeclaration) { printComment(functionDeclaration.comment) sb.printf("/* function ").printf(functionDeclaration.name).printf(" */").nl() val returnType = functionDeclaration.returnType.identifier if (!(returnType == null || returnType.isEmpty())) sb.printf(returnType.toLowerCase()).printf(" ${functionDeclaration.name}( ") functionDeclaration.scope.variables.filter { it.isInput || it.isInOut }.forEachIndexed { i, it -> if (i != 0) { sb.printf(", ") } variableDataType(it) sb.printf(" ").printf(it.name) } sb.printf(" ) {").increaseIndent().nl() val scopeWithoutInput = Scope(functionDeclaration.scope.variables.filter { !it.isInput && !it.isInOut }) scopeWithoutInput.accept(this) printBody(functionDeclaration) val outVars = functionDeclaration.scope.variables.filter { it.isOutput || it.isInOut } if (outVars.isNotEmpty()) sb.nl().printf("return ${outVars.first().name};") sb.decreaseIndent().nl().printf("}").nl().printf("/* end function */").nl().nl() } override fun visit(returnStatement: ReturnStatement) { sb.nl().printf("return;") } override fun visit(ifStatement: IfStatement) { for (i in 0 until ifStatement.conditionalBranches.size) { sb.nl() if (i == 0) sb.printf("if( ") else sb.printf("} else if( ") ifStatement.conditionalBranches[i].condition.accept(this) sb.printf(" ) {").increaseIndent() ifStatement.conditionalBranches[i].statements.accept(this) sb.decreaseIndent() } if (ifStatement.elseBranch.size > 0) { sb.nl().printf("} else {").increaseIndent() ifStatement.elseBranch.accept(this) sb.decreaseIndent() } sb.nl().printf("}") } override fun visit(aCase: Case) { sb.nl() sb.printf("case ") aCase.conditions.joinInto(sb) { it.accept(this) } sb.printf(":") sb.block() { aCase.statements.accept(this@HccPrinter) } } override fun visit(simpleTypeDeclaration: SimpleTypeDeclaration) { if (simpleTypeDeclaration.baseType.obj is AnyBit.BOOL) { sb.printf("int") } else if (simpleTypeDeclaration.baseType.obj is EnumerateType) { sb.printf("int") } else if (simpleTypeDeclaration.baseType.obj is UINT) { sb.printf("unsigned int") } else { sb.printf(simpleTypeDeclaration.baseType.identifier!!.toLowerCase()) } } override fun visit(commentStatement: CommentStatement) { if (isPrintComments) { sb.nl() sb.printf("/* ") sb.printf(commentStatement.comment) sb.printf(" */") } val meta: SpecialCommentMeta? = commentStatement.meta<SpecialCommentMeta>() when (meta) { is SpecialCommentMeta.AssertComment -> { sb.nl() sb.printf("assert( ") meta.expr.accept(this) sb.printf(" );") } is SpecialCommentMeta.AssumeComment -> { sb.nl() sb.printf("assume( ") meta.expr.accept(this) sb.printf(" );") } is SpecialCommentMeta.HavocComment -> { sb.nl() val haveocName = "nondet_${meta.dataType.name.toLowerCase()}();" //sb.printf(" ").printf(haveocName).printf(" = _;").nl() //uninitialised Var sb.printf(meta.variable).printf(" = ").printf(haveocName) } } } override fun visit(literal: Literal) { fun print(prefix: Any?, suffix: Any) = "$suffix" sb.printf(when (literal) { is IntegerLit -> print(literal.dataType.obj?.name, literal.value.abs()) is RealLit -> print(literal.dataType.obj?.name, literal.value.abs()) //TODO maybe print the integer value is EnumLit -> ("${literal.dataType.obj?.name}__${literal.value}") is ToDLit -> { val (h, m, s, ms) = literal.value print(literal.dataType().name, "$h:$m:$s.$ms") } is DateLit -> { val (y, m, d) = literal.value print(literal.dataType().name, "$y-$m-$d") } is DateAndTimeLit -> { val (y, mo, d) = literal.value.date val (h, m, s, ms) = literal.value.tod print(literal.dataType().name, "$y-$mo-$d-$h:$m:$s.$ms") } is StringLit -> { if (literal.dataType() is IECString.WSTRING) "\"${literal.value}\"" else "'${literal.value}'" } is NullLit -> "null" is TimeLit -> { print(literal.dataType().name, "${literal.value.milliseconds}ms") } is BooleanLit -> { if (literal == BooleanLit.LTRUE) { "1" } else { "0" } } is BitLit -> { print(literal.dataType.obj?.name, "2#" + literal.value.toString(2)) } is UnindentifiedLit -> literal.value }) } override fun visit(localScope: Scope) { if (localScope.topLevel != localScope) visitVariables(localScope.topLevel.variables) val variables = VariableScope(localScope.variables) visitVariables(variables) } private fun visitVariables(variables: VariableScope) { variables.groupBy { it.type } .forEach { (type, v) -> val vars = v.toMutableList() vars.sortWith(compareBy { it.name }) sb.nl().printf("/* VAR") if (VariableDeclaration.INPUT and type >= VariableDeclaration.INOUT) { sb.printf("_INOUT") } else { when { VariableDeclaration.INPUT and type != 0 -> sb.printf("_INPUT") VariableDeclaration.OUTPUT and type != 0 -> sb.printf("_OUTPUT") VariableDeclaration.EXTERNAL and type != 0 -> sb.printf("_EXTERNAL") VariableDeclaration.GLOBAL and type != 0 -> sb.printf("_GLOBAL") VariableDeclaration.TEMP and type != 0 -> sb.printf("_TEMP") } } sb.printf(" ") if (VariableDeclaration.CONSTANT and type != 0) sb.printf("CONSTANT ") if (VariableDeclaration.RETAIN and type != 0) sb.printf("RETAIN ") sb.printf("*/") //sb.printf(type) sb.increaseIndent() for (vd in vars) { print(vd) } sb.decreaseIndent().nl().printf("/* END_VAR */") sb.nl() } } override fun print(vd: VariableDeclaration) { sb.nl() variableDataType(vd) sb.printf(" ").printf(vd.name) when { vd.initValue != null -> { sb.printf(" = ") val (dt, v) = vd.initValue as Value<*, *> when (dt) { is AnyBit.BOOL -> { if (v == true) { sb.printf("1") } else if (v == false) { sb.printf("0") } } is EnumerateType -> { sb.printf("${dt.name}__${v}") } else -> sb.printf(v.toString()) } } vd.init != null -> { sb.printf(" = ") vd.init!!.accept(this) } } sb.printf(";") } //copied private fun variableDataType(vd: VariableDeclaration) { val dt = vd.dataType if (variableDeclarationUseDataType && dt != null) { variableDataType(dt) } else { vd.typeDeclaration?.accept(this) } } override fun visit(jump: JumpStatement) { sb.nl().write("goto ${jump.target};") } // private functions //copied private fun printBody(a: HasBody) { val stBody = a.stBody val sfcBody = a.sfcBody val ilBody = a.ilBody loop@ for (type in bodyPrintingOrder) { when (type) { BodyPrinting.ST -> stBody?.accept(this) ?: continue@loop BodyPrinting.SFC -> sfcBody?.accept(this) ?: continue@loop BodyPrinting.IL -> ilBody?.accept(IlPrinter(sb)) ?: continue@loop } break@loop } } //adapted private fun printComment(comment: String) { if (comment.isNotBlank()) { sb.printf("/*") sb.printf(comment) sb.printf("*/").nl() } } } object SpecialCommentFactory { fun createHavoc(name: String, dt: AnyDt): CommentStatement { val comment = CommentStatement("havoc $name") comment.meta<SpecialCommentMeta>(SpecialCommentMeta.HavocComment(name, dt)) return comment } fun createAssume(expression: Expression): CommentStatement { val comment = CommentStatement("assumption of constraints") comment.meta<SpecialCommentMeta>(SpecialCommentMeta.AssumeComment(expression)) return comment } fun createAssert(expression: Expression): Statement { val comment = CommentStatement("assert") comment.meta<SpecialCommentMeta>(SpecialCommentMeta.AssertComment(expression)) return comment } } sealed class SpecialCommentMeta { class AssertComment(var expr: Expression) : SpecialCommentMeta() class AssumeComment(var expr: Expression) : SpecialCommentMeta() class HavocComment(var variable: String, val dataType: AnyDt) : SpecialCommentMeta() }
gpl-3.0
74521e502aa7884cb9dfbb7a7428bf22
32.038136
112
0.535817
4.510558
false
false
false
false
AndroidX/constraintlayout
projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/LaMotion.kt
2
3472
/* * 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.example.constraintlayout import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment.Companion.CenterHorizontally import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.layoutId import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.constraintlayout.compose.Arc import androidx.constraintlayout.compose.ConstraintSet import androidx.constraintlayout.compose.Motion import androidx.constraintlayout.compose.MotionLayout import androidx.constraintlayout.compose.MotionLayoutDebugFlags import androidx.constraintlayout.compose.MotionScene import androidx.constraintlayout.compose.RelativePosition import androidx.constraintlayout.compose.rememberMotionContent import java.util.* import kotlin.collections.ArrayList @Preview(group = "LookAheadMotion") @Composable public fun LaMotion01() { var vert: Boolean by remember { mutableStateOf(true) } var words = "This is a test of motionLayout".split(' ') val animationSpec: AnimationSpec<Float> = tween(2000) val s = rememberMotionContent { for (word in words) { Text(modifier = Modifier .padding(2.dp) .motion(animationSpec) { motionArc = Arc.ArcDown // keyPositions { // frame(50) { // type = RelativePosition.Delta // percentX = if (vert) 0f else 1.0f // // } // } }, text = word) } } Motion(modifier = Modifier .fillMaxWidth() .fillMaxHeight()) { Column(modifier = Modifier.background(Color.LightGray)) { Button(onClick = { vert = !vert }) { Text(modifier = Modifier.motion(), text = "Click") } if (vert) { Row() { s() } } else Column() { s() } } } }
apache-2.0
b151e67be11eb1a67e08c8e286a3243b
34.793814
75
0.696141
4.623169
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-locks-bukkit/src/main/kotlin/com/rpkit/locks/bukkit/listener/PlayerInteractListener.kt
1
8547
/* * Copyright 2022 Ren 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.locks.bukkit.listener import com.rpkit.characters.bukkit.character.RPKCharacter import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.bukkit.location.toRPKBlockLocation import com.rpkit.core.service.Services import com.rpkit.locks.bukkit.RPKLocksBukkit import com.rpkit.locks.bukkit.keyring.RPKKeyringService import com.rpkit.locks.bukkit.lock.RPKLockService import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import org.bukkit.block.Block import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.PlayerInteractEvent import org.bukkit.inventory.ItemStack class PlayerInteractListener(private val plugin: RPKLocksBukkit) : Listener { @EventHandler fun onPlayerInteract(event: PlayerInteractEvent) { val clickedBlock = event.clickedBlock ?: return val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] if (minecraftProfileService == null) { event.isCancelled = true return } val characterService = Services[RPKCharacterService::class.java] if (characterService == null) { event.isCancelled = true return } val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(event.player) if (minecraftProfile == null) { event.isCancelled = true return } val character = characterService.getPreloadedActiveCharacter(minecraftProfile) if (character == null) { event.isCancelled = true return } val lockService = Services[RPKLockService::class.java] if (lockService == null) { event.isCancelled = true return } var block: Block? = null xLoop@ for (x in clickedBlock.x - 1..clickedBlock.x + 1) { for (y in clickedBlock.y - 1..clickedBlock.y + 1) { for (z in clickedBlock.z - 1..clickedBlock.z + 1) { if (lockService.isLocked(clickedBlock.world.getBlockAt(x, y, z).toRPKBlockLocation())) { block = clickedBlock.world.getBlockAt(x, y, z) break@xLoop } } } } if (lockService.isClaiming(minecraftProfile)) { if (block != null) { event.player.sendMessage(plugin.messages.lockInvalidAlreadyLocked) event.isCancelled = true return } if (event.player.inventory.itemInMainHand.amount == 1) { event.player.inventory.setItemInMainHand(null) } else { event.player.inventory.itemInMainHand.amount = event.player.inventory.itemInMainHand.amount - 1 } lockService.setLocked(clickedBlock.toRPKBlockLocation(), true) for (item in event.player.inventory.addItem(lockService.getKeyFor(clickedBlock.toRPKBlockLocation())).values) { event.player.world.dropItem(event.player.location, item) } event.player.updateInventory() event.player.sendMessage(plugin.messages.lockSuccessful) event.isCancelled = true } else if (lockService.isUnclaiming(minecraftProfile)) { if (block != null) { if (hasKey(character, block)) { lockService.setLocked(block.toRPKBlockLocation(), false).thenRun { plugin.server.scheduler.runTask(plugin, Runnable { event.player.sendMessage(plugin.messages.unlockSuccessful) removeKey(character, block) event.player.inventory.addItem(lockService.lockItem) event.player.updateInventory() }) } } else { event.player.sendMessage(plugin.messages.unlockInvalidNoKey) } } else { event.player.sendMessage(plugin.messages.unlockInvalidNotLocked) } lockService.setUnclaiming(minecraftProfile, false) event.isCancelled = true } else if (lockService.isGettingKey(minecraftProfile)) { if (block == null) { event.player.sendMessage(plugin.messages.getKeyInvalidNotLocked) } else { for (item in event.player.inventory.addItem(lockService.getKeyFor(block.toRPKBlockLocation())).values) { event.player.world.dropItem(event.player.location, item) } event.player.updateInventory() event.player.sendMessage(plugin.messages.getKeySuccessful) } lockService.setGettingKey(minecraftProfile, false) event.isCancelled = true } else { if (block == null) return if (hasKey(character, block)) return event.isCancelled = true event.player.sendMessage(plugin.messages.blockLocked.withParameters( blockType = block.type )) } } private fun hasKey(character: RPKCharacter, block: Block): Boolean { val lockService = Services[RPKLockService::class.java] ?: return false val keyringService = Services[RPKKeyringService::class.java] ?: return false val minecraftProfile = character.minecraftProfile if (minecraftProfile != null) { val offlineBukkitPlayer = plugin.server.getOfflinePlayer(minecraftProfile.minecraftUUID) val bukkitPlayer = offlineBukkitPlayer.player if (bukkitPlayer != null) { val inventory = bukkitPlayer.inventory val inventoryContents = inventory.contents return keyringService.getPreloadedKeyring(character) ?.any { it?.isSimilar(lockService.getKeyFor(block.toRPKBlockLocation())) == true } ?: false || inventoryContents .filterNotNull() .any { it.isSimilar(lockService.getKeyFor(block.toRPKBlockLocation())) } } } return false } private fun removeKey(character: RPKCharacter, block: Block) { val lockService = Services[RPKLockService::class.java] ?: return val keyringService = Services[RPKKeyringService::class.java] ?: return val keyring = keyringService.getPreloadedKeyring(character) if (keyring != null) { val iterator = keyring.iterator() while (iterator.hasNext()) { val key = iterator.next() if (key?.isSimilar(lockService.getKeyFor(block.toRPKBlockLocation())) == true) { if (key.amount > 1) { key.amount = key.amount - 1 } else { iterator.remove() } return } } keyringService.setKeyring(character, keyring) } val minecraftProfile = character.minecraftProfile if (minecraftProfile != null) { val offlineBukkitPlayer = plugin.server.getOfflinePlayer(minecraftProfile.minecraftUUID) val bukkitPlayer = offlineBukkitPlayer.player if (bukkitPlayer != null) { val inventory = bukkitPlayer.inventory val inventoryContents = inventory.contents for (key in inventoryContents) { if (key.isSimilar(lockService.getKeyFor(block.toRPKBlockLocation()))) { val oneKey = ItemStack(key) oneKey.amount = 1 inventory.removeItem(oneKey) return } } } } } }
apache-2.0
cd212c55a43e36b6729084bdd813be5e
43.984211
123
0.601498
5.057396
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/ide/intentions/ContractModuleIntention.kt
1
1186
package org.rust.ide.intentions import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.impl.file.PsiFileImplUtil import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil import org.rust.lang.core.psi.RustMod import org.rust.lang.core.psi.impl.RustFile class ContractModuleIntention : IntentionAction { override fun getFamilyName() = "Contract module structure" override fun getText() = "Contract module" override fun startInWriteAction() = true override fun isAvailable(project: Project, editor: Editor, file: PsiFile) = file is RustFile && file.name == RustMod.MOD_RS && file.containingDirectory?.children?.size == 1 override fun invoke(project: Project, editor: Editor, file: PsiFile) { val parent = file.parent ?: return val dst = parent.parent ?: return val fileName = "${parent.name}.rs" PsiFileImplUtil.setName(file, fileName) MoveFilesOrDirectoriesUtil.doMoveFile(file, dst) parent.delete() } }
mit
225e86ae6d4e9f66f5c7e6b0d07e0643
37.258065
86
0.732715
4.441948
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/roleplay/declarations/RoleplayCommand.kt
1
2853
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.roleplay.declarations import net.perfectdreams.loritta.common.locale.LanguageManager import net.perfectdreams.loritta.common.utils.TodoFixThisData import net.perfectdreams.loritta.i18n.I18nKeysData import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.common.commands.CommandCategory import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandDeclarationWrapper import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.roleplay.RoleplayAttackExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.roleplay.RoleplayDanceExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.roleplay.RoleplayHeadPatExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.roleplay.RoleplayHighFiveExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.roleplay.RoleplayHugExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.roleplay.RoleplayKissExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.roleplay.RoleplaySlapExecutor import net.perfectdreams.randomroleplaypictures.client.RandomRoleplayPicturesClient class RoleplayCommand(languageManager: LanguageManager) : CinnamonSlashCommandDeclarationWrapper(languageManager) { companion object { val I18N_PREFIX = I18nKeysData.Commands.Command.Roleplay } override fun declaration() = slashCommand(I18N_PREFIX.Label, CommandCategory.ROLEPLAY, TodoFixThisData) { subcommand(I18N_PREFIX.Hug.Label, I18N_PREFIX.Hug.Description) { executor = { RoleplayHugExecutor(it, it.randomRoleplayPicturesClient) } } subcommand(I18N_PREFIX.Kiss.Label, I18N_PREFIX.Kiss.Description) { executor = { RoleplayKissExecutor(it, it.randomRoleplayPicturesClient) } } subcommand(I18N_PREFIX.Slap.Label, I18N_PREFIX.Slap.Description) { executor = { RoleplaySlapExecutor(it, it.randomRoleplayPicturesClient) } } subcommand(I18N_PREFIX.Headpat.Label, I18N_PREFIX.Headpat.Description) { executor = { RoleplayHeadPatExecutor(it, it.randomRoleplayPicturesClient) } } subcommand(I18N_PREFIX.Highfive.Label, I18N_PREFIX.Highfive.Description) { executor = { RoleplayHighFiveExecutor(it, it.randomRoleplayPicturesClient) } } subcommand(I18N_PREFIX.Attack.Label, I18N_PREFIX.Attack.Description) { executor = { RoleplayAttackExecutor(it, it.randomRoleplayPicturesClient) } } subcommand(I18N_PREFIX.Dance.Label, I18N_PREFIX.Dance.Description) { executor = { RoleplayDanceExecutor(it, it.randomRoleplayPicturesClient) } } } }
agpl-3.0
9f1ae20c15dace34cec380d6ae897d18
53.884615
115
0.788644
4.046809
false
false
false
false
STUDIO-apps/GeoShare_Android
mobile/src/main/java/uk/co/appsbystudio/geoshare/utils/GPSTracking.kt
1
2624
package uk.co.appsbystudio.geoshare.utils import android.annotation.SuppressLint import android.content.Context import android.location.Location import android.location.LocationListener import android.location.LocationManager import android.os.Bundle import com.google.android.gms.maps.model.LatLng class GPSTracking(private val context: Context?) : LocationListener { private var location: Location? = null private var locationManager: LocationManager? = null private var latitude: Double = 51.512467 private var longitude: Double = -0.093265 val latLng: LatLng get() = LatLng(latitude, longitude) init { setLocation() } private fun setLocation() { try { locationManager = context?.getSystemService(Context.LOCATION_SERVICE) as LocationManager var gpsEnabled = false var networkEnabled = false if (locationManager != null) { gpsEnabled = locationManager!!.isProviderEnabled(LocationManager.GPS_PROVIDER) networkEnabled = locationManager!!.isProviderEnabled(LocationManager.NETWORK_PROVIDER) } if (networkEnabled) { setLocationManager(LocationManager.NETWORK_PROVIDER) } if (gpsEnabled) { if (location == null) { setLocationManager(LocationManager.GPS_PROVIDER) } } } catch (e: Exception) { e.printStackTrace() } } @SuppressLint("MissingPermission") private fun setLocationManager(provider: String) { locationManager?.requestLocationUpdates(provider, TIME_TO_UPDATE, DISTANCE_TO_CHANGE.toFloat(), this) location = locationManager?.getLastKnownLocation(provider) if (location != null && location is Location) { latitude = location!!.latitude longitude = location!!.longitude } } fun getLatitude(): Double { if (location != null) latitude = location!!.latitude return latitude } fun getLongitude(): Double { if (location != null) longitude = location!!.longitude return longitude } override fun onLocationChanged(location: Location) { this.location = location } override fun onStatusChanged(s: String, i: Int, bundle: Bundle) { } override fun onProviderEnabled(s: String) { } override fun onProviderDisabled(s: String) { } companion object { private const val DISTANCE_TO_CHANGE: Long = 0 private const val TIME_TO_UPDATE: Long = 500 } }
apache-2.0
61ad5e1abc91709fa8783b5f55af888f
28.483146
109
0.642912
5.145098
false
false
false
false
zametki/zametki
src/main/java/com/github/zametki/db/sql/UsersSql.kt
1
1291
package com.github.zametki.db.sql import com.github.mjdbc.Bind import com.github.mjdbc.BindBean import com.github.mjdbc.Sql import com.github.zametki.model.User import com.github.zametki.model.UserId /** * Set of 'users' table queries */ interface UsersSql { @Sql("SELECT * FROM users WHERE id = :id") fun selectUserById(@Bind("id") userId: UserId): User? @Sql("SELECT * FROM users WHERE login = :login") fun selectUserByLogin(@Bind("login") login: String): User? @Sql("SELECT * FROM users WHERE email = :email") fun selectUserByEmail(@Bind("email") email: String): User? @Sql("INSERT INTO users (login, password_hash, email, uid, registration_date, termination_date, last_login_date, settings) " + "VALUES (:login, :passwordHash, :email, :uid, :registrationDate, :terminationDate, :lastLoginDate, :settings)") fun insertUser(@BindBean user: User): UserId @Sql("UPDATE users SET password_hash = :hash WHERE id = :id") fun updatePasswordHash(@Bind("id") id: UserId, @Bind("hash") passwordHash: String) @Sql("UPDATE users SET settings = :settings WHERE id = :id") fun updateSettings(@BindBean user: User) @Sql("UPDATE users SET last_login_date = :lastLoginDate WHERE id = :id") fun updateLastLoginDate(@BindBean user: User) }
apache-2.0
595d20d3d502e0d163bf25a5f66e3d72
36.970588
242
0.702556
3.626404
false
false
false
false
cliffano/swaggy-jenkins
clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/DiskSpaceMonitorDescriptorDiskSpace.kt
1
1168
package org.openapitools.model import java.util.Objects import com.fasterxml.jackson.annotation.JsonProperty import javax.validation.constraints.DecimalMax import javax.validation.constraints.DecimalMin import javax.validation.constraints.Email import javax.validation.constraints.Max import javax.validation.constraints.Min import javax.validation.constraints.NotNull import javax.validation.constraints.Pattern import javax.validation.constraints.Size import javax.validation.Valid import io.swagger.v3.oas.annotations.media.Schema /** * * @param propertyClass * @param timestamp * @param path * @param propertySize */ data class DiskSpaceMonitorDescriptorDiskSpace( @Schema(example = "null", description = "") @field:JsonProperty("_class") val propertyClass: kotlin.String? = null, @Schema(example = "null", description = "") @field:JsonProperty("timestamp") val timestamp: kotlin.Int? = null, @Schema(example = "null", description = "") @field:JsonProperty("path") val path: kotlin.String? = null, @Schema(example = "null", description = "") @field:JsonProperty("size") val propertySize: kotlin.Int? = null ) { }
mit
16fa7b955550215e0d9f6284abfd0748
28.948718
75
0.753425
4.141844
false
false
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/util/Rfc3711IndexTracker.kt
1
2720
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.nlj.util import org.jitsi.rtp.util.isNewerThan import org.jitsi.rtp.util.rolledOverTo class Rfc3711IndexTracker { var roc: Int = 0 private set private var highestSeqNumReceived = -1 /** * return the index (as defined by RFC3711 at https://tools.ietf.org/html/rfc3711#section-3.3.1) * for the given seqNum, updating our ROC if we roll over. * NOTE that this method must be called for all 'received' sequence numbers so that it may keep * its rollover counter accurate */ fun update(seqNum: Int): Int { return getIndex(seqNum, true) } /** * return the index (as defined by RFC3711 at https://tools.ietf.org/html/rfc3711#section-3.3.1) * for the given [seqNum]. If [updateRoc] is [true] and we've rolled over, updates our ROC. */ private fun getIndex(seqNum: Int, updateRoc: Boolean): Int { if (highestSeqNumReceived == -1) { if (updateRoc) { highestSeqNumReceived = seqNum } return seqNum } val v = when { seqNum rolledOverTo highestSeqNumReceived -> { // Seq num was from the previous roc value roc - 1 } highestSeqNumReceived rolledOverTo seqNum -> { // We've rolled over, so update the roc in place if updateRoc // is set, otherwise return the right value (our current roc // + 1) if (updateRoc) { ++roc } else { roc + 1 } } else -> roc } if (updateRoc && (seqNum isNewerThan highestSeqNumReceived)) { highestSeqNumReceived = seqNum } return 0x1_0000 * v + seqNum } /** * Interprets an RTP sequence number in the context of the highest sequence number received. Returns the index * which corresponds to the packet, but does not update the ROC. */ fun interpret(seqNum: Int): Int { return getIndex(seqNum, false) } }
apache-2.0
b79d195b2dbc32a44652dffb69e8cdbb
32.580247
114
0.60625
4.165391
false
false
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/form/field/SelectFieldState.kt
1
715
package mil.nga.giat.mage.form.field import mil.nga.giat.mage.form.ChoiceFormField import mil.nga.giat.mage.form.FormField class SelectFieldState(definition: ChoiceFormField<String>) : FieldState<String, FieldValue.Text>( definition, validator = ::isValid, errorFor = ::errorMessage, hasValue = ::hasValue ) private fun errorMessage(definition: FormField<String>, value: FieldValue.Text?): String { return "Please enter a value" } private fun isValid(definition: FormField<String>, value: FieldValue.Text?): Boolean { return !definition.required || value?.text?.isNotEmpty() == true } private fun hasValue(value: FieldValue.Text?): Boolean { return value?.text?.isNotEmpty() == true }
apache-2.0
d82b21b6cdc392e0a0c1565fc4b6c164
28.833333
90
0.73986
3.972222
false
false
false
false
facebook/litho
litho-core-kotlin/src/main/kotlin/com/facebook/litho/KComponent.kt
1
5706
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.litho import android.content.Context import android.view.View import androidx.core.view.accessibility.AccessibilityNodeInfoCompat /** Base class for Kotlin Components. */ abstract class KComponent : Component() { companion object { /** Method that will ensure the KComponent class is loaded. */ @JvmStatic fun preload() = object : KComponent() { override fun ComponentScope.render(): Component? = null } } final override fun render( renderStateContext: RenderStateContext, c: ComponentContext, widthSpec: Int, heightSpec: Int ): RenderResult { val componentScope = ComponentScope(c, renderStateContext) val componentResult = componentScope.render() componentScope.cleanUp() return RenderResult( componentResult, componentScope.transitions, componentScope.useEffectEntries) } abstract fun ComponentScope.render(): Component? /** * Compare this component to a different one to check if they are equivalent. This is used to be * able to skip rendering a component again. */ final override fun isEquivalentProps( other: Component?, shouldCompareCommonProps: Boolean ): Boolean { if (this === other) { return true } if (other == null || javaClass != other.javaClass) { return false } if (id == other.id) { return true } if (!EquivalenceUtils.hasEquivalentFields(this, other, shouldCompareCommonProps)) { return false } return true } // All other Component lifecycle methods are made final and no-op here as they shouldn't be // overriden. final override fun canMeasure() = false final override fun canResolve() = false final override fun dispatchOnEventImpl(eventHandler: EventHandler<*>, eventState: Any) = super.dispatchOnEventImpl(eventHandler, eventState) internal final override fun getCommonDynamicProps() = super.getCommonDynamicProps() final override fun getDynamicProps() = super.getDynamicProps() final override fun getMountType() = super.getMountType() final override fun getSimpleName(): String = super.getSimpleName() final override fun hasChildLithoViews() = false internal final override fun hasCommonDynamicProps() = super.hasCommonDynamicProps() final override fun isPureRender() = false final override fun makeShallowCopy() = super.makeShallowCopy() final override fun onCreateMountContent(context: Context) = super.onCreateMountContent(context) final override fun onCreateTransition(c: ComponentContext) = super.onCreateTransition(c) final override fun onLoadStyle(c: ComponentContext) = super.onLoadStyle(c) final override fun onPopulateAccessibilityNode( c: ComponentContext, host: View, accessibilityNode: AccessibilityNodeInfoCompat, interStagePropsContainer: InterStagePropsContainer? ) = super.onPopulateAccessibilityNode(c, host, accessibilityNode, interStagePropsContainer) final override fun onPopulateExtraAccessibilityNode( c: ComponentContext, accessibilityNode: AccessibilityNodeInfoCompat, extraNodeIndex: Int, componentBoundsX: Int, componentBoundsY: Int, interStagePropsContainer: InterStagePropsContainer? ) = super.onPopulateExtraAccessibilityNode( c, accessibilityNode, extraNodeIndex, componentBoundsX, componentBoundsY, interStagePropsContainer) final override fun resolve( renderStateContext: RenderStateContext, c: ComponentContext ): LithoNode? = super.resolve(renderStateContext, c) final override fun shouldUpdate( previous: Component?, prevStateContainer: StateContainer?, next: Component?, nextStateContainer: StateContainer? ) = super.shouldUpdate(previous, prevStateContainer, next, nextStateContainer) } /** * Sets a manual key on the given Component returned in the lambda, e.g. * ``` * key("my_key") { Text(...) } * ``` */ inline fun key(key: String, componentLambda: () -> Component): Component { val component = componentLambda() setKeyForComponentInternal(component, key) return component } /** * Sets a handle on the given Component returned in the lambda, e.g. * ``` * handle(Handle()) { Text(...) } * ``` */ inline fun handle(handle: Handle, componentLambda: () -> Component): Component { val component = componentLambda() setHandleForComponentInternal(component, handle) return component } /** * This is extracted out since we don't want to expose Component.setKey in the public API and will * hopefully change this implementation in the future. */ @PublishedApi internal fun setKeyForComponentInternal(component: Component, key: String) { component.key = key } /** * This is extracted out since we don't want to expose Component.handle in the public API and will * hopefully change this implementation in the future. */ @PublishedApi internal fun setHandleForComponentInternal(component: Component, handle: Handle) { component.handle = handle }
apache-2.0
2ecfd8a63116490872f2afd4c8006824
30.351648
98
0.723624
4.575782
false
false
false
false
xfournet/intellij-community
python/src/com/jetbrains/python/codeInsight/stdlib/PyDataclassesTypeProvider.kt
1
4275
/* * Copyright 2000-2017 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.codeInsight.stdlib import com.intellij.openapi.util.Ref import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyCallExpressionNavigator import com.jetbrains.python.psi.impl.stubs.PyDataclassFieldStubImpl import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.stubs.PyDataclassFieldStub import com.jetbrains.python.psi.types.* class PyDataclassesTypeProvider : PyTypeProviderBase() { override fun getReferenceExpressionType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyType? { return getDataclassTypeForCallee(referenceExpression, context) } override fun getParameterType(param: PyNamedParameter, func: PyFunction, context: TypeEvalContext): Ref<PyType>? { if (!param.isPositionalContainer && !param.isKeywordContainer && param.annotationValue == null && func.name == DUNDER_POST_INIT) { val cls = func.containingClass if (cls != null && parseDataclassParameters(cls, context)?.init == true) { var result: Ref<PyType>? = null cls.processClassLevelDeclarations { element, _ -> if (element is PyTargetExpression && element.name == param.name && element.annotationValue != null) { result = Ref.create(getTypeForParameter(element, context)) false } else { true } } return result } } return null } private fun getDataclassTypeForCallee(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyCallableType? { if (PyCallExpressionNavigator.getPyCallExpressionByCallee(referenceExpression) == null) return null val resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context) val resolveResults = referenceExpression.getReference(resolveContext).multiResolve(false) return PyUtil.filterTopPriorityResults(resolveResults) .asSequence() .filterIsInstance<PyClass>() .map { getDataclassTypeForClass(it, context) } .firstOrNull { it != null } } private fun getDataclassTypeForClass(cls: PyClass, context: TypeEvalContext): PyCallableType? { val dataclassParameters = parseDataclassParameters(cls, context) if (dataclassParameters == null || !dataclassParameters.init) { return null } val parameters = ArrayList<PyCallableParameter>() val ellipsis = PyElementGenerator.getInstance(cls.project).createEllipsis() cls.processClassLevelDeclarations { element, _ -> if (element is PyTargetExpression && !PyTypingTypeProvider.isClassVar(element, context)) { fieldToParameter(element, ellipsis, context)?.also { parameters.add(it) } } true } return PyCallableTypeImpl(parameters, context.getType(cls)) } private fun fieldToParameter(field: PyTargetExpression, ellipsis: PyNoneLiteralExpression, context: TypeEvalContext): PyCallableParameter? { val stub = field.stub val fieldStub = if (stub == null) PyDataclassFieldStubImpl.create(field) else stub.getCustomStub(PyDataclassFieldStub::class.java) return if (fieldStub == null) { val value = when { context.maySwitchToAST(field) -> field.findAssignedValue() field.hasAssignedValue() -> ellipsis else -> null } PyCallableParameterImpl.nonPsi(field.name, getTypeForParameter(field, context), value) } else if (!fieldStub.initValue()) { null } else { val value = if (fieldStub.hasDefault() || fieldStub.hasDefaultFactory()) ellipsis else null PyCallableParameterImpl.nonPsi(field.name, getTypeForParameter(field, context), value) } } private fun getTypeForParameter(element: PyTargetExpression, context: TypeEvalContext): PyType? { val type = context.getType(element) if (type is PyCollectionType && type is PyClassType && type.classQName == DATACLASSES_INITVAR_TYPE) { return type.elementTypes.firstOrNull() } return type } }
apache-2.0
83338c56ebd9282b0f3a71f304db1953
38.229358
140
0.716491
5.083234
false
false
false
false
wordpress-mobile/WordPress-FluxC-Android
fluxc/src/main/java/org/wordpress/android/fluxc/network/rest/wpapi/WPAPIEncodedBodyRequestBuilder.kt
2
2426
package org.wordpress.android.fluxc.network.rest.wpapi import com.android.volley.Request.Method import kotlinx.coroutines.CancellableContinuation import kotlinx.coroutines.suspendCancellableCoroutine import org.wordpress.android.fluxc.network.BaseRequest import org.wordpress.android.fluxc.network.rest.wpapi.WPAPIResponse.Error import org.wordpress.android.fluxc.network.rest.wpapi.WPAPIResponse.Success import javax.inject.Inject import kotlin.coroutines.resume class WPAPIEncodedBodyRequestBuilder @Inject constructor() { suspend fun syncGetRequest( restClient: BaseWPAPIRestClient, url: String, params: Map<String, String> = emptyMap(), body: Map<String, String> = emptyMap(), enableCaching: Boolean = false, cacheTimeToLive: Int = BaseRequest.DEFAULT_CACHE_LIFETIME, nonce: String? = null ) = suspendCancellableCoroutine<WPAPIResponse<String>> { cont -> callMethod(Method.GET, url, params, body, cont, enableCaching, cacheTimeToLive, nonce, restClient) } suspend fun syncPostRequest( restClient: BaseWPAPIRestClient, url: String, params: Map<String, String> = emptyMap(), body: Map<String, String> = emptyMap(), enableCaching: Boolean = false, cacheTimeToLive: Int = BaseRequest.DEFAULT_CACHE_LIFETIME, nonce: String? = null ) = suspendCancellableCoroutine<WPAPIResponse<String>> { cont -> callMethod(Method.POST, url, params, body, cont, enableCaching, cacheTimeToLive, nonce, restClient) } @Suppress("LongParameterList") private fun callMethod( method: Int, url: String, params: Map<String, String>, body: Map<String, String>, cont: CancellableContinuation<WPAPIResponse<String>>, enableCaching: Boolean, cacheTimeToLive: Int, nonce: String?, restClient: BaseWPAPIRestClient ) { val request = WPAPIEncodedBodyRequest(method, url, params, body, { response -> cont.resume(Success(response)) }, { error -> cont.resume(Error(error)) }) cont.invokeOnCancellation { request.cancel() } if (enableCaching) { request.enableCaching(cacheTimeToLive) } if (nonce != null) { request.addHeader("x-wp-nonce", nonce) } restClient.add(request) } }
gpl-2.0
cb62f2f7646ab3fa0989ddd2a602fb33
34.15942
107
0.666529
4.517691
false
false
false
false
tinypass/piano-sdk-for-android
id/id/src/main/java/io/piano/android/id/PianoIdClient.kt
1
14964
package io.piano.android.id import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.SparseArray import com.squareup.moshi.Moshi import io.piano.android.id.models.HostResponse import io.piano.android.id.models.PianoIdApi import io.piano.android.id.models.PianoIdAuthFailureResult import io.piano.android.id.models.PianoIdAuthSuccessResult import io.piano.android.id.models.PianoIdToken import io.piano.android.id.models.PianoUserInfo import io.piano.android.id.models.PianoUserProfile import io.piano.android.id.models.SocialTokenData import io.piano.android.id.models.SocialTokenResponse import io.piano.android.id.models.toProfileUpdateRequest import okhttp3.HttpUrl import retrofit2.Call import retrofit2.Callback import retrofit2.HttpException import retrofit2.Response import timber.log.Timber import java.util.Locale /** * Piano ID authorization */ class PianoIdClient internal constructor( private val api: PianoIdApi, private val moshi: Moshi, internal val aid: String ) { private val pianoIdTokenAdapter by lazy { moshi.adapter(PianoIdToken::class.java) } private val socialTokenResponseAdapter by lazy { moshi.adapter(SocialTokenResponse::class.java) } private val socialTokenDataAdapter by lazy { moshi.adapter(SocialTokenData::class.java) } internal var hostUrl: HttpUrl? = null private val exceptions = SparseArray<PianoIdException>() internal val oauthProviders: MutableMap<String, PianoIdOAuthProvider> = mutableMapOf() var authCallback: PianoIdAuthCallback? = null private set var javascriptInterface: PianoIdJs? = null init { getHostUrl { Timber.d("Getting host success = ${it.isSuccess}") } } /** * Sets callback for {@link PianoIdAuthSuccessResult} data * * @param callback {@link PianoIdCallback} for listening changes * @return {@link PianoIdClient} instance */ @Suppress("unused") // Public API. fun with(callback: PianoIdCallback<PianoIdAuthSuccessResult>?) = apply { authCallback = callback?.run { { when (it) { is PianoIdAuthSuccessResult -> onSuccess(it) is PianoIdAuthFailureResult -> onFailure(it.exception) } } } } /** * Sets callback for {@link PianoIdToken} changes * * @param callback Callback with {@link kotlin.Result} for listening changes * @return {@link PianoIdClient} instance */ @Suppress("unused") // Public API. fun with(callback: PianoIdAuthCallback?) = apply { authCallback = callback } /** * Sets javascript interface for processing custom events * * @param jsInterface {@link PianoIdJs} instance for processing events * @return {@link PianoIdClient} instance */ fun with(jsInterface: PianoIdJs?) = apply { javascriptInterface = jsInterface } /** * Adds OAuth provider * * @param provider {@link PianoIdOAuthProvider} instance * @return {@link PianoIdClient} instance */ @Suppress("unused") // Public API. fun with(provider: PianoIdOAuthProvider) = apply { oauthProviders[provider.name.lowercase(Locale.US)] = provider } @Suppress("unused") // Public API. fun signIn(): SignInContext = SignInContext(this) internal fun getHostUrl(callback: PianoIdFuncCallback<HttpUrl>) { hostUrl?.let { callback(Result.success(it)) } ?: run { api.getDeploymentHost(aid).enqueue( object : Callback<HostResponse> { override fun onResponse(call: Call<HostResponse>, response: Response<HostResponse>) { runCatching { with(response.bodyOrThrow()) { if (!hasError) { hostUrl = HttpUrl.get(host).also { callback(Result.success(it)) } } else callback(Result.failure(PianoIdException(error))) } }.onFailure { callback(Result.failure(it.toPianoIdException())) } } override fun onFailure(call: Call<HostResponse>, t: Throwable) = callback(Result.failure(t.toPianoIdException())) } ) } } internal fun signOut(accessToken: String, callback: PianoIdFuncCallback<Any>) = getHostUrl { r -> r.getOrNull()?.resolve(SIGN_OUT_PATH)?.let { api.signOut(it.toString(), aid, accessToken) .enqueue(callback.asRetrofitCallback()) } ?: callback(Result.failure(r.exceptionOrNull() ?: PianoIdException("Can't resolve sign out url"))) } internal fun getTokenByAuthCode(authCode: String, callback: PianoIdFuncCallback<PianoIdToken>) = getHostUrl { r -> r.getOrNull()?.let { api.exchangeAuthCode( it.newBuilder().encodedPath(EXCHANGE_AUTH_CODE_PATH).build().toString(), aid, authCode ).enqueue(callback.asRetrofitCallback()) } ?: callback(Result.failure(r.exceptionOrNull()!!)) } internal fun refreshToken(refreshToken: String, callback: PianoIdFuncCallback<PianoIdToken>) = getHostUrl { r -> r.getOrNull()?.let { api.refreshToken( it.newBuilder().encodedPath(REFRESH_TOKEN_PATH).build().toString(), mapOf( PARAM_CLIENT_ID to aid, PARAM_GRANT_TYPE to VALUE_GRANT_TYPE, PARAM_REFRESH_TOKEN to refreshToken ) ) .enqueue(callback.asRetrofitCallback()) } ?: callback(Result.failure(r.exceptionOrNull()!!)) } internal fun getSignInUrl( disableSignUp: Boolean, widget: String?, stage: String?, callback: PianoIdFuncCallback<String> ) = getHostUrl { r -> callback( r.mapCatching { url -> url.newBuilder() .encodedPath(AUTH_PATH) .addQueryParameter(PARAM_RESPONSE_TYPE, VALUE_RESPONSE_TYPE_TOKEN) .addQueryParameter(PARAM_CLIENT_ID, aid) .addQueryParameter(PARAM_FORCE_REDIRECT, VALUE_FORCE_REDIRECT) .addQueryParameter(PARAM_DISABLE_SIGN_UP, disableSignUp.toString()) .addQueryParameter(PARAM_REDIRECT_URI, "$LINK_SCHEME_PREFIX$aid://$LINK_AUTHORITY") .addQueryParameter(PARAM_SDK_FLAG, VALUE_SDK_FLAG) .apply { if (!widget.isNullOrEmpty()) addQueryParameter(PARAM_SCREEN, widget) if (!stage.isNullOrEmpty()) addQueryParameter(PARAM_STAGE, stage) if (oauthProviders.isNotEmpty()) addQueryParameter( PARAM_OAUTH_PROVIDERS, oauthProviders.keys.joinToString(separator = ",") ) } .build() .toString() } ) } internal fun getUserInfo(accessToken: String, formName: String?, callback: PianoIdFuncCallback<PianoUserProfile>) { getHostUrl { r -> r.getOrNull()?.let { api.getUserInfo( it.newBuilder().encodedPath(USERINFO_PATH).build().toString(), aid, accessToken, formName ).enqueue(callback.asRetrofitCallback()) } ?: callback(Result.failure(r.exceptionOrNull()!!)) } } internal fun putUserInfo( accessToken: String, newUserInfo: PianoUserInfo, callback: PianoIdFuncCallback<PianoUserProfile> ) { getHostUrl { r -> r.getOrNull()?.let { api.putUserInfo( it.newBuilder().encodedPath(USERINFO_PATH).build().toString(), aid, accessToken, newUserInfo.toProfileUpdateRequest() ).enqueue(callback.asRetrofitCallback()) } ?: callback(Result.failure(r.exceptionOrNull()!!)) } } internal fun getFormUrl(formName: String?, hideCompletedFields: Boolean, trackingId: String) = hostUrl?.let { url -> url.newBuilder() .encodedPath(FORM_PATH) .addQueryParameter(PARAM_CLIENT_ID, aid) .addQueryParameter(PARAM_FORM_NAME, formName ?: "") .addQueryParameter(PARAM_HIDE_COMPLETE, hideCompletedFields.toString()) .addQueryParameter(PARAM_TRACKING_ID, trackingId) .addQueryParameter(PARAM_SDK_FLAG, VALUE_SDK_FLAG) .build() .toString() } ?: "about:blank" internal fun saveException(exc: PianoIdException): Int = exc.hashCode().also { exceptions.append(it, exc) } internal fun getStoredException(code: Int): PianoIdException? = exceptions.get(code) internal fun parseToken(uri: Uri, callback: PianoIdFuncCallback<PianoIdToken>) { uri.runCatching { requireNotNull(getQueryParameter(PARAM_AUTH_CODE)) { "code must be filled" } }.onFailure { callback(Result.failure(it.toPianoIdException())) }.onSuccess { getTokenByAuthCode(it, callback) } } internal fun buildToken(jsPayload: String): PianoIdToken = pianoIdTokenAdapter.fromJson(jsPayload) ?: throw PianoIdException("Invalid payload '$jsPayload'") internal fun buildSocialAuthIntent(context: Context, jsPayload: String): Intent = socialTokenResponseAdapter.fromJson(jsPayload)?.let { r -> val bundle = r.toBundle() oauthProviders[r.oauthProvider.lowercase(Locale.US)]?.buildIntent(context, bundle)?.putExtras(bundle) ?: throw PianoIdException("OAuth provider '${r.oauthProvider}' is not registered") } ?: throw PianoIdException("Invalid payload '$jsPayload'") internal fun buildResultJsCommand(provider: String, token: String): String { val socialTokenData = socialTokenDataAdapter.toJson( SocialTokenData(provider.uppercase(Locale.US), token, aid) ) return "(function(){window.PianoIDMobileSDK.socialLoginCallback('$socialTokenData')})()" } // mock in tests @Suppress("NOTHING_TO_INLINE") internal inline fun SocialTokenResponse.toBundle() = Bundle().apply { putString(PianoId.KEY_CLIENT_ID, clientId) } private inline fun <reified T> PianoIdFuncCallback<T>.asRetrofitCallback(): Callback<T> = object : Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { invoke( runCatching { response.bodyOrThrow() } ) } override fun onFailure(call: Call<T>, t: Throwable) { invoke(Result.failure(t.toPianoIdException())) } } class SignInContext internal constructor( internal val client: PianoIdClient ) { internal var disableSignUp: Boolean = false internal var widget: String? = null internal var stage: String? = null /** * Turns off the registration screen * * @return {@link SignInContext} instance */ @Suppress("unused") // Public API. fun disableSignUp() = apply { disableSignUp = true } /** * Sets the screen when opening Piano ID. Use {@link PianoId#WIDGET_LOGIN} to open the login screen * or {@link PianoId#WIDGET_REGISTER} to open the registration screen. * * @param widget {@link PianoId#WIDGET_LOGIN}, {@link PianoId#WIDGET_REGISTER} or null * @return {@link SignInContext} instance */ @Suppress("unused") // Public API. fun widget(widget: String?) = apply { this.widget = widget } /** * Sets the stage directive element value, which can be used for show or hide parts of template * * @param stage Value for passing to template * @return {@link SignInContext} instance */ @Suppress("unused") // Public API. fun stage(stage: String?) = apply { this.stage = stage } } companion object { private const val AUTH_PATH = "/id/api/v1/identity/vxauth/authorize" private const val SIGN_OUT_PATH = "/id/api/v1/identity/logout?response_type=code" private const val EXCHANGE_AUTH_CODE_PATH = "/id/api/v1/identity/passwordless/authorization/code" private const val REFRESH_TOKEN_PATH = "/id/api/v1/identity/vxauth/token" private const val USERINFO_PATH = "/id/api/v1/identity/userinfo" private const val FORM_PATH = "/id/form" internal const val LINK_SCHEME_PREFIX = "piano.id.oauth." internal const val LINK_AUTHORITY = "success" internal const val PARAM_AUTH_CODE = "code" internal const val PARAM_RESPONSE_TYPE = "response_type" internal const val PARAM_CLIENT_ID = "client_id" internal const val PARAM_FORCE_REDIRECT = "force_redirect" internal const val PARAM_DISABLE_SIGN_UP = "disable_sign_up" internal const val PARAM_REDIRECT_URI = "redirect_uri" internal const val PARAM_SDK_FLAG = "is_sdk" internal const val PARAM_SCREEN = "screen" internal const val PARAM_OAUTH_PROVIDERS = "oauth_providers" internal const val PARAM_GRANT_TYPE = "grant_type" internal const val PARAM_REFRESH_TOKEN = "refresh_token" internal const val PARAM_FORM_NAME = "form_name" internal const val PARAM_HIDE_COMPLETE = "hide_if_complete" internal const val PARAM_TRACKING_ID = "trackingId" internal const val PARAM_STAGE = "stage" internal const val VALUE_RESPONSE_TYPE_TOKEN = "token" internal const val VALUE_FORCE_REDIRECT = "1" internal const val VALUE_SDK_FLAG = "true" internal const val VALUE_GRANT_TYPE = "refresh_token" private fun <T> Response<T>.bodyOrThrow(): T { if (!isSuccessful) throw PianoIdException(HttpException(this)) return body() ?: throw PianoIdException() } internal fun Throwable.toPianoIdException(): PianoIdException = if (this is PianoIdException) this else PianoIdException(this) } }
apache-2.0
95c14f23bd611b4291ca8f9b2de123b1
39.225806
119
0.599105
4.796154
false
false
false
false
wuan/rest-demo-jersey-kotlin
src/main/java/com/tngtech/demo/weather/resources/stations/StationsResource.kt
1
2994
package com.tngtech.demo.weather.resources.stations import com.mercateo.common.rest.schemagen.JerseyResource import com.mercateo.common.rest.schemagen.types.ObjectWithSchema import com.mercateo.common.rest.schemagen.types.PaginatedList import com.mercateo.common.rest.schemagen.types.PaginatedResponse import com.mercateo.common.rest.schemagen.types.WithId import com.tngtech.demo.weather.domain.Station import com.tngtech.demo.weather.repositories.StationRepository import com.tngtech.demo.weather.resources.Paths import com.tngtech.demo.weather.resources.Roles import io.swagger.annotations.Api import org.slf4j.LoggerFactory import org.springframework.stereotype.Component import javax.annotation.security.RolesAllowed import javax.ws.rs.* import javax.ws.rs.core.MediaType @Path(Paths.STATIONS) @Component @Api(value = Paths.STATIONS, description = "stations resource") open class StationsResource( private val stationRepository: StationRepository, private val stationsHyperschemaCreator: StationsHyperschemaCreator ) : JerseyResource { companion object { val log = LoggerFactory.getLogger(StationsResource::class.java) } /** * Return a list of known airports as a json formatted list * * @return HTTP Response code and a json formatted list of IATA codes */ @GET @Produces(MediaType.APPLICATION_JSON) open fun getStations(@QueryParam(Paths.OFFSET) @DefaultValue("0") offset: Int?, @QueryParam(Paths.LIMIT) @DefaultValue("100") limit: Int?): PaginatedResponse<WithId<Station>> { var offset = offset var limit = limit log.debug("getStations({}, {}) #{}", offset, limit, stationRepository.totalCount) offset = if (offset == null) 0 else offset limit = if (limit == null) 2000 else limit val paginatedStations = PaginatedList<WithId<Station>>( stationRepository.totalCount.toInt(), offset, limit, stationRepository.getStations(offset, limit)) return stationsHyperschemaCreator.createPaginatedResponse(paginatedStations) } /** * Add a new station to the known stations list. * * @param station new station parameters * @return HTTP Response code for the add operation */ @POST @RolesAllowed(Roles.ADMIN) @Produces(MediaType.APPLICATION_JSON) open fun addStation(station: Station?): ObjectWithSchema<WithId<Station>> { if (station == null) { throw NullPointerException() } log.debug("addStation({}, {}, {})", station.name, station.latitude, station.longitude) val stationWithId = WithId.create(station) stationRepository.addStation(stationWithId) return stationsHyperschemaCreator.create(stationWithId) } @Path("/{" + Paths.STATION_ID + "}") open fun stationSubResource(): Class<StationResource> { return StationResource::class.java } }
apache-2.0
eb004966da48a569e202fa718142b25f
35.512195
121
0.706079
4.25889
false
false
false
false
ronaldsmartin/20twenty20
app/src/main/java/com/itsronald/twenty2020/notifications/Notifier.kt
1
14235
package com.itsronald.twenty2020.notifications import android.app.Notification import android.app.PendingIntent import android.content.Context import android.content.Intent import android.net.Uri import android.support.annotation.StringRes import android.support.v4.app.NotificationManagerCompat import android.support.v4.content.ContextCompat import android.support.v4.app.NotificationCompat import android.text.format.DateUtils import com.f2prateek.rx.preferences.RxSharedPreferences import com.itsronald.twenty2020.R import com.itsronald.twenty2020.data.ResourceRepository import com.itsronald.twenty2020.model.Cycle import com.itsronald.twenty2020.timer.TimerActivity import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import timber.log.Timber import java.util.Random import javax.inject.Inject import javax.inject.Singleton /** * Used to build and post notifications to the system. */ @Singleton class Notifier @Inject constructor(private val context: Context, private val preferences: RxSharedPreferences, private val resources: ResourceRepository) { companion object { //region Notification IDs /** ID for the notification for cycle phase completion */ private val ID_PHASE_COMPLETE = 20 /** ID for the persistent notification updated by ForegroundProgressService. */ const val ID_FOREGROUND_PROGRESS = 30 //endregion //region Notification actions /** Action presented with [buildPhaseCompleteNotification] to pause the cycle. */ const val ACTION_PAUSE_TIMER = "com.itsronald.twenty2020.action.timer.pause" /** Action presented with [buildPhaseCompleteNotification] to resume the cycle. */ const val ACTION_RESUME_TIMER = "com.itsronald.twenty2020.action.timer.resume" //endregion //region Notification extras /** * Int extra. Used in conjunction with [EXTRA_FLAG_CANCEL_NOTIFICATION] to describe * which notification to cancel after an action is clicked. */ const val EXTRA_NOTIFICATION_ID = "com.itsronald.twenty2020.extra.notification_id" /** * Boolean extra. If true, [NotificationActionReceiver] will cancel the notification after * handling the notification action. */ const val EXTRA_FLAG_CANCEL_NOTIFICATION = "com.itsronald.twenty2020.extra.notification_flag_cancel" //endregion } @Suppress("unused") private val foregroundNotificationSubscription = foregroundNotificationPref() .subscribe { enabled -> Timber.i(if (enabled) "Starting ForegroundProgressService" else "Ending ForegroundProgressService") val intent = Intent(context, ForegroundProgressService::class.java) if (enabled) context.startService(intent) else context.stopService(intent) } /*** * Build a new notification indicating that the current phase is complete. * * @param phaseCompleted The phase that was completed. * @return a new notification for posting */ private fun buildPhaseCompleteNotification(phaseCompleted: Cycle.Phase): Notification { val builder = NotificationCompat.Builder(context) .setSmallIcon(R.drawable.ic_notification_small) .setColor(phaseCompleteColor(phaseCompleted = phaseCompleted)) .setContentTitle(phaseCompleteContentTitle(phaseCompleted = phaseCompleted)) .setContentText(makePhaseCompleteMessage(phaseCompleted)) .setContentIntent(timerContentIntent()) .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_HIGH) .setCategory(NotificationCompat.CATEGORY_REMINDER) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setDefaults( defaultFlagsForSettings(mapOf( R.string.pref_key_notifications_vibrate to NotificationCompat.DEFAULT_VIBRATE, R.string.pref_key_notifications_led_enabled to NotificationCompat.DEFAULT_LIGHTS )) ) .setSound(preferredNotificationSound) addPhaseCompleteActionsToBuilder(builder, phaseCompleted = phaseCompleted) return builder.build() } private fun phaseCompleteColor(phaseCompleted: Cycle.Phase) = ContextCompat .getColor(context, when(phaseCompleted) { Cycle.Phase.WORK -> R.color.solarized_red Cycle.Phase.BREAK -> R.color.solarized_cyan }) private fun phaseCompleteContentTitle(phaseCompleted: Cycle.Phase) = context .getString(when(phaseCompleted) { Cycle.Phase.WORK -> R.string.notification_title_work_cycle_complete Cycle.Phase.BREAK -> R.string.notification_title_break_cycle_complete }) /** * A URI for the notification sound chosen by the user in Settings. * If the user disabled sounds in the settings, this will be null. */ private val preferredNotificationSound: Uri? get() { val soundPreferenceKey = context.getString(R.string.pref_key_notifications_sound_enabled) val soundEnabled = preferences.getBoolean(soundPreferenceKey).get() ?: false return if (soundEnabled) preferences .getString(context.getString(R.string.pref_key_notifications_ringtone)) .get()?.let { Uri.parse(it) } else null } /** * Check a SharedPreferences [Boolean] value to determine if a Notification flag should be set. * @param prefKeyID Resource ID for the String key under which the preference is stored * @param prefFlag The flag to use if the preference corresponding to [prefKeyID] is set to true. * * @return [prefFlag] if the preference for [prefKeyID] is enabled, 0 otherwise. */ private fun flagForSetting(@StringRes prefKeyID: Int, prefFlag: Int): Int = if (preferences.getBoolean(context.getString(prefKeyID)).get() ?: false) prefFlag else 0 /** * Build Notification flags using values from SharedPreferences. * * @param keysToFlags A map from String resource IDs to the Notification flags that should be * set if the * @return Notification flags to be used with [NotificationCompat.Builder.setDefaults] */ private fun defaultFlagsForSettings(keysToFlags: Map<Int, Int>): Int = keysToFlags.entries .map { flagForSetting(prefKeyID = it.key, prefFlag = it.value) } .fold(0) { combined, nextFlag -> combined or nextFlag } /** RNG used for selecting strings in [makePhaseCompleteMessage]. */ private val random = Random() /** * Generate a content message to be displayed in a PHASE_COMPLETE notification. * * @param phase The phase that was completed. * @return The message to display in a notification. */ private fun makePhaseCompleteMessage(phase: Cycle.Phase): CharSequence = when(phase) { Cycle.Phase.WORK -> workPhaseCompleteMessage() Cycle.Phase.BREAK -> { // Notify the user what time the next break will occur. val breakCycleMilliseconds = Cycle.Phase.WORK.duration(resources) * 1000 val nextCycleTime = System.currentTimeMillis() + breakCycleMilliseconds val nextTime = DateUtils.getRelativeTimeSpanString(context, nextCycleTime, true) context.getString(R.string.notification_message_break_cycle_complete, nextTime) } } private fun workPhaseCompleteMessage(): String { val exercisePrefKey = resources.getString(R.string.pref_key_general_recommend_exercise) val shouldRecommend = preferences.getBoolean(exercisePrefKey).get() if (shouldRecommend != null && shouldRecommend) { // Choose a random exercise to suggest for the break. val messages = context.resources .getStringArray(R.array.notification_messages_work_cycle_complete) return messages[random.nextInt(messages.size)] } return resources.getString(R.string.notification_message_work_cycle_complete_no_exercise) } /** * Create an [PendingIntent] that returns the user to [TimerActivity]. * * @return An intent to TimerActivity. */ private fun timerContentIntent(): PendingIntent = PendingIntent.getActivity( context, 0, TimerActivity.intent(context = context), PendingIntent.FLAG_CANCEL_CURRENT ) private fun addPhaseCompleteActionsToBuilder(builder: NotificationCompat.Builder, phaseCompleted: Cycle.Phase): NotificationCompat.Builder { val autostartPrefKey = resources.getString(R.string.pref_key_general_auto_start_next_phase) val shouldAutoStartNextPhase = preferences.getBoolean(autostartPrefKey).get() ?: true if (shouldAutoStartNextPhase) { builder.addAction( R.drawable.ic_alarm_off_white_24dp, resources.getString(R.string.notification_action_timer_pause), pauseTimerIntent() ) } else { val startPhaseActionTitle = resources.getString(when (phaseCompleted) { Cycle.Phase.WORK -> R.string.notification_action_timer_start_break_phase Cycle.Phase.BREAK -> R.string.notification_action_timer_start_work_phase }) builder.addAction( R.drawable.ic_alarm_on_white_24dp, startPhaseActionTitle, startNextTimerIntent() ) } return builder } /** * Build an intent that pauses the cycle timer. */ private fun pauseTimerIntent(): PendingIntent = PendingIntent.getBroadcast( context, 0, actionBroadcastIntent(action = ACTION_PAUSE_TIMER, notificationID = ID_PHASE_COMPLETE), PendingIntent.FLAG_CANCEL_CURRENT ) private fun startNextTimerIntent(): PendingIntent = PendingIntent.getBroadcast( context, 0, actionBroadcastIntent(action = ACTION_RESUME_TIMER, notificationID = ID_PHASE_COMPLETE), PendingIntent.FLAG_CANCEL_CURRENT ) private fun actionBroadcastIntent(action: String, notificationID: Int, cancelNotification: Boolean = true): Intent = Intent(action) .putExtra(EXTRA_NOTIFICATION_ID, notificationID) .putExtra(EXTRA_FLAG_CANCEL_NOTIFICATION, cancelNotification) /** * Build and post a notification that a phase was completed. * * @param phase The phase that was completed. */ fun notifyPhaseComplete(phase: Cycle.Phase) { Timber.v("Building cycle complete notification.") val notification = buildPhaseCompleteNotification(phase) Timber.i("Posting cycle complete notification.") val notifyManager = NotificationManagerCompat.from(context) notifyManager.notify(ID_PHASE_COMPLETE, notification) } //region Foreground progress notification private fun foregroundNotificationPref(): Observable<Boolean> = preferences .getBoolean(context.getString(R.string.pref_key_notifications_persistent_enabled)) .asObservable() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .onErrorResumeNext { Timber.e(it, "Encountered an error while watching foreground notification preference.") foregroundNotificationPref() } /** * Create a notification displaying a cycle's current progress. * * See also: [notifyUpdatedProgress] * * @param cycle The cycle whose progress should be displayed in the notification. * @return A new notification displaying the progress of [cycle]. */ fun buildProgressNotification(cycle: Cycle): Notification = NotificationCompat.Builder(context) .setSmallIcon(R.drawable.ic_notification_small) .setContentTitle(context.getString(R.string.notification_title_foreground_progress)) .setContentText(progressNotificationMessage(cycle)) .setColor(ContextCompat.getColor(context, R.color.colorAccent)) .setContentIntent(timerContentIntent()) .setCategory(NotificationCompat.CATEGORY_PROGRESS) .setPriority(NotificationCompat.PRIORITY_LOW) .setOngoing(cycle.running) .setProgress(cycle.duration, cycle.elapsedTime, false) .build() /** * Generate the message to be used in the foreground progress notification. * * See: [buildProgressNotification]. * * @param cycle The cycle whose progress will be displayed in the notification. * @return The content title for the [Cycle] progress notification. */ private fun progressNotificationMessage(cycle: Cycle): String = if (cycle.running) context.getString( R.string.notification_message_foreground_progress, cycle.phaseName ) else context.getString( R.string.notification_message_foreground_progress_paused, cycle.phaseName ) /** * Build and post a notification of the cycle's current progress. * * See also: [buildProgressNotification] * * @param cycle The cycle whose progress should be displayed in the notification. */ fun notifyUpdatedProgress(cycle: Cycle) { Timber.v("Posting foreground progress notification for cycle: $cycle") val notification = buildProgressNotification(cycle) val notifyManager = NotificationManagerCompat.from(context) notifyManager.notify(ID_FOREGROUND_PROGRESS, notification) } //endregion }
gpl-3.0
a7fd434e6948fda66f2df7b2932e248f
42.402439
115
0.6621
5.019394
false
false
false
false
dya-tel/TSU-Schedule
src/main/kotlin/ru/dyatel/tsuschedule/parsing/GroupScheduleParser.kt
1
983
package ru.dyatel.tsuschedule.parsing import org.jsoup.nodes.Element import ru.dyatel.tsuschedule.model.GroupLesson import ru.dyatel.tsuschedule.model.Lesson object GroupScheduleParser : ScheduleParser<GroupLesson>() { private val SUBGROUP_PATTERN = Regex("(\\d) ?п/?гр?,?") override fun parseSingle(e: Element, base: Lesson): GroupLesson { val teacher = e.getElementsByClass("teac").requireSingleOrNull() ?.text()?.trim()?.takeUnless { it.isEmpty() } val subgroup: Int? val discipline: String val match = SUBGROUP_PATTERN.find(base.discipline) if (match != null) { subgroup = match.groupValues[1].toInt() discipline = base.discipline.removeRange(match.range).clean() } else { subgroup = null discipline = base.discipline } return with(base) { GroupLesson(parity, weekday, time, discipline, auditory, teacher, type, subgroup) } } }
mit
935886ebfa9cec6b4d384afd1c546ff4
31.666667
111
0.646939
4.279476
false
false
false
false
dya-tel/TSU-Schedule
src/main/kotlin/ru/dyatel/tsuschedule/utilities/PreferenceHelper.kt
1
4336
package ru.dyatel.tsuschedule.utilities import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import hirondelle.date4j.DateTime import ru.dyatel.tsuschedule.R import ru.dyatel.tsuschedule.events.Event import ru.dyatel.tsuschedule.events.EventBus import java.util.TimeZone private const val DATA_PREFERENCES = "data_preferences" private const val DATA_GROUP = "group" private const val DATA_GROUPS = "groups" private const val DATA_LAST_UPDATE_CHECK = "last_auto_update" private const val DATA_LAST_RELEASE_URL = "last_release" private const val DATA_LAST_USED_VERSION = "last_used_version" private const val DATA_PENDING_CHANGELOG_DISPLAY = "pending_changelog_display" class SchedulePreferences(private val context: Context) { private val preferences: SharedPreferences get() = PreferenceManager.getDefaultSharedPreferences(context) private val dataPreferences: SharedPreferences get() = context.getSharedPreferences(DATA_PREFERENCES, Context.MODE_PRIVATE) val connectionTimeout: Int get() { val preference = context.getString(R.string.preference_timeout) val fallback = context.getString(R.string.preference_timeout_default) return preferences.getString(preference, fallback).toInt() * 1000 } val historySize: Int get() { val preference = context.getString(R.string.preference_history_size) val fallback = context.getString(R.string.preference_history_size_default) return preferences.getString(preference, fallback).toInt() } val autoupdate: Boolean get() { val preference = context.getString(R.string.preference_update_auto) val fallback = context.getString(R.string.preference_update_auto_default)!!.toBoolean() return preferences.getBoolean(preference, fallback) } val allowPrerelease: Boolean get() { val preference = context.getString(R.string.preference_update_allow_prerelease) val fallback = context.getString(R.string.preference_update_allow_prerelease_default)!!.toBoolean() return preferences.getBoolean(preference, fallback) } var group: String? get() = dataPreferences.getString(DATA_GROUP, null)?.takeIf { it.isNotBlank() } set(value) = dataPreferences.editAndApply { putString(DATA_GROUP, value) } val groups: List<String> get() = dataPreferences.getStringSet(DATA_GROUPS, emptySet()).sorted() fun addGroup(group: String) { dataPreferences.editAndApply { putStringSet(DATA_GROUPS, HashSet(groups).apply { add(group) }) } } fun removeGroup(group: String) { dataPreferences.editAndApply { putStringSet(DATA_GROUPS, HashSet(groups).apply { remove(group) }) } } var pendingChangelogDisplay: Boolean get() = dataPreferences.getBoolean(DATA_PENDING_CHANGELOG_DISPLAY, false) set(value) = dataPreferences.editAndApply { putBoolean(DATA_PENDING_CHANGELOG_DISPLAY, value) } var lastUpdateCheck: DateTime? get() { return dataPreferences.getLong(DATA_LAST_UPDATE_CHECK, -1) .takeUnless { it == -1L } ?.let { DateTime.forInstant(it, TimeZone.getDefault()) } } set(value) { val timestamp = value?.getMilliseconds(TimeZone.getDefault()) ?: -1 dataPreferences.editAndApply { putLong(DATA_LAST_UPDATE_CHECK, timestamp) } } var lastReleaseUrl: String? get() = dataPreferences.getString(DATA_LAST_RELEASE_URL, null) set(value) { dataPreferences.editAndApply { putString(DATA_LAST_RELEASE_URL, value) } EventBus.broadcast(Event.PREFERENCES_LATEST_VERSION_CHANGED, value) } var lastUsedVersion: Int? get() = dataPreferences.getInt(DATA_LAST_USED_VERSION, -1).takeIf { it > 0 } set(value) = dataPreferences.editAndApply { putInt(DATA_LAST_USED_VERSION, value ?: -1) } } val Context.schedulePreferences: SchedulePreferences get() = SchedulePreferences(this) fun SharedPreferences.editAndApply(editor: SharedPreferences.Editor.() -> Unit) { val edit = edit() edit.editor() edit.apply() }
mit
ca2035159812d35da103edd56b365233
38.072072
111
0.685655
4.388664
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/editor/resources/PrismScriptProvider.kt
1
1780
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.editor.resources import com.vladsch.flexmark.html.HtmlRenderer import com.vladsch.md.nav.MdBundle import com.vladsch.md.nav.MdPlugin import com.vladsch.md.nav.editor.javafx.JavaFxHtmlPanelProvider import com.vladsch.md.nav.editor.util.HtmlCssResource import com.vladsch.md.nav.editor.util.HtmlScriptResource import com.vladsch.md.nav.editor.util.HtmlScriptResourceProvider import com.vladsch.md.nav.parser.flexmark.FlexmarkAttributeProvider import com.vladsch.md.nav.settings.MdPreviewSettings object PrismScriptProvider : HtmlScriptResourceProvider() { val NAME = MdBundle.message("editor.prismjs.html.script.provider.name") val ID = "com.vladsch.md.nav.editor.prismjs.html.script" override val HAS_PARENT = false override val INFO = HtmlScriptResourceProvider.Info(ID, NAME) override val COMPATIBILITY = JavaFxHtmlPanelProvider.COMPATIBILITY override val scriptResource: HtmlScriptResource = HtmlScriptResource(INFO, MdPlugin.PREVIEW_FX_PRISM_JS, "") init { scriptResource.set(HtmlRenderer.FENCED_CODE_LANGUAGE_CLASS_PREFIX, "language-") scriptResource.set(FlexmarkAttributeProvider.FENCED_CODE_PRE_CLASS, "line-numbers") scriptResource.set(FlexmarkAttributeProvider.INDENTED_CODE_PRE_CLASS, "language-none line-numbers") } override val cssResource: HtmlCssResource = PrismHtmlCssProvider.cssResource override fun isSupportedSetting(settingName: String): Boolean { return when (settingName) { MdPreviewSettings.PERFORMANCE_WARNING -> true else -> false } } }
apache-2.0
2dd77b7494bf517c90b4966e8cabb8bd
47.108108
177
0.775281
3.920705
false
false
false
false
paronos/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/track/myanimelist/MyanimelistApi.kt
2
7737
package eu.kanade.tachiyomi.data.track.myanimelist import android.net.Uri import android.util.Xml import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.data.track.model.TrackSearch import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.network.asObservable import eu.kanade.tachiyomi.network.asObservableSuccess import eu.kanade.tachiyomi.util.selectInt import eu.kanade.tachiyomi.util.selectText import okhttp3.* import org.jsoup.Jsoup import org.jsoup.parser.Parser import org.xmlpull.v1.XmlSerializer import rx.Observable import java.io.StringWriter class MyanimelistApi(private val client: OkHttpClient, username: String, password: String) { private var headers = createHeaders(username, password) fun addLibManga(track: Track): Observable<Track> { return Observable.defer { client.newCall(POST(getAddUrl(track), headers, getMangaPostPayload(track))) .asObservableSuccess() .map { track } } } fun updateLibManga(track: Track): Observable<Track> { return Observable.defer { client.newCall(POST(getUpdateUrl(track), headers, getMangaPostPayload(track))) .asObservableSuccess() .map { track } } } fun search(query: String, username: String): Observable<List<TrackSearch>> { return if (query.startsWith(PREFIX_MY)) { val realQuery = query.substring(PREFIX_MY.length).toLowerCase().trim() getList(username) .flatMap { Observable.from(it) } .filter { realQuery in it.title.toLowerCase() } .toList() } else { client.newCall(GET(getSearchUrl(query), headers)) .asObservable() .map { Jsoup.parse(Parser.unescapeEntities(it.body()!!.string(), false), "", Parser.xmlParser()) } .flatMap { Observable.from(it.select("entry")) } .filter { it.select("type").text() != "Novel" } .map { TrackSearch.create(TrackManager.MYANIMELIST).apply { title = it.selectText("title")!! remote_id = it.selectInt("id") total_chapters = it.selectInt("chapters") summary = it.selectText("synopsis")!! cover_url = it.selectText("image")!! tracking_url = MyanimelistApi.mangaUrl(remote_id) publishing_status = it.selectText("status")!! publishing_type = it.selectText("type")!! start_date = it.selectText("start_date")!! } } .toList() } } fun getList(username: String): Observable<List<TrackSearch>> { return client .newCall(GET(getListUrl(username), headers)) .asObservable() .map { Jsoup.parse(Parser.unescapeEntities(it.body()!!.string(), false), "", Parser.xmlParser()) } .flatMap { Observable.from(it.select("manga")) } .map { TrackSearch.create(TrackManager.MYANIMELIST).apply { title = it.selectText("series_title")!! remote_id = it.selectInt("series_mangadb_id") last_chapter_read = it.selectInt("my_read_chapters") status = it.selectInt("my_status") score = it.selectInt("my_score").toFloat() total_chapters = it.selectInt("series_chapters") cover_url = it.selectText("series_image")!! tracking_url = MyanimelistApi.mangaUrl(remote_id) } } .toList() } fun findLibManga(track: Track, username: String): Observable<Track?> { return getList(username) .map { list -> list.find { it.remote_id == track.remote_id } } } fun getLibManga(track: Track, username: String): Observable<Track> { return findLibManga(track, username) .map { it ?: throw Exception("Could not find manga") } } fun login(username: String, password: String): Observable<Response> { headers = createHeaders(username, password) return client.newCall(GET(getLoginUrl(), headers)) .asObservable() .doOnNext { response -> response.close() if (response.code() != 200) throw Exception("Login error") } } private fun getMangaPostPayload(track: Track): RequestBody { val data = xml { element(ENTRY_TAG) { if (track.last_chapter_read != 0) { text(CHAPTER_TAG, track.last_chapter_read.toString()) } text(STATUS_TAG, track.status.toString()) text(SCORE_TAG, track.score.toString()) } } return FormBody.Builder() .add("data", data) .build() } private inline fun xml(block: XmlSerializer.() -> Unit): String { val x = Xml.newSerializer() val writer = StringWriter() with(x) { setOutput(writer) startDocument("UTF-8", false) block() endDocument() } return writer.toString() } private inline fun XmlSerializer.element(tag: String, block: XmlSerializer.() -> Unit) { startTag("", tag) block() endTag("", tag) } private fun XmlSerializer.text(tag: String, body: String) { startTag("", tag) text(body) endTag("", tag) } fun getLoginUrl() = Uri.parse(baseUrl).buildUpon() .appendEncodedPath("api/account/verify_credentials.xml") .toString() fun getSearchUrl(query: String) = Uri.parse(baseUrl).buildUpon() .appendEncodedPath("api/manga/search.xml") .appendQueryParameter("q", query) .toString() fun getListUrl(username: String) = Uri.parse(baseUrl).buildUpon() .appendPath("malappinfo.php") .appendQueryParameter("u", username) .appendQueryParameter("status", "all") .appendQueryParameter("type", "manga") .toString() fun getUpdateUrl(track: Track) = Uri.parse(baseUrl).buildUpon() .appendEncodedPath("api/mangalist/update") .appendPath("${track.remote_id}.xml") .toString() fun getAddUrl(track: Track) = Uri.parse(baseUrl).buildUpon() .appendEncodedPath("api/mangalist/add") .appendPath("${track.remote_id}.xml") .toString() fun createHeaders(username: String, password: String): Headers { return Headers.Builder() .add("Authorization", Credentials.basic(username, password)) .add("User-Agent", "api-indiv-9F93C52A963974CF674325391990191C") .build() } companion object { const val baseUrl = "https://myanimelist.net" const val baseMangaUrl = baseUrl + "/manga/" fun mangaUrl(remoteId: Int): String { return baseMangaUrl + remoteId } private val ENTRY_TAG = "entry" private val CHAPTER_TAG = "chapter" private val SCORE_TAG = "score" private val STATUS_TAG = "status" const val PREFIX_MY = "my:" } }
apache-2.0
181f210ed67e8a3a890db44ecb089481
37.306931
118
0.55771
4.663653
false
false
false
false