repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
minecraft-dev/MinecraftDev
src/main/kotlin/platform/mixin/inspection/MixinCancellableInspection.kt
1
5319
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.INJECT import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Classes.CALLBACK_INFO import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Classes.CALLBACK_INFO_RETURNABLE import com.demonwav.mcdev.util.fullQualifiedName import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.JavaElementVisitor import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiClassType import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementFactory import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiExpressionList import com.intellij.psi.PsiFile import com.intellij.psi.PsiLiteral import com.intellij.psi.PsiMethod import com.intellij.psi.PsiReferenceExpression import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.psi.util.PsiUtil class MixinCancellableInspection : MixinInspection() { override fun getStaticDescription(): String = "Reports missing or unused cancellable @Inject usages" override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder) private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() { override fun visitMethod(method: PsiMethod) { val injectAnnotation = method.getAnnotation(INJECT) ?: return val cancellableAttribute = injectAnnotation.findAttributeValue("cancellable") as? PsiLiteral ?: return val isCancellable = cancellableAttribute.value == true val ciParam = method.parameterList.parameters.firstOrNull { val className = (it.type as? PsiClassType)?.fullQualifiedName ?: return@firstOrNull false className == CALLBACK_INFO || className == CALLBACK_INFO_RETURNABLE } ?: return val ciType = (ciParam.type as? PsiClassType)?.resolve() ?: return val searchingFor = ciType.findMethodsByName("setReturnValue", false).firstOrNull() ?: ciType.findMethodsByName("cancel", false).firstOrNull() ?: return var mayUseCancel = false var definitelyUsesCancel = false for (ref in ReferencesSearch.search(ciParam)) { val parent = PsiUtil.skipParenthesizedExprUp(ref.element.parent) if (parent is PsiExpressionList) { // method argument, we can't tell whether it uses cancel mayUseCancel = true } val methodCall = parent as? PsiReferenceExpression ?: continue if (methodCall.references.any { it.isReferenceTo(searchingFor) }) { definitelyUsesCancel = true break } } if (definitelyUsesCancel && !isCancellable) { holder.registerProblem( method.nameIdentifier ?: method, "@Inject must be marked as cancellable in order to be cancelled", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, MakeInjectCancellableFix(injectAnnotation) ) } else if (!definitelyUsesCancel && !mayUseCancel && isCancellable) { holder.registerProblem( cancellableAttribute.parent, "@Inject is cancellable but is never cancelled", ProblemHighlightType.GENERIC_ERROR_OR_WARNING, RemoveInjectCancellableFix(injectAnnotation) ) } } } private class MakeInjectCancellableFix(element: PsiAnnotation) : LocalQuickFixAndIntentionActionOnPsiElement(element) { override fun getFamilyName(): String = "Mark as cancellable" override fun getText(): String = familyName override fun invoke( project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement ) { val annotation = startElement as PsiAnnotation val value = PsiElementFactory.getInstance(project).createExpressionFromText("true", annotation) annotation.setDeclaredAttributeValue("cancellable", value) } } private class RemoveInjectCancellableFix(element: PsiAnnotation) : LocalQuickFixAndIntentionActionOnPsiElement(element) { override fun getFamilyName(): String = "Remove unused cancellable attribute" override fun getText(): String = familyName override fun invoke( project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement ) { val annotation = startElement as PsiAnnotation annotation.setDeclaredAttributeValue("cancellable", null) } } }
mit
946228e5cc678d2eb4394b02e24fb6f3
39.603053
114
0.668547
5.581322
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/util/bytecode-utils.kt
1
5239
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.util import com.intellij.openapi.project.Project import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiArrayType import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassType import com.intellij.psi.PsiField import com.intellij.psi.PsiMethod import com.intellij.psi.PsiPrimitiveType import com.intellij.psi.PsiType import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.TypeConversionUtil private const val INTERNAL_CONSTRUCTOR_NAME = "<init>" // Type val PsiPrimitiveType.internalName: Char get() = when (this) { PsiType.BYTE -> 'B' PsiType.CHAR -> 'C' PsiType.DOUBLE -> 'D' PsiType.FLOAT -> 'F' PsiType.INT -> 'I' PsiType.LONG -> 'J' PsiType.SHORT -> 'S' PsiType.BOOLEAN -> 'Z' PsiType.VOID -> 'V' else -> throw IllegalArgumentException("Unsupported primitive type: $this") } fun getPrimitiveType(internalName: Char): PsiPrimitiveType? { return when (internalName) { 'B' -> PsiType.BYTE 'C' -> PsiType.CHAR 'D' -> PsiType.DOUBLE 'F' -> PsiType.FLOAT 'I' -> PsiType.INT 'J' -> PsiType.LONG 'S' -> PsiType.SHORT 'Z' -> PsiType.BOOLEAN 'V' -> PsiType.VOID else -> null } } val PsiType.descriptor get() = appendDescriptor(StringBuilder()).toString() fun getPrimitiveWrapperClass(internalName: Char, project: Project): PsiClass? { val type = getPrimitiveType(internalName) ?: return null val boxedTypeName = type.boxedTypeName ?: return null return JavaPsiFacade.getInstance(project).findClass(boxedTypeName, GlobalSearchScope.allScope(project)) } private fun PsiClassType.erasure() = TypeConversionUtil.erasure(this) as PsiClassType @Throws(ClassNameResolutionFailedException::class) private fun PsiClassType.appendInternalName(builder: StringBuilder): StringBuilder = erasure().resolve()?.appendInternalName(builder) ?: builder @Throws(ClassNameResolutionFailedException::class) private fun PsiType.appendDescriptor(builder: StringBuilder): StringBuilder { return when (this) { is PsiPrimitiveType -> builder.append(internalName) is PsiArrayType -> componentType.appendDescriptor(builder.append('[')) is PsiClassType -> appendInternalName(builder.append('L')).append(';') else -> throw IllegalArgumentException("Unsupported PsiType: $this") } } fun parseClassDescriptor(descriptor: String): String { val internalName = descriptor.substring(1, descriptor.length - 1) return internalName.replace('/', '.') } // Class val PsiClass.internalName: String? get() { realName?.let { return it } return try { outerQualifiedName?.replace('.', '/') ?: buildInternalName(StringBuilder()).toString() } catch (e: ClassNameResolutionFailedException) { null } } @Throws(ClassNameResolutionFailedException::class) private fun PsiClass.appendInternalName(builder: StringBuilder): StringBuilder { return outerQualifiedName?.let { builder.append(it.replace('.', '/')) } ?: buildInternalName(builder) } @Throws(ClassNameResolutionFailedException::class) private fun PsiClass.buildInternalName(builder: StringBuilder): StringBuilder { buildInnerName(builder, { it.outerQualifiedName?.replace('.', '/') }) return builder } val PsiClass.descriptor: String? get() { return try { appendInternalName(StringBuilder().append('L')).append(';').toString() } catch (e: ClassNameResolutionFailedException) { null } } fun PsiClass.findMethodsByInternalName(internalName: String, checkBases: Boolean = false): Array<PsiMethod> { return if (internalName == INTERNAL_CONSTRUCTOR_NAME) { constructors } else { findMethodsByName(internalName, checkBases) } } // Method val PsiMethod.internalName: String get() { val realName = realName return when { isConstructor -> INTERNAL_CONSTRUCTOR_NAME realName != null -> realName else -> name } } val PsiMethod.descriptor: String? get() { return try { appendDescriptor(StringBuilder()).toString() } catch (e: ClassNameResolutionFailedException) { null } } @Throws(ClassNameResolutionFailedException::class) private fun PsiMethod.appendDescriptor(builder: StringBuilder): StringBuilder { builder.append('(') for (parameter in parameterList.parameters) { parameter.type.appendDescriptor(builder) } builder.append(')') return (returnType ?: PsiType.VOID).appendDescriptor(builder) } // Field val PsiField.descriptor: String? get() { return try { appendDescriptor(StringBuilder()).toString() } catch (e: ClassNameResolutionFailedException) { null } } @Throws(ClassNameResolutionFailedException::class) private fun PsiField.appendDescriptor(builder: StringBuilder): StringBuilder = type.appendDescriptor(builder)
mit
094ff412515a74f9803a62aa5967f4c3
29.817647
109
0.680282
4.60774
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/anime/resolver/DailymotionStreamResolver.kt
2
3106
package me.proxer.app.anime.resolver import com.squareup.moshi.JsonClass import com.squareup.moshi.JsonDataException import com.squareup.moshi.JsonEncodingException import io.reactivex.Single import me.proxer.app.MainApplication.Companion.GENERIC_USER_AGENT import me.proxer.app.exception.StreamResolutionException import me.proxer.app.util.extension.buildSingle import me.proxer.app.util.extension.toBodySingle import me.proxer.app.util.extension.toPrefixedUrlOrNull import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.Request import java.util.regex.Pattern.quote /** * @author Ruben Gees */ object DailymotionStreamResolver : StreamResolver() { private val regex = Regex("\"qualities\":(${quote("{")}.+${quote("}")}${quote("]")}${quote("}")}),") override val name = "Dailymotion" @Suppress("SwallowedException") override fun resolve(id: String): Single<StreamResolutionResult> { return api.anime.link(id) .buildSingle() .flatMap { url -> client.newCall( Request.Builder() .get() .url(url.toPrefixedUrlOrNull() ?: throw StreamResolutionException()) .header("User-Agent", GENERIC_USER_AGENT) .header("Connection", "close") .build() ) .toBodySingle() } .map { html -> val qualitiesJson = regex.find(html)?.value ?: throw StreamResolutionException() val qualityMap = try { moshi.adapter(DailymotionQualityMap::class.java) .fromJson("{${qualitiesJson.trimEnd(',')}}") ?: throw StreamResolutionException() } catch (error: JsonDataException) { throw StreamResolutionException() } catch (error: JsonEncodingException) { throw StreamResolutionException() } val link = qualityMap.qualities .flatMap { (quality, links) -> links.mapNotNull { (type, url) -> url.toHttpUrlOrNull()?.let { DailymotionLinkWithQuality(quality, type, it) } } } .filter { it.type == "application/x-mpegURL" || it.type == "video/mp4" } .sortedWith(compareBy<DailymotionLinkWithQuality> { it.type }.thenByDescending { it.quality }) .firstOrNull() ?: throw StreamResolutionException() StreamResolutionResult.Video(link.url, link.type) } } @JsonClass(generateAdapter = true) internal data class DailymotionQualityMap(val qualities: Map<String, Array<DailymotionLink>>) @JsonClass(generateAdapter = true) internal data class DailymotionLink(val type: String, val url: String) private data class DailymotionLinkWithQuality(val quality: String, val type: String, val url: HttpUrl) }
gpl-3.0
5e6ecfa2f6fa62d6cf87b3f4c95b78be
39.868421
114
0.59369
5.133884
false
false
false
false
EventFahrplan/EventFahrplan
app/src/main/java/nerd/tuxmobil/fahrplan/congress/MyApp.kt
1
1870
package nerd.tuxmobil.fahrplan.congress import androidx.annotation.CallSuper import androidx.multidex.MultiDexApplication import info.metadude.android.eventfahrplan.commons.logging.Logging import nerd.tuxmobil.fahrplan.congress.repositories.AppRepository import nerd.tuxmobil.fahrplan.congress.utils.ConferenceTimeFrame import org.ligi.tracedroid.TraceDroid import java.util.Calendar import java.util.GregorianCalendar import java.util.TimeZone class MyApp : MultiDexApplication() { enum class TASKS { NONE, FETCH, PARSE } companion object { private val FIRST_DAY_START = getMilliseconds( "Europe/Paris", BuildConfig.SCHEDULE_FIRST_DAY_START_YEAR, BuildConfig.SCHEDULE_FIRST_DAY_START_MONTH, BuildConfig.SCHEDULE_FIRST_DAY_START_DAY ) private val LAST_DAY_END = getMilliseconds( "Europe/Paris", BuildConfig.SCHEDULE_LAST_DAY_END_YEAR, BuildConfig.SCHEDULE_LAST_DAY_END_MONTH, BuildConfig.SCHEDULE_LAST_DAY_END_DAY ) private fun getMilliseconds(timeZoneId: String, year: Int, month: Int, day: Int): Long { val zeroBasedMonth = month - 1 val zone = TimeZone.getTimeZone(timeZoneId) return GregorianCalendar(zone).apply { set(year, zeroBasedMonth, day, 0, 0, 0) set(Calendar.MILLISECOND, 0) }.timeInMillis } val conferenceTimeFrame = ConferenceTimeFrame(FIRST_DAY_START, LAST_DAY_END) @JvmField var taskRunning = TASKS.NONE } @CallSuper override fun onCreate() { super.onCreate() TraceDroid.init(this) taskRunning = TASKS.NONE AppRepository.initialize( context = applicationContext, logging = Logging.get() ) } }
apache-2.0
6ffb6f949dbe05ab47400d1d85191f1f
29.16129
96
0.65508
4.495192
false
true
false
false
inorichi/tachiyomi-extensions
src/id/nyanfm/src/eu/kanade/tachiyomi/extension/id/nyanfm/NyanFM.kt
1
5135
package eu.kanade.tachiyomi.extension.id.nyanfm import eu.kanade.tachiyomi.network.GET 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.OkHttpClient import okhttp3.Request import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.text.SimpleDateFormat import java.util.Locale class NyanFM : ParsedHttpSource() { override val name = "Nyan FM" override val baseUrl = "https://nyanfm.com" override val lang = "id" override val supportsLatest = false override val client: OkHttpClient = network.cloudflareClient // popular override fun popularMangaRequest(page: Int): Request { return GET("$baseUrl/scanlation/", headers) } override fun popularMangaSelector() = ".elementor-column .elementor-widget-wrap .elementor-widget-container .elementor-cta:has(.elementor-cta__bg)" override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.thumbnail_url = element.select(".elementor-cta__bg-wrapper .elementor-cta__bg").attr("style").substringAfter("(").substringBefore(")") manga.url = element.select(".elementor-cta__content a.elementor-button").attr("href").substringAfter(".com") manga.title = element.select(".elementor-cta__content h2").text().trim() return manga } override fun popularMangaNextPageSelector() = "#nav-below .nav-links .next.page-numbers" // latest override fun latestUpdatesRequest(page: Int): Request = throw UnsupportedOperationException() override fun latestUpdatesSelector(): String = throw UnsupportedOperationException() override fun latestUpdatesFromElement(element: Element): SManga = throw UnsupportedOperationException() override fun latestUpdatesNextPageSelector(): String? = throw UnsupportedOperationException() // search override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { return GET("https://nyanfm.com/page/$page/?s=$query") } override fun searchMangaSelector() = "#main article .inside-article:has(.entry-summary:has(a))" override fun searchMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.thumbnail_url = element.select(".post-image img").attr("src") element.select(".entry-summary:has(p) a").let { manga.setUrlWithoutDomain(it.attr("href")) manga.title = it.attr("title") } return manga } override fun searchMangaNextPageSelector() = ".nav-links .next" // manga details override fun mangaDetailsParse(document: Document): SManga { return SManga.create().apply { document.select(".entry-content div.elementor-section-wrap").firstOrNull()?.let { infoElement -> thumbnail_url = infoElement.select("div.elementor-widget-wrap div.elementor-element.elementor-hidden-tablet.elementor-widget img").attr("src") title = infoElement.select("h1").text().trim() artist = infoElement.select("div.elementor-element:has(h3:contains(author)) + div.elementor-element p").firstOrNull()?.ownText() status = parseStatus(infoElement.select("div.elementor-element:has(h3:contains(status)) + div.elementor-element p").text()) genre = infoElement.select("div.elementor-element:has(h3:contains(genre)) + div.elementor-element p").joinToString(", ") { it.text() } description = infoElement.select("div.elementor-element:has(h3:contains(sinopsis)) + div.elementor-element p").joinToString("\n") { it.text() } } } } private fun parseStatus(element: String): Int = when { element.toLowerCase().contains("ongoing") -> SManga.ONGOING element.toLowerCase().contains("completed") -> SManga.COMPLETED else -> SManga.UNKNOWN } // chapters override fun chapterListSelector() = "table tbody tr" override fun chapterFromElement(element: Element) = SChapter.create().apply { element.select("td:last-child a").let { name = it.text() url = it.attr("href").substringAfter(baseUrl) } date_upload = parseChapterDate(element.select("td:first-child").text()) } private fun parseChapterDate(date: String): Long { return SimpleDateFormat("dd-MMM-yy", Locale.ENGLISH).parse(date)?.time ?: 0L } // pages override fun pageListParse(document: Document): List<Page> { val pages = mutableListOf<Page>() var i = 0 document.select("div.elementor-widget-container > div.elementor-image a > img.attachment-large.size-large").forEach { element -> val url = element.attr("src") i++ if (url.isNotEmpty()) { pages.add(Page(i, "", url)) } } return pages } override fun imageUrlParse(document: Document) = "" }
apache-2.0
225094cc1366bd1b8f203bd655ae0174
41.791667
159
0.676728
4.403945
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/xpath/XPathPostfixExprPsiImpl.kt
1
1659
/* * Copyright (C) 2016-2018, 2020-2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xpath.psi.impl.xpath import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.xdm.types.XdmItemType import uk.co.reecedunn.intellij.plugin.xdm.types.XdmNodeItem import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathPostfixExpr import uk.co.reecedunn.intellij.plugin.xpm.optree.expression.XpmExpression import uk.co.reecedunn.intellij.plugin.xpm.optree.path.XpmAxisType class XPathPostfixExprPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XPathPostfixExpr { // region XpmPathStep override val axisType: XpmAxisType = XpmAxisType.Self override val nodeName: XsQNameValue? = null override val nodeType: XdmItemType = XdmNodeItem override val predicateExpression: XpmExpression? = null // endregion // region XpmExpression override val expressionElement: PsiElement? = null // endregion }
apache-2.0
3444c2b111bf60a5b81d7266d75dc1f2
35.866667
93
0.77818
4.066176
false
false
false
false
kazhida/kotos2d
src/jp/kazhida/kotos2d/Kotos2dActivity.kt
1
2288
package jp.kazhida.kotos2d import android.app.Activity import android.content.Context import android.os.Build import android.util.Log import android.os.Message import android.os.Bundle import android.widget.FrameLayout import android.view.ViewGroup /** * Created by kazhida on 2013/07/27. */ public abstract class Kotos2dActivity : Activity(), Kotos2dHelper.HelperListener { class object { val TAG = javaClass<Kotos2dActivity>().getSimpleName() var context: Context? = null val isAndroidEmulator: Boolean get() { val model = Build.MODEL val product = Build.PRODUCT Log.d(TAG, "model=" + model + ", product=" + product) return product.equals("sdk") || product.contains("_sdk") || product.contains("sdk_") } } var surfaceView: Kotos2dGLSurfaceView? = null val handler = Kotos2dHandler(this) open fun onCreateView(): Kotos2dGLSurfaceView { return Kotos2dGLSurfaceView(this) } override fun onCreate(savedInstanceState: Bundle?) { super<Activity>.onCreate(savedInstanceState) context = this val MP = ViewGroup.LayoutParams.MATCH_PARENT val WC = ViewGroup.LayoutParams.WRAP_CONTENT val frameLayout = FrameLayout(this) //todo: EditText関連 surfaceView = onCreateView(); surfaceView?.renderer = Kotos2dRenderer() if (isAndroidEmulator) surfaceView?.setEGLConfigChooser(8, 8, 8, 8, 16, 0) setContentView(frameLayout, ViewGroup.LayoutParams(MP, MP)) Kotos2dHelper.init(this, this) } override fun onResume() { super<Activity>.onResume() Kotos2dHelper.sharedInstance().onResume() surfaceView?.onResume() } override fun onPause() { super<Activity>.onPause() Kotos2dHelper.sharedInstance().onPause() surfaceView?.onPause() } override fun runOnGLThread(runnable: Runnable) { surfaceView?.queueEvent(runnable) } override fun showDialog(title: String, message: String) { val msg = Message() msg.what = Kotos2dHandler.HANDLE_SHOW_DIALOG msg.obj = Kotos2dHandler.DialogMessage(title, message) handler.sendMessage(msg) } }
mit
79bcbac01e25d1d887c72df42a26a72c
27.911392
100
0.651926
4.309434
false
false
false
false
InsertKoinIO/koin
core/koin-core/src/commonMain/kotlin/org/koin/core/instance/ScopedInstanceFactory.kt
1
2329
/* * Copyright 2017-2021 the original author or authors. * * 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.koin.core.instance import org.koin.core.definition.BeanDefinition import org.koin.core.scope.Scope import org.koin.core.scope.ScopeID import org.koin.mp.KoinPlatformTools import org.koin.mp.KoinPlatformTools.safeHashMap /** * Single instance holder * @author Arnaud Giuliani */ class ScopedInstanceFactory<T>(beanDefinition: BeanDefinition<T>) : InstanceFactory<T>(beanDefinition) { private var values = hashMapOf<ScopeID,T>() override fun isCreated(context: InstanceContext?): Boolean = (values[context?.scope?.id] != null) override fun drop(scope: Scope?) { scope?.let { beanDefinition.callbacks.onClose?.invoke(values[it.id]) values.remove(it.id) } } override fun create(context: InstanceContext): T { return if (values[context.scope.id] == null) { super.create(context) } else values[context.scope.id] ?: error("Scoped instance not found for ${context.scope.id} in $beanDefinition") } override fun get(context: InstanceContext): T { if (context.scope.scopeQualifier != beanDefinition.scopeQualifier){ error("Wrong Scope: trying to open instance for ${context.scope.id} in $beanDefinition") } KoinPlatformTools.synchronized(this) { if (!isCreated(context)) { values[context.scope.id] = create(context) } } return values[context.scope.id] ?: error("Scoped instance not found for ${context.scope.id} in $beanDefinition") } override fun dropAll(){ values.clear() } fun refreshInstance(scopeID: ScopeID, instance: Any) { values[scopeID] = instance as T } }
apache-2.0
d791baaaca985a3dceb34b25714f1595
33.776119
121
0.68055
4.151515
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt
1
16594
package info.nightscout.androidaps.plugins.general.actions import android.content.Context import android.content.Intent import android.os.Bundle import android.util.DisplayMetrics import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import androidx.core.content.ContextCompat import dagger.android.support.DaggerFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.activities.HistoryBrowseActivity import info.nightscout.androidaps.activities.TDDStatsActivity import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.ValueWrapper import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.databinding.ActionsFragmentBinding import info.nightscout.androidaps.dialogs.* import info.nightscout.androidaps.events.EventCustomActionsChanged import info.nightscout.androidaps.events.EventExtendedBolusChange import info.nightscout.androidaps.events.EventInitializationChanged import info.nightscout.androidaps.events.EventTempBasalChange import info.nightscout.androidaps.events.EventTherapyEventChange import info.nightscout.androidaps.extensions.toStringMedium import info.nightscout.androidaps.extensions.toStringShort import info.nightscout.androidaps.extensions.toVisibility import info.nightscout.androidaps.interfaces.* import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction import info.nightscout.androidaps.plugins.general.overview.StatusLightHandler import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.skins.SkinProvider import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.interfaces.BuildHelper import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import info.nightscout.androidaps.utils.ui.SingleClickButton import info.nightscout.androidaps.utils.ui.UIRunnable import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import java.util.* import javax.inject.Inject class ActionsFragment : DaggerFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBus @Inject lateinit var sp: SP @Inject lateinit var dateUtil: DateUtil @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var ctx: Context @Inject lateinit var rh: ResourceHelper @Inject lateinit var statusLightHandler: StatusLightHandler @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var buildHelper: BuildHelper @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var skinProvider: SkinProvider @Inject lateinit var config: Config @Inject lateinit var uel: UserEntryLogger @Inject lateinit var repository: AppRepository @Inject lateinit var loop: Loop private var disposable: CompositeDisposable = CompositeDisposable() private val pumpCustomActions = HashMap<String, CustomAction>() private val pumpCustomButtons = ArrayList<SingleClickButton>() private lateinit var dm: DisplayMetrics private var _binding: ActionsFragmentBinding? = null // This property is only valid between onCreateView and onDestroyView. private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { //check screen width dm = DisplayMetrics() if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) { @Suppress("DEPRECATION") activity?.display?.getRealMetrics(dm) } else { @Suppress("DEPRECATION") activity?.windowManager?.defaultDisplay?.getMetrics(dm) } _binding = ActionsFragmentBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) skinProvider.activeSkin().preProcessLandscapeActionsLayout(dm, binding) binding.profileSwitch.setOnClickListener { activity?.let { activity -> protectionCheck.queryProtection( activity, ProtectionCheck.Protection.BOLUS, UIRunnable { ProfileSwitchDialog().show(childFragmentManager, "ProfileSwitchDialog")}) } } binding.tempTarget.setOnClickListener { activity?.let { activity -> protectionCheck.queryProtection( activity, ProtectionCheck.Protection.BOLUS, UIRunnable { TempTargetDialog().show(childFragmentManager, "Actions") }) } } binding.extendedBolus.setOnClickListener { activity?.let { activity -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { OKDialog.showConfirmation( activity, rh.gs(R.string.extended_bolus), rh.gs(R.string.ebstopsloop), Runnable { ExtendedBolusDialog().show(childFragmentManager, "Actions") }, null ) }) } } binding.extendedBolusCancel.setOnClickListener { if (iobCobCalculator.getExtendedBolus(dateUtil.now()) != null) { uel.log(Action.CANCEL_EXTENDED_BOLUS, Sources.Actions) commandQueue.cancelExtended(object : Callback() { override fun run() { if (!result.success) { ErrorHelperActivity.runAlarm(ctx, result.comment, rh.gs(R.string.extendedbolusdeliveryerror), R.raw.boluserror) } } }) } } binding.setTempBasal.setOnClickListener { activity?.let { activity -> protectionCheck.queryProtection( activity, ProtectionCheck.Protection.BOLUS, UIRunnable { TempBasalDialog().show(childFragmentManager, "Actions") }) } } binding.cancelTempBasal.setOnClickListener { if (iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now()) != null) { uel.log(Action.CANCEL_TEMP_BASAL, Sources.Actions) commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { if (!result.success) { ErrorHelperActivity.runAlarm(ctx, result.comment, rh.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror) } } }) } } binding.fill.setOnClickListener { activity?.let { activity -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { FillDialog().show(childFragmentManager, "FillDialog") }) } } binding.historyBrowser.setOnClickListener { startActivity(Intent(context, HistoryBrowseActivity::class.java)) } binding.tddStats.setOnClickListener { startActivity(Intent(context, TDDStatsActivity::class.java)) } binding.bgCheck.setOnClickListener { CareDialog().setOptions(CareDialog.EventType.BGCHECK, R.string.careportal_bgcheck).show(childFragmentManager, "Actions") } binding.cgmSensorInsert.setOnClickListener { CareDialog().setOptions(CareDialog.EventType.SENSOR_INSERT, R.string.careportal_cgmsensorinsert).show(childFragmentManager, "Actions") } binding.pumpBatteryChange.setOnClickListener { CareDialog().setOptions(CareDialog.EventType.BATTERY_CHANGE, R.string.careportal_pumpbatterychange).show(childFragmentManager, "Actions") } binding.note.setOnClickListener { CareDialog().setOptions(CareDialog.EventType.NOTE, R.string.careportal_note).show(childFragmentManager, "Actions") } binding.exercise.setOnClickListener { CareDialog().setOptions(CareDialog.EventType.EXERCISE, R.string.careportal_exercise).show(childFragmentManager, "Actions") } binding.question.setOnClickListener { CareDialog().setOptions(CareDialog.EventType.QUESTION, R.string.careportal_question).show(childFragmentManager, "Actions") } binding.announcement.setOnClickListener { CareDialog().setOptions(CareDialog.EventType.ANNOUNCEMENT, R.string.careportal_announcement).show(childFragmentManager, "Actions") } sp.putBoolean(R.string.key_objectiveuseactions, true) } @Synchronized override fun onResume() { super.onResume() disposable += rxBus .toObservable(EventInitializationChanged::class.java) .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventExtendedBolusChange::class.java) .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventTempBasalChange::class.java) .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventCustomActionsChanged::class.java) .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventTherapyEventChange::class.java) .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) updateGui() } @Synchronized override fun onPause() { super.onPause() disposable.clear() } override fun onDestroyView() { super.onDestroyView() _binding = null } @Synchronized fun updateGui() { val profile = profileFunction.getProfile() val pump = activePlugin.activePump binding.profileSwitch.visibility = ( activePlugin.activeProfileSource.profile != null && pump.pumpDescription.isSetBasalProfileCapable && pump.isInitialized() && !pump.isSuspended() && !loop.isDisconnected).toVisibility() if (!pump.pumpDescription.isExtendedBolusCapable || !pump.isInitialized() || pump.isSuspended() || loop.isDisconnected || pump.isFakingTempsByExtendedBoluses || config.NSCLIENT) { binding.extendedBolus.visibility = View.GONE binding.extendedBolusCancel.visibility = View.GONE } else { val activeExtendedBolus = repository.getExtendedBolusActiveAt(dateUtil.now()).blockingGet() if (activeExtendedBolus is ValueWrapper.Existing) { binding.extendedBolus.visibility = View.GONE binding.extendedBolusCancel.visibility = View.VISIBLE @Suppress("SetTextI18n") binding.extendedBolusCancel.text = rh.gs(R.string.cancel) + " " + activeExtendedBolus.value.toStringMedium(dateUtil) } else { binding.extendedBolus.visibility = View.VISIBLE binding.extendedBolusCancel.visibility = View.GONE } } if (!pump.pumpDescription.isTempBasalCapable || !pump.isInitialized() || pump.isSuspended() || loop.isDisconnected || config.NSCLIENT) { binding.setTempBasal.visibility = View.GONE binding.cancelTempBasal.visibility = View.GONE } else { val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis()) if (activeTemp != null) { binding.setTempBasal.visibility = View.GONE binding.cancelTempBasal.visibility = View.VISIBLE @Suppress("SetTextI18n") binding.cancelTempBasal.text = rh.gs(R.string.cancel) + " " + activeTemp.toStringShort() } else { binding.setTempBasal.visibility = View.VISIBLE binding.cancelTempBasal.visibility = View.GONE } } val activeBgSource = activePlugin.activeBgSource binding.historyBrowser.visibility = (profile != null).toVisibility() binding.fill.visibility = (pump.pumpDescription.isRefillingCapable && pump.isInitialized() && !pump.isSuspended()).toVisibility() binding.pumpBatteryChange.visibility = (pump.pumpDescription.isBatteryReplaceable || pump.isBatteryChangeLoggingEnabled()).toVisibility() binding.tempTarget.visibility = (profile != null && !loop.isDisconnected).toVisibility() binding.tddStats.visibility = pump.pumpDescription.supportsTDDs.toVisibility() val isPatchPump = pump.pumpDescription.isPatchPump binding.status.apply { cannulaOrPatch.text = if (isPatchPump) rh.gs(R.string.patch_pump) else rh.gs(R.string.cannula) val imageResource = if (isPatchPump) R.drawable.ic_patch_pump_outline else R.drawable.ic_cp_age_cannula cannulaOrPatch.setCompoundDrawablesWithIntrinsicBounds(imageResource, 0, 0, 0) batteryLayout.visibility = (!isPatchPump || pump.pumpDescription.useHardwareLink).toVisibility() if (!config.NSCLIENT) { statusLightHandler.updateStatusLights(cannulaAge, insulinAge, reservoirLevel, sensorAge, sensorLevel, pbAge, batteryLevel) sensorLevelLabel.text = if (activeBgSource.sensorBatteryLevel == -1) "" else rh.gs(R.string.careportal_level_label) } else { statusLightHandler.updateStatusLights(cannulaAge, insulinAge, null, sensorAge, null, pbAge, null) sensorLevelLabel.text = "" insulinLevelLabel.text = "" pbLevelLabel.text = "" } } checkPumpCustomActions() } private fun checkPumpCustomActions() { val activePump = activePlugin.activePump val customActions = activePump.getCustomActions() ?: return val currentContext = context ?: return removePumpCustomActions() for (customAction in customActions) { if (!customAction.isEnabled) continue val btn = SingleClickButton(currentContext, null, R.attr.customBtnStyle) btn.text = rh.gs(customAction.name) val layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f ) layoutParams.setMargins(20, 8, 20, 8) // 10,3,10,3 btn.layoutParams = layoutParams btn.setOnClickListener { v -> val b = v as SingleClickButton this.pumpCustomActions[b.text.toString()]?.let { activePlugin.activePump.executeCustomAction(it.customActionType) } } val top = activity?.let { ContextCompat.getDrawable(it, customAction.iconResourceId) } btn.setCompoundDrawablesWithIntrinsicBounds(null, top, null, null) binding.buttonsLayout.addView(btn) this.pumpCustomActions[rh.gs(customAction.name)] = customAction this.pumpCustomButtons.add(btn) } } private fun removePumpCustomActions() { for (customButton in pumpCustomButtons) binding.buttonsLayout.removeView(customButton) pumpCustomButtons.clear() } }
agpl-3.0
b5117179c2aa4d3e72c1504b880758ba
47.238372
187
0.680969
5.131107
false
false
false
false
Heiner1/AndroidAPS
wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt
1
5782
@file:Suppress("DEPRECATION") package info.nightscout.androidaps.watchfaces import android.annotation.SuppressLint import android.view.LayoutInflater import androidx.core.content.ContextCompat import androidx.viewbinding.ViewBinding import com.ustwo.clockwise.common.WatchMode import info.nightscout.androidaps.R import info.nightscout.androidaps.databinding.ActivityBigchartBinding import info.nightscout.androidaps.databinding.ActivityBigchartSmallBinding import info.nightscout.androidaps.watchfaces.utils.BaseWatchFace import info.nightscout.androidaps.watchfaces.utils.WatchfaceViewAdapter class BigChartWatchface : BaseWatchFace() { private lateinit var binding: WatchfaceViewAdapter override fun inflateLayout(inflater: LayoutInflater): ViewBinding { if (resources.displayMetrics.widthPixels < SCREEN_SIZE_SMALL || resources.displayMetrics.heightPixels < SCREEN_SIZE_SMALL) { val layoutBinding = ActivityBigchartSmallBinding.inflate(inflater) binding = WatchfaceViewAdapter.getBinding(layoutBinding) return layoutBinding } val layoutBinding = ActivityBigchartBinding.inflate(inflater) binding = WatchfaceViewAdapter.getBinding(layoutBinding) return layoutBinding } @SuppressLint("SetTextI18n") override fun setDataFields() { super.setDataFields() binding.status?.text = status.externalStatus + if (sp.getBoolean(R.string.key_show_cob, true)) (" " + this.status.cob) else "" } override fun setColorLowRes() { binding.time?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) binding.status?.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)) binding.mainLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) binding.sgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) binding.delta?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) binding.avgDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) binding.timestamp.setTextColor(ContextCompat.getColor(this, R.color.dark_Timestamp)) highColor = ContextCompat.getColor(this, R.color.dark_midColor) lowColor = ContextCompat.getColor(this, R.color.dark_midColor) midColor = ContextCompat.getColor(this, R.color.dark_midColor) gridColor = ContextCompat.getColor(this, R.color.dark_gridColor) basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_dark_lowres) basalCenterColor = ContextCompat.getColor(this, R.color.basal_light_lowres) pointSize = 2 setupCharts() } override fun setColorDark() { binding.time?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) binding.status?.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)) binding.mainLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) val color = when (singleBg.sgvLevel) { 1L -> R.color.dark_highColor 0L -> R.color.dark_midColor -1L -> R.color.dark_lowColor else -> R.color.dark_midColor } binding.sgv?.setTextColor(ContextCompat.getColor(this, color)) binding.delta?.setTextColor(ContextCompat.getColor(this, color)) binding.avgDelta?.setTextColor(ContextCompat.getColor(this, color)) val colorTime = if (ageLevel == 1) R.color.dark_Timestamp else R.color.dark_TimestampOld binding.timestamp.setTextColor(ContextCompat.getColor(this, colorTime)) highColor = ContextCompat.getColor(this, R.color.dark_highColor) lowColor = ContextCompat.getColor(this, R.color.dark_lowColor) midColor = ContextCompat.getColor(this, R.color.dark_midColor) gridColor = ContextCompat.getColor(this, R.color.dark_gridColor) basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_dark) basalCenterColor = ContextCompat.getColor(this, R.color.basal_light) pointSize = 2 setupCharts() } override fun setColorBright() { if (currentWatchMode == WatchMode.INTERACTIVE) { binding.time?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_time)) binding.status?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_status)) binding.mainLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)) val color = when (singleBg.sgvLevel) { 1L -> R.color.light_highColor 0L -> R.color.light_midColor -1L -> R.color.light_lowColor else -> R.color.light_midColor } binding.sgv?.setTextColor(ContextCompat.getColor(this, color)) binding.delta?.setTextColor(ContextCompat.getColor(this, color)) binding.avgDelta?.setTextColor(ContextCompat.getColor(this, color)) val colorTime = if (ageLevel == 1) R.color.light_mTimestamp1 else R.color.light_mTimestamp binding.timestamp.setTextColor(ContextCompat.getColor(this, colorTime)) highColor = ContextCompat.getColor(this, R.color.light_highColor) lowColor = ContextCompat.getColor(this, R.color.light_lowColor) midColor = ContextCompat.getColor(this, R.color.light_midColor) gridColor = ContextCompat.getColor(this, R.color.light_gridColor) basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_light) basalCenterColor = ContextCompat.getColor(this, R.color.basal_dark) pointSize = 2 setupCharts() } else { setColorDark() } } }
agpl-3.0
83fad2a4958ad91b6be4cbaf3fdf739d
49.719298
134
0.707887
4.282963
false
false
false
false
Saketme/JRAW
lib/src/main/kotlin/net/dean/jraw/databind/RedditModelAdapterFactory.kt
1
9768
package net.dean.jraw.databind import com.squareup.moshi.* import net.dean.jraw.models.KindConstants import net.dean.jraw.models.Listing import net.dean.jraw.models.internal.RedditModelEnvelope import java.lang.reflect.ParameterizedType import java.lang.reflect.Type /** * Creates JsonAdapters for a class annotated with [RedditModel]. * * This class assumes that the data is encapsulated in an envelope like this: * * ```json * { * "kind": "<kind>", * "data": { ... } * } * ``` * * The [Enveloped] annotation must be specified in order for this adapter factory to produce anything. * * ```kt * val adapter = moshi.adapter<Something>(Something::class.java, Enveloped::class.java) * val something = adapter.fromJson(json) * ``` * * If the target type does NOT have the `@RedditModel` annotation, it will be deserialized dynamically. For example, if * the JSON contains either a `Foo` or a `Bar`, we can specify their closest comment parent instead of either `Foo` or * `Bar`. * * ```kt * // Get an adapter that can deserialize boths Foos and Bars * moshi.adapter<Parent>(Parent::class.java, Enveloped::class.java) * ``` * * Dynamic deserialization works like this: * * 1. Write the JSON value into a "simple" type (e.g. a Map) * 2. Lookup the value of the "kind" node * 3. Determine the correct concrete class by looking up the kind in the [registry] * 4. Transform the intermediate JSON (the Map) into an instance of that class * * Keep in mind that dynamic deserialization is a bit hacky and is probably slower than static deserialization. */ class RedditModelAdapterFactory( /** * A Map of kinds (the value of the 'kind' node) to the concrete classes they represent. Not necessary if only * deserializing statically. Adding [Listing] to this class may cause problems. */ private val registry: Map<String, Class<*>> ) : JsonAdapter.Factory { /** @inheritDoc */ override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi): JsonAdapter<*>? { // Require @Enveloped val delegateAnnotations = Types.nextAnnotations(annotations, Enveloped::class.java) ?: return null val rawType = Types.getRawType(type) // Special handling for Listings if (rawType == Listing::class.java) { val childType = (type as ParameterizedType).actualTypeArguments.first() // Assume children are enveloped val delegate = moshi.adapter<Any>(childType, Enveloped::class.java).nullSafe() return ListingAdapter(delegate) } val isRedditModel = rawType.isAnnotationPresent(RedditModel::class.java) return if (isRedditModel) { // Static JsonAdapter val enveloped = rawType.getAnnotation(RedditModel::class.java).enveloped return if (enveloped) { val actualType = Types.newParameterizedType(RedditModelEnvelope::class.java, type) val delegate = moshi.adapter<RedditModelEnvelope<*>>(actualType).nullSafe() StaticAdapter(registry, delegate) } else { moshi.nextAdapter<Any>(this, type, delegateAnnotations).nullSafe() } } else { // Dynamic JsonAdapter DynamicNonGenericModelAdapter(registry, moshi, rawType) } } /** * Statically (normally) deserializes some JSON value into a concrete class. All generic types must be resolved * beforehand. */ private class StaticAdapter( private val registry: Map<String, Class<*>>, private val delegate: JsonAdapter<RedditModelEnvelope<*>> ) : JsonAdapter<Any>() { override fun toJson(writer: JsonWriter, value: Any?) { if (value == null) { writer.nullValue() return } // Reverse lookup the actual value of 'kind' from the registry var actualKind: String? = null for ((kind, clazz) in registry) if (clazz == value.javaClass) actualKind = kind if (actualKind == null) throw IllegalArgumentException("No registered kind for Class '${value.javaClass}'") delegate.toJson(writer, RedditModelEnvelope.create(actualKind, value)) } override fun fromJson(reader: JsonReader): Any? { return delegate.fromJson(reader)?.data ?: return null } } private abstract class DynamicAdapter<T>( protected val registry: Map<String, Class<*>>, protected val moshi: Moshi, protected val upperBound: Class<*> ) : JsonAdapter<T>() { override fun toJson(writer: JsonWriter?, value: T?) { throw UnsupportedOperationException("Serializing dynamic models aren't supported right now") } /** * Asserts that the given object is not null and the same class or a subclass of [upperBound]. Returns the value * after the check. */ protected fun ensureInBounds(obj: Any?): Any { if (!upperBound.isAssignableFrom(obj!!.javaClass)) throw IllegalArgumentException("Expected ${upperBound.name} to be assignable from $obj") return obj } } private class DynamicNonGenericModelAdapter(registry: Map<String, Class<*>>, moshi: Moshi, upperBound: Class<*>) : DynamicAdapter<Any>(registry, moshi, upperBound) { override fun fromJson(reader: JsonReader): Any? { val json = expectType<Map<String, Any>>(reader.readJsonValue(), "<root>") val kind = expectType<String>(json["kind"], "kind") val clazz = registry[kind] ?: throw IllegalArgumentException("No registered class for kind '$kind'") val envelopeType = Types.newParameterizedType(RedditModelEnvelope::class.java, clazz) val adapter = moshi.adapter<RedditModelEnvelope<*>>(envelopeType) val result = adapter.fromJsonValue(json)!! return ensureInBounds(result.data) } } private class ListingAdapter(val childrenDelegate: JsonAdapter<Any>) : JsonAdapter<Listing<Any>>() { override fun fromJson(reader: JsonReader): Listing<Any>? { // Assume that the JSON is enveloped, we have to strip that away and then parse the listing reader.beginObject() var listing: Listing<Any>? = null while (reader.hasNext()) { when (reader.selectName(envelopeOptions)) { 0 -> { // "kind" if (reader.nextString() != KindConstants.LISTING) throw IllegalArgumentException("Expecting kind to be listing at ${reader.path}") } 1 -> { // "data" listing = readListing(reader) } -1 -> { // Unknown, skip it reader.nextName() reader.skipValue() } } } reader.endObject() return listing } private fun readListing(reader: JsonReader): Listing<Any> { var after: String? = null val children: MutableList<Any> = ArrayList() reader.beginObject() while (reader.hasNext()) { when (reader.selectName(listingOptions)) { 0 -> { // "after" after = if (reader.peek() == JsonReader.Token.NULL) reader.nextNull() else reader.nextString() } 1 -> { // "data" reader.beginArray() while (reader.hasNext()) children.add(childrenDelegate.fromJson(reader)!!) reader.endArray() } -1 -> { // Unknown, skip it reader.nextName() reader.skipValue() } } } reader.endObject() return Listing.create(after, children) } override fun toJson(writer: JsonWriter, value: Listing<Any>?) { if (value == null) { writer.nullValue() return } writer.beginObject() writer.name("kind") writer.value(KindConstants.LISTING) writer.name("data") writeListing(writer, value) writer.endObject() } private fun writeListing(writer: JsonWriter, value: Listing<Any>) { writer.beginObject() writer.name("after") writer.value(value.nextName) writer.name("children") writer.beginArray() for (child in value.children) childrenDelegate.toJson(writer, child) writer.endArray() writer.endObject() } companion object { private val envelopeOptions = JsonReader.Options.of("kind", "data") private val listingOptions = JsonReader.Options.of("after", "children") } } /** */ companion object { private inline fun <reified T> expectType(obj: Any?, name: String): T { if (obj == null) throw IllegalArgumentException("Expected $name to be non-null") return obj as? T ?: throw IllegalArgumentException("Expected $name to be a ${T::class.java.name}, was ${obj::class.java.name}") } } }
mit
093f05f51d0e148633ecde8594494e8b
37.761905
123
0.575041
5.027277
false
false
false
false
k9mail/k-9
app/ui/legacy/src/test/java/com/fsck/k9/activity/compose/AttachmentPresenterTest.kt
2
6997
package com.fsck.k9.activity.compose import android.net.Uri import androidx.loader.app.LoaderManager import androidx.loader.app.LoaderManager.LoaderCallbacks import androidx.test.core.app.ApplicationProvider import com.fsck.k9.K9RobolectricTest import com.fsck.k9.activity.compose.AttachmentPresenter.AttachmentMvpView import com.fsck.k9.activity.compose.AttachmentPresenter.AttachmentsChangedListener import com.fsck.k9.activity.misc.Attachment import com.fsck.k9.mail.internet.MimeHeader import com.fsck.k9.mail.internet.MimeMessage import com.fsck.k9.mail.internet.MimeMessageHelper import com.fsck.k9.mail.internet.TextBody import com.fsck.k9.mailstore.AttachmentResolver import com.fsck.k9.mailstore.AttachmentViewInfo import com.fsck.k9.mailstore.LocalBodyPart import com.fsck.k9.mailstore.MessageViewInfo import com.google.common.truth.Truth.assertThat import java.util.function.Supplier import org.junit.Before import org.junit.Test import org.mockito.ArgumentMatchers.anyInt import org.mockito.Mockito.doAnswer import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.whenever private val attachmentMvpView = mock<AttachmentMvpView>() private val loaderManager = mock<LoaderManager>() private val listener = mock<AttachmentsChangedListener>() private val attachmentResolver = mock<AttachmentResolver>() private const val ACCOUNT_UUID = "uuid" private const val SUBJECT = "subject" private const val TEXT = "text" private const val EXTRA_TEXT = "extra text" private const val ATTACHMENT_NAME = "1x1.png" private const val MESSAGE_ID = 1L private const val PATH_TO_FILE = "path/to/file.png" private const val MIME_TYPE = "image/png" private val URI = Uri.Builder().scheme("content://").build() class AttachmentPresenterTest : K9RobolectricTest() { lateinit var attachmentPresenter: AttachmentPresenter @Before fun setUp() { attachmentPresenter = AttachmentPresenter( ApplicationProvider.getApplicationContext(), attachmentMvpView, loaderManager, listener ) } @Test fun loadNonInlineAttachments_normalAttachment() { val size = 42L val message = MimeMessage() MimeMessageHelper.setBody(message, TextBody(TEXT)) val attachmentViewInfo = AttachmentViewInfo( MIME_TYPE, ATTACHMENT_NAME, size, URI, false, LocalBodyPart(ACCOUNT_UUID, mock(), MESSAGE_ID, size), true ) val messageViewInfo = MessageViewInfo( message, false, message, SUBJECT, false, TEXT, listOf(attachmentViewInfo), null, attachmentResolver, EXTRA_TEXT, ArrayList(), null ) mockLoaderManager({ attachmentPresenter.attachments.get(0) as Attachment }) val result = attachmentPresenter.loadAllAvailableAttachments(messageViewInfo) assertThat(result).isTrue() assertThat(attachmentPresenter.attachments).hasSize(1) assertThat(attachmentPresenter.inlineAttachments).isEmpty() val attachment = attachmentPresenter.attachments.get(0) assertThat(attachment?.name).isEqualTo(ATTACHMENT_NAME) assertThat(attachment?.size).isEqualTo(size) assertThat(attachment?.state).isEqualTo(com.fsck.k9.message.Attachment.LoadingState.COMPLETE) assertThat(attachment?.fileName).isEqualTo(PATH_TO_FILE) } @Test fun loadNonInlineAttachments_normalAttachmentNotAvailable() { val size = 42L val message = MimeMessage() MimeMessageHelper.setBody(message, TextBody(TEXT)) val attachmentViewInfo = AttachmentViewInfo( MIME_TYPE, ATTACHMENT_NAME, size, URI, false, LocalBodyPart(ACCOUNT_UUID, mock(), MESSAGE_ID, size), false ) val messageViewInfo = MessageViewInfo( message, false, message, SUBJECT, false, TEXT, listOf(attachmentViewInfo), null, attachmentResolver, EXTRA_TEXT, ArrayList(), null ) val result = attachmentPresenter.loadAllAvailableAttachments(messageViewInfo) assertThat(result).isFalse() assertThat(attachmentPresenter.attachments).isEmpty() assertThat(attachmentPresenter.inlineAttachments).isEmpty() } @Test fun loadNonInlineAttachments_inlineAttachment() { val size = 42L val contentId = "xyz" val message = MimeMessage() MimeMessageHelper.setBody(message, TextBody(TEXT)) val localBodyPart = LocalBodyPart(ACCOUNT_UUID, mock(), MESSAGE_ID, size) localBodyPart.addHeader(MimeHeader.HEADER_CONTENT_ID, contentId) val attachmentViewInfo = AttachmentViewInfo(MIME_TYPE, ATTACHMENT_NAME, size, URI, true, localBodyPart, true) val messageViewInfo = MessageViewInfo( message, false, message, SUBJECT, false, TEXT, listOf(attachmentViewInfo), null, attachmentResolver, EXTRA_TEXT, ArrayList(), null ) mockLoaderManager({ attachmentPresenter.inlineAttachments.get(contentId) as Attachment }) val result = attachmentPresenter.loadAllAvailableAttachments(messageViewInfo) assertThat(result).isTrue() assertThat(attachmentPresenter.attachments).isEmpty() assertThat(attachmentPresenter.inlineAttachments).hasSize(1) val attachment = attachmentPresenter.inlineAttachments.get(contentId) assertThat(attachment?.name).isEqualTo(ATTACHMENT_NAME) assertThat(attachment?.size).isEqualTo(size) assertThat(attachment?.state).isEqualTo(com.fsck.k9.message.Attachment.LoadingState.COMPLETE) assertThat(attachment?.fileName).isEqualTo(PATH_TO_FILE) } @Test fun loadNonInlineAttachments_inlineAttachmentNotAvailable() { val size = 42L val contentId = "xyz" val message = MimeMessage() MimeMessageHelper.setBody(message, TextBody(TEXT)) val localBodyPart = LocalBodyPart(ACCOUNT_UUID, mock(), MESSAGE_ID, size) localBodyPart.addHeader(MimeHeader.HEADER_CONTENT_ID, contentId) val attachmentViewInfo = AttachmentViewInfo(MIME_TYPE, ATTACHMENT_NAME, size, URI, true, localBodyPart, false) val messageViewInfo = MessageViewInfo( message, false, message, SUBJECT, false, TEXT, listOf(attachmentViewInfo), null, attachmentResolver, EXTRA_TEXT, ArrayList(), null ) val result = attachmentPresenter.loadAllAvailableAttachments(messageViewInfo) assertThat(result).isFalse() assertThat(attachmentPresenter.attachments).isEmpty() assertThat(attachmentPresenter.inlineAttachments).isEmpty() } private fun mockLoaderManager(attachmentSupplier: Supplier<Attachment>) { doAnswer { val loaderCallbacks = it.getArgument<LoaderCallbacks<Attachment>>(2) loaderCallbacks.onLoadFinished(mock(), attachmentSupplier.get().deriveWithLoadComplete(PATH_TO_FILE)) null }.whenever(loaderManager).initLoader(anyInt(), any(), any<LoaderCallbacks<Attachment>>()) } }
apache-2.0
33de947beb3ed41894d8688fe9b8fc34
43.006289
118
0.730599
4.615435
false
true
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/fragment/HorizontalTabBarBuilder.kt
1
1913
package org.hexworks.zircon.api.builder.fragment import org.hexworks.zircon.api.Beta import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.fragment.TabBar import org.hexworks.zircon.api.fragment.builder.FragmentBuilder import org.hexworks.zircon.internal.fragment.impl.DefaultHorizontalTabBar import org.hexworks.zircon.internal.fragment.impl.TabBarBuilder import kotlin.jvm.JvmStatic @Beta class HorizontalTabBarBuilder private constructor( size: Size = Size.unknown(), defaultSelected: String? = null, tabs: List<TabBuilder> = listOf(), position: Position = Position.zero() ) : TabBarBuilder( size = size, defaultSelected = defaultSelected, tabs = tabs, position = position ), FragmentBuilder<TabBar, HorizontalTabBarBuilder> { fun HorizontalTabBarBuilder.tab(init: TabBuilder.() -> Unit) { tabs = tabs + TabBuilder.newBuilder().apply(init) } val contentSize: Size get() = size.withRelativeHeight(-3) override fun withPosition(position: Position) = also { this.position = position } override fun createCopy() = HorizontalTabBarBuilder( size = size, defaultSelected = defaultSelected, tabs = tabs, position = position ) override fun build(): TabBar { checkCommonProperties() val finalTabs = tabs.map { it.build() } require(finalTabs.fold(0) { acc, next -> acc + next.tab.tabButton.width } <= size.width) { "There is not enough space to display all the tabs" } return DefaultHorizontalTabBar( size = size, defaultSelected = defaultSelected ?: finalTabs.first().tab.key, tabs = finalTabs ) } companion object { @JvmStatic fun newBuilder(): HorizontalTabBarBuilder = HorizontalTabBarBuilder() } }
apache-2.0
681f020295876e22ac1f329f7eb88d1a
29.365079
98
0.680084
4.289238
false
false
false
false
android/renderscript-intrinsics-replacement-toolkit
test-app/src/main/java/com/google/android/renderscript_test/ReferenceLut3d.kt
1
2934
/* * 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.google.android.renderscript_test import com.google.android.renderscript.Range2d import com.google.android.renderscript.Rgba3dArray /** * Reference implementation of a 3D LookUpTable operation. */ @ExperimentalUnsignedTypes fun referenceLut3d( inputArray: ByteArray, sizeX: Int, sizeY: Int, cube: Rgba3dArray, restriction: Range2d? ): ByteArray { val input = Vector2dArray(inputArray.asUByteArray(), 4, sizeX, sizeY) val output = input.createSameSized() input.forEach(restriction) { x, y -> output[x, y] = lookup(input[x, y], cube) } return output.values.asByteArray() } @ExperimentalUnsignedTypes private fun lookup(input: UByteArray, cube: Rgba3dArray): UByteArray { // Calculate the two points at opposite edges of the size 1 // cube that contains our point. val maxIndex = Int4(cube.sizeX - 1, cube.sizeY - 1, cube.sizeZ - 1, 0) val baseCoordinate: Float4 = input.toFloat4() * maxIndex.toFloat4() / 255f val point1: Int4 = baseCoordinate.intFloor() val point2: Int4 = min(point1 + 1, maxIndex) val fractionAwayFromPoint1: Float4 = baseCoordinate - point1.toFloat4() // Get the RGBA values at each of the four corners of the size 1 cube. val v000 = cube[point1.x, point1.y, point1.z].toFloat4() val v100 = cube[point2.x, point1.y, point1.z].toFloat4() val v010 = cube[point1.x, point2.y, point1.z].toFloat4() val v110 = cube[point2.x, point2.y, point1.z].toFloat4() val v001 = cube[point1.x, point1.y, point2.z].toFloat4() val v101 = cube[point2.x, point1.y, point2.z].toFloat4() val v011 = cube[point1.x, point2.y, point2.z].toFloat4() val v111 = cube[point2.x, point2.y, point2.z].toFloat4() // Do the linear mixing of these eight values. val yz00 = mix(v000, v100, fractionAwayFromPoint1.x) val yz10 = mix(v010, v110, fractionAwayFromPoint1.x) val yz01 = mix(v001, v101, fractionAwayFromPoint1.x) val yz11 = mix(v011, v111, fractionAwayFromPoint1.x) val z0 = mix(yz00, yz10, fractionAwayFromPoint1.y) val z1 = mix(yz01, yz11, fractionAwayFromPoint1.y) val v = mix(z0, z1, fractionAwayFromPoint1.z) // Preserve the alpha of the original value return ubyteArrayOf(v.x.clampToUByte(), v.y.clampToUByte(), v.z.clampToUByte(), input[3]) }
apache-2.0
c99fb15466cd787eda8bc9425e2c28c8
38.648649
93
0.706203
3.360825
false
false
false
false
pyamsoft/pydroid
billing/src/main/java/com/pyamsoft/pydroid/billing/store/PlayBillingSku.kt
1
1239
/* * Copyright 2022 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.pydroid.billing.store import com.android.billingclient.api.ProductDetails import com.pyamsoft.pydroid.billing.BillingSku import com.pyamsoft.pydroid.core.requireNotNull internal data class PlayBillingSku internal constructor(internal val sku: ProductDetails) : BillingSku { private val product = sku.oneTimePurchaseOfferDetails.requireNotNull() override val id: String = sku.productId override val displayPrice: String = product.formattedPrice override val price: Long = product.priceAmountMicros override val title: String = sku.title override val description: String = sku.description }
apache-2.0
116c902f31ac56a63baf6862d0a15c41
32.486486
91
0.774011
4.378092
false
false
false
false
Hexworks/zircon
zircon.core/src/jvmTest/kotlin/org/hexworks/zircon/internal/uievent/impl/UIEventToComponentDispatcherTest.kt
1
6311
package org.hexworks.zircon.internal.uievent.impl import org.assertj.core.api.Assertions.assertThat import org.hexworks.cobalt.events.api.EventBus import org.hexworks.zircon.api.uievent.* import org.hexworks.zircon.internal.behavior.ComponentFocusOrderList import org.hexworks.zircon.internal.component.InternalContainer import org.hexworks.zircon.internal.component.impl.RootContainer import org.hexworks.zircon.internal.event.ZirconScope import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.Mock import org.mockito.junit.MockitoJUnit import org.mockito.junit.MockitoRule import org.mockito.kotlin.* import org.mockito.quality.Strictness import kotlin.contracts.ExperimentalContracts @Suppress("TestFunctionName") @ExperimentalContracts class UIEventToComponentDispatcherTest { @get:Rule val mockitoRule: MockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS) lateinit var target: UIEventToComponentDispatcher @Mock lateinit var rootMock: RootContainer @Mock lateinit var child0Mock: InternalContainer @Mock lateinit var child1Mock: InternalContainer @Mock lateinit var focusOrderListMock: ComponentFocusOrderList @Before fun setUp() { val eventBus = EventBus.create() val eventScope = ZirconScope() whenever(rootMock.calculatePathTo(anyOrNull())).thenReturn(listOf(rootMock)) whenever(rootMock.eventScope).thenReturn(eventScope) whenever(rootMock.eventBus).thenReturn(eventBus) target = UIEventToComponentDispatcher(rootMock, focusOrderListMock) } @Test fun dispatchShouldReturnPassWhenThereIsNoTarget() { whenever(focusOrderListMock.focusedComponent).thenReturn(rootMock) whenever(rootMock.process(KEY_A_PRESSED_EVENT, UIEventPhase.TARGET)).thenReturn(Pass) whenever(rootMock.keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.TARGET)).thenReturn(Pass) val result = target.dispatch(KEY_A_PRESSED_EVENT) assertThat(result).isEqualTo(Pass) } @Test fun dispatchShouldReturnProcessedWhenTargetsDefaultIsRun() { whenever(focusOrderListMock.focusedComponent).thenReturn(rootMock) whenever(rootMock.process(KEY_A_PRESSED_EVENT, UIEventPhase.TARGET)).thenReturn(Pass) whenever(rootMock.keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.TARGET)).thenReturn(Processed) val result = target.dispatch(KEY_A_PRESSED_EVENT) assertThat(result).isEqualTo(Processed) } @Test fun dispatchShouldReturnPreventDefaultWhenChildPreventedDefault() { whenever(focusOrderListMock.focusedComponent).thenReturn(child1Mock) whenever(rootMock.calculatePathTo(child1Mock)).thenReturn(listOf(rootMock, child0Mock, child1Mock)) whenever(rootMock.process(KEY_A_PRESSED_EVENT, UIEventPhase.CAPTURE)).thenReturn(Pass) whenever(rootMock.keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.CAPTURE)).thenReturn(Pass) whenever(child0Mock.process(KEY_A_PRESSED_EVENT, UIEventPhase.CAPTURE)).thenReturn(PreventDefault) whenever(child1Mock.process(KEY_A_PRESSED_EVENT, UIEventPhase.TARGET)).thenReturn(Pass) whenever(child0Mock.process(KEY_A_PRESSED_EVENT, UIEventPhase.BUBBLE)).thenReturn(Pass) whenever(rootMock.process(KEY_A_PRESSED_EVENT, UIEventPhase.BUBBLE)).thenReturn(Pass) val result = target.dispatch(KEY_A_PRESSED_EVENT) // Child mock 0 shouldn't be called with key pressed in the capture phase verify(child0Mock, never()).keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.CAPTURE) // Child mock 1 shouldn't be called with key pressed in the target phase verify(child1Mock, never()).keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.TARGET) // Root mock shouldn't be called with key pressed in the bubble phase verify(rootMock, never()).keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.BUBBLE) assertThat(result).isEqualTo(PreventDefault) } @Test fun dispatchShouldReturnStopPropagationWhenFirstChildStoppedPropagation() { whenever(focusOrderListMock.focusedComponent).thenReturn(child1Mock) whenever(rootMock.calculatePathTo(child1Mock)).thenReturn(listOf(rootMock, child0Mock, child1Mock)) whenever(rootMock.process(KEY_A_PRESSED_EVENT, UIEventPhase.CAPTURE)).thenReturn(Pass) whenever(rootMock.keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.CAPTURE)).thenReturn(Pass) whenever(child0Mock.process(KEY_A_PRESSED_EVENT, UIEventPhase.CAPTURE)).thenReturn(StopPropagation) val result = target.dispatch(KEY_A_PRESSED_EVENT) // Child mock 1 shouldn't be called with process in the target phase verify(child1Mock, never()).keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.TARGET) // Child mock 0 shouldn't be called with process in the bubble phase verify(child0Mock, never()).keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.BUBBLE) // Root mock shouldn't be called with process in the bubble phase verify(rootMock, never()).keyPressed(KEY_A_PRESSED_EVENT, UIEventPhase.BUBBLE) assertThat(result).isEqualTo(StopPropagation) } @Test fun When_a_child_stops_propagation_of_the_tab_key_Then_component_events_shouldnt_be_performed() { whenever(focusOrderListMock.focusedComponent).thenReturn(child0Mock) whenever(rootMock.calculatePathTo(child0Mock)).thenReturn(listOf(rootMock, child0Mock)) whenever(rootMock.process(TAB_PRESSED_EVENT, UIEventPhase.CAPTURE)).thenReturn(Pass) whenever(rootMock.keyPressed(TAB_PRESSED_EVENT, UIEventPhase.CAPTURE)).thenReturn(Pass) whenever(child0Mock.process(TAB_PRESSED_EVENT, UIEventPhase.TARGET)).thenReturn(StopPropagation) val result = target.dispatch(TAB_PRESSED_EVENT) verify(child0Mock, never()).focusGiven() assertThat(result).isEqualTo(StopPropagation) } companion object { val KEY_A_PRESSED_EVENT = KeyboardEvent( type = KeyboardEventType.KEY_PRESSED, key = "a", code = KeyCode.KEY_A ) val TAB_PRESSED_EVENT = KeyboardEvent( type = KeyboardEventType.KEY_PRESSED, code = KeyCode.TAB, key = "\t" ) } }
apache-2.0
117dc99c75d0e7e84397ea9adc05f291
38.44375
107
0.737918
4.22706
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/main/jetpack/migration/compose/components/ButtonsColumn.kt
1
804
package org.wordpress.android.ui.main.jetpack.migration.compose.components import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.padding import androidx.compose.material.Divider import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.colorResource import androidx.compose.ui.unit.dp import org.wordpress.android.R.color @Composable fun ButtonsColumn( modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit ) { Column( modifier = modifier.padding(bottom = 50.dp) ) { Divider( color = colorResource(color.gray_10), thickness = 0.5.dp, ) content() } }
gpl-2.0
726ce6dad7e4411ac9d8855628e0f275
28.777778
74
0.722637
4.165803
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/components/TextFieldComponent.kt
4
2147
// 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.tools.projectWizard.wizard.ui.components import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.core.entity.SettingValidator import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.componentWithCommentAtBottom import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.textField import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import javax.swing.JComponent class TextFieldComponent( context: Context, labelText: String? = null, description: String? = null, initialValue: String? = null, validator: SettingValidator<String>? = null, onValueUpdate: (String, isByUser: Boolean) -> Unit = { _, _ -> } ) : UIComponent<String>( context, labelText, validator, onValueUpdate ) { private var isDisabled: Boolean = false private var cachedValueWhenDisabled: String? = null @Suppress("HardCodedStringLiteral") private val textField = textField(initialValue.orEmpty(), ::fireValueUpdated) override val alignTarget: JComponent get() = textField override val uiComponent = componentWithCommentAtBottom(textField, description) override fun updateUiValue(newValue: String) = safeUpdateUi { textField.text = newValue } fun onUserType(action: () -> Unit) { textField.addKeyListener(object : KeyAdapter() { override fun keyReleased(e: KeyEvent?) = action() }) } fun disable(@Nls message: String) { cachedValueWhenDisabled = getUiValue() textField.isEditable = false textField.foreground = UIUtil.getLabelDisabledForeground() isDisabled = true updateUiValue(message) } override fun validate(value: String) { if (isDisabled) return super.validate(value) } override fun getUiValue(): String = cachedValueWhenDisabled ?: textField.text }
apache-2.0
e84050e230bbe01d08371da7be2bc467
34.213115
158
0.726129
4.539112
false
false
false
false
JetBrains/teamcity-nuget-support
nuget-feed/src/jetbrains/buildServer/nuget/feed/server/json/JsonRegistrationHandler.kt
1
3080
package jetbrains.buildServer.nuget.feed.server.json import jetbrains.buildServer.nuget.feed.server.NuGetFeedConstants import jetbrains.buildServer.nuget.feed.server.controllers.NuGetFeedHandler import jetbrains.buildServer.nuget.feed.server.index.NuGetFeedData import jetbrains.buildServer.nuget.feed.server.index.NuGetFeedFactory import jetbrains.buildServer.serverSide.TeamCityProperties import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse class JsonRegistrationHandler(private val feedFactory: NuGetFeedFactory, private val packageSourceFactory: JsonPackageSourceFactory, private val adapterFactory: JsonPackageAdapterFactory) : NuGetFeedHandler { override fun handleRequest(feedData: NuGetFeedData, request: HttpServletRequest, response: HttpServletResponse) { val matchResult = REGISTRATION_URL.find(request.pathInfo) if (matchResult != null) { val (id, resource) = matchResult.destructured val feed = feedFactory.createFeed(feedData) val context = JsonNuGetFeedContext(feed, request) if (resource == "index") { if (DispatcherUtils.isAsyncEnabled()) { DispatcherUtils.dispatchGetRegistrations(request, response, context, id) } else { getAllRegistrations(response, context, id) } } else { if (DispatcherUtils.isAsyncEnabled()) { DispatcherUtils.dispatchGetRegistration(request, response, context, id, resource) } else { getRegistration(response, context, id, resource) } } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Requested resource not found") } } private fun getRegistration(response: HttpServletResponse, context: JsonNuGetFeedContext, id: String, version: String) { val packageSource = packageSourceFactory.create(context.feed) val results = packageSource.getPackages(id) if (!results.isEmpty()) { val adapter = adapterFactory.create(context) response.writeJson(adapter.createPackagesResponse(id, results)) } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Package $id:$version not found") } } private fun getAllRegistrations(response: HttpServletResponse, context: JsonNuGetFeedContext,id: String) { val packageSource = packageSourceFactory.create(context.feed) val results = packageSource.getPackages(id) if (!results.isEmpty()) { val adapter = adapterFactory.create(context) response.writeJson(adapter.createPackagesResponse(id, results)) } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Package $id not found") } } companion object { private val REGISTRATION_URL = Regex("\\/registration1\\/([^\\/]+)\\/([^\\/]+)\\.json") } }
apache-2.0
6d658c1aa27b87901eede917fa657bcc
44.970149
124
0.66526
4.928
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/achievement/list/AchievementListViewState.kt
1
1554
package io.ipoli.android.achievement.list import io.ipoli.android.achievement.usecase.CreateAchievementItemsUseCase import io.ipoli.android.common.AppState import io.ipoli.android.common.BaseViewStateReducer import io.ipoli.android.common.DataLoadedAction import io.ipoli.android.common.redux.Action import io.ipoli.android.common.redux.BaseViewState /** * Created by Venelin Valkov <[email protected]> * on 06/09/2018. */ sealed class AchievementListAction : Action { object Load : AchievementListAction() } object AchievementListReducer : BaseViewStateReducer<AchievementListViewState>() { override val stateKey = key<AchievementListViewState>() override fun reduce( state: AppState, subState: AchievementListViewState, action: Action ) = when (action) { is DataLoadedAction.AchievementItemsChanged -> { subState.copy( type = AchievementListViewState.StateType.ACHIEVEMENTS_LOADED, achievementListItems = action.achievementListItems ) } else -> subState } override fun defaultState() = AchievementListViewState( type = AchievementListViewState.StateType.LOADING, achievementListItems = emptyList() ) } data class AchievementListViewState( val type: StateType, val achievementListItems: List<CreateAchievementItemsUseCase.AchievementListItem> ) : BaseViewState() { enum class StateType { LOADING, ACHIEVEMENTS_LOADED } }
gpl-3.0
9ae0187cb03cfa29832b6994e0111007
29.490196
85
0.702059
5.111842
false
false
false
false
mobilesolutionworks/works-controller-android
library/src/main/kotlin/com/mobilesolutionworks/android/app/controller/WorksController.kt
1
3882
package com.mobilesolutionworks.android.app.controller import android.content.Context import android.content.res.Configuration import android.os.Bundle import android.support.annotation.StringRes /** * The main class of this library. * * * Created by yunarta on 16/11/15. */ open class WorksController(val mManager: WorksControllerManager) { // /** // * Reference to manager. // */ // private var mManager: WorksControllerManager? = null // /** // * Set controller manager, called by manager. // // * @param manager the controller manager. // */ // internal fun setControllerManager(manager: WorksControllerManager) { // mManager = manager // } /** * Get application context from controller. * @return application context. */ val context: Context get() = mManager.context /** * Get string from context */ fun getString(@StringRes id: Int): String { return mManager.context.getString(id) } /** * Called when manager is creating this controller. * * * This is not related to Activity or Fragment onCreate. * @param arguments arguments that is supplied in [WorksControllerManager.initController] */ open fun onCreate(arguments: Bundle?) { // Lifecycle event called when controller is created } internal fun dispatchOnPaused() = onPaused() /** * Called when host enters paused state. */ protected fun onPaused() { // Lifecycle event called when host is paused } /** * Called when host enters resumed state */ protected fun onResume() { // Lifecycle event called when host is resumed } internal fun dispatchOnResume() = onResume() /** * Called when manager destroy the controller. */ open fun onDestroy() { // Lifecycle event called when controlled is destroyed } /** * Called when after host re-creation. * @param state contains stated that you store in onSaveInstanceState. */ open fun onRestoreInstanceState(state: Bundle) { // Lifecycle event called when host is view state is restored } internal fun dispatchOnRestoreInstanceState(state: Bundle) = onRestoreInstanceState(state) /** * Called when host enter re-creation state. * * * In certain state, the controller might get release along with host * but usually what you store in state is still preserved after creation. * @param outState bundle for storing information if required. */ open fun onSaveInstanceState(outState: Bundle) { // Lifecycle event called when host is want to save instance state } internal fun dispatchOnSaveInstanceState(outState: Bundle) = onSaveInstanceState(outState) /** * Called when host receive onConfigurationChanged. * @param config new configuration. */ open fun onConfigurationChanged(config: Configuration) { // Lifecycle event called when host has configuration changed } /** * Executes the specified runnable after application enter resumed state. * @param runnable runnable object. */ fun runWhenUiIsReady(runnable: Runnable) { mManager.mainScheduler.runWhenUiIsReady(runnable) } /** * Executes the specified runnable immediately in main thread. * @param runnable runnable object. */ fun runOnMainThread(runnable: Runnable) { mManager.mainScheduler.runOnMainThread(runnable) } /** * Executes the specified runnable delayed in main thread. * @param runnable runnable object. * * * @param delay time to delay in milliseconds. */ fun runOnMainThreadDelayed(runnable: Runnable, delay: Long) { mManager.mainScheduler.runOnMainThreadDelayed(runnable, delay) } }
apache-2.0
7bd1bbfa6809b1566714e058d8da21b1
25.772414
94
0.661515
4.907712
false
true
false
false
GunoH/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/imports/ImportsUtils.kt
8
2434
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("ImportsUtils") package org.jetbrains.kotlin.idea.imports import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtReferenceExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.bindingContextUtil.getReferenceTargets import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor import org.jetbrains.kotlin.types.KotlinType val DeclarationDescriptor.importableFqName: FqName? get() { if (!canBeReferencedViaImport()) return null return getImportableDescriptor().fqNameSafe } fun DeclarationDescriptor.canBeReferencedViaImport(): Boolean { if (this is PackageViewDescriptor || DescriptorUtils.isTopLevelDeclaration(this) || this is CallableDescriptor && DescriptorUtils.isStaticDeclaration(this) ) { return !name.isSpecial } //Both TypeAliasDescriptor and ClassDescriptor val parentClassifier = containingDeclaration as? ClassifierDescriptorWithTypeParameters ?: return false if (!parentClassifier.canBeReferencedViaImport()) return false return when (this) { is ConstructorDescriptor -> !parentClassifier.isInner // inner class constructors can't be referenced via import is ClassDescriptor, is TypeAliasDescriptor -> true else -> parentClassifier is ClassDescriptor && parentClassifier.kind == ClassKind.OBJECT } } fun DeclarationDescriptor.canBeAddedToImport(): Boolean = this !is PackageViewDescriptor && canBeReferencedViaImport() fun KotlinType.canBeReferencedViaImport(): Boolean { val descriptor = constructor.declarationDescriptor return descriptor != null && descriptor.canBeReferencedViaImport() } // for cases when class qualifier refers companion object treats it like reference to class itself fun KtReferenceExpression.getImportableTargets(bindingContext: BindingContext): Collection<DeclarationDescriptor> { val targets = bindingContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, this]?.let { listOf(it) } ?: getReferenceTargets(bindingContext) return targets.map { it.getImportableDescriptor() }.toSet() }
apache-2.0
830b16dc6686d2b1b0387e1a9717681f
44.074074
120
0.786771
5.31441
false
false
false
false
GunoH/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/ToolWindowUtils.kt
2
3311
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.DataProvider import com.intellij.ui.content.Content import com.intellij.ui.content.ContentFactory import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.PackageSearchPanelBase import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.SimpleToolWindowWithToolWindowActionsPanel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.SimpleToolWindowWithTwoToolbarsPanel import org.jetbrains.annotations.Nls import javax.swing.JComponent internal fun PackageSearchPanelBase.initialize(contentFactory: ContentFactory): Content { val panelContent = content // should be executed before toolbars val toolbar = toolbar val topToolbar = topToolbar val gearActions = gearActions val titleActions = titleActions return if (topToolbar == null) { createSimpleToolWindowWithToolWindowActionsPanel( title = title, content = panelContent, toolbar = toolbar, gearActions = gearActions, titleActions = titleActions, contentFactory = contentFactory, provider = this ) } else { contentFactory.createContent( toolbar?.let { SimpleToolWindowWithTwoToolbarsPanel( it, topToolbar, gearActions, titleActions, panelContent ) }, title, false ).apply { isCloseable = false } } } internal fun createSimpleToolWindowWithToolWindowActionsPanel( @Nls title: String, content: JComponent, toolbar: JComponent?, gearActions: ActionGroup?, titleActions: List<AnAction>, contentFactory: ContentFactory, provider: DataProvider ): Content { val createContent = contentFactory.createContent(null, title, false) val actionsPanel = SimpleToolWindowWithToolWindowActionsPanel( gearActions = gearActions, titleActions = titleActions, vertical = false, provider = provider ) actionsPanel.setProvideQuickActions(true) actionsPanel.setContent(content) toolbar?.let { actionsPanel.toolbar = it } createContent.component = actionsPanel createContent.isCloseable = false return createContent }
apache-2.0
4b1faf79aa8abd20a20dfc1522964777
36.202247
114
0.673815
5.323151
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/gdpr/Agreements.kt
2
4512
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("Agreements") package com.intellij.ide.gdpr import com.intellij.diagnostic.LoadingState import com.intellij.idea.AppExitCodes import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.impl.ApplicationInfoImpl import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.HtmlChunk import com.intellij.ui.AppUIUtil import java.util.* import kotlin.system.exitProcess fun showEndUserAndDataSharingAgreements(agreement: EndUserAgreement.Document) { val ui = AgreementUi.create(agreement.text) applyUserAgreement(ui, agreement).pack().show() } internal fun showDataSharingAgreement() { val ui = AgreementUi.create() applyDataSharing(ui, ResourceBundle.getBundle("messages.AgreementsBundle")).pack().show() } private fun applyUserAgreement(ui: AgreementUi, agreement: EndUserAgreement.Document): AgreementUi { val isPrivacyPolicy = agreement.isPrivacyPolicy val bundle = ResourceBundle.getBundle("messages.AgreementsBundle") val commonUserAgreement = ui .setTitle( if (isPrivacyPolicy) ApplicationInfoImpl.getShadowInstance().shortCompanyName + " " + bundle.getString("userAgreement.dialog.privacyPolicy.title") else ApplicationNamesInfo.getInstance().fullProductName + " " + bundle.getString("userAgreement.dialog.userAgreement.title")) .setDeclineButton(bundle.getString("userAgreement.dialog.exit")) { if (LoadingState.COMPONENTS_REGISTERED.isOccurred) { ApplicationManager.getApplication().exit(true, true, false) } else { exitProcess(AppExitCodes.PRIVACY_POLICY_REJECTION) } } .addCheckBox(bundle.getString("userAgreement.dialog.checkBox")) { checkBox -> ui.enableAcceptButton(checkBox.isSelected) if (checkBox.isSelected) ui.focusToAcceptButton() } if (ApplicationInfoImpl.getShadowInstance().isEAP) { commonUserAgreement .setAcceptButton(bundle.getString("userAgreement.dialog.continue"), false) { dialogWrapper: DialogWrapper -> EndUserAgreement.setAccepted(agreement) dialogWrapper.close(DialogWrapper.OK_EXIT_CODE) } .addEapPanel(isPrivacyPolicy) } else { commonUserAgreement .setAcceptButton(bundle.getString("userAgreement.dialog.continue"), false) { dialogWrapper: DialogWrapper -> EndUserAgreement.setAccepted(agreement) if (ConsentOptions.needToShowUsageStatsConsent()) { applyDataSharing(ui, bundle) } else { dialogWrapper.close(DialogWrapper.OK_EXIT_CODE) } } } return ui } private fun applyDataSharing(ui: AgreementUi, bundle: ResourceBundle): AgreementUi { val dataSharingConsent = ConsentOptions.getInstance().getConsents(ConsentOptions.condUsageStatsConsent()).first[0] ui.setContent(prepareConsentsHtml(dataSharingConsent, bundle)) .setTitle(bundle.getString("dataSharing.dialog.title")) .clearBottomPanel() .focusToText() .setAcceptButton(bundle.getString("dataSharing.dialog.accept")) { AppUIUtil.saveConsents(listOf(dataSharingConsent.derive(true))) it.close(DialogWrapper.OK_EXIT_CODE) } .setDeclineButton(bundle.getString("dataSharing.dialog.decline")) { AppUIUtil.saveConsents(listOf(dataSharingConsent.derive(false))) it.close(DialogWrapper.CANCEL_EXIT_CODE) } return ui } private fun prepareConsentsHtml(consent: Consent, bundle: ResourceBundle): HtmlChunk { val allProductChunk = if (!ConsentOptions.getInstance().isEAP) { val hint = bundle.getString("dataSharing.applyToAll.hint").replace("{0}", ApplicationInfoImpl.getShadowInstance().shortCompanyName) HtmlChunk.text(hint).wrapWith("hint").wrapWith("p") } else HtmlChunk.empty() val preferencesHint = bundle.getString("dataSharing.revoke.hint").replace("{0}", ShowSettingsUtil.getSettingsMenuName()) val preferencesChunk = HtmlChunk.text(preferencesHint).wrapWith("hint").wrapWith("p") val title = HtmlChunk.text(bundle.getString("dataSharing.consents.title")).wrapWith("h1") return HtmlBuilder() .append(title) .append(HtmlChunk.p().addRaw(consent.text)) .append(allProductChunk) .append(preferencesChunk) .wrapWithHtmlBody() }
apache-2.0
75fbb17b3f2678df5202cd50b3f1ce15
42.394231
135
0.755984
4.363636
false
false
false
false
jk1/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/ssi/SsiProcessor.kt
3
14607
// 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.builtInWebServer.ssi import com.intellij.openapi.diagnostic.Logger import com.intellij.util.SmartList import com.intellij.util.io.inputStream import com.intellij.util.io.lastModified import com.intellij.util.io.readChars import com.intellij.util.io.size import com.intellij.util.text.CharArrayUtil import gnu.trove.THashMap import io.netty.buffer.ByteBufUtf8Writer import java.io.IOException import java.nio.file.Path import java.util.* internal val LOG = Logger.getInstance(SsiProcessor::class.java) internal val COMMAND_START = "<!--#" internal val COMMAND_END = "-->" class SsiStopProcessingException : RuntimeException() class SsiProcessor(allowExec: Boolean) { private val commands: MutableMap<String, SsiCommand> = THashMap() init { commands.put("config", SsiCommand { state, _, paramNames, paramValues, writer -> for (i in paramNames.indices) { val paramName = paramNames[i] val paramValue = paramValues[i] val substitutedValue = state.substituteVariables(paramValue) when { paramName.equals("errmsg", ignoreCase = true) -> state.configErrorMessage = substitutedValue paramName.equals("sizefmt", ignoreCase = true) -> state.configSizeFmt = substitutedValue paramName.equals("timefmt", ignoreCase = true) -> state.setConfigTimeFormat(substitutedValue, false) else -> { LOG.info("#config--Invalid attribute: $paramName") // We need to fetch this value each time, since it may change during the loop writer.write(state.configErrorMessage) } } } 0 }) commands.put("echo", SsiCommand { state, _, paramNames, paramValues, writer -> var encoding = "entity" var originalValue: String? = null val errorMessage = state.configErrorMessage for (i in paramNames.indices) { val paramName = paramNames[i] val paramValue = paramValues[i] if (paramName.equals("var", ignoreCase = true)) { originalValue = paramValue } else if (paramName.equals("encoding", ignoreCase = true)) { if (paramValue.equals("url", ignoreCase = true) || paramValue.equals("entity", ignoreCase = true) || paramValue.equals("none", ignoreCase = true)) { encoding = paramValue } else { LOG.info("#echo--Invalid encoding: $paramValue") writer.write(errorMessage) } } else { LOG.info("#echo--Invalid attribute: $paramName") writer.write(errorMessage) } } val variableValue = state.getVariableValue(originalValue!!, encoding) writer.write(variableValue ?: "(none)") System.currentTimeMillis() }) //noinspection StatementWithEmptyBody if (allowExec) { // commands.put("exec", new SsiExec()); } commands.put("include", SsiCommand { state, commandName, paramNames, paramValues, writer -> var lastModified: Long = 0 val configErrorMessage = state.configErrorMessage for (i in paramNames.indices) { val paramName = paramNames[i] if (paramName.equals("file", ignoreCase = true) || paramName.equals("virtual", ignoreCase = true)) { val substitutedValue = state.substituteVariables(paramValues[i]) try { val virtual = paramName.equals("virtual", ignoreCase = true) lastModified = state.ssiExternalResolver.getFileLastModified(substitutedValue, virtual) val file = state.ssiExternalResolver.findFile(substitutedValue, virtual) if (file == null) { LOG.warn("#include-- Couldn't find file: $substitutedValue") return@SsiCommand 0 } file.inputStream().use { writer.write(it, file.size().toInt()) } } catch (e: IOException) { LOG.warn("#include--Couldn't include file: $substitutedValue", e) writer.write(configErrorMessage) } } else { LOG.info("#include--Invalid attribute: $paramName") writer.write(configErrorMessage) } } lastModified }) commands.put("flastmod", SsiCommand { state, _, paramNames, paramValues, writer -> var lastModified: Long = 0 val configErrMsg = state.configErrorMessage for (i in paramNames.indices) { val paramName = paramNames[i] val paramValue = paramValues[i] val substitutedValue = state.substituteVariables(paramValue) if (paramName.equals("file", ignoreCase = true) || paramName.equals("virtual", ignoreCase = true)) { val virtual = paramName.equals("virtual", ignoreCase = true) lastModified = state.ssiExternalResolver.getFileLastModified(substitutedValue, virtual) val strftime = Strftime(state.configTimeFmt, Locale.US) writer.write(strftime.format(Date(lastModified))) } else { LOG.info("#flastmod--Invalid attribute: $paramName") writer.write(configErrMsg) } } lastModified }) commands.put("fsize", SsiFsize()) commands.put("printenv", SsiCommand { state, _, paramNames, _, writer -> var lastModified: Long = 0 // any arguments should produce an error if (paramNames.isEmpty()) { val variableNames = LinkedHashSet<String>() //These built-in variables are supplied by the mediator ( if not over-written by the user ) and always exist variableNames.add("DATE_GMT") variableNames.add("DATE_LOCAL") variableNames.add("LAST_MODIFIED") state.ssiExternalResolver.addVariableNames(variableNames) for (variableName in variableNames) { var variableValue: String? = state.getVariableValue(variableName) // This shouldn't happen, since all the variable names must have values if (variableValue == null) { variableValue = "(none)" } writer.append(variableName).append('=').append(variableValue).append('\n') lastModified = System.currentTimeMillis() } } else { writer.write(state.configErrorMessage) } lastModified }) commands.put("set", SsiCommand { state, _, paramNames, paramValues, writer -> var lastModified: Long = 0 val errorMessage = state.configErrorMessage var variableName: String? = null for (i in paramNames.indices) { val paramName = paramNames[i] val paramValue = paramValues[i] if (paramName.equals("var", ignoreCase = true)) { variableName = paramValue } else if (paramName.equals("value", ignoreCase = true)) { if (variableName != null) { val substitutedValue = state.substituteVariables(paramValue) state.ssiExternalResolver.setVariableValue(variableName, substitutedValue) lastModified = System.currentTimeMillis() } else { LOG.info("#set--no variable specified") writer.write(errorMessage) throw SsiStopProcessingException() } } else { LOG.info("#set--Invalid attribute: $paramName") writer.write(errorMessage) throw SsiStopProcessingException() } } lastModified }) val ssiConditional = SsiConditional() commands.put("if", ssiConditional) commands.put("elif", ssiConditional) commands.put("endif", ssiConditional) commands.put("else", ssiConditional) } /** * @return the most current modified date resulting from any SSI commands */ fun process(ssiExternalResolver: SsiExternalResolver, file: Path, writer: ByteBufUtf8Writer): Long { val fileContents = file.readChars() var lastModifiedDate = file.lastModified().toMillis() val ssiProcessingState = SsiProcessingState(ssiExternalResolver, lastModifiedDate) var index = 0 var inside = false val command = StringBuilder() writer.ensureWritable(file.size().toInt()) try { while (index < fileContents.length) { val c = fileContents[index] if (inside) { if (c == COMMAND_END[0] && charCmp(fileContents, index, COMMAND_END)) { inside = false index += COMMAND_END.length val commandName = parseCommand(command) if (LOG.isDebugEnabled) { LOG.debug("SSIProcessor.process -- processing command: $commandName") } val paramNames = parseParamNames(command, commandName.length) val paramValues = parseParamValues(command, commandName.length, paramNames.size) // We need to fetch this value each time, since it may change during the loop val configErrMsg = ssiProcessingState.configErrorMessage val ssiCommand = commands[commandName.toLowerCase(Locale.ENGLISH)] var errorMessage: String? = null if (ssiCommand == null) { errorMessage = "Unknown command: $commandName" } else if (paramValues == null) { errorMessage = "Error parsing directive parameters." } else if (paramNames.size != paramValues.size) { errorMessage = "Parameter names count does not match parameter values count on command: $commandName" } else { // don't process the command if we are processing conditional commands only and the command is not conditional if (!ssiProcessingState.conditionalState.processConditionalCommandsOnly || ssiCommand is SsiConditional) { val newLastModified = ssiCommand.process(ssiProcessingState, commandName, paramNames, paramValues, writer) if (newLastModified > lastModifiedDate) { lastModifiedDate = newLastModified } } } if (errorMessage != null) { LOG.warn(errorMessage) writer.write(configErrMsg) } } else { command.append(c) index++ } } else if (c == COMMAND_START[0] && charCmp(fileContents, index, COMMAND_START)) { inside = true index += COMMAND_START.length command.setLength(0) } else { if (!ssiProcessingState.conditionalState.processConditionalCommandsOnly) { writer.append(c) } index++ } } } catch (e: SsiStopProcessingException) { //If we are here, then we have already stopped processing, so all is good } return lastModifiedDate } protected fun parseParamNames(command: StringBuilder, start: Int): List<String> { var bIdx = start val values = SmartList<String>() var inside = false val builder = StringBuilder() while (bIdx < command.length) { if (inside) { while (bIdx < command.length && command[bIdx] != '=') { builder.append(command[bIdx]) bIdx++ } values.add(builder.toString()) builder.setLength(0) inside = false var quotes = 0 var escaped = false while (bIdx < command.length && quotes != 2) { val c = command[bIdx] // Need to skip escaped characters if (c == '\\' && !escaped) { escaped = true bIdx++ continue } if (c == '"' && !escaped) { quotes++ } escaped = false bIdx++ } } else { while (bIdx < command.length && isSpace(command[bIdx])) { bIdx++ } if (bIdx >= command.length) { break } inside = true } } return values } @SuppressWarnings("AssignmentToForLoopParameter") protected fun parseParamValues(command: StringBuilder, start: Int, count: Int): Array<String>? { var valueIndex = 0 var inside = false val values = arrayOfNulls<String>(count) val builder = StringBuilder() var endQuote: Char = 0.toChar() var bIdx = start while (bIdx < command.length) { if (!inside) { while (bIdx < command.length && !isQuote(command[bIdx])) { bIdx++ } if (bIdx >= command.length) { break } inside = true endQuote = command[bIdx] } else { var escaped = false while (bIdx < command.length) { val c = command[bIdx] // Check for escapes if (c == '\\' && !escaped) { escaped = true bIdx++ continue } // If we reach the other " then stop if (c == endQuote && !escaped) { break } // Since parsing of attributes and var // substitution is done in separate places, // we need to leave escape in the string if (c == '$' && escaped) { builder.append('\\') } escaped = false builder.append(c) bIdx++ } // If we hit the end without seeing a quote // the signal an error if (bIdx == command.length) { return null } values[valueIndex++] = builder.toString() builder.setLength(0) inside = false } bIdx++ } @Suppress("CAST_NEVER_SUCCEEDS", "UNCHECKED_CAST") return values as Array<String> } private fun parseCommand(instruction: StringBuilder): String { var firstLetter = -1 var lastLetter = -1 for (i in 0..instruction.length - 1) { val c = instruction[i] if (Character.isLetter(c)) { if (firstLetter == -1) { firstLetter = i } lastLetter = i } else if (isSpace(c)) { if (lastLetter > -1) { break } } else { break } } return if (firstLetter == -1) "" else instruction.substring(firstLetter, lastLetter + 1) } protected fun charCmp(buf: CharSequence, index: Int, command: String): Boolean = CharArrayUtil.regionMatches(buf, index, index + command.length, command) protected fun isSpace(c: Char): Boolean = c == ' ' || c == '\n' || c == '\t' || c == '\r' protected fun isQuote(c: Char): Boolean = c == '\'' || c == '\"' || c == '`' }
apache-2.0
588642be4d34099efc98b1f153249985
35.338308
158
0.595947
4.547634
false
false
false
false
jk1/intellij-community
platform/diff-impl/src/com/intellij/diff/comparison/TrimUtil.kt
3
19540
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("TrimUtil") @file:Suppress("NAME_SHADOWING") package com.intellij.diff.comparison import com.intellij.diff.util.IntPair import com.intellij.diff.util.MergeRange import com.intellij.diff.util.Range import com.intellij.openapi.util.text.StringUtil.isWhiteSpace import java.util.* fun isPunctuation(c: Char): Boolean { if (c == '_') return false val b = c.toInt() return b >= 33 && b <= 47 || // !"#$%&'()*+,-./ b >= 58 && b <= 64 || // :;<=>?@ b >= 91 && b <= 96 || // [\]^_` b >= 123 && b <= 126 // {|}~ } fun isAlpha(c: Char): Boolean { return !isWhiteSpace(c) && !isPunctuation(c) } fun trim(text: CharSequence, start: Int, end: Int): IntPair { return trim(start, end, { index -> isWhiteSpace(text[index]) }) } fun trim(start: Int, end: Int, ignored: BitSet): IntPair { return trim(start, end, { index -> ignored[index] }) } fun trimStart(text: CharSequence, start: Int, end: Int): Int { return trimStart(start, end, { index -> isWhiteSpace(text[index]) }) } fun trimEnd(text: CharSequence, start: Int, end: Int): Int { return trimEnd(start, end, { index -> isWhiteSpace(text[index]) }) } fun trim(text1: CharSequence, text2: CharSequence, start1: Int, start2: Int, end1: Int, end2: Int): Range { return trim(start1, start2, end1, end2, { index -> isWhiteSpace(text1[index]) }, { index -> isWhiteSpace(text2[index]) }) } fun trim(text1: CharSequence, text2: CharSequence, text3: CharSequence, start1: Int, start2: Int, start3: Int, end1: Int, end2: Int, end3: Int): MergeRange { return trim(start1, start2, start3, end1, end2, end3, { index -> isWhiteSpace(text1[index]) }, { index -> isWhiteSpace(text2[index]) }, { index -> isWhiteSpace(text3[index]) }) } fun expand(text1: List<*>, text2: List<*>, start1: Int, start2: Int, end1: Int, end2: Int): Range { return expand(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }) } fun expandForward(text1: List<*>, text2: List<*>, start1: Int, start2: Int, end1: Int, end2: Int): Int { return expandForward(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }) } fun expandBackward(text1: List<*>, text2: List<*>, start1: Int, start2: Int, end1: Int, end2: Int): Int { return expandBackward(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }) } fun <T> expand(text1: List<T>, text2: List<T>, start1: Int, start2: Int, end1: Int, end2: Int, equals: (T, T) -> Boolean): Range { return expand(start1, start2, end1, end2, { index1, index2 -> equals(text1[index1], text2[index2]) }) } fun expand(text1: CharSequence, text2: CharSequence, start1: Int, start2: Int, end1: Int, end2: Int): Range { return expand(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }) } fun expandForward(text1: CharSequence, text2: CharSequence, start1: Int, start2: Int, end1: Int, end2: Int): Int { return expandForward(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }) } fun expandBackward(text1: CharSequence, text2: CharSequence, start1: Int, start2: Int, end1: Int, end2: Int): Int { return expandBackward(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }) } fun expandWhitespaces(text1: CharSequence, text2: CharSequence, start1: Int, start2: Int, end1: Int, end2: Int): Range { return expandIgnored(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }, { index -> isWhiteSpace(text1[index]) }) } fun expandWhitespacesForward(text1: CharSequence, text2: CharSequence, start1: Int, start2: Int, end1: Int, end2: Int): Int { return expandIgnoredForward(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }, { index -> isWhiteSpace(text1[index]) }) } fun expandWhitespacesBackward(text1: CharSequence, text2: CharSequence, start1: Int, start2: Int, end1: Int, end2: Int): Int { return expandIgnoredBackward(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }, { index -> isWhiteSpace(text1[index]) }) } fun expandWhitespaces(text1: CharSequence, text2: CharSequence, text3: CharSequence, start1: Int, start2: Int, start3: Int, end1: Int, end2: Int, end3: Int): MergeRange { return expandIgnored(start1, start2, start3, end1, end2, end3, { index1, index2 -> text1[index1] == text2[index2] }, { index1, index3 -> text1[index1] == text3[index3] }, { index -> isWhiteSpace(text1[index]) }) } fun expandWhitespacesForward(text1: CharSequence, text2: CharSequence, text3: CharSequence, start1: Int, start2: Int, start3: Int, end1: Int, end2: Int, end3: Int): Int { return expandIgnoredForward(start1, start2, start3, end1, end2, end3, { index1, index2 -> text1[index1] == text2[index2] }, { index1, index3 -> text1[index1] == text3[index3] }, { index -> isWhiteSpace(text1[index]) }) } fun expandWhitespacesBackward(text1: CharSequence, text2: CharSequence, text3: CharSequence, start1: Int, start2: Int, start3: Int, end1: Int, end2: Int, end3: Int): Int { return expandIgnoredBackward(start1, start2, start3, end1, end2, end3, { index1, index2 -> text1[index1] == text2[index2] }, { index1, index3 -> text1[index1] == text3[index3] }, { index -> isWhiteSpace(text1[index]) }) } fun <T> trimExpandRange(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean, ignored2: (Int) -> Boolean): Range { return trimExpand(start1, start2, end1, end2, { index1, index2 -> equals(index1, index2) }, { index -> ignored1(index) }, { index -> ignored2(index) }) } fun trimExpandText(text1: CharSequence, text2: CharSequence, start1: Int, start2: Int, end1: Int, end2: Int, ignored1: BitSet, ignored2: BitSet): Range { return trimExpand(start1, start2, end1, end2, { index1, index2 -> text1[index1] == text2[index2] }, { index -> ignored1[index] }, { index -> ignored2[index] }) } fun trim(text1: CharSequence, text2: CharSequence, range: Range): Range { return trim(text1, text2, range.start1, range.start2, range.end1, range.end2) } fun trim(text1: CharSequence, text2: CharSequence, text3: CharSequence, range: MergeRange): MergeRange { return trim(text1, text2, text3, range.start1, range.start2, range.start3, range.end1, range.end2, range.end3) } fun expand(text1: CharSequence, text2: CharSequence, range: Range): Range { return expand(text1, text2, range.start1, range.start2, range.end1, range.end2) } fun expandWhitespaces(text1: CharSequence, text2: CharSequence, range: Range): Range { return expandWhitespaces(text1, text2, range.start1, range.start2, range.end1, range.end2) } fun expandWhitespaces(text1: CharSequence, text2: CharSequence, text3: CharSequence, range: MergeRange): MergeRange { return expandWhitespaces(text1, text2, text3, range.start1, range.start2, range.start3, range.end1, range.end2, range.end3) } fun isEquals(text1: CharSequence, text2: CharSequence, range: Range): Boolean { val sequence1 = text1.subSequence(range.start1, range.end1) val sequence2 = text2.subSequence(range.start2, range.end2) return ComparisonUtil.isEquals(sequence1, sequence2, ComparisonPolicy.DEFAULT) } fun isEqualsIgnoreWhitespaces(text1: CharSequence, text2: CharSequence, range: Range): Boolean { val sequence1 = text1.subSequence(range.start1, range.end1) val sequence2 = text2.subSequence(range.start2, range.end2) return ComparisonUtil.isEquals(sequence1, sequence2, ComparisonPolicy.IGNORE_WHITESPACES) } fun isEquals(text1: CharSequence, text2: CharSequence, text3: CharSequence, range: MergeRange): Boolean { val sequence1 = text1.subSequence(range.start1, range.end1) val sequence2 = text2.subSequence(range.start2, range.end2) val sequence3 = text3.subSequence(range.start3, range.end3) return ComparisonUtil.isEquals(sequence2, sequence1, ComparisonPolicy.DEFAULT) && ComparisonUtil.isEquals(sequence2, sequence3, ComparisonPolicy.DEFAULT) } fun isEqualsIgnoreWhitespaces(text1: CharSequence, text2: CharSequence, text3: CharSequence, range: MergeRange): Boolean { val sequence1 = text1.subSequence(range.start1, range.end1) val sequence2 = text2.subSequence(range.start2, range.end2) val sequence3 = text3.subSequence(range.start3, range.end3) return ComparisonUtil.isEquals(sequence2, sequence1, ComparisonPolicy.IGNORE_WHITESPACES) && ComparisonUtil.isEquals(sequence2, sequence3, ComparisonPolicy.IGNORE_WHITESPACES) } // // Trim // private inline fun trim(start1: Int, start2: Int, end1: Int, end2: Int, ignored1: (Int) -> Boolean, ignored2: (Int) -> Boolean): Range { var start1 = start1 var start2 = start2 var end1 = end1 var end2 = end2 start1 = trimStart(start1, end1, ignored1) end1 = trimEnd(start1, end1, ignored1) start2 = trimStart(start2, end2, ignored2) end2 = trimEnd(start2, end2, ignored2) return Range(start1, end1, start2, end2) } private inline fun trim(start1: Int, start2: Int, start3: Int, end1: Int, end2: Int, end3: Int, ignored1: (Int) -> Boolean, ignored2: (Int) -> Boolean, ignored3: (Int) -> Boolean): MergeRange { var start1 = start1 var start2 = start2 var start3 = start3 var end1 = end1 var end2 = end2 var end3 = end3 start1 = trimStart(start1, end1, ignored1) end1 = trimEnd(start1, end1, ignored1) start2 = trimStart(start2, end2, ignored2) end2 = trimEnd(start2, end2, ignored2) start3 = trimStart(start3, end3, ignored3) end3 = trimEnd(start3, end3, ignored3) return MergeRange(start1, end1, start2, end2, start3, end3) } private inline fun trim(start: Int, end: Int, ignored: (Int) -> Boolean): IntPair { var start = start var end = end start = trimStart(start, end, ignored) end = trimEnd(start, end, ignored) return IntPair(start, end) } private inline fun trimStart(start: Int, end: Int, ignored: (Int) -> Boolean): Int { var start = start while (start < end) { if (!ignored(start)) break start++ } return start } private inline fun trimEnd(start: Int, end: Int, ignored: (Int) -> Boolean): Int { var end = end while (start < end) { if (!ignored(end - 1)) break end-- } return end } // // Expand // private inline fun expand(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean): Range { var start1 = start1 var start2 = start2 var end1 = end1 var end2 = end2 val count1 = expandForward(start1, start2, end1, end2, equals) start1 += count1 start2 += count1 val count2 = expandBackward(start1, start2, end1, end2, equals) end1 -= count2 end2 -= count2 return Range(start1, end1, start2, end2) } private inline fun expandForward(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean): Int { var start1 = start1 var start2 = start2 val oldStart1 = start1 while (start1 < end1 && start2 < end2) { if (!equals(start1, start2)) break start1++ start2++ } return start1 - oldStart1 } private inline fun expandBackward(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean): Int { var end1 = end1 var end2 = end2 val oldEnd1 = end1 while (start1 < end1 && start2 < end2) { if (!equals(end1 - 1, end2 - 1)) break end1-- end2-- } return oldEnd1 - end1 } // // Expand Ignored // private inline fun expandIgnored(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean): Range { var start1 = start1 var start2 = start2 var end1 = end1 var end2 = end2 val count1 = expandIgnoredForward(start1, start2, end1, end2, equals, ignored1) start1 += count1 start2 += count1 val count2 = expandIgnoredBackward(start1, start2, end1, end2, equals, ignored1) end1 -= count2 end2 -= count2 return Range(start1, end1, start2, end2) } private inline fun expandIgnoredForward(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean): Int { var start1 = start1 var start2 = start2 val oldStart1 = start1 while (start1 < end1 && start2 < end2) { if (!equals(start1, start2)) break if (!ignored1(start1)) break start1++ start2++ } return start1 - oldStart1 } private inline fun expandIgnoredBackward(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean): Int { var end1 = end1 var end2 = end2 val oldEnd1 = end1 while (start1 < end1 && start2 < end2) { if (!equals(end1 - 1, end2 - 1)) break if (!ignored1(end1 - 1)) break end1-- end2-- } return oldEnd1 - end1 } private inline fun expandIgnored(start1: Int, start2: Int, start3: Int, end1: Int, end2: Int, end3: Int, equals12: (Int, Int) -> Boolean, equals13: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean): MergeRange { var start1 = start1 var start2 = start2 var start3 = start3 var end1 = end1 var end2 = end2 var end3 = end3 val count1 = expandIgnoredForward(start1, start2, start3, end1, end2, end3, equals12, equals13, ignored1) start1 += count1 start2 += count1 start3 += count1 val count2 = expandIgnoredBackward(start1, start2, start3, end1, end2, end3, equals12, equals13, ignored1) end1 -= count2 end2 -= count2 end3 -= count2 return MergeRange(start1, end1, start2, end2, start3, end3) } private inline fun expandIgnoredForward(start1: Int, start2: Int, start3: Int, end1: Int, end2: Int, end3: Int, equals12: (Int, Int) -> Boolean, equals13: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean): Int { var start1 = start1 var start2 = start2 var start3 = start3 val oldStart1 = start1 while (start1 < end1 && start2 < end2 && start3 < end3) { if (!equals12(start1, start2)) break if (!equals13(start1, start3)) break if (!ignored1(start1)) break start1++ start2++ start3++ } return start1 - oldStart1 } private inline fun expandIgnoredBackward(start1: Int, start2: Int, start3: Int, end1: Int, end2: Int, end3: Int, equals12: (Int, Int) -> Boolean, equals13: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean): Int { var end1 = end1 var end2 = end2 var end3 = end3 val oldEnd1 = end1 while (start1 < end1 && start2 < end2 && start3 < end3) { if (!equals12(end1 - 1, end2 - 1)) break if (!equals13(end1 - 1, end3 - 1)) break if (!ignored1(end1 - 1)) break end1-- end2-- end3-- } return oldEnd1 - end1 } // // Trim Expand // private inline fun trimExpand(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean, ignored2: (Int) -> Boolean): Range { var start1 = start1 var start2 = start2 var end1 = end1 var end2 = end2 val starts = trimExpandForward(start1, start2, end1, end2, equals, ignored1, ignored2) start1 = starts.val1 start2 = starts.val2 val ends = trimExpandBackward(start1, start2, end1, end2, equals, ignored1, ignored2) end1 = ends.val1 end2 = ends.val2 return Range(start1, end1, start2, end2) } private inline fun trimExpandForward(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean, ignored2: (Int) -> Boolean): IntPair { var start1 = start1 var start2 = start2 while (start1 < end1 && start2 < end2) { if (equals(start1, start2)) { start1++ start2++ continue } var skipped = false if (ignored1(start1)) { skipped = true start1++ } if (ignored2(start2)) { skipped = true start2++ } if (!skipped) break } start1 = trimStart(start1, end1, ignored1) start2 = trimStart(start2, end2, ignored2) return IntPair(start1, start2) } private inline fun trimExpandBackward(start1: Int, start2: Int, end1: Int, end2: Int, equals: (Int, Int) -> Boolean, ignored1: (Int) -> Boolean, ignored2: (Int) -> Boolean): IntPair { var end1 = end1 var end2 = end2 while (start1 < end1 && start2 < end2) { if (equals(end1 - 1, end2 - 1)) { end1-- end2-- continue } var skipped = false if (ignored1(end1 - 1)) { skipped = true end1-- } if (ignored2(end2 - 1)) { skipped = true end2-- } if (!skipped) break } end1 = trimEnd(start1, end1, ignored1) end2 = trimEnd(start2, end2, ignored2) return IntPair(end1, end2) }
apache-2.0
2f90fb669341af081861bb0cc1f9105e
32.287905
125
0.590839
3.457795
false
false
false
false
robnixon/ComputingTutorAndroidApp
app/src/main/java/net/computingtutor/robert/computingtutor/BaseConverterUI.kt
1
815
package net.computingtutor.robert.computingtutor import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.TextView class BaseConverterUI : BaseActivity() { var showingHelp: Boolean = false lateinit var helpTextView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_base_converter_ui) helpTextView = findViewById(R.id.baseConverterHelpTextView) as TextView } fun showBaseConverterHelp(view: View) { if (showingHelp) { helpTextView.visibility = View.GONE showingHelp = false } else { helpTextView.visibility = View.VISIBLE showingHelp = true } } }
mit
ca90754a4589a36127122daf0b37aa1e
28.107143
79
0.695706
4.527778
false
false
false
false
jaycarey/ethtrader-ticker
src/main/java/org/ethtrader/ticker/Reddit.kt
1
961
package org.ethtrader.ticker import org.jsoup.Jsoup import java.io.InputStream class Reddit(private val client: OAuthClient, val subRedditName: String) { fun uploadImage(name: String, ticker: InputStream) { val response = client.postRSubredditUpload_sr_img(subRedditName, "file" to ticker, "name" to name, "upload_type" to "img") println("Response: " + response) } fun uploadStylesheet(css: String) { val response = client.postRSubredditSubreddit_stylesheet(subRedditName, "stylesheet_contents" to css, "op" to "save") println("Response: " + response) } fun getStylesheet(): String = retry(3) { val cssPage = client.requestPlain("/r/$subRedditName/about/stylesheet/").get(String::class.java) val document = Jsoup.parse(cssPage) document.select("pre.subreddit-stylesheet-source > code").text() } }
apache-2.0
76102d7be49794ba3dfbdef385fdb8ba
33.357143
104
0.633715
4.124464
false
false
false
false
drakelord/wire
wire-kotlin-generator/src/test/java/com/squareup/wire/kotlin/KotlinGeneratorTest.kt
1
12828
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.kotlin import com.squareup.kotlinpoet.FileSpec import com.squareup.wire.schema.IdentifierSet import com.squareup.wire.schema.RepoBuilder import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue class KotlinGeneratorTest { @Test fun basic() { val repoBuilder = RepoBuilder() .add("message.proto", """ |message Person { | required string name = 1; | required int32 id = 2; | optional string email = 3; | enum PhoneType { | HOME = 0; | WORK = 1; | MOBILE = 2; | } | message PhoneNumber { | required string number = 1; | optional PhoneType type = 2 [default = HOME]; | } | repeated PhoneNumber phone = 4; |}""".trimMargin()) val code = repoBuilder.generateKotlin("Person") assertTrue(code.contains("data class Person")) assertTrue(code.contains("object : ProtoAdapter<PhoneNumber>(\n")) assertTrue(code.contains("FieldEncoding.LENGTH_DELIMITED")) assertTrue(code.contains("PhoneNumber::class.java")) assertTrue(code.contains("override fun encode(writer: ProtoWriter, value: Person)")) assertTrue(code.contains("enum class PhoneType(private val value: Int) : WireEnum")) assertTrue(code.contains("WORK(1),")) } @Test fun defaultValues() { val repoBuilder = RepoBuilder() .add("message.proto", """ |message Message { | optional int32 a = 1 [default = 10 ]; | optional int32 b = 2 [default = 0x20 ]; | optional int64 c = 3 [default = 11 ]; | optional int64 d = 4 [default = 0x21 ]; |}""".trimMargin()) val code = repoBuilder.generateKotlin("Message") assertTrue(code.contains("val a: Int? = 10")) assertTrue(code.contains("val b: Int? = 0x20")) assertTrue(code.contains("val c: Long? = 11")) assertTrue(code.contains("val d: Long? = 0x21")) } @Test fun nameAllocatorIsUsed() { val repoBuilder = RepoBuilder() .add("message.proto", """ |message Message { | required float when = 1; | required int32 ADAPTER = 2; |}""".trimMargin()) val code = repoBuilder.generateKotlin("Message") assertTrue(code.contains("val when_: Float")) assertTrue(code.contains("val ADAPTER_: Int")) assertTrue(code.contains("ProtoAdapter.FLOAT.encodedSizeWithTag(1, value.when_) +")) assertTrue(code.contains("ProtoAdapter.FLOAT.encodeWithTag(writer, 1, value.when_)")) assertTrue(code.contains("ProtoAdapter.FLOAT.encodeWithTag(writer, 1, value.when_)")) assertTrue(code.contains("1 -> when_ = ProtoAdapter.FLOAT.decode(reader)")) } @Test fun enclosing() { val schema = RepoBuilder() .add("message.proto", """ |message A { | message B { | } | optional B b = 1; |}""".trimMargin()) .schema() val pruned = schema.prune(IdentifierSet.Builder().include("A.B").build()) val kotlinGenerator = KotlinGenerator.invoke(pruned) val typeSpec = kotlinGenerator.generateType(pruned.getType("A")) val code = FileSpec.get("", typeSpec).toString() assertTrue(code.contains("object A {")) assertTrue(code.contains("data class B(.*) : Message<B, B.Builder>".toRegex())) } @Test fun requestResponse() { val expected = """ |package routeguide | |import com.squareup.wire.Service |import com.squareup.wire.WireRpc | |interface RouteGuide : Service { | @WireRpc( | path = "/routeguide.RouteGuide/GetFeature", | requestAdapter = "routeguide.Point#ADAPTER", | responseAdapter = "routeguide.Feature#ADAPTER" | ) | suspend fun GetFeature(request: Point): Feature |} |""".trimMargin() val repoBuilder = RepoBuilder() .add("routeguide.proto", """ |package routeguide; | |service RouteGuide { | rpc GetFeature(Point) returns (Feature) {} |} |$pointMessage |$featureMessage |""".trimMargin()) assertEquals(expected, repoBuilder.generateGrpcKotlin("routeguide.RouteGuide")) } @Test fun noPackage() { val expected = """ |import com.squareup.wire.Service |import com.squareup.wire.WireRpc | |interface RouteGuide : Service { | @WireRpc( | path = "/RouteGuide/GetFeature", | requestAdapter = "Point#ADAPTER", | responseAdapter = "Feature#ADAPTER" | ) | suspend fun GetFeature(request: Point): Feature |} |""".trimMargin() val repoBuilder = RepoBuilder() .add("routeguide.proto", """ |service RouteGuide { | rpc GetFeature(Point) returns (Feature) {} |} |$pointMessage |$featureMessage |""".trimMargin()) assertEquals(expected, repoBuilder.generateGrpcKotlin("RouteGuide")) } @Test fun multiDepthPackage() { val expected = """ |package routeguide.grpc | |import com.squareup.wire.Service |import com.squareup.wire.WireRpc | |interface RouteGuide : Service { | @WireRpc( | path = "/routeguide.grpc.RouteGuide/GetFeature", | requestAdapter = "routeguide.grpc.Point#ADAPTER", | responseAdapter = "routeguide.grpc.Feature#ADAPTER" | ) | suspend fun GetFeature(request: Point): Feature |} |""".trimMargin() val repoBuilder = RepoBuilder() .add("routeguide.proto", """ |package routeguide.grpc; | |service RouteGuide { | rpc GetFeature(Point) returns (Feature) {} |} |$pointMessage |$featureMessage |""".trimMargin()) assertEquals(expected, repoBuilder.generateGrpcKotlin("routeguide.grpc.RouteGuide")) } @Test fun streamingRequest() { val expected = """ |package routeguide | |import com.squareup.wire.Service |import com.squareup.wire.WireRpc |import kotlin.Pair |import kotlinx.coroutines.Deferred |import kotlinx.coroutines.channels.SendChannel | |interface RouteGuide : Service { | @WireRpc( | path = "/routeguide.RouteGuide/RecordRoute", | requestAdapter = "routeguide.Point#ADAPTER", | responseAdapter = "routeguide.RouteSummary#ADAPTER" | ) | suspend fun RecordRoute(): Pair<SendChannel<Point>, Deferred<RouteSummary>> |} |""".trimMargin() val repoBuilder = RepoBuilder() .add("routeguide.proto", """ |package routeguide; | |service RouteGuide { | rpc RecordRoute(stream Point) returns (RouteSummary) {} |} |$pointMessage |$routeSummaryMessage |""".trimMargin()) assertEquals(expected, repoBuilder.generateGrpcKotlin("routeguide.RouteGuide")) } @Test fun streamingResponse() { val expected = """ |package routeguide | |import com.squareup.wire.Service |import com.squareup.wire.WireRpc |import kotlinx.coroutines.channels.ReceiveChannel | |interface RouteGuide : Service { | @WireRpc( | path = "/routeguide.RouteGuide/ListFeatures", | requestAdapter = "routeguide.Rectangle#ADAPTER", | responseAdapter = "routeguide.Feature#ADAPTER" | ) | suspend fun ListFeatures(request: Rectangle): ReceiveChannel<Feature> |} |""".trimMargin() val repoBuilder = RepoBuilder() .add("routeguide.proto", """ |package routeguide; | |service RouteGuide { | rpc ListFeatures(Rectangle) returns (stream Feature) {} |} |$rectangeMessage |$pointMessage |$featureMessage |""".trimMargin()) assertEquals(expected, repoBuilder.generateGrpcKotlin("routeguide.RouteGuide")) } @Test fun bidirectional() { val expected = """ |package routeguide | |import com.squareup.wire.Service |import com.squareup.wire.WireRpc |import kotlin.Pair |import kotlinx.coroutines.channels.ReceiveChannel |import kotlinx.coroutines.channels.SendChannel | |interface RouteGuide : Service { | @WireRpc( | path = "/routeguide.RouteGuide/RouteChat", | requestAdapter = "routeguide.RouteNote#ADAPTER", | responseAdapter = "routeguide.RouteNote#ADAPTER" | ) | suspend fun RouteChat(): Pair<SendChannel<RouteNote>, ReceiveChannel<RouteNote>> |} |""".trimMargin() val repoBuilder = RepoBuilder() .add("routeguide.proto", """ |package routeguide; | |service RouteGuide { | rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} |} |$pointMessage |$routeNoteMessage |""".trimMargin()) assertEquals(expected, repoBuilder.generateGrpcKotlin("routeguide.RouteGuide")) } @Test fun multipleRpcs() { val expected = """ |package routeguide | |import com.squareup.wire.Service |import com.squareup.wire.WireRpc |import kotlin.Pair |import kotlinx.coroutines.channels.ReceiveChannel |import kotlinx.coroutines.channels.SendChannel | |interface RouteGuide : Service { | @WireRpc( | path = "/routeguide.RouteGuide/GetFeature", | requestAdapter = "routeguide.Point#ADAPTER", | responseAdapter = "routeguide.Feature#ADAPTER" | ) | suspend fun GetFeature(request: Point): Feature | | @WireRpc( | path = "/routeguide.RouteGuide/RouteChat", | requestAdapter = "routeguide.RouteNote#ADAPTER", | responseAdapter = "routeguide.RouteNote#ADAPTER" | ) | suspend fun RouteChat(): Pair<SendChannel<RouteNote>, ReceiveChannel<RouteNote>> |} |""".trimMargin() val repoBuilder = RepoBuilder() .add("routeguide.proto", """ |package routeguide; | |service RouteGuide { | rpc GetFeature(Point) returns (Feature) {} | rpc RouteChat(stream RouteNote) returns (stream RouteNote) {} |} |$pointMessage |$featureMessage |$routeNoteMessage |""".trimMargin()) assertEquals(expected, repoBuilder.generateGrpcKotlin("routeguide.RouteGuide")) } companion object { private val pointMessage = """ |message Point { | optional int32 latitude = 1; | optional int32 longitude = 2; |}""".trimMargin() private val rectangeMessage = """ |message Rectangle { | optional Point lo = 1; | optional Point hi = 2; |}""".trimMargin() private val featureMessage = """ |message Feature { | optional string name = 1; | optional Point location = 2; |}""".trimMargin() private val routeNoteMessage = """ |message RouteNote { | optional Point location = 1; | optional string message = 2; |}""".trimMargin() private val routeSummaryMessage = """ |message RouteSummary { | optional int32 point_count = 1; | optional int32 feature_count = 2; | optional int32 distance = 3; | optional int32 elapsed_time = 4; |}""".trimMargin() } }
apache-2.0
2f0e33075dd4722ea49bb9ddb2b3b7ed
34.241758
95
0.570237
4.599498
false
false
false
false
dahlstrom-g/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUVariable.kt
4
10440
// 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.uast.java import com.intellij.psi.* import com.intellij.psi.impl.light.LightRecordCanonicalConstructor.LightRecordConstructorParameter import com.intellij.psi.impl.light.LightRecordField import com.intellij.psi.impl.source.PsiParameterImpl import com.intellij.psi.impl.source.tree.java.PsiLocalVariableImpl import com.intellij.psi.util.PsiTypesUtil import com.intellij.psi.util.parentOfType import com.intellij.util.castSafelyTo import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* import org.jetbrains.uast.internal.UElementAlternative import org.jetbrains.uast.internal.accommodate import org.jetbrains.uast.internal.alternative import org.jetbrains.uast.java.internal.JavaUElementWithComments @ApiStatus.Internal abstract class AbstractJavaUVariable( givenParent: UElement? ) : JavaAbstractUElement(givenParent), PsiVariable, UVariableEx, JavaUElementWithComments, UAnchorOwner { abstract override val javaPsi: PsiVariable @Suppress("OverridingDeprecatedMember") override val psi get() = javaPsi override val uastInitializer: UExpression? by lz { val initializer = javaPsi.initializer ?: return@lz null UastFacade.findPlugin(initializer)?.convertElement(initializer, this) as? UExpression } override val uAnnotations: List<UAnnotation> by lz { javaPsi.annotations.map { JavaUAnnotation(it, this) } } override val typeReference: UTypeReferenceExpression? by lz { javaPsi.typeElement?.let { UastFacade.findPlugin(it)?.convertOpt<UTypeReferenceExpression>(javaPsi.typeElement, this) } } abstract override val sourcePsi: PsiVariable? override val uastAnchor: UIdentifier? get() = sourcePsi?.let { UIdentifier(it.nameIdentifier, this) } override fun equals(other: Any?): Boolean = other is AbstractJavaUVariable && javaPsi == other.javaPsi override fun hashCode(): Int = javaPsi.hashCode() } @ApiStatus.Internal class JavaUVariable( override val javaPsi: PsiVariable, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UVariableEx, PsiVariable by javaPsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiVariable get() = javaPsi override val sourcePsi: PsiVariable? get() = javaPsi.takeIf { it.isPhysical || it is PsiLocalVariableImpl} companion object { fun create(psi: PsiVariable, containingElement: UElement?): UVariable { return when (psi) { is PsiEnumConstant -> JavaUEnumConstant(psi, containingElement) is PsiLocalVariable -> JavaULocalVariable(psi, containingElement) is PsiParameter -> JavaUParameter(psi, containingElement) is PsiField -> JavaUField(psi, containingElement) else -> JavaUVariable(psi, containingElement) } } } override fun getOriginalElement(): PsiElement? = javaPsi.originalElement } @ApiStatus.Internal class JavaUParameter( override val javaPsi: PsiParameter, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UParameterEx, PsiParameter by javaPsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiParameter get() = javaPsi override val sourcePsi: PsiParameter? get() = javaPsi.takeIf { it.isPhysical || (it is PsiParameterImpl && it.parentOfType<PsiMethod>()?.let { canBeSourcePsi(it) } == true) } override fun getOriginalElement(): PsiElement? = javaPsi.originalElement } private class JavaRecordUParameter( override val sourcePsi: PsiRecordComponent, override val javaPsi: PsiParameter, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UParameterEx, PsiParameter by javaPsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiParameter get() = javaPsi override val uastAnchor: UIdentifier get() = UIdentifier(sourcePsi.nameIdentifier, this) override fun getPsiParentForLazyConversion(): PsiElement? = javaPsi.context } internal fun convertRecordConstructorParameterAlternatives(element: PsiElement, givenParent: UElement?, expectedTypes: Array<out Class<out UElement>>): Sequence<UVariable> { val (paramAlternative, fieldAlternative) = createAlternatives(element, givenParent)?:return emptySequence() return when (element) { is LightRecordField -> expectedTypes.accommodate(fieldAlternative, paramAlternative) else -> expectedTypes.accommodate(paramAlternative, fieldAlternative) } } internal fun convertRecordConstructorParameterAlternatives(element: PsiElement, givenParent: UElement?, expectedType: Class<out UElement>): UVariable? { val (paramAlternative, fieldAlternative) = createAlternatives(element, givenParent)?:return null return when (element) { is LightRecordField -> expectedType.accommodate(fieldAlternative, paramAlternative) else -> expectedType.accommodate(paramAlternative, fieldAlternative) } } private fun createAlternatives(element: PsiElement, givenParent: UElement?): Pair<UElementAlternative<JavaRecordUParameter>, UElementAlternative<JavaRecordUField>>? { val (psiRecordComponent, lightRecordField, lightConstructorParameter) = when (element) { is PsiRecordComponent -> Triple(element, null, null) is LightRecordConstructorParameter -> { val lightRecordField = element.parentOfType<PsiMethod>()?.containingClass?.findFieldByName(element.name, false) ?.castSafelyTo<LightRecordField>() ?: return null Triple(lightRecordField.recordComponent, lightRecordField, element) } is LightRecordField -> Triple(element.recordComponent, element, null) else -> return null } val paramAlternative = alternative { val psiClass = psiRecordComponent.containingClass ?: return@alternative null val jvmParameter = lightConstructorParameter ?: psiClass.constructors.asSequence() .filter { !it.isPhysical } .flatMap { it.parameterList.parameters.asSequence() }.firstOrNull { it.name == psiRecordComponent.name } JavaRecordUParameter(psiRecordComponent, jvmParameter ?: return@alternative null, givenParent) } val fieldAlternative = alternative { val psiField = lightRecordField ?: psiRecordComponent.containingClass?.findFieldByName(psiRecordComponent.name, false) ?: return@alternative null JavaRecordUField(psiRecordComponent, psiField, givenParent) } return Pair(paramAlternative, fieldAlternative) } @ApiStatus.Internal class JavaUField( override val sourcePsi: PsiField, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UFieldEx, PsiField by sourcePsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiField get() = javaPsi override val javaPsi: PsiField = unwrap<UField, PsiField>(sourcePsi) override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement } private class JavaRecordUField( private val psiRecord: PsiRecordComponent, override val javaPsi: PsiField, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UFieldEx, PsiField by javaPsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiField get() = javaPsi override val sourcePsi: PsiVariable? get() = null override val uastAnchor: UIdentifier get() = UIdentifier(psiRecord.nameIdentifier, this) override fun getPsiParentForLazyConversion(): PsiElement? = javaPsi.context } @ApiStatus.Internal class JavaULocalVariable( override val sourcePsi: PsiLocalVariable, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), ULocalVariableEx, PsiLocalVariable by sourcePsi { @Suppress("OverridingDeprecatedMember") override val psi: PsiLocalVariable get() = javaPsi override val javaPsi: PsiLocalVariable = unwrap<ULocalVariable, PsiLocalVariable>(sourcePsi) override fun getPsiParentForLazyConversion(): PsiElement? = super.getPsiParentForLazyConversion()?.let { when (it) { is PsiResourceList -> it.parent else -> it } } override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement } @ApiStatus.Internal class JavaUEnumConstant( override val sourcePsi: PsiEnumConstant, givenParent: UElement? ) : AbstractJavaUVariable(givenParent), UEnumConstantEx, UCallExpression, PsiEnumConstant by sourcePsi, UMultiResolvable { override val initializingClass: UClass? by lz { UastFacade.findPlugin(sourcePsi)?.convertOpt(sourcePsi.initializingClass, this) } @Suppress("OverridingDeprecatedMember") override val psi: PsiEnumConstant get() = javaPsi override val javaPsi: PsiEnumConstant get() = sourcePsi override val kind: UastCallKind get() = UastCallKind.CONSTRUCTOR_CALL override val receiver: UExpression? get() = null override val receiverType: PsiType? get() = null override val methodIdentifier: UIdentifier? get() = null override val classReference: UReferenceExpression get() = JavaEnumConstantClassReference(sourcePsi, this) override val typeArgumentCount: Int get() = 0 override val typeArguments: List<PsiType> get() = emptyList() override val valueArgumentCount: Int get() = sourcePsi.argumentList?.expressions?.size ?: 0 override val valueArguments: List<UExpression> by lz { sourcePsi.argumentList?.expressions?.map { UastFacade.findPlugin(it)?.convertElement(it, this) as? UExpression ?: UastEmptyExpression(this) } ?: emptyList() } override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i) override val returnType: PsiType get() = sourcePsi.type override fun resolve(): PsiMethod? = sourcePsi.resolveMethod() override fun multiResolve(): Iterable<ResolveResult> = listOfNotNull(sourcePsi.resolveMethodGenerics()) override val methodName: String? get() = null private class JavaEnumConstantClassReference( override val sourcePsi: PsiEnumConstant, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), USimpleNameReferenceExpression, UMultiResolvable { override fun resolve() = sourcePsi.containingClass override fun multiResolve(): Iterable<ResolveResult> = listOfNotNull(resolve()?.let { PsiTypesUtil.getClassType(it).resolveGenerics() }) override val resolvedName: String? get() = sourcePsi.containingClass?.name override val identifier: String get() = sourcePsi.containingClass?.name ?: "<error>" } override fun getOriginalElement(): PsiElement? = sourcePsi.originalElement }
apache-2.0
e4fcf48645bd659f8e4fd7f62ff76738
37.523985
173
0.769157
5.077821
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/grazie/src/org/jetbrains/kotlin/idea/grazie/KotlinTextExtractor.kt
5
2997
// 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.grazie import com.intellij.grazie.text.TextContent import com.intellij.grazie.text.TextContent.TextDomain.* import com.intellij.grazie.text.TextContentBuilder import com.intellij.grazie.text.TextExtractor import com.intellij.grazie.utils.Text import com.intellij.grazie.utils.getNotSoDistantSimilarSiblings import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.tree.PsiCommentImpl import com.intellij.psi.util.elementType import org.jetbrains.kotlin.kdoc.lexer.KDocTokens import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtStringTemplateEntryWithExpression import org.jetbrains.kotlin.psi.KtStringTemplateExpression import java.util.regex.Pattern internal class KotlinTextExtractor : TextExtractor() { private val kdocBuilder = TextContentBuilder.FromPsi .withUnknown { e -> e.elementType == KDocTokens.MARKDOWN_LINK && e.text.startsWith("[") } .excluding { e -> e.elementType == KDocTokens.MARKDOWN_LINK && !e.text.startsWith("[") } .excluding { e -> e.elementType == KDocTokens.LEADING_ASTERISK } .removingIndents(" \t").removingLineSuffixes(" \t") public override fun buildTextContent(root: PsiElement, allowedDomains: Set<TextContent.TextDomain>): TextContent? { if (DOCUMENTATION in allowedDomains) { if (root is KDocSection) { return kdocBuilder.excluding { e -> e is KDocTag && e != root }.build(root, DOCUMENTATION)?.removeCode() } if (root is KDocTag) { return kdocBuilder.excluding { e -> e.elementType == KDocTokens.TAG_NAME }.build(root, DOCUMENTATION)?.removeCode() } } if (COMMENTS in allowedDomains && root is PsiCommentImpl) { val roots = getNotSoDistantSimilarSiblings(root) { it == root || root.elementType == KtTokens.EOL_COMMENT && it.elementType == KtTokens.EOL_COMMENT } return TextContent.joinWithWhitespace('\n', roots.mapNotNull { TextContentBuilder.FromPsi.removingIndents(" \t*/").removingLineSuffixes(" \t").build(it, COMMENTS) }) } if (LITERALS in allowedDomains && root is KtStringTemplateExpression) { // For multiline strings, we want to treat `'|'` as an indentation because it is commonly used with [String.trimMargin]. return TextContentBuilder.FromPsi .withUnknown { it is KtStringTemplateEntryWithExpression } .removingIndents(" \t|").removingLineSuffixes(" \t") .build(root, LITERALS) } return null } private val codeFragments = Pattern.compile("(?s)```.+?```|`.+?`") private fun TextContent.removeCode(): TextContent? = excludeRanges(Text.allOccurrences(codeFragments, this).map { TextContent.Exclusion.markUnknown(it) }) }
apache-2.0
7ee87b46f76e7a36fec9694df52d3a7f
49.813559
158
0.734735
4.156727
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/parameterInfo/functionCall/NamedAndDefaultParameter.kt
3
685
// IGNORE_FIR open class A(x: Int) { fun m(x: Int) = 1 fun m(x: Int, y: Boolean = true, z: Long = 12345678901234, u: String = "abc\n", u0: String = "" + "123", uu: String = "$u", v: Char = '\u0000', vv: String = "asdfsdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf") = 2 fun d(x: Int) { m(<caret>y = false, x = 1) } } /* Text: (<highlight>[y: Boolean = true]</highlight>, [x: Int], [z: Long = 12345678901234], [u: String = "abc\n"], [u0: String = "" + "123"], [uu: String = "$u"], [v: Char = '\u0000'], [vv: String = "..."]), Disabled: false, Strikeout: false, Green: true Text: ([x: Int]), Disabled: true, Strikeout: false, Green: false */
apache-2.0
ae46faf34fdb39b1ccb207057206152a
51.769231
251
0.583942
2.854167
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/BinaryOperatorReferenceSearcher.kt
6
2286
// 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.search.usagesSearch.operators import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.search.SearchRequestCollector import com.intellij.psi.search.SearchScope import com.intellij.util.Processor import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.lexer.KtSingleValueToken import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance class BinaryOperatorReferenceSearcher( targetFunction: PsiElement, private val operationTokens: List<KtSingleValueToken>, searchScope: SearchScope, consumer: Processor<in PsiReference>, optimizer: SearchRequestCollector, options: KotlinReferencesSearchOptions ) : OperatorReferenceSearcher<KtBinaryExpression>( targetFunction, searchScope, consumer, optimizer, options, wordsToSearch = operationTokens.map { it.value }) { override fun processPossibleReceiverExpression(expression: KtExpression) { val binaryExpression = expression.parent as? KtBinaryExpression ?: return if (binaryExpression.operationToken !in operationTokens) return if (expression != binaryExpression.left) return processReferenceElement(binaryExpression) } override fun isReferenceToCheck(ref: PsiReference): Boolean { if (ref !is KtSimpleNameReference) return false val element = ref.element if (element.parent !is KtBinaryExpression) return false return element.getReferencedNameElementType() in operationTokens } override fun extractReference(element: KtElement): PsiReference? { val binaryExpression = element as? KtBinaryExpression ?: return null if (binaryExpression.operationToken !in operationTokens) return null return binaryExpression.operationReference.references.firstIsInstance<KtSimpleNameReference>() } }
apache-2.0
001a44e46d04f2ce7c6f56201bf65e63
42.980769
158
0.787402
5.417062
false
false
false
false
airbnb/epoxy
epoxy-sample/src/main/java/com/airbnb/epoxy/sample/models/TestModel5.kt
1
522
package com.airbnb.epoxy.sample.models import android.view.View import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyModel import com.airbnb.epoxy.EpoxyModelClass import com.airbnb.epoxy.sample.R @EpoxyModelClass(layout = R.layout.model_color) abstract class TestModel5 : EpoxyModel<View>() { @EpoxyAttribute var num: Int = 0 @EpoxyAttribute var num2: Int = 0 @EpoxyAttribute var num3: Int = 0 @EpoxyAttribute var num4: Int = 0 @EpoxyAttribute var num5: Int = 0 }
apache-2.0
18a49ff079fa06a88e43dd752e5c09cd
22.727273
48
0.726054
3.755396
false
false
false
false
RuneSuite/client
plugins/src/main/java/org/runestar/client/plugins/fpsthrottle/FpsThrottle.kt
1
836
package org.runestar.client.plugins.fpsthrottle import org.runestar.client.api.plugins.DisposablePlugin import org.runestar.client.raw.CLIENT import org.runestar.client.raw.access.XRasterProvider import org.runestar.client.api.plugins.PluginSettings class FpsThrottle : DisposablePlugin<FpsThrottle.Settings>() { override val defaultSettings = Settings() override val name = "FPS Throttle" override fun onStart() { if (settings.sleepTimeMs <= 0) return add(XRasterProvider.drawFull0.exit.subscribe { if (!CLIENT.canvas.isFocusOwner || !settings.onlyWhenUnfocused) { Thread.sleep(settings.sleepTimeMs) } }) } data class Settings( val onlyWhenUnfocused: Boolean = true, val sleepTimeMs: Long = 50L ) : PluginSettings() }
mit
23f4dc800a92ef160c79cb44177aeb5f
30
77
0.691388
4.331606
false
false
false
false
StephenVinouze/AdvancedRecyclerView
sample/src/main/java/com/github/stephenvinouze/advancedrecyclerview/sample/activities/MainActivity.kt
1
3342
package com.github.stephenvinouze.advancedrecyclerview.sample.activities import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import com.github.stephenvinouze.advancedrecyclerview.sample.R import com.github.stephenvinouze.advancedrecyclerview.sample.fragments.GestureRecyclerFragment import com.github.stephenvinouze.advancedrecyclerview.sample.fragments.GestureSectionRecyclerFragment import com.github.stephenvinouze.advancedrecyclerview.sample.fragments.MultipleChoiceRecyclerFragment import com.github.stephenvinouze.advancedrecyclerview.sample.fragments.PaginationRecyclerFragment import com.github.stephenvinouze.advancedrecyclerview.sample.fragments.SectionRecyclerFragment import com.github.stephenvinouze.advancedrecyclerview.sample.fragments.SingleChoiceRecyclerFragment class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) displaySingleChoiceRecyclerFragment() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main_menu, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.single_choice_action -> displaySingleChoiceRecyclerFragment() R.id.multiple_choice_action -> displayMultipleChoiceRecyclerFragment() R.id.section_action -> displaySectionRecyclerFragment() R.id.gesture_action -> displayGestureRecyclerFragment() R.id.gesture_section_action -> displayGestureSectionRecyclerFragment() R.id.pagination_action -> displayPaginationRecyclerFragment() } return super.onOptionsItemSelected(item) } private fun displaySingleChoiceRecyclerFragment() { title = getString(R.string.single_choice_recycler_name) supportFragmentManager.beginTransaction().replace(R.id.main_container, SingleChoiceRecyclerFragment()).commit() } private fun displayMultipleChoiceRecyclerFragment() { title = getString(R.string.multiple_choice_recycler_name) supportFragmentManager.beginTransaction().replace(R.id.main_container, MultipleChoiceRecyclerFragment()).commit() } private fun displaySectionRecyclerFragment() { title = getString(R.string.section_recycler_name) supportFragmentManager.beginTransaction().replace(R.id.main_container, SectionRecyclerFragment()).commit() } private fun displayGestureRecyclerFragment() { title = getString(R.string.gesture_recycler_name) supportFragmentManager.beginTransaction().replace(R.id.main_container, GestureRecyclerFragment()).commit() } private fun displayGestureSectionRecyclerFragment() { title = getString(R.string.gesture_sections_recycler_name) supportFragmentManager.beginTransaction().replace(R.id.main_container, GestureSectionRecyclerFragment()).commit() } private fun displayPaginationRecyclerFragment() { title = getString(R.string.pagination_recycler_name) supportFragmentManager.beginTransaction().replace(R.id.main_container, PaginationRecyclerFragment()).commit() } }
apache-2.0
1eca1569467d382375c3d15fd9f94951
46.742857
121
0.770497
5.304762
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/InlineTypeParameterFix.kt
1
3456
// 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 import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.util.elementType import com.intellij.psi.util.siblings import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext class InlineTypeParameterFix(val typeReference: KtTypeReference) : KotlinQuickFixAction<KtTypeReference>(typeReference) { override fun invoke(project: Project, editor: Editor?, file: KtFile) { val parameterListOwner = typeReference.getStrictParentOfType<KtTypeParameterListOwner>() ?: return val parameterList = parameterListOwner.typeParameterList ?: return val (parameter, bound, constraint) = when (val parent = typeReference.parent) { is KtTypeParameter -> { val bound = parent.extendsBound ?: return Triple(parent, bound, null) } is KtTypeConstraint -> { val subjectTypeParameterName = parent.subjectTypeParameterName?.text ?: return val parameter = parameterList.parameters.firstOrNull { it.name == subjectTypeParameterName } ?: return val bound = parent.boundTypeReference ?: return Triple(parameter, bound, parent) } else -> return } val context = parameterListOwner.analyzeWithContent() val parameterDescriptor = context[BindingContext.TYPE_PARAMETER, parameter] ?: return parameterListOwner.forEachDescendantOfType<KtTypeReference> { typeReference -> val typeElement = typeReference.typeElement val type = context[BindingContext.TYPE, typeReference] if (typeElement != null && type != null && type.constructor.declarationDescriptor == parameterDescriptor) { typeReference.replace(bound) } } if (parameterList.parameters.size == 1) { parameterList.delete() val constraintList = parameterListOwner.typeConstraintList if (constraintList != null) { constraintList.siblings(forward = false).firstOrNull { it.elementType == KtTokens.WHERE_KEYWORD }?.delete() constraintList.delete() } } else { EditCommaSeparatedListHelper.removeItem(parameter) if (constraint != null) { EditCommaSeparatedListHelper.removeItem(constraint) } } } override fun getText() = KotlinBundle.message("inline.type.parameter") override fun getFamilyName() = text companion object Factory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic) = InlineTypeParameterFix(Errors.FINAL_UPPER_BOUND.cast(diagnostic).psiElement) } }
apache-2.0
21d51d7df70a1243e09519beceab3993
47.013889
158
0.704572
5.300613
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/CreateKotlinSubClassIntention.kt
1
10448
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.CodeInsightUtil import com.intellij.codeInsight.daemon.impl.quickfix.CreateClassKind import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.JavaDirectoryService import com.intellij.psi.PsiFile import com.intellij.refactoring.rename.PsiElementRenameHandler import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.descriptors.DescriptorVisibility import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.overrideImplement.ImplementMembersHandler import org.jetbrains.kotlin.idea.refactoring.getOrCreateKotlinFile import org.jetbrains.kotlin.idea.refactoring.ui.CreateKotlinClassDialog import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.KtPsiFactory.ClassHeaderBuilder import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.ModifiersChecker private const val IMPL_SUFFIX = "Impl" class CreateKotlinSubClassIntention : SelfTargetingRangeIntention<KtClass>( KtClass::class.java, KotlinBundle.lazyMessage("create.kotlin.subclass") ) { override fun applicabilityRange(element: KtClass): TextRange? { if (element.name == null || element.getParentOfType<KtFunction>(true) != null) { // Local / anonymous classes are not supported return null } if (!element.isInterface() && !element.isSealed() && !element.isAbstract() && !element.hasModifier(KtTokens.OPEN_KEYWORD)) { return null } val primaryConstructor = element.primaryConstructor if (!element.isInterface() && primaryConstructor != null) { val constructors = element.secondaryConstructors + primaryConstructor if (constructors.none { !it.isPrivate() && it.valueParameters.all { parameter -> parameter.hasDefaultValue() } }) { // At this moment we require non-private default constructor // TODO: handle non-private constructors with parameters return null } } setTextGetter(getImplementTitle(element)) return TextRange(element.startOffset, element.body?.lBrace?.startOffset ?: element.endOffset) } private fun getImplementTitle(baseClass: KtClass) = when { baseClass.isInterface() -> KotlinBundle.lazyMessage("implement.interface") baseClass.isAbstract() -> KotlinBundle.lazyMessage("implement.abstract.class") baseClass.isSealed() -> KotlinBundle.lazyMessage("implement.sealed.class") else /* open class */ -> KotlinBundle.lazyMessage("create.subclass") } override fun startInWriteAction() = false override fun checkFile(file: PsiFile): Boolean { return true } override fun preparePsiElementForWriteIfNeeded(target: KtClass): Boolean { return true } override fun applyTo(element: KtClass, editor: Editor?) { if (editor == null) throw IllegalArgumentException("This intention requires an editor") val name = element.name ?: throw IllegalStateException("This intention should not be applied to anonymous classes") if (element.isSealed() && !element.languageVersionSettings.supportsFeature(LanguageFeature.SealedInterfaces)) { createNestedSubclass(element, name, editor) } else { createExternalSubclass(element, name, editor) } } private fun defaultTargetName(baseName: String) = "$baseName$IMPL_SUFFIX" private fun KtClassOrObject.hasSameDeclaration(name: String) = declarations.any { it is KtNamedDeclaration && it.name == name } private fun targetNameWithoutConflicts(baseName: String, container: KtClassOrObject?) = Fe10KotlinNameSuggester.suggestNameByName(defaultTargetName(baseName)) { container?.hasSameDeclaration(it) != true } private fun createNestedSubclass(sealedClass: KtClass, sealedName: String, editor: Editor) { if (!super.preparePsiElementForWriteIfNeeded(sealedClass)) return val project = sealedClass.project val klass = runWriteAction { val builder = buildClassHeader(targetNameWithoutConflicts(sealedName, sealedClass), sealedClass, sealedName) val classFromText = KtPsiFactory(project).createClass(builder.asString()) val body = sealedClass.getOrCreateBody() body.addBefore(classFromText, body.rBrace) as KtClass } runInteractiveRename(klass, project, sealedClass, editor) chooseAndImplementMethods(project, klass, editor) } private fun createExternalSubclass(baseClass: KtClass, baseName: String, editor: Editor) { var container: KtClassOrObject = baseClass var name = baseName var visibility = ModifiersChecker.resolveVisibilityFromModifiers(baseClass, DescriptorVisibilities.PUBLIC) while (!container.isPrivate() && !container.isProtected() && !(container is KtClass && container.isInner())) { val parent = container.containingClassOrObject if (parent != null) { val parentName = parent.name if (parentName != null) { container = parent name = "$parentName.$name" val parentVisibility = ModifiersChecker.resolveVisibilityFromModifiers(parent, visibility) if ((DescriptorVisibilities.compare(parentVisibility, visibility) ?: 0) < 0) { visibility = parentVisibility } } } if (container != parent) { break } } val project = baseClass.project val factory = KtPsiFactory(project) if (container.containingClassOrObject == null && !isUnitTestMode()) { val dlg = chooseSubclassToCreate(baseClass, baseName) ?: return val targetName = dlg.className val (file, klass) = runWriteAction { val file = getOrCreateKotlinFile("$targetName.kt", dlg.targetDirectory!!)!! val builder = buildClassHeader(targetName, baseClass, baseClass.fqName!!.asString()) file.add(factory.createClass(builder.asString())) val klass = file.getChildOfType<KtClass>()!! ShortenReferences.DEFAULT.process(klass) file to klass } chooseAndImplementMethods(project, klass, CodeInsightUtil.positionCursor(project, file, klass) ?: editor) } else { if (!super.preparePsiElementForWriteIfNeeded(baseClass)) return val klass = runWriteAction { val builder = buildClassHeader( targetNameWithoutConflicts(baseName, baseClass.containingClassOrObject), baseClass, name, visibility ) val classFromText = factory.createClass(builder.asString()) container.parent.addAfter(classFromText, container) as KtClass } runInteractiveRename(klass, project, container, editor) chooseAndImplementMethods(project, klass, editor) } } private fun runInteractiveRename(klass: KtClass, project: Project, container: KtClassOrObject, editor: Editor) { if (isUnitTestMode()) return PsiElementRenameHandler.rename(klass, project, container, editor) } private fun chooseSubclassToCreate(baseClass: KtClass, baseName: String): CreateKotlinClassDialog? { val sourceDir = baseClass.containingFile.containingDirectory val aPackage = JavaDirectoryService.getInstance().getPackage(sourceDir) val dialog = object : CreateKotlinClassDialog( baseClass.project, text, targetNameWithoutConflicts(baseName, baseClass.containingClassOrObject), aPackage?.qualifiedName ?: "", CreateClassKind.CLASS, true, ModuleUtilCore.findModuleForPsiElement(baseClass), baseClass.isSealed() ) { override fun getBaseDir(packageName: String?) = sourceDir override fun reportBaseInTestSelectionInSource() = true } return if (!dialog.showAndGet() || dialog.targetDirectory == null) null else dialog } private fun buildClassHeader( targetName: String, baseClass: KtClass, baseName: String, defaultVisibility: DescriptorVisibility = ModifiersChecker.resolveVisibilityFromModifiers(baseClass, DescriptorVisibilities.PUBLIC) ): ClassHeaderBuilder { return ClassHeaderBuilder().apply { if (!baseClass.isInterface()) { if (defaultVisibility != DescriptorVisibilities.PUBLIC) { modifier(defaultVisibility.name) } if (baseClass.isInner()) { modifier(KtTokens.INNER_KEYWORD.value) } } name(targetName) val typeParameters = baseClass.typeParameterList?.parameters typeParameters(typeParameters?.map { it.text }.orEmpty()) baseClass(baseName, typeParameters?.map { it.name ?: "" }.orEmpty(), baseClass.isInterface()) typeConstraints(baseClass.typeConstraintList?.constraints?.map { it.text }.orEmpty()) } } private fun chooseAndImplementMethods(project: Project, targetClass: KtClass, editor: Editor) { editor.caretModel.moveToOffset(targetClass.textRange.startOffset) ImplementMembersHandler().invoke(project, editor, targetClass.containingFile) } }
apache-2.0
b89ba7b4e0b882a193eeab91c9cd95f1
48.051643
139
0.687117
5.382792
false
false
false
false
Hexworks/snap
src/main/kotlin/org/codetome/snap/service/parser/EndpointSegmentParser.kt
1
3056
package org.codetome.snap.service.parser import org.codetome.snap.model.ConfigSegmentType.REST_ENDPOINT import org.codetome.snap.model.ConfigSegmentType.REST_METHOD import org.codetome.snap.model.ParseContext import org.codetome.snap.model.rest.MethodType import org.codetome.snap.model.rest.Path import org.codetome.snap.model.rest.RestEndpoint import org.codetome.snap.model.rest.RestMethod import org.codetome.snap.util.SubstringRanges abstract class EndpointSegmentParser<N>( private val segmentTypeAnalyzer: SegmentTypeAnalyzer<N>, private val headerSegmentParser: HeaderSegmentParser<N>, private val descriptionSegmentParser: DescriptionSegmentParser<N>, private val schemaSegmentParser: SchemaSegmentParser<N>, private val restMethodSegmentParser: RestMethodSegmentParser<N>) : SegmentParser<N, RestEndpoint> { override fun parseSegment(nodes: List<N>, context: ParseContext): Pair<RestEndpoint, List<N>> { if (nodes.size < 3) { throw IllegalArgumentException("An Endpoint declaration must contain at least a description, a schema declaration and a method!") } if (REST_ENDPOINT != segmentTypeAnalyzer.determineSegmentType(nodes.first())) { throw IllegalArgumentException("An Endpoint declaration must start with an Endpoint header!") } val (header, rest0) = headerSegmentParser.parseSegment(nodes, context) val (description, rest1) = descriptionSegmentParser.parseSegment(rest0, context) val (schema, rest2) = schemaSegmentParser.parseSegment(rest1, context) context.declaredSchemas.put(schema.name, schema) if (rest2.isEmpty()) { throw IllegalArgumentException("An Endpoint declaration must contain at least a single Rest Method!") } var remaining = rest2 val restMethods = mutableMapOf<MethodType, RestMethod>() while (hasRemainingRestMethods(remaining)) { val (restMethod, tempRemaining) = restMethodSegmentParser.parseSegment(remaining, context) remaining = tempRemaining restMethods.put(restMethod.method, restMethod) } return Pair(RestEndpoint( name = header.name, description = description, path = Path( pathStr = header.linkContent, paramToSchemaPropertyMapping = parsePathParams(header.linkContent) // TODO: fill this properly in next version! ), schema = schema, restMethods = restMethods ), remaining) } private fun parsePathParams(pathStr: String): Map<String, String> { return SubstringRanges.rangesDelimitedByPairInString(Pair('{', '}'), pathStr) .subStrings .map { Pair(it, it) } .toMap() } private fun hasRemainingRestMethods(remaining: List<N>) = remaining.isNotEmpty() && REST_METHOD == segmentTypeAnalyzer.determineSegmentType(remaining.first()) }
agpl-3.0
403dc7018f9f2727c04b45b8d931a346
47.52381
141
0.684228
4.789969
false
false
false
false
theunknownxy/mcdocs
src/main/kotlin/de/theunknownxy/mcdocs/docs/loader/FileDocumentationLoader.kt
1
3352
package de.theunknownxy.mcdocs.docs.loader import de.theunknownxy.mcdocs.docs.* import de.theunknownxy.mcdocs.docs.loader.xml.XMLParserHandler import java.io.File import java.nio.file.Path import java.util.ArrayList import javax.xml.parsers.SAXParserFactory public class FileDocumentationLoader(private val root_path: Path) : DocumentationLoader { private val extension = ".xml" private fun get_nodepath(ref: DocumentationNodeRef): Path { var filepath: Path = root_path.resolve(ref.path) // Check whether the path is valid if (!filepath.startsWith(root_path)) { throw IllegalArgumentException("The path '$filepath' is not within '$root_path'") } return filepath } private fun should_show_entry(p: File): Boolean { return p.getName() != "index.xml" && (p.isDirectory() || p.extension.equalsIgnoreCase("xml")) } private fun collect_childs(p: Path): MutableList<DocumentationNodeRef> { var childs: MutableList<DocumentationNodeRef> = ArrayList() if (p.toFile().isDirectory()) { val files = p.toFile().list() files.sort() for (child in files) { if (should_show_entry(File(p.toFile(), child))) { val childpath = p.resolve(child.replace(".xml", "")) childs.add(DocumentationNodeRef(root_path.relativize(childpath).toString())) } } } return childs } private fun get_filepath(p: Path): Path { // Construct the real filesystem path if (p.toFile().isDirectory()) { // The actual content is within the folder return p.resolve("index" + extension) } else { // Append the .xml suffix if it's a file return p.getParent().resolve((p.getFileName().toString() + extension)) } } private fun parse_file(filepath: Path): Pair<String, Content> { // Read and parse the file var title: String var content: Content try { val spf = SAXParserFactory.newInstance() val parser = spf.newSAXParser() val handler = XMLParserHandler() parser.parse(filepath.toFile(), handler) title = handler.document.title content = handler.document.content } catch(e: Exception) { title = "Invalid" // Create a page with the error content = Content() val p: ParagraphBlock = ParagraphBlock(ParagraphElement()) p.value.childs.add(TextElement("Invalid document($filepath): $e")) content.blocks.add(p) } return Pair(title, content) } override fun load(ref: DocumentationNodeRef): DocumentationNode { val nodepath: Path = get_nodepath(ref) val childs = collect_childs(nodepath) val filepath = get_filepath(nodepath) if (!filepath.toFile().exists()) { val node = DocumentationNode(ref, "FIXME", null) node.children = childs return node } var (title: String, content: Content) = parse_file(filepath) val node = DocumentationNode(ref, title, content) node.children = childs node.parent = ref.parent() return node } }
mit
df93a06f12953f3eaaef6a8bc562c690
33.927083
96
0.597852
4.523617
false
false
false
false
Homes-MinecraftServerMod/Homes
src/main/kotlin/com/masahirosaito/spigot/homes/datas/strings/commands/ListCommandStringData.kt
1
502
package com.masahirosaito.spigot.homes.datas.strings.commands data class ListCommandStringData( val DESCRIPTION_PLAYER_COMMAND: String = "Display the list of your homes", val DESCRIPTION_CONSOLE_COMMAND: String = "Display the list of player homes", val USAGE_CONSOLE_COMMAND_LIST: String = "Display the list of players", val USAGE_PLAYER_COMMAND_LIST: String = "Display the list of homes", val USAGE_LIST_PLAYER: String = "Display the list of player's homes" )
apache-2.0
88e07881997421068a894a97a9e35cbd
54.777778
85
0.721116
4.254237
false
false
false
false
cortinico/myo-emg-visualizer
app/src/test/java/it/ncorti/emgvisualizer/ui/export/ExportPresenterTest.kt
1
4561
package it.ncorti.emgvisualizer.ui.export import com.ncorti.myonnaise.Myo import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import io.reactivex.Flowable import it.ncorti.emgvisualizer.dagger.DeviceManager import it.ncorti.emgvisualizer.ui.testutil.TestSchedulerRule import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.ArgumentMatchers import org.mockito.ArgumentMatchers.anyInt class ExportPresenterTest { @get:Rule val testSchedulerRule = TestSchedulerRule() private lateinit var mockedView: ExportContract.View private lateinit var mockedDeviceManager: DeviceManager private lateinit var mockedMyo: Myo private lateinit var testPresenter: ExportPresenter @Before fun setUp() { mockedView = mock {} mockedMyo = mock {} mockedDeviceManager = mock { on(mock.myo) doReturn mockedMyo } testPresenter = ExportPresenter(mockedView, mockedDeviceManager) } @Test fun onStart_collectedPointsAreShown() { testPresenter.start() verify(mockedView).showCollectedPoints(anyInt()) } @Test fun onStart_withStreamingDevice_enableCollection() { whenever(mockedDeviceManager.myo?.isStreaming()).thenReturn(true) testPresenter.start() verify(mockedView).enableStartCollectingButton() } @Test fun onStart_withNotStreamingDevice_disableCollection() { whenever(mockedDeviceManager.myo?.isStreaming()).thenReturn(false) testPresenter.start() verify(mockedView).disableStartCollectingButton() } @Test fun onCollectionTogglePressed_withNotStreamingDevice_showErrorMessage() { testPresenter.onCollectionTogglePressed() verify(mockedView).showNotStreamingErrorMessage() } @Test fun onCollectionTogglePressed_withStreamingDeviceAndNotSubscribed_showCollectedPoints() { whenever(mockedDeviceManager.myo?.isStreaming()).thenReturn(true) whenever(mockedDeviceManager.myo?.dataFlowable()) .thenReturn( Flowable.just( floatArrayOf(1.0f), floatArrayOf(2.0f), floatArrayOf(3.0f) ) ) testPresenter.dataSubscription = null testPresenter.onCollectionTogglePressed() assertNotNull(testPresenter.dataSubscription) verify(mockedView).showCollectionStarted() verify(mockedView).disableResetButton() verify(mockedView).showCollectedPoints(1) verify(mockedView).showCollectedPoints(2) verify(mockedView).showCollectedPoints(3) } @Test fun onCollectionTogglePressed_withStreamingDevice_showCollectedPoints() { whenever(mockedDeviceManager.myo?.isStreaming()).thenReturn(true) // We simulate that we are subscribed to a flowable testPresenter.dataSubscription = mock {} testPresenter.onCollectionTogglePressed() verify(testPresenter.dataSubscription)?.dispose() verify(mockedView).enableResetButton() verify(mockedView).showSaveArea() verify(mockedView).showCollectionStopped() } @Test fun onResetPressed_resetTheView() { testPresenter.onResetPressed() verify(mockedView).showCollectedPoints(0) verify(mockedView).hideSaveArea() verify(mockedView).disableResetButton() } @Test fun onSavePressed_askViewToSave() { testPresenter.onSavePressed() verify(mockedView).saveCsvFile(ArgumentMatchers.anyString()) } @Test fun onSharePressed_askViewToShare() { testPresenter.onSharePressed() verify(mockedView).sharePlainText(ArgumentMatchers.anyString()) } @Test fun createCsv_withEmptyBuffer_EmptyList() { assertEquals("", testPresenter.createCsv(arrayListOf())) } @Test fun createCsv_withSingleLine_OneLineCsv() { val buffer = arrayListOf(floatArrayOf(1f, 2f, 3f)) assertEquals("1.0;2.0;3.0;\n", testPresenter.createCsv(buffer)) } @Test fun createCsv_withMultipleLine_MultipleLineCsv() { val buffer = arrayListOf( floatArrayOf(1f, 2f, 3f), floatArrayOf(4f, 5f, 6f) ) assertEquals("1.0;2.0;3.0;\n4.0;5.0;6.0;\n", testPresenter.createCsv(buffer)) } }
mit
d8a9bbc45b73ce5fe75cdf371cb89138
29.61745
93
0.695242
4.611729
false
true
false
false
F43nd1r/acra-backend
acrarium/src/main/kotlin/com/faendir/acra/security/SecurityUtils.kt
1
2958
/* * (C) Copyright 2018 Lukas Morawietz (https://github.com/F43nd1r) * * 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.faendir.acra.security import com.faendir.acra.model.App import com.faendir.acra.model.Permission import com.faendir.acra.model.User import com.vaadin.flow.server.HandlerHelper.RequestType import com.vaadin.flow.shared.ApplicationConstants import org.springframework.core.annotation.AnnotationUtils import org.springframework.security.authentication.AnonymousAuthenticationToken import org.springframework.security.core.context.SecurityContextHolder import javax.servlet.http.HttpServletRequest object SecurityUtils { @JvmStatic fun isLoggedIn(): Boolean = SecurityContextHolder.getContext().authentication?.takeIf { it !is AnonymousAuthenticationToken }?.isAuthenticated ?: false @JvmStatic fun hasRole(role: User.Role): Boolean = SecurityContextHolder.getContext().authentication?.authorities?.any { it.authority == role.authority } ?: false @JvmStatic fun getUsername(): String = SecurityContextHolder.getContext().authentication?.name ?: "" @JvmStatic fun hasPermission(app: App, level: Permission.Level): Boolean = SecurityContextHolder.getContext().authentication?.let { getPermission(app, it.authorities.filterIsInstance<Permission>()) { hasRole(User.Role.ADMIN) }.ordinal >= level.ordinal } ?: false @JvmStatic fun hasAccess(getApp: () -> App, target: Class<*>): Boolean { return AnnotationUtils.findAnnotation(target, RequiresRole::class.java)?.let { hasRole(it.value) } ?: true && AnnotationUtils.findAnnotation(target, RequiresPermission::class.java)?.let { hasPermission(getApp(), it.value) } ?: true } @JvmStatic fun getPermission(app: App, user: User): Permission.Level = getPermission(app, user.permissions) { user.roles.contains(User.Role.ADMIN) } private fun getPermission(app: App, permissionStream: Collection<Permission>, isAdmin: () -> Boolean): Permission.Level = permissionStream.firstOrNull { it.app == app }?.level ?: if (isAdmin()) Permission.Level.ADMIN else Permission.Level.NONE @JvmStatic fun isFrameworkInternalRequest(request: HttpServletRequest): Boolean { val parameterValue = request.getParameter(ApplicationConstants.REQUEST_TYPE_PARAMETER) return (parameterValue != null && RequestType.values().any { it.identifier == parameterValue }) } }
apache-2.0
1edb31c72aa03fd600a5ae9f277485f4
46.725806
155
0.748479
4.586047
false
false
false
false
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/main/kotlin/com/vrem/wifianalyzer/wifi/timegraph/DataManager.kt
1
3024
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.wifianalyzer.wifi.timegraph import com.jjoe64.graphview.series.LineGraphSeries import com.vrem.annotation.OpenClass import com.vrem.wifianalyzer.wifi.graphutils.* import com.vrem.wifianalyzer.wifi.model.WiFiDetail @OpenClass internal class DataManager(private val timeGraphCache: TimeGraphCache = TimeGraphCache()) { var scanCount: Int = 0 var xValue = 0 fun addSeriesData(graphViewWrapper: GraphViewWrapper, wiFiDetails: List<WiFiDetail>, levelMax: Int): Set<WiFiDetail> { val inOrder: Set<WiFiDetail> = wiFiDetails.toSet() inOrder.forEach { addData(graphViewWrapper, it, levelMax) } adjustData(graphViewWrapper, inOrder) xValue++ if (scanCount < MAX_SCAN_COUNT) { scanCount++ } if (scanCount == 2) { graphViewWrapper.setHorizontalLabelsVisible(true) } return newSeries(inOrder) } fun adjustData(graphViewWrapper: GraphViewWrapper, wiFiDetails: Set<WiFiDetail>) { graphViewWrapper.differenceSeries(wiFiDetails).forEach { val dataPoint = GraphDataPoint(xValue, MIN_Y + MIN_Y_OFFSET) val drawBackground = it.wiFiAdditional.wiFiConnection.connected graphViewWrapper.appendToSeries(it, dataPoint, scanCount, drawBackground) timeGraphCache.add(it) } timeGraphCache.clear() } fun newSeries(wiFiDetails: Set<WiFiDetail>): Set<WiFiDetail> = wiFiDetails.plus(timeGraphCache.active()) fun addData(graphViewWrapper: GraphViewWrapper, wiFiDetail: WiFiDetail, levelMax: Int) { val drawBackground = wiFiDetail.wiFiAdditional.wiFiConnection.connected val level = wiFiDetail.wiFiSignal.level.coerceAtMost(levelMax) if (graphViewWrapper.newSeries(wiFiDetail)) { val dataPoint = GraphDataPoint(xValue, (if (scanCount > 0) MIN_Y + MIN_Y_OFFSET else level)) val series = LineGraphSeries(arrayOf(dataPoint)) graphViewWrapper.addSeries(wiFiDetail, series, drawBackground) } else { val dataPoint = GraphDataPoint(xValue, level) graphViewWrapper.appendToSeries(wiFiDetail, dataPoint, scanCount, drawBackground) } timeGraphCache.reset(wiFiDetail) } }
gpl-3.0
8284924eb1f67842e2743db352d0e82c
42.214286
122
0.71164
4.382609
false
false
false
false
Raizlabs/DBFlow
core/src/main/kotlin/com/dbflow5/converter/TypeConverters.kt
1
4117
package com.dbflow5.converter import java.math.BigDecimal import java.math.BigInteger import java.sql.Time import java.sql.Timestamp import java.util.* /** * Author: andrewgrosner * Description: This class is responsible for converting the stored database value into the field value in * a Model. */ @com.dbflow5.annotation.TypeConverter abstract class TypeConverter<DataClass, ModelClass> { /** * Converts the ModelClass into a DataClass * * @param model this will be called upon syncing * @return The DataClass value that converts into a SQLite type */ abstract fun getDBValue(model: ModelClass?): DataClass? /** * Converts a DataClass from the DB into a ModelClass * * @param data This will be called when the model is loaded from the DB * @return The ModelClass value that gets set in a Model that holds the data class. */ abstract fun getModelValue(data: DataClass?): ModelClass? } /** * Description: Defines how we store and retrieve a [java.math.BigDecimal] */ @com.dbflow5.annotation.TypeConverter class BigDecimalConverter : TypeConverter<String, BigDecimal>() { override fun getDBValue(model: BigDecimal?): String? = model?.toString() override fun getModelValue(data: String?): BigDecimal? = if (data == null) null else BigDecimal(data) } /** * Description: Defines how we store and retrieve a [java.math.BigInteger] */ @com.dbflow5.annotation.TypeConverter class BigIntegerConverter : TypeConverter<String, BigInteger>() { override fun getDBValue(model: BigInteger?): String? = model?.toString() override fun getModelValue(data: String?): BigInteger? = if (data == null) null else BigInteger(data) } /** * Description: Converts a boolean object into an Integer for database storage. */ @com.dbflow5.annotation.TypeConverter class BooleanConverter : TypeConverter<Int, Boolean>() { override fun getDBValue(model: Boolean?): Int? = if (model == null) null else if (model) 1 else 0 override fun getModelValue(data: Int?): Boolean? = if (data == null) null else data == 1 } /** * Description: Defines how we store and retrieve a [java.util.Calendar] */ @com.dbflow5.annotation.TypeConverter(allowedSubtypes = [(GregorianCalendar::class)]) class CalendarConverter : TypeConverter<Long, Calendar>() { override fun getDBValue(model: Calendar?): Long? = model?.timeInMillis override fun getModelValue(data: Long?): Calendar? = if (data != null) Calendar.getInstance().apply { timeInMillis = data } else null } /** * Description: Converts a [Character] into a [String] for database storage. */ @com.dbflow5.annotation.TypeConverter class CharConverter : TypeConverter<String, Char>() { override fun getDBValue(model: Char?): String? = if (model != null) String(charArrayOf(model)) else null override fun getModelValue(data: String?): Char? = if (data != null) data[0] else null } /** * Description: Defines how we store and retrieve a [java.util.Date] */ @com.dbflow5.annotation.TypeConverter class DateConverter : TypeConverter<Long, Date>() { override fun getDBValue(model: Date?): Long? = model?.time override fun getModelValue(data: Long?): Date? = if (data == null) null else Date(data) } /** * Description: Defines how we store and retrieve a [java.sql.Date] */ @com.dbflow5.annotation.TypeConverter(allowedSubtypes = [(Time::class), (Timestamp::class)]) class SqlDateConverter : TypeConverter<Long, java.sql.Date>() { override fun getDBValue(model: java.sql.Date?): Long? = model?.time override fun getModelValue(data: Long?): java.sql.Date? = if (data == null) null else java.sql.Date(data) } /** * Description: Responsible for converting a [UUID] to a [String]. * * @author Andrew Grosner (fuzz) */ @com.dbflow5.annotation.TypeConverter class UUIDConverter : TypeConverter<String, UUID>() { override fun getDBValue(model: UUID?): String? = model?.toString() override fun getModelValue(data: String?): UUID? { return if (data == null) { null } else UUID.fromString(data) } }
mit
51cde6ef2c86311d782a636f33a0dbf5
31.944
109
0.70634
4.028376
false
false
false
false
nobuoka/vc-oauth-java
ktor-twitter-login/src/test/kotlin/info/vividcode/ktor/twitter/login/TwitterLoginInterceptorsTest.kt
1
5941
package info.vividcode.ktor.twitter.login import info.vividcode.ktor.twitter.login.application.TemporaryCredentialNotFoundException import info.vividcode.ktor.twitter.login.application.TestServerTwitter import info.vividcode.ktor.twitter.login.application.TwitterCallFailedException import info.vividcode.ktor.twitter.login.application.responseBuilder import info.vividcode.ktor.twitter.login.test.TestCallFactory import info.vividcode.ktor.twitter.login.test.TestTemporaryCredentialStore import info.vividcode.oauth.OAuth import io.ktor.application.Application import io.ktor.application.call import io.ktor.http.HttpMethod import io.ktor.http.HttpStatusCode import io.ktor.response.respondText import io.ktor.routing.get import io.ktor.routing.post import io.ktor.routing.routing import io.ktor.server.testing.handleRequest import io.ktor.server.testing.withTestApplication import kotlinx.coroutines.newSingleThreadContext import kotlinx.coroutines.runBlocking import okhttp3.Call import okhttp3.MediaType import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.ResponseBody import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import java.time.Clock import java.time.Instant import java.time.ZoneId import kotlin.coroutines.CoroutineContext internal class TwitterLoginInterceptorsTest { private val testServer = TestServerTwitter() private val testTemporaryCredentialStore = TestTemporaryCredentialStore() private val twitterLoginInterceptors = TwitterLoginInterceptors( ClientCredential("test-identifier", "test-secret"), "http://test.com/callback", object : Env { override val oauth: OAuth = OAuth(object : OAuth.Env { override val clock: Clock = Clock.fixed(Instant.parse("2015-01-01T00:00:00Z"), ZoneId.systemDefault()) override val nextInt: (Int) -> Int = { (it - 1) / 2 } }) override val httpClient: Call.Factory = TestCallFactory(testServer) override val httpCallContext: CoroutineContext = newSingleThreadContext("TestHttpCall") override val temporaryCredentialStore: TemporaryCredentialStore = testTemporaryCredentialStore }, object : OutputPort { override val success: OutputInterceptor<TwitterToken> = { call.respondText("test success") } override val twitterCallFailed: OutputInterceptor<TwitterCallFailedException> = { call.respondText("test twitter call failed") } override val temporaryCredentialNotFound: OutputInterceptor<TemporaryCredentialNotFoundException> = { call.respondText("test temporary credential not found (identifier : ${it.temporaryCredentialIdentifier})") } } ) private val testableModule: Application.() -> Unit = { routing { post("/start", twitterLoginInterceptors.startTwitterLogin) get("/callback", twitterLoginInterceptors.finishTwitterLogin) } } @Test fun testRequest() = withTestApplication(testableModule) { testServer.responseBuilders.add(responseBuilder { code(200).message("OK") body( ResponseBody.create( "application/x-www-form-urlencoded".toMediaTypeOrNull(), "oauth_token=test-temporary-token&oauth_token_secret=test-token-secret" ) ) }) handleRequest(HttpMethod.Post, "/start").run { assertEquals(HttpStatusCode.Found, response.status()) assertEquals( "https://api.twitter.com/oauth/authenticate?oauth_token=test-temporary-token", response.headers["Location"] ) } testServer.responseBuilders.add(responseBuilder { code(200).message("OK") body( ResponseBody.create( "application/x-www-form-urlencoded".toMediaTypeOrNull(), "oauth_token=test-access-token&oauth_token_secret=test-token-secret&user_id=101&screen_name=foo" ) ) }) handleRequest(HttpMethod.Get, "/callback?oauth_token=test-temporary-token&verifier=test-verifier").run { assertEquals(HttpStatusCode.OK, response.status()) assertEquals("test success", response.content) } } @Test fun redirect_twitterServerError() = withTestApplication(testableModule) { testServer.responseBuilders.add(responseBuilder { code(500).message("Internal Server Error") }) handleRequest(HttpMethod.Post, "/start").run { assertEquals(HttpStatusCode.OK, response.status()) assertEquals("test twitter call failed", response.content) } } @Test fun accessToken_twitterServerError() = withTestApplication(testableModule) { runBlocking { testTemporaryCredentialStore.saveTemporaryCredential( TemporaryCredential("test-temporary-token", "test-secret") ) } testServer.responseBuilders.add(responseBuilder { code(500).message("Internal Server Error") }) handleRequest(HttpMethod.Get, "/callback?oauth_token=test-temporary-token&verifier=test-verifier").run { assertEquals(HttpStatusCode.OK, response.status()) assertEquals("test twitter call failed", response.content) } } @Test fun accessToken_tokenNotFound() = withTestApplication(testableModule) { handleRequest(HttpMethod.Get, "/callback?oauth_token=test-temporary-token&verifier=test-verifier").run { assertEquals(HttpStatusCode.OK, response.status()) assertEquals("test temporary credential not found (identifier : test-temporary-token)", response.content) } } }
apache-2.0
c7892c91dc0d142d3552d2afccab02ae
40.545455
122
0.681535
4.918046
false
true
false
false
Raizlabs/DBFlow
lib/src/main/kotlin/com/dbflow5/query/Operator.kt
1
23769
@file:Suppress("UNCHECKED_CAST") package com.dbflow5.query import com.dbflow5.annotation.Collate import com.dbflow5.appendOptional import com.dbflow5.config.FlowLog import com.dbflow5.config.FlowManager import com.dbflow5.converter.TypeConverter import com.dbflow5.query.property.Property import com.dbflow5.query.property.TypeConvertedProperty import com.dbflow5.sql.Query /** * Description: The class that contains a column name, Operator<T>, and value. * This class is mostly reserved for internal use at this point. Using this class directly should be avoided * and use the generated [Property] instead. </T> */ class Operator<T : Any?> internal constructor(nameAlias: NameAlias?, private val table: Class<*>? = null, private val getter: TypeConvertedProperty.TypeConverterGetter? = null, private val convertToDB: Boolean) : BaseOperator(nameAlias), IOperator<T> { private val typeConverter: TypeConverter<*, *>? by lazy { table?.let { table -> getter?.getTypeConverter(table) } } private var convertToString = true override val query: String get() = appendToQuery() internal constructor(operator: Operator<*>) : this(operator.nameAlias, operator.table, operator.getter, operator.convertToDB) { this.value = operator.value } override fun appendConditionToQuery(queryBuilder: StringBuilder) { queryBuilder.append(columnName()).append(operation()) // Do not use value for certain operators // If is raw, we do not want to convert the value to a string. if (isValueSet) { queryBuilder.append(if (convertToString) convertObjectToString(value(), true) else value()) } postArgument()?.let { queryBuilder.append(" $it") } } override fun isNull() = apply { operation = " ${Operation.IS_NULL} " } override fun isNotNull() = apply { operation = " ${Operation.IS_NOT_NULL} " } override fun `is`(value: T?): Operator<T> { operation = Operation.EQUALS return value(value) } override fun eq(value: T?): Operator<T> = `is`(value) override fun isNot(value: T?): Operator<T> { operation = Operation.NOT_EQUALS return value(value) } override fun notEq(value: T?): Operator<T> = isNot(value) /** * Uses the LIKE operation. Case insensitive comparisons. * * @param value Uses sqlite LIKE regex to match rows. * It must be a string to escape it properly. * There are two wildcards: % and _ * % represents [0,many) numbers or characters. * The _ represents a single number or character. * @return This condition */ override fun like(value: String): Operator<T> { operation = " ${Operation.LIKE} " return value(value) } /** * Uses the MATCH operation. Faster than [like], using an FTS4 Table. * * . If the WHERE clause of the SELECT statement contains a sub-clause of the form "<column> MATCH ?", * FTS is able to use the built-in full-text index to restrict the search to those documents * that match the full-text query string specified as the right-hand operand of the MATCH clause. * * @param value a simple string to match. */ override fun match(value: String): Operator<T> { operation = " ${Operation.MATCH} " return value(value) } /** * Uses the NOT LIKE operation. Case insensitive comparisons. * * @param value Uses sqlite LIKE regex to inversely match rows. * It must be a string to escape it properly. * There are two wildcards: % and _ * % represents [0,many) numbers or characters. * The _ represents a single number or character. * */ override fun notLike(value: String): Operator<T> { operation = " ${Operation.NOT_LIKE} " return value(value) } /** * Uses the GLOB operation. Similar to LIKE except it uses case sensitive comparisons. * * @param value Uses sqlite GLOB regex to match rows. * It must be a string to escape it properly. * There are two wildcards: * and ? * * represents [0,many) numbers or characters. * The ? represents a single number or character * */ override fun glob(value: String): Operator<T> { operation = " ${Operation.GLOB} " return value(value) } /** * The value of the parameter * * @param value The value of the column in the DB * */ fun value(value: Any?) = apply { this.value = value isValueSet = true } override fun greaterThan(value: T): Operator<T> { operation = Operation.GREATER_THAN return value(value) } override fun greaterThanOrEq(value: T): Operator<T> { operation = Operation.GREATER_THAN_OR_EQUALS return value(value) } override fun lessThan(value: T): Operator<T> { operation = Operation.LESS_THAN return value(value) } override fun lessThanOrEq(value: T): Operator<T> { operation = Operation.LESS_THAN_OR_EQUALS return value(value) } override fun plus(value: T): Operator<T> = assignValueOp(value, Operation.PLUS) override fun minus(value: T): Operator<T> = assignValueOp(value, Operation.MINUS) override fun div(value: T): Operator<T> = assignValueOp(value, Operation.DIVISION) override fun times(value: T): Operator<T> = assignValueOp(value, Operation.MULTIPLY) override fun rem(value: T): Operator<T> = assignValueOp(value, Operation.MOD) /** * Add a custom operation to this argument * * @param operation The SQLite operator * */ fun operation(operation: String) = apply { this.operation = operation } /** * Adds a COLLATE to the end of this condition * * @param collation The SQLite collate function * . */ infix fun collate(collation: String) = apply { postArg = "COLLATE $collation" } /** * Adds a COLLATE to the end of this condition using the [Collate] enum. * * @param collation The SQLite collate function * . */ infix fun collate(collation: Collate) = apply { if (collation == Collate.NONE) { postArg = null } else { collate(collation.name) } } /** * Appends an optional SQL string to the end of this condition */ infix fun postfix(postfix: String) = apply { postArg = postfix } /** * Optional separator when chaining this Operator within a [OperatorGroup] * * @param separator The separator to use * @return This instance */ override fun separator(separator: String) = apply { this.separator = separator } override fun `is`(conditional: IConditional): Operator<*> = assignValueOp(conditional, Operation.EQUALS) override fun eq(conditional: IConditional): Operator<*> = assignValueOp(conditional, Operation.EQUALS) override fun isNot(conditional: IConditional): Operator<*> = assignValueOp(conditional, Operation.NOT_EQUALS) override fun notEq(conditional: IConditional): Operator<*> = assignValueOp(conditional, Operation.NOT_EQUALS) override fun like(conditional: IConditional): Operator<T> = like(conditional.query) override fun glob(conditional: IConditional): Operator<T> = glob(conditional.query) override fun greaterThan(conditional: IConditional): Operator<T> = assignValueOp(conditional, Operation.GREATER_THAN) override fun greaterThanOrEq(conditional: IConditional): Operator<T> = assignValueOp(conditional, Operation.GREATER_THAN_OR_EQUALS) override fun lessThan(conditional: IConditional): Operator<T> = assignValueOp(conditional, Operation.LESS_THAN) override fun lessThanOrEq(conditional: IConditional): Operator<T> = assignValueOp(conditional, Operation.LESS_THAN_OR_EQUALS) override fun between(conditional: IConditional): Between<*> = Between(this as Operator<Any>, conditional) override fun `in`(firstConditional: IConditional, vararg conditionals: IConditional): In<*> = In(this as Operator<Any>, firstConditional, true, *conditionals) override fun notIn(firstConditional: IConditional, vararg conditionals: IConditional): In<*> = In(this as Operator<Any>, firstConditional, false, *conditionals) override fun notIn(firstBaseModelQueriable: BaseModelQueriable<*>, vararg baseModelQueriables: BaseModelQueriable<*>): In<*> = In(this as Operator<Any>, firstBaseModelQueriable, false, *baseModelQueriables) override fun `is`(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = assignValueOp(baseModelQueriable, Operation.EQUALS) override fun eq(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = assignValueOp(baseModelQueriable, Operation.EQUALS) override fun isNot(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = assignValueOp(baseModelQueriable, Operation.NOT_EQUALS) override fun notEq(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = assignValueOp(baseModelQueriable, Operation.NOT_EQUALS) override fun like(baseModelQueriable: BaseModelQueriable<*>): Operator<T> = assignValueOp(baseModelQueriable, Operation.LIKE) override fun notLike(conditional: IConditional): Operator<*> = assignValueOp(conditional, Operation.NOT_LIKE) override fun notLike(baseModelQueriable: BaseModelQueriable<*>): Operator<*> = assignValueOp(baseModelQueriable, Operation.NOT_LIKE) override fun glob(baseModelQueriable: BaseModelQueriable<*>): Operator<T> = assignValueOp(baseModelQueriable, Operation.GLOB) override fun greaterThan(baseModelQueriable: BaseModelQueriable<*>): Operator<T> = assignValueOp(baseModelQueriable, Operation.GREATER_THAN) override fun greaterThanOrEq(baseModelQueriable: BaseModelQueriable<*>): Operator<T> = assignValueOp(baseModelQueriable, Operation.GREATER_THAN_OR_EQUALS) override fun lessThan(baseModelQueriable: BaseModelQueriable<*>): Operator<T> = assignValueOp(baseModelQueriable, Operation.LESS_THAN) override fun lessThanOrEq(baseModelQueriable: BaseModelQueriable<*>): Operator<T> = assignValueOp(baseModelQueriable, Operation.LESS_THAN_OR_EQUALS) operator fun plus(value: IConditional): Operator<*> = assignValueOp(value, Operation.PLUS) operator fun minus(value: IConditional): Operator<*> = assignValueOp(value, Operation.MINUS) operator fun div(value: IConditional): Operator<*> = assignValueOp(value, Operation.DIVISION) operator fun times(value: IConditional): Operator<*> = assignValueOp(value, Operation.MULTIPLY) operator fun rem(value: IConditional): Operator<*> = assignValueOp(value, Operation.MOD) override fun plus(value: BaseModelQueriable<*>): Operator<*> = assignValueOp(value, Operation.PLUS) override fun minus(value: BaseModelQueriable<*>): Operator<*> = assignValueOp(value, Operation.MINUS) override fun div(value: BaseModelQueriable<*>): Operator<*> = assignValueOp(value, Operation.DIVISION) override fun times(value: BaseModelQueriable<*>): Operator<*> = assignValueOp(value, Operation.MULTIPLY) override fun rem(value: BaseModelQueriable<*>): Operator<*> = assignValueOp(value, Operation.MOD) override fun between(baseModelQueriable: BaseModelQueriable<*>): Between<*> = Between(this as Operator<Any>, baseModelQueriable) override fun `in`(firstBaseModelQueriable: BaseModelQueriable<*>, vararg baseModelQueriables: BaseModelQueriable<*>): In<*> = In(this as Operator<Any>, firstBaseModelQueriable, true, *baseModelQueriables) override fun concatenate(value: Any?): Operator<T> { var _value = value operation = "${Operation.EQUALS}${columnName()}" var typeConverter: TypeConverter<*, Any>? = this.typeConverter as TypeConverter<*, Any>? if (typeConverter == null && _value != null) { typeConverter = FlowManager.getTypeConverterForClass(_value.javaClass) as TypeConverter<*, Any>? } if (typeConverter != null && convertToDB) { _value = typeConverter.getDBValue(_value) } operation = when (_value) { is String, is IOperator<*>, is Char -> "$operation ${Operation.CONCATENATE} " is Number -> "$operation ${Operation.PLUS} " else -> throw IllegalArgumentException( "Cannot concatenate the ${if (_value != null) _value.javaClass else "null"}") } this.value = _value isValueSet = true return this } override fun concatenate(conditional: IConditional): Operator<T> = concatenate(conditional as Any) /** * Turns this condition into a SQL BETWEEN operation * * @param value The value of the first argument of the BETWEEN clause * @return Between operator */ override fun between(value: T): Between<T> = Between(this, value) @SafeVarargs override fun `in`(firstValue: T, vararg values: T): In<T> = In(this, firstValue, true, *values) @SafeVarargs override fun notIn(firstValue: T, vararg values: T): In<T> = In(this, firstValue, false, *values) override fun `in`(values: Collection<T>): In<T> = In(this, values, true) override fun notIn(values: Collection<T>): In<T> = In(this, values, false) override fun convertObjectToString(obj: Any?, appendInnerParenthesis: Boolean): String = (typeConverter as? TypeConverter<*, Any>?)?.let { typeConverter -> var converted = obj try { converted = if (convertToDB) typeConverter.getDBValue(obj) else obj } catch (c: ClassCastException) { // if object type is not valid converted type, just use type as is here. // if object type is not valid converted type, just use type as is here. FlowLog.log(FlowLog.Level.I, "Value passed to operation is not valid type" + " for TypeConverter in the column. Preserving value $obj to be used as is.") } convertValueToString(converted, appendInnerParenthesis, false) } ?: super.convertObjectToString(obj, appendInnerParenthesis) private fun assignValueOp(value: Any?, operation: String): Operator<T> { return if (!isValueSet) { this.operation = operation value(value) } else { convertToString = false // convert value to a string value because of conversion. value(convertValueToString(this.value) + operation + convertValueToString(value)) } } /** * Static constants that define condition operations */ object Operation { /** * Equals comparison */ const val EQUALS = "=" /** * Not-equals comparison */ const val NOT_EQUALS = "!=" /** * String concatenation */ const val CONCATENATE = "||" /** * Number addition */ const val PLUS = "+" /** * Number subtraction */ const val MINUS = "-" const val DIVISION = "/" const val MULTIPLY = "*" const val MOD = "%" /** * If something is LIKE another (a case insensitive search). * There are two wildcards: % and _ * % represents [0,many) numbers or characters. * The _ represents a single number or character. */ const val LIKE = "LIKE" /** * If the WHERE clause of the SELECT statement contains a sub-clause of the form "<column> MATCH ?", * FTS is able to use the built-in full-text index to restrict the search to those documents * that match the full-text query string specified as the right-hand operand of the MATCH clause. */ const val MATCH = "MATCH" /** * If something is NOT LIKE another (a case insensitive search). * There are two wildcards: % and _ * % represents [0,many) numbers or characters. * The _ represents a single number or character. */ const val NOT_LIKE = "NOT LIKE" /** * If something is case sensitive like another. * It must be a string to escape it properly. * There are two wildcards: * and ? * * represents [0,many) numbers or characters. * The ? represents a single number or character */ const val GLOB = "GLOB" /** * Greater than some value comparison */ const val GREATER_THAN = ">" /** * Greater than or equals to some value comparison */ const val GREATER_THAN_OR_EQUALS = ">=" /** * Less than some value comparison */ const val LESS_THAN = "<" /** * Less than or equals to some value comparison */ const val LESS_THAN_OR_EQUALS = "<=" /** * Between comparison. A simplification of X&lt;Y AND Y&lt;Z to Y BETWEEN X AND Z */ const val BETWEEN = "BETWEEN" /** * AND comparison separator */ const val AND = "AND" /** * OR comparison separator */ const val OR = "OR" /** * An empty value for the condition. */ @Deprecated(replaceWith = ReplaceWith( expression = "Property.WILDCARD", imports = ["com.dbflow5.query.Property"] ), message = "Deprecated. This will translate to '?' in the query as it get's SQL-escaped. " + "Use the Property.WILDCARD instead to get desired ? behavior.") const val EMPTY_PARAM = "?" /** * Special operation that specify if the column is not null for a specified row. Use of this as * an operator will ignore the value of the [Operator] for it. */ const val IS_NOT_NULL = "IS NOT NULL" /** * Special operation that specify if the column is null for a specified row. Use of this as * an operator will ignore the value of the [Operator] for it. */ const val IS_NULL = "IS NULL" /** * The SQLite IN command that will select rows that are contained in a list of values. * EX: SELECT * from Table where column IN ('first', 'second', etc) */ const val IN = "IN" /** * The reverse of the [.IN] command that selects rows that are not contained * in a list of values specified. */ const val NOT_IN = "NOT IN" } /** * The SQL BETWEEN operator that contains two values instead of the normal 1. */ class Between<T> /** * Creates a new instance * * @param operator * @param value The value of the first argument of the BETWEEN clause */ internal constructor(operator: Operator<T>, value: T) : BaseOperator(operator.nameAlias), Query { private var secondValue: T? = null override val query: String get() = appendToQuery() init { this.operation = " ${Operation.BETWEEN} " this.value = value isValueSet = true this.postArg = operator.postArgument() } infix fun and(secondValue: T?) = apply { this.secondValue = secondValue } fun secondValue(): T? = secondValue override fun appendConditionToQuery(queryBuilder: StringBuilder) { queryBuilder.append(columnName()).append(operation()) .append(convertObjectToString(value(), true)) .append(" ${Operation.AND} ") .append(convertObjectToString(secondValue(), true)) .append(" ") .appendOptional(postArgument()) } } /** * The SQL IN and NOT IN operator that specifies a list of values to SELECT rows from. * EX: SELECT * FROM myTable WHERE columnName IN ('column1','column2','etc') */ class In<T> : BaseOperator, Query { private val inArguments = arrayListOf<T?>() override val query: String get() = appendToQuery() /** * Creates a new instance * * @param operator The operator object to pass in. We only use the column name here. * @param firstArgument The first value in the IN query as one is required. * @param isIn if this is an [Operator.Operation.IN] * statement or a [Operator.Operation.NOT_IN] */ @SafeVarargs internal constructor(operator: Operator<T>, firstArgument: T?, isIn: Boolean, vararg arguments: T?) : super(operator.columnAlias()) { inArguments.add(firstArgument) inArguments.addAll(arguments) operation = " ${if (isIn) Operation.IN else Operation.NOT_IN} " } internal constructor(operator: Operator<T>, args: Collection<T>, isIn: Boolean) : super(operator.columnAlias()) { inArguments.addAll(args) operation = " ${if (isIn) Operation.IN else Operation.NOT_IN} " } /** * Appends another value to this In statement * * @param argument The non-type converted value of the object. The value will be converted * in a [OperatorGroup]. * @return */ infix fun and(argument: T?): In<T> { inArguments.add(argument) return this } override fun appendConditionToQuery(queryBuilder: StringBuilder) { queryBuilder.append(columnName()) .append(operation()) .append("(") .append(joinArguments(",", inArguments, this)) .append(")") } } companion object { @JvmStatic fun convertValueToString(value: Any?): String? = convertValueToString(value, false) @JvmStatic fun <T> op(column: NameAlias): Operator<T> = Operator(column, convertToDB = false) @JvmStatic fun <T> op(alias: NameAlias, table: Class<*>, getter: TypeConvertedProperty.TypeConverterGetter, convertToDB: Boolean): Operator<T> = Operator(alias, table, getter, convertToDB) } } fun <T : Any> NameAlias.op() = Operator.op<T>(this) fun <T : Any> String.op(): Operator<T> = nameAlias.op() infix fun <T : Any> Operator<T>.and(sqlOperator: SQLOperator): OperatorGroup = OperatorGroup.clause(this).and(sqlOperator) infix fun <T : Any> Operator<T>.or(sqlOperator: SQLOperator): OperatorGroup = OperatorGroup.clause(this).or(sqlOperator) infix fun <T : Any> Operator<T>.andAll(sqlOperator: Collection<SQLOperator>): OperatorGroup = OperatorGroup.clause(this).andAll(sqlOperator) infix fun <T : Any> Operator<T>.orAll(sqlOperator: Collection<SQLOperator>): OperatorGroup = OperatorGroup.clause(this).orAll(sqlOperator) infix fun <T : Any> Operator<T>.`in`(values: Array<T>): Operator.In<T> = when (values.size) { 1 -> `in`(values[0]) else -> this.`in`(values[0], *values.sliceArray(IntRange(1, values.size))) } infix fun <T : Any> Operator<T>.notIn(values: Array<T>): Operator.In<T> = when (values.size) { 1 -> notIn(values[0]) else -> this.notIn(values[0], *values.sliceArray(IntRange(1, values.size))) }
mit
b6b7f7943ecd8d0d9fc0943881e8deb5
34.424739
141
0.626825
4.483025
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/boxInline/nonLocalReturns/deparenthesize/bracket.kt
5
669
// FILE: 1.kt package test public inline fun <R> doCall(block: ()-> R) : R { return block() } // FILE: 2.kt import test.* fun test1(b: Boolean): String { val localResult = doCall ((local@ { if (b) { return@local "local" } else { return "nonLocal" } })) return "result=" + localResult; } fun test2(nonLocal: String): String { val localResult = doCall { return nonLocal } } fun box(): String { val test1 = test1(true) if (test1 != "result=local") return "test1: ${test1}" val test2 = test1(false) if (test2 != "nonLocal") return "test2: ${test2}" return "OK" }
apache-2.0
725f64439f98c4271399a8b2a125502c
16.153846
57
0.544096
3.263415
false
true
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/evaluate/parenthesized.kt
2
1314
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME @Retention(AnnotationRetention.RUNTIME) annotation class Ann( val p1: Byte, val p2: Short, val p3: Int, val p4: Long, val p5: Double, val p6: Float ) val prop1: Byte = (1 + 2) * 2 val prop2: Short = (1 + 2) * 2 val prop3: Int = (1 + 2) * 2 val prop4: Long = (1 + 2) * 2 val prop5: Double = (1.0 + 2) * 2 val prop6: Float = (1.toFloat() + 2) * 2 @Ann((1 + 2) * 2, (1 + 2) * 2, (1 + 2) * 2, (1 + 2) * 2, (1.0 + 2) * 2, (1.toFloat() + 2) * 2) class MyClass fun box(): String { val annotation = MyClass::class.java.getAnnotation(Ann::class.java)!! if (annotation.p1 != prop1) return "fail 1, expected = ${prop1}, actual = ${annotation.p1}" if (annotation.p2 != prop2) return "fail 2, expected = ${prop2}, actual = ${annotation.p2}" if (annotation.p3 != prop3) return "fail 3, expected = ${prop3}, actual = ${annotation.p3}" if (annotation.p4 != prop4) return "fail 4, expected = ${prop4}, actual = ${annotation.p4}" if (annotation.p5 != prop5) return "fail 5, expected = ${prop5}, actual = ${annotation.p5}" if (annotation.p6 != prop6) return "fail 6, expected = ${prop6}, actual = ${annotation.p6}" return "OK" }
apache-2.0
ce7df93a92d0c394f520abf929efa286
37.647059
108
0.593607
2.926503
false
false
false
false
Pozo/threejs-kotlin
threejs-dsl/src/main/kotlin/three/dsl/CoreDsl.kt
1
3014
package three import three.core.Object3D import three.lights.DirectionalLight import three.materials.Material import three.materials.MaterialColors import three.materials.basic.MeshBasicMaterial import three.materials.basic.MeshBasicMaterialParam import three.materials.phong.MeshPhongMaterial import three.materials.phong.MeshPhongMaterialParam import three.math.Color import three.objects.Mesh import three.scenes.Scene @DslMarker annotation class ThreejsDSL interface Object3DBuilder { fun build(): Object3D } @ThreejsDSL class MeshBuilder : Object3DBuilder { val objects = mutableListOf<Object3D>() var geometry: dynamic = null var material: dynamic = null var x: Double? = null var y: Double? = null var rotationX: Double? = null override fun build(): Object3D { val mesh = Mesh(geometry, material) x?.apply { mesh.position.x = x as Double } y?.apply { mesh.position.y = y as Double } rotationX?.apply { mesh.rotation.x = rotationX as Double } for (`object` in objects) { mesh.add(`object`) } return mesh } fun mesh(setup: MeshBuilder.() -> Unit = {}) { val meshBuilder = MeshBuilder() meshBuilder.setup() objects += meshBuilder.build() } } @ThreejsDSL class SceneBuilder { val objects = mutableListOf<Object3D>() var background: Int = 0 operator fun Object3D.unaryPlus() { objects += this } fun build(): Scene { val scene = Scene() scene.background = Color(background) for (`object` in objects) { scene.add(`object`) } return scene } @Suppress("UNUSED_PARAMETER") @Deprecated(level = DeprecationLevel.ERROR, message = "Scene can't be nested.") fun scene(param: () -> Unit = {}) { } fun mesh(setup: MeshBuilder.() -> Unit = {}) { val meshBuilder = MeshBuilder() meshBuilder.setup() objects += meshBuilder.build() } fun directionalLight(setup: DirectionalLightBuilder.() -> Unit = {}) { val meshBuilder = DirectionalLightBuilder() meshBuilder.setup() objects += meshBuilder.build() } } @ThreejsDSL class DirectionalLightBuilder : Object3DBuilder { var color: Int? = null var intensity: Float? = null var x: Float = 0f var y: Float = 0f var z: Float = 0f override fun build(): Object3D { val mesh = DirectionalLight() color?.apply { mesh.color = Color(color as Int) } intensity?.apply { mesh.intensity = intensity as Float } mesh.position.set(x, y, z) return mesh } @Suppress("UNUSED_PARAMETER") @Deprecated(level = DeprecationLevel.ERROR, message = "Directional Light can't be nested.") fun directionalLight(param: () -> Unit = {}) { } } fun scene(setup: SceneBuilder.() -> Unit): Scene { val sectionBuilder = SceneBuilder() sectionBuilder.setup() return sectionBuilder.build() }
mit
c4f0b32ac2dafa004308d98e5af49c28
22.364341
95
0.640013
4.095109
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/coroutines/DirectUseOfResultTypeInspection.kt
3
4331
// 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.coroutines import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.types.KotlinType class DirectUseOfResultTypeInspection : AbstractIsResultInspection( typeShortName = SHORT_NAME, typeFullName = "kotlin.Result", allowedSuffix = CATCHING, allowedNames = setOf("success", "failure", "runCatching"), suggestedFunctionNameToCall = "getOrThrow" ) { private fun MemberScope.hasCorrespondingNonCatchingFunction( nameWithoutCatching: String, valueParameters: List<ValueParameterDescriptor>, returnType: KotlinType?, extensionReceiverType: KotlinType? ): Boolean { val nonCatchingFunctions = getContributedFunctions(Name.identifier(nameWithoutCatching), NoLookupLocation.FROM_IDE) return nonCatchingFunctions.any { nonCatchingFun -> nonCatchingFun.valueParameters.size == valueParameters.size && nonCatchingFun.returnType == returnType && nonCatchingFun.extensionReceiverParameter?.type == extensionReceiverType } } private fun FunctionDescriptor.hasCorrespondingNonCatchingFunction(returnType: KotlinType, nameWithoutCatching: String): Boolean? { val containingDescriptor = containingDeclaration val scope = when (containingDescriptor) { is ClassDescriptor -> containingDescriptor.unsubstitutedMemberScope is PackageFragmentDescriptor -> containingDescriptor.getMemberScope() else -> return null } val returnTypeArgument = returnType.arguments.firstOrNull()?.type val extensionReceiverType = extensionReceiverParameter?.type if (scope.hasCorrespondingNonCatchingFunction(nameWithoutCatching, valueParameters, returnTypeArgument, extensionReceiverType)) { return true } if (extensionReceiverType != null) { val extensionClassDescriptor = extensionReceiverType.constructor.declarationDescriptor as? ClassDescriptor if (extensionClassDescriptor != null) { val extensionClassScope = extensionClassDescriptor.unsubstitutedMemberScope if (extensionClassScope.hasCorrespondingNonCatchingFunction( nameWithoutCatching, valueParameters, returnTypeArgument, extensionReceiverType = null ) ) { return true } } } return false } override fun analyzeFunctionWithAllowedSuffix( name: String, descriptor: FunctionDescriptor, toReport: PsiElement, holder: ProblemsHolder ) { val returnType = descriptor.returnType ?: return val nameWithoutCatching = name.substringBeforeLast(CATCHING) if (descriptor.hasCorrespondingNonCatchingFunction(returnType, nameWithoutCatching) == false) { val returnTypeArgument = returnType.arguments.firstOrNull()?.type val typeName = returnTypeArgument?.constructor?.declarationDescriptor?.name?.asString() ?: "T" holder.registerProblem( toReport, KotlinBundle.message( "function.0.returning.1.without.the.corresponding", name, "$SHORT_NAME<$typeName>", nameWithoutCatching, typeName ), ProblemHighlightType.GENERIC_ERROR_OR_WARNING ) } } } private const val SHORT_NAME = "Result" private const val CATCHING = "Catching"
apache-2.0
1c09bfdd0714cae36f0831fec3f956a1
44.589474
158
0.698915
6.082865
false
false
false
false
smmribeiro/intellij-community
uast/uast-common/src/org/jetbrains/uast/kinds/UastClassKind.kt
19
1175
/* * 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 org.jetbrains.uast /** * Kinds of [UClass]. */ open class UastClassKind(val text: String) { companion object { @JvmField val CLASS: UastClassKind = UastClassKind("class") @JvmField val INTERFACE: UastClassKind = UastClassKind("interface") @JvmField val ANNOTATION: UastClassKind = UastClassKind("annotation") @JvmField val ENUM: UastClassKind = UastClassKind("enum") @JvmField val OBJECT: UastClassKind = UastClassKind("object") } override fun toString(): String { return "UastClassKind(text='$text')" } }
apache-2.0
aab532e4d9321e327eb906bdbd7fc25a
26.348837
75
0.711489
4.181495
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/AnnotationClassConversion.kt
1
3001
// 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.nj2k.conversions import org.jetbrains.kotlin.j2k.ast.Nullability import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.toExpression import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.types.JKJavaArrayType import org.jetbrains.kotlin.nj2k.types.isArrayType import org.jetbrains.kotlin.nj2k.types.replaceJavaClassWithKotlinClassType import org.jetbrains.kotlin.nj2k.types.updateNullabilityRecursively class AnnotationClassConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKClass) return recurse(element) if (element.classKind != JKClass.ClassKind.ANNOTATION) return recurse(element) val javaAnnotationMethods = element.classBody.declarations .filterIsInstance<JKJavaAnnotationMethod>() val constructor = JKKtPrimaryConstructor( JKNameIdentifier(""), javaAnnotationMethods.map { it.asKotlinAnnotationParameter() }, JKStubExpression(), JKAnnotationList(), emptyList(), JKVisibilityModifierElement(Visibility.PUBLIC), JKModalityModifierElement(Modality.FINAL) ) element.modality = Modality.FINAL element.classBody.declarations += constructor element.classBody.declarations -= javaAnnotationMethods return recurse(element) } private fun JKJavaAnnotationMethod.asKotlinAnnotationParameter(): JKParameter { val type = returnType.type .updateNullabilityRecursively(Nullability.NotNull) .replaceJavaClassWithKotlinClassType(symbolProvider) val initializer = this::defaultValue.detached().toExpression(symbolProvider) val isVarArgs = type is JKJavaArrayType && name.value == "value" return JKParameter( JKTypeElement( if (!isVarArgs) type else (type as JKJavaArrayType).type ), JKNameIdentifier(name.value), isVarArgs = isVarArgs, initializer = if (type.isArrayType() && initializer !is JKKtAnnotationArrayInitializerExpression && initializer !is JKStubExpression ) { JKKtAnnotationArrayInitializerExpression(initializer) } else initializer, annotationList = this::annotationList.detached(), ).also { parameter -> if (trailingComments.any { it is JKComment }) { parameter.trailingComments += trailingComments } if (leadingComments.any { it is JKComment }) { parameter.leadingComments += leadingComments } } } }
apache-2.0
34f06ef6fb529a6b5e3ce8aed469b732
43.80597
158
0.682772
5.705323
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/configuration/libraryUtils.kt
5
1302
// 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.configuration import com.intellij.openapi.roots.libraries.Library class ExternalLibraryInfo( val artifactId: String, val version: String ) fun parseExternalLibraryName(library: Library): ExternalLibraryInfo? { val libName = library.name ?: return null val versionWithKind = libName.substringAfterLastNullable(":") ?: return null val version = versionWithKind.substringBefore("@") val artifactId = libName.substringBeforeLastNullable(":")?.substringAfterLastNullable(":") ?: return null if (version.isBlank() || artifactId.isBlank()) return null return ExternalLibraryInfo(artifactId, version) } private fun String.substringBeforeLastNullable(delimiter: String, missingDelimiterValue: String? = null): String? { val index = lastIndexOf(delimiter) return if (index == -1) missingDelimiterValue else substring(0, index) } private fun String.substringAfterLastNullable(delimiter: String, missingDelimiterValue: String? = null): String? { val index = lastIndexOf(delimiter) return if (index == -1) missingDelimiterValue else substring(index + 1, length) }
apache-2.0
9f6a6e8c87cd640d6ba9a61bf3670235
38.454545
158
0.758833
4.600707
false
false
false
false
Flank/flank
flank-scripts/src/main/kotlin/flank/scripts/cli/assemble/ios/TestPlansExample.kt
1
669
package flank.scripts.cli.assemble.ios import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.options.flag import com.github.ajalt.clikt.parameters.options.option import flank.scripts.ops.assemble.ios.buildTestPlansExample object TestPlansExample : CliktCommand( name = "test_plans", help = "Build ios test plans example app" ) { private val generate: Boolean? by option(help = "Make build") .flag("-g", default = true) private val copy: Boolean? by option(help = "Copy output files to tmp") .flag("-c", default = true) override fun run() { buildTestPlansExample(generate, copy) } }
apache-2.0
0c2aaefa3fbc1fa7743862dd0d0cef78
30.857143
75
0.713004
3.779661
false
true
false
false
serssp/reakt
todo/src/main/kotlin/todo/components/MainSection.kt
3
1299
package todo.components import com.github.andrewoma.react.* import todo.actions.TodoActions import todo.stores.Todo import todo.stores.areAllCompleted data class MainSectionProperties(val todos: Collection<Todo>) class MainSection : ComponentSpec<MainSectionProperties, Unit>() { companion object { val factory = react.createFactory(MainSection()) } override fun Component.render() { log.debug("MainSection.render", props) if (props.todos.size < 1) return section({ id = "main" }) { input({ id = "toggle-all" `type` = "checkbox" onChange = { onToggleCompleteAll() } checked = if ( props.todos.areAllCompleted() ) "checked" else "" }) label({ htmlFor = "toggle-all" }) { text("Mark all as complete") } ul({ id = "todo-list" }) { for (todo in props.todos) { todoItem(TodoItemProperties(key = todo.id, todo = todo)) } } } } fun onToggleCompleteAll() { TodoActions.toggleCompleteAll(null) } } fun Component.todoMainSection(props: MainSectionProperties): Component { return constructAndInsert(Component({ MainSection.factory(Ref(props)) })) }
mit
fa5950c915b272fa9ee03c2281099e3c
27.888889
80
0.594303
4.35906
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/blocks/GetLightDirectionFromFragPos.kt
1
1086
package de.fabmax.kool.modules.ksl.blocks import de.fabmax.kool.modules.ksl.lang.* import de.fabmax.kool.scene.Light class GetLightDirectionFromFragPos(parentScope: KslScopeBuilder) : KslFunction<KslTypeFloat3>(FUNC_NAME, KslTypeFloat3, parentScope.parentStage) { init { val fragPos = paramFloat3("fragPos") val encLightPos = paramFloat4("encLightPos") body { val dir = float3Var() `if` (encLightPos.w eq Light.Type.DIRECTIONAL.encoded.const) { dir set encLightPos.xyz * -(1f.const) }.`else` { dir set encLightPos.xyz - fragPos } return@body dir } } companion object { const val FUNC_NAME = "getLightDirectionFromFragPos" } } fun KslScopeBuilder.getLightDirectionFromFragPos( fragPos: KslExprFloat3, encodedLightPos: KslExprFloat4 ): KslExprFloat3 { val func = parentStage.getOrCreateFunction(GetLightDirectionFromFragPos.FUNC_NAME) { GetLightDirectionFromFragPos(this) } return func(fragPos, encodedLightPos) }
apache-2.0
9d137a925f0f8d9bd53574d4a62b3f0c
30.028571
125
0.672192
3.851064
false
false
false
false
kohesive/kohesive-iac
model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredAmazonCloudFormation.kt
1
1353
package uy.kohesive.iac.model.aws.clients import com.amazonaws.services.cloudformation.AbstractAmazonCloudFormation import com.amazonaws.services.cloudformation.AmazonCloudFormation import com.amazonaws.services.cloudformation.model.* import uy.kohesive.iac.model.aws.IacContext import uy.kohesive.iac.model.aws.proxy.makeProxy open class BaseDeferredAmazonCloudFormation(val context: IacContext) : AbstractAmazonCloudFormation(), AmazonCloudFormation { override fun createChangeSet(request: CreateChangeSetRequest): CreateChangeSetResult { return with (context) { request.registerWithAutoName() makeProxy<CreateChangeSetRequest, CreateChangeSetResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun createStack(request: CreateStackRequest): CreateStackResult { return with (context) { request.registerWithAutoName() makeProxy<CreateStackRequest, CreateStackResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } } class DeferredAmazonCloudFormation(context: IacContext) : BaseDeferredAmazonCloudFormation(context)
mit
2e3b5427d6a2408bd6fc3010b094bc4f
36.583333
125
0.693274
5.326772
false
true
false
false
kohesive/kohesive-iac
cloudtrail-tool/src/test/kotlin/uy/kohesive/iac/model/aws/cloudtrail/SmokeTest.kt
1
1776
package uy.kohesive.iac.model.aws.cloudtrail import uy.kohesive.iac.model.aws.codegen.AWSModelProvider import uy.kohesive.iac.model.aws.codegen.TemplateDescriptor import java.io.File fun main(args: Array<String>) { val packageName = "uy.kohesive.iac.model.aws.cloudtrail.test4" val outputDir = File("/Users/eliseyev/TMP/codegen/runners/", packageName.replace('.', '/')).apply { mkdirs() } val awsModelProvider = AWSModelProvider() var counter = 0 FileSystemEventsProcessor( // eventsDir = File("/Users/eliseyev/Downloads/CloudTrail2/us-east-1/2017/02/16/"), // eventsDir = File("/Users/eliseyev/Downloads/CloudTrail/"), eventsDir = File("/Users/eliseyev/TMP/cloudtrail/"), // eventsDir = File("/Users/eliseyev/Downloads/BadCloudTrail/"), oneEventPerFile = true, gzipped = false ).process { event -> if (listOf("Create", "Put", "Attach", "Run", "Set").any { event.eventName.startsWith(it) }) { val serviceName = event.eventSource.split('.').first() val awsModel = try { awsModelProvider.getModel(serviceName, event.apiVersion) } catch (t: Throwable) { throw RuntimeException("Can't obtain an AWS model for $event", t) } val className = "${event.eventName}Runner_${counter++}" val classContent = AWSApiCallBuilder( intermediateModel = awsModel, event = event, packageName = packageName, className = className ).build(TemplateDescriptor.RequestRunner) File(outputDir, "$className.kt").writeText(classContent) } }.forEach { } }
mit
dd69f0ca55849bf0a2603266d19c423c
41.285714
116
0.603041
4.238663
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/inference/nullability/NullabilityConstraintsCollector.kt
2
3523
// 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.j2k.post.processing.inference.nullability import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isNullExpression import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.* import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.collectors.ConstraintsCollector import org.jetbrains.kotlin.psi.* class NullabilityConstraintsCollector : ConstraintsCollector() { override fun ConstraintBuilder.collectConstraints( element: KtElement, boundTypeCalculator: BoundTypeCalculator, inferenceContext: InferenceContext, resolutionFacade: ResolutionFacade ) { when { element is KtBinaryExpression && (element.left?.isNullExpression() == true || element.right?.isNullExpression() == true) -> { val notNullOperand = if (element.left?.isNullExpression() == true) element.right else element.left notNullOperand?.isTheSameTypeAs(org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.UPPER, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.COMPARE_WITH_NULL) } element is KtQualifiedExpression -> { element.receiverExpression.isTheSameTypeAs(org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER) } element is KtForExpression -> { element.loopRange?.isTheSameTypeAs(org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER) } element is KtWhileExpressionBase -> { element.condition?.isTheSameTypeAs(org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER) } element is KtIfExpression -> { element.condition?.isTheSameTypeAs(org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER) } element is KtValueArgument && element.isSpread -> { element.getArgumentExpression()?.isTheSameTypeAs( org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER) } element is KtBinaryExpression && !KtPsiUtil.isAssignment(element) -> { element.left?.isTheSameTypeAs(org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER) element.right?.isTheSameTypeAs(org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.State.LOWER, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.USE_AS_RECEIVER) } } } }
apache-2.0
74f8560eebc31c66bb6d2c9830232839
66.769231
233
0.720409
4.448232
false
false
false
false
leafclick/intellij-community
plugins/gradle/java/src/service/resolve/GradleMiscContributor.kt
1
5658
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.service.resolve import com.intellij.patterns.PsiJavaPatterns.psiElement import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.ResolveState import com.intellij.psi.scope.PsiScopeProcessor import groovy.lang.Closure import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.* import org.jetbrains.plugins.groovy.lang.psi.GroovyFile import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder import org.jetbrains.plugins.groovy.lang.psi.patterns.GroovyClosurePattern import org.jetbrains.plugins.groovy.lang.psi.patterns.groovyClosure import org.jetbrains.plugins.groovy.lang.psi.patterns.psiMethod import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_CLOSURE import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DELEGATES_TO_TYPE_KEY import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DelegatesToInfo /** * @author Vladislav.Soroka */ class GradleMiscContributor : GradleMethodContextContributor { companion object { val useJUnitClosure: GroovyClosurePattern = groovyClosure().inMethod(psiMethod(GRADLE_API_TASKS_TESTING_TEST, "useJUnit")) val testLoggingClosure: GroovyClosurePattern = groovyClosure().inMethod(psiMethod(GRADLE_API_TASKS_TESTING_TEST, "testLogging")) val downloadClosure: GroovyClosurePattern = groovyClosure().inMethod(psiMethod(GRADLE_API_PROJECT, "download")) val domainCollectionWithTypeClosure: GroovyClosurePattern = groovyClosure().inMethod(psiMethod(GRADLE_API_DOMAIN_OBJECT_COLLECTION, "withType")) val manifestClosure: GroovyClosurePattern = groovyClosure().inMethod(psiMethod(GRADLE_JVM_TASKS_JAR, "manifest")) // val publicationsClosure = groovyClosure().inMethod(psiMethod("org.gradle.api.publish.PublishingExtension", "publications")) const val downloadSpecFqn: String = "de.undercouch.gradle.tasks.download.DownloadSpec" const val pluginDependenciesSpecFqn: String = "org.gradle.plugin.use.PluginDependenciesSpec" } override fun getDelegatesToInfo(closure: GrClosableBlock): DelegatesToInfo? { if (useJUnitClosure.accepts(closure)) { return DelegatesToInfo(createType(GRADLE_API_JUNIT_OPTIONS, closure), Closure.DELEGATE_FIRST) } if (testLoggingClosure.accepts(closure)) { return DelegatesToInfo(createType(GRADLE_API_TEST_LOGGING_CONTAINER, closure), Closure.DELEGATE_FIRST) } if (downloadClosure.accepts(closure)) { return DelegatesToInfo(createType(downloadSpecFqn, closure), Closure.DELEGATE_FIRST) } if (manifestClosure.accepts(closure)) { return DelegatesToInfo(createType(GRADLE_API_JAVA_ARCHIVES_MANIFEST, closure), Closure.DELEGATE_FIRST) } // if (publicationsClosure.accepts(closure)) { // return DelegatesToInfo(TypesUtil.createType("org.gradle.api.publish.PublicationContainer", closure), Closure.DELEGATE_FIRST) // } val parent = closure.parent if (domainCollectionWithTypeClosure.accepts(closure)) { if (parent is GrMethodCallExpression) { val psiElement = parent.argumentList.allArguments.singleOrNull()?.reference?.resolve() if (psiElement is PsiClass) { return DelegatesToInfo(createType(psiElement.qualifiedName, closure), Closure.DELEGATE_FIRST) } } } // resolve closure type to delegate based on return method type, e.g. // FlatDirectoryArtifactRepository flatDir(Closure configureClosure) if (parent is GrMethodCall) { parent.resolveMethod()?.returnType?.let { type -> return DelegatesToInfo(type, Closure.DELEGATE_FIRST) } } return null } override fun process(methodCallInfo: MutableList<String>, processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { val classHint = processor.getHint(com.intellij.psi.scope.ElementClassHint.KEY) val shouldProcessMethods = ResolveUtil.shouldProcessMethods(classHint) val groovyPsiManager = GroovyPsiManager.getInstance(place.project) val resolveScope = place.resolveScope if (shouldProcessMethods && place.parent?.parent is GroovyFile && place.text == "plugins") { val pluginsDependenciesClass = JavaPsiFacade.getInstance(place.project).findClass(pluginDependenciesSpecFqn, resolveScope) ?: return true val returnClass = groovyPsiManager.createTypeByFQClassName(pluginDependenciesSpecFqn, resolveScope) ?: return true val methodBuilder = GrLightMethodBuilder(place.manager, "plugins").apply { containingClass = pluginsDependenciesClass returnType = returnClass } methodBuilder.addAndGetParameter("configuration", GROOVY_LANG_CLOSURE).putUserData(DELEGATES_TO_TYPE_KEY, pluginDependenciesSpecFqn) if (!processor.execute(methodBuilder, state)) return false } if (psiElement().inside(domainCollectionWithTypeClosure).accepts(place)) { } return true } }
apache-2.0
90b9d2088d4651e87e0299416eb7a859
53.932039
148
0.77766
4.637705
false
true
false
false
josecefe/Rueda
src/es/um/josecefe/rueda/util/Combinatoria.kt
1
1643
/* * Copyright (c) 2016-2017. Jose Ceferino Ortega Carretero * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package es.um.josecefe.rueda.util import java.util.* tailrec fun factorial(n: Long, a: Long = 1): Long = if (n <= 1) a else factorial(n - 1, a * n) fun permutations(n: Long, r: Long): Long = factorial(n) / factorial(n - r) fun combinations(n: Long, r: Long): Long = permutations(n, r) / factorial(r) fun <T> cartesianProduct(lists: List<List<T>>): List<List<T>> { val resultLists = ArrayList<List<T>>() if (lists.isEmpty()) { resultLists.add(emptyList()) return resultLists } else { val firstList = lists[0] val remainingLists = cartesianProduct(lists.subList(1, lists.size)) for (condition in firstList) { for (remainingList in remainingLists) { val resultList = ArrayList<T>() resultList.add(condition) resultList.addAll(remainingList) resultLists.add(resultList) } } } return resultLists }
gpl-3.0
ff5be9e9c35cf4a99823490a5a9c6bec
42.263158
242
0.671942
4.026961
false
false
false
false
allotria/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/SimpleToolWindowWithTwoToolbarsPanel.kt
1
2740
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels import com.intellij.openapi.actionSystem.ActionToolbar import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.DataProvider import com.intellij.ui.JBColor import com.intellij.ui.switcher.QuickActionProvider import com.intellij.util.ui.UIUtil import java.awt.BorderLayout import java.awt.Container import java.awt.Graphics import java.awt.event.ContainerAdapter import java.awt.event.ContainerEvent import javax.swing.JComponent import javax.swing.JPanel import org.jetbrains.annotations.NonNls class SimpleToolWindowWithTwoToolbarsPanel( val leftToolbar: JComponent, val topToolbar: JComponent, val content: JComponent ) : JPanel(), QuickActionProvider, DataProvider { private var myProvideQuickActions: Boolean = false init { layout = BorderLayout(1, 1) myProvideQuickActions = true addContainerListener(object : ContainerAdapter() { override fun componentAdded(e: ContainerEvent?) { val child = e!!.child if (child is Container) { child.addContainerListener(this) } } override fun componentRemoved(e: ContainerEvent?) { val child = e!!.child if (child is Container) { child.removeContainerListener(this) } } }) add(leftToolbar, BorderLayout.WEST) add(JPanel(BorderLayout()).apply { add(topToolbar, BorderLayout.NORTH) add(content, BorderLayout.CENTER) }, BorderLayout.CENTER) revalidate() repaint() } override fun getData(@NonNls dataId: String) = when { QuickActionProvider.KEY.`is`(dataId) && myProvideQuickActions -> this else -> null } override fun getActions(originalProvider: Boolean): List<AnAction> { val actions = ArrayList<AnAction>() actions.addAll(extractActions(topToolbar)) actions.addAll(extractActions(leftToolbar)) return actions } override fun getComponent(): JComponent? { return this } override fun paintComponent(g: Graphics) { super.paintComponent(g) val x = leftToolbar.bounds.maxX.toInt() val y = topToolbar.bounds.maxY.toInt() g.apply { color = JBColor.border() drawLine(0, y, width, y) drawLine(x, 0, x, height) } } fun extractActions(c: JComponent): List<AnAction> = UIUtil.uiTraverser(c) .traverse() .filter(ActionToolbar::class.java) .flatten { toolbar -> toolbar.actions } .toList() }
apache-2.0
b3e8f9f9cf9b2fd9582cde3aff5e7a0f
30.860465
77
0.64708
4.732297
false
false
false
false
androidx/androidx
core/core-remoteviews/src/androidTest/java/androidx/core/widget/RemoteViewsCompatTest.kt
3
16973
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.widget import android.Manifest.permission import android.app.PendingIntent import android.app.UiAutomation import android.appwidget.AppWidgetHostView import android.appwidget.AppWidgetManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Build import android.os.Parcel import android.view.View import android.view.ViewGroup import android.view.ViewTreeObserver.OnDrawListener import android.widget.Adapter import android.widget.ListView import android.widget.RemoteViews import android.widget.TextView import androidx.core.remoteviews.test.R import androidx.core.widget.RemoteViewsCompat.RemoteCollectionItems import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import androidx.test.platform.app.InstrumentationRegistry import com.google.common.truth.Truth.assertThat import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import kotlin.test.assertFailsWith import kotlin.test.fail @SdkSuppress(minSdkVersion = 29) @MediumTest public class RemoteViewsCompatTest { private val mUsingBackport = Build.VERSION.SDK_INT <= Build.VERSION_CODES.S private val mContext = ApplicationProvider.getApplicationContext<Context>() private val mPackageName = mContext.packageName private val mAppWidgetManager = AppWidgetManager.getInstance(mContext) @Rule @JvmField public val mActivityTestRule: ActivityScenarioRule<AppWidgetHostTestActivity> = ActivityScenarioRule(AppWidgetHostTestActivity::class.java) private lateinit var mRemoteViews: RemoteViews private lateinit var mHostView: AppWidgetHostView private var mAppWidgetId = 0 private val mUiAutomation: UiAutomation get() = InstrumentationRegistry.getInstrumentation().uiAutomation private val mListView: ListView get() = mHostView.getChildAt(0) as ListView @Before public fun setUp() { mUiAutomation.adoptShellPermissionIdentity(permission.BIND_APPWIDGET) mActivityTestRule.scenario.onActivity { activity -> mHostView = activity.bindAppWidget() } mAppWidgetId = mHostView.appWidgetId mRemoteViews = RemoteViews(mPackageName, R.layout.remote_views_list) mAppWidgetManager.updateAppWidget(mAppWidgetId, mRemoteViews) // Wait until the remote views has been added to the host view. observeDrawUntil { mHostView.childCount > 0 } } @After public fun tearDown() { mUiAutomation.dropShellPermissionIdentity() } @Test public fun testParcelingAndUnparceling() { val items = RemoteCollectionItems.Builder() .setHasStableIds(true) .setViewTypeCount(10) .addItem(id = 3, RemoteViews(mPackageName, R.layout.list_view_row)) .addItem(id = 5, RemoteViews(mPackageName, R.layout.list_view_row2)) .build() val parcel = Parcel.obtain() val unparceled = try { items.writeToParcel(parcel, /* flags= */ 0) parcel.setDataPosition(0) RemoteCollectionItems(parcel) } finally { parcel.recycle() } assertThat(unparceled.itemCount).isEqualTo(2) assertThat(unparceled.getItemId(0)).isEqualTo(3) assertThat(unparceled.getItemId(1)).isEqualTo(5) assertThat(unparceled.getItemView(0).layoutId).isEqualTo(R.layout.list_view_row) assertThat(unparceled.getItemView(1).layoutId).isEqualTo(R.layout.list_view_row2) assertThat(unparceled.hasStableIds()).isTrue() assertThat(unparceled.viewTypeCount).isEqualTo(10) } @Test public fun testBuilder_empty() { val items = RemoteCollectionItems.Builder().build() assertThat(items.itemCount).isEqualTo(0) assertThat(items.viewTypeCount).isEqualTo(1) assertThat(items.hasStableIds()).isFalse() } @Test public fun testBuilder_viewTypeCountUnspecified() { val firstItem = RemoteViews(mPackageName, R.layout.list_view_row) val secondItem = RemoteViews(mPackageName, R.layout.list_view_row2) val items = RemoteCollectionItems.Builder() .setHasStableIds(true) .addItem(id = 3, firstItem) .addItem(id = 5, secondItem) .build() assertThat(items.itemCount).isEqualTo(2) assertThat(items.getItemId(0)).isEqualTo(3) assertThat(items.getItemId(1)).isEqualTo(5) assertThat(items.getItemView(0).layoutId).isEqualTo(R.layout.list_view_row) assertThat(items.getItemView(1).layoutId).isEqualTo(R.layout.list_view_row2) assertThat(items.hasStableIds()).isTrue() // The view type count should be derived from the number of different layout ids if // unspecified. assertThat(items.viewTypeCount).isEqualTo(2) } @Test public fun testBuilder_viewTypeCountSpecified() { val firstItem = RemoteViews(mPackageName, R.layout.list_view_row) val secondItem = RemoteViews(mPackageName, R.layout.list_view_row2) val items = RemoteCollectionItems.Builder() .addItem(id = 3, firstItem) .addItem(id = 5, secondItem) .setViewTypeCount(15) .build() assertThat(items.viewTypeCount).isEqualTo(15) } @Test public fun testBuilder_repeatedIdsAndLayouts() { val firstItem = RemoteViews(mPackageName, R.layout.list_view_row) val secondItem = RemoteViews(mPackageName, R.layout.list_view_row) val thirdItem = RemoteViews(mPackageName, R.layout.list_view_row) val items = RemoteCollectionItems.Builder() .setHasStableIds(false) .addItem(id = 42, firstItem) .addItem(id = 42, secondItem) .addItem(id = 42, thirdItem) .build() assertThat(items.itemCount).isEqualTo(3) assertThat(items.getItemId(0)).isEqualTo(42) assertThat(items.getItemId(1)).isEqualTo(42) assertThat(items.getItemId(2)).isEqualTo(42) assertThat(items.getItemView(0)).isSameInstanceAs(firstItem) assertThat(items.getItemView(1)).isSameInstanceAs(secondItem) assertThat(items.getItemView(2)).isSameInstanceAs(thirdItem) assertThat(items.hasStableIds()).isFalse() assertThat(items.viewTypeCount).isEqualTo(1) } @Test public fun testBuilder_viewTypeCountLowerThanLayoutCount() { assertFailsWith(IllegalArgumentException::class) { RemoteCollectionItems.Builder() .setHasStableIds(true) .setViewTypeCount(1) .addItem(3, RemoteViews(mPackageName, R.layout.list_view_row)) .addItem(5, RemoteViews(mPackageName, R.layout.list_view_row2)) .build() } } @Test public fun testServiceIntent_hasSameUriForSameIds() { val intent1 = RemoteViewsCompatService.createIntent(mContext, appWidgetId = 1, viewId = 42) val intent2 = RemoteViewsCompatService.createIntent(mContext, appWidgetId = 1, viewId = 42) assertThat(intent1.data).isEqualTo(intent2.data) } @Test public fun testServiceIntent_hasDifferentUriForDifferentWidgetIds() { val intent1 = RemoteViewsCompatService.createIntent(mContext, appWidgetId = 1, viewId = 42) val intent2 = RemoteViewsCompatService.createIntent(mContext, appWidgetId = 2, viewId = 42) assertThat(intent1.data).isNotEqualTo(intent2.data) } @Test public fun testServiceIntent_hasDifferentUriForDifferentViewIds() { val intent1 = RemoteViewsCompatService.createIntent(mContext, appWidgetId = 1, viewId = 42) val intent2 = RemoteViewsCompatService.createIntent(mContext, appWidgetId = 1, viewId = 43) assertThat(intent1.data).isNotEqualTo(intent2.data) } @Test public fun testSetRemoteAdapter_emptyCollection() { val items = RemoteCollectionItems.Builder().build() RemoteViewsCompat.setRemoteAdapter( mContext, mRemoteViews, mAppWidgetId, R.id.list_view, items ) mAppWidgetManager.updateAppWidget(mAppWidgetId, mRemoteViews) observeDrawUntil { mListView.adapter != null } assertThat(mListView.childCount).isEqualTo(0) assertThat(mListView.adapter.count).isEqualTo(0) assertThat(mListView.adapter.viewTypeCount).isAtLeast(1) assertThat(mListView.adapter.hasStableIds()).isFalse() } @Test public fun testSetRemoteAdapter_withItems() { val items = RemoteCollectionItems.Builder() .setHasStableIds(true) .addItem(id = 10, createTextRow("Hello")) .addItem(id = 11, createTextRow("World")) .build() RemoteViewsCompat.setRemoteAdapter( mContext, mRemoteViews, mAppWidgetId, R.id.list_view, items ) mAppWidgetManager.updateAppWidget(mAppWidgetId, mRemoteViews) observeDrawUntil { mListView.adapter != null && mListView.childCount == 2 } val adapter = mListView.adapter assertThat(adapter.count).isEqualTo(2) assertThat(adapter.getItemViewType(1)).isEqualTo(adapter.getItemViewType(0)) assertThat(adapter.getItemId(0)).isEqualTo(10) assertThat(adapter.getItemId(1)).isEqualTo(11) assertThat(mListView.adapter.hasStableIds()).isTrue() assertThat(mListView.childCount).isEqualTo(2) assertThat(getListChildAt<TextView>(0).text.toString()).isEqualTo("Hello") assertThat(getListChildAt<TextView>(1).text.toString()).isEqualTo("World") } @Test public fun testSetRemoteAdapter_clickListener() { val action = "my-action" val receiver = TestBroadcastReceiver() mContext.registerReceiver(receiver, IntentFilter(action)) val pendingIntent = PendingIntent.getBroadcast( mContext, 0, Intent(action).setPackage(mPackageName), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE ) mRemoteViews.setPendingIntentTemplate(R.id.list_view, pendingIntent) val item2 = RemoteViews(mPackageName, R.layout.list_view_row2) item2.setTextViewText(R.id.text, "Clickable") item2.setOnClickFillInIntent(R.id.text, Intent().putExtra("my-extra", 42)) val items = RemoteCollectionItems.Builder() .setHasStableIds(true) .addItem(id = 10, createTextRow("Hello")) .addItem(id = 11, createTextRow("World")) .addItem(id = 12, createTextRow("Mundo")) .addItem(id = 13, item2) .build() RemoteViewsCompat.setRemoteAdapter( mContext, mRemoteViews, mAppWidgetId, R.id.list_view, items ) mAppWidgetManager.updateAppWidget(mAppWidgetId, mRemoteViews) observeDrawUntil { mListView.adapter != null && mListView.childCount == 4 } val adapter: Adapter = mListView.adapter assertThat(adapter.count).isEqualTo(4) assertThat(adapter.getItemViewType(0)).isEqualTo(adapter.getItemViewType(1)) assertThat(adapter.getItemViewType(0)).isEqualTo(adapter.getItemViewType(2)) assertThat(adapter.getItemViewType(0)).isNotEqualTo(adapter.getItemViewType(3)) assertThat(adapter.getItemId(0)).isEqualTo(10) assertThat(adapter.getItemId(1)).isEqualTo(11) assertThat(adapter.getItemId(2)).isEqualTo(12) assertThat(adapter.getItemId(3)).isEqualTo(13) assertThat(adapter.hasStableIds()).isTrue() assertThat(mListView.childCount).isEqualTo(4) val textView2 = getListChildAt<ViewGroup>(3).getChildAt(0) as TextView assertThat(getListChildAt<TextView>(0).text.toString()).isEqualTo("Hello") assertThat(getListChildAt<TextView>(1).text.toString()).isEqualTo("World") assertThat(getListChildAt<TextView>(2).text.toString()).isEqualTo("Mundo") assertThat(textView2.text.toString()).isEqualTo("Clickable") // View being clicked should launch the intent. val receiverIntent = receiver.runAndAwaitIntentReceived { textView2.performClick() } assertThat(receiverIntent.getIntExtra("my-extra", 0)).isEqualTo(42) mContext.unregisterReceiver(receiver) } @Test public fun testSetRemoteAdapter_multipleCalls() { var items = RemoteCollectionItems.Builder() .setHasStableIds(true) .addItem(id = 10, createTextRow("Hello")) .addItem(id = 11, createTextRow("World")) .build() RemoteViewsCompat.setRemoteAdapter( mContext, mRemoteViews, mAppWidgetId, R.id.list_view, items ) mAppWidgetManager.updateAppWidget(mAppWidgetId, mRemoteViews) observeDrawUntil { mListView.adapter != null && mListView.childCount == 2 } items = RemoteCollectionItems.Builder() .setHasStableIds(true) .addItem(id = 20, createTextRow("Bonjour")) .addItem(id = 21, createTextRow("le")) .addItem(id = 22, createTextRow("monde")) .build() RemoteViewsCompat.setRemoteAdapter( mContext, mRemoteViews, mAppWidgetId, R.id.list_view, items ) mAppWidgetManager.updateAppWidget(mAppWidgetId, mRemoteViews) observeDrawUntil { mListView.childCount == 3 } val adapter: Adapter = mListView.adapter assertThat(adapter.count).isEqualTo(3) assertThat(adapter.getItemId(0)).isEqualTo(20) assertThat(adapter.getItemId(1)).isEqualTo(21) assertThat(adapter.getItemId(2)).isEqualTo(22) assertThat(mListView.childCount).isEqualTo(3) assertThat(getListChildAt<TextView>(0).text.toString()).isEqualTo("Bonjour") assertThat(getListChildAt<TextView>(1).text.toString()).isEqualTo("le") assertThat(getListChildAt<TextView>(2).text.toString()).isEqualTo("monde") } private fun createTextRow(text: String): RemoteViews { return RemoteViews(mPackageName, R.layout.list_view_row) .also { it.setTextViewText(R.id.text, text) } } private fun observeDrawUntil(test: () -> Boolean) { val latch = CountDownLatch(1) val onDrawListener = OnDrawListener { if (test()) latch.countDown() } mActivityTestRule.scenario.onActivity { mHostView.viewTreeObserver.addOnDrawListener(onDrawListener) } val countedDown = latch.await(5, TimeUnit.SECONDS) mActivityTestRule.scenario.onActivity { mHostView.viewTreeObserver.removeOnDrawListener(onDrawListener) } if (!countedDown && !test()) { fail("Expected condition to be met within 5 seconds") } } @Suppress("UNCHECKED_CAST") private fun <V : View> getListChildAt(position: Int): V { return if (mUsingBackport) { // When using RemoteViewsAdapter, an extra wrapper FrameLayout is added. (mListView.getChildAt(position) as ViewGroup).getChildAt(0) as V } else { mListView.getChildAt(position) as V } } private inner class TestBroadcastReceiver : BroadcastReceiver() { private lateinit var mCountDownLatch: CountDownLatch private var mIntent: Intent? = null override fun onReceive(context: Context, intent: Intent) { mIntent = intent mCountDownLatch.countDown() } fun runAndAwaitIntentReceived(runnable: () -> Unit): Intent { mCountDownLatch = CountDownLatch(1) mActivityTestRule.scenario.onActivity { runnable() } mCountDownLatch.await(5, TimeUnit.SECONDS) return mIntent ?: fail("Expected intent to be received within five seconds") } } }
apache-2.0
1a4f1cc035c5fc3768a6a2580003e2bf
37.577273
99
0.675072
4.645047
false
true
false
false
androidx/androidx
glance/glance/src/androidMain/kotlin/androidx/glance/layout/Padding.kt
3
8609
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.glance.layout import android.content.res.Resources import androidx.annotation.DimenRes import androidx.annotation.RestrictTo import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.glance.GlanceModifier /** * Apply additional space along each edge of the content in [Dp]: [start], [top], [end] and * [bottom]. The start and end edges will be determined by layout direction of the current locale. * Padding is applied before content measurement and takes precedence; content may only be as large * as the remaining space. * * If any value is not defined, it will be [0.dp] or whatever value was defined by an earlier * modifier. */ fun GlanceModifier.padding( start: Dp = 0.dp, top: Dp = 0.dp, end: Dp = 0.dp, bottom: Dp = 0.dp, ): GlanceModifier = this.then( PaddingModifier( start = start.toPadding(), top = top.toPadding(), end = end.toPadding(), bottom = bottom.toPadding(), ) ) /** * Apply additional space along each edge of the content in [Dp]: [start], [top], [end] and * [bottom]. The start and end edges will be determined by layout direction of the current locale. * Padding is applied before content measurement and takes precedence; content may only be as large * as the remaining space. * * If any value is not defined, it will be [0.dp] or whatever value was defined by an earlier * modifier. */ fun GlanceModifier.padding( @DimenRes start: Int = 0, @DimenRes top: Int = 0, @DimenRes end: Int = 0, @DimenRes bottom: Int = 0 ): GlanceModifier = this.then( PaddingModifier( start = start.toPadding(), top = top.toPadding(), end = end.toPadding(), bottom = bottom.toPadding(), ) ) /** * Apply [horizontal] dp space along the left and right edges of the content, and [vertical] dp * space along the top and bottom edges. * * If any value is not defined, it will be [0.dp] or whatever value was defined by an earlier * modifier. */ fun GlanceModifier.padding( horizontal: Dp = 0.dp, vertical: Dp = 0.dp, ): GlanceModifier = this.then( PaddingModifier( start = horizontal.toPadding(), top = vertical.toPadding(), end = horizontal.toPadding(), bottom = vertical.toPadding(), ) ) /** * Apply [horizontal] dp space along the left and right edges of the content, and [vertical] dp * space along the top and bottom edges. * * If any value is not defined, it will be [0.dp] or whatever value was defined by an earlier * modifier. */ fun GlanceModifier.padding( @DimenRes horizontal: Int = 0, @DimenRes vertical: Int = 0 ): GlanceModifier = this.then( PaddingModifier( start = horizontal.toPadding(), top = vertical.toPadding(), end = horizontal.toPadding(), bottom = vertical.toPadding(), ) ) /** * Apply [all] dp of additional space along each edge of the content, left, top, right and bottom. */ fun GlanceModifier.padding(all: Dp): GlanceModifier { val allDp = all.toPadding() return this.then( PaddingModifier( start = allDp, top = allDp, end = allDp, bottom = allDp, ) ) } /** * Apply [all] dp of additional space along each edge of the content, left, top, right and bottom. */ fun GlanceModifier.padding(@DimenRes all: Int): GlanceModifier { val allDp = all.toPadding() return this.then( PaddingModifier( start = allDp, top = allDp, end = allDp, bottom = allDp, ) ) } /** * Apply additional space along each edge of the content in [Dp]: [left], [top], [right] and * [bottom], ignoring the current locale's layout direction. */ fun GlanceModifier.absolutePadding( left: Dp = 0.dp, top: Dp = 0.dp, right: Dp = 0.dp, bottom: Dp = 0.dp, ): GlanceModifier = this.then( PaddingModifier( left = left.toPadding(), top = top.toPadding(), right = right.toPadding(), bottom = bottom.toPadding(), ) ) /** * Apply additional space along each edge of the content in [Dp]: [left], [top], [right] and * [bottom], ignoring the current locale's layout direction. */ fun GlanceModifier.absolutePadding( @DimenRes left: Int = 0, @DimenRes top: Int = 0, @DimenRes right: Int = 0, @DimenRes bottom: Int = 0 ): GlanceModifier = this.then( PaddingModifier( left = left.toPadding(), top = top.toPadding(), right = right.toPadding(), bottom = bottom.toPadding(), ) ) private fun Dp.toPadding() = PaddingDimension(dp = this) private fun Int.toPadding() = if (this == 0) PaddingDimension() else PaddingDimension(this) /** @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun GlanceModifier.collectPadding(): PaddingModifier? = foldIn<PaddingModifier?>(null) { acc, modifier -> if (modifier is PaddingModifier) { (acc ?: PaddingModifier()) + modifier } else { acc } } /** @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun GlanceModifier.collectPaddingInDp(resources: Resources) = collectPadding()?.toDp(resources) private fun List<Int>.toDp(resources: Resources) = fold(0.dp) { acc, res -> acc + (resources.getDimension(res) / resources.displayMetrics.density).dp } /** @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class PaddingModifier( val left: PaddingDimension = PaddingDimension(), val start: PaddingDimension = PaddingDimension(), val top: PaddingDimension = PaddingDimension(), val right: PaddingDimension = PaddingDimension(), val end: PaddingDimension = PaddingDimension(), val bottom: PaddingDimension = PaddingDimension(), ) : GlanceModifier.Element { operator fun plus(other: PaddingModifier) = PaddingModifier( left = left + other.left, start = start + other.start, top = top + other.top, right = right + other.right, end = end + other.end, bottom = bottom + other.bottom, ) fun toDp(resources: Resources): PaddingInDp = PaddingInDp( left = left.dp + left.resourceIds.toDp(resources), start = start.dp + start.resourceIds.toDp(resources), top = top.dp + top.resourceIds.toDp(resources), right = right.dp + right.resourceIds.toDp(resources), end = end.dp + end.resourceIds.toDp(resources), bottom = bottom.dp + bottom.resourceIds.toDp(resources), ) } /** @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class PaddingDimension( val dp: Dp = 0.dp, val resourceIds: List<Int> = emptyList(), ) { constructor(@DimenRes resource: Int) : this(resourceIds = listOf(resource)) operator fun plus(other: PaddingDimension) = PaddingDimension( dp = dp + other.dp, resourceIds = resourceIds + other.resourceIds, ) companion object { val Zero = PaddingDimension() } } /** @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class PaddingInDp( val left: Dp = 0.dp, val start: Dp = 0.dp, val top: Dp = 0.dp, val right: Dp = 0.dp, val end: Dp = 0.dp, val bottom: Dp = 0.dp, ) { /** Transfer [start] / [end] to [left] / [right] depending on [isRtl]. */ fun toAbsolute(isRtl: Boolean) = PaddingInDp( left = left + if (isRtl) end else start, top = top, right = right + if (isRtl) start else end, bottom = bottom, ) /** Transfer [left] / [right] to [start] / [end] depending on [isRtl]. */ fun toRelative(isRtl: Boolean) = PaddingInDp( start = start + if (isRtl) right else left, top = top, end = end + if (isRtl) left else right, bottom = bottom ) }
apache-2.0
deda819f9a40b3c1a1436875f6e37b23
29.746429
99
0.635265
3.952709
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/androidAndroidTest/kotlin/androidx/compose/ui/text/TextPainterTest.kt
3
16146
/* * 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. */ @file:OptIn(ExperimentalTextApi::class) package androidx.compose.ui.text import android.graphics.Bitmap import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.drawscope.CanvasDrawScope import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Fill import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.createFontFamilyResolver import androidx.compose.ui.text.font.toFontFamily import androidx.compose.ui.text.matchers.assertThat import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.sp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.test.platform.app.InstrumentationRegistry import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @MediumTest class TextPainterTest { private val fontFamilyMeasureFont = FontTestData.BASIC_MEASURE_FONT.toFontFamily() private val context = InstrumentationRegistry.getInstrumentation().context private val fontFamilyResolver = createFontFamilyResolver(context) private var defaultDensity = Density(density = 1f) private var layoutDirection = LayoutDirection.Ltr private val longText = AnnotatedString( "Lorem ipsum dolor sit amet, consectetur " + "adipiscing elit. Curabitur augue leo, finibus vitae felis ac, pretium condimentum " + "augue. Nullam non libero sed lectus aliquet venenatis non at purus. Fusce id arcu " + "eu mauris pulvinar laoreet." ) @Test fun drawTextWithMeasurer_shouldBeEqualTo_drawTextLayoutResult() { val measurer = textMeasurer() val textLayoutResult = measurer.measure( text = longText, style = TextStyle(fontFamily = fontFamilyMeasureFont, fontSize = 20.sp), constraints = Constraints(maxWidth = 400, maxHeight = 400) ) val bitmap = draw { drawText(textLayoutResult) } val bitmap2 = draw { drawText( measurer, text = longText, style = TextStyle(fontFamily = fontFamilyMeasureFont, fontSize = 20.sp), maxSize = IntSize(400, 400) ) } assertThat(bitmap).isEqualToBitmap(bitmap2) } @Test fun textMeasurerCache_shouldNotAffectTheResult_forColor() { val measurer = textMeasurer(cacheSize = 8) val bitmap = draw { drawText( textMeasurer = measurer, text = longText, style = TextStyle( color = Color.Red, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), maxSize = IntSize(400, 400) ) } val bitmap2 = draw { drawText( textMeasurer = measurer, text = longText, style = TextStyle( color = Color.Blue, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), maxSize = IntSize(400, 400) ) } assertThat(bitmap).isNotEqualToBitmap(bitmap2) } @Test fun textMeasurerCache_shouldNotAffectTheResult_forFontSize() { val measurer = textMeasurer(cacheSize = 8) val bitmap = draw { drawText( textMeasurer = measurer, text = longText, style = TextStyle(fontFamily = fontFamilyMeasureFont, fontSize = 20.sp), maxSize = IntSize(400, 400) ) } val bitmap2 = draw { drawText( textMeasurer = measurer, text = longText, style = TextStyle(fontFamily = fontFamilyMeasureFont, fontSize = 24.sp), maxSize = IntSize(400, 400) ) } assertThat(bitmap).isNotEqualToBitmap(bitmap2) } @Test fun drawTextLayout_shouldChangeColor() { val measurer = textMeasurer() val textLayoutResultRed = measurer.measure( text = longText, style = TextStyle( color = Color.Red, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(400, 400) ) val textLayoutResultBlue = measurer.measure( text = longText, style = TextStyle( color = Color.Blue, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(400, 400) ) val bitmap = draw { drawText(textLayoutResultRed, color = Color.Blue) } val bitmap2 = draw { drawText(textLayoutResultBlue) } assertThat(bitmap).isEqualToBitmap(bitmap2) } @Test fun drawTextLayout_shouldChangeAlphaColor() { val measurer = textMeasurer() val textLayoutResultOpaque = measurer.measure( text = longText, style = TextStyle( color = Color.Red, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(400, 400) ) val textLayoutResultHalfOpaque = measurer.measure( text = longText, style = TextStyle( color = Color.Red.copy(alpha = 0.5f), fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(400, 400) ) val bitmap = draw { drawText(textLayoutResultOpaque, alpha = 0.5f) } val bitmap2 = draw { drawText(textLayoutResultHalfOpaque) } assertThat(bitmap).isEqualToBitmap(bitmap2) } @Test fun drawTextLayout_shouldChangeBrush() { val rbBrush = Brush.radialGradient(listOf(Color.Red, Color.Blue)) val gyBrush = Brush.radialGradient(listOf(Color.Green, Color.Yellow)) val measurer = textMeasurer() val textLayoutResultRB = measurer.measure( text = longText, style = TextStyle( brush = rbBrush, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(400, 400) ) val textLayoutResultGY = measurer.measure( text = longText, style = TextStyle( brush = gyBrush, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(400, 400) ) val bitmap = draw { drawText(textLayoutResultRB, brush = gyBrush) } val bitmap2 = draw { drawText(textLayoutResultGY) } assertThat(bitmap).isEqualToBitmap(bitmap2) } @Test fun drawTextLayout_shouldChangeAlphaForBrush() { val rbBrush = Brush.radialGradient(listOf(Color.Red, Color.Blue)) val measurer = textMeasurer() val textLayoutResultOpaque = measurer.measure( text = longText, style = TextStyle( brush = rbBrush, alpha = 1f, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(400, 400) ) val textLayoutResultHalfOpaque = measurer.measure( text = longText, style = TextStyle( brush = rbBrush, alpha = 0.5f, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(400, 400) ) val bitmap = draw { drawText(textLayoutResultOpaque, alpha = 0.5f) } val bitmap2 = draw { drawText(textLayoutResultHalfOpaque) } assertThat(bitmap).isEqualToBitmap(bitmap2) } @Test fun drawTextLayout_shouldChangeDrawStyle() { val fillDrawStyle = Fill val strokeDrawStyle = Stroke(8f, cap = StrokeCap.Round) val measurer = textMeasurer() val textLayoutResultFill = measurer.measure( text = longText, style = TextStyle( drawStyle = fillDrawStyle, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints(maxWidth = 400, maxHeight = 400) ) val textLayoutResultStroke = measurer.measure( text = longText, style = TextStyle( drawStyle = strokeDrawStyle, fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints(maxWidth = 400, maxHeight = 400) ) val bitmap = draw { drawText(textLayoutResultFill, drawStyle = strokeDrawStyle) } val bitmap2 = draw { drawText(textLayoutResultStroke) } assertThat(bitmap).isEqualToBitmap(bitmap2) } @Test fun textMeasurerDraw_isConstrainedTo_canvasSizeByDefault() { val measurer = textMeasurer() // constrain the width, height is ignored val textLayoutResult = measurer.measure( text = longText, style = TextStyle( fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), constraints = Constraints.fixed(200, 4000) ) val bitmap = draw(200f, 4000f) { drawText(textLayoutResult) } val bitmap2 = draw(200f, 4000f) { drawText(measurer, longText, style = TextStyle( fontFamily = fontFamilyMeasureFont, fontSize = 20.sp )) } assertThat(bitmap).isEqualToBitmap(bitmap2) } @Test fun textMeasurerDraw_usesCanvasDensity_ByDefault() { val measurer = textMeasurer() // constrain the width, height is ignored val textLayoutResult = measurer.measure( text = longText, style = TextStyle( fontFamily = fontFamilyMeasureFont, fontSize = 20.sp ), density = Density(4f), constraints = Constraints.fixed(1000, 1000) ) val bitmap = draw { drawText(textLayoutResult) } defaultDensity = Density(4f) val bitmap2 = draw { drawText(measurer, longText, style = TextStyle( fontFamily = fontFamilyMeasureFont, fontSize = 20.sp )) } assertThat(bitmap).isEqualToBitmap(bitmap2) } @Test fun drawTextClipsTheContent_ifOverflowIsClip() { val measurer = textMeasurer() // constrain the width, height is ignored val textLayoutResult = measurer.measure( text = longText, style = TextStyle( fontFamily = fontFamilyMeasureFont, fontSize = 14.sp ), softWrap = false, overflow = TextOverflow.Clip, constraints = Constraints.fixed(200, 200) ) val bitmap = draw(400f, 200f) { drawText(textLayoutResult) } val croppedBitmap = Bitmap.createBitmap(bitmap, 200, 0, 200, 200) // cropped part should be empty assertThat(croppedBitmap).isEqualToBitmap(Bitmap.createBitmap( 200, 200, Bitmap.Config.ARGB_8888)) } @Test fun drawTextClipsTheContent_ifOverflowIsEllipsis_ifLessThanOneLineFits() { val measurer = textMeasurer() with(defaultDensity) { val fontSize = 20.sp val height = fontSize.toPx().ceilToInt() / 2 val textLayoutResult = measurer.measure( text = longText, style = TextStyle( fontFamily = fontFamilyMeasureFont, fontSize = fontSize ), softWrap = false, overflow = TextOverflow.Ellipsis, constraints = Constraints.fixed(200, height) ) val bitmap = draw(200f, 200f) { drawText(textLayoutResult) } val croppedBitmap = Bitmap.createBitmap(bitmap, 0, height, 200, 200 - height) // cropped part should be empty assertThat(croppedBitmap).isEqualToBitmap( Bitmap.createBitmap( 200, 200 - height, Bitmap.Config.ARGB_8888 ) ) } } @Test fun drawTextDoesNotClipTheContent_ifOverflowIsVisible() { val measurer = textMeasurer() // constrain the width, height is ignored val textLayoutResult = measurer.measure( text = longText, style = TextStyle( fontFamily = fontFamilyMeasureFont, fontSize = 14.sp ), softWrap = false, overflow = TextOverflow.Clip, constraints = Constraints.fixed(400, 200) ) val textLayoutResultNoClip = measurer.measure( text = longText, style = TextStyle( fontFamily = fontFamilyMeasureFont, fontSize = 14.sp ), softWrap = false, overflow = TextOverflow.Visible, constraints = Constraints.fixed(200, 200) ) val bitmap = draw(400f, 200f) { drawText(textLayoutResult) } val bitmapNoClip = draw(400f, 200f) { drawText(textLayoutResultNoClip) } // cropped part should be empty assertThat(bitmap).isEqualToBitmap(bitmapNoClip) } private fun textMeasurer( fontFamilyResolver: FontFamily.Resolver = this.fontFamilyResolver, density: Density = this.defaultDensity, layoutDirection: LayoutDirection = this.layoutDirection, cacheSize: Int = 0 ): TextMeasurer = TextMeasurer( fontFamilyResolver, density, layoutDirection, cacheSize ) fun draw( width: Float = 1000f, height: Float = 1000f, block: DrawScope.() -> Unit ): Bitmap { val size = Size(width, height) val bitmap = Bitmap.createBitmap( size.width.toIntPx(), size.height.toIntPx(), Bitmap.Config.ARGB_8888 ) val canvas = Canvas(bitmap.asImageBitmap()) val drawScope = CanvasDrawScope() drawScope.draw( defaultDensity, layoutDirection, canvas, size, block ) return bitmap } }
apache-2.0
1b2b747b2f87333a59299acdbfb880c9
31.037698
98
0.574755
5.026775
false
false
false
false
GunoH/intellij-community
python/src/com/jetbrains/python/sdk/add/wizardUIUtil.kt
9
2802
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.jetbrains.python.sdk.add import com.intellij.openapi.project.Project import com.intellij.openapi.util.SystemInfoRt import com.intellij.ui.JBCardLayout import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.messages.showProcessExecutionErrorDialog import com.intellij.util.ui.GridBag import com.intellij.util.ui.JBInsets import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.jetbrains.python.packaging.PyExecutionException import java.awt.* import javax.swing.BorderFactory import javax.swing.Box import javax.swing.JButton import javax.swing.JPanel internal fun doCreateSouthPanel(leftButtons: List<JButton>, rightButtons: List<JButton>): JPanel { val panel = JPanel(BorderLayout()) //noinspection UseDPIAwareInsets val insets = if (SystemInfoRt.isMac) if (UIUtil.isUnderIntelliJLaF()) JBUI.insets(0, 8) else JBInsets.emptyInsets() else if (UIUtil.isUnderWin10LookAndFeel()) JBInsets.emptyInsets() else Insets(8, 0, 0, 0) //don't wrap to JBInsets val bag = GridBag().setDefaultInsets(insets) val lrButtonsPanel = NonOpaquePanel(GridBagLayout()) val leftButtonsPanel = createButtonsPanel(leftButtons) leftButtonsPanel.border = BorderFactory.createEmptyBorder(0, 0, 0, 20) // leave some space between button groups lrButtonsPanel.add(leftButtonsPanel, bag.next()) lrButtonsPanel.add(Box.createHorizontalGlue(), bag.next().weightx(1.0).fillCellHorizontally()) // left strut val buttonsPanel = createButtonsPanel(rightButtons) lrButtonsPanel.add(buttonsPanel, bag.next()) panel.add(lrButtonsPanel, BorderLayout.CENTER) panel.border = JBUI.Borders.emptyTop(8) return panel } private fun createButtonsPanel(buttons: List<JButton>): JPanel { val hgap = if (SystemInfoRt.isMac) if (UIUtil.isUnderIntelliJLaF()) 8 else 0 else 5 val buttonsPanel = NonOpaquePanel(GridLayout(1, buttons.size, hgap, 0)) buttons.forEach { buttonsPanel.add(it) } return buttonsPanel } internal fun swipe(panel: JPanel, stepContent: Component, swipeDirection: JBCardLayout.SwipeDirection) { val stepContentName = stepContent.hashCode().toString() panel.add(stepContentName, stepContent) (panel.layout as JBCardLayout).swipe(panel, stepContentName, swipeDirection) } internal fun show(panel: JPanel, stepContent: Component) { val stepContentName = stepContent.hashCode().toString() panel.add(stepContentName, stepContent) (panel.layout as CardLayout).show(panel, stepContentName) } fun showProcessExecutionErrorDialog(project: Project?, e: PyExecutionException) = showProcessExecutionErrorDialog(project, e.localizedMessage.orEmpty(), e.command, e.stdout, e.stderr, e.exitCode)
apache-2.0
b7cf45bcfaf16d78b817be12e59f85c1
39.042857
120
0.790507
4.037464
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderPresenter.kt
1
17162
package eu.kanade.tachiyomi.ui.reader import android.os.Bundle import eu.kanade.tachiyomi.data.cache.ChapterCache import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.History import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.database.models.MangaSync import eu.kanade.tachiyomi.data.download.DownloadManager import eu.kanade.tachiyomi.data.mangasync.MangaSyncManager import eu.kanade.tachiyomi.data.mangasync.UpdateMangaSyncService import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.source.SourceManager import eu.kanade.tachiyomi.data.source.model.Page import eu.kanade.tachiyomi.data.source.online.OnlineSource import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter import eu.kanade.tachiyomi.util.RetryWithDelay import eu.kanade.tachiyomi.util.SharedData import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import timber.log.Timber import uy.kohesive.injekt.injectLazy import java.io.File import java.util.* /** * Presenter of [ReaderActivity]. */ class ReaderPresenter : BasePresenter<ReaderActivity>() { /** * Preferences. */ val prefs: PreferencesHelper by injectLazy() /** * Database. */ val db: DatabaseHelper by injectLazy() /** * Download manager. */ val downloadManager: DownloadManager by injectLazy() /** * Sync manager. */ val syncManager: MangaSyncManager by injectLazy() /** * Source manager. */ val sourceManager: SourceManager by injectLazy() /** * Chapter cache. */ val chapterCache: ChapterCache by injectLazy() /** * Manga being read. */ lateinit var manga: Manga private set /** * Active chapter. */ lateinit var chapter: ReaderChapter private set /** * Previous chapter of the active. */ private var prevChapter: ReaderChapter? = null /** * Next chapter of the active. */ private var nextChapter: ReaderChapter? = null /** * Source of the manga. */ private val source by lazy { sourceManager.get(manga.source)!! } /** * Chapter list for the active manga. It's retrieved lazily and should be accessed for the first * time in a background thread to avoid blocking the UI. */ private val chapterList by lazy { val dbChapters = db.getChapters(manga).executeAsBlocking().map { it.toModel() } val sortFunction: (Chapter, Chapter) -> Int = when (manga.sorting) { Manga.SORTING_SOURCE -> { c1, c2 -> c2.source_order.compareTo(c1.source_order) } Manga.SORTING_NUMBER -> { c1, c2 -> c1.chapter_number.compareTo(c2.chapter_number) } else -> throw NotImplementedError("Unknown sorting method") } dbChapters.sortedWith(Comparator<Chapter> { c1, c2 -> sortFunction(c1, c2) }) } /** * Map of chapters that have been loaded in the reader. */ private val loadedChapters = hashMapOf<Long?, ReaderChapter>() /** * List of manga services linked to the active manga, or null if auto syncing is not enabled. */ private var mangaSyncList: List<MangaSync>? = null /** * Chapter loader whose job is to obtain the chapter list and initialize every page. */ private val loader by lazy { ChapterLoader(downloadManager, manga, source) } /** * Subscription for appending a chapter to the reader (seamless mode). */ private var appenderSubscription: Subscription? = null /** * Subscription for retrieving the adjacent chapters to the current one. */ private var adjacentChaptersSubscription: Subscription? = null companion object { /** * Id of the restartable that loads the active chapter. */ private const val LOAD_ACTIVE_CHAPTER = 1 } override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) if (savedState == null) { val event = SharedData.get(ReaderEvent::class.java) ?: return manga = event.manga chapter = event.chapter.toModel() } else { manga = savedState.getSerializable(ReaderPresenter::manga.name) as Manga chapter = savedState.getSerializable(ReaderPresenter::chapter.name) as ReaderChapter } // Send the active manga to the view to initialize the reader. Observable.just(manga) .subscribeLatestCache({ view, manga -> view.onMangaOpen(manga) }) // Retrieve the sync list if auto syncing is enabled. if (prefs.autoUpdateMangaSync()) { add(db.getMangasSync(manga).asRxSingle() .subscribe({ mangaSyncList = it })) } restartableLatestCache(LOAD_ACTIVE_CHAPTER, { loadChapterObservable(chapter) }, { view, chapter -> view.onChapterReady(this.chapter) }, { view, error -> view.onChapterError(error) }) if (savedState == null) { loadChapter(chapter) } } override fun onSave(state: Bundle) { chapter.requestedPage = chapter.last_page_read state.putSerializable(ReaderPresenter::manga.name, manga) state.putSerializable(ReaderPresenter::chapter.name, chapter) super.onSave(state) } override fun onDestroy() { loader.cleanup() onChapterLeft() super.onDestroy() } /** * Converts a chapter to a [ReaderChapter] if needed. */ private fun Chapter.toModel(): ReaderChapter { if (this is ReaderChapter) return this return ReaderChapter(this) } /** * Returns an observable that loads the given chapter, discarding any previous work. * * @param chapter the now active chapter. */ private fun loadChapterObservable(chapter: ReaderChapter): Observable<ReaderChapter> { loader.restart() return loader.loadChapter(chapter) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } /** * Obtains the adjacent chapters of the given one in a background thread, and notifies the view * when they are known. * * @param chapter the current active chapter. */ private fun getAdjacentChapters(chapter: ReaderChapter) { // Keep only one subscription adjacentChaptersSubscription?.let { remove(it) } adjacentChaptersSubscription = Observable .fromCallable { getAdjacentChaptersStrategy(chapter) } .doOnNext { pair -> prevChapter = loadedChapters.getOrElse(pair.first?.id) { pair.first } nextChapter = loadedChapters.getOrElse(pair.second?.id) { pair.second } } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeLatestCache({ view, pair -> view.onAdjacentChapters(pair.first, pair.second) }) } /** * Returns the previous and next chapters of the given one in a [Pair] according to the sorting * strategy set for the manga. * * @param chapter the current active chapter. * @param previousChapterAmount the desired number of chapters preceding the current active chapter (Default: 1). * @param nextChapterAmount the desired number of chapters succeeding the current active chapter (Default: 1). */ private fun getAdjacentChaptersStrategy(chapter: ReaderChapter, previousChapterAmount: Int = 1, nextChapterAmount: Int = 1) = when (manga.sorting) { Manga.SORTING_SOURCE -> { val currChapterIndex = chapterList.indexOfFirst { chapter.id == it.id } val nextChapter = chapterList.getOrNull(currChapterIndex + nextChapterAmount) val prevChapter = chapterList.getOrNull(currChapterIndex - previousChapterAmount) Pair(prevChapter, nextChapter) } Manga.SORTING_NUMBER -> { val currChapterIndex = chapterList.indexOfFirst { chapter.id == it.id } val chapterNumber = chapter.chapter_number var prevChapter: ReaderChapter? = null for (i in (currChapterIndex - previousChapterAmount) downTo 0) { val c = chapterList[i] if (c.chapter_number < chapterNumber && c.chapter_number >= chapterNumber - previousChapterAmount) { prevChapter = c break } } var nextChapter: ReaderChapter? = null for (i in (currChapterIndex + nextChapterAmount) until chapterList.size) { val c = chapterList[i] if (c.chapter_number > chapterNumber && c.chapter_number <= chapterNumber + nextChapterAmount) { nextChapter = c break } } Pair(prevChapter, nextChapter) } else -> throw NotImplementedError("Unknown sorting method") } /** * Loads the given chapter and sets it as the active one. This method also accepts a requested * page, which will be set as active when it's displayed in the view. * * @param chapter the chapter to load. * @param requestedPage the requested page from the view. */ private fun loadChapter(chapter: ReaderChapter, requestedPage: Int = 0) { // Cleanup any append. appenderSubscription?.let { remove(it) } this.chapter = loadedChapters.getOrPut(chapter.id) { chapter } // If the chapter is partially read, set the starting page to the last the user read // otherwise use the requested page. chapter.requestedPage = if (!chapter.read) chapter.last_page_read else requestedPage // Reset next and previous chapter. They have to be fetched again nextChapter = null prevChapter = null start(LOAD_ACTIVE_CHAPTER) getAdjacentChapters(chapter) } /** * Changes the active chapter, but doesn't load anything. Called when changing chapters from * the reader with the seamless mode. * * @param chapter the chapter to set as active. */ fun setActiveChapter(chapter: ReaderChapter) { onChapterLeft() this.chapter = chapter nextChapter = null prevChapter = null getAdjacentChapters(chapter) } /** * Appends the next chapter to the reader, if possible. */ fun appendNextChapter() { appenderSubscription?.let { remove(it) } val nextChapter = nextChapter ?: return val chapterToLoad = loadedChapters.getOrPut(nextChapter.id) { nextChapter } appenderSubscription = loader.loadChapter(chapterToLoad) .subscribeOn(Schedulers.io()) .retryWhen(RetryWithDelay(1, { 3000 })) .observeOn(AndroidSchedulers.mainThread()) .subscribeLatestCache({ view, chapter -> view.onAppendChapter(chapter) }, { view, error -> view.onChapterAppendError() }) } /** * Retries a page that failed to load due to network error or corruption. * * @param page the page that failed. */ fun retryPage(page: Page?) { if (page != null && source is OnlineSource) { page.status = Page.QUEUE if (page.imagePath != null) { val file = File(page.imagePath) chapterCache.removeFileFromCache(file.name) } loader.retryPage(page) } } /** * Called before loading another chapter or leaving the reader. It allows to do operations * over the chapter read like saving progress */ fun onChapterLeft() { // Reference these locally because they are needed later from another thread. val chapter = chapter val pages = chapter.pages ?: return Observable.fromCallable { // Chapters with 1 page don't trigger page changes, so mark them as read. if (pages.size == 1) { chapter.read = true } // Cache current page list progress for online chapters to allow a faster reopen if (!chapter.isDownloaded) { source.let { if (it is OnlineSource) it.savePageList(chapter, pages) } } if (chapter.read) { val removeAfterReadSlots = prefs.removeAfterReadSlots() when (removeAfterReadSlots) { // Setting disabled -1 -> { /**Empty function**/ } // Remove current read chapter 0 -> deleteChapter(chapter, manga) // Remove previous chapter specified by user in settings. else -> getAdjacentChaptersStrategy(chapter, removeAfterReadSlots) .first?.let { deleteChapter(it, manga) } } } db.updateChapterProgress(chapter).executeAsBlocking() try { val history = History.create(chapter).apply { last_read = Date().time } db.updateHistoryLastRead(history).executeAsBlocking() } catch (error: Exception) { // TODO find out why it crashes Timber.e(error) } } .subscribeOn(Schedulers.io()) .subscribe() } /** * Called when the active page changes in the reader. * * @param page the active page */ fun onPageChanged(page: Page) { val chapter = page.chapter chapter.last_page_read = page.pageNumber if (chapter.pages!!.last() === page) { chapter.read = true } if (!chapter.isDownloaded && page.status == Page.QUEUE) { loader.loadPriorizedPage(page) } } /** * Delete selected chapter * * @param chapter chapter that is selected * @param manga manga that belongs to chapter */ fun deleteChapter(chapter: ReaderChapter, manga: Manga) { chapter.isDownloaded = false chapter.pages?.forEach { it.status == Page.QUEUE } downloadManager.deleteChapter(source, manga, chapter) } /** * Returns the chapter to be marked as last read in sync services or 0 if no update required. */ fun getMangaSyncChapterToUpdate(): Int { val mangaSyncList = mangaSyncList if (chapter.pages == null || mangaSyncList == null || mangaSyncList.isEmpty()) return 0 val prevChapter = prevChapter // Get the last chapter read from the reader. val lastChapterRead = if (chapter.read) Math.floor(chapter.chapter_number.toDouble()).toInt() else if (prevChapter != null && prevChapter.read) Math.floor(prevChapter.chapter_number.toDouble()).toInt() else 0 mangaSyncList.forEach { sync -> if (lastChapterRead > sync.last_chapter_read) { sync.last_chapter_read = lastChapterRead sync.update = true } } return if (mangaSyncList.any { it.update }) lastChapterRead else 0 } /** * Starts the service that updates the last chapter read in sync services */ fun updateMangaSyncLastChapterRead() { mangaSyncList?.forEach { sync -> val service = syncManager.getService(sync.sync_id) if (service != null && service.isLogged && sync.update) { UpdateMangaSyncService.start(context, sync) } } } /** * Loads the next chapter. * * @return true if the next chapter is being loaded, false if there is no next chapter. */ fun loadNextChapter(): Boolean { nextChapter?.let { onChapterLeft() loadChapter(it, 0) return true } return false } /** * Loads the next chapter. * * @return true if the previous chapter is being loaded, false if there is no previous chapter. */ fun loadPreviousChapter(): Boolean { prevChapter?.let { onChapterLeft() loadChapter(it, if (it.read) -1 else 0) return true } return false } /** * Returns true if there's a next chapter. */ fun hasNextChapter(): Boolean { return nextChapter != null } /** * Returns true if there's a previous chapter. */ fun hasPreviousChapter(): Boolean { return prevChapter != null } /** * Updates the viewer for this manga. * * @param viewer the id of the viewer to set. */ fun updateMangaViewer(viewer: Int) { manga.viewer = viewer db.insertManga(manga).executeAsBlocking() } }
gpl-3.0
fefc1a301420e9fb6e457c4f0cb01050
32.585127
152
0.61205
4.77784
false
false
false
false
GunoH/intellij-community
java/idea-ui/src/com/intellij/ide/starters/shared/ui/LibrariesSearchTextField.kt
3
2501
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.starters.shared.ui import com.intellij.ide.starters.JavaStartersBundle import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonShortcuts import com.intellij.ui.JBColor import com.intellij.ui.SearchTextField import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBUI import org.jetbrains.annotations.ApiStatus import java.awt.Dimension import java.awt.event.KeyEvent import javax.swing.JComponent @ApiStatus.Internal class LibrariesSearchTextField : SearchTextField() { var list: JComponent? = null init { textEditor.putClientProperty("JTextField.Search.Gap", JBUIScale.scale(6)) textEditor.putClientProperty("JTextField.Search.GapEmptyText", JBUIScale.scale(-1)) textEditor.border = JBUI.Borders.empty() textEditor.emptyText.text = JavaStartersBundle.message("hint.library.search") border = JBUI.Borders.customLine(JBColor.border(), 1, 1, 0, 1) } override fun preprocessEventForTextField(event: KeyEvent): Boolean { val keyCode: Int = event.keyCode val id: Int = event.id if ((keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_ENTER) && id == KeyEvent.KEY_PRESSED && handleListEvents(event)) { return true } return super.preprocessEventForTextField(event) } private fun handleListEvents(event: KeyEvent): Boolean { val selectionTracker = list if (selectionTracker != null) { selectionTracker.dispatchEvent(event) return true } return false } override fun getPreferredSize(): Dimension { val size = super.getPreferredSize() size.height = JBUIScale.scale(30) return size } override fun toClearTextOnEscape(): Boolean { object : AnAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabled = text.isNotEmpty() } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun actionPerformed(e: AnActionEvent) { text = "" } init { isEnabledInModalContext = true } }.registerCustomShortcutSet(CommonShortcuts.ESCAPE, this) return false } }
apache-2.0
60fe2ac2317095c0225d7e15349da5ea
30.275
158
0.730508
4.555556
false
false
false
false
GunoH/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaULambdaExpression.kt
7
3051
/* * 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 org.jetbrains.uast.java import com.intellij.psi.* import org.jetbrains.annotations.ApiStatus import org.jetbrains.uast.* @ApiStatus.Internal class JavaULambdaExpression( override val sourcePsi: PsiLambdaExpression, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), ULambdaExpression { override val functionalInterfaceType: PsiType? get() = sourcePsi.functionalInterfaceType override val valueParameters: List<UParameter> by lz { sourcePsi.parameterList.parameters.map { JavaUParameter(it, this) } } override val body: UExpression by lz { when (val b = sourcePsi.body) { is PsiCodeBlock -> JavaConverter.convertBlock(b, this) is PsiExpression -> wrapLambdaBody(this, b) else -> UastEmptyExpression(this) } } } private fun wrapLambdaBody(parent: JavaULambdaExpression, b: PsiExpression): UBlockExpression = JavaImplicitUBlockExpression(parent).apply { expressions = listOf(JavaImplicitUReturnExpression(this).apply { returnExpression = JavaConverter.convertOrEmpty(b, this) }) } private class JavaImplicitUReturnExpression(givenParent: UElement?) : JavaAbstractUExpression(givenParent), UReturnExpression { override val label: String? get() = null override val jumpTarget: UElement? = getParentOfType(ULambdaExpression::class.java, strict = true) override val sourcePsi: PsiElement? get() = null override val psi: PsiElement? get() = null override lateinit var returnExpression: UExpression internal set override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as JavaImplicitUReturnExpression val b = returnExpression != other.returnExpression if (b) return false return true } override fun hashCode(): Int = 31 + returnExpression.hashCode() } private class JavaImplicitUBlockExpression(givenParent: UElement?) : JavaAbstractUExpression(givenParent), UBlockExpression { override val sourcePsi: PsiElement? get() = null override lateinit var expressions: List<UExpression> internal set override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as JavaImplicitUBlockExpression if (expressions != other.expressions) return false return true } override fun hashCode(): Int = 31 + expressions.hashCode() }
apache-2.0
29e5d4d2ba37fb481e8232a20a8911ca
30.78125
127
0.740741
4.715611
false
false
false
false
GunoH/intellij-community
plugins/ide-features-trainer/src/training/featuresSuggester/suggesters/ReplaceCompletionSuggester.kt
2
5180
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package training.featuresSuggester.suggesters import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.refactoring.suggested.startOffset import training.featuresSuggester.* import training.featuresSuggester.actions.* class ReplaceCompletionSuggester : AbstractFeatureSuggester() { override val id: String = "Completion with replace" override val suggestingActionDisplayName: String = FeatureSuggesterBundle.message("replace.completion.name") override val message = FeatureSuggesterBundle.message("replace.completion.message") override val suggestingActionId = "EditorChooseLookupItemReplace" override val suggestingDocUrl = "https://www.jetbrains.com/help/idea/auto-completing-code.html#accept" override val minSuggestingIntervalDays = 14 override val languages = listOf("JAVA", "kotlin", "Python", "JavaScript", "ECMAScript 6") private data class EditedStatementData(val dotOffset: Int) { var isCompletionStarted: Boolean = false var textToDelete: String = "" var deletedText: String = "" var addedExprEndOffset: Int = -1 val isCompletionFinished: Boolean get() = textToDelete != "" fun isAroundDot(offset: Int): Boolean { return offset in dotOffset..(dotOffset + 7) } fun isIdentifierNameDeleted(caretOffset: Int, newDeletedText: String): Boolean { return isCaretInRangeOfExprToDelete(caretOffset, newDeletedText) && (deletedText.contains(textToDelete) || deletedText.contains(textToDelete.reversed())) } private fun isCaretInRangeOfExprToDelete(caretOffset: Int, newDeletedText: String): Boolean { return caretOffset in (addedExprEndOffset - 2)..(addedExprEndOffset + newDeletedText.length) } fun isDeletedTooMuch(): Boolean { return deletedText.length >= textToDelete.length * 2 } } private var editedStatementData: EditedStatementData? = null override fun getSuggestion(action: Action): Suggestion { val language = action.language ?: return NoSuggestion val langSupport = SuggesterSupport.getForLanguage(language) ?: return NoSuggestion when (action) { is BeforeEditorTextRemovedAction -> { if (action.textFragment.text == ".") { editedStatementData = langSupport.createEditedStatementData(action, action.caretOffset) } } is BeforeEditorTextInsertedAction -> { if (editedStatementData != null && action.text == "." && action.caretOffset == editedStatementData!!.dotOffset ) { editedStatementData!!.isCompletionStarted = true } } is EditorCodeCompletionAction -> { val caretOffset = action.caretOffset if (caretOffset == 0) return NoSuggestion if (action.document.getText(TextRange(caretOffset - 1, caretOffset)) == ".") { editedStatementData = langSupport.createEditedStatementData(action, action.caretOffset)?.apply { isCompletionStarted = true } } } is BeforeCompletionChooseItemAction -> { if (editedStatementData == null || editedStatementData?.isAroundDot(action.caretOffset) != true) { return NoSuggestion } val curElement = action.psiFile?.findElementAt(action.caretOffset) ?: return NoSuggestion if (langSupport.isIdentifier(curElement)) { // remove characters that user typed before completion editedStatementData!!.textToDelete = curElement.text.substring(action.caretOffset - curElement.startOffset) } } is CompletionChooseItemAction -> { editedStatementData?.addedExprEndOffset = action.caretOffset } is EditorTextInsertedAction -> { if (editedStatementData?.isCompletionFinished != true) return NoSuggestion if (action.caretOffset < editedStatementData!!.addedExprEndOffset) { editedStatementData!!.addedExprEndOffset += action.text.length } } is EditorTextRemovedAction -> { if (editedStatementData?.isCompletionFinished != true) return NoSuggestion editedStatementData!!.deletedText += action.textFragment.text if (editedStatementData!!.isDeletedTooMuch()) { editedStatementData = null } else if (editedStatementData!!.isIdentifierNameDeleted( action.caretOffset, action.textFragment.text ) ) { editedStatementData = null return createSuggestion() } } is EditorEscapeAction -> { editedStatementData = null } } return NoSuggestion } private fun SuggesterSupport.createEditedStatementData(action: EditorAction, offset: Int): EditedStatementData? { val curElement = action.psiFile?.findElementAt(offset) ?: return null return if (curElement.getParentByPredicate(::isLiteralExpression) == null && curElement.getParentOfType<PsiComment>() == null ) { EditedStatementData(offset) } else { null } } }
apache-2.0
e364f6b2efed0a0eb130655aa9102004
38.846154
120
0.69305
4.942748
false
false
false
false
smmribeiro/intellij-community
plugins/devkit/devkit-core/src/inspections/missingApi/MissingRecentApiInspection.kt
10
5895
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.devkit.inspections.missingApi import com.intellij.codeInspection.InspectionProfileEntry import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.apiUsage.ApiUsageUastVisitor import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.roots.TestSourcesFilter import com.intellij.openapi.util.BuildNumber import com.intellij.psi.PsiElementVisitor import com.intellij.psi.xml.XmlFile import com.intellij.ui.components.JBLabel import com.intellij.util.ui.FormBuilder import org.jetbrains.idea.devkit.DevKitBundle import org.jetbrains.idea.devkit.actions.DevkitActionsUtil import org.jetbrains.idea.devkit.module.PluginModuleType import org.jetbrains.idea.devkit.util.DescriptorUtil import org.jetbrains.idea.devkit.util.PsiUtil import java.awt.BorderLayout import javax.swing.JComponent import javax.swing.JPanel /** * Inspection that warns plugin authors if they use IntelliJ Platform's APIs that aren't available * in some IDE versions specified as compatible with the plugin via the "since-until" constraints. * * Suppose a plugin specifies `183.1; 181.9` as compatibility range, but some IntelliJ Platform's API * in use appeared only in `183.5`. Then the plugin won't work in `[181.1, 181.5)` * and this inspection's goal is to prevent it. * * *Implementation details*. * Info on when APIs were first introduced is obtained from "available since" artifacts. * They are are built on the build server for each IDE build and uploaded to * [IntelliJ artifacts repository](https://www.jetbrains.com/intellij-repository/releases/), * containing external annotations [org.jetbrains.annotations.ApiStatus.AvailableSince] * where APIs' introduction versions are specified. */ class MissingRecentApiInspection : LocalInspectionTool() { companion object { val INSPECTION_SHORT_NAME = InspectionProfileEntry.getShortName(MissingRecentApiInspection::class.java.simpleName) } /** * Actual "since" build constraint of the plugin under development. * * Along with [untilBuildString] it may be set manually if values in plugin.xml * differ from the actual values. For example, it is the case for gradle-intellij-plugin, * which allows to override "since" and "until" values during plugin build. */ var sinceBuildString: String? = null /** * Actual "until" build constraint of the plugin under development. */ var untilBuildString: String? = null private val sinceBuild: BuildNumber? get() = sinceBuildString?.let { BuildNumber.fromStringOrNull(it) } private val untilBuild: BuildNumber? get() = untilBuildString?.let { BuildNumber.fromStringOrNull(it) } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { val project = holder.project val virtualFile = holder.file.virtualFile if (PsiUtil.isIdeaProject(project) || virtualFile != null && TestSourcesFilter.isTestSources(virtualFile, project)) { return PsiElementVisitor.EMPTY_VISITOR } val module = ModuleUtil.findModuleForPsiElement(holder.file) ?: return PsiElementVisitor.EMPTY_VISITOR val targetedSinceUntilRanges = getTargetedSinceUntilRanges(module) if (targetedSinceUntilRanges.isEmpty()) { return PsiElementVisitor.EMPTY_VISITOR } return ApiUsageUastVisitor.createPsiElementVisitor( MissingRecentApiUsageProcessor(holder, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, targetedSinceUntilRanges) ) } override fun createOptionsPanel(): JComponent { val emptyBuildNumber = BuildNumber.fromString("1.0")!! val sinceField = BuildNumberField("since", emptyBuildNumber) sinceBuild?.also { sinceField.value = it } sinceField.emptyText.text = DevKitBundle.message("inspections.missing.recent.api.settings.since.empty.text") sinceField.valueEditor.addListener { value -> sinceBuildString = value.takeIf { it != emptyBuildNumber }?.asString() } val untilField = BuildNumberField("until", untilBuild ?: emptyBuildNumber) untilField.emptyText.text = DevKitBundle.message("inspections.missing.recent.api.settings.until.empty.text") untilBuild?.also { untilField.value = it } untilField.valueEditor.addListener { value -> untilBuildString = value.takeIf { it != emptyBuildNumber }?.asString() } val formBuilder = FormBuilder.createFormBuilder() .addComponent(JBLabel(DevKitBundle.message("inspections.missing.recent.api.settings.range"))) .addLabeledComponent(DevKitBundle.message("inspections.missing.recent.api.settings.since"), sinceField) .addLabeledComponent(DevKitBundle.message("inspections.missing.recent.api.settings.until"), untilField) val container = JPanel(BorderLayout()) container.add(formBuilder.panel, BorderLayout.NORTH) return container } private fun getTargetedSinceUntilRanges(module: Module): List<SinceUntilRange> { if (sinceBuild == null && untilBuild == null) { return DevkitActionsUtil.getCandidatePluginModules(module) .mapNotNull { PluginModuleType.getPluginXml(it) } .mapNotNull { getSinceUntilRange(it) } .filterNot { it.sinceBuild == null } } return listOf(SinceUntilRange(sinceBuild, untilBuild)) } private fun getSinceUntilRange(pluginXml: XmlFile): SinceUntilRange? { val ideaPlugin = DescriptorUtil.getIdeaPlugin(pluginXml) ?: return null val ideaVersion = ideaPlugin.ideaVersion val sinceBuild = ideaVersion.sinceBuild.value val untilBuild = ideaVersion.untilBuild.value return SinceUntilRange(sinceBuild, untilBuild) } }
apache-2.0
e90d927b27d20073959655ab6d2954be
45.0625
140
0.77218
4.476082
false
false
false
false
mjdev/libaums
libaums/src/main/java/me/jahnen/libaums/core/ErrNo.kt
2
782
package me.jahnen.libaums.core import android.util.Log /** * Created by magnusja on 5/19/17. */ object ErrNo { private val TAG = "ErrNo" private var isInited = true val errno: Int get() = if (isInited) { errnoNative } else { 1337 } val errstr: String get() = if (isInited) { errstrNative } else { "errno-lib could not be loaded!" } private val errnoNative: Int external get private val errstrNative: String external get init { try { System.loadLibrary("errno-lib") } catch (e: UnsatisfiedLinkError) { isInited = false Log.e(TAG, "could not load errno-lib", e) } } }
apache-2.0
c6625d1d3b4e148c12c1e4e7613499da
17.186047
53
0.517903
3.929648
false
false
false
false
MartinStyk/AndroidApkAnalyzer
app/src/main/java/sk/styk/martin/apkanalyzer/ui/permission/detail/pager/PermissionDetailFragmentViewModel.kt
1
2437
package sk.styk.martin.apkanalyzer.ui.permission.detail.pager import android.content.pm.PackageManager import android.view.MenuItem import androidx.appcompat.widget.Toolbar import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import sk.styk.martin.apkanalyzer.R import sk.styk.martin.apkanalyzer.model.permissions.LocalPermissionData import sk.styk.martin.apkanalyzer.util.TAG_APP_ANALYSIS import sk.styk.martin.apkanalyzer.util.TextInfo import sk.styk.martin.apkanalyzer.util.components.DialogComponent import sk.styk.martin.apkanalyzer.util.live.SingleLiveEvent import timber.log.Timber class PermissionDetailFragmentViewModel @AssistedInject constructor( @Assisted val localPermissionData: LocalPermissionData, private val packageManager: PackageManager, ) : ViewModel(), Toolbar.OnMenuItemClickListener { val title = localPermissionData.permissionData.simpleName private val showDialogEvent = SingleLiveEvent<DialogComponent>() val showDialog: LiveData<DialogComponent> = showDialogEvent private val closeEvent = SingleLiveEvent<Unit>() val close: LiveData<Unit> = closeEvent fun onNavigationClick() = closeEvent.call() override fun onMenuItemClick(item: MenuItem): Boolean { when (item.itemId) { R.id.description -> showDescriptionDialog() } return true } private fun showDescriptionDialog() { val description = try { packageManager.getPermissionInfo(localPermissionData.permissionData.name, PackageManager.GET_META_DATA).loadDescription(packageManager) } catch (e: PackageManager.NameNotFoundException) { Timber.tag(TAG_APP_ANALYSIS).i("No description for permission ${localPermissionData.permissionData.name}") null }?.takeIf { it.isNotBlank() } ?.let { TextInfo.from(it) } ?: TextInfo.from(R.string.NA) showDialogEvent.value = DialogComponent( title = TextInfo.from(localPermissionData.permissionData.simpleName), message = description, negativeButtonText = TextInfo.from(R.string.dismiss) ) } @AssistedFactory interface Factory { fun create(localPermissionData: LocalPermissionData): PermissionDetailFragmentViewModel } }
gpl-3.0
d9ce167a48ea901987c8b40d7b95e7ce
37.68254
147
0.739434
4.787819
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/domains/variables/TemporaryVariableRepository.kt
1
4393
package ch.rmy.android.http_shortcuts.data.domains.variables import ch.rmy.android.framework.data.BaseRepository import ch.rmy.android.framework.data.RealmFactory import ch.rmy.android.framework.data.RealmTransactionContext import ch.rmy.android.framework.extensions.swap import ch.rmy.android.http_shortcuts.data.domains.getTemporaryVariable import ch.rmy.android.http_shortcuts.data.enums.VariableType import ch.rmy.android.http_shortcuts.data.models.OptionModel import ch.rmy.android.http_shortcuts.data.models.VariableModel import io.realm.RealmList import io.realm.kotlin.deleteFromRealm import kotlinx.coroutines.flow.Flow import javax.inject.Inject class TemporaryVariableRepository @Inject constructor( realmFactory: RealmFactory, ) : BaseRepository(realmFactory) { fun getObservableTemporaryVariable(): Flow<VariableModel> = observeItem { getTemporaryVariable() } suspend fun createNewTemporaryVariable(type: VariableType) { commitTransaction { copyOrUpdate( VariableModel( id = VariableModel.TEMPORARY_ID, variableType = type, ) ) } } suspend fun setKey(key: String) { commitTransactionForVariable { variable -> variable.key = key } } suspend fun setTitle(title: String) { commitTransactionForVariable { variable -> variable.title = title } } suspend fun setMessage(message: String) { commitTransactionForVariable { variable -> variable.message = message } } suspend fun setUrlEncode(enabled: Boolean) { commitTransactionForVariable { variable -> variable.urlEncode = enabled } } suspend fun setJsonEncode(enabled: Boolean) { commitTransactionForVariable { variable -> variable.jsonEncode = enabled } } suspend fun setSharingSupport(shareText: Boolean, shareTitle: Boolean) { commitTransactionForVariable { variable -> variable.isShareText = shareText variable.isShareTitle = shareTitle } } suspend fun setRememberValue(enabled: Boolean) { commitTransactionForVariable { variable -> variable.rememberValue = enabled } } suspend fun setMultiline(enabled: Boolean) { commitTransactionForVariable { variable -> variable.isMultiline = enabled } } suspend fun setValue(value: String) { commitTransactionForVariable { variable -> variable.value = value } } suspend fun setDataForType(data: Map<String, String?>) { commitTransactionForVariable { variable -> variable.dataForType = data } } private suspend fun commitTransactionForVariable(transaction: RealmTransactionContext.(VariableModel) -> Unit) { commitTransaction { transaction( getTemporaryVariable() .findFirst() ?: return@commitTransaction ) } } suspend fun moveOption(optionId1: String, optionId2: String) { commitTransactionForVariable { variable -> variable.options?.swap(optionId1, optionId2) { id } } } suspend fun addOption(label: String, value: String) { commitTransactionForVariable { variable -> if (variable.options == null) { variable.options = RealmList() } variable.options!!.add( copy( OptionModel( label = label, value = value, ) ) ) } } suspend fun updateOption(optionId: String, label: String, value: String) { commitTransactionForVariable { variable -> val option = variable.options ?.find { it.id == optionId } ?: return@commitTransactionForVariable option.label = label option.value = value } } suspend fun removeOption(optionId: String) { commitTransactionForVariable { variable -> variable.options ?.find { it.id == optionId } ?.deleteFromRealm() } } }
mit
56d6f42b6dd53569ee5fa8ce8db5fa31
28.682432
116
0.605281
5.350792
false
false
false
false
kirimin/mitsumine
app/src/main/java/me/kirimin/mitsumine/top/TopPresenter.kt
1
4428
package me.kirimin.mitsumine.top import android.view.View import me.kirimin.mitsumine.R import me.kirimin.mitsumine._common.domain.enums.Category import me.kirimin.mitsumine._common.domain.enums.Type class TopPresenter(private val useCase: TopUseCase) { lateinit var view: TopView set var selectedType = Type.HOT private set var selectedCategory = Category.MAIN private set fun getTypeInt(type: Type) = if (type == Type.HOT) 0 else 1 fun onCreate(view: TopView, category: Category = Category.MAIN, type: Type = Type.HOT) { this.view = view selectedCategory = category selectedType = type view.initViews() view.addNavigationCategoryButton(Category.MAIN) view.addNavigationCategoryButton(Category.SOCIAL) view.addNavigationCategoryButton(Category.ECONOMICS) view.addNavigationCategoryButton(Category.LIFE) view.addNavigationCategoryButton(Category.KNOWLEDGE) view.addNavigationCategoryButton(Category.IT) view.addNavigationCategoryButton(Category.FUN) view.addNavigationCategoryButton(Category.ENTERTAINMENT) view.addNavigationCategoryButton(Category.GAME) // 古い既読を削除 useCase.deleteOldFeedData(3) view.refreshShowCategoryAndType(selectedCategory, selectedType) } fun onStart() { view.removeNavigationAdditions() useCase.additionKeywords.forEach { keyword -> view.addAdditionKeyword(keyword) } useCase.additionUsers.forEach { userId -> view.addAdditionUser(userId) } val account = useCase.account if (account != null) { view.enableUserInfo(account.displayName, account.imageUrl) } else { view.disableUserInfo() } } fun onDestroy() { } fun onNavigationClick(position: Int): Boolean { selectedType = if (position == 0) Type.HOT else Type.NEW view.closeNavigation() view.refreshShowCategoryAndType(selectedCategory, selectedType) return true } fun onToolbarClick() { if (view.isOpenNavigation()) { view.closeNavigation() } else { view.openNavigation() } } fun onBackKeyClick() { if (view.isOpenNavigation()) { view.closeNavigation() } else { view.backPress() } } fun onNavigationItemClick(id: Int) { when (id) { R.id.navigationReadTextView -> { view.startReadActivity() view.closeNavigation() } R.id.navigationSettingsTextView -> { view.startSettingActivity() view.closeNavigation() } R.id.navigationKeywordSearchTextView -> { view.startKeywordSearchActivity() view.closeNavigation() } R.id.navigationUserSearchTextView -> { view.startUserSearchActivity() view.closeNavigation() } R.id.navigationMyBookmarksButton -> { view.startMyBookmarksActivity() view.closeNavigation() } R.id.navigationLoginButton -> { view.startLoginActivity() view.closeNavigation() } } } fun onCategoryClick(category: Category) { view.closeNavigation() view.refreshShowCategoryAndType(category, selectedType) selectedCategory = category } fun onAdditionUserClick(userId: String) { view.closeNavigation() view.startUserSearchActivity(userId) } fun onAdditionUserLongClick(userId: String, target: View): Boolean { view.showDeleteUserDialog(userId, target) return false } fun onAdditionKeywordClick(keyword: String) { view.closeNavigation() view.startKeywordSearchActivity(keyword) } fun onAdditionKeywordLongClick(keyword: String, target: View): Boolean { view.showDeleteKeywordDialog(keyword, target) return false } fun onDeleteUserIdDialogClick(word: String, target: View) { useCase.deleteAdditionUser(word) target.visibility = View.GONE } fun onDeleteKeywordDialogClick(word: String, target: View) { useCase.deleteAdditionKeyword(word) target.visibility = View.GONE } }
apache-2.0
b281f2412281e3268f60d0a76e17d177
29.867133
92
0.630041
4.715812
false
false
false
false
nebula-plugins/nebula-bintray-plugin
src/main/kotlin/nebula/plugin/bintray/NebulaBintrayAbstractTask.kt
1
2440
/* * Copyright 2019 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 nebula.plugin.bintray import org.gradle.api.DefaultTask import org.gradle.api.GradleException import org.gradle.api.provider.Property import org.gradle.api.provider.Provider import org.gradle.api.tasks.Input import org.gradle.api.tasks.Internal import org.gradle.api.tasks.Optional import org.gradle.kotlin.dsl.property open class NebulaBintrayAbstractTask : DefaultTask() { protected companion object { const val UNSET = "UNSET" } @Input val user: Property<String> = project.objects.property() @Input val apiKey: Property<String> = project.objects.property() @Input val apiUrl: Property<String> = project.objects.property() @Input val pkgName: Property<String> = project.objects.property() @Input val repo: Property<String> = project.objects.property() @Input @Optional val userOrg: Property<String> = project.objects.property() @Input @Optional val version: Property<String> = project.objects.property() @Internal val readTimeoutInSeconds: Property<Long> = project.objects.property() @Internal val connectionTimeoutInSeconds: Property<Long> = project.objects.property() @Internal val resolveSubject : Provider<String> = user.map { val resolvedSubject = userOrg.getOrElse(user.get()) if (resolvedSubject.isNotSet()) { throw GradleException("userOrg or bintray.user must be set") } resolvedSubject } @Internal val resolveVersion : Provider<String> = version.map { val resolvedVersion = version.getOrElse(UNSET) if (resolvedVersion == "unspecified" || resolvedVersion.isNotSet()) { throw GradleException("version or project.version must be set") } resolvedVersion } private fun String.isNotSet() = this == UNSET }
apache-2.0
1ac902c377088fd77b8f21d172a7f2d1
31.546667
79
0.704918
4.250871
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/problem/rest/RestCallResult.kt
1
2074
package org.evomaster.core.problem.rest import com.google.common.annotations.VisibleForTesting import com.google.gson.Gson import com.google.gson.JsonObject import org.evomaster.core.problem.httpws.service.HttpWsCallResult import org.evomaster.core.search.Action import org.evomaster.core.search.ActionResult import javax.ws.rs.core.MediaType class RestCallResult : HttpWsCallResult { constructor(stopping: Boolean = false) : super(stopping) @VisibleForTesting internal constructor(other: ActionResult) : super(other) companion object { const val HEURISTICS_FOR_CHAINED_LOCATION = "HEURISTICS_FOR_CHAINED_LOCATION" } override fun copy(): ActionResult { return RestCallResult(this) } fun getResourceIdName() = "id" fun getResourceId(): String? { if(!MediaType.APPLICATION_JSON_TYPE.isCompatible(getBodyType())){ //TODO could also handle other media types return null } return getBody()?.let { try { /* TODO: "id" is the most common word, but could check if others are used as well. */ Gson().fromJson(it, JsonObject::class.java).get(getResourceIdName())?.asString } catch (e: Exception){ //nothing to do null } } } /** * It might happen that we need to chain call location, but * there was no "location" header in the response of call that * created a new resource. However, it "might" still be possible * to try to infer the location (based on object response and * the other available endpoints in the API) */ fun setHeuristicsForChainedLocation(on: Boolean) = addResultValue(HEURISTICS_FOR_CHAINED_LOCATION, on.toString()) fun getHeuristicsForChainedLocation(): Boolean = getResultValue(HEURISTICS_FOR_CHAINED_LOCATION)?.toBoolean() ?: false override fun matchedType(action: Action): Boolean { return action is RestCallAction } }
lgpl-3.0
70513b9ec02e247f41b4ae85e886ff93
30.907692
122
0.655256
4.619154
false
false
false
false
grote/BlitzMail
src/de/grobox/blitzmail/send/SendLaterWorker.kt
1
1352
package de.grobox.blitzmail.send import android.content.Context import android.content.Intent import androidx.core.content.ContextCompat.startForegroundService import androidx.work.* import androidx.work.ListenableWorker.Result.success import de.grobox.blitzmail.send.SendActivity.ACTION_RESEND import java.util.concurrent.TimeUnit class SendLaterWorker(context: Context, params: WorkerParameters) : Worker(context, params) { override fun doWork(): Result { val intent = Intent(applicationContext, SenderService::class.java) startForegroundService(applicationContext, intent) return success() } } fun scheduleSending(delayInMinutes: Long = 5) { val workManager = WorkManager.getInstance() val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() val worker = OneTimeWorkRequestBuilder<SendLaterWorker>() .setInitialDelay(delayInMinutes, TimeUnit.MINUTES) .setConstraints(constraints) .build() workManager.enqueue(worker) } fun sendQueuedMails(context: Context) { val intent = Intent(context, SendActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK) intent.action = ACTION_RESEND context.startActivity(intent) }
agpl-3.0
da8e429e826dc57b38900082cf5bf267
33.666667
93
0.745562
4.552189
false
false
false
false
kpspemu/kpspemu
src/jvmMain/kotlin/com/soywiz/dynarek2/target/jvm/JvmGenerator.kt
1
12669
package com.soywiz.dynarek2.target.jvm import com.soywiz.dynarek2.* import org.objectweb.asm.* import org.objectweb.asm.Type import java.lang.reflect.* import kotlin.reflect.* class JvmGenerator { val objectRef = java.lang.Object::class.asmRef val d2MemoryRef = D2Memory::class.asmRef //val classLoader = this::class.javaClass.classLoader // 0: this // 1: regs // 2: mem // 3: temp // 4: external fun generate(func: D2Func, context: D2Context, name: String?, debug: Boolean): D2Result { val cw = ClassWriter(0) val className = "Dynarek2Generated" cw.visit( Opcodes.V1_5, Opcodes.ACC_PUBLIC or Opcodes.ACC_FINAL, className, null, java.lang.Object::class.internalName, arrayOf(D2KFuncInt::class.java.internalName) ) cw.apply { // constructor visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null).apply { visitMaxs(2, 1) visitVarInsn(Opcodes.ALOAD, 0) // push `this` to the operand stack visitMethodInsn( Opcodes.INVOKESPECIAL, java.lang.Object::class.internalName, "<init>", "()V", false ) // call the constructor of super class visitInsn(Opcodes.RETURN) visitEnd() } // invoke method visitMethod( Opcodes.ACC_PUBLIC, "invoke", "($d2MemoryRef$d2MemoryRef$d2MemoryRef$objectRef)I", null, null ).apply { visitMaxs(32, 32) generate(func.body) // DUMMY to make valid labels pushInt(0) visitIReturn() visitEnd() } } cw.visitEnd() val classBytes = cw.toByteArray() try { val gclazz = createDynamicClass<D2KFuncInt>( ClassLoader.getSystemClassLoader(), className.replace('/', '.'), classBytes ) val instance = gclazz.declaredConstructors.first().newInstance() as D2KFuncInt return D2Result(name, debug, classBytes, instance::invoke, free = { }) } catch (e: VerifyError) { throw D2InvalidCodeGen("JvmGenerator", classBytes, e) } } fun MethodVisitor.generate(s: D2Stm): Unit = when (s) { is D2Stm.Stms -> for (c in s.children) generate(c) is D2Stm.Expr -> { generate(s.expr) visitPop() } is D2Stm.Return -> { generate(s.expr) visitIReturn() } is D2Stm.Set<*> -> { val ref = s.ref visitIntInsn(Opcodes.ALOAD, ref.memSlot.jArgIndex) generate(ref.offset) generate(s.value) val methodName = when (ref.size) { D2Size.BYTE -> JvmMemTools::set8.name D2Size.SHORT -> JvmMemTools::set16.name D2Size.INT -> JvmMemTools::set32.name D2Size.FLOAT -> JvmMemTools::setF32.name D2Size.LONG -> JvmMemTools::set64.name } val primType = ref.size.jPrimType val signature = "(${d2MemoryRef}I$primType)V" //println("signature:$signature") visitMethodInsn( Opcodes.INVOKESTATIC, JvmMemTools::class.internalName, methodName, signature, false ) } is D2Stm.If -> { val cond = s.cond val strue = s.strue val sfalse = s.sfalse if (sfalse == null) { // IF val endLabel = Label() generateJumpFalse(cond, endLabel) generate(strue) visitLabel(endLabel) } else { // IF+ELSE val elseLabel = Label() val endLabel = Label() generateJumpFalse(cond, elseLabel) generate(strue) generateJumpAlways(endLabel) visitLabel(elseLabel) generate(sfalse) visitLabel(endLabel) } } is D2Stm.While -> { val startLabel = Label() val endLabel = Label() visitLabel(startLabel) generateJumpFalse(s.cond, endLabel) generate(s.body) generateJumpAlways(startLabel) visitLabel(endLabel) } else -> TODO("$s") } val D2Size.jPrimType get() = when (this) { D2Size.BYTE, D2Size.SHORT, D2Size.INT -> 'I' D2Size.FLOAT -> 'F' D2Size.LONG -> 'J' } fun MethodVisitor.generateJump(e: D2Expr<*>, label: Label, isTrue: Boolean): Unit { generate(e) visitJumpInsn(if (isTrue) Opcodes.IFNE else Opcodes.IFEQ, label) } fun MethodVisitor.generateJumpFalse(e: D2Expr<*>, label: Label): Unit = generateJump(e, label, false) fun MethodVisitor.generateJumpTrue(e: D2Expr<*>, label: Label): Unit = generateJump(e, label, true) fun MethodVisitor.generateJumpAlways(label: Label): Unit = visitJumpInsn(Opcodes.GOTO, label) val D2MemSlot.jArgIndex get() = this.index + 1 // 0 is used for THIS fun MethodVisitor.generate(e: D2Expr<*>): Unit { when (e) { is D2Expr.ILit -> pushInt(e.lit) is D2Expr.FLit -> pushFloat(e.lit) is D2Expr.LLit -> pushLong(e.lit) is D2Expr.IBinOp -> { generate(e.l) generate(e.r) when (e.op) { D2IBinOp.ADD -> visitInsn(Opcodes.IADD) D2IBinOp.SUB -> visitInsn(Opcodes.ISUB) D2IBinOp.MUL -> visitInsn(Opcodes.IMUL) D2IBinOp.DIV -> visitInsn(Opcodes.IDIV) D2IBinOp.REM -> visitInsn(Opcodes.IREM) D2IBinOp.SHL -> visitInsn(Opcodes.ISHL) D2IBinOp.SHR -> visitInsn(Opcodes.ISHR) D2IBinOp.USHR -> visitInsn(Opcodes.IUSHR) D2IBinOp.OR -> visitInsn(Opcodes.IOR) D2IBinOp.AND -> visitInsn(Opcodes.IAND) D2IBinOp.XOR -> visitInsn(Opcodes.IXOR) } } is D2Expr.LBinOp -> { generate(e.l) generate(e.r) when (e.op) { D2IBinOp.ADD -> visitInsn(Opcodes.LADD) D2IBinOp.SUB -> visitInsn(Opcodes.LSUB) D2IBinOp.MUL -> visitInsn(Opcodes.LMUL) D2IBinOp.DIV -> visitInsn(Opcodes.LDIV) D2IBinOp.REM -> visitInsn(Opcodes.LREM) D2IBinOp.SHL -> visitInsn(Opcodes.LSHL) D2IBinOp.SHR -> visitInsn(Opcodes.LSHR) D2IBinOp.USHR -> visitInsn(Opcodes.LUSHR) D2IBinOp.OR -> visitInsn(Opcodes.LOR) D2IBinOp.AND -> visitInsn(Opcodes.LAND) D2IBinOp.XOR -> visitInsn(Opcodes.LXOR) } } is D2Expr.FBinOp -> { generate(e.l) generate(e.r) when (e.op) { D2FBinOp.ADD -> visitInsn(Opcodes.FADD) D2FBinOp.SUB -> visitInsn(Opcodes.FSUB) D2FBinOp.MUL -> visitInsn(Opcodes.FMUL) D2FBinOp.DIV -> visitInsn(Opcodes.FDIV) //D2FBinOp.REM -> visitInsn(Opcodes.FREM) } } is D2Expr.IComOp -> { generate(e.l) generate(e.r) val opcode = when (e.op) { D2CompOp.EQ -> Opcodes.IF_ICMPEQ D2CompOp.NE -> Opcodes.IF_ICMPNE D2CompOp.LT -> Opcodes.IF_ICMPLT D2CompOp.LE -> Opcodes.IF_ICMPLE D2CompOp.GT -> Opcodes.IF_ICMPGT D2CompOp.GE -> Opcodes.IF_ICMPGE } val label1 = Label() val label2 = Label() visitJumpInsn(opcode, label1) pushBool(false) visitJumpInsn(Opcodes.GOTO, label2) visitLabel(label1) pushBool(true) visitLabel(label2) } is D2Expr.IUnop -> { generate(e.l) when (e.op) { D2UnOp.NEG -> visitInsn(Opcodes.INEG) D2UnOp.INV -> TODO() } } is D2Expr.Ref -> { visitIntInsn(Opcodes.ALOAD, e.memSlot.jArgIndex) generate(e.offset) val methodName = when (e.size) { D2Size.BYTE -> JvmMemTools::get8.name D2Size.SHORT -> JvmMemTools::get16.name D2Size.INT -> JvmMemTools::get32.name D2Size.LONG -> JvmMemTools::get64.name D2Size.FLOAT -> JvmMemTools::getF32.name } val retType = e.size.jPrimType visitMethodInsn( Opcodes.INVOKESTATIC, JvmMemTools::class.internalName, methodName, "(${d2MemoryRef}I)$retType", false ) } is D2Expr.Invoke<*> -> { val func = e.func val name = func.name val owner = func.owner val smethod = func.method if (smethod.parameterCount != e.args.size) error("Arity mismatch generating method call") val signature = "(" + smethod.signature.substringAfter('(') for ((index, arg) in e.args.withIndex()) { generate(arg) val param = smethod.parameterTypes[index] if (!param.isPrimitive) { //println("PARAM: $param") visitTypeInsn(Opcodes.CHECKCAST, param.internalName) } } visitMethodInsn(Opcodes.INVOKESTATIC, owner.internalName, name, signature, false) } is D2Expr.External -> { visitVarInsn(Opcodes.ALOAD, 4) } else -> TODO("$e") } return } fun <T> createDynamicClass(parent: ClassLoader, clazzName: String, b: ByteArray): Class<T> = OwnClassLoader(parent).defineClass(clazzName, b) as Class<T> private class OwnClassLoader(parent: ClassLoader) : ClassLoader(parent) { fun defineClass(name: String, b: ByteArray): Class<*> = defineClass(name, b, 0, b.size) } } val KFunction<*>.owner: Class<*> get() = (javaClass.methods.first { it.name == "getOwner" }.apply { isAccessible = true }.invoke(this) as kotlin.jvm.internal.PackageReference).jClass val KFunction<*>.fullSignature: String get() = javaClass.methods.first { it.name == "getSignature" }.apply { isAccessible = true }.invoke(this) as String val KFunction<*>.method: Method get() = owner.methods.firstOrNull { it.name == name } ?: error("Can't find method $name") object JvmMemTools { @JvmStatic fun get8(m: D2Memory, index: Int): Int = m.get8(index) @JvmStatic fun get16(m: D2Memory, index: Int): Int = m.get16(index) @JvmStatic fun get32(m: D2Memory, index: Int): Int = m.get32(index) @JvmStatic fun get64(m: D2Memory, index: Int): Long = m.get64(index) @JvmStatic fun set8(m: D2Memory, index: Int, value: Int) = m.set8(index, value) @JvmStatic fun set16(m: D2Memory, index: Int, value: Int) = m.set16(index, value) @JvmStatic fun set32(m: D2Memory, index: Int, value: Int) = m.set32(index, value) @JvmStatic fun set64(m: D2Memory, index: Int, value: Long) = m.set64(index, value) @JvmStatic fun getF32(m: D2Memory, index: Int): Float = Float.fromBits(m.get32(index)) @JvmStatic fun setF32(m: D2Memory, index: Int, value: Float) = m.set32(index, value.toRawBits()) @JvmStatic fun printi(i: Int): Unit = println(i) } val <T> Class<T>.internalName get() = Type.getInternalName(this) val <T : Any> KClass<T>.internalName get() = this.java.internalName val <T> Class<T>.asmRef get() = "L" + this.internalName + ";" val <T : Any> KClass<T>.asmRef get() = this.java.asmRef
mit
2b8d01755705669a9ffdcb19582cfbff
35.615607
182
0.511958
4.090733
false
false
false
false
Litote/kmongo
kmongo-annotation-processor/src/test/kotlin/org/litote/kmongo/model/other/SimpleReferencedData.kt
1
1852
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo.model.other import org.litote.kmongo.Data import org.litote.kmongo.model.SimpleReferenced2Data import org.litote.kmongo.model.SubData import org.litote.kmongo.model.TestData import java.util.Locale /** * */ @Data class SimpleReferencedData { var version: Int = 0 private val pojo2: SimpleReferenced2Data? = null var pojo: TestData? = null private val subPojo: SubData? = null val labels: Map<Locale, List<String>> = emptyMap() override fun toString(): String { return "SimpleReferencedData(version=$version, pojo2=$pojo2, pojo=$pojo, subPojo=$subPojo)" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SimpleReferencedData) return false if (version != other.version) return false if (pojo2 != other.pojo2) return false if (pojo != other.pojo) return false if (subPojo != other.subPojo) return false return true } override fun hashCode(): Int { var result = version result = 31 * result + (pojo2?.hashCode() ?: 0) result = 31 * result + (pojo?.hashCode() ?: 0) result = 31 * result + (subPojo?.hashCode() ?: 0) return result } }
apache-2.0
68bbfd578546a172bf752cc38214eae7
28.887097
99
0.674946
4
false
false
false
false
sonnytron/FitTrainerBasic
mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/adapters/WorkoutItemUi.kt
1
1239
package com.sonnyrodriguez.fittrainer.fittrainerbasic.adapters import android.support.v4.content.ContextCompat import android.view.Gravity import android.view.ViewGroup import com.sonnyrodriguez.fittrainer.fittrainerbasic.R import org.jetbrains.anko.* class WorkoutItemUi: AnkoComponent<ViewGroup> { override fun createView(ui: AnkoContext<ViewGroup>) = with(ui) { relativeLayout { backgroundDrawable = ContextCompat.getDrawable(ctx, R.drawable.list_background_white) lparams(width = matchParent, height = dimen(R.dimen.single_list_item_default_height)) { horizontalMargin = dip(16) topMargin = dip(6) } verticalLayout { themedTextView(R.style.BasicListItemTitle) { id = R.id.workout_item_title }.lparams(width = matchParent, height = wrapContent) { gravity = Gravity.CENTER } themedTextView(R.style.BasicListItemStyle) { id = R.id.workout_exercise_count }.lparams(width = matchParent, height = wrapContent) { gravity = Gravity.BOTTOM } } } } }
apache-2.0
481064855b15d1c720861df6b1d9d0d9
38.967742
99
0.607748
4.897233
false
false
false
false
RocketChat/Rocket.Chat.Android
suggestions/src/main/java/chat/rocket/android/suggestions/strategy/trie/data/Trie.kt
2
1996
package chat.rocket.android.suggestions.strategy.trie.data import chat.rocket.android.suggestions.model.SuggestionModel internal class Trie { private val root = TrieNode(' ') private var count = 0 fun insert(item: SuggestionModel) { val sanitizedWord = item.text.trim().toLowerCase() // Word exists, bail out. if (search(sanitizedWord)) return var current = root sanitizedWord.forEach { ch -> val child = current.getChild(ch) if (child == null) { val node = TrieNode(ch, current) current.children[ch] = node current = node count++ } else { current = child } } // Set last node as leaf. if (current != root) { current.isLeaf = true current.item = item } } fun search(word: String): Boolean { val sanitizedWord = word.trim().toLowerCase() var current = root sanitizedWord.forEach { ch -> val child = current.getChild(ch) ?: return false current = child } if (current.isLeaf) { return true } return false } fun autocomplete(prefix: String): List<String> { val sanitizedPrefix = prefix.trim().toLowerCase() var lastNode: TrieNode? = root sanitizedPrefix.forEach { ch -> lastNode = lastNode?.getChild(ch) if (lastNode == null) return emptyList() } return lastNode!!.getWords() } fun autocompleteItems(prefix: String): List<SuggestionModel> { val sanitizedPrefix = prefix.trim().toLowerCase() var lastNode: TrieNode? = root sanitizedPrefix.forEach { ch -> lastNode = lastNode?.getChild(ch) if (lastNode == null) return emptyList() } return lastNode!!.getItems().take(5).toList() } fun getCount() = count }
mit
67d0a1c587edd9c7713dbf3b72323849
28.791045
66
0.553106
4.729858
false
false
false
false
Cognifide/AET
core/accessibility-report/src/main/kotlin/com/cognifide/aet/accessibility/report/models/AccessibilityIssue.kt
1
2327
/* * AET * * Copyright (C) 2020 Cognifide Limited * * 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.cognifide.aet.accessibility.report.models import java.io.Serializable import java.util.Objects class AccessibilityIssue( val type: IssueType, val message: String, val code: String, val elementString: String, val elementStringAbbreviated: String) : Serializable { var lineNumber = 0 var columnNumber = 0 var isExcluded = false private set var url: String = "" fun getAccessibilityCode(): AccessibilityCode = AccessibilityCode(code) override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other == null || javaClass != other.javaClass) { return false } val that = other as AccessibilityIssue return (lineNumber == that.lineNumber && columnNumber == that.columnNumber && isExcluded == that.isExcluded && type == that.type && message == that.message && code == that.code && elementString == that.elementString && elementStringAbbreviated == that.elementStringAbbreviated && url == that.url) } override fun hashCode(): Int { return Objects.hash( type, message, code, elementString, elementStringAbbreviated, lineNumber, columnNumber, isExcluded, url) } enum class IssueType { ERROR, WARN, NOTICE, UNKNOWN; companion object { fun fromString(issue: String): IssueType? = values().find { it.toString() == issue.toUpperCase() } ?: throw IllegalArgumentException("Unrecognized value for issue verbosity was provided: $issue") } } companion object { private const val serialVersionUID = -53665467524179701L } }
apache-2.0
986075579d50e5752f030f436235746f
27.378049
110
0.664375
4.492278
false
false
false
false
gradle/gradle
subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/TrackingDynamicLookupRoutine.kt
2
2735
/* * Copyright 2022 the original author or authors. * * 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.gradle.configurationcache import groovy.lang.MissingPropertyException import org.gradle.api.internal.project.DynamicLookupRoutine import org.gradle.configuration.internal.DynamicCallContextTracker import org.gradle.internal.Factory import org.gradle.internal.deprecation.DeprecationLogger import org.gradle.internal.metaobject.DynamicInvokeResult import org.gradle.internal.metaobject.DynamicObject class TrackingDynamicLookupRoutine( private val dynamicCallContextTracker: DynamicCallContextTracker ) : DynamicLookupRoutine { @Throws(MissingPropertyException::class) override fun property(receiver: DynamicObject, propertyName: String): Any? = withDynamicCall(receiver) { receiver.getProperty(propertyName) } override fun findProperty(receiver: DynamicObject, propertyName: String): Any? = withDynamicCall(receiver) { val dynamicInvokeResult: DynamicInvokeResult = receiver.tryGetProperty(propertyName) if (dynamicInvokeResult.isFound) dynamicInvokeResult.value else null } override fun setProperty(receiver: DynamicObject, name: String, value: Any?) = withDynamicCall(receiver) { receiver.setProperty(name, value) } override fun hasProperty(receiver: DynamicObject, propertyName: String): Boolean = withDynamicCall(receiver) { receiver.hasProperty(propertyName) } override fun getProperties(receiver: DynamicObject): Map<String, *>? = withDynamicCall(receiver) { DeprecationLogger.whileDisabled(Factory<Map<String, *>> { receiver.properties }) } override fun invokeMethod(receiver: DynamicObject, name: String, args: Array<Any>): Any? = withDynamicCall(receiver) { receiver.invokeMethod(name, *args) } private fun <T> withDynamicCall(entryPoint: Any, action: () -> T): T = try { dynamicCallContextTracker.enterDynamicCall(entryPoint) action() } finally { dynamicCallContextTracker.leaveDynamicCall(entryPoint) } }
apache-2.0
277e4351b470e5e799acd29c449b966d
36.986111
96
0.719561
4.691252
false
false
false
false
premnirmal/StockTicker
app/src/main/kotlin/com/github/premnirmal/ticker/ui/StockFieldView.kt
1
4290
package com.github.premnirmal.ticker.ui import android.content.Context import android.content.res.TypedArray import android.util.AttributeSet import android.util.TypedValue import android.view.Gravity import android.view.LayoutInflater import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import com.github.premnirmal.tickerwidget.R import com.robinhood.ticker.TickerUtils import com.robinhood.ticker.TickerView /** * Created by premnirmal on 2/27/16. */ class StockFieldView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : LinearLayout(context, attrs) { companion object { const val ORIENTATION_HORIZONTAL = 0 const val ORIENTATION_VERTICAL = 1 const val GRAVITY_LEFT = 0 const val GRAVITY_RIGHT = 1 const val GRAVITY_CENTER = 2 } private val fieldname: TextView private val fieldvalue: TickerView init { LayoutInflater.from(context) .inflate(R.layout.stock_field_view, this, true) fieldname = findViewById(R.id.fieldname) fieldvalue = findViewById(R.id.fieldvalue) fieldvalue.setCharacterLists(TickerUtils.provideNumberList()) attrs?.let { val array = context.obtainStyledAttributes(it, R.styleable.StockFieldView) val orientation = array.getInt(R.styleable.StockFieldView_or, 0) if (orientation == ORIENTATION_HORIZONTAL) { setOrientation(HORIZONTAL) fieldname.layoutParams = LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 0.5f) fieldvalue.layoutParams = LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 0.5f) fieldvalue.gravity = Gravity.END } else { setOrientation(VERTICAL) fieldname.layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) fieldvalue.layoutParams = LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) fieldvalue.gravity = Gravity.START } weightSum = 1f val name = getStringValue(context, array, R.styleable.StockFieldView_name) fieldname.text = name val textSize = array.getDimensionPixelSize(R.styleable.StockFieldView_size, 20) .toFloat() fieldname.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize) fieldvalue.setTextSize(textSize * 0.9f) val centerText = array.getBoolean(R.styleable.StockFieldView_center_text, false) when { centerText -> { fieldname.gravity = Gravity.CENTER fieldvalue.gravity = Gravity.CENTER } orientation == ORIENTATION_HORIZONTAL -> { fieldname.gravity = Gravity.START fieldvalue.gravity = Gravity.END } orientation == ORIENTATION_VERTICAL -> { val textGravity = array.getInt(R.styleable.StockFieldView_text_gravity, 0) when (textGravity) { GRAVITY_LEFT -> { fieldname.gravity = Gravity.START fieldvalue.gravity = Gravity.START } GRAVITY_RIGHT -> { fieldname.gravity = Gravity.END fieldvalue.gravity = Gravity.END } GRAVITY_CENTER -> { fieldname.gravity = Gravity.CENTER fieldvalue.gravity = Gravity.CENTER } } } } array.recycle() } } constructor( context: Context, attrs: AttributeSet, defStyleAttr: Int ) : this(context, attrs) constructor( context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int ) : this( context, attrs ) fun setLabel(text: CharSequence?) { fieldname.text = text } fun setText(text: CharSequence?) { fieldvalue.text = text.toString() } fun setTextColor(color: Int) { fieldvalue.textColor = color } private fun getStringValue( context: Context, array: TypedArray, stylelable: Int ): String { var name = array.getString(stylelable) if (name == null) { val stringId = array.getResourceId(stylelable, -1) name = if (stringId > 0) { context.getString(stringId) } else { "" } } return name } }
gpl-3.0
788b352d1bd7a7f8d461c7fac415a9f3
28.190476
86
0.654079
4.364191
false
false
false
false
AlmasB/FXGL
fxgl-scene/src/main/kotlin/com/almasb/fxgl/ui/InGamePanel.kt
1
1740
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.ui import com.almasb.fxgl.animation.Interpolators import javafx.animation.TranslateTransition import javafx.geometry.HorizontalDirection import javafx.scene.layout.Pane import javafx.scene.paint.Color import javafx.scene.shape.Rectangle import javafx.util.Duration /** * An in-game semi-transparent panel with in/out animations. * Can be used to display various UI elements, e.g. game score, inventory, * player stats, etc. * * @author Almas Baimagambetov ([email protected]) */ class InGamePanel(val panelWidth: Double, val panelHeight: Double, val direction: HorizontalDirection = HorizontalDirection.LEFT) : Pane() { var isOpen = false private set init { translateX = -panelWidth - 4 val bg = Rectangle(panelWidth, panelHeight, Color.color(0.0, 0.0, 0.0, 0.85)) children += bg isDisable = true } fun open() { if (isOpen) return isOpen = true isDisable = false val translation = TranslateTransition(Duration.seconds(0.33), this) with(translation) { interpolator = Interpolators.EXPONENTIAL.EASE_OUT() toX = 0.0 play() } } fun close() { if (!isOpen) return isOpen = false isDisable = true val translation = TranslateTransition(Duration.seconds(0.33), this) with(translation) { interpolator = Interpolators.EXPONENTIAL.EASE_OUT() toX = -panelWidth - 4 play() } } }
mit
9aeae7fdcc157c560c38f640feddb809
23.871429
91
0.620115
4.202899
false
false
false
false
duftler/orca
orca-queue-tck/src/main/kotlin/com/netflix/spinnaker/orca/q/PendingExecutionServiceTest.kt
1
3985
package com.netflix.spinnaker.orca.q import com.netflix.spinnaker.orca.fixture.pipeline import com.netflix.spinnaker.orca.fixture.stage import com.netflix.spinnaker.orca.q.pending.PendingExecutionService import com.netflix.spinnaker.q.Message import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import org.assertj.core.api.Assertions import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import org.jetbrains.spek.subject.SubjectSpek import java.util.UUID object PendingExecutionServiceTest : SubjectSpek<PendingExecutionService>({ val id = UUID.randomUUID().toString() val pipeline = pipeline { pipelineConfigId = id stage { refId = "1" } stage { refId = "2" requisiteStageRefIds = setOf("1") } } val startMessage = StartExecution(pipeline) val restartMessage = RestartStage(pipeline.stageByRef("2"), "[email protected]") val callback = mock<(Message) -> Unit>() sequenceOf<Message>(startMessage, restartMessage).forEach { message -> describe("enqueueing a ${message.javaClass.simpleName} message") { given("the queue is empty") { beforeGroup { Assertions.assertThat(subject.depth(id)).isZero() } on("enqueueing the message") { subject.enqueue(id, message) it("makes the depth 1") { Assertions.assertThat(subject.depth(id)).isOne() } } afterGroup { subject.purge(id, callback) } } } } describe("popping a message") { given("the queue is empty") { beforeGroup { Assertions.assertThat(subject.depth(id)).isZero() } on("popping a message") { val popped = subject.popOldest(id) it("returns null") { Assertions.assertThat(popped).isNull() } } } given("a message was enqueued") { beforeGroup { subject.enqueue(id, startMessage) } on("popping a message") { val popped = subject.popOldest(id) it("returns the message") { Assertions.assertThat(popped).isEqualTo(startMessage) } it("removes the message from the queue") { Assertions.assertThat(subject.depth(id)).isZero() } } afterGroup { subject.purge(id, callback) } } given("multiple messages were enqueued") { beforeEachTest { subject.enqueue(id, startMessage) subject.enqueue(id, restartMessage) } on("popping the oldest message") { val popped = subject.popOldest(id) it("returns the oldest message") { Assertions.assertThat(popped).isEqualTo(startMessage) } it("removes the message from the queue") { Assertions.assertThat(subject.depth(id)).isOne() } } on("popping the newest message") { val popped = subject.popNewest(id) it("returns the newest message") { Assertions.assertThat(popped).isEqualTo(restartMessage) } it("removes the message from the queue") { Assertions.assertThat(subject.depth(id)).isOne() } } afterEachTest { subject.purge(id, callback) } } } describe("purging the queue") { val purgeCallback = mock<(Message) -> Unit>() given("there are some messages on the queue") { beforeGroup { subject.enqueue(id, startMessage) subject.enqueue(id, restartMessage) } on("purging the queue") { subject.purge(id, purgeCallback) it("makes the queue empty") { Assertions.assertThat(subject.depth(id)).isZero() } it("invokes the callback passing each message") { verify(purgeCallback).invoke(startMessage) verify(purgeCallback).invoke(restartMessage) } } afterGroup { subject.purge(id, callback) } } } })
apache-2.0
3219d6ac955537276c46ef74daadbdc0
25.925676
82
0.630615
4.294181
false
false
false
false
dslomov/intellij-community
plugins/settings-repository/src/IcsBundle.kt
23
911
package org.jetbrains.settingsRepository import com.intellij.CommonBundle import org.jetbrains.annotations.PropertyKey import java.lang.ref.Reference import java.lang.ref.SoftReference import java.util.ResourceBundle import kotlin.platform.platformStatic class IcsBundle { companion object { private var ourBundle: Reference<ResourceBundle>? = null val BUNDLE: String = "messages.IcsBundle" platformStatic fun message(PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any?): String { return CommonBundle.message(getBundle(), key, *params) } private fun getBundle(): ResourceBundle { var bundle: ResourceBundle? = null if (ourBundle != null) { bundle = ourBundle!!.get() } if (bundle == null) { bundle = ResourceBundle.getBundle(BUNDLE) ourBundle = SoftReference(bundle) } return bundle!! } } }
apache-2.0
a7641c35ec41fe9a864a817618af80fd
26.636364
96
0.701427
4.577889
false
false
false
false
coil-kt/coil
coil-compose-base/src/main/java/coil/compose/ImagePainter.kt
1
4144
@file:Suppress("NOTHING_TO_INLINE", "UNUSED_PARAMETER") package coil.compose import androidx.compose.runtime.Composable import androidx.compose.ui.geometry.Size import androidx.compose.ui.platform.LocalContext import coil.ImageLoader import coil.compose.AsyncImagePainter.State import coil.request.ImageRequest @Deprecated( message = "ImagePainter has been renamed to AsyncImagePainter.", replaceWith = ReplaceWith( expression = "AsyncImagePainter", imports = ["coil.compose.AsyncImagePainter"] ) ) typealias ImagePainter = AsyncImagePainter @Deprecated( message = "ImagePainter has been renamed to AsyncImagePainter.", replaceWith = ReplaceWith( expression = "rememberAsyncImagePainter(data, imageLoader)", imports = ["coil.compose.rememberAsyncImagePainter"] ) ) @Composable inline fun rememberImagePainter( data: Any?, imageLoader: ImageLoader, ) = rememberAsyncImagePainter(data, imageLoader) @Deprecated( message = "ImagePainter has been renamed to AsyncImagePainter.", replaceWith = ReplaceWith( expression = "rememberAsyncImagePainter(data, imageLoader)", imports = ["coil.compose.rememberAsyncImagePainter"] ), level = DeprecationLevel.ERROR // ExecuteCallback is no longer supported. ) @Composable inline fun rememberImagePainter( data: Any?, imageLoader: ImageLoader, onExecute: ExecuteCallback ) = rememberAsyncImagePainter(data, imageLoader) @Deprecated( message = "ImagePainter has been renamed to AsyncImagePainter.", replaceWith = ReplaceWith( expression = "rememberAsyncImagePainter(ImageRequest.Builder(LocalContext.current)" + ".data(data).apply(builder).build(), imageLoader)", imports = [ "androidx.compose.ui.platform.LocalContext", "coil.compose.rememberAsyncImagePainter", "coil.request.ImageRequest", ] ) ) @Composable inline fun rememberImagePainter( data: Any?, imageLoader: ImageLoader, builder: ImageRequest.Builder.() -> Unit, ) = rememberAsyncImagePainter( model = ImageRequest.Builder(LocalContext.current).data(data).apply(builder).build(), imageLoader = imageLoader ) @Deprecated( message = "ImagePainter has been renamed to AsyncImagePainter.", replaceWith = ReplaceWith( expression = "rememberAsyncImagePainter(ImageRequest.Builder(LocalContext.current)" + ".data(data).apply(builder).build(), imageLoader)", imports = [ "androidx.compose.ui.platform.LocalContext", "coil.compose.rememberAsyncImagePainter", "coil.request.ImageRequest", ] ), level = DeprecationLevel.ERROR // ExecuteCallback is no longer supported. ) @Composable inline fun rememberImagePainter( data: Any?, imageLoader: ImageLoader, onExecute: ExecuteCallback, builder: ImageRequest.Builder.() -> Unit, ) = rememberAsyncImagePainter( model = ImageRequest.Builder(LocalContext.current).data(data).apply(builder).build(), imageLoader = imageLoader ) @Deprecated( message = "ImagePainter has been renamed to AsyncImagePainter.", replaceWith = ReplaceWith( expression = "rememberAsyncImagePainter(request, imageLoader)", imports = ["coil.compose.rememberAsyncImagePainter"] ) ) @Composable inline fun rememberImagePainter( request: ImageRequest, imageLoader: ImageLoader, ) = rememberAsyncImagePainter(request, imageLoader) @Deprecated( message = "ImagePainter has been renamed to AsyncImagePainter.", replaceWith = ReplaceWith( expression = "rememberAsyncImagePainter(request, imageLoader)", imports = ["coil.compose.rememberAsyncImagePainter"] ), level = DeprecationLevel.ERROR // ExecuteCallback is no longer supported. ) @Composable inline fun rememberImagePainter( request: ImageRequest, imageLoader: ImageLoader, onExecute: ExecuteCallback, ) = rememberAsyncImagePainter(request, imageLoader) private typealias ExecuteCallback = (Snapshot, Snapshot) -> Boolean private typealias Snapshot = Triple<State, ImageRequest, Size>
apache-2.0
772bd6303874534f29d8ca6321e56dda
32.152
93
0.723938
5.066015
false
false
false
false
madtcsa/AppManager
app/src/main/java/com/md/appmanager/activities/SettingsActivity.kt
1
6921
package com.md.appmanager.activities import android.content.Context import android.content.SharedPreferences import android.content.res.ColorStateList import android.os.Build import android.os.Bundle import android.preference.ListPreference import android.preference.Preference import android.preference.PreferenceActivity import android.preference.PreferenceManager import android.support.v7.widget.Toolbar import android.view.LayoutInflater import android.view.ViewGroup import android.view.WindowManager import android.widget.LinearLayout import com.md.appmanager.AppManagerApplication import com.md.appmanager.R import com.md.appmanager.utils.AppPreferences import com.md.appmanager.utils.UtilsApp import com.md.appmanager.utils.UtilsUI import net.rdrei.android.dirchooser.DirectoryChooserConfig import net.rdrei.android.dirchooser.DirectoryChooserFragment class SettingsActivity : PreferenceActivity(), SharedPreferences.OnSharedPreferenceChangeListener, DirectoryChooserFragment.OnFragmentInteractionListener { // Load Settings private var appPreferences: AppPreferences? = null private var toolbar: Toolbar? = null private var context: Context? = null private var prefDeleteAll: Preference? = null private var prefNavigationBlack: Preference? = null private var prefCustomPath: Preference? = null private var prefCustomFilename: ListPreference? = null private var prefSortMode: ListPreference? = null private var chooserDialog: DirectoryChooserFragment? = null public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.settings) this.context = this this.appPreferences = AppManagerApplication.appPreferences val prefs = PreferenceManager.getDefaultSharedPreferences(this) prefs.registerOnSharedPreferenceChangeListener(this) prefDeleteAll = findPreference("prefDeleteAll") prefCustomFilename = findPreference("prefCustomFilename") as ListPreference prefSortMode = findPreference("prefSortMode") as ListPreference prefCustomPath = findPreference("prefCustomPath") setInitialConfiguration() val versionName = UtilsApp.getAppVersionName(context as SettingsActivity) val versionCode = UtilsApp.getAppVersionCode(context as SettingsActivity) // prefCustomFilename setCustomFilenameSummary() // prefSortMode setSortModeSummary() // prefCustomPath setCustomPathSummary() // prefDeleteAll prefDeleteAll!!.onPreferenceClickListener = Preference.OnPreferenceClickListener { prefDeleteAll!!.setSummary(R.string.deleting) prefDeleteAll!!.isEnabled = false val deleteAll = UtilsApp.deleteAppFiles() if (deleteAll!!) { prefDeleteAll!!.setSummary(R.string.deleting_done) } else { prefDeleteAll!!.setSummary(R.string.deleting_error) } prefDeleteAll!!.isEnabled = true true } // prefCustomPath prefCustomPath!!.onPreferenceClickListener = Preference.OnPreferenceClickListener { val chooserConfig = DirectoryChooserConfig.builder() .newDirectoryName("App Manager APKs") .allowReadOnlyDirectory(false) .allowNewDirectoryNameModification(true) .initialDirectory(appPreferences!!.customPath) .build() chooserDialog = DirectoryChooserFragment.newInstance(chooserConfig) chooserDialog!!.show(fragmentManager, null) false } } override fun setContentView(layoutResID: Int) { val contentView = LayoutInflater.from(this).inflate(R.layout.activity_settings, LinearLayout(this), false) as ViewGroup toolbar = contentView.findViewById(R.id.toolbar) as Toolbar toolbar!!.setTitleTextColor(resources.getColor(R.color.white)) toolbar!!.setNavigationOnClickListener { onBackPressed() } toolbar!!.navigationIcon = UtilsUI.tintDrawable(toolbar!!.navigationIcon!!, ColorStateList.valueOf(resources.getColor(R.color.white))) val contentWrapper = contentView.findViewById(R.id.content_wrapper) as ViewGroup LayoutInflater.from(this).inflate(layoutResID, contentWrapper, true) window.setContentView(contentView) } private fun setInitialConfiguration() { toolbar!!.title = resources.getString(R.string.action_settings) // Android 5.0+ devices if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = UtilsUI.darker(appPreferences!!.primaryColorPref, 0.8) toolbar!!.setBackgroundColor(appPreferences!!.primaryColorPref) if (appPreferences!!.navigationBlackPref!!) { window.navigationBarColor = appPreferences!!.primaryColorPref } } // Pre-Lollipop devices if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { prefNavigationBlack!!.isEnabled = false prefNavigationBlack!!.setDefaultValue(true) } } private fun setCustomFilenameSummary() { val filenameValue = Integer.valueOf(appPreferences!!.customFilename)!! - 1 prefCustomFilename!!.summary = resources.getStringArray(R.array.filenameEntries)[filenameValue] } private fun setSortModeSummary() { val sortValue = Integer.valueOf(appPreferences!!.sortMode)!! - 1 prefSortMode!!.summary = resources.getStringArray(R.array.sortEntries)[sortValue] } private fun setCustomPathSummary() { val path = appPreferences!!.customPath if (path == UtilsApp.defaultAppFolder.getPath()) { prefCustomPath!!.summary = resources.getString(R.string.button_default) + ": " + UtilsApp.defaultAppFolder.getPath() } else { prefCustomPath!!.summary = path } } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { val pref = findPreference(key) if (pref === prefCustomFilename) { setCustomFilenameSummary() } else if (pref === prefSortMode) { setSortModeSummary() } else if (pref === prefCustomPath) { setCustomPathSummary() } } override fun onSelectDirectory(path: String) { appPreferences!!.customPath = path setCustomPathSummary() chooserDialog!!.dismiss() } override fun onCancelChooser() { chooserDialog!!.dismiss() } override fun onBackPressed() { super.onBackPressed() overridePendingTransition(R.anim.fade_forward, R.anim.slide_out_right) } }
gpl-3.0
2948919afd2e445b878630267c19ea31
38.101695
155
0.698743
5.271135
false
false
false
false
angcyo/RLibrary
uiview/src/main/java/com/angcyo/uiview/base/UINavigationView.kt
1
6058
package com.angcyo.uiview.base import android.view.LayoutInflater import android.view.View import android.widget.FrameLayout import com.angcyo.uiview.R import com.angcyo.uiview.container.ContentLayout import com.angcyo.uiview.container.UILayoutImpl import com.angcyo.uiview.container.UIParam import com.angcyo.uiview.model.TitleBarPattern import com.angcyo.uiview.widget.TouchMoveGroupLayout import com.angcyo.uiview.widget.TouchMoveView /** * Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved. * 项目名称: * 类的描述:自带类似QQ底部导航效果的主页面 * 创建人员:Robi * 创建时间:2017/06/06 10:51 * 修改人员:Robi * 修改时间:2017/06/06 10:51 * 修改备注: * Version: 1.0.0 */ abstract class UINavigationView : UIContentView() { /**默认选择的页面*/ var selectorPosition = 0 set(value) { touchMoveGroupLayout?.selectorPosition = selectorPosition } /**保存所有界面*/ var pages = arrayListOf<PageBean>() var lastIndex = selectorPosition override fun getTitleBar(): TitleBarPattern? { return null } /**导航的root layout, 用来包裹 TouchMoveView*/ val touchMoveGroupLayout: TouchMoveGroupLayout? by lazy { mViewHolder.v<TouchMoveGroupLayout>(R.id.navigation_bar_wrapper) } /**底部导航上层的阴影图层*/ val shadowView: View? by lazy { val view = mViewHolder.v<View>(R.id.shadow_view) view?.visibility = if (showShadowView) View.VISIBLE else View.GONE view } /**用来管理子页面的ILayout*/ val mainLayoutImpl: UILayoutImpl? by lazy { val impl = mViewHolder.v<UILayoutImpl>(R.id.main_layout_imp) setChildILayout(impl) impl } var showShadowView = true set(value) { field = value shadowView?.visibility = if (value) View.VISIBLE else View.GONE } override fun inflateContentLayout(baseContentLayout: ContentLayout?, inflater: LayoutInflater?) { inflate(R.layout.base_navigation_view) } override fun onViewLoad() { super.onViewLoad() mainLayoutImpl?.setEnableSwipeBack(false)//关闭侧滑 createPages(pages) onCreatePages() } fun onCreatePages() { pages?.forEach { touchMoveGroupLayout?.addView(createNavItem(it)) } touchMoveGroupLayout?.selectorPosition = selectorPosition touchMoveGroupLayout?.updateSelectorStyle() touchMoveGroupLayout?.listener = object : TouchMoveGroupLayout.OnSelectorPositionListener { override fun onRepeatSelectorPosition(targetView: TouchMoveView, position: Int) { //重复选择页面 [email protected](targetView, position) } override fun onSelectorPosition(targetView: TouchMoveView, position: Int) { //选择新页面 mainLayoutImpl?.startIView(pages?.get(position)?.iview?.setIsRightJumpLeft(lastIndex > position), UIParam(lastIndex != position).setLaunchMode(UIParam.SINGLE_TOP)) lastIndex = position [email protected](targetView, position) } } } open fun createNavItem(page: PageBean): TouchMoveView { val view = TouchMoveView(mActivity) view.textNormal = page.textNormal view.textSelected = page.textSelected if (page.textColorNormal != null) { view.mTextColorNormal = page.textColorNormal } if (page.textColorSelected != null) { view.mTextColorSelected = page.textColorSelected } if (page.icoResNormal != null) { view.mDrawableNormal = getDrawable(page.icoResNormal) } else { view.mDrawableNormal = null } if (page.icoResSelected != null) { view.mDrawableSelected = getDrawable(page.icoResSelected) } else { view.mDrawableSelected = null } if (page.icoSubResNormal != null) { view.mSubDrawableNormal = getDrawable(page.icoSubResNormal) } else { view.mSubDrawableNormal = null } if (page.icoSubResSelected != null) { view.mSubDrawableSelected = getDrawable(page.icoSubResSelected) } else { view.mSubDrawableSelected = null } page.iview.bindParentILayout(iLayout) return view } /**创建页面*/ abstract fun createPages(pages: ArrayList<PageBean>) open fun onSelectorPosition(targetView: TouchMoveView, position: Int) { } open fun onRepeatSelectorPosition(targetView: TouchMoveView, position: Int) { } /**页面*/ data class PageBean( val iview: UIBaseView, val textNormal: String? = null, val textSelected: String? = null, val textColorNormal: Int? = null, val textColorSelected: Int? = null, val icoResNormal: Int? = null, val icoResSelected: Int? = null, val icoSubResNormal: Int? = null, val icoSubResSelected: Int? = null ) { constructor(iview: UIBaseView, textNormal: String? = null, icoResNormal: Int? = null ) : this(iview, textNormal, textNormal, null, null, icoResNormal, icoResNormal, null, null) constructor(iview: UIBaseView, textNormal: String? = null, textColorNormal: Int? = null, textColorSelected: Int? = null, icoResNormal: Int? = null ) : this(iview, textNormal, textNormal, textColorNormal, textColorSelected, icoResNormal, icoResNormal, null, null) } }
apache-2.0
96a766e5eb68e8d1e464357852c3f808
32.378698
123
0.614114
4.306894
false
false
false
false
kekc42/memorizing-pager
app/src/main/java/com/lockwood/pagerdemo/BaseNavigationActivity.kt
1
1424
package com.lockwood.pagerdemo import android.os.Bundle import android.os.Parcelable import androidx.appcompat.app.AppCompatActivity import com.google.android.material.bottomnavigation.BottomNavigationView import com.lockwood.memorizingpager.NavigationHistory abstract class BaseNavigationActivity(contentLayoutId: Int) : AppCompatActivity(contentLayoutId), BottomNavigationView.OnNavigationItemSelectedListener { protected lateinit var navigation: BottomNavigationView protected lateinit var navigationHistory: NavigationHistory override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) navigationHistory = if (savedInstanceState == null) { NavigationHistory() } else { savedInstanceState.getParcelable<Parcelable>(EXTRA_NAV_HISTORY) as NavigationHistory } // initBottomNavigation navigation = findViewById(R.id.navigation) navigation.setOnNavigationItemSelectedListener(this) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelable(EXTRA_NAV_HISTORY, navigationHistory) } protected fun isItemSelected(itemId: Int): Boolean = navigation.selectedItemId == itemId companion object { const val HOME_NAVIGATION_ITEM = 0 private const val EXTRA_NAV_HISTORY = "nav_history" } }
apache-2.0
e60b696d033051c77f995a19ea52a08d
32.139535
96
0.751404
5.51938
false
false
false
false
christophpickl/gadsu
src/test/kotlin/non_test/kotlin_playground/config.kt
1
2962
package non_test.kotlin_playground import non_test.kotlin_playground.ConfigFields.baseUrl import non_test.kotlin_playground.ConfigFields.threshold import java.net.URL interface Config { fun <T> get(field: Field<T>): T } class InMemoryConfig : Config, InternalConfig { private val data = mapOf( "presto.port" to "80", "presto.host" to "localhost", "threshold" to "142" ) override fun <T> get(field: Field<T>) = field.valueOf(this) override fun get(name: String) = data[name] ?: throw IllegalArgumentException(name) } interface InternalConfig { operator fun get(name: String): String } interface Field<out T> { fun valueOf(config: InternalConfig): T val name: String } open class IntField(override val name: String) : Field<Int> { override fun valueOf(config: InternalConfig) = config[name].toInt() } open class StringField(override val name: String) : Field<String> { override fun valueOf(config: InternalConfig) = config[name] } open class UrlField(final override val name: String) : Field<URL> { private val host = StringField("$name.host") private val port = IntField("$name.port") override fun valueOf(config: InternalConfig) = URL("https://${host.valueOf(config)}:${port.valueOf(config)}") } object ConfigFields { object threshold : IntField(name = "threshold") object baseUrl : UrlField(name = "presto") } fun main(args: Array<String>) { val config = InMemoryConfig() // and we call get and get directly the proper type val thresholdConfig: Int = config.get(threshold) val url: URL = config.get(baseUrl) println(thresholdConfig) println(url) } // //interface Config { // fun <T> get(field: Field<T>): T //} //class InMemoryConfig : Config { // private val data = mapOf("port" to "80", "url" to "http://localhost") // override fun <T> get(field: Field<T>) = // data[field.name]?.toT(field) ?: // throw IllegalArgumentException(field.name) // private fun <T> String.toT(field: Field<T>) = field.valueOf(this) //} // //interface Field<out T> { // fun valueOf(rawValue: String): T // val name: String //} //open class IntField(override val name: String) : Field<Int> { // override fun valueOf(rawValue: String) = rawValue.toInt() //} //open class StringField(override val name: String) : Field<String> { // override fun valueOf(rawValue: String) = rawValue //} //open class UrlField(override val name: String) : Field<URL> { // override fun valueOf(rawValue: String) = URL() //} // //object ConfigFields { // object port : IntField(name = "port") // object url : StringField(name = "url") //} // //fun main(args: Array<String>) { // val config = InMemoryConfig() // // val jettyPort: Int = config.get(port) // val jettyUrl: String = config.get(url) // // println("$jettyUrl:$jettyPort") //} //
apache-2.0
ce3cc31b663f7891a52355d67e67850c
27.757282
75
0.647535
3.585956
false
true
false
false
YounesRahimi/java-utils
src/main/java/ir/iais/utilities/hnutils/services/db/Res.kt
2
1548
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ir.iais.utilities.hnutils.services.db import ir.iais.utilities.hnutils.services.db.interfaces.ISession import java.io.Closeable /** * Result Wrapper * * @param <T> Result type * @author yoones </T> */ @Deprecated("Will be deleted soon.") class Res<T > constructor(private val result: T, private val session: ISession<*>?) : Closeable { override fun close() { closeSession() } @Deprecated("") fun <RT> then(thenAction: (T) -> RT): RT = use { thenAction(result) } // @Deprecated("") // fun <RT> then_NotCloseSession(thenAction: (T) -> RT): RT = try { // thenAction(result) // } catch (t: Throwable) { // close().run { throw t } // } @Deprecated("") fun run(runnable: (T) -> Unit): Res<T> = try { runnable(result) } catch (e: Throwable) { close() }.let { this } @Suppress("MemberVisibilityCanPrivate") @Deprecated("") fun closeSession(): Unit? = session?.close() @Deprecated("") fun session(): ISession<*>? = session @Deprecated("") fun result(): T = closeSession().run { result } // @Deprecated("") // fun result_NotCloseSession(): T = result companion object { @Deprecated("Will be deleted soon. ") @JvmStatic fun <T > of(result: T): Res<T> { return Res(result, null) } } }
gpl-3.0
bf95e4e8db86a6ca227c1428bf67235a
24.8
97
0.598837
3.721154
false
false
false
false
mp911de/lettuce
src/main/kotlin/io/lettuce/core/api/coroutines/RedisServerCoroutinesCommandsImpl.kt
1
6074
/* * Copyright 2020-2021 the original author or authors. * * 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 io.lettuce.core.api.coroutines import io.lettuce.core.ExperimentalLettuceCoroutinesApi import io.lettuce.core.KillArgs import io.lettuce.core.TrackingArgs import io.lettuce.core.UnblockType import io.lettuce.core.api.reactive.RedisServerReactiveCommands import io.lettuce.core.protocol.CommandType import kotlinx.coroutines.flow.toList import kotlinx.coroutines.reactive.asFlow import kotlinx.coroutines.reactive.awaitFirstOrNull import java.util.* /** * Coroutine executed commands (based on reactive commands) for Server Control. * * @param <K> Key type. * @param <V> Value type. * @author Mikhael Sokolov * @since 6.0 * * @generated by io.lettuce.apigenerator.CreateKotlinCoroutinesReactiveImplementation */ @ExperimentalLettuceCoroutinesApi internal class RedisServerCoroutinesCommandsImpl<K : Any, V : Any>(private val ops: RedisServerReactiveCommands<K, V>) : RedisServerCoroutinesCommands<K, V> { override suspend fun bgrewriteaof(): String? = ops.bgrewriteaof().awaitFirstOrNull() override suspend fun bgsave(): String? = ops.bgsave().awaitFirstOrNull() override suspend fun clientCaching(enabled: Boolean): String? = ops.clientCaching(enabled).awaitFirstOrNull() override suspend fun clientGetname(): K? = ops.clientGetname().awaitFirstOrNull() override suspend fun clientGetredir(): Long? = ops.clientGetredir().awaitFirstOrNull() override suspend fun clientId(): Long? = ops.clientId().awaitFirstOrNull() override suspend fun clientKill(addr: String): String? = ops.clientKill(addr).awaitFirstOrNull() override suspend fun clientKill(killArgs: KillArgs): Long? = ops.clientKill(killArgs).awaitFirstOrNull() override suspend fun clientList(): String? = ops.clientList().awaitFirstOrNull() override suspend fun clientPause(timeout: Long): String? = ops.clientPause(timeout).awaitFirstOrNull() override suspend fun clientSetname(name: K): String? = ops.clientSetname(name).awaitFirstOrNull() override suspend fun clientTracking(args: TrackingArgs): String? = ops.clientTracking(args).awaitFirstOrNull() override suspend fun clientUnblock(id: Long, type: UnblockType): Long? = ops.clientUnblock(id, type).awaitFirstOrNull() override suspend fun command(): List<Any> = ops.command().asFlow().toList() override suspend fun commandCount(): Long? = ops.commandCount().awaitFirstOrNull() override suspend fun commandInfo(vararg commands: String): List<Any> = ops.commandInfo(*commands).asFlow().toList() override suspend fun commandInfo(vararg commands: CommandType): List<Any> = ops.commandInfo(*commands).asFlow().toList() override suspend fun configGet(parameter: String): Map<String, String>? = ops.configGet(parameter).awaitFirstOrNull() override suspend fun configResetstat(): String? = ops.configResetstat().awaitFirstOrNull() override suspend fun configRewrite(): String? = ops.configRewrite().awaitFirstOrNull() override suspend fun configSet(parameter: String, value: String): String? = ops.configSet(parameter, value).awaitFirstOrNull() override suspend fun dbsize(): Long? = ops.dbsize().awaitFirstOrNull() override suspend fun debugCrashAndRecover(delay: Long): String? = ops.debugCrashAndRecover(delay).awaitFirstOrNull() override suspend fun debugHtstats(db: Int): String? = ops.debugHtstats(db).awaitFirstOrNull() override suspend fun debugObject(key: K): String? = ops.debugObject(key).awaitFirstOrNull() override suspend fun debugOom() = ops.debugOom().awaitFirstOrNull().let { Unit } override suspend fun debugReload(): String? = ops.debugReload().awaitFirstOrNull() override suspend fun debugRestart(delay: Long): String? = ops.debugRestart(delay).awaitFirstOrNull() override suspend fun debugSdslen(key: K): String? = ops.debugSdslen(key).awaitFirstOrNull() override suspend fun debugSegfault() = ops.debugSegfault().awaitFirstOrNull().let { Unit } override suspend fun flushall(): String? = ops.flushall().awaitFirstOrNull() override suspend fun flushallAsync(): String? = ops.flushallAsync().awaitFirstOrNull() override suspend fun flushdb(): String? = ops.flushdb().awaitFirstOrNull() override suspend fun flushdbAsync(): String? = ops.flushdbAsync().awaitFirstOrNull() override suspend fun info(): String? = ops.info().awaitFirstOrNull() override suspend fun info(section: String): String? = ops.info(section).awaitFirstOrNull() override suspend fun lastsave(): Date? = ops.lastsave().awaitFirstOrNull() override suspend fun memoryUsage(key: K): Long? = ops.memoryUsage(key).awaitFirstOrNull() override suspend fun save(): String? = ops.save().awaitFirstOrNull() override suspend fun shutdown(save: Boolean) = ops.shutdown(save).awaitFirstOrNull().let { Unit } override suspend fun slaveof(host: String, port: Int): String? = ops.slaveof(host, port).awaitFirstOrNull() override suspend fun slaveofNoOne(): String? = ops.slaveofNoOne().awaitFirstOrNull() override suspend fun slowlogGet(): List<Any> = ops.slowlogGet().asFlow().toList() override suspend fun slowlogGet(count: Int): List<Any> = ops.slowlogGet(count).asFlow().toList() override suspend fun slowlogLen(): Long? = ops.slowlogLen().awaitFirstOrNull() override suspend fun slowlogReset(): String? = ops.slowlogReset().awaitFirstOrNull() override suspend fun time(): List<V> = ops.time().asFlow().toList() }
apache-2.0
036436d6b495b329d6b558e3cb942134
42.697842
158
0.749588
4.351003
false
true
false
false
chenxyu/android-banner
bannerlibrary/src/main/java/com/chenxyu/bannerlibrary/indicator/ScrollBarView.kt
1
4982
package com.chenxyu.bannerlibrary.indicator import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.util.AttributeSet import android.view.View import androidx.recyclerview.widget.RecyclerView import com.chenxyu.bannerlibrary.extend.dpToPx import java.math.BigDecimal /** * @Author: ChenXingYu * @CreateDate: 2021/3/27 22:38 * @Description: 滚动条 * @Version: 1.0 */ internal class ScrollBarView : View { companion object { private const val RADIUS = 5F } private val mPaint: Paint = Paint() private val mRectF = RectF() private var mMeasureWidth: Int = 0 private var mMeasureHeight: Int = 0 private var mBarWH: Int = 0 private var mStartX: Int = 0 private var mStartY: Int = 0 private var mDx: Float = 0F private var mDy: Float = 0F private var mMaxWH: Int = 0 /** * 方向 */ var orientation: Int = RecyclerView.HORIZONTAL /** * 滚动条颜色 */ var barColor: Int? = null set(value) { field = value invalidate() } /** * 滚动条轨道颜色 */ var trackColor: Int? = null set(value) { field = value invalidate() } init { mPaint.apply { isAntiAlias = true style = Paint.Style.FILL } } constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val widthMode = MeasureSpec.getMode(widthMeasureSpec) val widthSize = MeasureSpec.getSize(widthMeasureSpec) val heightMode = MeasureSpec.getMode(heightMeasureSpec) val heightSize = MeasureSpec.getSize(heightMeasureSpec) mMeasureWidth = 0 mMeasureHeight = 0 if (widthMode == MeasureSpec.EXACTLY) { mMeasureWidth = widthSize } else if (widthMode == MeasureSpec.AT_MOST) { mMeasureWidth = widthSize.coerceAtMost(width) } if (heightMode == MeasureSpec.EXACTLY) { mMeasureHeight = heightSize } else if (heightMode == MeasureSpec.AT_MOST) { mMeasureHeight = heightSize.coerceAtMost(height) } setMeasuredDimension(mMeasureWidth, mMeasureHeight) } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) when (orientation) { RecyclerView.HORIZONTAL -> { mBarWH = mMeasureWidth.div(2) // 轨道 mPaint.apply { color = trackColor ?: Color.WHITE } mRectF.set(0F, 0F, mMeasureWidth.toFloat(), mMeasureHeight.toFloat()) canvas?.drawRoundRect(mRectF, RADIUS.dpToPx(context), RADIUS.dpToPx(context), mPaint) // 滚动条 mPaint.apply { color = barColor ?: Color.BLUE } mRectF.set(mDx, 0F, mBarWH + mDx, mMeasureHeight.toFloat()) canvas?.drawRoundRect(mRectF, RADIUS.dpToPx(context), RADIUS.dpToPx(context), mPaint) } RecyclerView.VERTICAL -> { mBarWH = mMeasureHeight.div(2) // 轨道 mPaint.apply { color = trackColor ?: Color.WHITE } mRectF.set(0F, 0F, mMeasureWidth.toFloat(), mMeasureHeight.toFloat()) canvas?.drawRoundRect(mRectF, RADIUS.dpToPx(context), RADIUS.dpToPx(context), mPaint) // 滚动条 mPaint.apply { color = barColor ?: Color.BLUE } mRectF.set(0F, mDy, mMeasureWidth.toFloat(), mBarWH + mDy) canvas?.drawRoundRect(mRectF, RADIUS.dpToPx(context), RADIUS.dpToPx(context), mPaint) } } } fun scroll(maxWH: Int, dx: Int, dy: Int) { if (maxWH != 0) { when (orientation) { RecyclerView.HORIZONTAL -> { mMaxWH = maxWH val b1 = BigDecimal(mMeasureWidth - mBarWH) val b2 = BigDecimal(mMaxWH) val b3 = BigDecimal(mStartX + dx) mDx = b1.divide(b2, 5, BigDecimal.ROUND_HALF_UP).times(b3).toFloat() mStartX += dx } RecyclerView.VERTICAL -> { mMaxWH = maxWH val b1 = BigDecimal(mMeasureHeight - mBarWH) val b2 = BigDecimal(mMaxWH) val b3 = BigDecimal(mStartY + dy) mDy = b1.divide(b2, 5, BigDecimal.ROUND_HALF_UP).times(b3).toFloat() mStartY += dy } } invalidate() } } }
mit
83d7d163d4290c0b6e9650aa397822dc
31.215686
101
0.551136
4.364925
false
false
false
false
tmarsteel/compiler-fiddle
src/compiler/binding/expression/BoundIfExpression.kt
1
3931
/* * Copyright 2018 Tobias Marstaller * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package compiler.binding.expression import compiler.ast.expression.Expression import compiler.ast.expression.IfExpression import compiler.binding.BoundExecutable import compiler.binding.context.CTContext import compiler.binding.type.BaseTypeReference import compiler.binding.type.BuiltinBoolean import compiler.binding.type.Unit import compiler.nullableAnd import compiler.reportings.Reporting class BoundIfExpression( override val context: CTContext, override val declaration: IfExpression, val condition: BoundExpression<Expression<*>>, val thenCode: BoundExecutable<*>, val elseCode: BoundExecutable<*>? ) : BoundExpression<IfExpression>, BoundExecutable<IfExpression> { override val isGuaranteedToThrow: Boolean? get() = thenCode.isGuaranteedToThrow nullableAnd (elseCode?.isGuaranteedToThrow ?: false) override val isGuaranteedToReturn: Boolean? get() { if (elseCode == null) { return false } else { return thenCode.isGuaranteedToReturn nullableAnd elseCode.isGuaranteedToReturn } } override var type: BaseTypeReference? = null private set override fun semanticAnalysisPhase1(): Collection<Reporting> { var reportings = condition.semanticAnalysisPhase1() + thenCode.semanticAnalysisPhase1() val elseCodeReportings = elseCode?.semanticAnalysisPhase1() if (elseCodeReportings != null) { reportings = reportings + elseCodeReportings } return reportings } override fun semanticAnalysisPhase2(): Collection<Reporting> { var reportings = condition.semanticAnalysisPhase2() + thenCode.semanticAnalysisPhase2() val elseCodeReportings = elseCode?.semanticAnalysisPhase2() if (elseCodeReportings != null) { reportings = reportings + elseCodeReportings } return reportings } override fun semanticAnalysisPhase3(): Collection<Reporting> { var reportings = mutableSetOf<Reporting>() reportings.addAll(condition.semanticAnalysisPhase3()) reportings.addAll(thenCode.semanticAnalysisPhase3()) if (elseCode != null) { reportings.addAll(elseCode.semanticAnalysisPhase3()) } if (condition.type != null) { val conditionType = condition.type!! if (!conditionType.isAssignableTo(BuiltinBoolean.baseReference(context))) { reportings.add(Reporting.conditionIsNotBoolean(condition, condition.declaration.sourceLocation)) } } var thenType = if (thenCode is BoundExpression<*>) thenCode.type else Unit.baseReference(context) var elseType = if (elseCode is BoundExpression<*>) elseCode.type else Unit.baseReference(context) if (thenType != null && elseType != null) { type = BaseTypeReference.closestCommonAncestorOf(thenType, elseType) } return reportings } override fun enforceReturnType(type: BaseTypeReference) { thenCode.enforceReturnType(type) elseCode?.enforceReturnType(type) } }
lgpl-3.0
b4dc3290d6c8c0d6ab6445c3d7025261
35.747664
112
0.704655
4.68534
false
false
false
false
lehaSVV2009/dnd
api/src/main/kotlin/kadet/dnd/api/model/Profile.kt
1
749
package kadet.dnd.api.model class Profile { /** * Display name like 'Frode' or 'Alex' */ val name: String? = null /** * Hero notes */ val description: String? = null /** * Link to avatar */ val avatar: String? = null /** * Link to large descriptive image */ val image: String? = null /** * From 0 to .... * Level is calculated from experience */ val experience: Int = 0 /** * Wizard/warrior/... */ // TODO move to enums val category: String? = null /** * Elf/dwarf/... */ // TODO move to enums val race: String? = null /** * Known languages */ val languages: Set<String> = setOf() }
mit
5c9b5fa97943cffe6acb6ae74393b72b
14.625
42
0.495327
4.005348
false
false
false
false
clhols/zapr
app/src/main/java/dk/youtec/zapr/ui/view/AspectImageView.kt
1
1264
package dk.youtec.zapr.ui.view import android.content.Context import android.support.v7.widget.AppCompatImageView import android.util.AttributeSet class AspectImageView : AppCompatImageView { private var mMeasurer: ViewAspectRatioMeasurer? = null constructor(context: Context) : super(context) { } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { } fun setAspectRatio(width: Int, height: Int) { val ratio = width.toDouble() / height if (mMeasurer?.aspectRatio != ratio) { mMeasurer = ViewAspectRatioMeasurer(ratio) } } fun setAspectRatio(ratio: Double) { if (mMeasurer?.aspectRatio != ratio) { mMeasurer = ViewAspectRatioMeasurer(ratio) } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { if (mMeasurer != null) { mMeasurer!!.measure(widthMeasureSpec, heightMeasureSpec) setMeasuredDimension(mMeasurer!!.measuredWidth, mMeasurer!!.measuredHeight) } else { super.onMeasure(widthMeasureSpec, heightMeasureSpec) } } }
mit
472813bedf04fbe4ea41c9c4d57ee499
29.829268
113
0.671677
4.647059
false
false
false
false