repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
ebraminio/DroidPersianCalendar
PersianCalendar/src/main/java/com/byagowi/persiancalendar/ui/calendar/calendarpager/DayView.kt
1
7991
package com.byagowi.persiancalendar.ui.calendar.calendarpager import android.content.Context import android.graphics.* import android.util.AttributeSet import android.util.TypedValue import android.view.View import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import com.byagowi.persiancalendar.R import com.byagowi.persiancalendar.utils.appTheme import com.byagowi.persiancalendar.utils.formatNumber import com.byagowi.persiancalendar.utils.isHighTextContrastEnabled import com.byagowi.persiancalendar.utils.isNonArabicScriptSelected import kotlin.math.min class DayView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : View(context, attrs) { private val tempTypedValue = TypedValue() @ColorInt fun resolveColor(attr: Int) = tempTypedValue.let { context.theme.resolveAttribute(attr, it, true) ContextCompat.getColor(context, it.resourceId) } private val colorHoliday = resolveColor(R.attr.colorHoliday) private val colorHolidaySelected = resolveColor(R.attr.colorHolidaySelected) // private val colorTextHoliday = resolveColor(R.attr.colorTextHoliday) private val colorTextDay = resolveColor(R.attr.colorTextDay) private val colorTextDaySelected = resolveColor(R.attr.colorTextDaySelected) // private val colorTextToday = resolveColor(R.attr.colorTextToday) private val colorTextDayName = resolveColor(R.attr.colorTextDayName) private val colorEventLine = resolveColor(R.attr.colorEventLine) private val halfEventBarWidth = context.resources .getDimensionPixelSize(R.dimen.day_item_event_bar_width) / 2 private val appointmentYOffset = context.resources .getDimensionPixelSize(R.dimen.day_item_appointment_y_offset) private val eventYOffset = context.resources .getDimensionPixelSize(R.dimen.day_item_event_y_offset) private val eventBarPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { strokeWidth = context.resources .getDimensionPixelSize(R.dimen.day_item_event_bar_thickness).toFloat() } private val selectedPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL color = resolveColor(R.attr.colorSelectDay) } private val todayPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE strokeWidth = context.resources .getDimensionPixelSize(R.dimen.day_item_today_indicator_thickness).toFloat() color = resolveColor(R.attr.colorCurrentDay) } private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG) fun setTextTypeface(typeface: Typeface) { textPaint.typeface = typeface } private val bounds = Rect() private val drawingRect = RectF() private var text = "" private var today: Boolean = false private var dayIsSelected: Boolean = false private var hasEvent: Boolean = false private var hasAppointment: Boolean = false private var holiday: Boolean = false private var textSize: Int = 0 var jdn: Long = -1 private set var dayOfMonth = -1 private set private var isNumber: Boolean = false private var header = "" override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val width = width val height = height val radius = min(width, height) / 2 val isModernTheme = appTheme == R.style.ModernTheme getDrawingRect(bounds) drawingRect.set(bounds) drawingRect.inset(radius * 0.1f, radius * 0.1f) val yOffsetToApply = if (isModernTheme) (-height * .07f).toInt() else 0 if (dayIsSelected) { if (isModernTheme) { canvas.drawRoundRect(drawingRect, 0f, 0f, selectedPaint) } else { canvas.drawCircle( width / 2f, height / 2f, (radius - 5).toFloat(), selectedPaint ) } } if (today) { if (isModernTheme) { canvas.drawRoundRect(drawingRect, 0f, 0f, todayPaint) } else { canvas.drawCircle( width / 2f, height / 2f, (radius - 5).toFloat(), todayPaint ) } } val color: Int = if (isNumber) { if (holiday) if (dayIsSelected) colorHolidaySelected else colorHoliday else if (dayIsSelected) colorTextDaySelected else colorTextDay // if (today && !selected) { // color = resource.colorTextToday; // } } else { colorTextDayName } eventBarPaint.color = if (dayIsSelected && !isModernTheme) color else colorEventLine // a11y improvement if (isHighTextContrastEnabled && holiday) eventBarPaint.color = color if (hasEvent) { canvas.drawLine( width / 2f - halfEventBarWidth, (height - eventYOffset + yOffsetToApply).toFloat(), width / 2f + halfEventBarWidth, (height - eventYOffset + yOffsetToApply).toFloat(), eventBarPaint ) } if (hasAppointment) { canvas.drawLine( width / 2f - halfEventBarWidth, (height - appointmentYOffset + yOffsetToApply).toFloat(), width / 2f + halfEventBarWidth, (height - appointmentYOffset + yOffsetToApply).toFloat(), eventBarPaint ) } // TODO: Better to not change resource's paint objects, but for now textPaint.color = color textPaint.textSize = textSize.toFloat() if (isModernTheme) { textPaint.isFakeBoldText = today textPaint.textSize = textSize * .8f } val xPos = (width - textPaint.measureText(text).toInt()) / 2 val textToMeasureHeight = if (isNumber) text else if (isNonArabicScriptSelected()) "Y" else "شچ" textPaint.getTextBounds(textToMeasureHeight, 0, textToMeasureHeight.length, bounds) var yPos = (height + bounds.height()) / 2 yPos += yOffsetToApply canvas.drawText(text, xPos.toFloat(), yPos.toFloat(), textPaint) textPaint.color = if (dayIsSelected) colorTextDaySelected else colorTextDay textPaint.textSize = textSize / 2f if (header.isNotEmpty()) { val headerXPos = (width - textPaint.measureText(header).toInt()) / 2F canvas.drawText(header, headerXPos, yPos * 0.87f - bounds.height(), textPaint) } } private fun setAll( text: String, isToday: Boolean, isSelected: Boolean, hasEvent: Boolean, hasAppointment: Boolean, isHoliday: Boolean, textSize: Int, jdn: Long, dayOfMonth: Int, isNumber: Boolean, header: String ) { this.text = text this.today = isToday this.dayIsSelected = isSelected this.hasEvent = hasEvent this.hasAppointment = hasAppointment this.holiday = isHoliday this.textSize = textSize this.jdn = jdn this.dayOfMonth = dayOfMonth this.isNumber = isNumber this.header = header postInvalidate() } fun setDayOfMonthItem( isToday: Boolean, isSelected: Boolean, hasEvent: Boolean, hasAppointment: Boolean, isHoliday: Boolean, textSize: Int, jdn: Long, dayOfMonth: Int, header: String ) = setAll( formatNumber(dayOfMonth), isToday, isSelected, hasEvent, hasAppointment, isHoliday, textSize, jdn, dayOfMonth, true, header ) fun setNonDayOfMonthItem(text: String, textSize: Int) = setAll( text, isToday = false, isSelected = false, hasEvent = false, hasAppointment = false, isHoliday = false, textSize = textSize, jdn = -1, dayOfMonth = -1, isNumber = false, header = "" ) }
gpl-3.0
209273e6a1759862c04cbaaa7ae3d62a
36.862559
92
0.63625
4.523783
false
false
false
false
ebraminio/DroidPersianCalendar
PersianCalendar/src/main/java/com/byagowi/persiancalendar/entities/Entities.kt
1
1893
package com.byagowi.persiancalendar.entities import com.byagowi.persiancalendar.utils.CalendarType import io.github.persiancalendar.calendar.AbstractDate import io.github.persiancalendar.calendar.CivilDate import io.github.persiancalendar.calendar.IslamicDate import io.github.persiancalendar.calendar.PersianDate import io.github.persiancalendar.praytimes.Coordinate import java.util.* interface CalendarEvent<T : AbstractDate> { val title: String val isHoliday: Boolean val date: T } data class GregorianCalendarEvent( override val date: CivilDate, override val title: String, override val isHoliday: Boolean ) : CalendarEvent<CivilDate> { override fun toString(): String = title } data class IslamicCalendarEvent( override val date: IslamicDate, override val title: String, override val isHoliday: Boolean ) : CalendarEvent<IslamicDate> { override fun toString(): String = title } data class PersianCalendarEvent( override val date: PersianDate, override val title: String, override val isHoliday: Boolean ) : CalendarEvent<PersianDate> { override fun toString(): String = title } data class DeviceCalendarEvent( override val date: CivilDate, override val title: String, override val isHoliday: Boolean, val id: Int, val description: String, val start: Date, val end: Date, val color: String ) : CalendarEvent<CivilDate> { override fun toString(): String = "$title ($description)" } data class ShiftWorkRecord(val type: String, val length: Int) data class CityItem( val key: String, val en: String, val fa: String, val ckb: String, val ar: String, val countryCode: String, val countryEn: String, val countryFa: String, val countryCkb: String, val countryAr: String, val coordinate: Coordinate ) data class CalendarTypeItem(val type: CalendarType, private val title: String) { override fun toString(): String = title }
gpl-3.0
36a5b1b22df51f74cd512b509a99cf1f
35.423077
98
0.766508
4.292517
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/tactile_paving/AddTactilePavingBusStop.kt
1
2200
package de.westnordost.streetcomplete.quests.tactile_paving import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.meta.updateWithCheckDate import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.BLIND import de.westnordost.streetcomplete.ktx.toYesNo class AddTactilePavingBusStop : OsmFilterQuestType<Boolean>() { override val elementFilter = """ nodes, ways with ( (public_transport = platform and (bus = yes or trolleybus = yes or tram = yes)) or (highway = bus_stop and public_transport != stop_position) ) and physically_present != no and naptan:BusStopType != HAR and ( !tactile_paving or tactile_paving = unknown or tactile_paving = no and tactile_paving older today -4 years or tactile_paving = yes and tactile_paving older today -8 years ) """ override val commitMessage = "Add tactile pavings on bus stops" override val wikiLink = "Key:tactile_paving" override val icon = R.drawable.ic_quest_blind_bus override val enabledInCountries = COUNTRIES_WHERE_TACTILE_PAVING_IS_COMMON override val questTypeAchievements = listOf(BLIND) override fun getTitle(tags: Map<String, String>): Int { val hasName = tags.containsKey("name") val isTram = tags["tram"] == "yes" return when { isTram && hasName -> R.string.quest_tactilePaving_title_name_tram isTram -> R.string.quest_tactilePaving_title_tram hasName -> R.string.quest_tactilePaving_title_name_bus else -> R.string.quest_tactilePaving_title_bus } } override fun createForm() = TactilePavingForm() override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) { changes.updateWithCheckDate("tactile_paving", answer.toYesNo()) } override val defaultDisabledMessage = R.string.default_disabled_msg_boring }
gpl-3.0
e50cf0de9ff4968bd7ac863597769057
42.137255
89
0.687273
4.462475
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/advancement/criteria/AbstractOperatorCriterion.kt
1
2711
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.advancement.criteria import org.lanternpowered.api.util.collections.contentToString import org.lanternpowered.api.util.collections.immutableSetBuilderOf import org.lanternpowered.api.util.collections.toImmutableSet import org.lanternpowered.api.util.optional.asOptional import org.lanternpowered.api.util.optional.emptyOptional import org.spongepowered.api.advancement.criteria.AdvancementCriterion import org.spongepowered.api.advancement.criteria.OperatorCriterion import org.spongepowered.api.advancement.criteria.trigger.FilteredTrigger import java.util.Optional abstract class AbstractOperatorCriterion internal constructor( namePrefix: String, private val criteria: Collection<AdvancementCriterion> ) : AbstractCriterion(namePrefix + criteria.asSequence().map { it.name }.contentToString()), OperatorCriterion { private val _recursiveChildren by lazy { this.getAllChildrenCriteria(false) } private val _leafCriteria by lazy { this.getAllChildrenCriteria(true) } override fun getTrigger(): Optional<FilteredTrigger<*>> = emptyOptional() private fun getAllChildrenCriteria(onlyLeaves: Boolean): Collection<AdvancementCriterion> { val criteria = immutableSetBuilderOf<AdvancementCriterion>() if (!onlyLeaves) criteria.add(this) for (criterion in this.criteria) { if (criterion is AbstractOperatorCriterion) { criteria.addAll(criterion.getAllChildrenCriteria(onlyLeaves)) } else { criteria.add(criterion) } } return criteria.build() } val recursiveChildren: Collection<AdvancementCriterion> get() = this._recursiveChildren override fun getCriteria(): Collection<AdvancementCriterion> = this.criteria override fun getLeafCriteria(): Collection<AdvancementCriterion> = this._leafCriteria override fun find(name: String): Collection<AdvancementCriterion> = this.recursiveChildren.asSequence() .filter { criterion -> criterion.name == name } .toImmutableSet() override fun findFirst(name: String): Optional<AdvancementCriterion> = this.recursiveChildren.asSequence() .filter { criterion -> criterion.name == name } .firstOrNull() .asOptional() }
mit
4d9544f8fd70701e9cf8057eb774db14
42.725806
112
0.719292
5.001845
false
false
false
false
Geobert/radis
app/src/main/kotlin/fr/geobert/radis/tools/QuickAddTextWatcher.kt
1
946
package fr.geobert.radis.tools import android.text.Editable import android.text.TextWatcher import android.widget.AutoCompleteTextView import android.widget.EditText import android.widget.ImageButton import fr.geobert.radis.ui.QuickAddController class QuickAddTextWatcher(private val mThirdParty: AutoCompleteTextView, private val mAmount: EditText, private val mQuickAdd: ImageButton) : TextWatcher { override fun afterTextChanged(s: Editable) { val amount = mAmount QuickAddController.setQuickAddButEnabled( mQuickAdd, ((mThirdParty.length() != 0) && (amount.length() != 0) && !(amount.length() == 1 && amount.text[0] == '-'))) } override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { } }
gpl-2.0
6dc612b240cb65b17294b3015666edd7
34.037037
124
0.663848
4.504762
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/preferences/fragments/MicrosoftAccount.kt
1
4621
package org.tasks.preferences.fragments import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Bundle import androidx.fragment.app.viewModels import androidx.lifecycle.LiveData import androidx.lifecycle.lifecycleScope import com.todoroo.astrid.service.TaskDeleter import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import org.tasks.LocalBroadcastManager import org.tasks.R import org.tasks.billing.Inventory import org.tasks.data.CaldavAccount import org.tasks.data.CaldavAccount.Companion.isPaymentRequired import org.tasks.data.CaldavDao import org.tasks.preferences.IconPreference import org.tasks.sync.microsoft.MicrosoftSignInViewModel import javax.inject.Inject @AndroidEntryPoint class MicrosoftAccount : BaseAccountPreference() { @Inject lateinit var taskDeleter: TaskDeleter @Inject lateinit var inventory: Inventory @Inject lateinit var localBroadcastManager: LocalBroadcastManager @Inject lateinit var caldavDao: CaldavDao private val microsoftVM: MicrosoftSignInViewModel by viewModels() private lateinit var microsoftAccountLiveData: LiveData<CaldavAccount> val microsoftAccount: CaldavAccount get() = microsoftAccountLiveData.value ?: requireArguments().getParcelable(EXTRA_ACCOUNT)!! private val purchaseReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { lifecycleScope.launch { microsoftAccount.let { if (inventory.subscription.value != null && it.error.isPaymentRequired()) { it.error = null caldavDao.update(it) } refreshUi(it) } } } } override fun getPreferenceXml() = R.xml.preferences_google_tasks override suspend fun setupPreferences(savedInstanceState: Bundle?) { super.setupPreferences(savedInstanceState) microsoftAccountLiveData = caldavDao.watchAccount( arguments?.getParcelable<CaldavAccount>(EXTRA_ACCOUNT)?.id ?: 0 ) microsoftAccountLiveData.observe(this) { refreshUi(it) } findPreference(R.string.reinitialize_account) .setOnPreferenceClickListener { requestLogin() } } override suspend fun removeAccount() { taskDeleter.delete(microsoftAccount) } override fun onResume() { super.onResume() localBroadcastManager.registerPurchaseReceiver(purchaseReceiver) localBroadcastManager.registerRefreshListReceiver(purchaseReceiver) } override fun onPause() { super.onPause() localBroadcastManager.unregisterReceiver(purchaseReceiver) } private fun refreshUi(account: CaldavAccount?) { if (account == null) { return } (findPreference(R.string.sign_in_with_google) as IconPreference).apply { if (account.error.isNullOrBlank()) { isVisible = false return@apply } isVisible = true when { account.error.isPaymentRequired() -> { setOnPreferenceClickListener { showPurchaseDialog() } setTitle(R.string.name_your_price) setSummary(R.string.requires_pro_subscription) } account.error.isUnauthorized() -> { setTitle(R.string.sign_in) setSummary(R.string.authentication_required) setOnPreferenceClickListener { requestLogin() } } else -> { this.title = null this.summary = account.error this.onPreferenceClickListener = null } } iconVisible = true } } private fun requestLogin(): Boolean { microsoftAccount.username?.let { microsoftVM.signIn(requireActivity()) // should force a specific account } return false } companion object { private const val EXTRA_ACCOUNT = "extra_account" fun String?.isUnauthorized(): Boolean = this?.startsWith("401 Unauthorized", ignoreCase = true) == true fun newMicrosoftAccountPreference(account: CaldavAccount) = MicrosoftAccount().apply { arguments = Bundle().apply { putParcelable(EXTRA_ACCOUNT, account) } } } }
gpl-3.0
cf308f5b99bceac8247d222694898e78
34.015152
99
0.637957
5.423709
false
false
false
false
SpineEventEngine/core-java
server/src/main/kotlin/io/spine/server/event/model/RejectionEnvelope.kt
1
2957
/* * Copyright 2022, TeamDev. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.event.model import io.spine.base.CommandMessage import io.spine.base.RejectionMessage import io.spine.core.Command import io.spine.core.CommandContext import io.spine.core.Event import io.spine.core.EventContext import io.spine.core.EventId import io.spine.server.type.EventClass import io.spine.server.type.EventEnvelope import io.spine.server.type.SignalEnvelope /** * The holder of a rejection `Event` which provides convenient access to its properties. */ internal class RejectionEnvelope(delegate: EventEnvelope) : SignalEnvelope<EventId, Event, EventContext> by delegate { private val delegate: EventEnvelope /** Ensures the passed delegate contains a rejection. */ init { require(delegate.isRejection) { "`EventEnvelope` must contain a rejection." } this.delegate = delegate } override fun message(): RejectionMessage = delegate.message() as RejectionMessage /** Obtains the rejection message. */ fun rejectionMessage(): RejectionMessage = message() override fun messageClass(): EventClass { val eventClass = delegate.messageClass() @Suppress("UNCHECKED_CAST") // Ensured by the type of delegate. val value = eventClass.value() as Class<out RejectionMessage> return EventClass.from(value) } /** Obtains the command which caused the rejection. */ private fun command(): Command = context().rejection.command /** Obtains the message of the command which cased the rejection. */ fun commandMessage(): CommandMessage = command().enclosedMessage() /** Obtains the context of the rejected command. */ fun commandContext(): CommandContext = command().context() }
apache-2.0
2b445b22886b3e4a625289e63c9b234e
38.959459
88
0.741292
4.393759
false
false
false
false
nemerosa/ontrack
ontrack-ui-graphql/src/test/java/net/nemerosa/ontrack/graphql/BuildGraphQLIT.kt
1
53133
package net.nemerosa.ontrack.graphql import net.nemerosa.ontrack.common.getOrNull import net.nemerosa.ontrack.extension.api.support.TestSimpleProperty import net.nemerosa.ontrack.extension.api.support.TestSimplePropertyType import net.nemerosa.ontrack.json.* import net.nemerosa.ontrack.model.exceptions.BranchNotFoundException import net.nemerosa.ontrack.model.exceptions.ProjectNotFoundException import net.nemerosa.ontrack.model.security.BuildCreate import net.nemerosa.ontrack.model.structure.Build import net.nemerosa.ontrack.model.structure.NameDescription.Companion.nd import net.nemerosa.ontrack.model.structure.RunInfoInput import net.nemerosa.ontrack.model.structure.Signature import net.nemerosa.ontrack.test.TestUtils.uid import net.nemerosa.ontrack.test.assertJsonNull import org.junit.jupiter.api.Test import java.time.LocalDateTime import kotlin.test.* /** * Integration tests around the `builds` root query. */ class BuildGraphQLIT : AbstractQLKTITSupport() { @Test fun `Build creation`() { val branch = doCreateBranch() val build = asUser().with(branch, BuildCreate::class.java).call { structureService.newBuild( Build.of( branch, nd("1", ""), Signature.of( LocalDateTime.of(2016, 11, 25, 14, 43), "test" ) ) ) } run("""{builds (id: ${build.id}) { creation { user time } } }""") { data -> val creation = data.path("builds").first().path("creation") assertEquals("test", creation.getRequiredTextField("user")) assertEquals("2016-11-25T14:43:00", creation.getRequiredTextField("time")) } } @Test fun `Build property by name`() { val build = doCreateBuild() setProperty(build, TestSimplePropertyType::class.java, TestSimpleProperty("value 1")) run("""{ builds(id: ${build.id}) { testSimpleProperty { type { typeName name description } value editable } } }""") { data -> val p = data.path("builds").first().path("testSimpleProperty") assertEquals("net.nemerosa.ontrack.extension.api.support.TestSimplePropertyType", p.path("type").path("typeName").asText()) assertEquals("Simple value", p.path("type").path("name").asText()) assertEquals("Value.", p.path("type").path("description").asText()) assertEquals("value 1", p.path("value").path("value").asText()) assertEquals(false, p.path("editable").asBoolean()) } } @Test fun `Build property by list`() { val build = doCreateBuild() setProperty(build, TestSimplePropertyType::class.java, TestSimpleProperty("value 2")) run("""{ builds(id: ${build.id}) { properties { type { typeName name description } value editable } } }""") { data -> var p = data.path("builds").first().path("properties").find { it.path("type").path("name").asText() == "Simple value" } ?: fail("Cannot find property") assertEquals("net.nemerosa.ontrack.extension.api.support.TestSimplePropertyType", p.path("type").path("typeName").asText()) assertEquals("Simple value", p.path("type").path("name").asText()) assertEquals("Value.", p.path("type").path("description").asText()) assertEquals("value 2", p.path("value").path("value").asText()) assertEquals(false, p.path("editable").asBoolean()) p = data.path("builds").first().path("properties").find { it.path("type").path("name").asText() == "Configuration value" } ?: fail("Cannot find property") assertEquals("net.nemerosa.ontrack.extension.api.support.TestPropertyType", p.path("type").path("typeName").asText()) assertEquals("Configuration value", p.path("type").path("name").asText()) assertEquals("Value.", p.path("type").path("description").asText()) assertJsonNull(p.path("type").path("value")) assertEquals(false, p.path("editable").asBoolean()) } } @Test fun `Build property filtered by type`() { val build = doCreateBuild() setProperty(build, TestSimplePropertyType::class.java, TestSimpleProperty("value 2")) run("""{ builds(id: ${build.id}) { properties(type: "net.nemerosa.ontrack.extension.api.support.TestSimplePropertyType") { type { typeName name description } value editable } } }""") { data -> val properties = data.path("builds").first().path("properties") assertEquals(1, properties.size()) val p = properties.first() assertEquals("net.nemerosa.ontrack.extension.api.support.TestSimplePropertyType", p.path("type").path("typeName").asText()) assertEquals("Simple value", p.path("type").path("name").asText()) assertEquals("Value.", p.path("type").path("description").asText()) assertEquals("value 2", p.path("value").path("value").asText()) assertEquals(false, p.path("editable").asBoolean()) } } @Test fun `Build property filtered by value`() { val build = doCreateBuild() setProperty(build, TestSimplePropertyType::class.java, TestSimpleProperty("value 2")) run("""{ builds(id: ${build.id}) { properties(hasValue: true) { type { typeName name description } value editable } } }""") { data -> val properties = data.path("builds").first().path("properties") assertEquals(1, properties.size()) val p = properties.first() assertEquals("net.nemerosa.ontrack.extension.api.support.TestSimplePropertyType", p.path("type").path("typeName").asText()) assertEquals("Simple value", p.path("type").path("name").asText()) assertEquals("Value.", p.path("type").path("description").asText()) assertEquals("value 2", p.path("value").path("value").asText()) assertEquals(false, p.path("editable").asBoolean()) } } @Test fun `By branch not found`() { project { val name = uid("B") assertFailsWith<BranchNotFoundException> { run( """{ builds(project: "${project.name}", branch: "$name") { name } }""" ) } } } @Test fun `By branch`() { val build = doCreateBuild() run("""{ builds(project: "${build.project.name}", branch: "${build.branch.name}") { id } }""") { data -> assertEquals(build.id(), data.path("builds").first().getInt("id")) } } @Test fun `By project not found`() { val name = uid("P") assertFailsWith<ProjectNotFoundException> { run( """{ builds(project: "$name") { name } }""" ) } } @Test fun `By project`() { val build = doCreateBuild() run("""{ builds(project: "${build.project.name}") { id } }""") { data -> assertEquals(build.id(), data.path("builds").first().getInt("id")) } } @Test fun `No argument means no result`() { doCreateBuild() run("""{ builds { id } }""") { data -> assertTrue(data.path("builds").isEmpty) } } @Test fun `Branch filter`() { // Builds val branch = doCreateBranch() val build1 = doCreateBuild(branch, nd("1", "")) doCreateBuild(branch, nd("2", "")) val pl = doCreatePromotionLevel(branch, nd("PL", "")) doPromote(build1, pl, "") // Query run("""{ builds( project: "${branch.project.name}", branch: "${branch.name}", buildBranchFilter: {withPromotionLevel: "PL"}) { id } }""") { data -> val builds = data.path("builds") assertEquals(1, builds.size()) assertEquals(build1.id(), builds.first().getInt("id")) } } @Test fun `Build filter with promotion since promotion when no promotion is available`() { // Branch val branch = doCreateBranch() // A few builds without promotions (1..4).forEach { doCreateBuild(branch, nd(it.toString(), "")) } // Query run(""" { builds(project: "${branch.project.name}", branch: "${branch.name}", buildBranchFilter: {count: 100, withPromotionLevel: "BRONZE", sincePromotionLevel: "SILVER"}) { id } }""") { data -> // We should not have any build assertEquals(0, data.path("builds").size()) } } @Test fun `Branch filter requires a branch`() { // Builds val branch = doCreateBranch() val build1 = doCreateBuild(branch, nd("1", "")) doCreateBuild(branch, nd("2", "")) val pl = doCreatePromotionLevel(branch, nd("PL", "")) doPromote(build1, pl, "") // Query assertFailsWith<IllegalStateException> { run( """{ builds( buildBranchFilter: {withPromotionLevel: "PL"}) { id } }""" ) } } @Test fun `Project filter requires a project`() { // Builds doCreateBuild() // Query assertFailsWith<IllegalStateException> { run( """{ builds( buildProjectFilter: {promotionName: "PL"}) { id } }""" ) } } @Test fun `Project filter`() { // Builds val project = doCreateProject() val branch1 = doCreateBranch(project, nd("1.0", "")) doCreateBuild(branch1, nd("1.0.0", "")) val branch2 = doCreateBranch(project, nd("2.0", "")) doCreateBuild(branch2, nd("2.0.0", "")) doCreateBuild(branch2, nd("2.0.1", "")) // Query run("""{ builds( project: "${project.name}", buildProjectFilter: {branchName: "2.0"}) { name } }""") { data -> assertEquals(2, data.path("builds").size()) assertEquals("2.0.1", data.path("builds").get(0).getTextField("name")) assertEquals("2.0.0", data.path("builds").get(1).getTextField("name")) } } @Test fun `Creating a build from a branch ID`() { asAdmin { project project@{ branch branch@{ val data = run(""" mutation { createBuild(input: {branchId: ${[email protected]}, name: "1"}) { build { id name } errors { message exception } } } """) // Checks the build has been created assertNotNull( structureService.findBuildByName([email protected], [email protected], "1").getOrNull(), "Build has been created") // Checks the data val build = data["createBuild"]["build"] assertTrue(build["id"].asInt() > 0, "ID is set") assertEquals("1", build["name"].asText(), "Name is OK") assertTrue(data["createBuild"]["errors"].isNullOrNullNode(), "No error") } } } } @Test fun `Creating a build with some run info`() { asAdmin { project project@{ branch branch@{ val runInfo = RunInfoInput(runTime = 27) val data = run(""" mutation CreateBuild(${"$"}runInfo: RunInfoInput) { createBuild(input: {branchId: ${[email protected]}, name: "1", runInfo: ${"$"}runInfo}) { build { id name runInfo { runTime } } errors { message exception } } } """, mapOf( "runInfo" to runInfo.asJson().toJsonMap() )) // Checks the build has been created assertNotNull( structureService.findBuildByName([email protected], [email protected], "1").getOrNull(), "Build has been created") // Checks the data val node = assertNoUserError(data, "createBuild") val build = node["build"] assertTrue(build["id"].asInt() > 0, "ID is set") assertEquals("1", build["name"].asText(), "Name is OK") // Run info assertEquals(27, build.path("runInfo").path("runTime").asInt()) } } } } @Test fun `Creating a build from a branch ID with invalid name`() { asAdmin { project project@{ branch branch@{ val data = run(""" mutation { createBuild(input: {branchId: ${[email protected]}, name: "1 0"}) { build { id name } errors { message exception } } } """) // Checks the errors val error = data["createBuild"]["errors"][0] assertEquals("The name can only have letters, digits, dots (.), dashes (-) or underscores (_).", error["message"].asText()) assertEquals("net.nemerosa.ontrack.graphql.support.MutationInputValidationException", error["exception"].asText()) assertTrue(data["createBuild"]["build"].isNullOrNullNode(), "Build not returned") } } } } @Test fun `Creating a build from a branch ID with existing name`() { asAdmin { project project@{ branch branch@{ build(name = "1") val data = run(""" mutation { createBuild(input: {branchId: ${[email protected]}, name: "1"}) { build { id name } errors { message exception } } } """) // Checks the errors val error = data["createBuild"]["errors"][0] assertEquals("Build name already exists: 1", error["message"].asText()) assertEquals("net.nemerosa.ontrack.model.exceptions.BuildNameAlreadyDefinedException", error["exception"].asText()) assertTrue(data["createBuild"]["build"].isNullOrNullNode(), "Build not returned") } } } } @Test fun `Creating a build from a project ID and branch name`() { asAdmin { project project@{ branch branch@{ val data = run(""" mutation { createBuild(input: {projectId: ${[email protected]}, branchName: "${[email protected]}", name: "1"}) { build { id name } errors { message exception } } } """) // Checks the build has been created assertNotNull( structureService.findBuildByName([email protected], [email protected], "1").getOrNull(), "Build has been created") // Checks the data val build = data["createBuild"]["build"] assertTrue(build["id"].asInt() > 0, "ID is set") assertEquals("1", build["name"].asText(), "Name is OK") assertTrue(data["createBuild"]["errors"].isNullOrNullNode(), "No error") } } } } @Test fun `Creating a build from a project name and branch name`() { asAdmin { project project@{ branch branch@{ val data = run(""" mutation { createBuild(input: {projectName: "${[email protected]}", branchName: "${[email protected]}", name: "1"}) { build { id name } errors { message exception } } } """) // Checks the build has been created assertNotNull( structureService.findBuildByName([email protected], [email protected], "1").getOrNull(), "Build has been created") // Checks the data val build = data["createBuild"]["build"] assertTrue(build["id"].asInt() > 0, "ID is set") assertEquals("1", build["name"].asText(), "Name is OK") assertTrue(data["createBuild"]["errors"].isNullOrNullNode(), "No error") } } } } @Test fun `Creating a build from a project ID and missing branch name`() { asAdmin { project project@{ branch branch@{ build(name = "1") val data = run(""" mutation { createBuild(input: {projectId: ${[email protected]}, name: "1"}) { build { id name } errors { message exception } } } """) // Checks the errors val error = data["createBuild"]["errors"][0] assertEquals("branchName is required if branchId is not provided", error["message"].asText()) assertEquals("net.nemerosa.ontrack.graphql.schema.BuildInputMismatchException", error["exception"].asText()) assertTrue(data["createBuild"]["build"].isNullOrNullNode(), "Build not returned") } } } } @Test fun `Creating a build from a branch name and missing project information`() { asAdmin { project project@{ branch branch@{ build(name = "1") val data = run(""" mutation { createBuild(input: {branchName: "${[email protected]}", name: "1"}) { build { id name } errors { message exception } } } """) // Checks the errors val error = data["createBuild"]["errors"][0] assertEquals("When using branchName, projectName is required if projectId is not provided", error["message"].asText()) assertEquals("net.nemerosa.ontrack.graphql.schema.BuildInputMismatchException", error["exception"].asText()) assertTrue(data["createBuild"]["build"].isNullOrNullNode(), "Build not returned") } } } } @Test fun `Creating a build from a branch ID and superfluous branch name`() { asAdmin { project project@{ branch branch@{ build(name = "1") val data = run(""" mutation { createBuild(input: {branchId: ${[email protected]}, branchName: "${[email protected]}", name: "1"}) { build { id name } errors { message exception } } } """) // Checks the errors val error = data["createBuild"]["errors"][0] assertEquals("Since branchId is provided, branchName is not required.", error["message"].asText()) assertEquals("net.nemerosa.ontrack.graphql.schema.BuildInputMismatchException", error["exception"].asText()) assertTrue(data["createBuild"]["build"].isNullOrNullNode(), "Build not returned") } } } } @Test fun `Creating a build from a branch ID and superfluous project name`() { asAdmin { project project@{ branch branch@{ build(name = "1") val data = run(""" mutation { createBuild(input: {branchId: ${[email protected]}, projectName: "${[email protected]}", name: "1"}) { build { id name } errors { message exception } } } """) // Checks the errors val error = data["createBuild"]["errors"][0] assertEquals("Since branchId is provided, projectName is not required.", error["message"].asText()) assertEquals("net.nemerosa.ontrack.graphql.schema.BuildInputMismatchException", error["exception"].asText()) assertTrue(data["createBuild"]["build"].isNullOrNullNode(), "Build not returned") } } } } @Test fun `Creating a build from a branch ID and superfluous project ID`() { asAdmin { project project@{ branch branch@{ build(name = "1") val data = run(""" mutation { createBuild(input: {branchId: ${[email protected]}, projectId: ${[email protected]}, name: "1"}) { build { id name } errors { message exception } } } """) // Checks the errors val error = data["createBuild"]["errors"][0] assertEquals("Since branchId is provided, projectId is not required.", error["message"].asText()) assertEquals("net.nemerosa.ontrack.graphql.schema.BuildInputMismatchException", error["exception"].asText()) assertTrue(data["createBuild"]["build"].isNullOrNullNode(), "Build not returned") } } } } @Test fun `Creating a build from a project ID, branch name and superfluous project name`() { asAdmin { project project@{ branch branch@{ build(name = "1") val data = run(""" mutation { createBuild(input: {branchName: "${[email protected]}", projectId: ${[email protected]}, projectName: "${[email protected]}", name: "1"}) { build { id name } errors { message exception } } } """) // Checks the errors val error = data["createBuild"]["errors"][0] assertEquals("Since projectId is provided, projectName is not required.", error["message"].asText()) assertEquals("net.nemerosa.ontrack.graphql.schema.BuildInputMismatchException", error["exception"].asText()) assertTrue(data["createBuild"]["build"].isNullOrNullNode(), "Build not returned") } } } } @Test fun `Creating a build in get mode from a branch ID`() { asAdmin { project project@{ branch branch@{ val data = run(""" mutation { createBuildOrGet(input: {branchId: ${[email protected]}, name: "1"}) { build { id name } errors { message exception } } } """) // Checks the build has been created assertNotNull( structureService.findBuildByName([email protected], [email protected], "1").getOrNull(), "Build has been created") // Checks the data val build = data["createBuildOrGet"]["build"] assertTrue(build["id"].asInt() > 0, "ID is set") assertEquals("1", build["name"].asText(), "Name is OK") assertTrue(data["createBuildOrGet"]["errors"].isNullOrNullNode(), "No error") } } } } @Test fun `Creating a build in get mode from a branch name and project name`() { asAdmin { project project@{ branch branch@{ val data = run(""" mutation { createBuildOrGet(input: {projectName: "${[email protected]}", branchName: "${[email protected]}", name: "1"}) { build { id name } errors { message exception } } } """) // Checks the build has been created assertNotNull( structureService.findBuildByName([email protected], [email protected], "1").getOrNull(), "Build has been created") // Checks the data val build = data["createBuildOrGet"]["build"] assertTrue(build["id"].asInt() > 0, "ID is set") assertEquals("1", build["name"].asText(), "Name is OK") assertTrue(data["createBuildOrGet"]["errors"].isNullOrNullNode(), "No error") } } } } @Test fun `Creating a build in get mode for an existing build from a branch ID`() { asAdmin { project project@{ branch branch@{ val existing = build(name = "1") val data = run(""" mutation { createBuildOrGet(input: {branchId: ${[email protected]}, name: "1"}) { build { id name } errors { message exception } } } """) // Checks the build has been created assertNotNull( structureService.findBuildByName([email protected], [email protected], "1").getOrNull(), "Build has been created") // Checks the data val build = data["createBuildOrGet"]["build"] assertEquals(existing.id(), build["id"].asInt(), "ID is the same") assertEquals("1", build["name"].asText(), "Name is OK") assertTrue(data["createBuildOrGet"]["errors"].isNullOrNullNode(), "No error") } } } } @Test fun `Creating a build in get mode for an existing build from a branch name and project name`() { asAdmin { project project@{ branch branch@{ val existing = build(name = "1") val data = run(""" mutation { createBuildOrGet(input: {projectName: "${[email protected]}", branchName: "${[email protected]}", name: "1"}) { build { id name } errors { message exception } } } """) // Checks the build has been created assertNotNull( structureService.findBuildByName([email protected], [email protected], "1").getOrNull(), "Build has been created") // Checks the data val build = data["createBuildOrGet"]["build"] assertEquals(existing.id(), build["id"].asInt(), "ID is the same") assertEquals("1", build["name"].asText(), "Name is OK") assertTrue(data["createBuildOrGet"]["errors"].isNullOrNullNode(), "No error") } } } } @Test fun `Filtered build links`() { // Reference project with two builds to reference val ref1 = project { branch("maintenance") { build("1.0") } branch("master") { build("2.0") } } // Other reference project with one build val ref2 = project { branch("master") { build("3.0") } } // Parent build project { branch { build { // Links to all the builds above linkTo(ref1, "1.0") linkTo(ref1, "2.0") linkTo(ref2, "3.0") // No filter run("""{ builds(id: $id) { using { pageItems { name } } } }""" ).run { this["builds"][0]["using"]["pageItems"].map { it["name"].asText() }.toSet() }.run { assertEquals( setOf("1.0", "2.0", "3.0"), this ) } // Filter by project run("""{ builds(id: $id) { using(project: "${ref1.name}") { pageItems { name } } } }""" ).run { this["builds"][0]["using"]["pageItems"].map { it["name"].asText() }.toSet() }.run { assertEquals( setOf("1.0", "2.0"), this ) } // Filter by branch run("""{ builds(id: $id) { using(project: "${ref1.name}", branch: "master") { pageItems { name } } } }""" ).run { this["builds"][0]["using"]["pageItems"].map { it["name"].asText() }.toSet() }.run { assertEquals( setOf("2.0"), this ) } } } } } @Test fun `Filtered build origin links`() { // Target build val build = project<Build> { branch<Build> { build() } } // Reference project with two builds to reference from val ref1 = project { branch("maintenance") { build("1.0") { linkTo(build.project, build.name) } } branch("master") { build("2.0") { linkTo(build.project, build.name) } } } // Other reference project with one build project { branch("master") { build("3.0") { linkTo(build.project, build.name) } } } build.apply { // No filter, all of them run("""{ builds(id: $id) { usedBy { pageItems { name } } } }""" ).run { this["builds"][0]["usedBy"]["pageItems"].map { it["name"].asText() }.toSet() }.run { assertEquals( setOf("1.0", "2.0", "3.0"), this ) } // No filter, first one only run("""{ builds(id: $id) { usedBy(size: 1) { pageItems { name } } } }""" ).run { this["builds"][0]["usedBy"]["pageItems"].map { it["name"].asText() }.toSet() }.run { assertEquals( setOf("3.0"), this ) } // Project restriction, all of them run("""{ builds(id: $id) { usedBy(project: "${ref1.name}") { pageItems { name } } } }""" ).run { this["builds"][0]["usedBy"]["pageItems"].map { it["name"].asText() }.toSet() }.run { assertEquals( setOf("1.0", "2.0"), this ) } // Project restriction, first one run("""{ builds(id: $id) { usedBy(project: "${ref1.name}", size: 1) { pageItems { name } } } }""" ).run { this["builds"][0]["usedBy"]["pageItems"].map { it["name"].asText() }.toSet() }.run { assertEquals( setOf("2.0"), this ) } // Branch restriction run("""{ builds(id: $id) { usedBy(project: "${ref1.name}", branch: "master") { pageItems { name } } } }""" ).run { this["builds"][0]["usedBy"]["pageItems"].map { it["name"].asText() }.toSet() }.run { assertEquals( setOf("2.0"), this ) } } } @Test fun `Build links are empty by default`() { val build = doCreateBuild() val data = run("""{ builds(id: ${build.id}) { using { pageItems { name } } usedBy { pageItems { name } } } }""") val b = data["builds"].first() assertNotNull(b["using"]["pageItems"]) { assertTrue(it.size() == 0) } assertNotNull(b["usedBy"]["pageItems"]) { assertTrue(it.size() == 0) } } @Test fun `Build links`() { val build = doCreateBuild() val targetBuild = doCreateBuild() asAdmin().execute { structureService.addBuildLink(build, targetBuild) } val data = run("""{ builds(id: ${build.id}) { using { pageItems { name branch { name project { name } } } } } }""") val links = data["builds"].first()["using"]["pageItems"] assertNotNull(links) { assertEquals(1, it.size()) val link = it.first() assertEquals(targetBuild.name, link["name"].asText()) assertEquals(targetBuild.branch.name, link["branch"]["name"].asText()) assertEquals(targetBuild.branch.project.name, link["branch"]["project"]["name"].asText()) } } @Test fun `Following build links TO`() { // Three builds val a = doCreateBuild() val b = doCreateBuild() val c = doCreateBuild() // Links: a -> b -> c asAdmin().execute { structureService.addBuildLink(a, b) structureService.addBuildLink(b, c) } // Query build links of "b" TO val data = run("""{ builds(id: ${b.id}) { using { pageItems { id name } } } }""") // Checks the result val links = data["builds"].first()["using"]["pageItems"] assertNotNull(links) { assertEquals(1, it.size()) val link = it.first() assertEquals(c.name, link["name"].asText()) assertEquals(c.id(), link["id"].asInt()) } } @Test fun `Following build links FROM`() { // Three builds val a = doCreateBuild() val b = doCreateBuild() val c = doCreateBuild() // Links: a -> b -> c asAdmin().execute { structureService.addBuildLink(a, b) structureService.addBuildLink(b, c) } // Query build links of "b" FROM val data = withGrantViewToAll { run("""{ builds(id: ${b.id}) { usedBy { pageItems { id name } } } }""") } // Checks the result val links = data["builds"].first()["usedBy"]["pageItems"] assertNotNull(links) { assertEquals(1, it.size()) val link = it.first() assertEquals(a.name, link["name"].asText()) assertEquals(a.id(), link["id"].asInt()) } } @Test fun `Build using dependencies`() { val dep1 = project<Build> { branch<Build> { val pl = promotionLevel("IRON") build { promote(pl) } } } val dep2 = project<Build> { branch<Build> { build() } } // Source build project { branch { build { // Creates links linkTo(dep1) linkTo(dep2) // Looks for dependencies val data = asUser().withView(this).call { run(""" { builds(id: $id) { name using { pageItems { id } } } } """.trimIndent()) } // Dependencies Ids val dependencies = data["builds"][0]["using"]["pageItems"].map { it["id"].asInt() } assertEquals( setOf(dep1.id(), dep2.id()), dependencies.toSet() ) } } } } @Test fun `Promotion runs when promotion does not exist`() { // Creates a build val build = doCreateBuild() // Looks for promotion runs val data = asUser().withView(build).call { run(""" { builds(id: ${build.id}) { name promotionRuns(promotion: "PLATINUM") { creation { time } } } } """.trimIndent()) } // Checks the build val b = data["builds"][0] assertEquals(build.name, b["name"].asText()) // Checks that there is no promotion run (but the query did not fail!) assertEquals(0, b["promotionRuns"].size()) } @Test fun `Validations when validation stamp does not exist`() { // Creates a build val build = doCreateBuild() // Looks for validations val data = asUser().withView(build).call { run(""" { builds(id: ${build.id}) { name validations(validationStamp: "VS") { validationRuns(count: 1) { creation { time } } } } } """.trimIndent()) } // Checks the build val b = data["builds"][0] assertEquals(build.name, b["name"].asText()) // Checks that there is no validation run (but the query did not fail!) assertEquals(0, b["validations"].size()) } @Test fun `Validation runs filtered by validation stamp`() { project { branch { val stamps = (1..3).map { validationStamp(name = "VS$it") } build { stamps.forEach { vs -> validate(vs) } // Validation runs for this build, filtered on first validation stamp val data = asUserWithView { run("""{ builds(id: $id) { validationRuns(validationStamp: "VS1") { id } } }""") } // Checks the validation runs val runs = data["builds"][0]["validationRuns"] assertEquals(1, runs.size()) } } } } @Test fun `Validation runs filtered by validation stamp using a regular expression`() { project { branch { val stamps = (1..3).map { validationStamp(name = "VS$it") } build { stamps.forEach { vs -> validate(vs) } // Validation runs for this build, filtered on first validation stamp val data = asUserWithView { run("""{ builds(id: $id) { validationRuns(validationStamp: "VS(1|2)") { id } } }""") } // Checks the validation runs val runs = data["builds"][0]["validationRuns"] assertEquals(2, runs.size()) } } } } @Test fun `Validation runs sorted by decreasing run time`() { project { branch { val stamps = (1..3).map { validationStamp(name = "VS$it") } build { // Creating validation runs with decreasing run times val runs = stamps.mapIndexed { index, vs -> validate(vs, duration = 100 - 10 * index) } // Validation runs for this build, ordered by decreasing run time asUserWithView { run("""{ builds(id: $id) { validationRunsPaginated(sortingMode: RUN_TIME) { pageItems { id runInfo { runTime } } } } }""") { data -> val build = data.path("builds").path(0) val actualRunIds = build.path("validationRunsPaginated").path("pageItems").map { it.getRequiredIntField("id") } val runTimes = build.path("validationRunsPaginated").path("pageItems").map { it.path("runInfo").getRequiredIntField("runTime") } val expectedRunIds = runs.map { it.id() } assertEquals( expectedRunIds, actualRunIds, "Runs are sorted" ) assertEquals( listOf(100, 90, 80), runTimes, "Correctly sorted run times" ) } } } } } } @Test fun `Build by name`() { project { branch { val builds = (1..10).map { build("$it") } // Gets all builds by name, one by one builds.forEach { build -> val data = asUserWithView { run("""{ builds(project: "${build.branch.project.name}", branch: "${build.branch.name}", name: "${build.name}") { id } }""") } val id = data["builds"][0]["id"].asInt() assertEquals(build.id(), id) } // Looks for a non existing build val data = asUserWithView { run("""{ builds(project: "${project.name}", branch: "$name", name: "11") { id } }""") } val list = data["builds"] assertEquals(0, list.size()) } } } }
mit
5e8c8fd8a0e01ee3af93fe660ba79d39
36.078856
173
0.375247
6.158206
false
false
false
false
deadpixelsociety/twodee
src/main/kotlin/com/thedeadpixelsociety/twodee/scripts/ColorTween.kt
1
1324
package com.thedeadpixelsociety.twodee.scripts import com.badlogic.ashley.core.Engine import com.badlogic.ashley.core.Entity import com.badlogic.gdx.graphics.Color import com.thedeadpixelsociety.twodee.Tween import com.thedeadpixelsociety.twodee.components.Tint import com.thedeadpixelsociety.twodee.components.mapper /** * Script to change the color of an entity over duration. Requires the Tint component. */ class ColorTween() : TweenScript<Color>() { companion object { val DEFAULT_TWEEN: Tween<Color> = { start, end, t -> c0.set(start).lerp(end, t) } private val c0 = Color(Color.WHITE) } init { tween = DEFAULT_TWEEN } constructor(start: Color, target: Color, time: Float = Duration.INSTANT) : this() { this.start.set(start) this.end.set(target) this.duration = time } override var start = Color(Color.WHITE) override var end = Color(Color.WHITE) private val tintMapper by mapper<Tint>() override fun updateValue(engine: Engine, entity: Entity, value: Color) { val tint = tintMapper[entity] ?: return tint.color.set(value) } override fun reset() { super.reset() start.set(Color.WHITE) end.set(Color.WHITE) c0.set(Color.WHITE) tween = DEFAULT_TWEEN } }
mit
bc6e5e45086f1d9e56ecd8c1dde5e1b6
27.191489
89
0.66994
3.871345
false
false
false
false
nextcloud/android
app/src/main/java/com/nextcloud/client/mixins/SessionMixin.kt
1
4777
/* * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2020 Chris Narkiewicz <[email protected]> * Copyright (C) 2020 Nextcloud GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.mixins import android.accounts.Account import android.app.Activity import android.content.ContentResolver import android.content.Intent import android.os.Bundle import com.nextcloud.client.account.User import com.nextcloud.client.account.UserAccountManager import com.nextcloud.java.util.Optional import com.owncloud.android.datamodel.FileDataStorageManager import com.owncloud.android.lib.resources.status.OCCapability import com.owncloud.android.ui.activity.BaseActivity import com.owncloud.android.utils.theme.CapabilityUtils /** * Session mixin collects all account / user handling logic currently * spread over various activities. * * It is an intermediary step facilitating comprehensive rework of * account handling logic. */ class SessionMixin constructor( private val activity: Activity, private val contentResolver: ContentResolver, private val accountManager: UserAccountManager ) : ActivityMixin { private companion object { private val TAG = BaseActivity::class.java.simpleName } var currentAccount: Account? = null private set var storageManager: FileDataStorageManager? = null private set val capabilities: OCCapability? get() = getUser() .map { CapabilityUtils.getCapability(it, activity) } .orElse(null) fun setAccount(account: Account?) { val validAccount = account != null && accountManager.setCurrentOwnCloudAccount(account.name) if (validAccount) { currentAccount = account } else { swapToDefaultAccount() } currentAccount?.let { val storageManager = FileDataStorageManager(getUser().get(), contentResolver) this.storageManager = storageManager } } fun setUser(user: User) { setAccount(user.toPlatformAccount()) } fun getUser(): Optional<User> = when (val it = this.currentAccount) { null -> Optional.empty() else -> accountManager.getUser(it.name) } /** * Tries to swap the current ownCloud [Account] for other valid and existing. * * If no valid ownCloud [Account] exists, then the user is requested * to create a new ownCloud [Account]. */ private fun swapToDefaultAccount() { // default to the most recently used account val newAccount = accountManager.currentAccount if (newAccount == null) { // no account available: force account creation currentAccount = null startAccountCreation() } else { currentAccount = newAccount } } /** * Launches the account creation activity. */ fun startAccountCreation() { accountManager.startAccountCreation(activity) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) val current = accountManager.currentAccount val currentAccount = this.currentAccount if (current != null && currentAccount != null && !currentAccount.name.equals(current.name)) { this.currentAccount = current } } /** * Since ownCloud {@link Account} can be managed from the system setting menu, the existence of the {@link * Account} associated to the instance must be checked every time it is restarted. */ override fun onRestart() { super.onRestart() val validAccount = currentAccount != null && accountManager.exists(currentAccount) if (!validAccount) { swapToDefaultAccount() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val account = accountManager.currentAccount setAccount(account) } override fun onResume() { super.onResume() if (currentAccount == null) { swapToDefaultAccount() } } }
gpl-2.0
8daed801738a6fbeed4a3cb355083f55
32.405594
111
0.681809
4.854675
false
false
false
false
equeim/tremotesf-android
app/src/main/kotlin/org/equeim/tremotesf/ui/torrentpropertiesfragment/PeersFragment.kt
1
7304
/* * Copyright (C) 2017-2022 Alexey Rochev <[email protected]> * * This file is part of Tremotesf. * * Tremotesf 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. * * Tremotesf is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.equeim.tremotesf.ui.torrentpropertiesfragment import android.os.Bundle import android.view.View import androidx.fragment.app.viewModels import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import org.equeim.tremotesf.R import org.equeim.tremotesf.databinding.PeersFragmentBinding import org.equeim.tremotesf.rpc.GlobalRpc import org.equeim.tremotesf.torrentfile.rpc.Rpc import org.equeim.tremotesf.torrentfile.rpc.Torrent import org.equeim.tremotesf.ui.navController import org.equeim.tremotesf.ui.torrentpropertiesfragment.TorrentPropertiesFragmentViewModel.Companion.hasTorrent import org.equeim.tremotesf.ui.utils.launchAndCollectWhenStarted import org.equeim.tremotesf.ui.utils.viewLifecycleObject import timber.log.Timber data class Peer( val address: String, val client: String, var downloadSpeed: Long, var uploadSpeed: Long, var progress: Double ) { constructor(peer: org.equeim.libtremotesf.Peer) : this( peer.address, peer.client, peer.downloadSpeed, peer.uploadSpeed, peer.progress ) fun updatedFrom(peer: org.equeim.libtremotesf.Peer): Peer { return this.copy( downloadSpeed = peer.downloadSpeed, uploadSpeed = peer.uploadSpeed, progress = peer.progress ) } } class PeersFragment : TorrentPropertiesFragment.PagerFragment(R.layout.peers_fragment, TorrentPropertiesFragment.PagerAdapter.Tab.Peers) { private val model: Model by viewModels { viewModelFactory { initializer { Model(TorrentPropertiesFragmentViewModel.get(navController).torrent) } } } private val binding by viewLifecycleObject(PeersFragmentBinding::bind) override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) val peersAdapter = PeersAdapter() binding.peersView.apply { adapter = peersAdapter layoutManager = LinearLayoutManager(activity) addItemDecoration(DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL)) (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false } model.peers.launchAndCollectWhenStarted(viewLifecycleOwner, peersAdapter::update) combine(model.torrent.hasTorrent(), model.peers, model.loaded, ::Triple) .launchAndCollectWhenStarted(viewLifecycleOwner) { (torrent, peers, loaded) -> updatePlaceholder(torrent, peers, loaded) } } override fun onToolbarClicked() { binding.peersView.scrollToPosition(0) } override fun onNavigatedFromParent() { model.destroy() } private fun updatePlaceholder(hasTorrent: Boolean, peers: List<Peer>, loaded: Boolean) = with(binding) { if (!hasTorrent) { progressBar.visibility = View.GONE placeholder.visibility = View.GONE } else { if (loaded) { progressBar.visibility = View.GONE placeholder.visibility = if (peers.isEmpty()) { View.VISIBLE } else { View.GONE } } else { progressBar.visibility = View.VISIBLE } } } private class Model(val torrent: StateFlow<Torrent?>) : ViewModel() { private val _peers = MutableStateFlow<List<Peer>>(emptyList()) val peers: StateFlow<List<Peer>> by ::_peers private val _loaded = MutableStateFlow(false) val loaded: StateFlow<Boolean> by ::_loaded init { Timber.i("constructor called") torrent.hasTorrent().onEach { if (it) { Timber.i("Torrent appeared, setting peersEnabled to true") torrent.value?.peersEnabled = true } else { Timber.i("Torrent appeared, resetting") reset() } }.launchIn(viewModelScope) viewModelScope.launch { GlobalRpc.torrentPeersUpdatedEvents.collect(::onTorrentPeersUpdated) } } override fun onCleared() { Timber.i("onCleared() called") destroy() } fun destroy() { Timber.i("destroy() called") viewModelScope.cancel() reset() } private fun reset() { Timber.i("reset() called") torrent.value?.peersEnabled = false _peers.value = emptyList() _loaded.value = false } private fun onTorrentPeersUpdated(data: Rpc.TorrentPeersUpdatedData) { val (torrentId, removedIndexRanges, changed, added) = data if (torrentId != torrent.value?.id) return if (loaded.value && removedIndexRanges.isEmpty() && changed.isEmpty() && added.isEmpty()) { return } val peers = this.peers.value.toMutableList() for (range in removedIndexRanges) { peers.subList(range.first, range.last).clear() } if (changed.isNotEmpty()) { val changedIter = changed.iterator() var changedPeer = changedIter.next() var changedPeerAddress = changedPeer.address val peersIter = peers.listIterator() while (peersIter.hasNext()) { val peer = peersIter.next() if (peer.address == changedPeerAddress) { peersIter.set(peer.updatedFrom(changedPeer)) if (changedIter.hasNext()) { changedPeer = changedIter.next() changedPeerAddress = changedPeer.address } else { break } } } } for (peer in added) { peers.add(Peer(peer)) } _loaded.value = true _peers.value = peers } } }
gpl-3.0
3a73577c0c6489efdc7eb6263e04465e
33.785714
138
0.623768
4.989071
false
false
false
false
groupdocs-comparison/GroupDocs.Comparison-for-Java
Demos/Ktor/src/main/kotlin/com/groupdocs/ui/usecase/AreFilesSupportedUseCase.kt
1
1243
package com.groupdocs.ui.usecase import com.groupdocs.ui.status.InternalServerException import io.ktor.util.* import org.koin.core.component.KoinComponent import java.nio.file.Paths class AreFilesSupportedUseCase : KoinComponent { operator fun invoke(sourceFileName: String, targetFileName: String): Boolean { sourceFileName.ifBlank { throw AreFilesSupportedException("Source file name can't be blank") } targetFileName.ifBlank { throw AreFilesSupportedException("Target file name can't be blank") } val sourceExtension = Paths.get(sourceFileName).extension val targetExtension = Paths.get(targetFileName).extension return (sourceExtension == targetExtension && sourceExtension in SUPPORTED_EXTENSIONS) } companion object { val SUPPORTED_EXTENSIONS = listOf( "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf", "png", "txt", "html", "htm", "jpg", "jpeg" ) } } class AreFilesSupportedException(message: String, e: Throwable? = null) : InternalServerException(message, e)
mit
1e26ae88e16a675154357cde28e8451c
28.619048
109
0.611424
4.726236
false
false
false
false
AngrySoundTech/CouponCodes3
core/src/main/kotlin/tech/feldman/couponcodes/core/event/SimpleEventHandler.kt
2
2810
/** * The MIT License * Copyright (c) 2015 Nicholas Feldman (AngrySoundTech) * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package tech.feldman.couponcodes.core.event import tech.feldman.couponcodes.api.event.CouponListener import tech.feldman.couponcodes.api.event.Event import tech.feldman.couponcodes.api.event.EventHandler import java.util.* class SimpleEventHandler : EventHandler { private val handlers = ArrayList<Class<*>>() override fun post(event: Event): Event { object : Thread() { override fun run() { for (handler in getHandlers()) { val methods = handler.methods for (method in methods) { val couponListener = method.getAnnotation(CouponListener::class.java) if (couponListener != null) { val methodParams = method.parameterTypes if (methodParams.size < 1) continue if (event.javaClass.simpleName != methodParams[0].simpleName) continue try { method.invoke(handler.newInstance(), event) } catch (e: Exception) { e.printStackTrace() } } } } } }.start() return event } override fun subscribe(clazz: Class<*>) { handlers.add(clazz) } override fun unsubscribe(clazz: Class<*>) { handlers.remove(clazz) } private fun getHandlers(): List<Class<*>> { return handlers } }
mit
5ab91db763b9d225b572ea4d10c7f13b
35.493506
93
0.600712
4.947183
false
false
false
false
apixandru/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInstaller.kt
1
6304
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.updateSettings.impl import com.intellij.ide.IdeBundle import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.BuildNumber import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.util.ArrayUtil import com.intellij.util.Restarter import com.intellij.util.io.HttpRequests import java.io.File import java.io.IOException import java.net.URL import javax.swing.UIManager object UpdateInstaller { private val patchesUrl: String get() = System.getProperty("idea.patches.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls.patchesUrl @JvmStatic @Throws(IOException::class) fun downloadPatchFile(patch: PatchInfo, toBuild: BuildNumber, forceHttps: Boolean, indicator: ProgressIndicator): File { indicator.text = IdeBundle.message("update.downloading.patch.progress") val product = ApplicationInfo.getInstance().build.productCode val from = patch.fromBuild.asStringWithoutProductCode() val to = toBuild.asStringWithoutProductCode() val jdk = if (System.getProperty("idea.java.redist", "").lastIndexOf("NoJavaDistribution") >= 0) "-no-jdk" else "" val patchName = "${product}-${from}-${to}-patch${jdk}-${patch.osSuffix}.jar" val baseUrl = patchesUrl val url = URL(URL(if (baseUrl.endsWith('/')) baseUrl else baseUrl + '/'), patchName) val patchFile = File(getTempDir(), "patch.jar") HttpRequests.request(url.toString()).gzip(false).forceHttps(forceHttps).saveToFile(patchFile, indicator) return patchFile } @JvmStatic fun installPluginUpdates(downloaders: Collection<PluginDownloader>, indicator: ProgressIndicator): Boolean { indicator.text = IdeBundle.message("update.downloading.plugins.progress") UpdateChecker.saveDisabledToUpdatePlugins() val disabledToUpdate = UpdateChecker.disabledToUpdatePlugins val readyToInstall = mutableListOf<PluginDownloader>() for (downloader in downloaders) { try { if (downloader.pluginId !in disabledToUpdate && downloader.prepareToInstall(indicator) && downloader.descriptor != null) { readyToInstall += downloader } indicator.checkCanceled() } catch (e: ProcessCanceledException) { throw e } catch (e: Exception) { Logger.getInstance(UpdateChecker::class.java).info(e) } } var installed = false try { indicator.startNonCancelableSection() for (downloader in readyToInstall) { try { downloader.install() installed = true } catch (e: Exception) { Logger.getInstance(UpdateChecker::class.java).info(e) } } } finally { indicator.finishNonCancelableSection() } return installed } @JvmStatic fun cleanupPatch() { val tempDir = getTempDir() if (tempDir.exists()) FileUtil.delete(tempDir) } @JvmStatic @Throws(IOException::class) fun preparePatchCommand(patchFile: File): Array<String> { val log4j = findLib("log4j.jar") val jna = findLib("jna.jar") val jnaUtils = findLib("jna-platform.jar") val tempDir = getTempDir() if (FileUtil.isAncestor(PathManager.getHomePath(), tempDir.path, true)) { throw IOException("Temp directory inside installation: $tempDir") } if (!(tempDir.exists() || tempDir.mkdirs())) { throw IOException("Cannot create temp directory: $tempDir") } val log4jCopy = log4j.copyTo(File(tempDir, log4j.name), true) val jnaCopy = jna.copyTo(File(tempDir, jna.name), true) val jnaUtilsCopy = jnaUtils.copyTo(File(tempDir, jnaUtils.name), true) var java = System.getProperty("java.home") if (FileUtil.isAncestor(PathManager.getHomePath(), java, true)) { val javaCopy = File(tempDir, "jre") FileUtil.copyDir(File(java), javaCopy) java = javaCopy.path } val args = arrayListOf<String>() if (SystemInfo.isWindows) { val launcher = PathManager.findBinFile("launcher.exe") val elevator = PathManager.findBinFile("elevator.exe") // "launcher" depends on "elevator" if (launcher != null && elevator != null && launcher.canExecute() && elevator.canExecute()) { args += Restarter.createTempExecutable(launcher).path Restarter.createTempExecutable(elevator) } } args += File(java, if (SystemInfo.isWindows) "bin\\java.exe" else "bin/java").path args += "-Xmx750m" args += "-cp" args += arrayOf(patchFile.path, log4jCopy.path, jnaCopy.path, jnaUtilsCopy.path).joinToString(File.pathSeparator) args += "-Djna.nosys=true" args += "-Djna.boot.library.path=" args += "-Djna.debug_load=true" args += "-Djna.debug_load.jna=true" args += "-Djava.io.tmpdir=${tempDir.path}" args += "-Didea.updater.log=${PathManager.getLogPath()}" args += "-Dswing.defaultlaf=${UIManager.getSystemLookAndFeelClassName()}" args += "com.intellij.updater.Runner" args += "install" args += PathManager.getHomePath() return ArrayUtil.toStringArray(args) } private fun findLib(libName: String): File { val libFile = File(PathManager.getLibPath(), libName) return if (libFile.exists()) libFile else throw IOException("Missing: ${libFile}") } private fun getTempDir() = File(PathManager.getTempPath(), "patch-update") }
apache-2.0
82e7a6a84ea876588b87837b7160aedc
35.656977
130
0.699556
4.282609
false
false
false
false
cashapp/sqldelight
sqldelight-compiler/src/main/kotlin/app/cash/sqldelight/core/compiler/QueryGenerator.kt
1
12723
package app.cash.sqldelight.core.compiler import app.cash.sqldelight.core.compiler.integration.javadocText import app.cash.sqldelight.core.compiler.model.BindableQuery import app.cash.sqldelight.core.compiler.model.NamedMutator import app.cash.sqldelight.core.compiler.model.NamedQuery import app.cash.sqldelight.core.lang.ASYNC_RESULT_TYPE import app.cash.sqldelight.core.lang.DRIVER_NAME import app.cash.sqldelight.core.lang.MAPPER_NAME import app.cash.sqldelight.core.lang.PREPARED_STATEMENT_TYPE import app.cash.sqldelight.core.lang.encodedJavaType import app.cash.sqldelight.core.lang.preparedStatementBinder import app.cash.sqldelight.core.lang.util.childOfType import app.cash.sqldelight.core.lang.util.columnDefSource import app.cash.sqldelight.core.lang.util.findChildrenOfType import app.cash.sqldelight.core.lang.util.isArrayParameter import app.cash.sqldelight.core.lang.util.range import app.cash.sqldelight.core.lang.util.rawSqlText import app.cash.sqldelight.core.lang.util.sqFile import app.cash.sqldelight.core.psi.SqlDelightStmtClojureStmtList import app.cash.sqldelight.dialect.api.IntermediateType import app.cash.sqldelight.dialect.grammar.mixins.BindParameterMixin import com.alecstrong.sql.psi.core.psi.SqlBinaryEqualityExpr import com.alecstrong.sql.psi.core.psi.SqlBindExpr import com.alecstrong.sql.psi.core.psi.SqlStmt import com.alecstrong.sql.psi.core.psi.SqlTypes import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.PsiTreeUtil import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.NameAllocator abstract class QueryGenerator( private val query: BindableQuery, ) { protected val dialect = query.statement.sqFile().dialect protected val treatNullAsUnknownForEquality = query.statement.sqFile().treatNullAsUnknownForEquality protected val generateAsync = query.statement.sqFile().generateAsync /** * Creates the block of code that prepares [query] as a prepared statement and binds the * arguments to it. This code block does not make any use of class fields, and only populates a * single variable [STATEMENT_NAME] * * val numberIndexes = createArguments(count = number.size) * val statement = database.prepareStatement(""" * |SELECT * * |FROM player * |WHERE number IN $numberIndexes * """.trimMargin(), SqlPreparedStatement.Type.SELECT, 1 + (number.size - 1)) * number.forEachIndexed { index, number -> * check(this is SqlCursorSubclass) * statement.bindLong(index + 2, number) * } */ protected fun executeBlock(): CodeBlock { val result = CodeBlock.builder() if (query.statement is SqlDelightStmtClojureStmtList) { if (query is NamedQuery) { result .apply { if (generateAsync) beginControlFlow("return %T", ASYNC_RESULT_TYPE) } .beginControlFlow(if (generateAsync) "transactionWithResult" else "return transactionWithResult") } else { result.beginControlFlow("transaction") } val handledArrayArgs = mutableSetOf<BindableQuery.Argument>() query.statement.findChildrenOfType<SqlStmt>().forEachIndexed { index, statement -> val (block, additionalArrayArgs) = executeBlock(statement, handledArrayArgs, query.idForIndex(index)) handledArrayArgs.addAll(additionalArrayArgs) result.add(block) } result.endControlFlow() if (generateAsync && query is NamedQuery) { result.endControlFlow() } } else { result.add(executeBlock(query.statement, emptySet(), query.id).first) } return result.build() } private fun executeBlock( statement: PsiElement, handledArrayArgs: Set<BindableQuery.Argument>, id: Int, ): Pair<CodeBlock, Set<BindableQuery.Argument>> { val dialectPreparedStatementType = if (generateAsync) dialect.asyncRuntimeTypes.preparedStatementType else dialect.runtimeTypes.preparedStatementType val result = CodeBlock.builder() val positionToArgument = mutableListOf<Triple<Int, BindableQuery.Argument, SqlBindExpr?>>() val seenArgs = mutableSetOf<BindableQuery.Argument>() val duplicateTypes = mutableSetOf<IntermediateType>() query.arguments.forEach { argument -> if (argument.bindArgs.isNotEmpty()) { argument.bindArgs .filter { PsiTreeUtil.isAncestor(statement, it, true) } .forEach { bindArg -> if (!seenArgs.add(argument)) { duplicateTypes.add(argument.type) } positionToArgument.add(Triple(bindArg.node.textRange.startOffset, argument, bindArg)) } } else { positionToArgument.add(Triple(0, argument, null)) } } val bindStatements = CodeBlock.builder() val replacements = mutableListOf<Pair<IntRange, String>>() val argumentCounts = mutableListOf<String>() var needsFreshStatement = false val seenArrayArguments = mutableSetOf<BindableQuery.Argument>() val argumentNameAllocator = NameAllocator().apply { query.arguments.forEach { newName(it.type.name) } } // A list of [SqlBindExpr] in order of appearance in the query. val orderedBindArgs = positionToArgument.sortedBy { it.first } // The number of non-array bindArg's we've encountered so far. var nonArrayBindArgsCount = 0 // A list of arrays we've encountered so far. val precedingArrays = mutableListOf<String>() val extractedVariables = mutableMapOf<IntermediateType, String>() // extract the variable for duplicate types, so we don't encode twice for (type in duplicateTypes) { if (type.bindArg?.isArrayParameter() == true) continue val encodedJavaType = type.encodedJavaType() ?: continue val variableName = argumentNameAllocator.newName(type.name) extractedVariables[type] = variableName bindStatements.add("val %N = $encodedJavaType\n", variableName) } // For each argument in the sql orderedBindArgs.forEach { (_, argument, bindArg) -> val type = argument.type // Need to replace the single argument with a group of indexed arguments, calculated at // runtime from the list parameter: // val idIndexes = id.mapIndexed { index, _ -> "?${previousArray.size + index}" }.joinToString(prefix = "(", postfix = ")") val offset = (precedingArrays.map { "$it.size" } + "$nonArrayBindArgsCount") .joinToString(separator = " + ").replace(" + 0", "") if (bindArg?.isArrayParameter() == true) { needsFreshStatement = true if (!handledArrayArgs.contains(argument) && seenArrayArguments.add(argument)) { result.addStatement( """ |val ${type.name}Indexes = createArguments(count = ${type.name}.size) """.trimMargin(), ) } // Replace the single bind argument with the array of bind arguments: // WHERE id IN ${idIndexes} replacements.add(bindArg.range to "\$${type.name}Indexes") // Perform the necessary binds: // id.forEachIndex { index, parameter -> // statement.bindLong(previousArray.size + index, parameter) // } val indexCalculator = "index + $offset".replace(" + 0", "") val elementName = argumentNameAllocator.newName(type.name) bindStatements.add( """ |${type.name}.forEachIndexed { index, $elementName -> | %L} | """.trimMargin(), type.copy(name = elementName).preparedStatementBinder(indexCalculator), ) precedingArrays.add(type.name) argumentCounts.add("${type.name}.size") } else { val bindParameter = bindArg?.bindParameter as? BindParameterMixin if (bindParameter == null || bindParameter.text != "DEFAULT") { nonArrayBindArgsCount += 1 if (!treatNullAsUnknownForEquality && type.javaType.isNullable) { val parent = bindArg?.parent if (parent is SqlBinaryEqualityExpr) { needsFreshStatement = true var symbol = parent.childOfType(SqlTypes.EQ) ?: parent.childOfType(SqlTypes.EQ2) val nullableEquality: String if (symbol != null) { nullableEquality = "${symbol.leftWhitspace()}IS${symbol.rightWhitespace()}" } else { symbol = parent.childOfType(SqlTypes.NEQ) ?: parent.childOfType(SqlTypes.NEQ2)!! nullableEquality = "${symbol.leftWhitspace()}IS NOT${symbol.rightWhitespace()}" } val block = CodeBlock.of("if (${type.name} == null) \"$nullableEquality\" else \"${symbol.text}\"") replacements.add(symbol.range to "\${ $block }") } } // Binds each parameter to the statement: // statement.bindLong(0, id) bindStatements.add(type.preparedStatementBinder(offset, extractedVariables[type])) // Replace the named argument with a non named/indexed argument. // This allows us to use the same algorithm for non Sqlite dialects // :name becomes ? if (bindParameter != null) { replacements.add(bindArg.range to bindParameter.replaceWith(generateAsync, index = nonArrayBindArgsCount)) } } } } val optimisticLock = if (query is NamedMutator.Update) { val columnsUpdated = query.update.updateStmtSubsequentSetterList.mapNotNull { it.columnName } + query.update.columnNameList columnsUpdated.singleOrNull { it.columnDefSource()!!.columnType.node.getChildren(null).any { it.text == "LOCK" } } } else { null } // Adds the actual SqlPreparedStatement: // statement = database.prepareStatement("SELECT * FROM test") val isNamedQuery = query is NamedQuery && (statement == query.statement || statement == query.statement.children.filterIsInstance<SqlStmt>().last()) if (nonArrayBindArgsCount != 0) { argumentCounts.add(0, nonArrayBindArgsCount.toString()) } val arguments = mutableListOf<Any>( statement.rawSqlText(replacements), argumentCounts.ifEmpty { listOf(0) }.joinToString(" + "), ) var binder: String if (argumentCounts.isEmpty()) { binder = "" } else { val binderLambda = CodeBlock.builder() .add(" {\n") .indent() if (PREPARED_STATEMENT_TYPE != dialectPreparedStatementType) { binderLambda.add("check(this is %T)\n", dialectPreparedStatementType) } binderLambda.add(bindStatements.build()) .unindent() .add("}") arguments.add(binderLambda.build()) binder = "%L" } if (generateAsync) { val awaiter = awaiting() if (isNamedQuery) { awaiter?.let { (bind, arg) -> binder += bind arguments.add(arg) } } else { binder += "%L" arguments.add(".await()") } } val statementId = if (needsFreshStatement) "null" else "$id" if (isNamedQuery) { val execute = if (query.statement is SqlDelightStmtClojureStmtList) { "$DRIVER_NAME.executeQuery" } else { "return $DRIVER_NAME.executeQuery" } result.addStatement( "$execute($statementId, %P, $MAPPER_NAME, %L)$binder", *arguments.toTypedArray(), ) } else if (optimisticLock != null) { result.addStatement( "val result = $DRIVER_NAME.execute($statementId, %P, %L)$binder", *arguments.toTypedArray(), ) } else { result.addStatement( "$DRIVER_NAME.execute($statementId, %P, %L)$binder", *arguments.toTypedArray(), ) } if (query is NamedMutator.Update && optimisticLock != null) { result.addStatement( """ if (result%L == 0L) throw %T(%S) """.trimIndent(), if (generateAsync) "" else ".value", ClassName("app.cash.sqldelight.db", "OptimisticLockException"), "UPDATE on ${query.tablesAffected.single().name} failed because optimistic lock ${optimisticLock.name} did not match", ) } return Pair(result.build(), seenArrayArguments) } private fun PsiElement.leftWhitspace(): String { return if (prevSibling is PsiWhiteSpace) "" else " " } private fun PsiElement.rightWhitespace(): String { return if (nextSibling is PsiWhiteSpace) "" else " " } protected fun addJavadoc(builder: FunSpec.Builder) { if (query.javadoc != null) { builder.addKdoc(javadocText(query.javadoc)) } } protected open fun awaiting(): Pair<String, String>? = "%L" to ".await()" }
apache-2.0
b0a2d5cb81fdc0ae46d243aa88e9482b
38.027607
153
0.666588
4.345287
false
false
false
false
RocketChat/Rocket.Chat.Android.Lily
app/src/main/java/chat/rocket/android/server/infrastructure/RocketChatClientFactory.kt
2
1302
package chat.rocket.android.server.infrastructure import android.os.Build import chat.rocket.android.BuildConfig import chat.rocket.android.server.domain.TokenRepository import chat.rocket.common.util.PlatformLogger import chat.rocket.core.RocketChatClient import chat.rocket.core.createRocketChatClient import okhttp3.OkHttpClient import timber.log.Timber import javax.inject.Inject import javax.inject.Singleton @Singleton class RocketChatClientFactory @Inject constructor( private val okHttpClient: OkHttpClient, private val repository: TokenRepository, private val logger: PlatformLogger ) { private val cache = HashMap<String, RocketChatClient>() fun get(url: String): RocketChatClient { cache[url]?.let { Timber.d("Returning CACHED client for: $url") return it } val client = createRocketChatClient { httpClient = okHttpClient restUrl = url userAgent = "RC Mobile; Android ${Build.VERSION.RELEASE}; v${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})" tokenRepository = repository platformLogger = logger enableLogger = false } Timber.d("Returning NEW client for: $url") cache[url] = client return client } }
mit
dc4c4995ceb487856780b6076e78970e
30.780488
129
0.700461
4.633452
false
true
false
false
pennlabs/penn-mobile-android
PennMobile/src/main/java/com/pennapps/labs/pennmobile/SettingsFragment.kt
1
5378
package com.pennapps.labs.pennmobile import android.app.AlertDialog import android.app.Dialog import android.content.Context import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.webkit.CookieManager import android.widget.Button import android.widget.EditText import androidx.appcompat.view.ContextThemeWrapper import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceManager class SettingsFragment : PreferenceFragmentCompat() { private var accountSettings: Preference? = null private var logInOutButton: Preference? = null private lateinit var mActivity: MainActivity private lateinit var mContext: Context override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.preference) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val context: Context = ContextThemeWrapper(activity, R.style.ReferenceTheme) mActivity = activity as MainActivity mContext = context val localInflater = inflater.cloneInContext(context) return super.onCreateView(localInflater, container, savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val sp = PreferenceManager.getDefaultSharedPreferences(mActivity) val editor = sp.edit() accountSettings = findPreference("pref_account_edit") accountSettings?.onPreferenceClickListener = Preference.OnPreferenceClickListener { val dialog = Dialog(mContext) val lp = WindowManager.LayoutParams() lp.copyFrom(dialog.window?.attributes) lp.width = WindowManager.LayoutParams.MATCH_PARENT lp.height = WindowManager.LayoutParams.WRAP_CONTENT dialog.setContentView(R.layout.account_settings_dialog) val cancelButton = dialog.findViewById<Button>(R.id.cancel_button) val saveButton = dialog.findViewById<Button>(R.id.save_button) val firstName = dialog.findViewById<EditText>(R.id.first_name) val lastName = dialog.findViewById<EditText>(R.id.last_name) val email = dialog.findViewById<EditText>(R.id.email) firstName.setText(sp.getString(getString(R.string.first_name), null)) lastName.setText(sp.getString(getString(R.string.last_name), null)) email.setText(sp.getString(getString(R.string.email_address), null)) cancelButton.setOnClickListener { dialog.cancel() } saveButton.setOnClickListener { editor.putString(getString(R.string.first_name), firstName.text.toString()) editor.putString(getString(R.string.last_name), lastName.text.toString()) editor.putString(getString(R.string.email_address), email.text.toString()) editor.apply() dialog.cancel() } dialog.window?.attributes = lp dialog.show() true } logInOutButton = findPreference("pref_account_login_logout") val pennKey = sp.getString(getString(R.string.pennkey), null) if (pennKey != null) { logInOutButton?.title = "Log out" } else { logInOutButton?.title = "Log in" } logInOutButton?.onPreferenceClickListener = Preference.OnPreferenceClickListener { if (pennKey != null) { val dialog = AlertDialog.Builder(context).create() dialog.setTitle("Log out") dialog.setMessage("Are you sure you want to log out?") dialog.setButton("Logout") { dialog, _ -> CookieManager.getInstance().removeAllCookie() editor.remove(getString(R.string.penn_password)) editor.remove(getString(R.string.penn_user)) editor.remove(getString(R.string.first_name)) editor.remove(getString(R.string.last_name)) editor.remove(getString(R.string.email_address)) editor.remove(getString(R.string.pennkey)) editor.remove(getString(R.string.accountID)) editor.remove(getString(R.string.access_token)) editor.remove(getString(R.string.guest_mode)) editor.remove(getString(R.string.campus_express_token)) editor.remove(getString(R.string.campus_token_expires_in)) editor.apply() dialog.cancel() mActivity.startLoginFragment() } dialog.setButton2("Cancel") { dialog, _ -> dialog.cancel() } dialog.show() } else { mActivity.startLoginFragment() } true } } override fun onResume() { super.onResume() mActivity.removeTabs() mActivity.setTitle(R.string.action_settings) if (Build.VERSION.SDK_INT > 17) { mActivity.setSelectedTab(MainActivity.MORE) } } }
mit
9a823f8c50b22fbb9b0647524cb9c8ca
44.974359
116
0.647453
4.956682
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/analytics/LoginFunnel.kt
1
1408
package org.wikipedia.analytics import org.wikipedia.WikipediaApp class LoginFunnel(app: WikipediaApp) : Funnel(app, SCHEMA_NAME, REVISION) { @JvmOverloads fun logStart(source: String = "", editSessionToken: String = "") { log("action", "start", "source", source, "edit_session_token", editSessionToken) } fun logCreateAccountAttempt() { log("action", "createAccountAttempt") } fun logCreateAccountFailure() { log("action", "createAccountFailure") } fun logCreateAccountSuccess() { log("action", "createAccountSuccess") } fun logError(code: String?) { log("action", "error", "error_text", code) } fun logSuccess() { log("action", "success") } companion object { private const val SCHEMA_NAME = "MobileWikiAppLogin" private const val REVISION = 24000493 const val SOURCE_NAV = "navigation" const val SOURCE_EDIT = "edit" const val SOURCE_BLOCKED = "blocked" const val SOURCE_SYSTEM = "system" const val SOURCE_ONBOARDING = "onboarding" const val SOURCE_SETTINGS = "settings" const val SOURCE_SUBSCRIBE = "subscribe" const val SOURCE_READING_MANUAL_SYNC = "reading_lists_manual_sync" const val SOURCE_LOGOUT_BACKGROUND = "logout_background" const val SOURCE_SUGGESTED_EDITS = "suggestededits" } }
apache-2.0
8b1481b061fb1cf79ad3c39c252c621a
29.608696
88
0.640625
4.266667
false
false
false
false
UnsignedInt8/d.Wallet-Core
android/lib/src/test/java/dWallet/u8/SocketTests.kt
1
1420
package dwallet.u8 /** * Created by unsignedint8 on 8/14/17. */ import dwallet.core.infrastructure.SocketEx import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.delay import kotlinx.coroutines.experimental.runBlocking import org.junit.Test import org.junit.Assert.* import java.net.ServerSocket class SocketTests { @Test fun testConnect() { val s = SocketEx() assert(s.connect("baidu.com", 80)) assertEquals(null, s.lastException) } @Test fun testConnectAsync() = runBlocking { val s = SocketEx() assert(s.connectAsync("baidu.com", 80).await()) assertEquals(null, s.lastException) } @Test fun testWrite() = runBlocking { async(CommonPool) { val server = ServerSocket(9999) val client = server.accept() var msg = client.getInputStream().bufferedReader().readLine() assertEquals("hello\n", msg) msg = client.getInputStream().bufferedReader().readLine() assertEquals("world\n", msg) } delay(1000) val c1 = SocketEx() assert(c1.connectAsync("localhost", 9999).await()) assertEquals(6, c1.writeAsync("hello\n".toByteArray()).await()) assertEquals(6, c1.writeAsync("world\n".toByteArray()).await()) delay(1000) } }
gpl-3.0
4e777542cfaa72c1261a8a9cb5afc005
26.843137
73
0.642958
4.22619
false
true
false
false
FDeityLink/KeroEdit
src/io/fdeitylink/util/fx/FXUtil.kt
1
10065
/* * TODO: * Make the extension functions top-level functions? * Make all of the functions top-level functions? */ package io.fdeitylink.util.fx import java.util.concurrent.Callable import javafx.scene.layout.Region import javafx.scene.layout.GridPane import javafx.scene.layout.Background import javafx.scene.layout.BackgroundImage import javafx.scene.layout.BackgroundFill import javafx.scene.layout.CornerRadii import javafx.scene.layout.Priority import javafx.geometry.Insets import javafx.scene.control.Tab import com.sun.javafx.scene.control.skin.TabPaneSkin import javafx.application.Platform import javafx.scene.control.TextInputControl import javafx.scene.control.TextArea import javafx.scene.control.TextField import javafx.scene.control.Dialog import javafx.scene.control.Alert import javafx.scene.control.ButtonType import javafx.embed.swing.SwingFXUtils import javafx.scene.image.Image import java.awt.image.BufferedImage import java.awt.geom.AffineTransform import java.awt.image.AffineTransformOp import javafx.scene.paint.Color import javafx.concurrent.Service import javafx.concurrent.Task object FXUtil { /** * Returns a [Task] that calls [callable.call][Callable.call] in its [Task.call] method. */ fun <V> task(callable: Callable<V>) = //TODO: Take a () -> V for callable object : Task<V>() { @Throws(Exception::class) override fun call() = callable.call() } /** * Returns a [Service] that in its [Service.createTask] method returns a [Task] that calls * [callable.call][Callable.call] in its [Task.call] method. */ fun <V> service(callable: Callable<V>) = //TODO: Take a () -> V for callable object : Service<V>() { override fun createTask(): Task<V> { return object : Task<V>() { @Throws(Exception::class) override fun call() = callable.call() } } } /** * Returns a [String] representation of the receiving [Color] suitable for use with * [Color.web] and [Color.valueOf]. The official documentation for [Color.toString] * does not specify that it can be used for the methods mentioned above, so this * method should be used for such purposes as it will always be compatible. */ fun Color.toWeb() = String.format("0x%02X%02X%02X%02X", (this.red * 255).toInt(), (this.green * 255).toInt(), (this.blue * 255).toInt(), (this.opacity * 255).toInt()) /** * Creates and returns an [Alert] with the given properties * * @param type the [Alert.AlertType] of the [Alert]. Defaults to [Alert.AlertType.NONE] * @param title the title text of the [Alert] * @param headerText the header text of the [Alert]. Defaults to null * @param message the content text of the [Alert] * * @return the created [Alert] */ fun createAlert(type: Alert.AlertType = Alert.AlertType.NONE, title: String?, headerText: String? = null, message: String?): Alert { val alert = Alert(type) alert.title = title alert.headerText = headerText alert.contentText = message return alert } /** * Creates and returns an [Dialog] with the given properties and two [TextField]s * * @param title the title text of the [Dialog] * @param headerText the header text of the [Dialog]. Defaults to null * @param firstPrompt the prompt text for the first [TextField]. Defaults to null * @param secondPrompt the prompt text for the second [TextField]. Defaults to null * * @return the created [Dialog]. Its result is a [Pair] with both components being * [String]s. The first component is the text of the first [TextField], and the second * component is the text of the second [TextField], **provided that the user confirmed * their choice by clicking the OK button**. If they did not, such as by clicking the * Cancel button, then both [String]s in the [Pair] result will be empty. */ fun createDualTextFieldDialog(title: String?, headerText: String? = null, firstPrompt: String? = null, secondPrompt: String? = null ): Dialog<Pair<String, String>> { //TODO: Add 'message' parameter that defaults to null? val dialog = Dialog<Pair <String, String>>() dialog.title = title dialog.headerText = headerText dialog.dialogPane.buttonTypes.addAll(ButtonType.OK, ButtonType.CANCEL) val firstField = TextField() firstField.promptText = firstPrompt val secondField = TextField() secondField.promptText = secondPrompt val pane = GridPane() pane.add(firstField, 1, 0) pane.add(secondField, 1, 1) dialog.dialogPane.content = pane Platform.runLater(firstField::requestFocus) dialog.setResultConverter { return@setResultConverter if (ButtonType.OK == it) Pair(firstField.text, secondField.text) else Pair("", "") } return dialog } /** * Creates and returns an [Alert] with the given properties and a [TextArea] inside * * @param type the [Alert.AlertType] of the alert. Defaults to [Alert.AlertType.NONE] * @param title the title text of the [Alert] * @param headerText the header text of the [Alert]. Defaults to null * @param message the content text of the [Alert] * @param textAreaContent the content of the text box in the [Alert]. Defaults to null * @param editable true if the user should be able to edit the content of the [TextArea], * false otherwise. Defaults to false * * @return the created [Alert] */ fun createTextboxAlert(type: Alert.AlertType = Alert.AlertType.NONE, title: String?, headerText: String? = null, message: String?, textAreaContent: String? = null, editable: Boolean = false): Alert { val alert = createAlert(type, title, headerText, message) val textArea = TextArea(textAreaContent) textArea.isEditable = editable textArea.isWrapText = true textArea.maxWidth = Double.MAX_VALUE textArea.maxHeight = Double.MAX_VALUE GridPane.setVgrow(textArea, Priority.ALWAYS) GridPane.setHgrow(textArea, Priority.ALWAYS) val pane = GridPane() //TODO: Find another solution that doesn't use a GridPane? pane.maxWidth = Double.MAX_VALUE pane.add(textArea, 0, 0) alert.dialogPane.expandableContent = pane alert.dialogPane.isExpanded = true return alert } //TODO: Test this method on a tab that is specified as not-closeable /** * Closes the receiving [Tab] such that if it has an * [EventHandler][javafx.event.EventHandler] set for its onCloseRequest * or onClosed property, they will be triggered. * * @receiver a [Tab] */ fun Tab.close() { if (null == tabPane) { return } /* * Assumes default TabPane skin * https://stackoverflow.com/a/22783949/7355843 */ val behavior = (this.tabPane.skin as TabPaneSkin).behavior if (behavior.canCloseTab(this)) { behavior.closeTab(this) } } /** * Sets the maximum length of the [String] text in the receiving [TextInputControl] * * @receiver a [TextInputControl] whose text should have a maximum length * * @param len the maximum length of the text * * @throws IllegalArgumentException if [len] is negative */ fun TextInputControl.setMaxLen(len: Int) { //TODO: Remove previous listeners set by this method require(len >= 0) { "length $len is negative" } textProperty().addListener { _, _, newValue -> if (newValue.length > len) { text = newValue.substring(0, len) } } } //TODO: Change background image and background color to properties /** * Sets the background of the receiving [Region] to the given [Image] * * @receiver a [Region] to set the background image of * * @param image the [Image] to use as the background of the receiving [Region] */ fun Region.setBackgroundImage(image: Image) { background = Background(BackgroundImage(image, null, null, null, null)) } /** * Sets the background of the receiving [Region] to the given [Color] * * @receiver a [Region] to set the background color of * * @param color the [Color] to use as the background of the receiving [Region] */ fun Region.setBackgroundColor(color: Color) { background = Background(BackgroundFill(color, CornerRadii.EMPTY, Insets.EMPTY)) } /** * Returns the receiving [Image] if it is null, its width or height * are 0, or [scale] is `1.0`, otherwise the result of scaling the * receiving [Image] by [scale]. If the receiver is a nullable type, * then the return value is nullable, otherwise it is non-nullable. */ fun <T : Image?> T.scale(scale: Double): T { if (null == this || 1.0 == scale) { return this } val srcWidth = width.toInt() val srcHeight = height.toInt() if (0 == srcWidth || 0 == srcHeight) { return this } val dest = BufferedImage((srcWidth * scale).toInt(), (srcHeight * scale).toInt(), BufferedImage.TYPE_INT_ARGB) val src = SwingFXUtils.fromFXImage(this, null) val trans = AffineTransform() trans.scale(scale, scale) AffineTransformOp(trans, AffineTransformOp.TYPE_NEAREST_NEIGHBOR).filter(src, dest) @Suppress("UNCHECKED_CAST") return SwingFXUtils.toFXImage(dest, null) as T } }
apache-2.0
cce7c06e1302998f60e253735325ba18
34.695035
120
0.632489
4.308647
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/RsFnPointerType.kt
3
907
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi.ext import org.rust.lang.core.psi.RsFnPointerType import org.rust.lang.core.psi.RsValueParameter import org.rust.lang.core.stubs.RsFnPointerTypeStub val RsFnPointerType.valueParameters: List<RsValueParameter> get() = valueParameterList?.valueParameterList.orEmpty() val RsFnPointerType.isUnsafe: Boolean get() { val stub = greenStub as? RsFnPointerTypeStub return stub?.isUnsafe ?: (unsafe != null) } val RsFnPointerType.isExtern: Boolean get() { val stub = greenStub as? RsFnPointerTypeStub return stub?.isExtern ?: (externAbi != null) } val RsFnPointerType.abiName: String? get() { val stub = greenStub as? RsFnPointerTypeStub return stub?.abiName ?: externAbi?.litExpr?.stringValue }
mit
fa59b8d39710a82277272e0dfa393293
28.258065
69
0.711136
3.779167
false
false
false
false
chaseberry/KGeoJson
src/main/kotlin/edu/csh/chase/kgeojson/boundingbox/BoundingBox.kt
1
721
package edu.csh.chase.kgeojson.boundingbox import edu.csh.chase.kgeojson.models.Position public data class BoundingBox(val bottomLeft: Position, val topRight: Position) { public val dimensions: Int = bottomLeft.dimensions public fun contains(position: Position): Boolean { return position.x >= bottomLeft.x && position.y >= bottomLeft.y && position.x <= topRight.x && position.y <= topRight.y && ((position.z == null || bottomLeft.z == null || topRight.z == null) || (position.z >= bottomLeft.z && position.z <= topRight.z)) } }
apache-2.0
a574b296fe3bf71779a65af6db8a2c67
33.380952
81
0.533981
4.806667
false
false
false
false
android/identity-samples
Fido2/app/src/main/java/com/google/android/gms/identity/sample/fido2/ui/home/HomeViewModel.kt
1
3011
/* * Copyright 2021 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gms.identity.sample.fido2.ui.home import android.app.PendingIntent import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.android.gms.identity.sample.fido2.repository.AuthRepository import com.google.android.gms.identity.sample.fido2.repository.SignInState import com.google.android.gms.fido.fido2.api.common.PublicKeyCredential import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class HomeViewModel @Inject constructor( private val repository: AuthRepository ) : ViewModel() { private val _processing = MutableStateFlow(false) val processing = _processing.asStateFlow() val currentUsername = repository.signInState.map { state -> when (state) { is SignInState.SigningIn -> state.username is SignInState.SignedIn -> state.username else -> "(user)" } }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), "(user)") val credentials = repository.credentials.stateIn( viewModelScope, SharingStarted.WhileSubscribed(), emptyList() ) fun reauth() { viewModelScope.launch { repository.clearCredentials() } } fun signOut() { viewModelScope.launch { repository.signOut() } } suspend fun registerRequest(): PendingIntent? { _processing.value = true try { return repository.registerRequest() } finally { _processing.value = false } } fun registerResponse(credential: PublicKeyCredential) { viewModelScope.launch { _processing.value = true try { repository.registerResponse(credential) } finally { _processing.value = false } } } fun removeKey(credentialId: String) { viewModelScope.launch { _processing.value = true try { repository.removeKey(credentialId) } finally { _processing.value = false } } } }
apache-2.0
c9c921d0d303bc614ae6f57bd05cc8b8
30.041237
77
0.674859
4.756714
false
false
false
false
moove-it/android-kotlin-architecture
app/src/main/java/com/mooveit/kotlin/kotlintemplateproject/presentation/view/home/HomeActivity.kt
1
6292
package com.mooveit.kotlin.kotlintemplateproject.presentation.view.home import android.content.Context import android.content.Intent import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v4.content.ContextCompat import android.support.v4.widget.ContentLoadingProgressBar import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.view.View import butterknife.BindView import butterknife.ButterKnife import butterknife.OnClick import com.mooveit.kotlin.kotlintemplateproject.R import com.mooveit.kotlin.kotlintemplateproject.data.entity.Pet import com.mooveit.kotlin.kotlintemplateproject.presentation.common.ui.VerticalSpacingItemDecoration import com.mooveit.kotlin.kotlintemplateproject.presentation.common.view.BaseActivity import com.mooveit.kotlin.kotlintemplateproject.presentation.internal.di.component.DaggerActivityComponent import com.mooveit.kotlin.kotlintemplateproject.presentation.internal.di.module.ActivityModule import java.util.* import javax.inject.Inject class HomeActivity : BaseActivity(), HomeView, PetsListAdapter.OnPetItemClickListener, PetsListAdapter.OnItemDeletedListener, SwipeRefreshLayout.OnRefreshListener { val VERTICAL_SPACING: Int = 30 @BindView(R.id.toolbar) lateinit var mToolbar: Toolbar @BindView(R.id.swipe_refresh) lateinit var mSwipeRefreshLayout: SwipeRefreshLayout @BindView(R.id.pets_list) lateinit var mPetsListRV: RecyclerView @BindView(R.id.progressbar) lateinit var mProgressBar: ContentLoadingProgressBar @BindView(R.id.empty_pets_list) lateinit var mPetsListEmptyView: View @Inject lateinit var mPresenter: HomePresenter lateinit var mPetsListAdapter: PetsListAdapter private var mSyncPetsSnackbar: Snackbar? = null private val mAdapterDataObserver = object : RecyclerView.AdapterDataObserver() { override fun onChanged() { onPetsListChanged() } override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) { onPetsListChanged() } override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { onPetsListChanged() } } companion object IntentFactory { fun getIntent(context: Context): Intent { return Intent(context, HomeActivity::class.java) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) ButterKnife.bind(this) DaggerActivityComponent.builder() .applicationComponent(mApplicationComponent) .activityModule(ActivityModule()) .build() .inject(this) mPresenter.setView(this) setSupportActionBar(mToolbar) setupRecyclerView() setupSwipeRefresh() } override fun onResume() { super.onResume() mPresenter.fetchPets() } override fun onPause() { super.onPause() mPresenter.onPause() } override fun onDestroy() { super.onDestroy() mPresenter.onDestroy() mPetsListAdapter.unregisterAdapterDataObserver(mAdapterDataObserver) } private fun setupRecyclerView() { mPetsListAdapter = PetsListAdapter(ArrayList<Pet>(0), this, this) mPetsListRV.itemAnimator = DefaultItemAnimator() mPetsListRV.addItemDecoration(VerticalSpacingItemDecoration(VERTICAL_SPACING)) mPetsListRV.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) mPetsListRV.setHasFixedSize(true) mPetsListRV.adapter = mPetsListAdapter mPetsListAdapter.registerAdapterDataObserver(mAdapterDataObserver) } private fun setupSwipeRefresh() { mSwipeRefreshLayout.setColorSchemeColors( ContextCompat.getColor(this, R.color.colorAccent), ContextCompat.getColor(this, R.color.colorPrimary), ContextCompat.getColor(this, R.color.colorPrimaryDark) ) mSwipeRefreshLayout.setOnRefreshListener(this) } override fun showPets(pets: List<Pet>) { mPetsListAdapter.pets = pets } override fun showPet(pet: Pet) { } override fun showEditPet(pet: Pet) { } override fun showPets() { mPetsListAdapter.notifyDataSetChanged() } override fun showError(message: String) { Snackbar.make(mPetsListRV, message, Snackbar.LENGTH_SHORT).show() } override fun onPetItemClick(pet: Pet) { showPet(pet) } override fun onEditPetItemClick(pet: Pet) { showEditPet(pet) } override fun onPetItemDeleted(pet: Pet) { mPresenter.deletePet(pet) } private fun onPetsListChanged() { if (mPetsListAdapter.itemCount == 0) { showEmptyView() } else { showListView() } } @OnClick(R.id.add_pet_fab) fun onAddButtonClicked() { } override fun onRefresh() { mPresenter.fetchPets() } fun showEmptyView() { mPetsListEmptyView.visibility = View.VISIBLE mPetsListRV.visibility = View.GONE } fun showListView() { mPetsListEmptyView.visibility = View.GONE mPetsListRV.visibility = View.VISIBLE } override fun showProgress() { if (!mSwipeRefreshLayout.isRefreshing) { mPetsListEmptyView.visibility = View.GONE mPetsListRV.visibility = View.GONE mProgressBar.show() } else { mSyncPetsSnackbar = Snackbar.make(mToolbar, R.string.synching_pets_message, Snackbar.LENGTH_INDEFINITE) mSyncPetsSnackbar!!.show() } } override fun hideProgress() { if (mSwipeRefreshLayout.isRefreshing) { mSwipeRefreshLayout.isRefreshing = false } if (mSyncPetsSnackbar != null && mSyncPetsSnackbar!!.isShownOrQueued) { mSyncPetsSnackbar!!.dismiss() mSyncPetsSnackbar = null } mProgressBar.hide() } }
mit
f35e2e93e76742c7d42bd0ed659648f7
29.400966
115
0.694215
4.83628
false
false
false
false
robohorse/RoboPOJOGenerator
generator/src/main/kotlin/com/robohorse/robopojogenerator/properties/annotations/KotlinAnnotations.kt
1
866
package com.robohorse.robopojogenerator.properties.annotations internal sealed class KotlinAnnotations( val classAnnotation: String = EMPTY_ANNOTATION, val annotation: String ) { object GSON : KotlinAnnotations( annotation = "@field:SerializedName(\"%1\$s\")" ) object LOGAN_SQUARE : KotlinAnnotations( classAnnotation = "@JsonObject", annotation = "@field:JsonField(name = [\"%1\$s\"])" ) object JACKSON : KotlinAnnotations( annotation = "@field:JsonProperty(\"%1\$s\")" ) object FAST_JSON : KotlinAnnotations( annotation = "@JSONField(name=\"%1\$s\")" ) data class MOSHI( val adapterClassAnnotation: String = "@JsonClass(generateAdapter = true)" ) : KotlinAnnotations( annotation = "@Json(name=\"%1\$s\")" ) } private const val EMPTY_ANNOTATION = ""
mit
7eba533e1b2e66c9d782ae4363ee90ae
26.935484
81
0.638568
4.351759
false
false
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/debugger/utils/HaskellUtils.kt
1
2161
package org.jetbrains.haskell.debugger.utils import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiManager import org.jetbrains.haskell.fileType.HaskellFile import com.intellij.openapi.application.ApplicationManager import java.util.concurrent.locks.ReentrantLock import javax.swing.JPanel import javax.swing.JComponent import org.jetbrains.haskell.util.gridBagConstraints import java.awt.Insets import javax.swing.JLabel import org.jetbrains.haskell.util.setConstraints import java.awt.GridBagConstraints import javax.swing.Box public class HaskellUtils { companion object { fun zeroBasedToHaskellLineNumber(zeroBasedFileLineNumber: Int) = zeroBasedFileLineNumber + 1 fun haskellLineNumberToZeroBased(haskellFileLineNumber: Int) = haskellFileLineNumber - 1 public fun getModuleName(project: Project, file: VirtualFile): String { class NameReader(val project: Project, val file: VirtualFile) : Runnable { private var read: Boolean = false private var name: String? = null private val lock = ReentrantLock() private val condition = lock.newCondition() override fun run() { lock.lock() val hsFile = PsiManager.getInstance(project).findFile(file) as HaskellFile name = hsFile.getModule()!!.getModuleName()!!.getText()!! read = true condition.signalAll() lock.unlock() } public fun returnName(): String { lock.lock() while (!read) { condition.await() } lock.unlock() return name!! } } val reader = NameReader(project, file) ApplicationManager.getApplication()!!.runReadAction(reader) return reader.returnName() } public val HS_BOOLEAN_TYPENAME: String = "Bool" public val HS_BOOLEAN_TRUE: String = "True" } }
apache-2.0
a3d221ed5a05d43f53a8dbddae433ec8
36.275862
100
0.621009
5.120853
false
false
false
false
ZieIony/Carbon
samples/src/main/java/tk/zielony/carbonsamples/widget/NavigationViewActivity.kt
1
1300
package tk.zielony.carbonsamples.widget import android.os.Bundle import carbon.component.NavigationHeader import kotlinx.android.synthetic.main.activity_navigationview.* import tk.zielony.carbonsamples.SampleAnnotation import tk.zielony.carbonsamples.R import tk.zielony.carbonsamples.ThemedActivity import tk.zielony.randomdata.person.DrawableAvatarGenerator import tk.zielony.randomdata.person.Gender import tk.zielony.randomdata.person.StringEmailGenerator import tk.zielony.randomdata.person.StringNameGenerator @SampleAnnotation(layoutId = R.layout.activity_navigationview, titleId = R.string.navigationViewActivity_title) class NavigationViewActivity : ThemedActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initToolbar() val avatarGenerator = DrawableAvatarGenerator(this) val nameGenerator = StringNameGenerator(Gender.Both) val emailGenerator = StringEmailGenerator() val header = NavigationHeader(this) header.setItem(NavigationHeader.Item(avatarGenerator.next(), nameGenerator.next(), emailGenerator.next())) drawerMenu.setHeader(header) } override fun applyTheme() { super.applyTheme() theme.applyStyle(R.style.Translucent, true) } }
apache-2.0
140002ec88b8420b287749fe2189eb26
37.235294
114
0.780769
4.676259
false
false
false
false
wix/react-native-navigation
lib/android/app/src/main/java/com/reactnativenavigation/views/animations/DefaultViewAnimatorCreator.kt
1
1624
package com.reactnativenavigation.views.animations import android.animation.Animator import android.animation.ObjectAnimator import android.view.View import androidx.interpolator.view.animation.FastOutSlowInInterpolator import com.reactnativenavigation.utils.ViewUtils class DefaultViewAnimatorCreator : ViewAnimatorCreator { companion object { private const val DURATION = 300L private val fastOutSlowInInterpolator = FastOutSlowInInterpolator() } override fun getShowAnimator( view: View, hideDirection: BaseViewAnimator.HideDirection, translationStart: Float ): Animator { val direction = if (hideDirection == BaseViewAnimator.HideDirection.Up) 1 else -1 return ObjectAnimator.ofFloat( view, View.TRANSLATION_Y, direction * (-ViewUtils.getHeight(view) - translationStart), 0f ).apply { interpolator = fastOutSlowInInterpolator duration = DURATION } } override fun getHideAnimator( view: View, hideDirection: BaseViewAnimator.HideDirection, additionalDy: Float ): Animator { val direction = if (hideDirection == BaseViewAnimator.HideDirection.Up) -1 else 1 return ObjectAnimator.ofFloat( view, View.TRANSLATION_Y, view.translationY, direction * (view.measuredHeight + additionalDy) ).apply { interpolator = fastOutSlowInInterpolator duration = DURATION } } }
mit
6b214e8befcc3a5b09ada202e5e0b091
32.854167
89
0.64101
5.678322
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/adaptive/ui/fragments/AdaptiveOnboardingFragment.kt
2
2627
package org.stepic.droid.adaptive.ui.fragments import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.StringRes import kotlinx.android.synthetic.main.fragment_adaptive_onboarding.* import org.stepic.droid.R import org.stepic.droid.adaptive.model.Card import org.stepic.droid.adaptive.ui.adapters.OnboardingQuizCardsAdapter import org.stepic.droid.base.FragmentBase import org.stepic.droid.ui.util.initCenteredToolbar import org.stepik.android.model.Block import org.stepik.android.model.Lesson import org.stepik.android.model.Step import org.stepik.android.model.attempts.Attempt class AdaptiveOnboardingFragment: FragmentBase() { private val adapter = OnboardingQuizCardsAdapter { if (it == 0) onOnboardingCompleted() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initOnboardingCards() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_adaptive_onboarding, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) cardsContainer.setAdapter(adapter) initCenteredToolbar(R.string.adaptive_onboarding_title, showHomeButton = true, homeIndicatorRes = getCloseIconDrawableRes()) } private fun initOnboardingCards() { adapter.add(createMockCard(-1, R.string.adaptive_onboarding_card_title_1, R.string.adaptive_onboarding_card_question_1)) adapter.add(createMockCard(-2, R.string.adaptive_onboarding_card_title_2, R.string.adaptive_onboarding_card_question_2)) adapter.add(createMockCard(-3, R.string.adaptive_onboarding_card_title_3, R.string.adaptive_onboarding_card_question_3)) adapter.add(createMockCard(-4, R.string.adaptive_onboarding_card_title_4, R.string.adaptive_onboarding_card_question_4)) } private fun createMockCard(id: Long, @StringRes titleId: Int, @StringRes questionId: Int) : Card { val lesson = Lesson(title = getString(titleId)) val block = Block(text = getString(questionId)) val step = Step(block = block) return Card(id, 0, lesson, step, Attempt()) } private fun onOnboardingCompleted() { activity?.onBackPressed() } override fun onDestroyView() { adapter.detach() super.onDestroyView() } override fun onDestroy() { adapter.destroy() super.onDestroy() } }
apache-2.0
dfe890079a24125e084ec902d3831906
38.223881
132
0.737343
4.196486
false
false
false
false
hitoshura25/Media-Player-Omega-Android
player_framework/src/main/java/com/vmenon/mpo/player/framework/exo/MPOExoPlayer.kt
1
6081
package com.vmenon.mpo.player.framework.exo import android.content.Context import android.media.MediaMetadataRetriever import android.net.Uri import android.util.Log import android.view.SurfaceHolder import com.google.android.exoplayer2.* import com.google.android.exoplayer2.C.CONTENT_TYPE_SPEECH import com.google.android.exoplayer2.C.USAGE_MEDIA import com.google.android.exoplayer2.audio.AudioAttributes import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory import com.google.android.exoplayer2.source.ProgressiveMediaSource import com.google.android.exoplayer2.source.TrackGroupArray import com.google.android.exoplayer2.trackselection.TrackSelectionArray import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory import com.google.android.exoplayer2.util.Util import com.vmenon.mpo.extensions.useFileDescriptor import com.vmenon.mpo.player.framework.BaseMPOPlayer import java.io.File import javax.inject.Inject /** * Uses ExoPlayer under the hood */ class MPOExoPlayer @Inject constructor(context: Context) : BaseMPOPlayer() { private var exoPlayer: SimpleExoPlayer? = null private val appContext: Context = context.applicationContext private var seekRequested = false private var prepareRequested = false private var surfaceHolder: SurfaceHolder? = null private val eventListener = ExoPlayerEventListener() private val mediaMetadataRetriever = MediaMetadataRetriever() override val isPlaying: Boolean get() = exoPlayer?.playWhenReady ?: false override fun play() { exoPlayer?.playWhenReady = true } override fun pause() { exoPlayer?.let { player -> if (player.playWhenReady) { player.playWhenReady = false currentPos = player.currentPosition } } } override fun stop() { exoPlayer?.let { player -> if (player.playWhenReady) { player.stop() currentPos = player.currentPosition } } } override fun getCurrentPosition(): Long { return exoPlayer?.currentPosition ?: currentPos } override fun seekTo(position: Long) { if (exoPlayer == null) { currentPos = position } else { seekRequested = true exoPlayer?.seekTo(position) } } override fun setVolume(volume: Float) { exoPlayer?.volume = volume } override fun setDisplay(surfaceHolder: SurfaceHolder?) { this.surfaceHolder = surfaceHolder exoPlayer?.setVideoSurfaceHolder(surfaceHolder) } override fun doPrepareForPlayback(file: File) { createMediaPlayerIfNeeded() val bandwidthMeter = DefaultBandwidthMeter.Builder(appContext).build() val dataSourceFactory = DefaultDataSourceFactory( appContext, Util.getUserAgent(appContext, "MPO"), bandwidthMeter ) val extractorsFactory = DefaultExtractorsFactory() val videoSource = ProgressiveMediaSource.Factory(dataSourceFactory, extractorsFactory) .createMediaSource(MediaItem.Builder().setUri(Uri.fromFile(file)).build()) exoPlayer?.playWhenReady = false file.useFileDescriptor { fileDescriptor -> mediaMetadataRetriever.setDataSource(fileDescriptor) } prepareRequested = true exoPlayer?.setMediaSource(videoSource) exoPlayer?.prepare() } override fun doCleanUp() { exoPlayer?.release() exoPlayer?.removeListener(eventListener) exoPlayer = null } private fun createMediaPlayerIfNeeded() { Log.d("MPO", "createMediaPlayerIfNeeded. needed? " + (exoPlayer == null)) if (exoPlayer == null) { val audioAttributes = AudioAttributes.Builder() .setContentType(CONTENT_TYPE_SPEECH) .setUsage(USAGE_MEDIA) .build() exoPlayer = SimpleExoPlayer.Builder(appContext) .setAudioAttributes(audioAttributes, false) .build() exoPlayer?.addListener(ExoPlayerEventListener()) /** TODO * // Make sure the media player will acquire a wake-lock while * // playing. If we don't do that, the CPU might go to sleep while the * // song is playing, causing playback to stop. * mMediaPlayer.setWakeMode(mService.getApplicationContext(), * PowerManager.PARTIAL_WAKE_LOCK); */ if (surfaceHolder != null) { exoPlayer?.setVideoSurfaceHolder(surfaceHolder) } } } private inner class ExoPlayerEventListener : Player.Listener { override fun onTracksChanged( trackGroups: TrackGroupArray, trackSelections: TrackSelectionArray ) { } override fun onLoadingChanged(isLoading: Boolean) { } override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) { when (playbackState) { Player.STATE_READY -> { if (seekRequested) { seekRequested = false mListener?.onMediaSeekFinished() } if (prepareRequested) { prepareRequested = false Log.d("MPO", "Prepared, currentPosition: " + exoPlayer?.currentPosition) mListener?.onMediaPrepared() } } Player.STATE_ENDED -> mListener?.onMediaFinished() else -> { } } } override fun onRepeatModeChanged(repeatMode: Int) { } override fun onPlayerError(error: PlaybackException) { Log.w("MPO", "ExoPlayer error", error) } override fun onPlaybackParametersChanged(playbackParameters: PlaybackParameters) { } } }
apache-2.0
5ea0baec6674f26bb62750129be670e1
32.229508
96
0.636737
5.405333
false
false
false
false
hurricup/intellij-community
platform/built-in-server/src/org/jetbrains/io/fastCgi/FastCgiService.kt
1
6595
/* * Copyright 2000-2014 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.io.fastCgi import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.util.Consumer import com.intellij.util.containers.ContainerUtil import io.netty.bootstrap.Bootstrap import io.netty.buffer.ByteBuf import io.netty.channel.Channel import io.netty.handler.codec.http.* import org.jetbrains.builtInWebServer.SingleConnectionNetService import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.doneRun import org.jetbrains.io.* import java.util.concurrent.atomic.AtomicInteger val LOG = Logger.getInstance(FastCgiService::class.java) // todo send FCGI_ABORT_REQUEST if client channel disconnected abstract class FastCgiService(project: Project) : SingleConnectionNetService(project) { private val requestIdCounter = AtomicInteger() private val requests = ContainerUtil.createConcurrentIntObjectMap<ClientInfo>() override fun configureBootstrap(bootstrap: Bootstrap, errorOutputConsumer: Consumer<String>) { bootstrap.handler { it.pipeline().addLast("fastCgiDecoder", FastCgiDecoder(errorOutputConsumer, this@FastCgiService)) it.pipeline().addLast("exceptionHandler", ChannelExceptionHandler.getInstance()) it.closeFuture().addChannelListener { requestIdCounter.set(0) if (!requests.isEmpty) { val waitingClients = requests.elements().toList() requests.clear() for (client in waitingClients) { sendBadGateway(client.channel, client.extraHeaders) } } } } } fun send(fastCgiRequest: FastCgiRequest, content: ByteBuf) { val notEmptyContent: ByteBuf? if (content.isReadable) { content.retain() notEmptyContent = content notEmptyContent.touch() } else { notEmptyContent = null } try { val promise: Promise<*> if (processHandler.has()) { val channel = processChannel.get() if (channel == null || !channel.isOpen) { // channel disconnected for some reason promise = connectAgain() } else { fastCgiRequest.writeToServerChannel(notEmptyContent, channel) return } } else { promise = processHandler.get() } promise .doneRun { fastCgiRequest.writeToServerChannel(notEmptyContent, processChannel.get()!!) } .rejected { Promise.logError(LOG, it) handleError(fastCgiRequest, notEmptyContent) } } catch (e: Throwable) { LOG.error(e) handleError(fastCgiRequest, notEmptyContent) } } private fun handleError(fastCgiRequest: FastCgiRequest, content: ByteBuf?) { try { if (content != null && content.refCnt() != 0) { content.release() } } finally { requests.remove(fastCgiRequest.requestId)?.let { sendBadGateway(it.channel, it.extraHeaders) } } } fun allocateRequestId(channel: Channel, extraHeaders: HttpHeaders): Int { var requestId = requestIdCounter.getAndIncrement() if (requestId >= java.lang.Short.MAX_VALUE) { requestIdCounter.set(0) requestId = requestIdCounter.getAndDecrement() } requests.put(requestId, ClientInfo(channel, extraHeaders)) return requestId } fun responseReceived(id: Int, buffer: ByteBuf?) { val client = requests.remove(id) if (client == null || !client.channel.isActive) { buffer?.release() return } val channel = client.channel if (buffer == null) { HttpResponseStatus.BAD_GATEWAY.send(channel) return } val httpResponse = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer) try { parseHeaders(httpResponse, buffer) httpResponse.addServer() if (!HttpUtil.isContentLengthSet(httpResponse)) { HttpUtil.setContentLength(httpResponse, buffer.readableBytes().toLong()) } httpResponse.headers().add(client.extraHeaders) } catch (e: Throwable) { buffer.release() try { LOG.error(e) } finally { HttpResponseStatus.INTERNAL_SERVER_ERROR.send(channel) } return } channel.writeAndFlush(httpResponse) } } private fun sendBadGateway(channel: Channel, extraHeaders: HttpHeaders) { try { if (channel.isActive) { HttpResponseStatus.BAD_GATEWAY.send(channel, extraHeaders = extraHeaders) } } catch (e: Throwable) { NettyUtil.log(e, LOG) } } private fun parseHeaders(response: HttpResponse, buffer: ByteBuf) { val builder = StringBuilder() while (buffer.isReadable) { builder.setLength(0) var key: String? = null var valueExpected = true while (true) { val b = buffer.readByte().toInt() if (b < 0 || b.toChar() == '\n') { break } if (b.toChar() != '\r') { if (valueExpected && b.toChar() == ':') { valueExpected = false key = builder.toString() builder.setLength(0) MessageDecoder.skipWhitespace(buffer) } else { builder.append(b.toChar()) } } } if (builder.length == 0) { // end of headers return } // skip standard headers if (key.isNullOrEmpty() || key!!.startsWith("http", ignoreCase = true) || key.startsWith("X-Accel-", ignoreCase = true)) { continue } val value = builder.toString() if (key.equals("status", ignoreCase = true)) { val index = value.indexOf(' ') if (index == -1) { LOG.warn("Cannot parse status: " + value) response.status = HttpResponseStatus.OK } else { response.status = HttpResponseStatus.valueOf(Integer.parseInt(value.substring(0, index))) } } else if (!(key.startsWith("http") || key.startsWith("HTTP"))) { response.headers().add(key, value) } } } private class ClientInfo(val channel: Channel, val extraHeaders: HttpHeaders)
apache-2.0
9195b05b6ca6e9cbfc0cd4bc08da6d40
28.578475
126
0.657316
4.411371
false
false
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/LL1/syntax/solver/FollowSetSolver.kt
1
3306
package com.bajdcc.LL1.syntax.solver import com.bajdcc.LL1.syntax.ISyntaxComponentVisitor import com.bajdcc.LL1.syntax.exp.BranchExp import com.bajdcc.LL1.syntax.exp.RuleExp import com.bajdcc.LL1.syntax.exp.SequenceExp import com.bajdcc.LL1.syntax.exp.TokenExp import com.bajdcc.util.VisitBag /** * 求解一个产生式的Follow集合 * * @author bajdcc */ class FollowSetSolver( private val origin: RuleExp, private val target: RuleExp) : ISyntaxComponentVisitor { /** * Follow集是否更新,作为算法收敛的依据 */ /** * Follow集是否更改 * * @return 经过此次计算,Follow集是否更新 */ var isUpdated = false private set /** * 上一次是否刚遍历过当前求解的非终结符 */ private var enable = false /** * 添加非终结符Follow集 * * * A=origin,B=target * * * * 添加Follow集(A->...B或A->...B(...->epsilon)) * * * * Follow(B) = Follow(A) U Follow(B) * */ private fun addVnFollowToFollow() { setUpdate(target.rule.setFollows.addAll(origin.rule.setFollows)) } /** * 添加非终结符First集 * * * A=origin,B=target,beta=exp=Vn * * * * 添加First集(A->...B beta) * * * * Follow(B) = Follow(A) U First(beta) * * * @param exp 非终结符 */ private fun addVnFirstToFollow(exp: RuleExp) { setUpdate(target.rule.setFollows.addAll(exp.rule.arrFirsts)) } /** * * * A=origin,B=target,beta=exp=Vt * * * * 添加终结符(A->...B beta) * * * * Follow(B) = Follow(A) U beta * * * @param exp 终结符 */ private fun addVtFirstToFollow(exp: TokenExp) { setUpdate(target.rule.setFollows.add(exp)) } /** * 设置更新状态 * * @param update 更新状态 */ private fun setUpdate(update: Boolean) { if (update) { this.isUpdated = true } } override fun visitBegin(node: TokenExp, bag: VisitBag) { bag.visitChildren = false bag.visitEnd = false if (enable) {// 上次经过非终结符 addVtFirstToFollow(node) enable = false } } override fun visitBegin(node: RuleExp, bag: VisitBag) { bag.visitChildren = false bag.visitEnd = false if (enable) {// 上次经过非终结符 addVnFirstToFollow(node) if (!node.rule.epsilon) { enable = false } } if (node.rule === target.rule) {// 设置为经过非终结符 enable = true } } override fun visitBegin(node: SequenceExp, bag: VisitBag) { } override fun visitBegin(node: BranchExp, bag: VisitBag) { bag.visitEnd = false } override fun visitEnd(node: TokenExp) { } override fun visitEnd(node: RuleExp) { } override fun visitEnd(node: SequenceExp) { if (enable) {// 上次经过非终结符 addVnFollowToFollow() } enable = false } override fun visitEnd(node: BranchExp) { } }
mit
7007151847caae43e56f0caddec45cb7
18.432258
72
0.539509
3.470046
false
false
false
false
AcornUI/Acorn
acornui-core/src/main/kotlin/com/acornui/obj/objectUtils.kt
1
920
/* * Copyright 2020 Poly Forest, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.acornui.obj fun removeNullValues(obj: dynamic) { //language=JavaScript js(""" for (var propName in obj) { if (obj[propName] === null || obj[propName] === undefined) { delete obj[propName]; } } """) } fun obj(init: dynamic.()->Unit): dynamic { val o = js("{}") init.invoke(o) return o }
apache-2.0
73b277ace78781603a169defcb9a2d64
26.088235
75
0.691304
3.650794
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/component/data/ComponentMetadata.kt
1
1894
package org.hexworks.zircon.api.component.data import org.hexworks.cobalt.databinding.api.extension.toProperty import org.hexworks.cobalt.databinding.api.property.Property import org.hexworks.cobalt.databinding.api.value.ObservableValue import org.hexworks.zircon.api.component.ColorTheme import org.hexworks.zircon.api.component.Component import org.hexworks.zircon.api.component.ComponentStyleSet import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.resource.TilesetResource /** * Contains metadata that is common to **all** [Component]s. */ // TODO: add API breakage to release notes data class ComponentMetadata( // TODO: next big thing is to make these observable too val relativePosition: Position, val size: Size, val name: String = "", val updateOnAttach: Boolean = true, // properties val themeProperty: Property<ColorTheme> = ColorTheme.unknown().toProperty(), val componentStyleSetProperty: Property<ComponentStyleSet> = ComponentStyleSet.unknown().toProperty(), val tilesetProperty: Property<TilesetResource> = TilesetResource.unknown().toProperty(), val hiddenProperty: Property<Boolean> = false.toProperty(), val disabledProperty: Property<Boolean> = false.toProperty() ) { val tileset: TilesetResource get() = tilesetProperty.value val componentStyleSet: ComponentStyleSet get() = componentStyleSetProperty.value val theme: ColorTheme get() = themeProperty.value val isHidden: Boolean get() = hiddenProperty.value val isDisabled: Boolean get() = disabledProperty.value init { require(relativePosition.hasNegativeComponent.not()) { "Can't have a Component with a relative position ($relativePosition) which has a " + "negative dimension." } } }
apache-2.0
e4e0b175fc3a5252158b638f1ec0936b
34.735849
106
0.733369
4.642157
false
false
false
false
AcornUI/Acorn
acornui-core/src/main/kotlin/com/acornui/cursor/CursorManager.kt
1
1371
/* * Copyright 2019 Poly Forest, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.acornui.cursor import com.acornui.component.UiComponent /** * A list of standard cursors supported in css. */ object StandardCursor { const val ALIAS = "alias" const val ALL_SCROLL = "all-scroll" const val CELL = "cell" const val COPY = "copy" const val CROSSHAIR = "crosshair" const val DEFAULT = "default" const val POINTER = "pointer" const val HELP = "help" const val TEXT = "text" const val MOVE = "move" const val NONE = "none" const val NOT_ALLOWED = "not-allowed" const val PROGRESS = "progress" const val EW_RESIZE = "ew-resize" const val NS_RESIZE = "ns-resize" const val NE_RESIZE = "ne-resize" const val SE_RESIZE = "se-resize" const val WAIT = "wait" } fun UiComponent.cursor(cursor: String) { dom.style.cursor = cursor }
apache-2.0
ea30af3a41c944e3a09be569c8702c4e
28.191489
75
0.716995
3.453401
false
false
false
false
SnakeEys/MessagePlus
app/src/main/java/info/fox/messup/base/DrawerActivity.kt
1
3131
package info.fox.messup.base import android.content.Intent import android.os.Bundle import android.support.design.widget.NavigationView import android.support.v4.app.NavUtils import android.support.v4.app.TaskStackBuilder import android.support.v4.view.GravityCompat import android.support.v4.widget.DrawerLayout import android.support.v7.widget.Toolbar import android.util.Log import android.view.MenuItem import info.fox.messup.MainActivity import info.fox.messup.R import info.fox.messup.activity.ArchivedActivity import info.fox.messup.activity.ContactsActivity import info.fox.messup.activity.UnspecifiedActivity /** *<p> * Created by user * on 2017/8/21. *</p> */ abstract class DrawerActivity : AbstractViewActivity(), NavigationView.OnNavigationItemSelectedListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_drawer) val toolbar = findWidget<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) val nav = findWidget<NavigationView>(R.id.nav_view) nav.setNavigationItemSelectedListener(this) } override fun onNavigationItemSelected(item: MenuItem): Boolean { val nav = findWidget<NavigationView>(R.id.nav_view) showActivityLog("selected $item") if (nav.menu.findItem(item.itemId).isChecked) { Log.d(javaClass.simpleName, "$item has been checked") return true } when (item.itemId) { R.id.nav_conversations -> { if (this is MainActivity) { } else { startActivity(Intent(this, MainActivity::class.java)) finish() } } R.id.nav_contacts -> { startActivity(Intent(this, ContactsActivity::class.java)) } R.id.nav_unspecified -> { startActivity(Intent(this, UnspecifiedActivity::class.java)) } R.id.nav_archive -> { startActivity(Intent(this, ArchivedActivity::class.java)) } R.id.nav_setting -> { } R.id.nav_share -> { } } val drawer = findWidget<DrawerLayout>(R.id.drawer_layout) drawer.closeDrawer(GravityCompat.START) return true } override fun onDestroy() { super.onDestroy() } override fun onBackPressed() { val drawer = findWidget<DrawerLayout>(R.id.drawer_layout) if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START) } else { val intent = NavUtils.getParentActivityIntent(this) intent?.let { intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP if (NavUtils.shouldUpRecreateTask(this, intent)) { TaskStackBuilder.create(this).addNextIntentWithParentStack(intent) } else { NavUtils.navigateUpTo(this, intent) } }?: super.onBackPressed() } } }
mit
acf4f1aaf8d5a22f1a2e24ade5ff78c6
31.625
105
0.621527
4.604412
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildMultipleEntityImpl.kt
1
9459
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ChildMultipleEntityImpl : ChildMultipleEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentMultipleEntity::class.java, ChildMultipleEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } @JvmField var _childData: String? = null override val childData: String get() = _childData!! override val parentEntity: ParentMultipleEntity get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ChildMultipleEntityData?) : ModifiableWorkspaceEntityBase<ChildMultipleEntity>(), ChildMultipleEntity.Builder { constructor() : this(ChildMultipleEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ChildMultipleEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isChildDataInitialized()) { error("Field ChildMultipleEntity#childData should be initialized") } if (_diff != null) { if (_diff.extractOneToManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field ChildMultipleEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field ChildMultipleEntity#parentEntity should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ChildMultipleEntity this.entitySource = dataSource.entitySource this.childData = dataSource.childData if (parents != null) { this.parentEntity = parents.filterIsInstance<ParentMultipleEntity>().single() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var childData: String get() = getEntityData().childData set(value) { checkModificationAllowed() getEntityData().childData = value changedProperty.add("childData") } override var parentEntity: ParentMultipleEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentMultipleEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentMultipleEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override fun getEntityData(): ChildMultipleEntityData = result ?: super.getEntityData() as ChildMultipleEntityData override fun getEntityClass(): Class<ChildMultipleEntity> = ChildMultipleEntity::class.java } } class ChildMultipleEntityData : WorkspaceEntityData<ChildMultipleEntity>() { lateinit var childData: String fun isChildDataInitialized(): Boolean = ::childData.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildMultipleEntity> { val modifiable = ChildMultipleEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): ChildMultipleEntity { val entity = ChildMultipleEntityImpl() entity._childData = childData entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ChildMultipleEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ChildMultipleEntity(childData, entitySource) { this.parentEntity = parents.filterIsInstance<ParentMultipleEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(ParentMultipleEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildMultipleEntityData if (this.entitySource != other.entitySource) return false if (this.childData != other.childData) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildMultipleEntityData if (this.childData != other.childData) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + childData.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + childData.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
d0c03203da3c391697fca2f49f03a4b9
36.240157
158
0.696374
5.356172
false
false
false
false
DanielGrech/anko
dsl/static/src/ContextUtils.kt
3
11912
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.anko import android.content.Intent import android.content.Context import android.content.SharedPreferences import android.content.ActivityNotFoundException import android.preference.PreferenceManager import android.app.Activity import android.app.Fragment import android.app.Service import android.os.Bundle import android.net.Uri import java.io.Serializable import android.os.Parcelable import android.view.View import org.jetbrains.anko.internals.AnkoInternals import org.jetbrains.anko.internals.noBinding public val LDPI: Int = android.util.DisplayMetrics.DENSITY_LOW public val MDPI: Int = android.util.DisplayMetrics.DENSITY_MEDIUM public val HDPI: Int = android.util.DisplayMetrics.DENSITY_HIGH //May not be available on older Android versions public val TVDPI: Int = 213 public val XHDPI: Int = 320 public val XXHDPI: Int = 480 public val XXXHDPI: Int = 640 public val MAXDPI: Int = 0xfffe //returns dip(dp) dimension value in pixels public fun Context.dip(value: Int): Int = (value * (getResources()?.getDisplayMetrics()?.density ?: 0f)).toInt() public fun Context.dip(value: Float): Int = (value * (getResources()?.getDisplayMetrics()?.density ?: 0f)).toInt() //return sp dimension value in pixels public fun Context.sp(value: Int): Int = (value * (getResources()?.getDisplayMetrics()?.scaledDensity ?: 0f)).toInt() public fun Context.sp(value: Float): Int = (value * (getResources()?.getDisplayMetrics()?.scaledDensity ?: 0f)).toInt() //converts px value into dip or sp public fun Context.px2dip(px: Int): Float = (px.toFloat() / (getResources()?.getDisplayMetrics()?.density ?: 1f)).toFloat() public fun Context.px2sp(px: Int): Float = (px.toFloat() / (getResources()?.getDisplayMetrics()?.scaledDensity ?: 1f)).toFloat() public fun Context.dimen(resource: Int): Int = getResources().getDimensionPixelSize(resource) //the same for nested DSL components @suppress("NOTHING_TO_INLINE") public inline fun UiHelper.dip(value: Int): Int = ctx.dip(value) @suppress("NOTHING_TO_INLINE") public inline fun UiHelper.dip(value: Float): Int = ctx.dip(value) @suppress("NOTHING_TO_INLINE") public inline fun UiHelper.sp(value: Int): Int = ctx.sp(value) @suppress("NOTHING_TO_INLINE") public inline fun UiHelper.sp(value: Float): Int = ctx.sp(value) @suppress("NOTHING_TO_INLINE") public inline fun UiHelper.px2dip(px: Int): Float = ctx.px2dip(px) @suppress("NOTHING_TO_INLINE") public inline fun UiHelper.px2sp(px: Int): Float = ctx.px2sp(px) @suppress("NOTHING_TO_INLINE") public inline fun UiHelper.dimen(resource: Int): Int = ctx.dimen(resource) //the same for Fragments @suppress("NOTHING_TO_INLINE") public inline fun Fragment.dip(value: Int): Int = getActivity().dip(value) @suppress("NOTHING_TO_INLINE") public inline fun Fragment.dip(value: Float): Int = getActivity().dip(value) @suppress("NOTHING_TO_INLINE") public inline fun Fragment.sp(value: Int): Int = getActivity().sp(value) @suppress("NOTHING_TO_INLINE") public inline fun Fragment.sp(value: Float): Int = getActivity().sp(value) @suppress("NOTHING_TO_INLINE") public inline fun Fragment.px2dip(px: Int): Float = getActivity().px2dip(px) @suppress("NOTHING_TO_INLINE") public inline fun Fragment.px2sp(px: Int): Float = getActivity().px2sp(px) @suppress("NOTHING_TO_INLINE") public inline fun Fragment.dimen(resource: Int): Int = getActivity().dimen(resource) public noBinding val Activity.intent: Intent get() = getIntent() public val Context.defaultSharedPreferences: SharedPreferences get() = PreferenceManager.getDefaultSharedPreferences(this) public val Fragment.defaultSharedPreferences: SharedPreferences get() = PreferenceManager.getDefaultSharedPreferences(getActivity()) public val Fragment.act: Activity get() = getActivity() public val Fragment.ctx: Context get() = getActivity() public val Context.ctx: Context get() = this public val Activity.act: Activity get() = this //type casting is now under the hood @suppress("UNCHECKED_CAST") public fun <T : View> View.find(id: Int): T = findViewById(id) as T @suppress("UNCHECKED_CAST") public fun <T : View> Activity.find(id: Int): T = findViewById(id) as T @suppress("UNCHECKED_CAST") public fun <T : View> Fragment.find(id: Int): T = getView()?.findViewById(id) as T @suppress("NOTHING_TO_INLINE") public inline fun Fragment.browse(url: String): Boolean = getActivity().browse(url) public fun Context.browse(url: String): Boolean { try { val intent = Intent(Intent.ACTION_VIEW) intent.setData(Uri.parse(url)) startActivity(intent) return true } catch (e: ActivityNotFoundException) { e.printStackTrace() return false } } @suppress("NOTHING_TO_INLINE") public inline fun Fragment.share(text: String, subject: String = ""): Boolean = getActivity().share(text, subject) public fun Context.share(text: String, subject: String = ""): Boolean { try { val intent = Intent(android.content.Intent.ACTION_SEND) intent.setType("text/plain") intent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject) intent.putExtra(android.content.Intent.EXTRA_TEXT, text) startActivity(Intent.createChooser(intent, null)) return true } catch (e: ActivityNotFoundException) { e.printStackTrace() return false } } @suppress("NOTHING_TO_INLINE") public inline fun Fragment.email(email: String, subject: String = "", text: String = ""): Boolean = getActivity().email(email, subject, text) public fun Context.email(email: String, subject: String = "", text: String = ""): Boolean { val intent = Intent(Intent.ACTION_SENDTO) intent.setData(Uri.parse("mailto:")) intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(email)) if (subject.length() > 0) intent.putExtra(Intent.EXTRA_SUBJECT, subject) if (text.length() > 0) intent.putExtra(Intent.EXTRA_TEXT, text) if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent) return true } return false } @suppress("NOTHING_TO_INLINE") public inline fun Fragment.makeCall(number: String): Boolean = getActivity().makeCall(number) public fun Context.makeCall(number: String): Boolean { try { val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:$number")) startActivity(intent) return true } catch (e: Exception) { e.printStackTrace() return false } } @suppress("NOTHING_TO_INLINE") public inline fun <reified T: Activity> Context.startActivity(vararg params: Pair<String, Any>) { AnkoInternals.internalStartActivity(this, javaClass<T>(), params) } @suppress("NOTHING_TO_INLINE") public inline fun <reified T: Activity> Activity.startActivityForResult(requestCode: Int, vararg params: Pair<String, Any>) { AnkoInternals.internalStartActivityForResult(this, javaClass<T>(), requestCode, params) } @suppress("NOTHING_TO_INLINE") public inline fun <reified T: Activity> Fragment.startActivity(vararg params: Pair<String, Any>) { AnkoInternals.internalStartActivity(getActivity(), javaClass<T>(), params) } @suppress("NOTHING_TO_INLINE") public inline fun <reified T: Activity> Fragment.startActivityForResult(requestCode: Int, vararg params: Pair<String, Any>) { AnkoInternals.internalStartActivityForResult(getActivity(), javaClass<T>(), requestCode, params) } @suppress("NOTHING_TO_INLINE") public inline fun <reified T: Service> Context.startService(vararg params: Pair<String, Any>) { AnkoInternals.internalStartService(this, javaClass<T>(), params) } @suppress("NOTHING_TO_INLINE") public inline fun <reified T: Service> Fragment.startService(vararg params: Pair<String, Any>) { AnkoInternals.internalStartService(getActivity(), javaClass<T>(), params) } public fun <T: Fragment> T.withArguments(vararg params: Pair<String, Any>): T { setArguments(bundleOf(*params)) return this } public fun bundleOf(vararg params: Pair<String, Any>): Bundle { val b = Bundle() for (p in params) { val (k, v) = p when (v) { is Boolean -> b.putBoolean(k, v) is Byte -> b.putByte(k, v) is Char -> b.putChar(k, v) is Short -> b.putShort(k, v) is Int -> b.putInt(k, v) is Long -> b.putLong(k, v) is Float -> b.putFloat(k, v) is Double -> b.putDouble(k, v) is String -> b.putString(k, v) is CharSequence -> b.putCharSequence(k, v) is Parcelable -> b.putParcelable(k, v) is Serializable -> b.putSerializable(k, v) is BooleanArray -> b.putBooleanArray(k, v) is ByteArray -> b.putByteArray(k, v) is CharArray -> b.putCharArray(k, v) is DoubleArray -> b.putDoubleArray(k, v) is FloatArray -> b.putFloatArray(k, v) is IntArray -> b.putIntArray(k, v) is LongArray -> b.putLongArray(k, v) is Array<Parcelable> -> b.putParcelableArray(k, v) is ShortArray -> b.putShortArray(k, v) is Array<CharSequence> -> b.putCharSequenceArray(k, v) is Array<String> -> b.putStringArray(k, v) is Bundle -> b.putBundle(k, v) else -> throw AnkoException("Unsupported bundle component (${v.javaClass})") } } return b } public noBinding val Context.displayMetrics: android.util.DisplayMetrics get() = getResources().getDisplayMetrics() public noBinding val Context.configuration: android.content.res.Configuration get() = getResources().getConfiguration() public val android.content.res.Configuration.portrait: Boolean get() = orientation == android.content.res.Configuration.ORIENTATION_PORTRAIT public val android.content.res.Configuration.landscape: Boolean get() = orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE public val android.content.res.Configuration.long: Boolean get() = (screenLayout and android.content.res.Configuration.SCREENLAYOUT_LONG_YES) != 0 public inline fun <reified T: Any> Context.intentFor(vararg params: Pair<String, Any>): Intent { return AnkoInternals.createIntent(this, javaClass<T>(), params) } public inline fun <reified T: Any> Fragment.intentFor(vararg params: Pair<String, Any>): Intent { return AnkoInternals.createIntent(getActivity(), javaClass<T>(), params) } @suppress("NOTHING_TO_INLINE") private inline fun Intent.setFlag(flag: Int): Intent { setFlags(flag) return this } public fun Intent.clearTask(): Intent = setFlag(Intent.FLAG_ACTIVITY_CLEAR_TASK) public fun Intent.clearTop(): Intent = setFlag(Intent.FLAG_ACTIVITY_CLEAR_TOP) public fun Intent.clearWhenTaskReset(): Intent = setFlag(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) public fun Intent.excludeFromRecents(): Intent = setFlag(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) public fun Intent.multipleTask(): Intent = setFlag(Intent.FLAG_ACTIVITY_MULTIPLE_TASK) public fun Intent.newTask(): Intent = setFlag(Intent.FLAG_ACTIVITY_NEW_TASK) public fun Intent.noAnimation(): Intent = setFlag(Intent.FLAG_ACTIVITY_NO_ANIMATION) public fun Intent.noHistory(): Intent = setFlag(Intent.FLAG_ACTIVITY_NO_HISTORY) public fun Intent.singleTop(): Intent = setFlag(Intent.FLAG_ACTIVITY_SINGLE_TOP)
apache-2.0
4704dc325c37af35751f5b3f0422c8b3
37.675325
125
0.712139
3.921001
false
false
false
false
mdaniel/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/actions/ReaderModeActionProvider.kt
1
7141
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInsight.actions import com.intellij.codeInsight.actions.ReaderModeSettings.Companion.matchMode import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.icons.AllIcons import com.intellij.ide.HelpTooltip import com.intellij.lang.LangBundle import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.actionSystem.impl.ActionButtonWithText import com.intellij.openapi.application.Experiments import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.ColorKey import com.intellij.openapi.editor.markup.InspectionWidgetActionProvider import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.DumbAwareToggleAction import com.intellij.openapi.project.Project import com.intellij.openapi.project.isNotificationSilentMode import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.registry.Registry import com.intellij.psi.PsiDocumentManager import com.intellij.ui.GotItTooltip import com.intellij.ui.JBColor import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.EmptyIcon import com.intellij.util.ui.JBInsets import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.Insets import javax.swing.JComponent import javax.swing.plaf.FontUIResource private class ReaderModeActionProvider : InspectionWidgetActionProvider { override fun createAction(editor: Editor): AnAction? { val project: Project? = editor.project return if (project == null || project.isDefault) null else object : DefaultActionGroup(ReaderModeAction(editor), Separator.create()) { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = false if (Experiments.getInstance().isFeatureEnabled("editor.reader.mode")) { val p = e.project ?: return if (p.isInitialized) { val textEditor = e.getData(CommonDataKeys.EDITOR) ?: return val file = PsiDocumentManager.getInstance(p).getPsiFile(textEditor.document)?.virtualFile e.presentation.isEnabledAndVisible = matchMode(p, file, textEditor) } } } } } private class ReaderModeAction(private val editor: Editor) : DumbAwareToggleAction( LangBundle.messagePointer("action.ReaderModeProvider.text"), LangBundle.messagePointer("action.ReaderModeProvider.description"), null), CustomComponentAction { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT override fun createCustomComponent(presentation: Presentation, place: String): JComponent = object : ActionButtonWithText(this, presentation, place, JBUI.size(18)) { override fun iconTextSpace() = JBUI.scale(2) override fun updateToolTipText() { val project = editor.project if (Registry.`is`("ide.helptooltip.enabled") && project != null) { HelpTooltip.dispose(this) HelpTooltip() .setTitle(myPresentation.description) .setDescription(LangBundle.message("action.ReaderModeProvider.description")) .setLink(LangBundle.message("action.ReaderModeProvider.link.configure")) { ShowSettingsUtil.getInstance().showSettingsDialog(project, ReaderModeConfigurable::class.java) } .installOn(this) } else { toolTipText = myPresentation.description } } override fun getInsets(): Insets = JBUI.insets(2) override fun getMargins(): Insets = if (myPresentation.icon == AllIcons.General.ReaderMode) JBInsets.emptyInsets() else JBUI.insetsRight(5) override fun updateUI() { super.updateUI() if (!SystemInfo.isWindows) { font = FontUIResource(font.deriveFont(font.style, font.size - JBUIScale.scale(2).toFloat())) } } }.also { it.foreground = JBColor.lazy { editor.colorsScheme.getColor(FOREGROUND) ?: FOREGROUND.defaultColor } if (!SystemInfo.isWindows) { it.font = FontUIResource(it.font.deriveFont(it.font.style, it.font.size - JBUIScale.scale(2).toFloat())) } editor.project?.let { p -> if (!ReaderModeSettings.getInstance(p).enabled || isNotificationSilentMode(p)) return@let val connection = p.messageBus.connect(p) val gotItTooltip = GotItTooltip("reader.mode.got.it", LangBundle.message("text.reader.mode.got.it.popup"), p) .withHeader(LangBundle.message("title.reader.mode.got.it.popup")) if (gotItTooltip.canShow()) { connection.subscribe(DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC, object : DaemonCodeAnalyzer.DaemonListener { override fun daemonFinished(fileEditors: Collection<FileEditor>) { fileEditors.find { fe -> (fe is TextEditor) && editor == fe.editor }?.let { _ -> gotItTooltip.setOnBalloonCreated { balloon -> balloon.addListener(object: JBPopupListener { override fun onClosed(event: LightweightWindowEvent) { connection.disconnect() } })}. show(it, GotItTooltip.BOTTOM_MIDDLE) } } }) } } } override fun isSelected(e: AnActionEvent): Boolean { return true } override fun setSelected(e: AnActionEvent, state: Boolean) { val project = e.project ?: return ReaderModeSettings.getInstance(project).enabled = !ReaderModeSettings.getInstance(project).enabled project.messageBus.syncPublisher(ReaderModeSettingsListener.TOPIC).modeChanged(project) } override fun update(e: AnActionEvent) { val project = e.project ?: return val presentation = e.presentation if (!ReaderModeSettings.getInstance(project).enabled) { presentation.text = null presentation.icon = AllIcons.General.ReaderMode presentation.hoveredIcon = null presentation.description = LangBundle.message("action.ReaderModeProvider.text.enter") } else { presentation.text = LangBundle.message("action.ReaderModeProvider.text") presentation.icon = EmptyIcon.ICON_16 presentation.hoveredIcon = AllIcons.Actions.CloseDarkGrey presentation.description = LangBundle.message("action.ReaderModeProvider.text.exit") } } } companion object { val FOREGROUND = ColorKey.createColorKey("ActionButton.iconTextForeground", UIUtil.getContextHelpForeground()) } }
apache-2.0
0d1ca8ba5c98d6a81f252640786c359c
43.08642
122
0.701582
4.904533
false
false
false
false
GunoH/intellij-community
plugins/kotlin/project-wizard/compose/src/org/jetbrains/kotlin/tools/composeProjectWizard/ComposeModuleTemplateGroup.kt
8
3353
// 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.tools.composeProjectWizard import com.intellij.icons.AllIcons import com.intellij.ide.fileTemplates.FileTemplateGroupDescriptor import com.intellij.ide.fileTemplates.FileTemplateGroupDescriptorFactory internal class ComposeModuleTemplateGroup : FileTemplateGroupDescriptorFactory { override fun getFileTemplatesDescriptor(): FileTemplateGroupDescriptor { val root = FileTemplateGroupDescriptor("COMPOSE", AllIcons.Nodes.Module) with (root) { addTemplate(COMPOSE_SETTINGS_GRADLE) addTemplate(COMPOSE_GRADLE_PROPERTIES) addTemplate(COMPOSE_GRADLE_WRAPPER_PROPERTIES) addTemplate(COMPOSE_LOCAL_PROPERTIES) addTemplate(COMPOSE_DESKTOP_BUILD_GRADLE) addTemplate(COMPOSE_COMMON_BUILD_GRADLE) addTemplate(COMPOSE_MPP_BUILD_GRADLE) addTemplate(COMPOSE_ANDROID_BUILD_GRADLE) addTemplate(COMPOSE_WEB_BUILD_GRADLE) addTemplate(COMPOSE_DESKTOP_MAINKT) addTemplate(COMPOSE_ANDROID_MAINACTIVITYKT) addTemplate(COMPOSE_ANDROID_MANIFEST) addTemplate(COMPOSE_WEB_MAINKT) addTemplate(COMPOSE_WEB_INDEX_HTML) addTemplate(COMPOSE_COMMON_ANDROID_PLATFORMKT) addTemplate(COMPOSE_COMMON_ANDROID_MANIFEST) addTemplate(COMPOSE_COMMON_COMMON_APPKT) addTemplate(COMPOSE_COMMON_COMMON_PLATFORMKT) addTemplate(COMPOSE_COMMON_DESKTOP_APPKT) addTemplate(COMPOSE_COMMON_DESKTOP_PLATFORMKT) } return root } companion object { const val COMPOSE_SETTINGS_GRADLE = "compose-settings.gradle.kts" const val COMPOSE_GRADLE_PROPERTIES = "compose-gradle.properties" const val COMPOSE_GRADLE_WRAPPER_PROPERTIES = "compose-gradle-wrapper.properties" const val COMPOSE_LOCAL_PROPERTIES = "compose-local.properties" const val COMPOSE_DESKTOP_BUILD_GRADLE = "compose-desktop-build.gradle.kts" const val COMPOSE_MPP_BUILD_GRADLE = "compose-mpp-build.gradle.kts" const val COMPOSE_COMMON_BUILD_GRADLE = "compose-common-build.gradle.kts" const val COMPOSE_ANDROID_BUILD_GRADLE = "compose-android-build.gradle.kts" const val COMPOSE_WEB_BUILD_GRADLE = "compose-web-build.gradle.kts" const val COMPOSE_DESKTOP_MAINKT = "compose-desktop-main.kt" const val COMPOSE_ANDROID_MAINACTIVITYKT = "compose-android-MainActivity.kt" const val COMPOSE_ANDROID_MANIFEST = "compose-android-AndroidManifest.xml" const val COMPOSE_WEB_MAINKT = "compose-web-main.kt" const val COMPOSE_WEB_INDEX_HTML = "compose-web-index.html" const val COMPOSE_COMMON_ANDROID_PLATFORMKT = "compose-common-android-platform.kt" const val COMPOSE_COMMON_ANDROID_MANIFEST = "compose-common-AndroidManifest.xml" const val COMPOSE_COMMON_COMMON_APPKT = "compose-common-common-App.kt" const val COMPOSE_COMMON_COMMON_PLATFORMKT = "compose-common-common-platform.kt" const val COMPOSE_COMMON_DESKTOP_APPKT = "compose-common-desktop-App.kt" const val COMPOSE_COMMON_DESKTOP_PLATFORMKT = "compose-common-desktop-platform.kt" } }
apache-2.0
bb1d76d960cdfc4be0eb00da3c73b595
43.131579
120
0.712795
4.377285
false
false
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/actions/commit/AbstractCommitChangesAction.kt
2
2459
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs.actions.commit import com.intellij.idea.ActionsBundle import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsDataKeys import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.changes.CommitExecutor import com.intellij.vcsUtil.VcsUtil abstract class AbstractCommitChangesAction : DumbAwareAction() { override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { CheckinActionUtil.updateCommonCommitAction(e) val presentation = e.presentation if (presentation.isEnabled) { val changes = e.getData(VcsDataKeys.CHANGES).orEmpty() if (e.place == ActionPlaces.CHANGES_VIEW_POPUP) { val changeLists = e.getData(VcsDataKeys.CHANGE_LISTS).orEmpty() presentation.isEnabled = when { changeLists.isEmpty() -> changes.isNotEmpty() changeLists.size == 1 -> changeLists.single().changes.isNotEmpty() else -> false } } if (presentation.isEnabled) { val manager = ChangeListManager.getInstance(e.project!!) presentation.isEnabled = changes.all { isActionEnabled(manager, it) } } } } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val initialChangeList = CheckinActionUtil.getInitiallySelectedChangeList(project, e) val pathsToCommit = ProjectLevelVcsManager.getInstance(project).allVersionedRoots .map { VcsUtil.getFilePath(it) } val executor = getExecutor(project) CheckinActionUtil.performCommonCommitAction(e, project, initialChangeList, pathsToCommit, ActionsBundle.message("action.CheckinProject.text"), executor, false) } protected abstract fun getExecutor(project: Project): CommitExecutor protected open fun isActionEnabled(manager: ChangeListManager, it: Change) = manager.getChangeList(it) != null }
apache-2.0
4f968c4550f94de2af6cc90a7852727f
39.983333
120
0.735258
4.840551
false
false
false
false
GunoH/intellij-community
java/java-analysis-impl/src/com/intellij/codeInspection/deprecation/RedundantScheduledForRemovalAnnotationInspection.kt
8
3260
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInspection.deprecation import com.intellij.codeInspection.* import com.intellij.java.analysis.JavaAnalysisBundle import com.intellij.lang.jvm.annotation.JvmAnnotationConstantValue import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.util.PsiUtil import org.jetbrains.annotations.ApiStatus class RedundantScheduledForRemovalAnnotationInspection : LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { if (!PsiUtil.isLanguageLevel9OrHigher(holder.file)) return PsiElementVisitor.EMPTY_VISITOR return object : JavaElementVisitor() { override fun visitClass(aClass: PsiClass) { visitAnnotatedElement(aClass) } override fun visitMethod(method: PsiMethod) { visitAnnotatedElement(method) } override fun visitField(field: PsiField) { visitAnnotatedElement(field) } private fun visitAnnotatedElement(element: PsiModifierListOwner) { val forRemovalAnnotation = element.getAnnotation(ApiStatus.ScheduledForRemoval::class.java.canonicalName) ?: return if (forRemovalAnnotation.hasAttribute("inVersion")) return val deprecatedAnnotation = element.getAnnotation(CommonClassNames.JAVA_LANG_DEPRECATED) ?: return val forRemovalAttribute = deprecatedAnnotation.findAttribute("forRemoval")?.attributeValue val alreadyHasAttribute = (forRemovalAttribute as? JvmAnnotationConstantValue)?.constantValue == true if (alreadyHasAttribute) { holder.registerProblem(forRemovalAnnotation, JavaAnalysisBundle.message("inspection.message.scheduled.for.removal.annotation.can.be.removed"), RemoveAnnotationQuickFix(forRemovalAnnotation, element)) } else { val fix = ReplaceAnnotationByForRemovalAttributeFix() holder.registerProblem(forRemovalAnnotation, JavaAnalysisBundle.message("inspection.message.scheduled.for.removal.annotation.can.be.replaced.by.attribute"), fix) } } } } class ReplaceAnnotationByForRemovalAttributeFix : LocalQuickFix { override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val forRemovalAnnotation = descriptor.psiElement as? PsiAnnotation ?: return val deprecatedAnnotation = forRemovalAnnotation.owner?.findAnnotation(CommonClassNames.JAVA_LANG_DEPRECATED) ?: return val javaFile = forRemovalAnnotation.containingFile as? PsiJavaFile forRemovalAnnotation.delete() val trueLiteral = JavaPsiFacade.getElementFactory(project).createExpressionFromText(PsiKeyword.TRUE, null) deprecatedAnnotation.setDeclaredAttributeValue("forRemoval", trueLiteral) if (javaFile != null) { JavaCodeStyleManager.getInstance(project).removeRedundantImports(javaFile) } } override fun getName(): String = familyName override fun getFamilyName(): String { return JavaAnalysisBundle.message("inspection.fix.name.remove.scheduled.for.removal.annotation.by.attribute") } } }
apache-2.0
48eadfd347f628dacbe57f1072ddf3c3
48.409091
209
0.767178
5.199362
false
false
false
false
google/accompanist
sample/src/main/java/com/google/accompanist/sample/placeholder/DocsSamplesMaterial.kt
1
1989
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.accompanist.sample.placeholder import androidx.compose.foundation.layout.padding import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.google.accompanist.placeholder.PlaceholderHighlight import com.google.accompanist.placeholder.material.fade import com.google.accompanist.placeholder.material.placeholder import com.google.accompanist.placeholder.material.shimmer @Composable fun DocSample_Material_Placeholder() { Text( text = "Content to display after content has loaded", modifier = Modifier .padding(16.dp) .placeholder(visible = true) ) } @Composable fun DocSample_Material_PlaceholderFade() { Text( text = "Content to display after content has loaded", modifier = Modifier .padding(16.dp) .placeholder( visible = true, highlight = PlaceholderHighlight.fade(), ) ) } @Composable fun DocSample_Material_PlaceholderShimmer() { Text( text = "Content to display after content has loaded", modifier = Modifier .padding(16.dp) .placeholder( visible = true, highlight = PlaceholderHighlight.shimmer(), ) ) }
apache-2.0
0b6f1f50d5bae4a4466e723d777295e4
30.571429
75
0.691302
4.551487
false
false
false
false
chaojimiaomiao/colorful_wechat
src/main/kotlin/com/rarnu/tophighlight/market/ThemeListAdapter.kt
1
1692
package com.rarnu.tophighlight.market import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import com.rarnu.tophighlight.R import com.rarnu.tophighlight.ThemePreviewView import com.rarnu.tophighlight.api.ThemeINI import com.rarnu.tophighlight.util.UIUtils /** * Created by rarnu on 2/28/17. */ class ThemeListAdapter : BaseAdapter { private var _ctx: Context? = null private var _list: MutableList<ThemeINI>? = null private var mViewHolder: ViewHolder ? =null constructor(ctx: Context, list: MutableList<ThemeINI>?): super() { _ctx = ctx _list = list } fun setList(list: MutableList<ThemeINI>?) { _list = list notifyDataSetChanged() } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? { var view = convertView if (view != null) { mViewHolder = view.getTag() as ViewHolder? } else { view = View.inflate(_ctx, R.layout.adapter_preview, null) mViewHolder = ViewHolder() mViewHolder!!.mThemePreview = view.findViewById(R.id.vPreview) as ThemePreviewView? view.setTag(mViewHolder) } mViewHolder!!.mThemePreview!!.layoutParams?.height = UIUtils.height() / 3 mViewHolder!!.mThemePreview!!.setThemePreview(_list!![position]) return view } override fun getItem(position: Int): Any? = _list!![position] override fun getItemId(position: Int): Long = position.toLong() override fun getCount(): Int = _list!!.size class ViewHolder { var mThemePreview: ThemePreviewView? = null } }
gpl-3.0
9f5f12001e8ef452d8ce9c8bca1771c5
29.232143
95
0.665485
4.147059
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/i18n/I18nConstants.kt
1
934
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.i18n object I18nConstants { const val FILE_EXTENSION = "lang" const val DEFAULT_LOCALE = "en_us" const val DEFAULT_LOCALE_FILE = "$DEFAULT_LOCALE.$FILE_EXTENSION" const val I18N_CLIENT_CLASS = "net.minecraft.client.resources.I18n" const val I18N_COMMON_CLASS = "net.minecraft.util.text.translation.I18n" const val CONSTRUCTOR = "<init>" const val TRANSLATION_COMPONENT_CLASS = "net.minecraft.util.text.TextComponentTranslation" const val COMMAND_EXCEPTION_CLASS = "net.minecraft.command.CommandException" const val FORMAT = "func_135052_a" const val TRANSLATE_TO_LOCAL = "func_74838_a" const val TRANSLATE_TO_LOCAL_FORMATTED = "func_74837_a" const val SET_BLOCK_NAME = "func_149663_c" const val SET_ITEM_NAME = "func_77655_b" }
mit
8c0dfc4540254cd321ba1c18b631c5c2
33.592593
94
0.710921
3.323843
false
false
false
false
mdanielwork/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/lValueUtil.kt
1
1783
// 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. @file:JvmName("GroovyLValueUtil") package org.jetbrains.plugins.groovy.lang.psi.util import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrParenthesizedExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrTuple import org.jetbrains.plugins.groovy.lang.resolve.api.Argument import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument import org.jetbrains.plugins.groovy.lang.resolve.api.JustTypeArgument /** * The expression is a rValue when it is in rValue position or it's a lValue of operator assignment. */ fun GrExpression.isRValue(): Boolean { val (parent, lastParent) = skipParentsOfType<GrParenthesizedExpression>() ?: return true return parent !is GrAssignmentExpression || lastParent != parent.lValue || parent.isOperatorAssignment } /** * The expression is a lValue when it's on the left of whatever assignment. */ fun GrExpression.isLValue(): Boolean { val parent = parent return when (parent) { is GrTuple -> true is GrAssignmentExpression -> this == parent.lValue else -> false } } class RValue(val argument: Argument) /** * @return non-null result iff this expression is an l-value */ fun GrExpression.getRValue(): RValue? { val parent = parent return when (parent) { is GrTuple -> RValue(JustTypeArgument(null)) is GrAssignmentExpression -> if (this !== parent.lValue) null else RValue(ExpressionArgument(parent)) else -> null } }
apache-2.0
6a1ce0bc5d10f0926dc9cd9221253aac
37.76087
140
0.77005
4.108295
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/program/programindicatorengine/internal/function/ProgramCountFunction.kt
1
5011
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.program.programindicatorengine.internal.function import org.hisp.dhis.android.core.event.EventTableInfo import org.hisp.dhis.android.core.parser.internal.expression.CommonExpressionVisitor import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramExpressionItem import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramIndicatorSQLUtils.getColumnValueCast import org.hisp.dhis.android.core.program.programindicatorengine.internal.ProgramIndicatorSQLUtils.getDataValueEventWhereClause import org.hisp.dhis.android.core.program.programindicatorengine.internal.dataitem.ProgramItemStageElement import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValueTableInfo import org.hisp.dhis.antlr.ParserExceptionWithoutContext import org.hisp.dhis.parser.expression.antlr.ExpressionParser.ExprContext internal abstract class ProgramCountFunction : ProgramExpressionItem() { override fun evaluate(ctx: ExprContext, visitor: CommonExpressionVisitor): Any { validateCountFunctionArgs(ctx) val programStage = ctx.uid0.text val dataElement = ctx.uid1.text var count = 0 val stageEvents = visitor.programIndicatorContext.events[programStage] stageEvents?.forEach { event -> event.trackedEntityDataValues()?.forEach { dataValue -> if (dataElement == dataValue.dataElement() && countIf(ctx, visitor, dataValue.value())) { count++ } } } return count.toString() } override fun getSql(ctx: ExprContext, visitor: CommonExpressionVisitor): Any { validateCountFunctionArgs(ctx) val programStageId = ctx.uid0.text val dataElementId = ctx.uid1.text val dataElement = visitor.dataElementStore.selectByUid(dataElementId) ?: throw IllegalArgumentException("DataElement $dataElementId does not exist.") val valueCastExpression = getColumnValueCast( TrackedEntityDataValueTableInfo.Columns.VALUE, dataElement.valueType() ) val conditionalSql = getConditionalSql(ctx, visitor) return "(SELECT COUNT() " + "FROM ${TrackedEntityDataValueTableInfo.TABLE_INFO.name()} " + "INNER JOIN ${EventTableInfo.TABLE_INFO.name()} " + "ON ${TrackedEntityDataValueTableInfo.Columns.EVENT} = ${EventTableInfo.Columns.UID} " + "WHERE ${TrackedEntityDataValueTableInfo.Columns.DATA_ELEMENT} = '$dataElementId' " + "AND ${EventTableInfo.Columns.PROGRAM_STAGE} = '$programStageId' " + "AND ${getDataValueEventWhereClause(visitor.programIndicatorSQLContext.programIndicator)} " + "AND ${TrackedEntityDataValueTableInfo.Columns.VALUE} IS NOT NULL " + "AND $valueCastExpression $conditionalSql " + ")" } protected abstract fun countIf(ctx: ExprContext, visitor: CommonExpressionVisitor, value: String?): Boolean protected abstract fun getConditionalSql(ctx: ExprContext, visitor: CommonExpressionVisitor): String private fun validateCountFunctionArgs(ctx: ExprContext) { if (getProgramArgType(ctx) !is ProgramItemStageElement) { throw ParserExceptionWithoutContext( "First argument not supported for d2:count... functions: ${ctx.text}" ) } } }
bsd-3-clause
b26e6ed3d30565c90a133cb58145c668
49.11
127
0.732588
4.907933
false
false
false
false
theapache64/Mock-API
src/com/theah64/mock_api/models/ParamResponse.kt
1
463
package com.theah64.mock_api.models class ParamResponse( val id: String?, val routeId: String, val paramId: String, val paramValue: String, val responseId: String, val relOpt: String ) { companion object { val EQUALS = "==" val NOT_EQUALS = "!=" val GREATER_THAN = ">" val GREATER_THAN_OR_EQUALS = ">=" val LESS_THAN = "<" val LESS_THAN_OR_EQUALS = "<=" } }
apache-2.0
2b931e2d1e80043c10e38b766e17da59
23.368421
41
0.531317
3.991379
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/ec2/src/main/kotlin/com/kotlin/ec2/FindRunningInstances.kt
1
1775
// snippet-sourcedescription:[FindRunningInstances.kt demonstrates how to find running Amazon Elastic Compute Cloud (Amazon EC2) instances by using a filter.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Amazon EC2] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.ec2 // snippet-start:[ec2.kotlin.running_instances.import] import aws.sdk.kotlin.services.ec2.Ec2Client import aws.sdk.kotlin.services.ec2.model.DescribeInstancesRequest import aws.sdk.kotlin.services.ec2.model.Filter // snippet-end:[ec2.kotlin.running_instances.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main() { findRunningEC2Instances() } // snippet-start:[ec2.kotlin.running_instances.main] suspend fun findRunningEC2Instances() { val filter = Filter { name = "instance-state-name" values = listOf("running") } val request = DescribeInstancesRequest { filters = listOf(filter) } Ec2Client { region = "us-west-2" }.use { ec2 -> val response = ec2.describeInstances(request) response.reservations?.forEach { reservation -> reservation.instances?.forEach { instance -> println("Found Reservation with id: ${instance.instanceId}, type: ${instance.instanceType} state: ${instance.state?.name} and monitoring state: ${instance.monitoring?.state}") } } } } // snippet-end:[ec2.kotlin.running_instances.main]
apache-2.0
e7557ddf5399f09a099f52026524f50e
33.5
191
0.696901
3.892544
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/glue/src/main/kotlin/com/kotlin/glue/DeleteCrawler.kt
1
1575
// snippet-sourcedescription:[DeleteCrawler.kt demonstrates how to delete an AWS Glue crawler.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-keyword:[AWS Glue] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.glue // snippet-start:[glue.kotlin.delete_crawler.import] import aws.sdk.kotlin.services.glue.GlueClient import aws.sdk.kotlin.services.glue.model.DeleteCrawlerRequest import kotlin.system.exitProcess // snippet-end:[glue.kotlin.delete_crawler.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <crawlerName> Where: crawlerName - The name of the crawler to delete. """ if (args.size != 1) { println(usage) exitProcess(0) } val crawlerName = args[0] deleteSpecificCrawler(crawlerName) } // snippet-start:[glue.kotlin.delete_crawler.main] suspend fun deleteSpecificCrawler(crawlerName: String) { val request = DeleteCrawlerRequest { name = crawlerName } GlueClient { region = "us-east-1" }.use { glueClient -> glueClient.deleteCrawler(request) println("$crawlerName was deleted") } } // snippet-end:[glue.kotlin.delete_crawler.main]
apache-2.0
b92c209460d5b99c73acde6fde145386
26.636364
95
0.686349
3.75
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/cloudwatch/src/main/kotlin/com/kotlin/cloudwatch/PutRule.kt
1
1994
// snippet-sourcedescription:[PutRule.kt demonstrates how to create an Amazon CloudWatch event-routing rule.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Amazon CloudWatch] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.cloudwatch // snippet-start:[cloudwatch.kotlin.put_rule.import] import aws.sdk.kotlin.services.cloudwatchevents.CloudWatchEventsClient import aws.sdk.kotlin.services.cloudwatchevents.model.PutRuleRequest import aws.sdk.kotlin.services.cloudwatchevents.model.RuleState import kotlin.system.exitProcess // snippet-end:[cloudwatch.kotlin.put_rule.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <ruleName> <roleArn> Where: ruleName - A rule name (for example, myrule). roleArn - A role ARN value (for example, arn:aws:iam::xxxxxx047983:user/MyUser). """ if (args.size != 2) { println(usage) exitProcess(0) } val ruleName = args[0] val roleArn = args[1] putCWRule(ruleName, roleArn) } // snippet-start:[cloudwatch.kotlin.put_rule.main] suspend fun putCWRule(ruleNameVal: String, roleArnVal: String) { val request = PutRuleRequest { name = ruleNameVal roleArn = roleArnVal scheduleExpression = "rate(5 minutes)" state = RuleState.Enabled } CloudWatchEventsClient { region = "us-east-1" }.use { cwe -> val response = cwe.putRule(request) println("Successfully created CloudWatch events ${roleArnVal}rule with ARN ${response.ruleArn}") } } // snippet-end:[cloudwatch.kotlin.put_rule.main]
apache-2.0
79be1c5ba299e0e2c006f0232f8660b5
29.650794
109
0.690572
3.734082
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/translate/src/main/kotlin/com/kotlin/translate/BatchTranslation.kt
1
3771
// snippet-sourcedescription:[BatchTranslation.kt demonstrates how to translate multiple text documents located in an Amazon S3 bucket.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Amazon Translate] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.translate // snippet-start:[translate.kotlin._batch.import] import aws.sdk.kotlin.services.translate.TranslateClient import aws.sdk.kotlin.services.translate.model.DescribeTextTranslationJobRequest import aws.sdk.kotlin.services.translate.model.InputDataConfig import aws.sdk.kotlin.services.translate.model.OutputDataConfig import aws.sdk.kotlin.services.translate.model.StartTextTranslationJobRequest import kotlinx.coroutines.delay import kotlin.system.exitProcess // snippet-end:[translate.kotlin._batch.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <s3Uri> <s3UriOut> <jobName> <dataAccessRoleArn> Where: s3Uri - The URI of the Amazon S3 bucket where the documents to translate are located. s3UriOut - The URI of the Amazon S3 bucket where the translated documents are saved to. jobName - The job name. dataAccessRoleArn - The Amazon Resource Name (ARN) value of the role required for translation jobs. """ if (args.size != 4) { println(usage) exitProcess(0) } val s3Uri = args[0] val s3UriOut = args[1] val jobName = args[2] val dataAccessRoleArn = args[3] translateDocuments(s3Uri, s3UriOut, jobName, dataAccessRoleArn) } // snippet-start:[translate.kotlin._batch.main] suspend fun translateDocuments( s3UriVal: String?, s3UriOutVal: String?, jobNameVal: String?, dataAccessRoleArnVal: String? ): String? { val sleepTime: Long = 5 val dataConfig = InputDataConfig { s3Uri = s3UriVal contentType = "text/plain" } val outputDataConfigVal = OutputDataConfig { s3Uri = s3UriOutVal } val myList = mutableListOf<String>() myList.add("fr") val textTranslationJobRequest = StartTextTranslationJobRequest { jobName = jobNameVal dataAccessRoleArn = dataAccessRoleArnVal inputDataConfig = dataConfig outputDataConfig = outputDataConfigVal sourceLanguageCode = "en" targetLanguageCodes = myList } TranslateClient { region = "us-west-2" }.use { translateClient -> val textTranslationJobResponse = translateClient.startTextTranslationJob(textTranslationJobRequest) // Keep checking until job is done. val jobDone = false var jobStatus: String val jobIdVal: String? = textTranslationJobResponse.jobId val jobRequest = DescribeTextTranslationJobRequest { jobId = jobIdVal } while (!jobDone) { // Check status on each loop. val response = translateClient.describeTextTranslationJob(jobRequest) jobStatus = response.textTranslationJobProperties?.jobStatus.toString() println(jobStatus) if (jobStatus.contains("COMPLETED")) break else { print(".") delay(sleepTime * 1000) } } return textTranslationJobResponse.jobId } } // snippet-end:[translate.kotlin._batch.main]
apache-2.0
e6abc5caa275fc1d2438441c28d6dcca
31.078947
136
0.67197
4.324541
false
true
false
false
lisuperhong/ModularityApp
KaiyanModule/src/main/java/com/lisuperhong/openeye/ui/fragment/follow/AuthorFragment.kt
1
2730
package com.lisuperhong.openeye.ui.fragment.follow import android.support.v7.widget.LinearLayoutManager import android.widget.Toast import com.company.commonbusiness.base.fragment.BaseMvpFragment import com.lisuperhong.openeye.R import com.lisuperhong.openeye.mvp.contract.AuthorContract import com.lisuperhong.openeye.mvp.model.bean.BaseBean import com.lisuperhong.openeye.mvp.presenter.AuthorPresenter import com.lisuperhong.openeye.ui.adapter.MultiItemAdapter import com.scwang.smartrefresh.layout.header.ClassicsHeader import kotlinx.android.synthetic.main.fragment_author.* /** * Author: lizhaohong * Time: Create on 2018/10/17 15:01 * Desc: 全部作者 */ class AuthorFragment : BaseMvpFragment<AuthorPresenter>(), AuthorContract.View { private var multiItemAdapter: MultiItemAdapter? = null private var isRefresh = false private var nextPageUrl: String? = null override val layoutId: Int get() = R.layout.fragment_author override fun setPresenter() { presenter = AuthorPresenter(this) } override fun initView() { refreshLayout.setRefreshHeader(ClassicsHeader(activity)) refreshLayout.setEnableAutoLoadMore(true) refreshLayout.setOnRefreshListener { isRefresh = true initData() } refreshLayout.setOnLoadMoreListener { isRefresh = false if (nextPageUrl != null) { presenter?.followLoadMore(nextPageUrl!!) } else { refreshLayout.setEnableLoadMore(false) } } multiItemAdapter = MultiItemAdapter(getContext()!!, ArrayList<BaseBean.Item>()) authorRecycleView.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false) authorRecycleView.adapter = multiItemAdapter isRefresh = false showLoading() } override fun initData() { presenter?.allAuthors() } override fun showContent(baseBean: BaseBean) { stopRefresh() if (baseBean.itemList.isEmpty()) return nextPageUrl = baseBean.nextPageUrl if (isRefresh) { multiItemAdapter?.setRefreshData(baseBean.itemList) } else { multiItemAdapter?.setLoadMore(baseBean.itemList) } } override fun showLoading() { loadingProgressBar.show() } override fun hideLoading() { loadingProgressBar.hide() } override fun showMessage(message: String) { stopRefresh() Toast.makeText(activity, message, Toast.LENGTH_LONG).show() } private fun stopRefresh() { refreshLayout.finishRefresh() refreshLayout.finishLoadMore() } }
apache-2.0
e603d2544bd99a150085b8c75417f762
29.255556
87
0.676708
4.931159
false
false
false
false
vladmm/intellij-community
platform/configuration-store-impl/src/SchemeManagerImpl.kt
3
29181
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.Disposable import com.intellij.openapi.application.AccessToken import com.intellij.openapi.application.WriteAction import com.intellij.openapi.application.ex.DecodeDefaultsUtil import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil.DEFAULT_EXT import com.intellij.openapi.components.service import com.intellij.openapi.extensions.AbstractExtensionPointBean import com.intellij.openapi.options.* import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.Condition import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtilRt import com.intellij.openapi.vfs.* import com.intellij.openapi.vfs.newvfs.NewVirtualFile import com.intellij.openapi.vfs.tracker.VirtualFileTracker import com.intellij.util.PathUtil import com.intellij.util.PathUtilRt import com.intellij.util.SmartList import com.intellij.util.ThrowableConvertor import com.intellij.util.containers.ContainerUtil import com.intellij.util.io.URLUtil import com.intellij.util.text.UniqueNameGenerator import gnu.trove.THashMap import gnu.trove.THashSet import gnu.trove.TObjectObjectProcedure import gnu.trove.TObjectProcedure import org.jdom.Document import org.jdom.Element import java.io.File import java.io.IOException import java.io.InputStream import java.util.* public class SchemeManagerImpl<T : Scheme, E>(private val fileSpec: String, private val processor: SchemeProcessor<E>, private val provider: StreamProvider?, private val ioDirectory: File, private val roamingType: RoamingType = RoamingType.DEFAULT, virtualFileTrackerDisposable: Disposable? = null) : SchemesManager<T, E>(), SafeWriteRequestor where E : ExternalizableScheme, E : T { private val schemes = ArrayList<T>() private val readOnlyExternalizableSchemes = THashMap<String, E>() /** * Schemes can be lazy loaded, so, client should be able to set current scheme by name, not only by instance. */ private @Volatile var currentPendingSchemeName: String? = null private var currentScheme: T? = null private var directory: VirtualFile? = null private val schemeExtension: String private val updateExtension: Boolean private val filesToDelete = THashSet<String>() // scheme could be changed - so, hashcode will be changed - we must use identity hashing strategy private val schemeToInfo = THashMap<E, ExternalInfo>(ContainerUtil.identityStrategy()) private val useVfs = virtualFileTrackerDisposable != null init { if (processor is SchemeExtensionProvider) { schemeExtension = processor.schemeExtension updateExtension = processor.isUpgradeNeeded } else { schemeExtension = FileStorageCoreUtil.DEFAULT_EXT updateExtension = false } if (useVfs && (provider == null || !provider.enabled)) { try { refreshVirtualDirectoryAndAddListener(virtualFileTrackerDisposable) } catch (e: Throwable) { LOG.error(e) } } } private fun refreshVirtualDirectoryAndAddListener(virtualFileTrackerDisposable: Disposable?) { // store refreshes root directory, so, we don't need to use refreshAndFindFile val directory = LocalFileSystem.getInstance().findFileByIoFile(ioDirectory) ?: return this.directory = directory directory.children if (directory is NewVirtualFile) { directory.markDirty() } directory.refresh(true, false, { addVfsListener(virtualFileTrackerDisposable) }) } private fun addVfsListener(virtualFileTrackerDisposable: Disposable?) { service<VirtualFileTracker>().addTracker("${LocalFileSystem.PROTOCOL_PREFIX}${ioDirectory.absolutePath.replace(File.separatorChar, '/')}", object : VirtualFileAdapter() { override fun contentsChanged(event: VirtualFileEvent) { if (event.requestor != null || !isMy(event)) { return } val oldScheme = findExternalizableSchemeByFileName(event.file.name) var oldCurrentScheme: T? = null if (oldScheme != null) { oldCurrentScheme = currentScheme removeScheme(oldScheme) processor.onSchemeDeleted(oldScheme) } val newScheme = readSchemeFromFile(event.file, false) if (newScheme != null) { processor.initScheme(newScheme) processor.onSchemeAdded(newScheme) updateCurrentScheme(oldCurrentScheme, newScheme) } } private fun updateCurrentScheme(oldCurrentScheme: T?, newCurrentScheme: E? = null) { if (oldCurrentScheme != currentScheme && currentScheme == null) { setCurrent(newCurrentScheme ?: schemes.firstOrNull()) } } override fun fileCreated(event: VirtualFileEvent) { if (event.requestor != null) { return } if (event.file.isDirectory) { val dir = getDirectory() if (event.file == dir) { for (file in dir.children) { if (isMy(file)) { schemeCreatedExternally(file) } } } } else if (isMy(event)) { schemeCreatedExternally(event.file) } } private fun schemeCreatedExternally(file: VirtualFile) { val readScheme = readSchemeFromFile(file, false) if (readScheme != null) { processor.initScheme(readScheme) processor.onSchemeAdded(readScheme) } } override fun fileDeleted(event: VirtualFileEvent) { if (event.requestor != null) { return } var oldCurrentScheme = currentScheme if (event.file.isDirectory) { val dir = directory if (event.file == dir) { directory = null removeExternalizableSchemes() } } else if (isMy(event)) { val scheme = findExternalizableSchemeByFileName(event.file.name) ?: return removeScheme(scheme) processor.onSchemeDeleted(scheme) } updateCurrentScheme(oldCurrentScheme) } }, false, virtualFileTrackerDisposable!!) } override fun loadBundledScheme(resourceName: String, requestor: Any, convertor: ThrowableConvertor<Element, T, Throwable>) { try { val url = if (requestor is AbstractExtensionPointBean) requestor.loaderForClass.getResource(resourceName) else DecodeDefaultsUtil.getDefaults(requestor, resourceName) if (url == null) { LOG.error("Cannot read scheme from $resourceName") return } val element = JDOMUtil.load(URLUtil.openStream(url)) val scheme = convertor.convert(element) if (scheme is ExternalizableScheme) { val fileName = PathUtilRt.getFileName(url.path) val extension = getFileExtension(fileName, true) val info = ExternalInfo(fileName.substring(0, fileName.length - extension.length), extension) info.hash = JDOMUtil.getTreeHash(element, true) info.schemeName = scheme.name val oldInfo = schemeToInfo.put(scheme.asExternalizable(), info) LOG.assertTrue(oldInfo == null) val oldScheme = readOnlyExternalizableSchemes.put(scheme.name, scheme.asExternalizable()) if (oldScheme != null) { LOG.warn("Duplicated scheme ${scheme.name} - old: $oldScheme, new $scheme") } } schemes.add(scheme) } catch (e: Throwable) { LOG.error("Cannot read scheme from $resourceName", e) } } private fun getFileExtension(fileName: CharSequence, allowAny: Boolean): String { return if (StringUtilRt.endsWithIgnoreCase(fileName, schemeExtension)) { schemeExtension } else if (StringUtilRt.endsWithIgnoreCase(fileName, DEFAULT_EXT)) { DEFAULT_EXT } else if (allowAny) { PathUtil.getFileExtension(fileName.toString())!! } else { throw IllegalStateException("Scheme file extension $fileName is unknown, must be filtered out") } } private fun isMy(event: VirtualFileEvent) = isMy(event.file) private fun isMy(file: VirtualFile) = StringUtilRt.endsWithIgnoreCase(file.nameSequence, schemeExtension) override fun loadSchemes(): Collection<E> { val newSchemesOffset = schemes.size if (provider != null && provider.enabled) { provider.processChildren(fileSpec, roamingType, { canRead(it) }) { name, input, readOnly -> val scheme = loadScheme(name, input, true) if (readOnly && scheme != null) { readOnlyExternalizableSchemes.put(scheme.name, scheme) } true } } else { ioDirectory.listFiles({ parent, name -> canRead(name) })?.let { for (file in it) { if (file.isDirectory) { continue } try { loadScheme(file.name, file.inputStream(), true) } catch (e: Throwable) { LOG.error("Cannot read scheme ${file.path}", e) } } } } val list = SmartList<E>() for (i in newSchemesOffset..schemes.size - 1) { val scheme = (schemes[i] as ExternalizableScheme).asExternalizable() processor.initScheme(scheme) list.add(scheme) processPendingCurrentSchemeName(scheme) } return list } public fun reload() { // we must not remove non-persistent (e.g. predefined) schemes, because we cannot load it (obviously) removeExternalizableSchemes() loadSchemes() } private fun removeExternalizableSchemes() { // todo check is bundled/read-only schemes correctly handled for (i in schemes.indices.reversed()) { val scheme = schemes[i] if (scheme is ExternalizableScheme && getState(scheme.asExternalizable()) != SchemeProcessor.State.NON_PERSISTENT) { if (scheme == currentScheme) { currentScheme = null } processor.onSchemeDeleted(scheme.asExternalizable()) } } retainExternalInfo(schemes) } private fun findExternalizableSchemeByFileName(fileName: String): E? { for (scheme in schemes) { if (scheme is ExternalizableScheme && fileName == "${scheme.fileName}$schemeExtension") { return scheme.asExternalizable() } } return null } private fun isOverwriteOnLoad(existingScheme: E): Boolean { if (readOnlyExternalizableSchemes[existingScheme.name] === existingScheme) { // so, bundled scheme is shadowed return true } val info = schemeToInfo[existingScheme] // scheme from file with old extension, so, we must ignore it return info != null && schemeExtension != info.fileExtension } private fun loadScheme(fileName: CharSequence, input: InputStream, duringLoad: Boolean): E? { try { val element = JDOMUtil.load(input) @Suppress("DEPRECATED_SYMBOL_WITH_MESSAGE") val scheme = processor.readScheme(element, duringLoad) ?: return null val extension = getFileExtension(fileName, false) val fileNameWithoutExtension = fileName.subSequence(0, fileName.length - extension.length).toString() if (duringLoad) { if (filesToDelete.isNotEmpty() && filesToDelete.contains(fileName.toString())) { LOG.warn("Scheme file \"$fileName\" is not loaded because marked to delete") return null } val existingScheme = findSchemeByName(scheme.name) if (existingScheme != null) { val existingSchemeAsExternalizable = if (existingScheme is ExternalizableScheme) existingScheme.asExternalizable() else null if (existingSchemeAsExternalizable != null && isOverwriteOnLoad(existingSchemeAsExternalizable)) { removeScheme(existingScheme) } else { if (schemeExtension != extension && existingSchemeAsExternalizable != null && schemeToInfo[existingSchemeAsExternalizable]?.fileNameWithoutExtension == fileNameWithoutExtension) { // 1.oldExt is loading after 1.newExt - we should delete 1.oldExt filesToDelete.add(fileName.toString()) } else { // We don't load scheme with duplicated name - if we generate unique name for it, it will be saved then with new name. // It is not what all can expect. Such situation in most cases indicates error on previous level, so, we just warn about it. LOG.warn("Scheme file \"$fileName\" is not loaded because defines duplicated name \"${scheme.name}\"") } return null } } } var info: ExternalInfo? = schemeToInfo[scheme] if (info == null) { info = ExternalInfo(fileNameWithoutExtension, extension) schemeToInfo.put(scheme, info) } else { info.setFileNameWithoutExtension(fileNameWithoutExtension, extension) } info.hash = JDOMUtil.getTreeHash(element, true) info.schemeName = scheme.name if (duringLoad) { schemes.add(scheme) } else { addScheme(scheme) } return scheme } catch (e: Throwable) { LOG.error("Cannot read scheme $fileName", e) return null } } private val ExternalizableScheme.fileName: String? get() = schemeToInfo[asExternalizable()]?.fileNameWithoutExtension private fun canRead(name: CharSequence) = updateExtension && StringUtilRt.endsWithIgnoreCase(name, DEFAULT_EXT) || StringUtilRt.endsWithIgnoreCase(name, schemeExtension) private fun readSchemeFromFile(file: VirtualFile, duringLoad: Boolean): E? { val fileName = file.nameSequence if (file.isDirectory || !canRead(fileName)) { return null } try { return loadScheme(fileName, file.inputStream, duringLoad) } catch (e: Throwable) { LOG.error("Cannot read scheme $fileName", e) return null } } fun save(errors: MutableList<Throwable>) { var hasSchemes = false val nameGenerator = UniqueNameGenerator() val schemesToSave = SmartList<E>() for (scheme in schemes) { @Suppress("UNCHECKED_CAST") if (scheme is ExternalizableScheme) { val state = getState(scheme as E) if (state == SchemeProcessor.State.NON_PERSISTENT) { continue } hasSchemes = true if (state != SchemeProcessor.State.UNCHANGED) { schemesToSave.add(scheme) } val fileName = scheme.fileName if (fileName != null && !isRenamed(scheme)) { nameGenerator.addExistingName(fileName) } } } for (scheme in schemesToSave) { try { saveScheme(scheme, nameGenerator) } catch (e: Throwable) { errors.add(RuntimeException("Cannot save scheme $fileSpec/$scheme", e)) } } if (!filesToDelete.isEmpty) { deleteFiles(errors) // remove empty directory only if some file was deleted - avoid check on each save if (!hasSchemes && (provider == null || !provider.enabled)) { removeDirectoryIfEmpty(errors) } } } private fun removeDirectoryIfEmpty(errors: MutableList<Throwable>) { ioDirectory.listFiles()?.let { for (file in it) { if (!file.isHidden) { LOG.info("Directory ${ioDirectory.name} is not deleted: at least one file ${file.name} exists") return } } } LOG.info("Remove schemes directory ${ioDirectory.name}") directory = null var deleteUsingIo = !useVfs if (!deleteUsingIo) { val dir = getDirectory() if (dir != null) { val token = WriteAction.start() try { dir.delete(this) } catch (e: Throwable) { deleteUsingIo = true errors.add(e) } finally { token.finish() } } } if (deleteUsingIo) { errors.catch { FileUtil.delete(ioDirectory) } } } private fun getState(scheme: E) = processor.getState(scheme) private fun saveScheme(scheme: E, nameGenerator: UniqueNameGenerator) { var externalInfo: ExternalInfo? = schemeToInfo[scheme] val currentFileNameWithoutExtension = if (externalInfo == null) null else externalInfo.fileNameWithoutExtension val parent = processor.writeScheme(scheme) val element = if (parent == null || parent is Element) parent as Element? else (parent as Document).detachRootElement() if (JDOMUtil.isEmpty(element)) { externalInfo?.scheduleDelete() return } var fileNameWithoutExtension = currentFileNameWithoutExtension if (fileNameWithoutExtension == null || isRenamed(scheme)) { fileNameWithoutExtension = nameGenerator.generateUniqueName(FileUtil.sanitizeFileName(scheme.name, false)) } val newHash = JDOMUtil.getTreeHash(element!!, true) if (externalInfo != null && currentFileNameWithoutExtension === fileNameWithoutExtension && newHash == externalInfo.hash) { return } // save only if scheme differs from bundled val bundledScheme = readOnlyExternalizableSchemes[scheme.name] if (bundledScheme != null && schemeToInfo[bundledScheme]?.hash == newHash) { externalInfo?.scheduleDelete() return } val fileName = fileNameWithoutExtension!! + schemeExtension // file will be overwritten, so, we don't need to delete it filesToDelete.remove(fileName) // stream provider always use LF separator val byteOut = element.toBufferExposingByteArray() var providerPath: String? if (provider != null && provider.enabled) { providerPath = fileSpec + '/' + fileName if (!provider.isApplicable(providerPath, roamingType)) { providerPath = null } } else { providerPath = null } // if another new scheme uses old name of this scheme, so, we must not delete it (as part of rename operation) val renamed = externalInfo != null && fileNameWithoutExtension !== currentFileNameWithoutExtension && nameGenerator.value(currentFileNameWithoutExtension) if (providerPath == null) { if (useVfs) { var file: VirtualFile? = null var dir = getDirectory() if (dir == null || !dir.isValid) { dir = createDir(ioDirectory, this) directory = dir } if (renamed) { file = dir.findChild(externalInfo!!.fileName) if (file != null) { runWriteAction { file!!.rename(this, fileName) } } } if (file == null) { file = getFile(fileName, dir, this) } runWriteAction { file!!.getOutputStream(this).use { byteOut.writeTo(it) } } } else { if (renamed) { externalInfo!!.scheduleDelete() } FileUtil.writeToFile(File(ioDirectory, fileName), byteOut.internalBuffer, 0, byteOut.size()) } } else { if (renamed) { externalInfo!!.scheduleDelete() } provider!!.write(providerPath, byteOut.internalBuffer, byteOut.size(), roamingType) } if (externalInfo == null) { externalInfo = ExternalInfo(fileNameWithoutExtension, schemeExtension) schemeToInfo.put(scheme, externalInfo) } else { externalInfo.setFileNameWithoutExtension(fileNameWithoutExtension, schemeExtension) } externalInfo.hash = newHash externalInfo.schemeName = scheme.name } private fun ExternalInfo.scheduleDelete() { filesToDelete.add(fileName) } private fun isRenamed(scheme: E): Boolean { val info = schemeToInfo[scheme] return info != null && scheme.name != info.schemeName } private fun deleteFiles(errors: MutableList<Throwable>) { val deleteUsingIo: Boolean if (provider != null && provider.enabled) { deleteUsingIo = false for (name in filesToDelete) { errors.catch { val spec = "$fileSpec/$name" if (provider.isApplicable(spec, roamingType)) { provider.delete(spec, roamingType) } } } } else if (!useVfs) { deleteUsingIo = true } else { val dir = getDirectory() deleteUsingIo = dir == null if (!deleteUsingIo) { var token: AccessToken? = null try { for (file in dir!!.children) { if (filesToDelete.contains(file.name)) { if (token == null) { token = WriteAction.start() } errors.catch { file.delete(this) } } } } finally { if (token != null) { token.finish() } } } } if (deleteUsingIo) { for (name in filesToDelete) { errors.catch { FileUtil.delete(File(ioDirectory, name)) } } } filesToDelete.clear() } private fun getDirectory(): VirtualFile? { var result = directory if (result == null) { result = LocalFileSystem.getInstance().findFileByIoFile(ioDirectory) directory = result } return result } override fun getRootDirectory() = ioDirectory override fun setSchemes(newSchemes: List<T>, newCurrentScheme: T?, removeCondition: Condition<T>?) { val oldCurrentScheme = currentScheme if (removeCondition == null) { schemes.clear() } else { for (i in schemes.indices.reversed()) { if (removeCondition.value(schemes[i])) { schemes.removeAt(i) } } } retainExternalInfo(newSchemes) schemes.addAll(newSchemes) if (oldCurrentScheme != newCurrentScheme) { if (newCurrentScheme != null) { currentScheme = newCurrentScheme } else if (oldCurrentScheme != null && !schemes.contains(oldCurrentScheme)) { currentScheme = schemes.firstOrNull() } if (oldCurrentScheme != currentScheme) { processor.onCurrentSchemeChanged(oldCurrentScheme) } } } private fun retainExternalInfo(newSchemes: List<T>) { if (schemeToInfo.isEmpty) { return } schemeToInfo.retainEntries(object : TObjectObjectProcedure<E, ExternalInfo> { override fun execute(scheme: E, info: ExternalInfo): Boolean { if (readOnlyExternalizableSchemes[scheme.name] == scheme) { return true } for (t in newSchemes) { // by identity if (t === scheme) { if (filesToDelete.isNotEmpty()) { filesToDelete.remove("${info.fileName}") } return true } } info.scheduleDelete() return false } }) } override fun addNewScheme(scheme: T, replaceExisting: Boolean) { var toReplace = -1 for (i in schemes.indices) { val existing = schemes[i] if (existing.name == scheme.name) { if (!Comparing.equal<Class<out Scheme>>(existing.javaClass, scheme.javaClass)) { LOG.warn("'${scheme.name}' ${existing.javaClass.simpleName} replaced with ${scheme.javaClass.simpleName}") } toReplace = i if (replaceExisting && existing is ExternalizableScheme) { val oldInfo = schemeToInfo.remove(existing.asExternalizable()) if (oldInfo != null && scheme is ExternalizableScheme && !schemeToInfo.containsKey(scheme.asExternalizable())) { schemeToInfo.put(scheme.asExternalizable(), oldInfo) } } break } } if (toReplace == -1) { schemes.add(scheme) } else if (replaceExisting || scheme !is ExternalizableScheme) { schemes.set(toReplace, scheme) } else { scheme.renameScheme(UniqueNameGenerator.generateUniqueName(scheme.name, collectExistingNames(schemes))) schemes.add(scheme) } if (scheme is ExternalizableScheme && filesToDelete.isNotEmpty()) { val info = schemeToInfo[scheme.asExternalizable()] if (info != null) { filesToDelete.remove(info.fileName) } } processPendingCurrentSchemeName(scheme) } private fun collectExistingNames(schemes: Collection<T>): Collection<String> { val result = THashSet<String>(schemes.size) for (scheme in schemes) { result.add(scheme.name) } return result } override fun clearAllSchemes() { schemeToInfo.forEachValue(object : TObjectProcedure<ExternalInfo> { override fun execute(info: ExternalInfo): Boolean { info.scheduleDelete() return true } }) currentScheme = null schemes.clear() schemeToInfo.clear() } override fun getAllSchemes() = Collections.unmodifiableList(schemes) override fun findSchemeByName(schemeName: String): T? { for (scheme in schemes) { if (scheme.name == schemeName) { return scheme } } return null } override fun setCurrent(scheme: T?, notify: Boolean) { currentPendingSchemeName = null val oldCurrent = currentScheme currentScheme = scheme if (notify && oldCurrent != scheme) { processor.onCurrentSchemeChanged(oldCurrent) } } override fun setCurrentSchemeName(schemeName: String?, notify: Boolean) { currentPendingSchemeName = schemeName val scheme = if (schemeName == null) null else findSchemeByName(schemeName) // don't set current scheme if no scheme by name - pending resolution (see currentSchemeName field comment) if (scheme != null || schemeName == null) { setCurrent(scheme, notify) } } override fun getCurrentScheme() = currentScheme override fun getCurrentSchemeName() = currentScheme?.name ?: currentPendingSchemeName private fun processPendingCurrentSchemeName(newScheme: T) { if (newScheme.name == currentPendingSchemeName) { setCurrent(newScheme, false) } } override fun removeScheme(scheme: T) { for (i in schemes.size - 1 downTo 0) { val s = schemes[i] if (scheme.name == s.name) { if (currentScheme == s) { currentScheme = null } if (s is ExternalizableScheme) { schemeToInfo.remove(s.asExternalizable())?.scheduleDelete() } schemes.removeAt(i) break } } } @Suppress("UNCHECKED_CAST", "NOTHING_TO_INLINE") private inline fun ExternalizableScheme.asExternalizable() = this as E override fun getAllSchemeNames(): Collection<String> { if (schemes.isEmpty()) { return emptyList() } val names = ArrayList<String>(schemes.size) for (scheme in schemes) { names.add(scheme.name) } return names } override fun isMetadataEditable(scheme: E) = !readOnlyExternalizableSchemes.containsKey(scheme.name) private class ExternalInfo(var fileNameWithoutExtension: String, var fileExtension: String?) { // we keep it to detect rename var schemeName: String? = null var hash = 0 val fileName: String get() = "$fileNameWithoutExtension$fileExtension" fun setFileNameWithoutExtension(nameWithoutExtension: String, extension: String) { fileNameWithoutExtension = nameWithoutExtension fileExtension = extension } override fun toString() = fileName } override fun toString() = fileSpec } private fun ExternalizableScheme.renameScheme(newName: String) { if (newName != name) { name = newName LOG.assertTrue(newName == name) } } private inline fun MutableList<Throwable>.catch(runnable: () -> Unit) { try { runnable() } catch (e: Throwable) { add(e) } } fun createDir(ioDir: File, requestor: Any): VirtualFile { ioDir.mkdirs() val parentFile = ioDir.getParent() val parentVirtualFile = (if (parentFile == null) null else VfsUtil.createDirectoryIfMissing(parentFile)) ?: throw IOException(ProjectBundle.message("project.configuration.save.file.not.found", parentFile)) return getFile(ioDir.name, parentVirtualFile, requestor) } fun getFile(fileName: String, parent: VirtualFile, requestor: Any): VirtualFile { val file = parent.findChild(fileName) if (file != null) { return file } return runWriteAction { parent.createChildData(requestor, fileName) } }
apache-2.0
4dc527f92aa0c20f91409cd561e8e687
31.10341
207
0.650492
4.770476
false
false
false
false
paplorinc/intellij-community
python/src/com/jetbrains/python/codeInsight/stdlib/PyOverridingClassDunderMembersProvider.kt
1
3502
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.codeInsight.stdlib import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.ResolveState import com.intellij.psi.scope.PsiScopeProcessor import com.jetbrains.python.PyNames import com.jetbrains.python.codeInsight.PyCustomMember import com.jetbrains.python.psi.AccessDirection import com.jetbrains.python.psi.PyExpression import com.jetbrains.python.psi.PyUtil import com.jetbrains.python.psi.impl.PyBuiltinCache import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.types.PyClassMembersProviderBase import com.jetbrains.python.psi.types.PyClassType import com.jetbrains.python.psi.types.PyOverridingClassMembersProvider import com.jetbrains.python.psi.types.TypeEvalContext class PyOverridingClassDunderMembersProvider : PyClassMembersProviderBase(), PyOverridingClassMembersProvider { override fun getMembers(clazz: PyClassType, location: PsiElement?, context: TypeEvalContext): Collection<PyCustomMember> { if (PyUtil.isObjectClass(clazz.pyClass)) return emptyList() val pyLocation = location as? PyExpression val direction = if (pyLocation != null && context.maySwitchToAST(location)) AccessDirection.of(pyLocation) else AccessDirection.READ val result = mutableListOf<PyCustomMember>() if (clazz.isDefinition && clazz.pyClass.isNewStyleClass(context) || /* override */ !clazz.isDefinition && !clazz.pyClass.isNewStyleClass(context) /* provide */) { result.addAll(resolveInObject(clazz, PyNames.__CLASS__, pyLocation, direction, context)) } val (overridesDoc, overridesModule) = overridesDocOrModule(clazz, location) if (!overridesDoc) result.addAll(resolveInObject(clazz, PyNames.DOC, pyLocation, direction, context)) if (!overridesModule) result.addAll(resolveInObject(clazz, "__module__", pyLocation, direction, context)) return result } private fun resolveInObject(type: PyClassType, name: String, location: PyExpression?, direction: AccessDirection, context: TypeEvalContext): List<PyCustomMember> { val objectType = PyBuiltinCache.getInstance(type.pyClass).objectType ?: return emptyList() val resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context) val results = objectType.resolveMember(name, location, direction, resolveContext) ?: return emptyList() return results.asSequence().mapNotNull { it.element }.map { PyCustomMember(name, it) }.toList() } private fun overridesDocOrModule(type: PyClassType, location: PsiElement?): Pair<Boolean, Boolean> { val cls = type.pyClass var overridesDoc = false var overridesModule = false val processor = object : PsiScopeProcessor { override fun execute(element: PsiElement, state: ResolveState): Boolean { if (element is PsiNamedElement) { when (element.name) { PyNames.DOC -> overridesDoc = true "__module__" -> overridesModule = true } } return !overridesDoc || !overridesModule } } cls.processClassLevelDeclarations(processor) if (!type.isDefinition) cls.processInstanceLevelDeclarations(processor, location) return overridesDoc to overridesModule } }
apache-2.0
b806c65168154e74680e5006d6292985
44.493506
140
0.737579
4.719677
false
false
false
false
google/intellij-community
plugins/kotlin/code-insight/impl-base/src/org/jetbrains/kotlin/idea/codeinsights/impl/base/applicators/ApplicabilityRanges.kt
3
2537
// 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.codeinsights.impl.base.applicators import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.tree.TokenSet import org.jetbrains.kotlin.idea.codeinsight.api.applicators.applicabilityRange import org.jetbrains.kotlin.idea.codeinsight.api.applicators.applicabilityRanges import org.jetbrains.kotlin.idea.codeinsight.api.applicators.applicabilityTarget import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* object ApplicabilityRanges { val SELF = applicabilityTarget<PsiElement> { it } val CALLABLE_RETURN_TYPE = applicabilityTarget<KtCallableDeclaration> { decalration -> decalration.typeReference?.typeElement } val VISIBILITY_MODIFIER = modifier(KtTokens.VISIBILITY_MODIFIERS) private fun modifier(tokens: TokenSet) = applicabilityTarget<KtModifierListOwner> { declaration -> declaration.modifierList?.getModifier(tokens) } val VALUE_ARGUMENT_EXCLUDING_LAMBDA = applicabilityRanges<KtValueArgument> { element -> val expression = element.getArgumentExpression() ?: return@applicabilityRanges emptyList() if (expression is KtLambdaExpression) { // Use OUTSIDE of curly braces only as applicability ranges for lambda. // If we use the text range of the curly brace elements, it will include the inside of the braces. // This matches FE 1.0 behavior (see AddNameToArgumentIntention). listOfNotNull(TextRange(0, 0), TextRange(element.textLength, element.textLength)) } else { listOf(TextRange(0, element.textLength)) } } val DECLARATION_WITHOUT_INITIALIZER = applicabilityRange<KtCallableDeclaration> { val selfRange = TextRange(0, it.textLength) if (it !is KtDeclarationWithInitializer) return@applicabilityRange selfRange val initializer = it.initializer ?: return@applicabilityRange selfRange // The IDE seems to treat the end offset inclusively when checking if the caret is within the range. Hence we do minus one here // so that the intention is available from the following highlighted range. // val i = 1 // ^^^^^^^^ TextRange(0, initializer.startOffsetInParent - 1) } val DECLARATION_NAME = applicabilityTarget<KtNamedDeclaration> { element -> element.nameIdentifier } }
apache-2.0
6e2c2641a89edb1fcafa2fe7ac69317a
46.886792
135
0.735909
4.935798
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SampleEntity2Impl.kt
1
7266
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class SampleEntity2Impl(val dataSource: SampleEntity2Data) : SampleEntity2, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override val data: String get() = dataSource.data override val boolData: Boolean get() = dataSource.boolData override val optionalData: String? get() = dataSource.optionalData override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: SampleEntity2Data?) : ModifiableWorkspaceEntityBase<SampleEntity2>(), SampleEntity2.Builder { constructor() : this(SampleEntity2Data()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity SampleEntity2 is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isDataInitialized()) { error("Field SampleEntity2#data should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as SampleEntity2 this.entitySource = dataSource.entitySource this.data = dataSource.data this.boolData = dataSource.boolData this.optionalData = dataSource.optionalData if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData().data = value changedProperty.add("data") } override var boolData: Boolean get() = getEntityData().boolData set(value) { checkModificationAllowed() getEntityData().boolData = value changedProperty.add("boolData") } override var optionalData: String? get() = getEntityData().optionalData set(value) { checkModificationAllowed() getEntityData().optionalData = value changedProperty.add("optionalData") } override fun getEntityData(): SampleEntity2Data = result ?: super.getEntityData() as SampleEntity2Data override fun getEntityClass(): Class<SampleEntity2> = SampleEntity2::class.java } } class SampleEntity2Data : WorkspaceEntityData<SampleEntity2>() { lateinit var data: String var boolData: Boolean = false var optionalData: String? = null fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<SampleEntity2> { val modifiable = SampleEntity2Impl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): SampleEntity2 { return getCached(snapshot) { val entity = SampleEntity2Impl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return SampleEntity2::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return SampleEntity2(data, boolData, entitySource) { this.optionalData = [email protected] } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as SampleEntity2Data if (this.entitySource != other.entitySource) return false if (this.data != other.data) return false if (this.boolData != other.boolData) return false if (this.optionalData != other.optionalData) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as SampleEntity2Data if (this.data != other.data) return false if (this.boolData != other.boolData) return false if (this.optionalData != other.optionalData) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() result = 31 * result + boolData.hashCode() result = 31 * result + optionalData.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + data.hashCode() result = 31 * result + boolData.hashCode() result = 31 * result + optionalData.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
66d01bc64bd0787409a41d8d221902dd
31.008811
121
0.720066
5.091801
false
false
false
false
Commit451/Easel
easel/src/main/java/com/commit451/easel/ReflectionUtil.kt
1
1022
package com.commit451.easel import android.graphics.PorterDuff import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import androidx.core.content.ContextCompat import android.widget.TextView import java.lang.reflect.Field /** * Reflection is fun */ internal object ReflectionUtil { fun getField(clazz: Class<*>, fieldName: String): Field { val field = clazz.getDeclaredField(fieldName) field.isAccessible = true return field } fun getEditorField(): Field { val fEditor = TextView::class.java.getDeclaredField("mEditor") fEditor.isAccessible = true return fEditor } fun setDrawable(textView: TextView, editor: Any, field: Field, @ColorInt color: Int, @DrawableRes drawableRes: Int) { val drawable = ContextCompat.getDrawable(textView.context, drawableRes) ?.mutate() drawable?.setColorFilter(color, PorterDuff.Mode.SRC_IN) field.set(editor, drawable) } }
apache-2.0
9b76029f875f7d5138540141d6661437
29.058824
88
0.684932
4.688073
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/formatter/KotlinPreFormatProcessor.kt
1
2865
// 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.formatter import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.codeStyle.PreFormatProcessor import com.intellij.psi.tree.IElementType import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.nextSiblingOfSameType import org.jetbrains.kotlin.utils.addToStdlib.lastIsInstanceOrNull private class Visitor(var range: TextRange) : KtTreeVisitorVoid() { override fun visitNamedDeclaration(declaration: KtNamedDeclaration) { fun PsiElement.containsToken(type: IElementType) = allChildren.any { it.node.elementType == type } if (!range.contains(declaration.textRange)) return val classBody = declaration.parent as? KtClassBody ?: return val klass = classBody.parent as? KtClass ?: return if (!klass.isEnum()) return var delta = 0 val psiFactory = KtPsiFactory(klass.project) if (declaration is KtEnumEntry) { val comma = psiFactory.createComma() val nextEntry = declaration.nextSiblingOfSameType() if (nextEntry != null && !declaration.containsToken(KtTokens.COMMA)) { declaration.add(comma) delta += comma.textLength } } else { val lastEntry = klass.declarations.lastIsInstanceOrNull<KtEnumEntry>() if (lastEntry != null && (lastEntry.containsToken(KtTokens.SEMICOLON) || lastEntry.nextSibling?.node?.elementType == KtTokens.SEMICOLON) ) return if (lastEntry == null && classBody.containsToken(KtTokens.SEMICOLON)) return val semicolon = psiFactory.createSemicolon() delta += if (lastEntry != null) { classBody.addAfter(semicolon, lastEntry) semicolon.textLength } else { val newLine = psiFactory.createNewLine() classBody.addAfter(semicolon, classBody.lBrace) classBody.addAfter(psiFactory.createNewLine(), classBody.lBrace) semicolon.textLength + newLine.textLength } } range = TextRange(range.startOffset, range.endOffset + delta) } } class KotlinPreFormatProcessor : PreFormatProcessor { override fun process(element: ASTNode, range: TextRange): TextRange { val psi = element.psi ?: return range if (!psi.isValid) return range if (psi.containingFile !is KtFile) return range return Visitor(range).apply { psi.accept(this) }.range } }
apache-2.0
e1b0cd7c0696f67174bc93c87b4c5c1e
41.761194
158
0.677836
4.92268
false
false
false
false
envoyproxy/envoy-mobile
test/kotlin/integration/TestStatsdServer.kt
2
1921
package test.kotlin.integration import java.io.IOException import java.net.DatagramPacket import java.net.DatagramSocket import java.net.SocketTimeoutException import java.util.concurrent.CountDownLatch import java.util.concurrent.atomic.AtomicReference class TestStatsdServer { private val shutdownLatch: CountDownLatch = CountDownLatch(1) private val awaitNextStat: AtomicReference<CountDownLatch> = AtomicReference(CountDownLatch(0)) private val matchCriteria: AtomicReference<(String) -> Boolean> = AtomicReference() private var thread: Thread? = null @Throws(IOException::class) fun runAsync(port: Int) { val socket = DatagramSocket(port) socket.setSoTimeout(1000) // 1 second thread = Thread( fun() { val buffer = ByteArray(256) while (shutdownLatch.getCount() != 0L) { val packet = DatagramPacket(buffer, buffer.size) try { socket.receive(packet) } catch (e: SocketTimeoutException) { // continue to next loop continue } catch (e: Exception) { // TODO(snowp): Bubble up this error somehow. return } // TODO(snowp): Parse (or use a parser) so we can extract out individual metric names // better. val received = String(packet.getData(), packet.getOffset(), packet.getLength()) val maybeMatch = matchCriteria.get() if (maybeMatch != null && maybeMatch.invoke(received)) { matchCriteria.set(null) awaitNextStat.get().countDown() } } } ) thread!!.start() } fun awaitStatMatching(predicate: (String) -> Boolean) { val latch = CountDownLatch(1) awaitNextStat.set(latch) matchCriteria.set(predicate) latch.await() } @Throws(InterruptedException::class) fun shutdown() { shutdownLatch.countDown() thread?.join() } }
apache-2.0
cf4bacd17a61b8d731141ab2c0082379
29.492063
97
0.650182
4.488318
false
false
false
false
allotria/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/util/RepeatUtils.kt
4
1011
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testGuiFramework.util import org.fest.swing.exception.WaitTimedOutError /* Wait for @condition during @timeOutSeconds */ inline fun waitFor(timeOutSeconds: Int = 5, intervalMillis: Long = 500, crossinline condition: () -> Boolean) { val endTime = System.currentTimeMillis() + timeOutSeconds * 1000 while (System.currentTimeMillis() < endTime) { if (condition()) { return } else { Thread.sleep(intervalMillis) } } throw WaitTimedOutError("Failed to wait for condition in $timeOutSeconds seconds") } fun attempt(times: Int, func: () -> Unit) { var exception: Exception? = null for (i in 0 until times) { try { return func() } catch (e: Exception) { if (exception == null) { exception = e } else { exception.addSuppressed(e) } } } throw exception!! }
apache-2.0
2bff90d2087486cf37c27c975c32ac05
27.111111
140
0.663699
4.093117
false
false
false
false
romannurik/muzei
main/src/main/java/com/google/android/apps/muzei/settings/Prefs.kt
2
6573
/* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei.settings import android.content.Context import android.content.SharedPreferences import androidx.core.content.ContextCompat import androidx.core.content.edit import androidx.core.os.UserManagerCompat import androidx.preference.PreferenceManager /** * Preference constants/helpers. */ object Prefs { const val PREF_DOUBLE_TAP = "double_tap" const val PREF_THREE_FINGER_TAP = "three_finger_tap" const val PREF_TAP_ACTION_TEMP = "temp" const val PREF_TAP_ACTION_NEXT = "next" const val PREF_TAP_ACTION_VIEW_DETAILS = "view_details" const val PREF_TAP_ACTION_NONE = "none" const val PREF_GREY_AMOUNT = "grey_amount" const val PREF_DIM_AMOUNT = "dim_amount" const val PREF_BLUR_AMOUNT = "blur_amount" const val PREF_LOCK_GREY_AMOUNT = "lock_grey_amount" const val PREF_LOCK_DIM_AMOUNT = "lock_dim_amount" const val PREF_LOCK_BLUR_AMOUNT = "lock_blur_amount" const val PREF_LINK_EFFECTS = "link_effects" private const val PREF_DISABLE_BLUR_WHEN_LOCKED = "disable_blur_when_screen_locked_enabled" private const val WALLPAPER_PREFERENCES_NAME = "wallpaper_preferences" private const val PREF_MIGRATED = "migrated_from_default" @Synchronized fun getSharedPreferences(context: Context): SharedPreferences { val deviceProtectedContext = ContextCompat.createDeviceProtectedStorageContext(context) if (UserManagerCompat.isUserUnlocked(context)) { // First migrate the wallpaper settings to their own file val defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) val wallpaperPreferences = context.getSharedPreferences( WALLPAPER_PREFERENCES_NAME, Context.MODE_PRIVATE) migratePreferences(defaultSharedPreferences, wallpaperPreferences) // Now migrate the file to device protected storage if available if (deviceProtectedContext != null) { val deviceProtectedPreferences = deviceProtectedContext.getSharedPreferences( WALLPAPER_PREFERENCES_NAME, Context.MODE_PRIVATE) migratePreferences(wallpaperPreferences, deviceProtectedPreferences) } } // Now open the correct SharedPreferences val contextToUse = deviceProtectedContext ?: context return contextToUse.getSharedPreferences(WALLPAPER_PREFERENCES_NAME, Context.MODE_PRIVATE).also { sp -> if (sp.contains(PREF_DISABLE_BLUR_WHEN_LOCKED)) { sp.edit { val disableBlurWhenLocked = sp.getBoolean( PREF_DISABLE_BLUR_WHEN_LOCKED, false) if (sp.contains(PREF_GREY_AMOUNT)) { val greyAmount = sp.getInt(PREF_GREY_AMOUNT, 0) putInt(PREF_LOCK_GREY_AMOUNT, if (disableBlurWhenLocked) 0 else greyAmount) } else if (disableBlurWhenLocked) { putInt(PREF_LOCK_GREY_AMOUNT, 0) } if (sp.contains(PREF_DIM_AMOUNT)) { val dimAmount = sp.getInt(PREF_DIM_AMOUNT, 0) putInt(PREF_LOCK_DIM_AMOUNT, if (disableBlurWhenLocked) 0 else dimAmount) } else if (disableBlurWhenLocked) { putInt(PREF_LOCK_DIM_AMOUNT, 0) } if (sp.contains(PREF_BLUR_AMOUNT)) { val blurAmount = sp.getInt(PREF_BLUR_AMOUNT, 0) putInt(PREF_LOCK_BLUR_AMOUNT, if (disableBlurWhenLocked) 0 else blurAmount) } else if (disableBlurWhenLocked) { putInt(PREF_LOCK_BLUR_AMOUNT, 0) } remove(PREF_DISABLE_BLUR_WHEN_LOCKED) } } } } private fun migratePreferences(source: SharedPreferences, destination: SharedPreferences) { if (source.getBoolean(PREF_MIGRATED, false)) { return } val sourceEditor = source.edit() val destinationEditor = destination.edit() val disableBlurWhenLocked = source.getBoolean( PREF_DISABLE_BLUR_WHEN_LOCKED, false) sourceEditor.remove(PREF_DISABLE_BLUR_WHEN_LOCKED) if (source.contains(PREF_GREY_AMOUNT)) { val greyAmount = source.getInt(PREF_GREY_AMOUNT, 0) destinationEditor.putInt(PREF_GREY_AMOUNT, greyAmount) destinationEditor.putInt(PREF_LOCK_GREY_AMOUNT, if (disableBlurWhenLocked) 0 else greyAmount) sourceEditor.remove(PREF_GREY_AMOUNT) } else if (disableBlurWhenLocked) { destinationEditor.putInt(PREF_LOCK_GREY_AMOUNT, 0) } if (source.contains(PREF_DIM_AMOUNT)) { val dimAmount = source.getInt(PREF_DIM_AMOUNT, 0) destinationEditor.putInt(PREF_DIM_AMOUNT, dimAmount) destinationEditor.putInt(PREF_LOCK_DIM_AMOUNT, if (disableBlurWhenLocked) 0 else dimAmount) sourceEditor.remove(PREF_DIM_AMOUNT) } else if (disableBlurWhenLocked) { destinationEditor.putInt(PREF_LOCK_DIM_AMOUNT, 0) } if (source.contains(PREF_BLUR_AMOUNT)) { val blurAmount = source.getInt(PREF_BLUR_AMOUNT, 0) destinationEditor.putInt(PREF_BLUR_AMOUNT, blurAmount) destinationEditor.putInt(PREF_LOCK_BLUR_AMOUNT, if (disableBlurWhenLocked) 0 else blurAmount) sourceEditor.remove(PREF_BLUR_AMOUNT) } else if (disableBlurWhenLocked) { destinationEditor.putInt(PREF_LOCK_BLUR_AMOUNT, 0) } sourceEditor.putBoolean(PREF_MIGRATED, true) sourceEditor.apply() destinationEditor.apply() } }
apache-2.0
6a1da296a9ba41509e5b9fcfa5100b3f
45.617021
97
0.631066
4.517526
false
false
false
false
JuliusKunze/kotlin-native
runtime/src/main/kotlin/kotlin/BitSet.kt
2
17286
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kotlin /** * A vector of bits growing if necessary and allowing one to set/clear/read bits from it by a bit index. */ class BitSet(size: Int = ELEMENT_SIZE) { companion object { // Size of one element in the array used to store bits. private const val ELEMENT_SIZE = 64 private const val MAX_BIT_OFFSET = ELEMENT_SIZE - 1 private const val ALL_TRUE = -1L // 0xFFFF_FFFF_FFFF_FFFF private const val ALL_FALSE = 0L // 0x0000_0000_0000_0000 } private var bits: LongArray = LongArray(bitToElementSize(size)) private val lastIndex: Int get() = size - 1 /** Returns an index of the last bit that has `true` value. Returns -1 if the set is empty. */ val lastTrueIndex: Int get() = previousSetBit(size) /** True if this BitSet contains no bits set to true. */ val isEmpty: Boolean get() = bits.all { it == ALL_FALSE } /** Actual number of bits available in the set. All bits with indices >= size assumed to be 0 */ var size: Int = size private set // TODO: Add more constructors. constructor(length: Int, initializer: (Int) -> Boolean): this(length) { for (i in 0 until length) { set(i, initializer(i)) } } // Transforms a bit index into an element index in the `bits` array. private val Int.elementIndex: Int get() = this / ELEMENT_SIZE // Transforms a bit index in the set into a bit in the element of the `bits` array. private val Int.bitOffset: Int get() = this % ELEMENT_SIZE // Transforms a bit index in the set into pair of a `bits` element index and a bit index in the element. private val Int.asBitCoordinates: Pair<Int, Int> get() = Pair(elementIndex, bitOffset) // Transforms a bit offset to the mask with only bit set corresponding to the offset. private val Int.asMask: Long get() = 0x1L shl this // Transforms a bit offset to the mask with only bits before the index (inclusive) set. private val Int.asMaskBefore: Long get() = getMaskBetween(0, this) // Transforms a bit offset to the mask with only bits after the index (inclusive) set. private val Int.asMaskAfter: Long get() = getMaskBetween(this, MAX_BIT_OFFSET) // Builds a masks with 1 between fromOffset and toOffset (both inclusive). private fun getMaskBetween(fromOffset: Int, toOffset: Int): Long { var res = 0L val maskToAdd = fromOffset.asMask for (i in fromOffset..toOffset) { res = (res shl 1) or maskToAdd } return res } // Transforms a size in bits to a size in elements of the `bits` array. private fun bitToElementSize(bitSize: Int): Int = (bitSize + ELEMENT_SIZE - 1) / ELEMENT_SIZE // Transforms a pair of an element index and a bit offset to a bit index. private fun bitIndex(elementIndex: Int, bitOffset: Int) = elementIndex * ELEMENT_SIZE + bitOffset // Sets all bits after the last available bit (size - 1) to 0. private fun clearUnusedTail() { val (lastElementIndex, lastBitOffset) = lastIndex.asBitCoordinates bits[bits.lastIndex] = bits[bits.lastIndex] and lastBitOffset.asMaskBefore for (i in lastElementIndex + 1 until bits.size) { bits[i] = ALL_FALSE } } // Internal function. Sets bits specified by the element index and the given mask to value. private fun setBitsWithMask(elementIndex: Int, mask: Long, value: Boolean) { val element = bits[elementIndex] if (value) { bits[elementIndex] = element or mask } else { bits[elementIndex] = element and mask.inv() } } // Internal function. Flips bits specified by the element index and the given mask. private fun flipBitsWithMask(elementIndex: Int, mask: Long) { val element = bits[elementIndex] bits[elementIndex] = element xor mask } /** * Checks if index is valid and extends the `bits` array if the index exceeds its size. * Throws [IndexOutOfBoundsException] if [index] < 0. */ private fun ensureCapacity(index: Int) { if (index < 0) { throw IndexOutOfBoundsException() } if (index >= size) { size = index + 1 if (index.elementIndex >= bits.size) { // Create a new array containing the index-th bit. bits = bits.copyOf(bitToElementSize(index + 1)) } // Set all bits after the index to 0. TODO: We can remove it. clearUnusedTail() } } /** Set the bit specified to the specified value. */ fun set(index: Int, value: Boolean = true) { ensureCapacity(index) val (elementIndex, offset) = index.asBitCoordinates setBitsWithMask(elementIndex, offset.asMask, value) } /** Sets the bits with indices between [from] (inclusive) and [to] (exclusive) to the specified value. */ fun set(from : Int, to: Int, value: Boolean = true) = set(from until to, value) /** Sets the bits from the range specified to the specified value. */ fun set(range: IntRange, value: Boolean = true) { if (range.start < 0 || range.endInclusive < 0) { throw IndexOutOfBoundsException() } if (range.start > range.endInclusive) { // Empty range. return } ensureCapacity(range.endInclusive) val (fromIndex, fromOffset) = range.start.asBitCoordinates val (toIndex, toOffset) = range.endInclusive.asBitCoordinates if (toIndex == fromIndex) { val mask = getMaskBetween(fromOffset, toOffset) setBitsWithMask(fromIndex, mask, value) } else { // Set bits in the first element. setBitsWithMask(fromIndex, fromOffset.asMaskAfter, value) // Set all bits of all elements (excluding border ones) to 0 or 1 depending. for (index in fromIndex + 1 until toIndex) { bits[index] = if (value) ALL_TRUE else ALL_FALSE } // Set bits in the last element setBitsWithMask(toIndex, toOffset.asMaskBefore, value) } } /** Clears the bit specified */ fun clear(index: Int) = set(index, false) /** Clears the bits with indices between [from] (inclusive) and [to] (exclusive) to the specified value. */ fun clear(from : Int, to: Int) = set(from, to, false) /** Clears the bit specified */ fun clear(range: IntRange) = set(range, false) /** Sets all bits in the BitSet to `false`. */ fun clear() { for (i in bits.indices) { bits[i] = ALL_FALSE } } /** Reverses the bit specified. */ fun flip(index: Int) { ensureCapacity(index) val (elementIndex, offset) = index.asBitCoordinates flipBitsWithMask(elementIndex, offset.asMask) } /** Reverses the bits with indices between [from] (inclusive) and [to] (exclusive). */ fun flip(from: Int, to: Int) = flip(from until to) /** Reverses the bits from the range specified. */ fun flip(range: IntRange) { if (range.start < 0 || range.endInclusive < 0) { throw IndexOutOfBoundsException() } if (range.start > range.endInclusive) { // Empty range. return } ensureCapacity(range.endInclusive) val (fromIndex, fromOffset) = range.start.asBitCoordinates val (toIndex, toOffset) = range.endInclusive.asBitCoordinates if (toIndex == fromIndex) { val mask = getMaskBetween(fromOffset, toOffset) flipBitsWithMask(fromIndex, mask) } else { // Flip bits in the first element. flipBitsWithMask(toIndex, toOffset.asMaskAfter) // Flip bits between the first and the last elements. for (index in fromIndex + 1 until toIndex) { bits[index] = bits[index].inv() } // Flip bits in the last element. flipBitsWithMask(toIndex, toOffset.asMaskBefore) } } /** * Returns an index of a next set (if [lookFor] == true) or clear * (if [lookFor] == false) bit after [startIndex] (inclusive). * Returns -1 (for [lookFor] == true) or [size] (for lookFor == false) * if there is no such bits between [startIndex] and [size] - 1. * Throws IndexOutOfBoundException if [startIndex] < 0. */ private fun nextBit(startIndex: Int, lookFor: Boolean): Int { if (startIndex < 0) { throw IndexOutOfBoundsException() } if (startIndex >= size) { return if (lookFor) -1 else startIndex } val (startElementIndex, startOffset) = startIndex.asBitCoordinates // Look for the next set bit in the first element. var element = bits[startElementIndex] for (offset in startOffset..MAX_BIT_OFFSET) { val bit = element and (0x1L shl offset) != 0L if (bit == lookFor) { // Look for not 0 if we need a set bit and look for 0 otherwise. return bitIndex(startElementIndex, offset) } } // Look for in the remaining elements. for (index in startElementIndex + 1..bits.lastIndex) { element = bits[index] for (offset in 0..MAX_BIT_OFFSET) { val bit = element and (0x1L shl offset) != 0L if (bit == lookFor) { // Look for not 0 if we need a set bit and look for 0 otherwise. return bitIndex(index, offset) } } } return if (lookFor) -1 else size } /** * Returns an index of a next bit which value is `true` after [startIndex] (inclusive). * Returns -1 if there is no such bits after [startIndex]. * Throws IndexOutOfBoundException if [startIndex] < 0. */ fun nextSetBit(startIndex: Int = 0): Int = nextBit(startIndex, true) /** * Returns an index of a next bit which value is `false` after [startIndex] (inclusive). * Returns [size] if there is no such bits between [startIndex] and [size] - 1 assuming that the set has an infinite * sequence of `false` bits after (size - 1)-th. * Throws IndexOutOfBoundException if [startIndex] < 0. */ fun nextClearBit(startIndex: Int = 0): Int = nextBit(startIndex, false) /** * Returns the biggest index of a bit which value is [lookFor] before [startIndex] (inclusive). * Returns -1 if there is no such bits before [startIndex]. * If [startIndex] >= [size] returns -1 */ fun previousBit(startIndex: Int, lookFor: Boolean): Int { var correctStartIndex = startIndex if (startIndex >= size) { // We assume that all bits after `size - 1` are 0. So we can return the start index if we are looking for 0. if (!lookFor) { return startIndex } else { // If we are looking for 1 we can skip all these 0 after `size - 1`. correctStartIndex = size - 1 } } if (correctStartIndex < -1) { throw IndexOutOfBoundsException() } if (correctStartIndex == -1) { return -1 } val (startElementIndex, startOffset) = correctStartIndex.asBitCoordinates // Look for the next set bit in the first element. var element = bits[startElementIndex] for (offset in startOffset downTo 0) { val bit = element and (0x1L shl offset) != 0L if (bit == lookFor) { // Look for not 0 if we need a set bit and look for 0 otherwise. return bitIndex(startElementIndex, offset) } } // Look for in the remaining elements. for (index in startElementIndex - 1 downTo 0) { element = bits[index] for (offset in MAX_BIT_OFFSET downTo 0) { val bit = element and (0x1L shl offset) != 0L if (bit == lookFor) { // Look for not 0 if we need a set bit and look for 0 otherwise. return bitIndex(index, offset) } } } return -1 } /** * Returns the biggest index of a bit which value is `true` before [startIndex] (inclusive). * Returns -1 if there is no such bits before [startIndex] or if [startIndex] == -1. * If [startIndex] >= size will search from (size - 1)-th bit. * Throws IndexOutOfBoundException if [startIndex] < -1. */ fun previousSetBit(startIndex: Int): Int = previousBit(startIndex, true) /** * Returns the biggest index of a bit which value is `false` before [startIndex] (inclusive). * Returns -1 if there is no such bits before [startIndex] or if [startIndex] == -1. * If [startIndex] >= size will return [startIndex] assuming that the set has an infinite * sequence of `false` bits after (size - 1)-th. * Throws IndexOutOfBoundException if [startIndex] < -1. */ fun previousClearBit(startIndex: Int): Int = previousBit(startIndex, false) /** Returns a value of a bit with the [index] specified. */ operator fun get(index: Int): Boolean { if (index < 0) { throw IndexOutOfBoundsException() } if (index >= size) { return false } val (elementIndex, offset) = index.asBitCoordinates return bits[elementIndex] and offset.asMask != 0L } private inline fun doOperation(another: BitSet, operation: Long.(Long) -> Long) { ensureCapacity(another.lastIndex) var index = 0 while (index < another.bits.size) { bits[index] = operation(bits[index], another.bits[index]) index++ } while (index < bits.size) { bits[index] = operation(bits[index], ALL_FALSE) index++ } } /** Performs a logical and operation over corresponding bits of this and [another] BitSets. The result is saved in this BitSet. */ fun and(another: BitSet) = doOperation(another, Long::and) /** Performs a logical or operation over corresponding bits of this and [another] BitSets. The result is saved in this BitSet. */ fun or(another: BitSet) = doOperation(another, Long::or) /** Performs a logical xor operation over corresponding bits of this and [another] BitSets. The result is saved in this BitSet. */ fun xor(another: BitSet) = doOperation(another, Long::xor) /** Performs a logical and + not operations over corresponding bits of this and [another] BitSets. The result is saved in this BitSet. */ fun andNot(another: BitSet) { ensureCapacity(another.lastIndex) var index = 0 while (index < another.bits.size) { bits[index] = bits[index] and another.bits[index].inv() index++ } while (index < bits.size) { bits[index] = bits[index] and ALL_TRUE index++ } } /** Returns true if the specified BitSet has any bits set to true that are also set to true in this BitSet. */ fun intersects(another: BitSet): Boolean = (0 until minOf(bits.size, another.bits.size)).any { bits[it] and another.bits[it] != 0L } override fun toString(): String { val sb = StringBuilder() var first = true sb.append('[') var index = nextSetBit(0) while (index != -1) { if (!first) { sb.append('|') } else { first = false } sb.append(index) index = nextSetBit(index + 1) } sb.append(']') return sb.toString() } override fun hashCode(): Int { var x: Long = 1234 for (i in 0..bits.lastIndex) { x = x xor bits[i] * (i + 1) } return (x shr 32 xor x).toInt() } override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other !is BitSet) { return false } var index = 0 while (index < minOf(bits.size, other.bits.size)) { if (bits[index] != other.bits[index]) { return false } index++ } val longestBits = if (bits.size > other.bits.size) bits else other.bits while (index < longestBits.size) { if (longestBits[index] != ALL_FALSE) { return false } index++ } return true } }
apache-2.0
55a375b3b0770edc6e762c55f0e89736
38.020316
141
0.598403
4.257635
false
false
false
false
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/ChannelConnections.kt
1
794
package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * All connections for a channel. * * @param privacyUsers Information provided to channel moderators about which users they have specifically permitted to * access a private channel. This data requires a bearer token with the private scope. * @param users Information about the users following or moderating this channel. * @param videos Information about the videos that belong to this channel. */ @JsonClass(generateAdapter = true) data class ChannelConnections( @Json(name = "privacy_users") val privacyUsers: BasicConnection? = null, @Json(name = "users") val users: BasicConnection? = null, @Json(name = "videos") val videos: BasicConnection? = null )
mit
23f08a360998ff57c58acdbe7e3019ba
29.538462
119
0.746851
4.245989
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/new/tests/testData/inference/common/arrayOfArrays.kt
13
484
class Test { fun foo() { val x: /*T5@*/Array</*T4@*/Array</*T3@*/Int>> = Array</*T2@*/Array</*T1@*/Int>>(1/*LIT*/, { arrayOf</*T0@*/Int>(2/*LIT*/)/*Array<T0@Int>*/ }/*Function0<Int, T6@Array<T7@Int>>*/ )/*Array<T2@Array<T1@Int>>*/ } } //LOWER <: T0 due to 'PARAMETER' //T7 := T0 due to 'RETURN' //T1 := T7 due to 'PARAMETER' //T6 <: T2 due to 'PARAMETER' //T3 := T1 due to 'INITIALIZER' //T4 := T2 due to 'INITIALIZER'
apache-2.0
a1ffc6b25eab4716ff4c855c4d784ff8
29.25
62
0.491736
2.703911
false
true
false
false
smmribeiro/intellij-community
plugins/git4idea/src/git4idea/ui/branch/GitCheckoutAndRebaseRemoteBranchWorkflow.kt
9
4050
// 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 git4idea.ui.branch import com.intellij.ide.IdeBundle import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.vcs.VcsNotifier import git4idea.GitNotificationIdsHolder import git4idea.branch.GitBranchUiHandlerImpl import git4idea.branch.GitBrancher import git4idea.branch.GitNewBranchOptions import git4idea.commands.Git import git4idea.i18n.GitBundle import git4idea.repo.GitRepository internal class GitCheckoutAndRebaseRemoteBranchWorkflow(private val project: Project, private val repositories: List<GitRepository>) { private val brancher = GitBrancher.getInstance(project) init { assert(repositories.isNotEmpty()) } fun execute(startPoint: String, options: GitNewBranchOptions) { val name = options.name val reset = options.reset if (repositories.any { it.currentBranchName == name }) { VcsNotifier.getInstance(project) .notifyError( GitNotificationIdsHolder.BRANCH_OPERATION_ERROR, GitBundle.message("branches.checkout.and.rebase.failed"), GitBundle.message("branches.checkout.and.rebase.error.current.with.same.name", name), ) return } val localHasMoreCommits = GitBranchCheckoutOperation.checkLocalHasMoreCommits(project, repositories, name, startPoint) if (localHasMoreCommits) { if (reset) { val result = Messages.showYesNoDialog( GitBundle.message("branches.create.with.reset.local.has.more.commits", name, startPoint), GitBundle.message("checkout.0", startPoint), GitBundle.message("branches.drop.local.commits"), IdeBundle.message("button.cancel"), null) if (result != Messages.YES) return } else { val result = Messages.showYesNoDialog( GitBundle.message("branches.create.local.has.more.commits", name, startPoint), GitBundle.message("checkout.0", startPoint), GitBundle.message("new.branch.dialog.operation.create.name"), IdeBundle.message("button.cancel"), null) if (result != Messages.YES) return } } object : Task.Backgroundable(project, GitBundle.message("branches.checkout.and.rebase.onto.current.process", startPoint), true) { override fun run(indicator: ProgressIndicator) { try { indicator.text2 = GitBundle.message("branch.creating.branch.process", name) doCreateNewBranch(startPoint, name, reset) } catch (e: Exception) { GitBranchUiHandlerImpl(project, indicator) .notifyError(GitBundle.message("create.branch.operation.could.not.create.new.branch", name), e.message!!) } indicator.text2 = GitBundle.message("branch.rebasing.process", name) brancher.rebaseOnCurrent(repositories, name) } }.queue() } private fun doCreateNewBranch(startPoint: String, name: String, reset: Boolean) { val (reposWithLocalBranch, reposWithoutLocalBranch) = repositories.partition { it.branches.findLocalBranch(name) != null } if (reposWithLocalBranch.isNotEmpty() && reset) { createBranch(name, startPoint, reposWithLocalBranch, true) } if (reposWithoutLocalBranch.isNotEmpty()) { createBranch(name, startPoint, reposWithoutLocalBranch, false) } } private fun createBranch(name: String, startPoint: String, repositories: List<GitRepository>, force: Boolean) { val git = Git.getInstance() for (repository in repositories) { val result = git.branchCreate(repository, name, startPoint, force) if (result.success()) { repository.update() } else { throw IllegalStateException(result.errorOutputAsHtmlString) } } } }
apache-2.0
f99799a32aa057d74ad721fb41c8a3c4
39.108911
158
0.701975
4.460352
false
false
false
false
smmribeiro/intellij-community
platform/script-debugger/protocol/protocol-model-generator/src/StandaloneType.kt
19
1502
package org.jetbrains.protocolModelGenerator class StandaloneType(private val namePath: NamePath, override val writeMethodName: String, override val defaultValue: String? = "null") : BoxableType { override val fullText: String = namePath.getFullText() override fun getShortText(contextNamespace: NamePath): String { val nameLength = namePath.getLength() val contextLength = contextNamespace.getLength() if (nameLength > contextLength) { val builder = subtractContextRecursively(namePath, nameLength - contextLength, contextNamespace) if (builder != null) { return builder.toString() } } return namePath.getFullText() } private fun subtractContextRecursively(namePos: NamePath?, count: Int, prefix: NamePath): StringBuilder? { if (count > 1) { val result = subtractContextRecursively(namePos!!.parent, count - 1, prefix) ?: return null result.append('.') result.append(namePos.lastComponent) return result } else { var namePos = namePos var prefix = prefix val nameComponent = namePos!!.lastComponent namePos = namePos.parent do { if (namePos!!.lastComponent != prefix.lastComponent) { return null } namePos = namePos.parent if (namePos == null) { break } prefix = prefix.parent!! } while (true) val result = StringBuilder() result.append(nameComponent) return result } } }
apache-2.0
95a0c0e4fa50e344207b2ccc79d6728d
29.673469
151
0.656458
4.593272
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/core/export/glTF/GLTF.kt
1
27708
package com.cout970.modeler.core.export.glTF import com.cout970.matrix.api.IMatrix4 import com.cout970.vector.api.IQuaternion import com.cout970.vector.api.IVector3 import com.cout970.vector.api.IVector4 import com.cout970.vector.extensions.Quaternion import com.cout970.vector.extensions.Vector3 import com.cout970.vector.extensions.Vector4 typealias JsObject = Map<String, Any> // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#reference-gltf // @formatter:off data class GltfFile( val extensionsUsed: List<String> = emptyList(), // Names of glTF extensions used somewhere in this asset. val extensionsRequired: List<String> = emptyList(), // Names of glTF extensions required to properly load this asset. val accessors: List<GltfAccessor> = emptyList(), // An array of accessors. An accessor is a typed view into a bufferView. val animations: List<GltfAnimation> = emptyList(), // An array of keyframe animations. val asset: JsObject = emptyMap(), // Metadata about the glTF asset. val buffers: List<GltfBuffer> = emptyList(), // An array of buffers. A buffer points to binary geometry, animation, or skins. val bufferViews: List<GltfBufferView> = emptyList(), // An array of bufferViews. A bufferView is a view into a buffer generally representing a subset of the buffer. val cameras: List<GltfCamera> = emptyList(), // An array of cameras. A camera defines a projection matrix. val images: List<GltfImage> = emptyList(), // An array of images. An image defines data used to create a texture. val materials: List<GltfMaterial> = emptyList(), // An array of materials. A material defines the appearance of a primitive. val meshes: List<GltfMesh> = emptyList(), // An array of meshes. A mesh is a set of primitives to be rendered. val nodes: List<GltfNode> = emptyList(), // An array of nodes. val samplers: List<GltfSampler> = emptyList(), // An array of samplers. A sampler contains properties for texture filtering and wrapping modes. val scene: Int? = null, // The index of the default scene. val scenes: List<GltfScene> = emptyList(), // An array of scenes. val skins: List<GltfSkin> = emptyList(), // An array of skins. A skin is defined by joints and matrices. val textures: List<GltfTexture> = emptyList(), // An array of textures. val extensions: JsObject? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ){ override fun toString(): String { return "glTF(\n" + " extensionsUsed = $extensionsUsed, \n" + " extensionsRequired = $extensionsRequired, \n" + " accessors = $accessors, \n" + " animations = $animations, \n" + " asset = $asset, \n" + " buffers = $buffers, \n" + " bufferViews = $bufferViews, \n" + " cameras = $cameras, \n" + " images = $images, \n" + " materials = $materials, \n" + " meshes = $meshes, \n" + " nodes = $nodes, \n" + " samplers = $samplers, \n" + " scene = $scene, \n" + " scenes = $scenes, \n" + " skins = $skins, \n" + " textures = $textures, \n" + " extensions = $extensions, \n" + " extras = $extras" + "\n)" } } data class GltfScene( val nodes: List<Int>? = null, // The indices of each root node. val name: String? = null, // The user-defined name of this object. This is not necessarily unique, e.g., an accessor and a buffer could have the same name, or two accessors could even have the same name. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfNode ( val camera: Int? = null, // The index of the camera referenced by this node. val children: List<Int> = emptyList(), // The indices of this node's children. val skin: Int? = null, // The index of the skin referenced by this node. val matrix: IMatrix4? = null, // A floating-point 4x4 transformation matrix stored in column-major order. val mesh: Int? = null, // The index of the mesh in this node. val rotation: IQuaternion? = Quaternion.IDENTITY, // The node's unit quaternion rotation in the order (x, y, z, w), where w is the scalar. val scale: IVector3? = Vector3.ONE, // The node's non-uniform scale, given as the scaling factors along the x, y, and z axes. val translation: IVector3? = Vector3.ZERO, // The node's translation along the x, y, and z axes. val weights: List<Double> = emptyList(), // The weights of the instantiated Morph Target. Number of elements must match number of Morph Targets of used mesh. val name: String? = null, // The user-defined name of this object. This is not necessarily unique, e.g., an accessor and a buffer could have the same name, or two accessors could even have the same name. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfBuffer( val uri: String? = null, // The uri of the buffer. Relative paths are relative to the .gltf file. Instead of referencing an external file, the uri can also be a data-uri. val byteLength: Int = 0, // The length of the buffer in bytes. val name: String? = null, // The user-defined name of this object. This is not necessarily unique, e.g., an accessor and a buffer could have the same name, or two accessors could even have the same name. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfBufferView( val buffer: Int = 0, // The index of the buffer. val byteOffset: Int? = 0, // The offset into the buffer in bytes. val byteLength: Int = 0, // The length of the bufferView in bytes. val byteStride: Int? = null, // The stride, in bytes, between vertex attributes. When this is not defined, data is tightly packed. When two or more accessors use the same bufferView, this field must be defined. val target: Int? = 0, // The target that the GPU buffer should be bound to. val name: String? = null, // The user-defined name of this object. This is not necessarily unique, e.g., an accessor and a buffer could have the same name, or two accessors could even have the same name. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfCamera( val orthographic: GltfOrthographicCamera? = null, // An orthographic camera containing properties to create an orthographic projection matrix. val perspective: GltfPerspectiveCamera? = null, // A perspective camera containing properties to create a perspective projection matrix. val type: GltfCameraType = GltfCameraType.orthographic, // Specifies if the camera uses a perspective or orthographic projection. Based on this, either the camera's perspective or orthographic property will be defined. val name: String? = null, // The user-defined name of this object. This is not necessarily unique, e.g., an accessor and a buffer could have the same name, or two accessors could even have the same name. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfAccessor( val bufferView: Int? = 0, // The index of the bufferView. When not defined, accessor must be initialized with zeros; sparse property or extensions could override zeros with actual values. val byteOffset: Int? = 0, // The offset relative to the start of the bufferView in bytes. This must be a multiple of the size of the component datatype. val componentType: Int = 0, // The datatype of components in the attribute. All valid values correspond to WebGL enums. The corresponding typed arrays are Int8Array, Uint8Array, Int16Array, Uint16Array, Uint32Array, and Float32Array, respectively. 5125 (UNSIGNED_INT) is only allowed when the accessor contains indices, i.e., the accessor is only referenced by primitive.indices. val normalized: Boolean? = false, // Specifies whether integer data values should be normalized (true) to [0, 1] (for unsigned types) or [-1, 1] (for signed types), or converted directly (false) when they are accessed. This property is defined only for accessors that contain vertex attributes or animation output data. val count: Int = 0, // The number of attributes referenced by this accessor, not to be confused with the number of bytes or number of components. val type: GltfType = GltfType.SCALAR, // Specifies if the attribute is a scalar, vector, or matrix. val max: List<Double> = emptyList(), // Maximum value of each component in this attribute. Array elements must be treated as having the same data type as accessor's componentType. Both min and max arrays have the same length. The length is determined by the value of the type property; it can be 1, 2, 3, 4, 9, or 16. val min: List<Double> = emptyList(), // Minimum value of each component in this attribute. Array elements must be treated as having the same data type as accessor's componentType. Both min and max arrays have the same length. The length is determined by the value of the type property; it can be 1, 2, 3, 4, 9, or 16. val sparse: GltfSparse? = null, // Sparse storage of attributes that deviate from their initialization value. val name: String? = null, // The user-defined name of this object. This is not necessarily unique, e.g., an accessor and a buffer could have the same name, or two accessors could even have the same name. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfSparse( val count: Int = 0, // The number of attributes encoded in this sparse accessor. val indices: List<GltfAccessor> = emptyList(), // Index array of size count that points to those accessor attributes that deviate from their initialization value. Indices must strictly increase. val values: List<GltfAccessor> = emptyList(), // Array of size count times number of components, storing the displaced accessor attributes pointed by indices. Substituted values must have the same componentType and number of components as the base accessor. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfMesh( val primitives: List<GltfPrimitive> = emptyList(), // An array of primitives, each defining geometry to be rendered with a material. val weights: List<Double> = emptyList(), // Array of weights to be applied to the Morph Targets. val name: String? = null, // The user-defined name of this object. This is not necessarily unique, e.g., an accessor and a buffer could have the same name, or two accessors could even have the same name. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfPrimitive( val attributes: Map<String, Int> = emptyMap(), // A dictionary object, where each key corresponds to mesh attribute semantic and each value is the index of the accessor containing attribute's data. val indices: Int? = null, // The index of the accessor that contains mesh indices. When this is not defined, the primitives should be rendered without indices using drawArrays(). When defined, the accessor must contain indices: the bufferView referenced by the accessor should have a target equal to 34963 (ELEMENT_ARRAY_BUFFER); componentType must be 5121 (UNSIGNED_BYTE), 5123 (UNSIGNED_SHORT) or 5125 (UNSIGNED_INT), the latter may require enabling additional hardware support; type must be "SCALAR". For triangle primitives, the front face has a counter-clockwise (CCW) winding order. val material: Int? = null, // The index of the material to apply to this primitive when rendering. val mode: Int = 4, // The type of primitives to render. All valid values correspond to WebGL enums. val targets: Map<String, Int> = emptyMap(), // An array of Morph Targets, each Morph Target is a dictionary mapping attributes (only POSITION, NORMAL, and TANGENT supported) to their deviations in the Morph Target. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfSkin( val inverseBindMatrices: Int? = 0, // The index of the accessor containing the floating-point 4x4 inverse-bind matrices. The default is that each matrix is a 4x4 identity matrix, which implies that inverse-bind matrices were pre-applied. val joints: List<Int> = emptyList(), // The index of the node used as a skeleton root. When undefined, joints transforms resolve to scene root. val skeleton: Int? = 0, // Indices of skeleton nodes, used as joints in this skin. The array length must be the same as the count property of the inverseBindMatrices accessor (when defined). val name: String? = null, // The user-defined name of this object. This is not necessarily unique, e.g., an accessor and a buffer could have the same name, or two accessors could even have the same name. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfTexture( val sampler: Int? = 0, // The index of the sampler used by this texture. When undefined, a sampler with repeat wrapping and auto filtering should be used. val source: Int? = 0, // The index of the image used by this texture. val name: String? = null, // The user-defined name of this object. This is not necessarily unique, e.g., an accessor and a buffer could have the same name, or two accessors could even have the same name. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfImage( val uri: String? = null, // The uri of the image. Relative paths are relative to the .gltf file. Instead of referencing an external file, the uri can also be a data-uri. The image format must be jpg or png. val mimeType: String? = null, // The image's MIME type. val bufferView: Int? = null, // The index of the bufferView that contains the image. Use this instead of the image's uri property. val name: String? = null, // The user-defined name of this object. This is not necessarily unique, e.g., an accessor and a buffer could have the same name, or two accessors could even have the same name. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfSampler( val magFilter: Int? = null, // Magnification filter. Valid values correspond to WebGL enums: 9728 (NEAREST) and 9729 (LINEAR). val minFilter: Int? = null, // Minification filter. All valid values correspond to WebGL enums. val wrapS: Int? = null, // S (U) wrapping mode. All valid values correspond to WebGL enums. val wrapT: Int? = null, // T (V) wrapping mode. All valid values correspond to WebGL enums. val name: String? = null, // The user-defined name of this object. This is not necessarily unique, e.g., an accessor and a buffer could have the same name, or two accessors could even have the same name. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfMaterial( val name: String? = null, // The user-defined name of this object. This is not necessarily unique, e.g., an accessor and a buffer could have the same name, or two accessors could even have the same name. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null, // Application-specific data. val pbrMetallicRoughness: GltfPbrMetallicRoughness? = null, // A set of parameter values that are used to define the metallic-roughness material model from Physically-Based Rendering (PBR) methodology. When not specified, all the default values of pbrMetallicRoughness apply. val normalTexture: GltfNormalTextureInfo? = null, // A tangent space normal map. The texture contains RGB components in linear space. Each texel represents the XYZ components of a normal vector in tangent space. Red [0 to 255] maps to X [-1 to 1]. Green [0 to 255] maps to Y [-1 to 1]. Blue [128 to 255] maps to Z [1/255 to 1]. The normal vectors use OpenGL conventions where +X is right and +Y is up. +Z points toward the viewer. In GLSL, this vector would be unpacked like so: vec3 normalVector = tex2D(normalMap, texCoord) * 2 - 1. Client implementations should normalize the normal vectors before using them in lighting equations. val occlusionTexture: GltfOcclusionTextureInfo? = null, // The occlusion map texture. The occlusion values are sampled from the R channel. Higher values indicate areas that should receive full indirect lighting and lower values indicate no indirect lighting. These values are linear. If other channels are present (GBA), they are ignored for occlusion calculations. val emissiveTexture: GltfTextureInfo? = null, // The emissive map controls the color and intensity of the light being emitted by the material. This texture contains RGB components in sRGB color space. If a fourth component (A) is present, it is ignored. val emissiveFactor: IVector3? = Vector3.ZERO, // The RGB components of the emissive color of the material. These values are linear. If an emissiveTexture is specified, this value is multiplied with the texel values. val alphaMode: GltfAlphaMode? = GltfAlphaMode.OPAQUE, // The material's alpha rendering mode enumeration specifying the interpretation of the alpha value of the main factor and texture. val alphaCutoff: Double? = 0.5, // Specifies the cutoff threshold when in MASK mode. If the alpha value is greater than or equal to this value then it is rendered as fully opaque, otherwise, it is rendered as fully transparent. A value greater than 1.0 will render the entire material as fully transparent. This value is ignored for other modes. val doubleSided: Boolean = false // Specifies whether the material is double sided. When this value is false, back-face culling is enabled. When this value is true, back-face culling is disabled and double sided lighting is enabled. The back-face must have its normals reversed before the lighting equation is evaluated. ) data class GltfPbrMetallicRoughness( val baseColorFactor: IVector4 = Vector4.ONE, // The RGBA components of the base color of the material. The fourth component (A) is the alpha coverage of the material. The alphaMode property specifies how alpha is interpreted. These values are linear. If a baseColorTexture is specified, this value is multiplied with the texel values. val baseColorTexture: GltfTextureInfo? = null, // The base color texture. This texture contains RGB(A) components in sRGB color space. The first three components (RGB) specify the base color of the material. If the fourth component (A) is present, it represents the alpha coverage of the material. Otherwise, an alpha of 1.0 is assumed. The alphaMode property specifies how alpha is interpreted. The stored texels must not be premultiplied. val metallicFactor: Double = 1.0, // The metalness of the material. A value of 1.0 means the material is a metal. A value of 0.0 means the material is a dielectric. Values in between are for blending between metals and dielectrics such as dirty metallic surfaces. This value is linear. If a metallicRoughnessTexture is specified, this value is multiplied with the metallic texel values. val roughnessFactor: Double = 1.0, // The roughness of the material. A value of 1.0 means the material is completely rough. A value of 0.0 means the material is completely smooth. This value is linear. If a metallicRoughnessTexture is specified, this value is multiplied with the roughness texel values. val metallicRoughnessTexture: GltfTextureInfo? = null, // The metallic-roughness texture. The metalness values are sampled from the B channel. The roughness values are sampled from the G channel. These values are linear. If other channels are present (R or A), they are ignored for metallic-roughness calculations. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfTextureInfo( val index: Int = 0, // The index of the texture. val texCoord: Int = 0, // This integer value is used to construct a string in the format TEXCOORD_ which is a reference to a key in mesh.primitives.attributes (e.g. A value of 0 corresponds to TEXCOORD_0). val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfNormalTextureInfo( val index: Int = 0, // The index of the texture. val texCoord: Int = 0, // This integer value is used to construct a string in the format TEXCOORD_ which is a reference to a key in mesh.primitives.attributes (e.g. A value of 0 corresponds to TEXCOORD_0). val scale: Double = 1.0, // The scalar multiplier applied to each normal vector of the texture. This value scales the normal vector using the formula: scaledNormal = normalize((normalize(<sampled normal texture value>) * 2.0 - 1.0) * vec3(<normal scale>, <normal scale>, 1.0)). This value is ignored if normalTexture is not specified. This value is linear. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfOcclusionTextureInfo( val index: Int = 0, // The index of the texture. val texCoord: Int = 0, // This integer value is used to construct a string in the format TEXCOORD_ which is a reference to a key in mesh.primitives.attributes (e.g. A value of 0 corresponds to TEXCOORD_0). val strength: Double = 1.0, // The scalar multiplier applied to each normal vector of the texture. This value scales the normal vector using the formula: scaledNormal = normalize((normalize(<sampled normal texture value>) * 2.0 - 1.0) * vec3(<normal scale>, <normal scale>, 1.0)). This value is ignored if normalTexture is not specified. This value is linear. val extensions: String? = null, // Dictionary object with extension-specific objects. val extras: Any? = null // Application-specific data. ) data class GltfPerspectiveCamera( val aspectRatio: Double, val yfov: Double, val znear: Double, val zfar: Double = Double.POSITIVE_INFINITY ) data class GltfOrthographicCamera( val xmag: Double, val ymag: Double, val zfar: Double, val znear: Double ) // @formatter:on data class GltfAnimation( val name: String?, val channels: List<GltfAnimationChannel>, val samplers: List<GltfAnimationSampler> ) data class GltfAnimationChannel( val sampler: Int, val target: GltfChannelTarget ) data class GltfChannelTarget( val node: Int, val path: String ) data class GltfAnimationSampler( val input: Int, val interpolation: GltfInterpolation, val output: Int ) enum class GltfChannelPath { translation, rotation, scale, weights } enum class GltfInterpolation { LINEAR, STEP, CUBICSPLINE } enum class GltfCameraType { perspective, orthographic } enum class GltfAlphaMode { OPAQUE, MASK, BLEND } enum class GltfAttribute { // default defined attributes POSITION, NORMAL, TANGENT, TEXCOORD_0, TEXCOORD_1, COLOR_0, JOINTS_0, WEIGHTS_0 } enum class GltfComponentType(val id: Int, val size: Int) { BYTE(5120, 1), UNSIGNED_BYTE(5121, 1), SHORT(5122, 2), UNSIGNED_SHORT(5123, 2), UNSIGNED_INT(5125, 4), FLOAT(5126, 4); companion object { val conversionMap: Map<Int, GltfComponentType> = values().associateBy { it.id } fun fromId(value: Int) = conversionMap[value] ?: error("Invalid Component type value: $value") } } enum class GltfType(val numComponents: Int) { SCALAR(1), VEC2(2), VEC3(3), VEC4(4), MAT2(4), MAT3(9), MAT4(16) } enum class GltfMode(val code: Int) { POINTS(0x0), LINES(0x1), LINE_LOOP(0x2), LINE_STRIP(0x3), TRIANGLES(0x4), TRIANGLE_STRIP(0x5), TRIANGLE_FAN(0x6), QUADS(0x7), QUAD_STRIP(0x8), POLYGON(0x9); companion object { val conversionMap: Map<Int, GltfMode> = GltfMode.values().associateBy { it.code } fun fromId(value: Int) = conversionMap[value] ?: error("Invalid GL mode: $value") } }
gpl-3.0
6a22d8b89c17969dcf3926181b6fba44
80.497059
664
0.660495
4.405788
false
false
false
false
Flank/flank
test_runner/src/main/kotlin/ftl/reports/HtmlErrorReport.kt
1
2692
package ftl.reports import com.google.gson.Gson import flank.tool.resource.readTextResource import ftl.api.JUnitTest import ftl.args.IArgs import ftl.domain.junit.failed import ftl.json.MatrixMap import ftl.reports.util.IReport import ftl.reports.util.ReportManager import java.nio.file.Files import java.nio.file.Paths /** * Outputs HTML report for Bitrise based on JUnit XML. Only run on failures. * */ object HtmlErrorReport : IReport { override val extension = ".html" internal data class Group(val label: String, val items: List<Item>) internal data class Item(val label: String, val url: String) override fun run( matrices: MatrixMap, result: JUnitTest.Result?, printToStdout: Boolean, args: IArgs ) { val suites = result?.testsuites?.process()?.takeIf { it.isNotEmpty() } ?: return Paths.get(reportPath(matrices, args)).let { val htmlReport = suites.createHtmlReport() Files.write(it, htmlReport.toByteArray()) ReportManager.uploadReportResult(htmlReport, args, it.fileName.toString()) } } } internal fun List<JUnitTest.Suite>.process(): List<HtmlErrorReport.Group> = getFailures() .groupByLabel() .createGroups() private fun List<JUnitTest.Suite>.getFailures(): List<Pair<String, List<JUnitTest.Case>>> = mapNotNull { suite -> suite.testcases?.let { testCases -> suite.name to testCases.filter { it.failed() } } } private fun List<Pair<String, List<JUnitTest.Case>>>.groupByLabel(): Map<String, List<JUnitTest.Case>> = map { (suiteName, testCases) -> testCases.map { testCase -> "$suiteName ${testCase.classname}#${testCase.name}".trim() to testCase } } .flatten() .groupBy({ (label: String, _) -> label }) { (_, useCase) -> useCase } private fun Map<String, List<JUnitTest.Case>>.createGroups(): List<HtmlErrorReport.Group> = map { (label, testCases: List<JUnitTest.Case>) -> HtmlErrorReport.Group( label = label, items = testCases.createItems() ) } private fun List<JUnitTest.Case>.createItems(): List<HtmlErrorReport.Item> = map { testCase -> HtmlErrorReport.Item( label = testCase.stackTrace().split("\n").firstOrNull() ?: "", url = testCase.webLink ?: "" ) } private fun JUnitTest.Case.stackTrace(): String { return failures?.joinToString() + errors?.joinToString() } private fun List<HtmlErrorReport.Group>.createHtmlReport(): String = readTextResource("inline.html").replace( oldValue = "\"INJECT-DATA-HERE\"", newValue = "`${Gson().toJson(this)}`" )
apache-2.0
1477254f099e236f63a0f19203047e97
31.829268
104
0.654903
4.035982
false
true
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/GuildFragment.kt
1
8407
package com.habitrpg.android.habitica.ui.fragments.social import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.* import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentPagerAdapter import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.google.firebase.analytics.FirebaseAnalytics import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.models.social.Group import com.habitrpg.android.habitica.ui.activities.GroupFormActivity import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment import com.habitrpg.android.habitica.ui.helpers.bindView import com.habitrpg.android.habitica.ui.helpers.resetViews import com.habitrpg.android.habitica.ui.viewmodels.GroupViewModel import com.habitrpg.android.habitica.ui.viewmodels.GroupViewType class GuildFragment : BaseMainFragment() { private val viewPager: androidx.viewpager.widget.ViewPager? by bindView(R.id.viewPager) internal lateinit var viewModel: GroupViewModel private var guildInformationFragment: GuildDetailFragment? = null private var chatFragment: ChatFragment? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { this.usesTabLayout = true this.hidesToolbar = true super.onCreateView(inflater, container, savedInstanceState) return inflater.inflate(R.layout.fragment_viewpager, container, false) } override fun injectFragment(component: UserComponent) { component.inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) resetViews() viewModel = ViewModelProviders.of(this).get(GroupViewModel::class.java) viewModel.groupViewType = GroupViewType.GUILD viewModel.getGroupData().observe(viewLifecycleOwner, Observer { setGroup(it) }) viewModel.getIsMemberData().observe(viewLifecycleOwner, Observer { activity?.invalidateOptionsMenu() }) arguments?.let { val args = GuildFragmentArgs.fromBundle(it) viewModel.setGroupID(args.groupID) } viewPager?.currentItem = 0 setViewPagerAdapter() setFragments() arguments?.let { val args = GuildFragmentArgs.fromBundle(it) viewPager?.currentItem = args.tabToOpen } if (viewModel.groupID == "f2db2a7f-13c5-454d-b3ee-ea1f5089e601") { context?.let { FirebaseAnalytics.getInstance(it).logEvent("opened_no_party_guild", null) } } viewModel.retrieveGroup { } } private fun setFragments() { val fragments = childFragmentManager.fragments for (childFragment in fragments) { if (childFragment is ChatFragment) { chatFragment = childFragment chatFragment?.viewModel = viewModel } if (childFragment is GuildDetailFragment) { guildInformationFragment = childFragment childFragment.viewModel = viewModel } } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { val guild = viewModel.getGroupData().value if (this.activity != null && guild != null) { if (viewModel.isMember) { if (this.user != null && this.user?.id == guild.leaderID) { this.activity?.menuInflater?.inflate(R.menu.guild_admin, menu) } else { this.activity?.menuInflater?.inflate(R.menu.guild_member, menu) } } else { this.activity?.menuInflater?.inflate(R.menu.guild_nonmember, menu) } } super.onCreateOptionsMenu(menu, inflater) } @Suppress("ReturnCount") override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_guild_join -> { viewModel.joinGroup() return true } R.id.menu_guild_leave -> { guildInformationFragment?.leaveGuild() return true } R.id.menu_guild_edit -> { this.displayEditForm() return true } R.id.action_reload -> { viewModel.retrieveGroup { } return true } R.id.menu_guild_refresh -> { viewModel.retrieveGroup { } return true } } return super.onOptionsItemSelected(item) } private fun setViewPagerAdapter() { val fragmentManager = childFragmentManager viewPager?.adapter = object : FragmentPagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) { override fun getItem(position: Int): Fragment { val fragment: Fragment? when (position) { 0 -> { guildInformationFragment = GuildDetailFragment.newInstance(viewModel) fragment = guildInformationFragment } 1 -> { chatFragment = ChatFragment() chatFragment?.viewModel = viewModel fragment = chatFragment } else -> fragment = Fragment() } return fragment ?: Fragment() } override fun getCount(): Int { return 2 } override fun getPageTitle(position: Int): CharSequence? { return when (position) { 0 -> context?.getString(R.string.guild) 1 -> context?.getString(R.string.chat) else -> "" } } } viewPager?.addOnPageChangeListener(object : androidx.viewpager.widget.ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { if (position == 1) { chatFragment?.setNavigatedToFragment() } } override fun onPageSelected(position: Int) { if (position == 1) { chatFragment?.setNavigatedToFragment() } } override fun onPageScrollStateChanged(state: Int) { /* no-on */ } }) tabLayout?.setupWithViewPager(viewPager) } private fun displayEditForm() { val bundle = Bundle() val guild = viewModel.getGroupData().value bundle.putString("groupID", guild?.id) bundle.putString("name", guild?.name) bundle.putString("description", guild?.description) bundle.putString("privacy", guild?.privacy) bundle.putString("leader", guild?.leaderID) bundle.putBoolean("leaderOnlyChallenges", guild?.leaderOnlyChallenges ?: true) val intent = Intent(activity, GroupFormActivity::class.java) intent.putExtras(bundle) intent.flags = Intent.FLAG_ACTIVITY_REORDER_TO_FRONT startActivityForResult(intent, GroupFormActivity.GROUP_FORM_ACTIVITY) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { GroupFormActivity.GROUP_FORM_ACTIVITY -> { if (resultCode == Activity.RESULT_OK) { val bundle = data?.extras viewModel.updateGroup(bundle) } } } } private fun setGroup(group: Group?) { this.activity?.invalidateOptionsMenu() if (group?.privacy == "public") { chatFragment?.autocompleteContext = "publicGuild" } else { chatFragment?.autocompleteContext = "privateGuild" } } }
gpl-3.0
dd16279f310110c9d8c34b4e7e06f298
35.199115
116
0.587843
5.368455
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/input/window/WindowHandler.kt
1
3848
package com.cout970.modeler.input.window import com.cout970.glutilities.texture.TextureLoader import com.cout970.glutilities.window.GLFWWindow import com.cout970.glutilities.window.WindowBuilder import com.cout970.modeler.NAME import com.cout970.modeler.core.log.Profiler import com.cout970.modeler.core.resource.ResourceLoader import com.cout970.modeler.util.ITickeable import com.cout970.modeler.util.VSyncTimer import com.cout970.vector.api.IVector2 import com.cout970.vector.extensions.vec2Of import org.lwjgl.glfw.GLFW.* import org.lwjgl.glfw.GLFWImage import org.lwjgl.opengl.GL11 import java.io.File import java.util.* /** * Created by cout970 on 2016/11/29. */ class WindowHandler : ITickeable { lateinit var window: GLFWWindow var viewport = Pair(vec2Of(0), vec2Of(1)) set(value) { GL11.glViewport(value.first.xi, value.first.yi, value.second.xi, value.second.yi) // GL11.glEnable(GL13.GL_MULTISAMPLE) field = value } private val viewportStack = Stack<Pair<IVector2, IVector2>>() private val vsync = VSyncTimer() fun create() { window = WindowBuilder.build { // screen = glfwGetMonitors()!![0] title = NAME size = vec2Of(800, 600) vSync = true properties[GLFW_STENCIL_BITS] = 24 // multisampling anti-aliasing makes a lot of artifacts on edges // properties[GLFW_SAMPLES] = 4 // glfwWindowHint( GLFW_DOUBLEBUFFER, GL_FALSE ) // properties[GLFW_DOUBLEBUFFER] = 0 properties[GLFW_CONTEXT_VERSION_MAJOR] = 3 properties[GLFW_CONTEXT_VERSION_MINOR] = 3 properties[GLFW_VISIBLE] = 0 // ths crashes OpenGL // properties[GLFW_OPENGL_PROFILE] = GLFW_OPENGL_CORE_PROFILE // properties[GLFW_OPENGL_FORWARD_COMPAT] = GL_TRUE } window.center() resetViewport() } fun loadIcon(rl: ResourceLoader) { val tex16 = TextureLoader.loadTexture(rl.readResource("assets/textures/icon16.png")) val tex32 = TextureLoader.loadTexture(rl.readResource("assets/textures/icon32.png")) val tex48 = TextureLoader.loadTexture(rl.readResource("assets/textures/icon48.png")) val icons = GLFWImage.malloc(3) icons.position(0) .width(tex16.size.xi) .height(tex16.size.yi) .pixels(tex16.bitMap) icons.position(1) .width(tex32.size.xi) .height(tex32.size.yi) .pixels(tex32.bitMap) icons.position(2) .width(tex48.size.xi) .height(tex48.size.yi) .pixels(tex48.bitMap) icons.position(0) glfwSetWindowIcon(window.id, icons) icons.free() } fun close() { glfwSetWindowShouldClose(window.id, true) } fun shouldClose() = window.shouldClose() fun updateTitle(projectName: String) { val projectPath = File(".").absolutePath window.setTitle("$projectName [$projectPath] - $NAME") } override fun tick() { Profiler.startSection("windows") Profiler.startSection("swapBuffers") window.swapBuffers() Profiler.nextSection("vsyncWait") vsync.waitIfNecessary() Profiler.endSection() Profiler.endSection() } fun resetViewport() { viewport = Pair(vec2Of(0), window.getFrameBufferSize()) } fun saveViewport(pos: IVector2, size: IVector2, funk: () -> Unit) { pushViewport(pos to size) funk() popViewport() } fun pushViewport(vp: Pair<IVector2, IVector2>) { viewportStack.push(viewport) viewport = vp } fun popViewport() { viewport = viewportStack.pop() } }
gpl-3.0
f5706f39744fed325b290782b19eab17
29.539683
93
0.62448
3.914547
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/user/Profile.kt
1
561
package com.habitrpg.android.habitica.models.user import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class Profile : RealmObject { @PrimaryKey var userId: String? = null internal var user: User? = null var name: String? = null var blurb: String? = null var imageUrl: String? = null @JvmOverloads constructor(name: String, blurb: String = "", imageUrl: String = "") { this.name = name this.blurb = blurb this.imageUrl = imageUrl } constructor() }
gpl-3.0
5829adb15f8edef350a207c5615554b7
21.375
74
0.625668
4.186567
false
false
false
false
fabmax/kool
kool-core/src/jvmMain/kotlin/de/fabmax/kool/platform/Lwjgl3Context.kt
1
10909
package de.fabmax.kool.platform import de.fabmax.kool.InputManager import de.fabmax.kool.KeyCode import de.fabmax.kool.KoolContext import de.fabmax.kool.math.clamp import de.fabmax.kool.math.min import de.fabmax.kool.modules.ksl.KslShader import de.fabmax.kool.pipeline.Pipeline import de.fabmax.kool.platform.gl.GlRenderBackend import de.fabmax.kool.platform.vk.VkRenderBackend import de.fabmax.kool.util.Viewport import org.lwjgl.glfw.GLFW.* import java.awt.Desktop import java.awt.image.BufferedImage import java.net.URI import java.util.* import java.util.concurrent.CompletableFuture import javax.imageio.ImageIO /** * @author fabmax */ class Lwjgl3Context(props: InitProps) : KoolContext() { override val assetMgr = JvmAssetManager(props, this) override val inputMgr: JvmInputManager val renderBackend: RenderBackend override val shaderGenerator get() = renderBackend.shaderGenerator override val windowWidth: Int get() = renderBackend.glfwWindow.framebufferWidth override val windowHeight: Int get() = renderBackend.glfwWindow.framebufferHeight override var isFullscreen: Boolean get() = renderBackend.glfwWindow.isFullscreen set(value) { renderBackend.glfwWindow.isFullscreen = value } var maxFrameRate = props.maxFrameRate var windowUnfocusedFrameRate = props.windowUnfocusedFrameRate private val mainThreadRunnables = mutableListOf<GpuThreadRunnable>() private var prevFrameTime = System.nanoTime() private object SysInfo : ArrayList<String>() { private var prevHeapSz = 1e9 private var prevHeapSzTime = 0L private var avgHeapGrowth = 0.0 fun set(api: String, deviceName: String) { clear() add(System.getProperty("java.vm.name") + " " + System.getProperty("java.version")) add(api) add(deviceName) add("") update() } fun update() { val rt = Runtime.getRuntime() val freeMem = rt.freeMemory() val totalMem = rt.totalMemory() val heapSz = (totalMem - freeMem) / 1024.0 / 1024.0 val t = System.currentTimeMillis() if (heapSz > prevHeapSz) { val growth = (heapSz - prevHeapSz) val dt = (t - prevHeapSzTime) / 1000.0 if (dt > 0.0) { val w = dt.clamp(0.0, 0.5) avgHeapGrowth = avgHeapGrowth * (1.0 - w) + (growth / dt) * w prevHeapSzTime = t } } prevHeapSz = heapSz set(3, String.format(Locale.ENGLISH, "Heap: %.1f MB (+%.1f MB/s)", heapSz, avgHeapGrowth)) } } init { renderBackend = if (props.renderBackend == Backend.VULKAN) { VkRenderBackend(props, this) } else { GlRenderBackend(props, this) } projCorrectionMatrixScreen.set(renderBackend.projCorrectionMatrixScreen) projCorrectionMatrixOffscreen.set(renderBackend.projCorrectionMatrixOffscreen) depthBiasMatrix.set(renderBackend.depthBiasMatrix) SysInfo.set(renderBackend.apiName, renderBackend.deviceName) inputMgr = JvmInputManager(renderBackend.glfwWindow.windowPtr, this) } fun setWindowTitle(windowTitle: String) = renderBackend.glfwWindow.setWindowTitle(windowTitle) fun setWindowIcon(icon: List<BufferedImage>) = renderBackend.glfwWindow.setWindowIcon(icon) override fun openUrl(url: String, sameWindow: Boolean) = Desktop.getDesktop().browse(URI(url)) override fun run() { while (!glfwWindowShouldClose(renderBackend.glfwWindow.windowPtr)) { SysInfo.update() glfwPollEvents() renderFrame() } renderBackend.cleanup(this) } internal fun renderFrame() { synchronized(mainThreadRunnables) { if (mainThreadRunnables.isNotEmpty()) { for (r in mainThreadRunnables) { r.r() r.future.complete(null) } mainThreadRunnables.clear() } } if (windowUnfocusedFrameRate > 0 || maxFrameRate > 0) { checkFrameRateLimits(prevFrameTime) } // determine time delta val time = System.nanoTime() val dt = (time - prevFrameTime) / 1e9 prevFrameTime = time // setup draw queues for all scenes / render passes render(dt) // execute draw queues engineStats.resetPerFrameCounts() renderBackend.drawFrame(this) } private fun checkFrameRateLimits(prevTime: Long) { val t = System.nanoTime() val dtFocused = if (maxFrameRate > 0) 1.0 / maxFrameRate else 0.0 val dtUnfocused = if (windowUnfocusedFrameRate > 0) 1.0 / windowUnfocusedFrameRate else dtFocused val dtCurrent = (t - prevTime) / 1e9 val dtCmp = if (isWindowFocused || inputMgr.isMouseOverWindow) dtFocused else dtUnfocused if (dtCmp > dtCurrent) { val untilFocused = t + ((dtFocused - dtCurrent) * 1e9).toLong() val untilUnfocused = t + ((dtUnfocused - dtCurrent) * 1e9).toLong() delayFrameRender(untilFocused, untilUnfocused) } } private fun delayFrameRender(untilFocused: Long, untilUnfocused: Long) { while (!glfwWindowShouldClose(renderBackend.glfwWindow.windowPtr)) { val t = System.nanoTime() val isFocused = isWindowFocused || inputMgr.isMouseOverWindow if ((isFocused && t >= untilFocused) || (!isFocused && t >= untilUnfocused)) { break } val until = if (isFocused) untilFocused else untilUnfocused val delayMillis = ((until - t) / 1e6).toLong() if (delayMillis > 5) { val sleep = min(5L, delayMillis) Thread.sleep(sleep) if (sleep == delayMillis) { break } glfwPollEvents() } } } override fun close() { renderBackend.close(this) } override fun generateKslShader(shader: KslShader, pipelineLayout: Pipeline.Layout) = renderBackend.generateKslShader(shader, pipelineLayout) override fun getSysInfos(): List<String> = SysInfo override fun getWindowViewport(result: Viewport) { renderBackend.getWindowViewport(result) } fun runOnMainThread(action: () -> Unit): CompletableFuture<Void> { synchronized(mainThreadRunnables) { val r = GpuThreadRunnable(action) mainThreadRunnables += r return r.future } } private class GpuThreadRunnable(val r: () -> Unit) { val future = CompletableFuture<Void>() } companion object { val KEY_CODE_MAP: Map<Int, KeyCode> = mutableMapOf( GLFW_KEY_LEFT_CONTROL to InputManager.KEY_CTRL_LEFT, GLFW_KEY_RIGHT_CONTROL to InputManager.KEY_CTRL_RIGHT, GLFW_KEY_LEFT_SHIFT to InputManager.KEY_SHIFT_LEFT, GLFW_KEY_RIGHT_SHIFT to InputManager.KEY_SHIFT_RIGHT, GLFW_KEY_LEFT_ALT to InputManager.KEY_ALT_LEFT, GLFW_KEY_RIGHT_ALT to InputManager.KEY_ALT_RIGHT, GLFW_KEY_LEFT_SUPER to InputManager.KEY_SUPER_LEFT, GLFW_KEY_RIGHT_SUPER to InputManager.KEY_SUPER_RIGHT, GLFW_KEY_ESCAPE to InputManager.KEY_ESC, GLFW_KEY_MENU to InputManager.KEY_MENU, GLFW_KEY_ENTER to InputManager.KEY_ENTER, GLFW_KEY_KP_ENTER to InputManager.KEY_NP_ENTER, GLFW_KEY_KP_DIVIDE to InputManager.KEY_NP_DIV, GLFW_KEY_KP_MULTIPLY to InputManager.KEY_NP_MUL, GLFW_KEY_KP_ADD to InputManager.KEY_NP_PLUS, GLFW_KEY_KP_SUBTRACT to InputManager.KEY_NP_MINUS, GLFW_KEY_BACKSPACE to InputManager.KEY_BACKSPACE, GLFW_KEY_TAB to InputManager.KEY_TAB, GLFW_KEY_DELETE to InputManager.KEY_DEL, GLFW_KEY_INSERT to InputManager.KEY_INSERT, GLFW_KEY_HOME to InputManager.KEY_HOME, GLFW_KEY_END to InputManager.KEY_END, GLFW_KEY_PAGE_UP to InputManager.KEY_PAGE_UP, GLFW_KEY_PAGE_DOWN to InputManager.KEY_PAGE_DOWN, GLFW_KEY_LEFT to InputManager.KEY_CURSOR_LEFT, GLFW_KEY_RIGHT to InputManager.KEY_CURSOR_RIGHT, GLFW_KEY_UP to InputManager.KEY_CURSOR_UP, GLFW_KEY_DOWN to InputManager.KEY_CURSOR_DOWN, GLFW_KEY_F1 to InputManager.KEY_F1, GLFW_KEY_F2 to InputManager.KEY_F2, GLFW_KEY_F3 to InputManager.KEY_F3, GLFW_KEY_F4 to InputManager.KEY_F4, GLFW_KEY_F5 to InputManager.KEY_F5, GLFW_KEY_F6 to InputManager.KEY_F6, GLFW_KEY_F7 to InputManager.KEY_F7, GLFW_KEY_F8 to InputManager.KEY_F8, GLFW_KEY_F9 to InputManager.KEY_F9, GLFW_KEY_F10 to InputManager.KEY_F10, GLFW_KEY_F11 to InputManager.KEY_F11, GLFW_KEY_F12 to InputManager.KEY_F12 ) } class InitProps(block: InitProps.() -> Unit = {}) { var width = 1600 var height = 900 var title = "Kool" var icon: List<BufferedImage> = DEFAULT_ICON?.let { listOf(it) } ?: emptyList() var monitor = -1 var isFullscreen = false var isWithHttpAssets = true var showWindowOnStart = true var isVsync = true var windowUnfocusedFrameRate = 0 var maxFrameRate = 0 var renderBackend = Backend.OPEN_GL var msaaSamples = 8 var localAssetPath = "./assets" var storageDir = "./.storage" val customFonts = mutableMapOf<String, String>() init { setWindowed(1600, 900) this.block() } fun setWindowed(width: Int, height: Int) { this.width = width this.height = height this.monitor = -1 this.isFullscreen = false } fun setFullscreen(monitor: Int = -1) { this.width = 1600 this.height = 900 this.monitor = monitor this.isFullscreen = true } companion object { val DEFAULT_ICON: BufferedImage? init { DEFAULT_ICON = try { ImageIO.read(ClassLoader.getSystemResourceAsStream("icon.png")) } catch (e: Exception) { null } } } } enum class Backend(val displayName: String) { VULKAN("Vulkan"), OPEN_GL("OpenGL") } }
apache-2.0
b3d0d82fa32760c0147548ce1452be07
35.122517
144
0.598313
4.296573
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/models/inventory/QuestBoss.kt
1
499
package com.habitrpg.android.habitica.models.inventory import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class QuestBoss : RealmObject() { @PrimaryKey var key: String? = null set(value) { field = value rage?.key = key } var name: String? = null var hp: Int = 0 var str: Float = 0.toFloat() var rage: QuestBossRage? = null fun hasRage(): Boolean { return rage?.value ?: 0.0 > 0.0 } }
gpl-3.0
501e469b1b09ab9c18511e514da5fc44
18.791667
54
0.589178
3.838462
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplacePrimitiveCastWithNumberConversionFix.kt
3
2802
// 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.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors.CAST_NEVER_SUCCEEDS import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.typeBinding.createTypeBinding import org.jetbrains.kotlin.types.typeUtil.isPrimitiveNumberType class ReplacePrimitiveCastWithNumberConversionFix( element: KtBinaryExpressionWithTypeRHS, private val targetShortType: String ) : KotlinQuickFixAction<KtBinaryExpressionWithTypeRHS>(element) { override fun getText() = KotlinBundle.message("replace.cast.with.call.to.to.0", targetShortType) override fun getFamilyName() = KotlinBundle.message("replace.cast.with.primitive.conversion.method") override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val factory = KtPsiFactory(element) val replaced = element.replaced(factory.createExpressionByPattern("$0.to$1()", element.left, targetShortType)) editor?.caretModel?.moveToOffset(replaced.endOffset) } companion object Factory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val element = CAST_NEVER_SUCCEEDS.cast(diagnostic).psiElement as? KtOperationReferenceExpression ?: return null val binaryExpression = element.parent as? KtBinaryExpressionWithTypeRHS ?: return null val context = binaryExpression.analyze() val expressionType = binaryExpression.left.getType(context) ?: return null if (!expressionType.isPrimitiveNumberType()) return null val castType = binaryExpression.right?.createTypeBinding(context)?.type ?: return null if (!castType.isPrimitiveNumberType()) return null return ReplacePrimitiveCastWithNumberConversionFix( binaryExpression, SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(castType) ) } } }
apache-2.0
32a4b305e94af808250d8982e8664245
49.053571
158
0.766952
4.873043
false
false
false
false
lucasgomes-eti/KotlinAndroidProjects
GitRepositories/app/src/main/java/com/lucasgomes/gitrepositories/GitApi.kt
1
1387
package com.lucasgomes.gitrepositories import com.google.gson.GsonBuilder import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import rx.Observable /** * Created by Lucas Gomes on 08/09/2017. */ class GitApi{ val service : GitApiDef init { val logging = HttpLoggingInterceptor() logging.level = HttpLoggingInterceptor.Level.BODY val httpClient = OkHttpClient.Builder() httpClient.addInterceptor(logging) val gson = GsonBuilder().setLenient().create() val retrofit = Retrofit.Builder() .baseUrl("https://api.github.com/") .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .client(httpClient.build()) .build() service = retrofit.create<GitApiDef>(GitApiDef::class.java) } fun loadRepositories() : Observable<RepositoryModel>?{ return service.listRepositories() .flatMap { repositoriesResults -> Observable.from(repositoriesResults.toList()) } .map { repository -> RepositoryModel(repository.id, repository.name, repository.description, repository.language) } } }
cc0-1.0
6d00508ead98096a8d18952f44f79e75
32.853659
131
0.694304
5.00722
false
false
false
false
Zhouzhouzhou/AndroidDemo
app/src/main/java/com/zhou/android/kotlin/SimpleListKotlinActivity.kt
1
1134
package com.zhou.android.kotlin import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.MenuItem import android.widget.ArrayAdapter import android.widget.ListView import com.zhou.android.R class SimpleListKotlinActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_kotin) val actionBar = supportActionBar actionBar?.title = "Kotlin" actionBar?.setDisplayHomeAsUpEnabled(true) var listView = findViewById<ListView>(R.id.listView) var data: ArrayList<String> = ArrayList() for (i in 0..20) { data.add("测试示例:" + i) } var adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, data) listView.adapter = adapter } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (android.R.id.home == item.itemId) { finish() return true } else return super.onOptionsItemSelected(item) } }
mit
b8e4089d1e25188e2456803bfaa66452
31.114286
103
0.673488
4.373541
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/search/KotlinSSDoubleColonExpressionTest.kt
3
1510
// 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.structuralsearch.search import org.jetbrains.kotlin.idea.structuralsearch.KotlinSSResourceInspectionTest class KotlinSSDoubleColonExpressionTest : KotlinSSResourceInspectionTest() { override fun getBasePath(): String = "doubleColonExpression" fun testClassLiteralExpression() { doTest("Int::class", """ fun foo(x: Any) { print(x) } class X { class Y { class Z { class Int } } } fun main() { foo(<warning descr="SSR">Int::class</warning>) foo(<warning descr="SSR">kotlin.Int::class</warning>) foo(<warning descr="SSR">X.Y.Z.Int::class</warning>) foo(<warning descr="SSR">Int::class</warning>.java) } """.trimIndent()) } fun testFqClassLiteralExpression() { doTest("kotlin.Int::class", """ fun foo(x: Any) { print(x) } class X { class Y { class Z { class Int } } } fun main() { foo(Int::class) foo(<warning descr="SSR">kotlin.Int::class</warning>) foo(X.Y.Z.Int::class) foo(Int::class.java) } """.trimIndent()) } fun testDotQualifiedExpression() { doTest("Int::class.java", """ fun foo(x: Any) { print(x) } fun main() { foo(Int::class) foo(<warning descr="SSR">Int::class.java</warning>) } """.trimIndent()) } }
apache-2.0
d35ab84567d82d5f7937345397f0beec
34.139535
120
0.595364
4.026667
false
true
false
false
DSteve595/Put.io
app/src/main/java/com/stevenschoen/putionew/files/FilesFragment.kt
1
13164
package com.stevenschoen.putionew.files import android.content.Context import android.os.Bundle import android.os.Parcelable import android.util.SparseArray import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentPagerAdapter import androidx.viewpager.widget.ViewPager import com.stevenschoen.putionew.PutioApplication import com.stevenschoen.putionew.R import com.stevenschoen.putionew.UIUtils import com.stevenschoen.putionew.analytics import com.stevenschoen.putionew.model.files.PutioFile import com.stevenschoen.putionew.putioApp import com.trello.rxlifecycle3.components.support.RxFragment import com.trello.rxlifecycle3.kotlin.bindToLifecycle import io.reactivex.android.schedulers.AndroidSchedulers import kotlinx.android.parcel.IgnoredOnParcel import kotlinx.android.parcel.Parcelize import retrofit2.HttpException import java.util.* open class FilesFragment : RxFragment() { open val canSelect = true open val choosingFolder = false open val showSearch = true open val showCreateFolder = true open val padForFab = true var callbacks: Callbacks? = null val pages = ArrayList<Page>() var currentPage: Page? = null get() = if (pagerView != null) { pages[pagerView!!.currentItem] } else { field } val fileListFragmentsAdapter by lazy { PageFragmentsPagerAdapter() } var pagerView: ViewPager? = null val pageChangeListener = PageChangeListener() var isSelecting = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) when { savedInstanceState != null -> { pages.addAll(savedInstanceState.getParcelableArrayList(STATE_PAGES)!!) if (savedInstanceState.containsKey(STATE_CURRENT_PAGE)) { currentPage = savedInstanceState.getParcelable(STATE_CURRENT_PAGE) } } arguments?.containsKey(EXTRA_FOLDER) == true -> { pages.add(Page.File(arguments!!.getParcelable(EXTRA_FOLDER)!!)) } else -> { pages.add(Page.File(PutioFile.makeRootFolder(resources))) } } fileListFragmentsAdapter.notifyDataSetChanged() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return inflater.inflate(R.layout.files, container, false).apply { pagerView = findViewById(R.id.files_pager) pagerView!!.adapter = fileListFragmentsAdapter pagerView!!.addOnPageChangeListener(pageChangeListener) if (UIUtils.hasLollipop()) { val folderFrontElevation = resources.getDimension(R.dimen.folder_front_elevation) pagerView!!.setPageTransformer(true) { page, position -> page.visibility = View.VISIBLE if (position <= -1) { page.translationZ = 0f } else { page.translationZ = (position + 1) * folderFrontElevation } if (position < 0) { if (position == -1f) { // To prevent the previous page from being clickable through the current page page.visibility = View.INVISIBLE } else { page.translationX = page.width * (-position * 0.5f) } } else { page.translationX = 0f } } } } } fun findPageWithIndexForFragment(fragment: FileListFragment<*>): IndexedValue<Page>? { val idToCompare = when (fragment) { is FolderFragment -> Page.File(fragment.folder).uniqueId is SearchFragment -> Page.Search(fragment.query, fragment.parentFolder).uniqueId else -> throw RuntimeException() } pages.forEachIndexed { index, page -> if (page.uniqueId == idToCompare) { return IndexedValue(index, page) } } return null } fun removePagesAfterIndex(position: Int, notifyAdapterIfChanged: Boolean) { var changed = false while (pages.lastIndex > position) { pages.removeAt(pages.lastIndex) changed = true } if (notifyAdapterIfChanged && changed) { fileListFragmentsAdapter.notifyDataSetChanged() } } fun addFile(file: PutioFile) { removePagesAfterIndex(pagerView!!.currentItem, false) val iter = pages.listIterator() var foundParentIndex = -1 for (existingPage in iter) { if (existingPage is Page.File) { if (existingPage.file.id == file.parentId) { foundParentIndex = iter.previousIndex() break } } } if (foundParentIndex != -1) { pages.add(foundParentIndex + 1, Page.File(file)) removePagesAfterIndex(foundParentIndex + 1, false) } else { pages.add(Page.File(file)) } fileListFragmentsAdapter.notifyDataSetChanged() pagerView!!.setCurrentItem(pages.lastIndex, true) if (file.isFolder) { analytics.logBrowsedToFolder(file) } else { analytics.logViewedFile(file) } } fun addSearch(query: String) { removePagesAfterIndex(pagerView!!.currentItem, false) pages.add(Page.Search(query, (pages.last() as Page.File).file)) fileListFragmentsAdapter.notifyDataSetChanged() pagerView!!.setCurrentItem(pages.lastIndex, true) analytics.logSearched(query) } fun goToFile(parentId: Long, id: Long) { var found = false var parentIndex = 0 pages.listIterator().apply { loop@ while (hasNext()) { val nextPage = next() when (nextPage) { is Page.Search -> { removePagesAfterIndex(previousIndex() - 1, false) break@loop } is Page.File -> { if (nextPage.file.id == parentId) { parentIndex = previousIndex() var targetIndex = parentIndex if (hasNext()) { val childPage = next() as Page.File if (childPage.file.id == id) { found = true targetIndex = previousIndex() } } removePagesAfterIndex(targetIndex, false) break@loop } } } } } if (!found) { removePagesAfterIndex(parentIndex, false) putioApp.putioUtils!!.restInterface.file(id) .bindToLifecycle(this) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ result -> addFile(result.file) }, { error -> if (error is HttpException && error.code() == 404) { Toast.makeText(context, R.string.filenotfound, Toast.LENGTH_LONG).show() } }) } fileListFragmentsAdapter.notifyDataSetChanged() pagerView!!.setCurrentItem(pages.lastIndex, true) } fun goBack(goToLastPageIfNotSelected: Boolean): Boolean { return when { pageChangeListener.isGoingBack -> { if (pagerView!!.currentItem == 0) { false } else { pageChangeListener.removeCount++ pagerView!!.setCurrentItem(pagerView!!.currentItem - 1, true) true } } goToLastPageIfNotSelected && pagerView!!.currentItem != pages.lastIndex -> { pagerView!!.setCurrentItem(pages.lastIndex, true) true } pages.size > 1 -> { pageChangeListener.isGoingBack = true pageChangeListener.removeCount++ pagerView!!.setCurrentItem(pages.lastIndex - 1, true) true } else -> false } } fun goBackToRoot(): Boolean { return when { pages.size == 1 -> false pageChangeListener.isGoingBack -> { pagerView!!.setCurrentItem(0, true) pageChangeListener.removeCount = (pages.size - 1) true } else -> { while (pageChangeListener.removeCount < (pages.size - 1)) { goBack(true) } true } } } override fun onAttachFragment(childFragment: Fragment) { super.onAttachFragment(childFragment) when (childFragment) { is FolderFragment, is SearchFragment -> { childFragment as FileListFragment<FileListFragment.Callbacks> childFragment.callbacks = object : FileListFragment.Callbacks { override fun onFileSelected(file: PutioFile) { if (!choosingFolder || file.isFolder) { addFile(file) } } override fun onBackSelected() { val pageWithIndex = findPageWithIndexForFragment(childFragment) pageWithIndex?.let { removePagesAfterIndex(it.index, true) } goBack(false) } override fun onSelectionStarted() { isSelecting = true callbacks?.onSelectionStarted() } override fun onSelectionEnded() { isSelecting = false callbacks?.onSelectionEnded() } } } is FileDetailsFragment -> { childFragment.onBackPressed = { goBack(false) } childFragment.castCallbacks = activity as PutioApplication.CastCallbacks } } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelableArrayList(STATE_PAGES, pages) outState.putParcelable(STATE_CURRENT_PAGE, currentPage) } companion object { const val STATE_PAGES = "pages" const val STATE_CURRENT_PAGE = "current_page" const val EXTRA_FOLDER = "folder" fun newInstance(context: Context, folder: PutioFile?): FilesFragment { val args = Bundle() if (folder != null) { args.putParcelable(EXTRA_FOLDER, folder) } return Fragment.instantiate(context, FilesFragment::class.java.name, args) as FilesFragment } } inner class PageFragmentsPagerAdapter : FragmentPagerAdapter( childFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT ) { private val fragments = SparseArray<Fragment>() override fun getItem(position: Int): Fragment { val page = pages[position] return when (page) { is Page.File -> { val file = page.file when { file.isFolder -> FolderFragment.newInstance(context!!, file, padForFab, canSelect, showSearch, showCreateFolder) else -> FileDetailsFragment.newInstance(context!!, file) } } is Page.Search -> { SearchFragment.newInstance(context!!, page.searchQuery, page.parentFolder, canSelect) } } } override fun instantiateItem(container: ViewGroup, position: Int): Any { val fragment = super.instantiateItem(container, position) as Fragment fragments.put(position, fragment) return fragment } override fun getItemPosition(obj: Any): Int { when (obj) { is FolderFragment -> { for ((index, page) in pages.withIndex()) { if (page is Page.File && page.file == obj.folder) { return index } } return POSITION_NONE } is SearchFragment -> { for ((index, page) in pages.withIndex()) { if (page is Page.Search && page.searchQuery == obj.query && page.parentFolder == obj.parentFolder) { return index } } return POSITION_NONE } else -> return POSITION_NONE } } override fun getItemId(position: Int): Long { return pages[position].uniqueId } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { super.destroyItem(container, position, `object`) if (position >= count) { childFragmentManager.beginTransaction() .remove(`object` as Fragment) .commitNowAllowingStateLoss() } fragments.removeAt(position) } override fun getCount() = pages.size fun getFragmentAt(position: Int) = fragments[position] } inner class PageChangeListener : ViewPager.SimpleOnPageChangeListener() { var removeCount = 0 var isGoingBack = false override fun onPageSelected(position: Int) { super.onPageSelected(position) callbacks?.onCurrentFileChanged() } override fun onPageScrollStateChanged(state: Int) { if (state == ViewPager.SCROLL_STATE_IDLE) { if (isGoingBack) { isGoingBack = false while (removeCount > 0) { pages.removeAt(pages.lastIndex) removeCount-- } fileListFragmentsAdapter.notifyDataSetChanged() } } } } sealed class Page : Parcelable { abstract val uniqueId: Long @Parcelize class File(val file: PutioFile) : Page() { @IgnoredOnParcel override val uniqueId = file.id } @Parcelize class Search(val searchQuery: String, val parentFolder: PutioFile) : Page() { @IgnoredOnParcel override val uniqueId = Objects.hash(searchQuery, parentFolder.id).toLong() } } interface Callbacks { fun onSelectionStarted() fun onSelectionEnded() fun onCurrentFileChanged() } }
mit
b268e5299407d66f007c4281f5d1382c
28.986333
124
0.630356
4.684698
false
false
false
false
androidx/androidx
wear/compose/compose-foundation/src/commonMain/kotlin/androidx/wear/compose/foundation/CurvedSize.kt
3
4602
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.foundation import androidx.compose.ui.geometry.Offset import androidx.compose.ui.layout.Measurable import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp /** * Specify the dimensions of the content to be restricted between the given bounds. * * @param minSweepDegrees the minimum angle (in degrees) for the content. * @param maxSweepDegrees the maximum angle (in degrees) for the content. * @param minThickness the minimum thickness (radial size) for the content. * @param maxThickness the maximum thickness (radial size) for the content. */ public fun CurvedModifier.sizeIn( /* @FloatRange(from = 0f, to = 360f) */ minSweepDegrees: Float = 0f, /* @FloatRange(from = 0f, to = 360f) */ maxSweepDegrees: Float = 360f, minThickness: Dp = 0.dp, maxThickness: Dp = Dp.Infinity, ) = this.then { child -> SizeWrapper( child, minSweepDegrees = minSweepDegrees, maxSweepDegrees = maxSweepDegrees, minThickness = minThickness, maxThickness = maxThickness ) } /** * Specify the dimensions (sweep and thickness) for the content. * * @sample androidx.wear.compose.foundation.samples.CurvedFixedSize * * @param sweepDegrees Indicates the sweep (angular size) of the content. * @param thickness Indicates the thickness (radial size) of the content. */ public fun CurvedModifier.size(sweepDegrees: Float, thickness: Dp) = sizeIn( /* @FloatRange(from = 0f, to = 360f) */ minSweepDegrees = sweepDegrees, /* @FloatRange(from = 0f, to = 360f) */ maxSweepDegrees = sweepDegrees, minThickness = thickness, maxThickness = thickness ) /** * Specify the sweep (angular size) for the content. * * @param sweepDegrees Indicates the sweep (angular size) of the content. */ public fun CurvedModifier.angularSize(sweepDegrees: Float) = sizeIn( minSweepDegrees = sweepDegrees, maxSweepDegrees = sweepDegrees ) /** * Specify the radialSize (thickness) for the content. * * @param thickness Indicates the thickness of the content. */ public fun CurvedModifier.radialSize(thickness: Dp) = sizeIn( minThickness = thickness, maxThickness = thickness ) internal class SizeWrapper( child: CurvedChild, val minSweepDegrees: Float, val maxSweepDegrees: Float, val minThickness: Dp, val maxThickness: Dp, ) : BaseCurvedChildWrapper(child) { private var minThicknessPx = 0f private var maxThicknessPx = 0f override fun CurvedMeasureScope.initializeMeasure( measurables: Iterator<Measurable> ) { minThicknessPx = minThickness.toPx() maxThicknessPx = maxThickness.toPx() with(wrapped) { // Call initializeMeasure on wrapper (while still having the MeasureScope scope) initializeMeasure(measurables) } } override fun doEstimateThickness(maxRadius: Float) = wrapped.estimateThickness(maxRadius).coerceIn(minThicknessPx, maxThicknessPx) override fun doRadialPosition( parentOuterRadius: Float, parentThickness: Float ): PartialLayoutInfo { val partialLayoutInfo = wrapped.radialPosition( parentOuterRadius, estimatedThickness ) return PartialLayoutInfo( partialLayoutInfo.sweepRadians.coerceIn( minSweepDegrees.toRadians(), maxSweepDegrees.toRadians() ), parentOuterRadius, thickness = estimatedThickness, measureRadius = partialLayoutInfo.measureRadius + partialLayoutInfo.outerRadius - parentOuterRadius ) } override fun doAngularPosition( parentStartAngleRadians: Float, parentSweepRadians: Float, centerOffset: Offset ): Float { wrapped.angularPosition( parentStartAngleRadians, parentSweepRadians = sweepRadians, centerOffset ) return parentStartAngleRadians } }
apache-2.0
78c36feccd8ca61914c720a50205e7cd
31.878571
92
0.696219
4.403828
false
false
false
false
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin-idea/tests/test/org/jetbrains/uast/test/kotlin/KotlinUastGenerationTest.kt
1
54102
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.test.kotlin import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.util.Key import com.intellij.openapi.util.Ref import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import com.intellij.psi.SyntaxTraverser import com.intellij.psi.util.parentOfType import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.UsefulTestCase import junit.framework.TestCase import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.utils.addToStdlib.cast import org.jetbrains.uast.* import org.jetbrains.uast.expressions.UInjectionHost import org.jetbrains.uast.generate.UParameterInfo import org.jetbrains.uast.generate.UastCodeGenerationPlugin import org.jetbrains.uast.generate.refreshed import org.jetbrains.uast.generate.replace import org.jetbrains.uast.kotlin.generate.KotlinUastElementFactory import org.jetbrains.uast.test.env.findElementByTextFromPsi import org.jetbrains.uast.test.env.findUElementByTextFromPsi import org.jetbrains.uast.visitor.UastVisitor import kotlin.test.fail as kfail class KotlinUastGenerationTest : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstance() private val psiFactory get() = KtPsiFactory(project) private val generatePlugin: UastCodeGenerationPlugin get() = UastCodeGenerationPlugin.byLanguage(KotlinLanguage.INSTANCE)!! private val uastElementFactory get() = generatePlugin.getElementFactory(myFixture.project) as KotlinUastElementFactory fun `test logical and operation with simple operands`() { val left = psiFactory.createExpression("true").toUElementOfType<UExpression>() ?: kfail("Cannot create left UExpression") val right = psiFactory.createExpression("false").toUElementOfType<UExpression>() ?: kfail("Cannot create right UExpression") val expression = uastElementFactory.createBinaryExpression(left, right, UastBinaryOperator.LOGICAL_AND, dummyContextFile()) ?: kfail("Cannot create expression") TestCase.assertEquals("true && false", expression.sourcePsi?.text) } fun `test logical and operation with simple operands with parenthesis`() { val left = psiFactory.createExpression("(true)").toUElementOfType<UExpression>() ?: kfail("Cannot create left UExpression") val right = psiFactory.createExpression("(false)").toUElementOfType<UExpression>() ?: kfail("Cannot create right UExpression") val expression = uastElementFactory.createFlatBinaryExpression(left, right, UastBinaryOperator.LOGICAL_AND, dummyContextFile()) ?: kfail("Cannot create expression") TestCase.assertEquals("true && false", expression.sourcePsi?.text) TestCase.assertEquals(""" UBinaryExpression (operator = &&) ULiteralExpression (value = true) ULiteralExpression (value = false) """.trimIndent(), expression.putIntoFunctionBody().asRecursiveLogString().trim()) } fun `test logical and operation with simple operands with parenthesis polyadic`() { val left = psiFactory.createExpression("(true && false)").toUElementOfType<UExpression>() ?: kfail("Cannot create left UExpression") val right = psiFactory.createExpression("(false)").toUElementOfType<UExpression>() ?: kfail("Cannot create right UExpression") val expression = uastElementFactory.createFlatBinaryExpression(left, right, UastBinaryOperator.LOGICAL_AND, dummyContextFile()) ?: kfail("Cannot create expression") TestCase.assertEquals("true && false && false", expression.sourcePsi?.text) TestCase.assertEquals(""" UBinaryExpression (operator = &&) UBinaryExpression (operator = &&) ULiteralExpression (value = null) ULiteralExpression (value = null) ULiteralExpression (value = null) """.trimIndent(), expression.asRecursiveLogString().trim()) } fun `test simple reference creating from variable`() { val context = dummyContextFile() val variable = uastElementFactory.createLocalVariable( "a", PsiType.INT, uastElementFactory.createNullLiteral(context), false, context ) val reference = uastElementFactory.createSimpleReference(variable, context) ?: kfail("cannot create reference") TestCase.assertEquals("a", reference.identifier) } fun `test simple reference by name`() { val reference = uastElementFactory.createSimpleReference("a", dummyContextFile()) TestCase.assertEquals("a", reference.identifier) } fun `test parenthesised expression`() { val expression = psiFactory.createExpression("a + b").toUElementOfType<UExpression>() ?: kfail("cannot create expression") val parenthesizedExpression = uastElementFactory.createParenthesizedExpression(expression, dummyContextFile()) ?: kfail("cannot create parenthesized expression") TestCase.assertEquals("(a + b)", parenthesizedExpression.sourcePsi?.text) } fun `test return expression`() { val expression = psiFactory.createExpression("a + b").toUElementOfType<UExpression>() ?: kfail("Cannot find plugin") val returnExpression = uastElementFactory.createReturnExpresion(expression, false, dummyContextFile()) TestCase.assertEquals("a + b", returnExpression.returnExpression?.asRenderString()) TestCase.assertEquals("return a + b", returnExpression.sourcePsi?.text) } fun `test variable declaration without type`() { val expression = psiFactory.createExpression("1 + 2").toUElementOfType<UExpression>() ?: kfail("cannot create variable declaration") val declaration = uastElementFactory.createLocalVariable("a", null, expression, false, dummyContextFile()) TestCase.assertEquals("var a = 1 + 2", declaration.sourcePsi?.text) } fun `test variable declaration with type`() { val expression = psiFactory.createExpression("b").toUElementOfType<UExpression>() ?: kfail("cannot create variable declaration") val declaration = uastElementFactory.createLocalVariable("a", PsiType.DOUBLE, expression, false, dummyContextFile()) TestCase.assertEquals("var a: kotlin.Double = b", declaration.sourcePsi?.text) } fun `test final variable declaration`() { val expression = psiFactory.createExpression("b").toUElementOfType<UExpression>() ?: kfail("cannot create variable declaration") val declaration = uastElementFactory.createLocalVariable("a", PsiType.DOUBLE, expression, true, dummyContextFile()) TestCase.assertEquals("val a: kotlin.Double = b", declaration.sourcePsi?.text) } fun `test final variable declaration with unique name`() { val expression = psiFactory.createExpression("b").toUElementOfType<UExpression>() ?: kfail("cannot create variable declaration") val declaration = uastElementFactory.createLocalVariable("a", PsiType.DOUBLE, expression, true, dummyContextFile()) TestCase.assertEquals("val a: kotlin.Double = b", declaration.sourcePsi?.text) TestCase.assertEquals(""" ULocalVariable (name = a) USimpleNameReferenceExpression (identifier = b) """.trimIndent(), declaration.asRecursiveLogString().trim()) } fun `test block expression`() { val statement1 = psiFactory.createExpression("System.out.println()").toUElementOfType<UExpression>() ?: kfail("cannot create statement") val statement2 = psiFactory.createExpression("System.out.println(2)").toUElementOfType<UExpression>() ?: kfail("cannot create statement") val block = uastElementFactory.createBlockExpression(listOf(statement1, statement2), dummyContextFile()) TestCase.assertEquals(""" { System.out.println() System.out.println(2) } """.trimIndent(), block.sourcePsi?.text ) } fun `test lambda expression`() { val statement = psiFactory.createExpression("System.out.println()").toUElementOfType<UExpression>() ?: kfail("cannot create statement") val lambda = uastElementFactory.createLambdaExpression( listOf( UParameterInfo(PsiType.INT, "a"), UParameterInfo(null, "b") ), statement, dummyContextFile() ) ?: kfail("cannot create lambda") TestCase.assertEquals("{ a: kotlin.Int, b -> System.out.println() }", lambda.sourcePsi?.text) TestCase.assertEquals(""" ULambdaExpression UParameter (name = a) UAnnotation (fqName = org.jetbrains.annotations.NotNull) UParameter (name = b) UAnnotation (fqName = null) UBlockExpression UQualifiedReferenceExpression UQualifiedReferenceExpression USimpleNameReferenceExpression (identifier = System) USimpleNameReferenceExpression (identifier = out) UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) UIdentifier (Identifier (println)) USimpleNameReferenceExpression (identifier = println, resolvesTo = null) """.trimIndent(), lambda.putIntoFunctionBody().asRecursiveLogString().trim()) } private fun UExpression.putIntoFunctionBody(): UExpression { val file = myFixture.configureByText("dummyFile.kt", "fun foo() { TODO() }") as KtFile val ktFunction = file.declarations.single { it.name == "foo" } as KtFunction val uMethod = ktFunction.toUElementOfType<UMethod>()!! return runWriteCommand { uMethod.uastBody.cast<UBlockExpression>().expressions.single().replace(this)!! } } private fun <T : UExpression> T.putIntoVarInitializer(): T { val file = myFixture.configureByText("dummyFile.kt", "val foo = TODO()") as KtFile val ktFunction = file.declarations.single { it.name == "foo" } as KtProperty val uMethod = ktFunction.toUElementOfType<UVariable>()!! return runWriteCommand { @Suppress("UNCHECKED_CAST") generatePlugin.replace(uMethod.uastInitializer!!, this, UExpression::class.java) as T } } private fun <T : UExpression> runWriteCommand(uExpression: () -> T): T { val result = Ref<T>() WriteCommandAction.runWriteCommandAction(project) { result.set(uExpression()) } return result.get() } fun `test lambda expression with explicit types`() { val statement = psiFactory.createExpression("System.out.println()").toUElementOfType<UExpression>() ?: kfail("cannot create statement") val lambda = uastElementFactory.createLambdaExpression( listOf( UParameterInfo(PsiType.INT, "a"), UParameterInfo(PsiType.DOUBLE, "b") ), statement, dummyContextFile() ) ?: kfail("cannot create lambda") TestCase.assertEquals("{ a: kotlin.Int, b: kotlin.Double -> System.out.println() }", lambda.sourcePsi?.text) TestCase.assertEquals(""" ULambdaExpression UParameter (name = a) UAnnotation (fqName = org.jetbrains.annotations.NotNull) UParameter (name = b) UAnnotation (fqName = org.jetbrains.annotations.NotNull) UBlockExpression UQualifiedReferenceExpression UQualifiedReferenceExpression USimpleNameReferenceExpression (identifier = System) USimpleNameReferenceExpression (identifier = out) UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) UIdentifier (Identifier (println)) USimpleNameReferenceExpression (identifier = println, resolvesTo = null) """.trimIndent(), lambda.putIntoFunctionBody().asRecursiveLogString().trim()) } fun `test lambda expression with simplified block body with context`() { val r = psiFactory.createExpression("return \"10\"").toUElementOfType<UExpression>() ?: kfail("cannot create return") val block = uastElementFactory.createBlockExpression(listOf(r), dummyContextFile()) val lambda = uastElementFactory.createLambdaExpression(listOf(UParameterInfo(null, "a")), block, dummyContextFile()) ?: kfail("cannot create lambda") TestCase.assertEquals("""{ a -> "10" }""".trimMargin(), lambda.sourcePsi?.text) TestCase.assertEquals(""" ULambdaExpression UParameter (name = a) UAnnotation (fqName = org.jetbrains.annotations.NotNull) UBlockExpression UReturnExpression ULiteralExpression (value = "10") """.trimIndent(), lambda.putIntoVarInitializer().asRecursiveLogString().trim()) } fun `test function argument replacement`() { val file = myFixture.configureByText( "test.kt", """ fun f(a: Any){} fun main(){ f(a) } """.trimIndent() ) val expression = file.findUElementByTextFromPsi<UCallExpression>("f(a)") val newArgument = psiFactory.createExpression("b").toUElementOfType<USimpleNameReferenceExpression>() ?: kfail("cannot create reference") WriteCommandAction.runWriteCommandAction(project) { TestCase.assertNotNull(expression.valueArguments[0].replace(newArgument)) } val updated = expression.refreshed() ?: kfail("cannot update expression") TestCase.assertEquals("f", updated.methodName) TestCase.assertTrue(updated.valueArguments[0] is USimpleNameReferenceExpression) TestCase.assertEquals("b", (updated.valueArguments[0] as USimpleNameReferenceExpression).identifier) TestCase.assertEquals(""" UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) UIdentifier (Identifier (f)) USimpleNameReferenceExpression (identifier = f, resolvesTo = null) USimpleNameReferenceExpression (identifier = b) """.trimIndent(), updated.asRecursiveLogString().trim()) } fun `test suggested name`() { val expression = psiFactory.createExpression("f(a) + 1").toUElementOfType<UExpression>() ?: kfail("cannot create expression") val variable = uastElementFactory.createLocalVariable(null, PsiType.INT, expression, true, dummyContextFile()) TestCase.assertEquals("val i: kotlin.Int = f(a) + 1", variable.sourcePsi?.text) TestCase.assertEquals(""" ULocalVariable (name = i) UBinaryExpression (operator = +) UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) UIdentifier (Identifier (f)) USimpleNameReferenceExpression (identifier = <anonymous class>, resolvesTo = null) USimpleNameReferenceExpression (identifier = a) ULiteralExpression (value = null) """.trimIndent(), variable.asRecursiveLogString().trim()) } fun `test method call generation with receiver`() { val receiver = psiFactory.createExpression(""""10"""").toUElementOfType<UExpression>() ?: kfail("cannot create receiver") val arg1 = psiFactory.createExpression("1").toUElementOfType<UExpression>() ?: kfail("cannot create arg1") val arg2 = psiFactory.createExpression("2").toUElementOfType<UExpression>() ?: kfail("cannot create arg2") val methodCall = uastElementFactory.createCallExpression( receiver, "substring", listOf(arg1, arg2), null, UastCallKind.METHOD_CALL ) ?: kfail("cannot create call") TestCase.assertEquals(""""10".substring(1,2)""", methodCall.uastParent?.sourcePsi?.text) TestCase.assertEquals(""" UQualifiedReferenceExpression ULiteralExpression (value = "10") UCallExpression (kind = UastCallKind(name='method_call'), argCount = 2)) UIdentifier (Identifier (substring)) USimpleNameReferenceExpression (identifier = <anonymous class>, resolvesTo = null) ULiteralExpression (value = null) ULiteralExpression (value = null) """.trimIndent(), methodCall.uastParent?.asRecursiveLogString()?.trim() ) } fun `test method call generation without receiver`() { val arg1 = psiFactory.createExpression("1").toUElementOfType<UExpression>() ?: kfail("cannot create arg1") val arg2 = psiFactory.createExpression("2").toUElementOfType<UExpression>() ?: kfail("cannot create arg2") val methodCall = uastElementFactory.createCallExpression( null, "substring", listOf(arg1, arg2), null, UastCallKind.METHOD_CALL ) ?: kfail("cannot create call") TestCase.assertEquals("""substring(1,2)""", methodCall.sourcePsi?.text) } fun `test method call generation with generics restoring`() { val arrays = psiFactory.createExpression("java.util.Arrays").toUElementOfType<UExpression>() ?: kfail("cannot create receiver") val methodCall = uastElementFactory.createCallExpression( arrays, "asList", listOf(), createTypeFromText("java.util.List<java.lang.String>", null), UastCallKind.METHOD_CALL, dummyContextFile() ) ?: kfail("cannot create call") TestCase.assertEquals("java.util.Arrays.asList<kotlin.String>()", methodCall.uastParent?.sourcePsi?.text) } fun `test method call generation with generics restoring 2 parameters`() { val collections = psiFactory.createExpression("java.util.Collections").toUElementOfType<UExpression>() ?: kfail("cannot create receiver") TestCase.assertEquals("java.util.Collections", collections.asRenderString()) val methodCall = uastElementFactory.createCallExpression( collections, "emptyMap", listOf(), createTypeFromText( "java.util.Map<java.lang.String, java.lang.Integer>", null ), UastCallKind.METHOD_CALL, dummyContextFile() ) ?: kfail("cannot create call") TestCase.assertEquals("emptyMap<kotlin.String,kotlin.Int>()", methodCall.sourcePsi?.text) TestCase.assertEquals("java.util.Collections.emptyMap<kotlin.String,kotlin.Int>()", methodCall.sourcePsi?.parent?.text) TestCase.assertEquals( """ UQualifiedReferenceExpression UQualifiedReferenceExpression UQualifiedReferenceExpression USimpleNameReferenceExpression (identifier = java) USimpleNameReferenceExpression (identifier = util) USimpleNameReferenceExpression (identifier = Collections) UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) UIdentifier (Identifier (emptyMap)) USimpleNameReferenceExpression (identifier = emptyMap, resolvesTo = null) """.trimIndent(), methodCall.uastParent?.asRecursiveLogString()?.trim() ) } private fun dummyContextFile(): KtFile = myFixture.configureByText("file.kt", "fun foo() {}") as KtFile fun `test method call generation with generics restoring 1 parameter with 1 existing`() { val a = psiFactory.createExpression("A").toUElementOfType<UExpression>() ?: kfail("cannot create a receiver") val param = psiFactory.createExpression("\"a\"").toUElementOfType<UExpression>() ?: kfail("cannot create a parameter") val methodCall = uastElementFactory.createCallExpression( a, "kek", listOf(param), createTypeFromText( "java.util.Map<java.lang.String, java.lang.Integer>", null ), UastCallKind.METHOD_CALL, dummyContextFile() ) ?: kfail("cannot create call") TestCase.assertEquals("A.kek<kotlin.String,kotlin.Int>(\"a\")", methodCall.sourcePsi?.parent?.text) TestCase.assertEquals( """ UQualifiedReferenceExpression USimpleNameReferenceExpression (identifier = A) UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) UIdentifier (Identifier (kek)) USimpleNameReferenceExpression (identifier = <anonymous class>, resolvesTo = null) ULiteralExpression (value = "a") """.trimIndent(), methodCall.uastParent?.asRecursiveLogString()?.trim() ) } fun `test callable reference generation with receiver`() { val receiver = uastElementFactory.createQualifiedReference("java.util.Arrays", myFixture.file) ?: kfail("failed to create receiver") val methodReference = uastElementFactory.createCallableReferenceExpression(receiver, "asList", myFixture.file) ?: kfail("failed to create method reference") TestCase.assertEquals(methodReference.sourcePsi?.text, "java.util.Arrays::asList") } fun `test callable reference generation without receiver`() { val methodReference = uastElementFactory.createCallableReferenceExpression(null, "asList", myFixture.file) ?: kfail("failed to create method reference") TestCase.assertEquals(methodReference.sourcePsi?.text, "::asList") } //not implemented (currently we dont perform resolve in code generating) fun `ignore method call generation with generics restoring 1 parameter with 1 unused `() { val aClassFile = myFixture.configureByText( "A.kt", """ object A { fun <T1, T2, T3> kek(a: T1): Map<T1, T3> { return TODO(); } } """.trimIndent() ) val a = psiFactory.createExpression("A").toUElementOfType<UExpression>() ?: kfail("cannot create a receiver") val param = psiFactory.createExpression("\"a\"").toUElementOfType<UExpression>() ?: kfail("cannot create a parameter") val methodCall = uastElementFactory.createCallExpression( a, "kek", listOf(param), createTypeFromText( "java.util.Map<java.lang.String, java.lang.Integer>", null ), UastCallKind.METHOD_CALL, aClassFile ) ?: kfail("cannot create call") TestCase.assertEquals("A.<String, Object, Integer>kek(\"a\")", methodCall.sourcePsi?.text) } fun `test method call generation with generics with context`() { val file = myFixture.configureByText("file.kt", """ class A { fun <T> method(): List<T> { TODO() } } fun main(){ val a = A() println(a) } """.trimIndent() ) as KtFile val reference = file.findUElementByTextFromPsi<UElement>("println(a)", strict = true) .findElementByTextFromPsi<UReferenceExpression>("a") val callExpression = uastElementFactory.createCallExpression( reference, "method", emptyList(), createTypeFromText( "java.util.List<java.lang.Integer>", null ), UastCallKind.METHOD_CALL, context = reference.sourcePsi ) ?: kfail("cannot create method call") TestCase.assertEquals("a.method<kotlin.Int>()", callExpression.uastParent?.sourcePsi?.text) TestCase.assertEquals(""" UQualifiedReferenceExpression USimpleNameReferenceExpression (identifier = a) UCallExpression (kind = UastCallKind(name='method_call'), argCount = 0)) UIdentifier (Identifier (method)) USimpleNameReferenceExpression (identifier = method, resolvesTo = null) """.trimIndent(), callExpression.uastParent?.asRecursiveLogString()?.trim() ) } fun `test method call generation without generics with context`() { val file = myFixture.configureByText("file.kt", """ class A { fun <T> method(t: T): List<T> { TODO() } } fun main(){ val a = A() println(a) } """.trimIndent() ) as KtFile val reference = file.findUElementByTextFromPsi<UElement>("println(a)") .findElementByTextFromPsi<UReferenceExpression>("a") val callExpression = uastElementFactory.createCallExpression( reference, "method", listOf(uastElementFactory.createIntLiteral(1, null)), createTypeFromText( "java.util.List<java.lang.Integer>", null ), UastCallKind.METHOD_CALL, context = reference.sourcePsi ) ?: kfail("cannot create method call") TestCase.assertEquals("a.method(1)", callExpression.uastParent?.sourcePsi?.text) TestCase.assertEquals(""" UQualifiedReferenceExpression USimpleNameReferenceExpression (identifier = a) UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) UIdentifier (Identifier (method)) USimpleNameReferenceExpression (identifier = method, resolvesTo = null) ULiteralExpression (value = 1) """.trimIndent(), callExpression.uastParent?.asRecursiveLogString()?.trim() ) } fun `test replace lambda implicit return value`() { val file = myFixture.configureByText( "file.kt", """ fun main(){ val a: (Int) -> String = { println(it) println(2) "abc" } } """.trimIndent() ) as KtFile val uLambdaExpression = file.findUElementByTextFromPsi<UInjectionHost>("\"abc\"") .getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda") val expressions = uLambdaExpression.body.cast<UBlockExpression>().expressions UsefulTestCase.assertSize(3, expressions) val uReturnExpression = expressions.last() as UReturnExpression val newStringLiteral = uastElementFactory.createStringLiteralExpression("def", file) val defReturn = runWriteCommand { uReturnExpression.replace(newStringLiteral) ?: kfail("cant replace") } val uLambdaExpression2 = defReturn.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda") TestCase.assertEquals("{\n println(it)\n println(2)\n \"def\"\n }", uLambdaExpression2.sourcePsi?.text) TestCase.assertEquals( """ ULambdaExpression UParameter (name = it) UBlockExpression UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) UIdentifier (Identifier (println)) USimpleNameReferenceExpression (identifier = println, resolvesTo = null) USimpleNameReferenceExpression (identifier = it) UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) UIdentifier (Identifier (println)) USimpleNameReferenceExpression (identifier = println, resolvesTo = null) ULiteralExpression (value = 2) UReturnExpression ULiteralExpression (value = "def") """.trimIndent(), uLambdaExpression2.asRecursiveLogString().trim() ) } private class UserDataChecker { private val storedData = Any() private val KEY = Key.create<Any>("testKey") private lateinit var uniqueStringLiteralText: String fun store(uElement: UInjectionHost) { val psiElement = uElement.sourcePsi as KtStringTemplateExpression uniqueStringLiteralText = psiElement.text psiElement.putCopyableUserData(KEY, storedData) } fun checkUserDataAlive(uElement: UElement) { val psiElements = uElement.let { SyntaxTraverser.psiTraverser(it.sourcePsi) } .filter(KtStringTemplateExpression::class.java) .filter { it.text == uniqueStringLiteralText }.toList() UsefulTestCase.assertNotEmpty(psiElements) UsefulTestCase.assertTrue("uElement still should keep the userdata", psiElements.any { storedData === it!!.getCopyableUserData(KEY) }) } } fun `test add intermediate returns to lambda`() { val file = myFixture.configureByText( "file.kt", """ fun main(){ val a: (Int) -> String = lname@{ println(it) println(2) "abc" } } """.trimIndent() ) as KtFile val aliveChecker = UserDataChecker() val uLambdaExpression = file.findUElementByTextFromPsi<UInjectionHost>("\"abc\"") .also(aliveChecker::store) .getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda") val oldBlockExpression = uLambdaExpression.body.cast<UBlockExpression>() UsefulTestCase.assertSize(3, oldBlockExpression.expressions) val conditionalExit = with(uastElementFactory) { createIfExpression( createBinaryExpression( createSimpleReference("it", uLambdaExpression.sourcePsi), createIntLiteral(3, uLambdaExpression.sourcePsi), UastBinaryOperator.GREATER, uLambdaExpression.sourcePsi )!!, createReturnExpresion( createStringLiteralExpression("exit", uLambdaExpression.sourcePsi), true, uLambdaExpression.sourcePsi ), null, uLambdaExpression.sourcePsi )!! } val newBlockExpression = uastElementFactory.createBlockExpression( listOf(conditionalExit) + oldBlockExpression.expressions, uLambdaExpression.sourcePsi ) aliveChecker.checkUserDataAlive(newBlockExpression) val uLambdaExpression2 = runWriteCommand { oldBlockExpression.replace(newBlockExpression) ?: kfail("cant replace") }.getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda") aliveChecker.checkUserDataAlive(uLambdaExpression2) TestCase.assertEquals( """ lname@{ if (it > 3) return@lname "exit" println(it) println(2) "abc" } """.trimIndent(), uLambdaExpression2.sourcePsi?.parent?.text ) TestCase.assertEquals( """ ULambdaExpression UParameter (name = it) UBlockExpression UIfExpression UBinaryExpression (operator = >) USimpleNameReferenceExpression (identifier = it) ULiteralExpression (value = 3) UReturnExpression ULiteralExpression (value = "exit") UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) UIdentifier (Identifier (println)) USimpleNameReferenceExpression (identifier = println, resolvesTo = null) USimpleNameReferenceExpression (identifier = it) UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) UIdentifier (Identifier (println)) USimpleNameReferenceExpression (identifier = println, resolvesTo = null) ULiteralExpression (value = 2) UReturnExpression ULiteralExpression (value = "abc") """.trimIndent(), uLambdaExpression2.asRecursiveLogString().trim() ) } fun `test converting lambda to if`() { val file = myFixture.configureByText( "file.kt", """ fun foo(call: (Int) -> String): String = call.invoke(2) fun main() { foo { println(it) println(2) "abc" } } } """.trimIndent() ) as KtFile val aliveChecker = UserDataChecker() val uLambdaExpression = file.findUElementByTextFromPsi<UInjectionHost>("\"abc\"") .also { aliveChecker.store(it) } .getParentOfType<ULambdaExpression>() ?: kfail("cant get lambda") val oldBlockExpression = uLambdaExpression.body.cast<UBlockExpression>() aliveChecker.checkUserDataAlive(oldBlockExpression) val newLambda = with(uastElementFactory) { createLambdaExpression( listOf(UParameterInfo(null, "it")), createIfExpression( createBinaryExpression( createSimpleReference("it", uLambdaExpression.sourcePsi), createIntLiteral(3, uLambdaExpression.sourcePsi), UastBinaryOperator.GREATER, uLambdaExpression.sourcePsi )!!, oldBlockExpression, createReturnExpresion( createStringLiteralExpression("exit", uLambdaExpression.sourcePsi), true, uLambdaExpression.sourcePsi ), uLambdaExpression.sourcePsi )!!.also { aliveChecker.checkUserDataAlive(it) }, uLambdaExpression.sourcePsi )!! } aliveChecker.checkUserDataAlive(newLambda) val uLambdaExpression2 = runWriteCommand { uLambdaExpression.replace(newLambda) ?: kfail("cant replace") } TestCase.assertEquals( """ { it -> if (it > 3) { println(it) println(2) "abc" } else return@foo "exit" } """.trimIndent(), uLambdaExpression2.sourcePsi?.parent?.text ) TestCase.assertEquals( """ ULambdaExpression UParameter (name = it) UAnnotation (fqName = null) UBlockExpression UReturnExpression UIfExpression UBinaryExpression (operator = >) USimpleNameReferenceExpression (identifier = it) ULiteralExpression (value = 3) UBlockExpression UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) UIdentifier (Identifier (println)) USimpleNameReferenceExpression (identifier = println, resolvesTo = null) USimpleNameReferenceExpression (identifier = it) UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) UIdentifier (Identifier (println)) USimpleNameReferenceExpression (identifier = println, resolvesTo = null) ULiteralExpression (value = 2) ULiteralExpression (value = "abc") UReturnExpression ULiteralExpression (value = "exit") """.trimIndent(), uLambdaExpression2.asRecursiveLogString().trim() ) aliveChecker.checkUserDataAlive(uLambdaExpression2) } fun `test removing unnecessary type parameters while replace`() { val aClassFile = myFixture.configureByText( "A.kt", """ class A { fun <T> method():List<T> = TODO() } """.trimIndent() ) val reference = psiFactory.createExpression("a") .toUElementOfType<UReferenceExpression>() ?: kfail("cannot create reference expression") val callExpression = uastElementFactory.createCallExpression( reference, "method", emptyList(), createTypeFromText( "java.util.List<java.lang.Integer>", null ), UastCallKind.METHOD_CALL, context = aClassFile ) ?: kfail("cannot create method call") val listAssigment = myFixture.addFileToProject("temp.kt", """ fun foo(kek: List<Int>) { val list: List<Int> = kek } """.trimIndent()).findUElementByTextFromPsi<UVariable>("val list: List<Int> = kek") WriteCommandAction.runWriteCommandAction(project) { val methodCall = listAssigment.uastInitializer?.replace(callExpression) ?: kfail("cannot replace!") // originally result expected be `a.method()` but we expect to clean up type arguments in other plase TestCase.assertEquals("a.method<Int>()", methodCall.sourcePsi?.parent?.text) } } fun `test create if`() { val condition = psiFactory.createExpression("true").toUElementOfType<UExpression>() ?: kfail("cannot create condition") val thenBranch = psiFactory.createBlock("{a(b);}").toUElementOfType<UExpression>() ?: kfail("cannot create then branch") val elseBranch = psiFactory.createExpression("c++").toUElementOfType<UExpression>() ?: kfail("cannot create else branch") val ifExpression = uastElementFactory.createIfExpression(condition, thenBranch, elseBranch, dummyContextFile()) ?: kfail("cannot create if expression") TestCase.assertEquals("if (true) {\n { a(b); }\n } else c++", ifExpression.sourcePsi?.text) } fun `test qualified reference`() { val reference = uastElementFactory.createQualifiedReference("java.util.List", myFixture.file) TestCase.assertEquals("java.util.List", reference?.sourcePsi?.text) } fun `test build lambda from returning a variable`() { val context = dummyContextFile() val localVariable = uastElementFactory.createLocalVariable("a", null, uastElementFactory.createNullLiteral(context), true, context) val declarationExpression = uastElementFactory.createDeclarationExpression(listOf(localVariable), context) val returnExpression = uastElementFactory.createReturnExpresion( uastElementFactory.createSimpleReference(localVariable, context), false, context ) val block = uastElementFactory.createBlockExpression(listOf(declarationExpression, returnExpression), context) TestCase.assertEquals(""" UBlockExpression UDeclarationsExpression ULocalVariable (name = a) ULiteralExpression (value = null) UReturnExpression USimpleNameReferenceExpression (identifier = a) """.trimIndent(), block.asRecursiveLogString().trim()) val lambda = uastElementFactory.createLambdaExpression(listOf(), block, context) ?: kfail("cannot create lambda expression") TestCase.assertEquals("{ val a = null\na }", lambda.sourcePsi?.text) TestCase.assertEquals(""" ULambdaExpression UBlockExpression UDeclarationsExpression ULocalVariable (name = a) ULiteralExpression (value = null) UReturnExpression USimpleNameReferenceExpression (identifier = a) """.trimIndent(), lambda.putIntoVarInitializer().asRecursiveLogString().trim()) } fun `test expand oneline lambda`() { val context = dummyContextFile() val parameters = listOf(UParameterInfo(PsiType.INT, "a")) val oneLineLambda = with(uastElementFactory) { createLambdaExpression( parameters, createBinaryExpression( createSimpleReference("a", context), createSimpleReference("a", context), UastBinaryOperator.PLUS, context )!!, context )!! }.putIntoVarInitializer() val lambdaReturn = (oneLineLambda.body as UBlockExpression).expressions.single() val lambda = with(uastElementFactory) { createLambdaExpression( parameters, createBlockExpression( listOf( createCallExpression( null, "println", listOf(createSimpleReference("a", context)), PsiType.VOID, UastCallKind.METHOD_CALL, context )!!, lambdaReturn ), context ), context )!! } TestCase.assertEquals("{ a: kotlin.Int -> println(a)\na + a }", lambda.sourcePsi?.text) TestCase.assertEquals(""" ULambdaExpression UParameter (name = a) UAnnotation (fqName = org.jetbrains.annotations.NotNull) UBlockExpression UCallExpression (kind = UastCallKind(name='method_call'), argCount = 1)) UIdentifier (Identifier (println)) USimpleNameReferenceExpression (identifier = println, resolvesTo = null) USimpleNameReferenceExpression (identifier = a) UReturnExpression UBinaryExpression (operator = +) USimpleNameReferenceExpression (identifier = a) USimpleNameReferenceExpression (identifier = a) """.trimIndent(), lambda.putIntoVarInitializer().asRecursiveLogString().trim()) } fun `test moving lambda from parenthesis`() { myFixture.configureByText("myFile.kt", """ fun a(p: (Int) -> Unit) {} """.trimIndent()) val lambdaExpression = uastElementFactory.createLambdaExpression( emptyList(), uastElementFactory.createNullLiteral(null), null ) ?: kfail("Cannot create lambda") val callExpression = uastElementFactory.createCallExpression( null, "a", listOf(lambdaExpression), null, UastCallKind.METHOD_CALL, myFixture.file ) ?: kfail("Cannot create method call") TestCase.assertEquals("""a{ null }""", callExpression.sourcePsi?.text) } fun `test saving space after receiver`() { myFixture.configureByText("myFile.kt", """ fun f() { a .b() .c<caret>() .d() } """.trimIndent()) val receiver = myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtDotQualifiedExpression>().toUElementOfType<UExpression>() ?: kfail("Cannot find UExpression") val callExpression = uastElementFactory.createCallExpression( receiver, "e", listOf(), null, UastCallKind.METHOD_CALL, null ) ?: kfail("Cannot create call expression") TestCase.assertEquals( """ a .b() .c() .e() """.trimIndent(), callExpression.sourcePsi?.parentOfType<KtDotQualifiedExpression>()?.text ) } fun `test initialize field`() { val psiFile = myFixture.configureByText("MyClass.kt", """ class My<caret>Class { var field: String? fun method(value: String) { } } """.trimIndent()) val uClass = myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtClass>().toUElementOfType<UClass>() ?: kfail("Cannot find UClass") val uField = uClass.fields.firstOrNull() ?: kfail("Cannot find field") val uParameter = uClass.methods.find { it.name == "method"}?.uastParameters?.firstOrNull() ?: kfail("Cannot find parameter") WriteCommandAction.runWriteCommandAction(project) { generatePlugin.initializeField(uField, uParameter) } TestCase.assertEquals(""" class MyClass { var field: String? fun method(value: String) { field = value } } """.trimIndent(), psiFile.text) } fun `test initialize field with same name`() { val psiFile = myFixture.configureByText("MyClass.kt", """ class My<caret>Class { var field: String? fun method(field: String) { } } """.trimIndent()) val uClass = myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtClass>().toUElementOfType<UClass>() ?: kfail("Cannot find UClass") val uField = uClass.fields.firstOrNull() ?: kfail("Cannot find field") val uParameter = uClass.methods.find { it.name == "method"}?.uastParameters?.firstOrNull() ?: kfail("Cannot find parameter") WriteCommandAction.runWriteCommandAction(project) { generatePlugin.initializeField(uField, uParameter) } TestCase.assertEquals(""" class MyClass { var field: String? fun method(field: String) { this.field = field } } """.trimIndent(), psiFile.text) } fun `test initialize field in constructor`() { val psiFile = myFixture.configureByText("MyClass.kt", """ class My<caret>Class() { constructor(value: String): this() { } var field: String? } """.trimIndent()) val uClass = myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtClass>().toUElementOfType<UClass>() ?: kfail("Cannot find UClass") val uField = uClass.fields.firstOrNull() ?: kfail("Cannot find field") val uParameter = uClass.methods.find { it.isConstructor && it.uastParameters.isNotEmpty() }?.uastParameters?.firstOrNull() ?: kfail("Cannot find parameter") WriteCommandAction.runWriteCommandAction(project) { generatePlugin.initializeField(uField, uParameter) } TestCase.assertEquals(""" class MyClass() { constructor(value: String): this() { field = value } var field: String? } """.trimIndent(), psiFile.text) } fun `test initialize field in primary constructor`() { val psiFile = myFixture.configureByText("MyClass.kt", """ class My<caret>Class(value: String) { val field: String } """.trimIndent()) val uClass = myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtClass>().toUElementOfType<UClass>() ?: kfail("Cannot find UClass") val uField = uClass.fields.firstOrNull() ?: kfail("Cannot find field") val uParameter = uClass.methods.find { it.uastParameters.isNotEmpty() }?.uastParameters?.firstOrNull() ?: kfail("Cannot find parameter") WriteCommandAction.runWriteCommandAction(project) { generatePlugin.initializeField(uField, uParameter) } TestCase.assertEquals(""" class MyClass(value: String) { val field: String = value } """.trimIndent(), psiFile.text) } fun `test initialize field in primary constructor with same name`() { val psiFile = myFixture.configureByText("MyClass.kt", """ class My<caret>Class(field: String) { private val field: String } """.trimIndent()) val uClass = myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtClass>().toUElementOfType<UClass>() ?: kfail("Cannot find UClass") val uField = uClass.fields.firstOrNull() ?: kfail("Cannot find field") val uParameter = uClass.methods.find { it.uastParameters.isNotEmpty() }?.uastParameters?.firstOrNull() ?: kfail("Cannot find parameter") WriteCommandAction.runWriteCommandAction(project) { generatePlugin.initializeField(uField, uParameter) } TestCase.assertEquals(""" class MyClass(private val field: String) { } """.trimIndent(), psiFile.text) } fun `test initialize field in primary constructor with same name and class body`() { val psiFile = myFixture.configureByText("MyClass.kt", """ class My<caret>Class(field: String) { private val field: String public fun test() { val i = 0 } } """.trimIndent()) val uClass = myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtClass>().toUElementOfType<UClass>() ?: kfail("Cannot find UClass") val uField = uClass.fields.firstOrNull() ?: kfail("Cannot find field") val uParameter = uClass.methods.find { it.uastParameters.isNotEmpty() }?.uastParameters?.firstOrNull() ?: kfail("Cannot find parameter") WriteCommandAction.runWriteCommandAction(project) { generatePlugin.initializeField(uField, uParameter) } TestCase.assertEquals(""" class MyClass(private val field: String) { public fun test() { val i = 0 } } """.trimIndent(), psiFile.text) } fun `test initialize field in primary constructor with leading blank line`() { val psiFile = myFixture.configureByText("MyClass.kt", """ class My<caret>Class(field: String) { private val field: String public fun test() { val i = 0 } } """.trimIndent()) val uClass = myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<KtClass>().toUElementOfType<UClass>() ?: kfail("Cannot find UClass") val uField = uClass.fields.firstOrNull() ?: kfail("Cannot find field") val uParameter = uClass.methods.find { it.uastParameters.isNotEmpty() }?.uastParameters?.firstOrNull() ?: kfail("Cannot find parameter") WriteCommandAction.runWriteCommandAction(project) { generatePlugin.initializeField(uField, uParameter) } TestCase.assertEquals(""" class MyClass(private val field: String) { public fun test() { val i = 0 } } """.trimIndent(), psiFile.text) } private fun createTypeFromText(s: String, newClass: PsiElement?): PsiType { return JavaPsiFacade.getElementFactory(myFixture.project).createTypeFromText(s, newClass) } } // it is a copy of org.jetbrains.uast.UastUtils.asRecursiveLogString with `appendLine` instead of `appendln` to avoid windows related issues private fun UElement.asRecursiveLogString(render: (UElement) -> String = { it.asLogString() }): String { val stringBuilder = StringBuilder() val indent = " " accept(object : UastVisitor { private var level = 0 override fun visitElement(node: UElement): Boolean { stringBuilder.append(indent.repeat(level)) stringBuilder.appendLine(render(node)) level++ return false } override fun afterVisitElement(node: UElement) { super.afterVisitElement(node) level-- } }) return stringBuilder.toString() }
apache-2.0
36a5cd8e0b174e02b94c639c48d58bce
42.385726
158
0.598573
5.72993
false
true
false
false
GunoH/intellij-community
plugins/kotlin/native/tests/test/org/jetbrains/kotlin/ide/konan/NativeDefinitinosParsingTest.kt
4
775
// 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.ide.konan import com.intellij.testFramework.ParsingTestCase import org.jetbrains.kotlin.idea.base.test.KotlinRoot import org.jetbrains.kotlin.idea.test.util.slashedPath class NativeDefinitionsParsingTest : ParsingTestCase("", "def", NativeDefinitionsParserDefinition()) { fun testAllProperties() = doTest(true) fun testBadDefinitions() = doTest(true) override fun getTestDataPath(): String = KotlinRoot.DIR.resolve("native/tests/testData/colorHighlighting").slashedPath override fun skipSpaces(): Boolean = false override fun includeRanges(): Boolean = true }
apache-2.0
c1bfea0a45810b408d748d461fd88008
37.8
158
0.781935
4.613095
false
true
false
false
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin/tests/test/org/jetbrains/uast/test/kotlin/AbstractKotlinUastLightCodeInsightFixtureTest.kt
2
1727
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.test.kotlin import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.testFramework.LightProjectDescriptor import com.intellij.util.io.URLUtil import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.uast.UFile import org.jetbrains.uast.UastFacade import java.io.File abstract class AbstractKotlinUastLightCodeInsightFixtureTest : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstanceFullJdk() fun getVirtualFile(testName: String): VirtualFile { val testFile = TEST_KOTLIN_MODEL_DIR.listFiles { pathname -> pathname.nameWithoutExtension == testName }.first() val vfs = VirtualFileManager.getInstance().getFileSystem(URLUtil.FILE_PROTOCOL) return vfs.findFileByPath(testFile.canonicalPath)!! } abstract fun check(testName: String, file: UFile) fun doTest(testName: String, checkCallback: (String, UFile) -> Unit = { testName, file -> check(testName, file) }) { val virtualFile = getVirtualFile(testName) val psiFile = myFixture.configureByText(virtualFile.name, File(virtualFile.canonicalPath!!).readText()) val uFile = UastFacade.convertElementWithParent(psiFile, null) ?: error("Can't get UFile for $testName") checkCallback(testName, uFile as UFile) } }
apache-2.0
e1072bffef0fc7fd9922d8652e290f97
47
158
0.779965
5.034985
false
true
false
false
smmribeiro/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ProjectExcludesIgnoredFileProvider.kt
5
2644
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes import com.intellij.openapi.application.runReadAction import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.roots.impl.DirectoryIndexExcludePolicy import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.VcsApplicationSettings import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.ui.ChangesComparator import com.intellij.openapi.vfs.VirtualFileManager class ProjectExcludesIgnoredFileProvider : IgnoredFileProvider { override fun isIgnoredFile(project: Project, filePath: FilePath) = VcsApplicationSettings.getInstance().MARK_EXCLUDED_AS_IGNORED && !Registry.`is`("ide.hide.excluded.files") && filePath.virtualFile?.let { file -> val projectFileIndex = ProjectFileIndex.getInstance(project) //should check only excluded files but not already ignored (e.g. .git directory) (projectFileIndex.isExcluded(file) && !projectFileIndex.isUnderIgnored(file)) } ?: false override fun getIgnoredFiles(project: Project) = getProjectExcludePaths(project) override fun getIgnoredGroupDescription() = VcsBundle.message("changes.project.exclude.paths") private fun getProjectExcludePaths(project: Project): Set<IgnoredFileDescriptor> { if (!VcsApplicationSettings.getInstance().MARK_EXCLUDED_AS_IGNORED) return emptySet() val excludes = sortedSetOf(ChangesComparator.getVirtualFileComparator(false)) val fileIndex = ProjectFileIndex.SERVICE.getInstance(project) for (policy in DirectoryIndexExcludePolicy.EP_NAME.getExtensions(project)) { for (url in policy.excludeUrlsForProject) { val file = VirtualFileManager.getInstance().findFileByUrl(url) if (file != null) { excludes.add(file) } } } for (module in ModuleManager.getInstance(project).modules) { if (module.isDisposed) continue for (excludeRoot in ModuleRootManager.getInstance(module).excludeRoots) { if (runReadAction { !fileIndex.isExcluded(excludeRoot) }) { //root is included into some inner module so it shouldn't be ignored continue } excludes.add(excludeRoot) } } return excludes.map { file -> IgnoredBeanFactory.ignoreFile(file, project) }.toSet() } }
apache-2.0
c801b01e2b40770b41ddbe35a6587d09
41.66129
140
0.759077
4.614311
false
false
false
false
MartinStyk/AndroidApkAnalyzer
app/src/main/java/sk/styk/martin/apkanalyzer/manager/persistence/PersistenceManager.kt
1
951
package sk.styk.martin.apkanalyzer.manager.persistence import android.content.SharedPreferences import javax.inject.Inject private const val FIRST_APP_START = "first_app_start" private const val PROMO_SHOW_TIME = "promo_shown" private const val APP_START_NUMBER = "app_start_number" class PersistenceManager @Inject constructor( private val sharedPreferences: SharedPreferences ) { var isOnboardingRequired: Boolean get() = sharedPreferences.getBoolean(FIRST_APP_START, true) set(value) = sharedPreferences.edit().putBoolean(FIRST_APP_START, value).apply() var lastPromoShowTime: Long get() = sharedPreferences.getLong(PROMO_SHOW_TIME, -1) set(value) = sharedPreferences.edit().putLong(PROMO_SHOW_TIME, value).apply() var appStartNumber: Int get() = sharedPreferences.getInt(APP_START_NUMBER, 0) set(value) = sharedPreferences.edit().putInt(APP_START_NUMBER, value).apply() }
gpl-3.0
813c3734dea768ad4055153c1c9dc9eb
34.259259
88
0.732913
4.029661
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/SelectionActionType.kt
1
676
package ch.rmy.android.http_shortcuts.scripting.actions.types import ch.rmy.android.http_shortcuts.scripting.ActionAlias import ch.rmy.android.http_shortcuts.scripting.actions.ActionDTO class SelectionActionType : BaseActionType() { override val type = TYPE override fun fromDTO(actionDTO: ActionDTO) = SelectionAction( dataObject = actionDTO.getObject(0), dataList = actionDTO.getList(0), ) override fun getAlias() = ActionAlias( functionName = FUNCTION_NAME, parameters = 1, ) companion object { private const val TYPE = "show_selection" private const val FUNCTION_NAME = "showSelection" } }
mit
90bb0fbbc5426d106d8a76586b331269
27.166667
65
0.701183
4.17284
false
false
false
false
spinnaker/clouddriver
clouddriver-saga/src/main/kotlin/com/netflix/spinnaker/clouddriver/saga/SagaService.kt
2
8437
/* * 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 com.netflix.spinnaker.clouddriver.saga import com.netflix.spectator.api.Registry import com.netflix.spinnaker.clouddriver.saga.exceptions.SagaIntegrationException import com.netflix.spinnaker.clouddriver.saga.exceptions.SagaMissingRequiredCommandException import com.netflix.spinnaker.clouddriver.saga.exceptions.SagaNotFoundException import com.netflix.spinnaker.clouddriver.saga.flow.SagaAction import com.netflix.spinnaker.clouddriver.saga.flow.SagaFlow import com.netflix.spinnaker.clouddriver.saga.flow.SagaFlowIterator import com.netflix.spinnaker.clouddriver.saga.models.Saga import com.netflix.spinnaker.clouddriver.saga.persistence.SagaRepository import com.netflix.spinnaker.kork.annotations.Beta import com.netflix.spinnaker.kork.exceptions.SpinnakerException import org.slf4j.LoggerFactory import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware /** * The main brains of the Saga library. Orchestrates the progression of a [Saga] until its completion. * * A [Saga] is a way of performing orchestrated distributed service transactions, and in the case of this library, * is implemented through the a series of log-backed "actions". A [SagaAction] is a reentrant and idempotent function * that changes a remote system. The results of a [SagaAction] are committed into a log so that if at any point a * Saga is interrupted, it may be resumed. Like all transactional systems, a [Saga] may also be rolled back if its * [SagaAction]s are implemented as a [CompensatingSagaAction]. A rollback is managed by consumers of the Saga * library and as such, there are no internal heuristics to dictate when a [Saga] will or will not be compensated. * * For every [SagaCommand], there is 0 to N [SagaAction]s. A [SagaAction] requires a [SagaCommand] which is provided * either by the initial request into the [SagaService], or by a predecessor [SagaAction]. A [SagaAction] can emit 0 * to N [SagaCommand]s, as well as [SagaEvent]s. The difference between the two is that a [SagaCommand] will move * the progress of a [Saga] forward (or backwards if rolling back), whereas a [SagaEvent] will be published to all * subscribers interested in it and will not affect the workflow of a [Saga]. * * ``` * val flow = SagaFlow() * .next(MyAction::class.java) * .completionHandler(MyCompletionHandler::class.java) * * val result = sagaService.applyBlocking(flow, DoMyAction()) * ``` */ @Beta class SagaService( private val sagaRepository: SagaRepository, private val registry: Registry ) : ApplicationContextAware { private lateinit var applicationContext: ApplicationContext private val log by lazy { LoggerFactory.getLogger(javaClass) } private val actionInvocationsId = registry.createId("sagas.actions.invocations") fun <T> applyBlocking(sagaName: String, sagaId: String, flow: SagaFlow, startingCommand: SagaCommand): T? { val initialSaga = initializeSaga(startingCommand, sagaName, sagaId) log.info("Applying saga: ${initialSaga.name}/${initialSaga.id}") if (initialSaga.isComplete()) { log.info("Saga already complete, exiting early: ${initialSaga.name}/${initialSaga.id}") return invokeCompletionHandler(initialSaga, flow) } // TODO(rz): Validate that the startingCommand == the originating startingCommand payload? SagaFlowIterator(sagaRepository, applicationContext, initialSaga, flow).forEach { flowState -> val saga = flowState.saga val action = flowState.action log.debug("Applying saga action ${action.javaClass.simpleName} for ${saga.name}/${saga.id}") val requiredCommand: Class<SagaCommand> = getRequiredCommand(action) if (!saga.finalizedCommand(requiredCommand)) { val stepCommand = saga.getNextCommand(requiredCommand) ?: throw SagaMissingRequiredCommandException("Missing required command ${requiredCommand.simpleName}") val result = try { action.apply(stepCommand, saga).also { registry .counter(actionInvocationsId.withTags("result", "success", "action", action.javaClass.simpleName)) .increment() } } catch (e: Exception) { // TODO(rz): Add SagaAction.recover() val handledException = invokeExceptionHandler(flow, e) log.error( "Encountered error while applying action '${action.javaClass.simpleName}' on ${saga.name}/${saga.id}", handledException ) saga.addEvent( SagaActionErrorOccurred( actionName = action.javaClass.simpleName, error = handledException, retryable = when (handledException) { is SpinnakerException -> handledException.retryable ?: false else -> false } ) ) sagaRepository.save(saga) registry .counter(actionInvocationsId.withTags("result", "failure", "action", action.javaClass.simpleName)) .increment() log.error("Failed to apply action ${action.javaClass.simpleName} for ${saga.name}/${saga.id}") throw handledException } saga.setSequence(stepCommand.getMetadata().sequence) val newEvents: MutableList<SagaEvent> = result.events.toMutableList().also { it.add(SagaCommandCompleted(getStepCommandName(stepCommand))) } val nextCommand = result.nextCommand if (nextCommand == null) { if (flowState.hasMoreSteps() && !saga.hasUnappliedCommands()) { saga.complete(false) sagaRepository.save(saga, listOf()) throw SagaIntegrationException("Result did not return a nextCommand value, but flow has more steps defined") } saga.complete(true) } else { // TODO(rz): Would be nice to flag commands that are optional so its clearer in the event log if (nextCommand is ManyCommands) { newEvents.addAll(nextCommand.commands) } else { newEvents.add(nextCommand) } } sagaRepository.save(saga, newEvents) } } return invokeCompletionHandler(initialSaga, flow) } private fun initializeSaga(command: SagaCommand, sagaName: String, sagaId: String): Saga { return sagaRepository.get(sagaName, sagaId) ?: Saga(sagaName, sagaId) .also { log.debug("Initializing new saga: $sagaName/$sagaId") it.addEvent(command) sagaRepository.save(it) } } private fun <T> invokeCompletionHandler(saga: Saga, flow: SagaFlow): T? { return flow.completionHandler ?.let { completionHandler -> val handler = applicationContext.getBean(completionHandler) val result = sagaRepository.get(saga.name, saga.id) ?.let { handler.handle(it) } ?: throw SagaNotFoundException("Could not find Saga to complete by ${saga.name}/${saga.id}") // TODO(rz): Haha... :( try { @Suppress("UNCHECKED_CAST") return result as T? } catch (e: ClassCastException) { throw SagaIntegrationException("The completion handler is incompatible with the expected return type", e) } } } private fun invokeExceptionHandler(flow: SagaFlow, exception: Exception): Exception { flow.exceptionHandler?.let { exceptionHandler -> val handler = applicationContext.getBean(exceptionHandler) return handler.handle(exception) } return exception } private fun getRequiredCommand(action: SagaAction<SagaCommand>): Class<SagaCommand> = getCommandTypeFromAction(action.javaClass) override fun setApplicationContext(applicationContext: ApplicationContext) { this.applicationContext = applicationContext } }
apache-2.0
2d377d687ff07dd17affca0c3d4e80b7
41.396985
120
0.701553
4.548248
false
false
false
false
sksamuel/ktest
kotest-tests/kotest-tests-core/src/jvmTest/kotlin/com/sksamuel/kotest/listeners/testlistener/instancepertest/BeforeSpecTest.kt
1
974
package com.sksamuel.kotest.listeners.testlistener.instancepertest import io.kotest.core.listeners.TestListener import io.kotest.core.spec.IsolationMode import io.kotest.core.spec.Spec import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe import java.util.concurrent.atomic.AtomicInteger class BeforeSpecTest : FunSpec() { val listener = object : TestListener { override suspend fun beforeSpec(spec: Spec) { counter.incrementAndGet() } } override fun isolationMode(): IsolationMode = IsolationMode.InstancePerTest companion object { private val counter = AtomicInteger(0) } init { listener(listener) afterProject { counter.get() shouldBe 5 } test("ignored test").config(enabled = false) {} test("a").config(enabled = true) {} test("b").config(enabled = true) {} test("c").config(enabled = true) {} test("d").config(enabled = true) {} } }
mit
6c4e6bfece41fb14829338a46598b1cd
24.631579
78
0.680698
4.21645
false
true
false
false
spring-projects/spring-security
config/src/main/kotlin/org/springframework/security/config/annotation/web/AuthorizeHttpRequestsDsl.kt
1
12249
/* * Copyright 2002-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 * * 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 org.springframework.security.config.annotation.web import org.springframework.http.HttpMethod import org.springframework.security.authorization.AuthenticatedAuthorizationManager import org.springframework.security.authorization.AuthorityAuthorizationManager import org.springframework.security.authorization.AuthorizationDecision import org.springframework.security.authorization.AuthorizationManager import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer import org.springframework.security.core.Authentication import org.springframework.security.web.access.intercept.AuthorizationFilter import org.springframework.security.web.access.intercept.RequestAuthorizationContext import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher import org.springframework.security.web.util.matcher.AnyRequestMatcher import org.springframework.security.web.util.matcher.RequestMatcher import org.springframework.util.ClassUtils import org.springframework.web.servlet.handler.HandlerMappingIntrospector import java.util.function.Supplier /** * A Kotlin DSL to configure [HttpSecurity] request authorization using idiomatic Kotlin code. * * @author Yuriy Savchenko * @since 5.7 * @property shouldFilterAllDispatcherTypes whether the [AuthorizationFilter] should filter all dispatcher types */ class AuthorizeHttpRequestsDsl : AbstractRequestMatcherDsl() { var shouldFilterAllDispatcherTypes: Boolean? = null private val authorizationRules = mutableListOf<AuthorizationManagerRule>() private val HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME = "mvcHandlerMappingIntrospector" private val HANDLER_MAPPING_INTROSPECTOR = "org.springframework.web.servlet.handler.HandlerMappingIntrospector" private val MVC_PRESENT = ClassUtils.isPresent( HANDLER_MAPPING_INTROSPECTOR, AuthorizeHttpRequestsDsl::class.java.classLoader) private val PATTERN_TYPE = if (MVC_PRESENT) PatternType.MVC else PatternType.ANT /** * Adds a request authorization rule. * * @param matches the [RequestMatcher] to match incoming requests against * @param access the [AuthorizationManager] to secure the matching request * (i.e. created via hasAuthority("ROLE_USER")) */ fun authorize(matches: RequestMatcher = AnyRequestMatcher.INSTANCE, access: AuthorizationManager<RequestAuthorizationContext>) { authorizationRules.add(MatcherAuthorizationManagerRule(matches, access)) } /** * Adds a request authorization rule for an endpoint matching the provided * pattern. * If Spring MVC is on the classpath, it will use an MVC matcher. * If Spring MVC is not on the classpath, it will use an ant matcher. * The MVC will use the same rules that Spring MVC uses for matching. * For example, often times a mapping of the path "/path" will match on * "/path", "/path/", "/path.html", etc. * If the current request will not be processed by Spring MVC, a reasonable default * using the pattern as an ant pattern will be used. * * @param pattern the pattern to match incoming requests against. * @param access the [AuthorizationManager] to secure the matching request * (i.e. created via hasAuthority("ROLE_USER")) */ fun authorize(pattern: String, access: AuthorizationManager<RequestAuthorizationContext>) { authorizationRules.add( PatternAuthorizationManagerRule( pattern = pattern, patternType = PATTERN_TYPE, rule = access ) ) } /** * Adds a request authorization rule for an endpoint matching the provided * pattern. * If Spring MVC is on the classpath, it will use an MVC matcher. * If Spring MVC is not on the classpath, it will use an ant matcher. * The MVC will use the same rules that Spring MVC uses for matching. * For example, often times a mapping of the path "/path" will match on * "/path", "/path/", "/path.html", etc. * If the current request will not be processed by Spring MVC, a reasonable default * using the pattern as an ant pattern will be used. * * @param method the HTTP method to match the income requests against. * @param pattern the pattern to match incoming requests against. * @param access the [AuthorizationManager] to secure the matching request * (i.e. created via hasAuthority("ROLE_USER")) */ fun authorize(method: HttpMethod, pattern: String, access: AuthorizationManager<RequestAuthorizationContext>) { authorizationRules.add( PatternAuthorizationManagerRule( pattern = pattern, patternType = PATTERN_TYPE, httpMethod = method, rule = access ) ) } /** * Adds a request authorization rule for an endpoint matching the provided * pattern. * If Spring MVC is on the classpath, it will use an MVC matcher. * If Spring MVC is not on the classpath, it will use an ant matcher. * The MVC will use the same rules that Spring MVC uses for matching. * For example, often times a mapping of the path "/path" will match on * "/path", "/path/", "/path.html", etc. * If the current request will not be processed by Spring MVC, a reasonable default * using the pattern as an ant pattern will be used. * * @param pattern the pattern to match incoming requests against. * @param servletPath the servlet path to match incoming requests against. This * only applies when using an MVC pattern matcher. * @param access the [AuthorizationManager] to secure the matching request * (i.e. created via hasAuthority("ROLE_USER")) */ fun authorize(pattern: String, servletPath: String, access: AuthorizationManager<RequestAuthorizationContext>) { authorizationRules.add( PatternAuthorizationManagerRule( pattern = pattern, patternType = PATTERN_TYPE, servletPath = servletPath, rule = access ) ) } /** * Adds a request authorization rule for an endpoint matching the provided * pattern. * If Spring MVC is on the classpath, it will use an MVC matcher. * If Spring MVC is not on the classpath, it will use an ant matcher. * The MVC will use the same rules that Spring MVC uses for matching. * For example, often times a mapping of the path "/path" will match on * "/path", "/path/", "/path.html", etc. * If the current request will not be processed by Spring MVC, a reasonable default * using the pattern as an ant pattern will be used. * * @param method the HTTP method to match the income requests against. * @param pattern the pattern to match incoming requests against. * @param servletPath the servlet path to match incoming requests against. This * only applies when using an MVC pattern matcher. * @param access the [AuthorizationManager] to secure the matching request * (i.e. created via hasAuthority("ROLE_USER")) */ fun authorize(method: HttpMethod, pattern: String, servletPath: String, access: AuthorizationManager<RequestAuthorizationContext>) { authorizationRules.add( PatternAuthorizationManagerRule( pattern = pattern, patternType = PATTERN_TYPE, servletPath = servletPath, httpMethod = method, rule = access ) ) } /** * Specify that URLs require a particular authority. * * @param authority the authority to require (i.e. ROLE_USER, ROLE_ADMIN, etc). * @return the [AuthorizationManager] with the provided authority */ fun hasAuthority(authority: String): AuthorizationManager<RequestAuthorizationContext> { return AuthorityAuthorizationManager.hasAuthority(authority) } /** * Specify that URLs require any of the provided authorities. * * @param authorities the authorities to require (i.e. ROLE_USER, ROLE_ADMIN, etc). * @return the [AuthorizationManager] with the provided authorities */ fun hasAnyAuthority(vararg authorities: String): AuthorizationManager<RequestAuthorizationContext> { return AuthorityAuthorizationManager.hasAnyAuthority(*authorities) } /** * Specify that URLs require a particular role. * * @param role the role to require (i.e. USER, ADMIN, etc). * @return the [AuthorizationManager] with the provided role */ fun hasRole(role: String): AuthorizationManager<RequestAuthorizationContext> { return AuthorityAuthorizationManager.hasRole(role) } /** * Specify that URLs require any of the provided roles. * * @param roles the roles to require (i.e. USER, ADMIN, etc). * @return the [AuthorizationManager] with the provided roles */ fun hasAnyRole(vararg roles: String): AuthorizationManager<RequestAuthorizationContext> { return AuthorityAuthorizationManager.hasAnyRole(*roles) } /** * Specify that URLs are allowed by anyone. */ val permitAll: AuthorizationManager<RequestAuthorizationContext> = AuthorizationManager { _: Supplier<Authentication>, _: RequestAuthorizationContext -> AuthorizationDecision(true) } /** * Specify that URLs are not allowed by anyone. */ val denyAll: AuthorizationManager<RequestAuthorizationContext> = AuthorizationManager { _: Supplier<Authentication>, _: RequestAuthorizationContext -> AuthorizationDecision(false) } /** * Specify that URLs are allowed by any authenticated user. */ val authenticated: AuthorizationManager<RequestAuthorizationContext> = AuthenticatedAuthorizationManager.authenticated() internal fun get(): (AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizationManagerRequestMatcherRegistry) -> Unit { return { requests -> authorizationRules.forEach { rule -> when (rule) { is MatcherAuthorizationManagerRule -> requests.requestMatchers(rule.matcher).access(rule.rule) is PatternAuthorizationManagerRule -> { when (rule.patternType) { PatternType.ANT -> requests.requestMatchers(rule.httpMethod, rule.pattern).access(rule.rule) PatternType.MVC -> { val introspector = requests.applicationContext.getBean(HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME, HandlerMappingIntrospector::class.java) val mvcMatcher = MvcRequestMatcher.Builder(introspector) .servletPath(rule.servletPath) .pattern(rule.pattern) mvcMatcher.setMethod(rule.httpMethod) requests.requestMatchers(mvcMatcher).access(rule.rule) } } } } } shouldFilterAllDispatcherTypes?.also { shouldFilter -> requests.shouldFilterAllDispatcherTypes(shouldFilter) } } } }
apache-2.0
1bb6d4c4002195bcce7fe8bc3d636254
44.705224
166
0.67728
5.049052
false
false
false
false
JayNewstrom/json
plugin/compiler/src/main/kotlin/com/jaynewstrom/jsonDelight/compiler/ModelSerializerBuilder.kt
1
4896
package com.jaynewstrom.jsonDelight.compiler import com.fasterxml.jackson.core.JsonGenerator import com.jaynewstrom.jsonDelight.runtime.JsonRegistrable import com.jaynewstrom.jsonDelight.runtime.JsonSerializer import com.jaynewstrom.jsonDelight.runtime.JsonSerializerFactory import com.jaynewstrom.jsonDelight.runtime.internal.ListSerializer import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.ParameterSpec import com.squareup.kotlinpoet.ParameterizedTypeName import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.TypeSpec import com.squareup.kotlinpoet.asTypeName internal data class ModelSerializerBuilder( private val isPublic: Boolean, private val packageName: String, private val name: String, private val fields: List<FieldDefinition> ) { fun build(): TypeSpec { val jsonFactoryType = JsonSerializer::class.asTypeName() val typeBuilder = TypeSpec.classBuilder(JsonCompiler.serializerName(name)) .addSuperinterface(jsonFactoryType.parameterizedBy(JsonCompiler.jsonModelType(packageName, name))) .addSuperinterface(JsonRegistrable::class.java) .addFunction(JsonCompiler.modelClassFunSpec(packageName, name)) .addFunction(serializeFunSpec()) if (!isPublic) { typeBuilder.addModifiers(KModifier.INTERNAL) } return typeBuilder.build() } private fun serializeFunSpec(): FunSpec { val methodBuilder = FunSpec.builder("serialize") .addAnnotation(JsonCompiler.throwsIoExceptionAnnotation()) .addModifiers(KModifier.OVERRIDE) .addParameter(ParameterSpec.builder(MODEL_VARIABLE_NAME, JsonCompiler.jsonModelType(packageName, name)).build()) .addParameter(ParameterSpec.builder(JSON_GENERATOR_VARIABLE_NAME, JsonGenerator::class).build()) .addParameter(ParameterSpec.builder(SERIALIZER_FACTORY_VARIABLE_NAME, JsonSerializerFactory::class).build()) serializeMethodBody(methodBuilder) return methodBuilder.build() } private fun serializeMethodBody(methodBuilder: FunSpec.Builder) { methodBuilder.addStatement("$JSON_GENERATOR_VARIABLE_NAME.writeStartObject()") fields.forEach { field -> val nullable = field.type.isNullable if (nullable) { methodBuilder.beginControlFlow("if (%L != null)", "$MODEL_VARIABLE_NAME.${field.fieldName}") } methodBuilder.addStatement("$JSON_GENERATOR_VARIABLE_NAME.writeFieldName(%S)", field.jsonName) field.serialize(methodBuilder) if (nullable) { methodBuilder.nextControlFlow("else") methodBuilder.addStatement("$JSON_GENERATOR_VARIABLE_NAME.writeNullField(%S)", field.jsonName) methodBuilder.endControlFlow() } } methodBuilder.addStatement("$JSON_GENERATOR_VARIABLE_NAME.writeEndObject()") } private fun FieldDefinition.serialize(methodBuilder: FunSpec.Builder) { if (type is ParameterizedTypeName && type.rawType == List::class.asTypeName()) { val modelType = type.typeArguments[0] val listSerializerType = ListSerializer::class.asTypeName() val serializer = getSerializer(modelType) val codeFormat = "%T(${serializer.code}).${callSerialize()}" methodBuilder.addStatement(codeFormat, listSerializerType, serializer.codeArgument) } else if (customSerializer == null && primitiveType != null) { methodBuilder.addStatement("$JSON_GENERATOR_VARIABLE_NAME.${primitiveType.serializeMethod}($MODEL_VARIABLE_NAME.$fieldName${primitiveType.conversionForSerializeMethod})") } else { val serializer = getSerializer(type) methodBuilder.addStatement("${serializer.code}.${callSerialize()}", serializer.codeArgument) } } private data class FieldSerializerResult(val code: String, val codeArgument: TypeName) private fun FieldDefinition.getSerializer(typeName: TypeName): FieldSerializerResult { return if (customSerializer == null) { FieldSerializerResult("$SERIALIZER_FACTORY_VARIABLE_NAME[%T::class.java]", typeName.copy(nullable = false)) } else { FieldSerializerResult("%T", customSerializer) } } private fun FieldDefinition.callSerialize(): String { return "serialize($MODEL_VARIABLE_NAME.$fieldName, $JSON_GENERATOR_VARIABLE_NAME, $SERIALIZER_FACTORY_VARIABLE_NAME)" } companion object { private const val MODEL_VARIABLE_NAME = "value" private const val JSON_GENERATOR_VARIABLE_NAME = "jg" private const val SERIALIZER_FACTORY_VARIABLE_NAME = "serializerFactory" } }
apache-2.0
ad263b753b1601d4a11d6726500b7b04
48.454545
182
0.710784
5.121339
false
false
false
false
luhaoaimama1/JavaZone
JavaTest_Zone/src/kt/Iterate.kt
1
1067
package kt fun main(args: Array<String>) { iterateSection() iterateFor() iterateForIndex() iterateWhile() println("describe${describe("Hello")}") } private fun iterateSection() { for (x in 1..10 step 2) { print(x) } println() for (x in 9 downTo 0 step 3) { print(x) } } private fun iterateWhile() { val items = listOf("apple", "banana", "kiwifruit") var index = 0 while (index < items.size) { println("item at $index is ${items[index]}") index++ } } private fun iterateForIndex() { val items = listOf("apple", "banana", "kiwifruit") for (index in items.indices) { println("item at $index is ${items[index]}") } } private fun iterateFor() { val items = listOf("apple", "banana", "kiwifruit") for (item in items) { if (item == "banana") break println(item) } } fun describe(obj: Any): String = when (obj) { 1 -> "One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a string" else -> "Unknown" }
epl-1.0
d3e1cbad965d2c3e51f3d1293f5a1101
19.538462
54
0.56045
3.47557
false
false
false
false
yrsegal/CommandControl
src/main/java/wiresegal/cmdctrl/common/commands/biome/CommandFillBiome.kt
1
3208
package wiresegal.cmdctrl.common.commands.biome import net.minecraft.command.CommandBase import net.minecraft.command.CommandException import net.minecraft.command.ICommandSender import net.minecraft.server.MinecraftServer import net.minecraft.util.ResourceLocation import net.minecraft.util.math.BlockPos import net.minecraft.world.biome.Biome import wiresegal.cmdctrl.common.CommandControl import wiresegal.cmdctrl.common.core.CTRLException import wiresegal.cmdctrl.common.core.CTRLUsageException import wiresegal.cmdctrl.common.core.Slice import wiresegal.cmdctrl.common.core.notifyCTRLListener /** * @author WireSegal * Created at 5:43 PM on 12/3/16. */ object CommandFillBiome : CommandBase() { val biomes: List<ResourceLocation?> get() = CommandSetBiome.biomes @Throws(CommandException::class) override fun execute(server: MinecraftServer, sender: ICommandSender, args: Array<out String>) { if (args.size > 4) { val senderPos = sender.position val x1 = parseDouble(senderPos.x.toDouble(), args[0], -3000000, 3000000, false).toInt() val z1 = parseDouble(senderPos.z.toDouble(), args[1], -3000000, 3000000, false).toInt() val x2 = parseDouble(senderPos.x.toDouble(), args[2], -3000000, 3000000, false).toInt() val z2 = parseDouble(senderPos.z.toDouble(), args[3], -3000000, 3000000, false).toInt() val pos1 = BlockPos(x1, 0, z1) val pos2 = BlockPos(x2, 0, z2) val biomeid = args[4] val biome = CommandSetBiome.parseBiome(biomeid) val world = sender.entityWorld val id = Biome.getIdForBiome(biome).toByte() val name = Biome.REGISTRY.getNameForObject(biome) if (world.isBlockLoaded(pos1) && world.isBlockLoaded(pos2)) { notifyCTRLListener(sender, this, "commandcontrol.fillbiomes.success", x1, z1, x2, z2, id, name) val slices = BlockPos.getAllInBoxMutable(pos1, pos2) .filter { CommandSetBiome.setBiome(world.getChunkFromBlockCoords(it), it, biome) } .map(::Slice) CommandSetBiome.updateBiomes(world, slices) } else throw CTRLException("commandcontrol.fillbiomes.range", x1, z1, x2, z2) } else throw CTRLUsageException(getCommandUsage(sender)) } override fun getTabCompletionOptions(server: MinecraftServer, sender: ICommandSender, args: Array<out String>, pos: BlockPos?): List<String> { return when (args.size) { 1 -> getTabCompletionCoordinate(args, 0, pos) 2 -> getTabCompletionCoordinate(args, -1, pos) 3 -> getTabCompletionCoordinate(args, 2, pos) 4 -> getTabCompletionCoordinate(args, 1, pos) 5 -> getListOfStringsMatchingLastWord(args, biomes) else -> emptyList() } } override fun getRequiredPermissionLevel() = 2 override fun getCommandName() = "fillbiomes" override fun getCommandAliases() = mutableListOf("biomefill") override fun getCommandUsage(sender: ICommandSender?) = CommandControl.translate("commandcontrol.fillbiomes.usage") }
mit
4aa232ca4f6bbc0d40fc1a7900e15fb6
43.555556
146
0.675187
4.045397
false
false
false
false
tmarsteel/kotlin-prolog
core/src/main/kotlin/com/github/prologdb/runtime/unification/Unification.kt
1
1236
package com.github.prologdb.runtime.unification import com.github.prologdb.async.LazySequence import com.github.prologdb.runtime.term.Variable /** * A single possible way to unify two expressions; one query result. */ class Unification(val variableValues: VariableBucket = VariableBucket()) { fun combinedWith(other: Unification): Unification { return Unification(variableValues.combinedWith(other.variableValues)) } override fun toString(): String { return variableValues.values.joinToString(", ") { (variable, value) -> "$variable = ${value ?: Variable.ANONYMOUS}" } } override fun equals(other: Any?): Boolean { if (other === null) return false if (this === other) return true other as Unification if (variableValues != other.variableValues) return false return true } override fun hashCode(): Int { return variableValues.hashCode() } companion object { val FALSE: Unification? = null val TRUE: Unification = Unification() val NONE: LazySequence<Unification> = LazySequence.empty() fun whether(condition: Boolean): Unification? = if(condition) TRUE else FALSE } }
mit
2f8e7de29ee09a947a12c3743e4d7790
27.113636
85
0.665049
4.809339
false
false
false
false
katanagari7c1/wolverine-comics-kotlin
app/src/main/kotlin/dev/katanagari7c1/wolverine/presentation/main/list/ComicListDiffCallback.kt
1
953
package dev.katanagari7c1.wolverine.presentation.main.list import android.support.v7.util.DiffUtil import dev.katanagari7c1.wolverine.domain.entity.Comic class ComicListDiffCallback( val oldList:List<dev.katanagari7c1.wolverine.domain.entity.Comic>, val newList:List<dev.katanagari7c1.wolverine.domain.entity.Comic> ): android.support.v7.util.DiffUtil.Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return this.oldList[oldItemPosition].comicId == this.newList[newItemPosition].comicId } override fun getOldListSize(): Int { return this.oldList.size } override fun getNewListSize(): Int { return this.newList.size } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return this.oldList[oldItemPosition].title == this.newList[newItemPosition].title && this.oldList[oldItemPosition].thumbnail == this.newList[newItemPosition].thumbnail } }
mit
25ccc8123b4415d33c4db7767ac82245
31.862069
87
0.794334
3.796813
false
false
false
false
frendyxzc/KotlinNews
model/src/main/java/vip/frendy/model/data/Constants.kt
1
369
package vip.frendy.model.data /** * Created by iiMedia on 2017/6/8. */ object Constants { val APP_ID = "5225" val APP_KEY = "9b836682f204ac0503980acd48b4df21" val APP_INFO = "app_id=" + APP_ID + "&app_key=" + APP_KEY val DEFAULT_URL: String = "http://frendy.vip/" val XW_BASE_URL: String = "http://www.myxianwen.cn/newsapp/pureArticle.action?" }
mit
f73b971afec71659c3c8d21b7ffbf844
27.461538
83
0.653117
2.673913
false
false
false
false
nickthecoder/tickle
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/scene/history/History.kt
1
4594
/* Tickle Copyright (C) 2017 Nick Robinson 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 uk.co.nickthecoder.tickle.editor.scene.history import uk.co.nickthecoder.tickle.editor.scene.SceneEditor /** * All modifications to the document happen through History. * Instead of changing the document, and then noting that change with [History], * we tell [History] of the changes to be made. * [History] will perform the modification, and add the modification to its list. * * The history is arranged in batches, where each batch is the smallest item that can be * undone or redone. * To modify the document, begin a batch with [beginBatch], then modify the document via [makeChange], and * finally end the batch with [endBatch]. If you wish to abandon a batch instead of ending it, use [abandonBatch]. * * The document will be modified */ class History(private val sceneEditor: SceneEditor) { private val history = mutableListOf<Batch>() /** * When adding */ private var currentBatch: Batch? = null /** * The index into [history] where new [Batch]es will be added. * If the index == 0, then there is no more to undo. * If the index == history.size, then there is nothing to redo. */ private var currentIndex = 0 /** * The index when the document was saved. * If currentIndex != savedIndex, then the document has changed to the version on disk. */ private var savedIndex = 0 /** * Set to true during undo and redo so that ParameterListeners don't cause ANOTHER Change to be added to the history. */ var updating = false fun canUndo() = currentIndex > 0 || currentBatch != null fun canRedo() = currentIndex < history.size fun clear() { savedIndex = -1 currentIndex = 0 currentBatch = null history.clear() } fun undo() { if (canUndo()) { updating = true if (currentBatch == null) { currentIndex-- val batch = history[currentIndex] batch.undo(sceneEditor) } else { abandonBatch() } updating = false } } fun redo() { if (canRedo()) { updating = true val batch = history[currentIndex] currentIndex++ batch.redo(sceneEditor) updating = false } } fun beginBatch() { currentBatch = Batch() } fun abandonBatch() { currentBatch?.undo(sceneEditor) currentBatch = null } fun endBatch() { currentBatch?.let { if (!it.changes.isEmpty()) { if (savedIndex > currentIndex) { // We've destroyed the redo that would take us back to the saved state. savedIndex = -1 } while (history.size > currentIndex) { history.removeAt(history.size - 1) } history.add(currentIndex, it) currentIndex++ } currentBatch = null } } fun makeChange(change: Change) { currentBatch?.let { it.makeChange(sceneEditor, change) return } beginBatch() makeChange(change) endBatch() } fun isSavedVersion() = savedIndex == currentIndex fun saved() { savedIndex = currentIndex } /** * Prints out all the changes while performing and "undo". */ fun debugUndo() { if (canUndo()) { if (currentBatch == null) { currentIndex-- val batch = history[currentIndex] println("Undoing a batch") println(batch) batch.undo(sceneEditor) } else { println("Abandoning the current batch...") println(currentBatch) abandonBatch() } } } }
gpl-3.0
cfd7be57ba7bd8cacd9f5d1bbdc32e32
27.7125
121
0.588811
4.72148
false
false
false
false
ajalt/clikt
clikt/src/commonMain/kotlin/com/github/ajalt/clikt/core/NoOpCliktCommand.kt
1
712
package com.github.ajalt.clikt.core /** * A [CliktCommand] that has a default implementation of [CliktCommand.run] that is a no-op. */ open class NoOpCliktCommand( help: String = "", epilog: String = "", name: String? = null, invokeWithoutSubcommand: Boolean = false, printHelpOnEmptyArgs: Boolean = false, helpTags: Map<String, String> = emptyMap(), autoCompleteEnvvar: String? = "", allowMultipleSubcommands: Boolean = false, hidden: Boolean = false, ) : CliktCommand( help, epilog, name, invokeWithoutSubcommand, printHelpOnEmptyArgs, helpTags, autoCompleteEnvvar, allowMultipleSubcommands, hidden ) { override fun run() = Unit }
apache-2.0
149452cecac71458ea3c1709fe9946a9
24.428571
92
0.674157
4.091954
false
false
false
false
Juuxel/ChatTime
api/src/main/kotlin/chattime/api/net/Packet.kt
1
3598
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package chattime.api.net import com.beust.klaxon.* import java.io.DataInputStream import java.io.DataOutputStream import kotlin.reflect.full.isSuperclassOf /** * A packet for client-server communications, identified with a unique [id]. * * @property id the unique ID for the packet type */ sealed class Packet(val id: Int) { /** * The companion object of `Packet`. * * Implements the `Converter` interface from Klaxon and provides functions for converting * packets to and from JSON. */ companion object : Converter { /** * Returns `true` if [cls] is `Packet::class` or a superclass of `Packet`. */ override fun canConvert(cls: Class<*>) = cls.kotlin.isSuperclassOf(Packet::class) /** * Converts the JSON value ([jv]) to a `Packet`. * * @throws IllegalArgumentException if [jv] does not contain a `JsonObject` * @throws NoSuchElementException if a packet property is missing */ override fun fromJson(jv: JsonValue): Packet { if (jv.obj == null) throw IllegalArgumentException("jv must contain an object") val obj = jv.obj!! val id = obj.int("id")!! return when (id) { 0 -> { val userId = obj.string("sender") ?: throw NoSuchElementException("Missing sender") val message = obj.string("message") ?: throw NoSuchElementException("Missing message") Message(userId, message) } else -> throw IllegalArgumentException("Unknown packet ID: $id") } } /** * Converts the [value] to JSON by calling `toJson(Packet)`. * * @throws IllegalArgumentException if the [value] is not a `Packet` */ override fun toJson(value: Any) = toJson(value as? Packet ?: throw IllegalArgumentException("value is not a Packet")) /** * Converts the [packet] to JSON. */ fun toJson(packet: Packet) = json { obj("id" to packet.id, *packet.toMap().entries.map(Map.Entry<String, *>::toPair).toTypedArray()) }.toJsonString() /** * Reads a packet from the input [stream]. * * @see fromJson * @see write */ fun read(stream: DataInputStream): Packet { val string = stream.readUTF() return Klaxon() .converter(this) .parse(json = string)!! } } /** * A message. * * Packet ID: 0 * * @property sender the message sender ([name][chattime.api.User.name]) * @property message the message content */ // TODO Change sender back to the id data class Message(val sender: String, val message: String) : Packet(0) { override fun toMap() = mapOf("sender" to sender, "message" to message) } /** * Converts this packet's properties to a `Map`. */ internal abstract fun toMap() : Map<String, *> /** * Writes this packet to the [outputStream]. * * @see toJson * @see read */ fun write(outputStream: DataOutputStream) = outputStream.writeUTF(toJson(this)) }
mpl-2.0
4f9726cb9b5698f82c8477f3ed178444
30.286957
112
0.558644
4.624679
false
false
false
false
iarchii/trade_app
app/src/main/java/xyz/thecodeside/tradeapp/repository/remote/socket/SocketItemPacker.kt
1
1665
package xyz.thecodeside.tradeapp.repository.remote.socket import android.util.Log import com.google.gson.Gson import org.json.JSONObject import xyz.thecodeside.tradeapp.model.* class SocketItemPacker { fun pack(item: SocketRequest): String { val messageString = Gson().toJson(item) Log.d(SocketManager.TAG, "sendMessage = $messageString") return messageString } fun unpack(message: String?): BaseSocket { Log.d(SocketManager.TAG, "messageString = $message") val gson = Gson() val json = JSONObject(message) json.has(SOCKET_TOPIC_NAME) val idString = if(json.has(SOCKET_TOPIC_NAME)) json.getString(SOCKET_TOPIC_NAME) else throw IllegalArgumentException("Cannot find id of SocketType in: $json") val id = gson.fromJson(idString, SocketType::class.java) ?: throw IllegalArgumentException("No SocketType mapping for given id: $idString") val body = if(json.has(SOCKET_BODY_NAME)) json.getString(SOCKET_BODY_NAME) else throw IllegalArgumentException("Cannot find body of SocketMessage in: $json") val socketBody = gson.fromJson(body , getItemClass(id)) return BaseSocket(id, socketBody) } } private val socketIdMap = mapOf( SocketType.CONNECT_CONNECTED to Connected::class.java, SocketType.CONNECT_FAILED to ResponseError::class.java, SocketType.TRADING_QUOTE to TradingQuote::class.java, SocketType.PORTFOLIO_PERFORMANCE to PortfolioPerformance::class.java ) fun getItemClass(id: SocketType): Class<out BaseSocketBody> = socketIdMap[id] ?: throw IllegalArgumentException("No SocketType mapping for given id: $id")
apache-2.0
7bd663e7303b017a111e1ae7d00373ee
40.625
166
0.721922
4.090909
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsGeneralController.kt
1
9238
package eu.kanade.tachiyomi.ui.setting import android.app.Dialog import android.os.Bundle import android.os.Handler import android.support.v7.preference.PreferenceScreen import android.view.View import com.afollestad.materialdialogs.MaterialDialog import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.library.LibraryUpdateJob import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.ui.base.controller.DialogController import eu.kanade.tachiyomi.util.LocaleHelper import kotlinx.android.synthetic.main.pref_library_columns.view.* import rx.Observable import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys class SettingsGeneralController : SettingsController() { private val db: DatabaseHelper = Injekt.get() override fun setupPreferenceScreen(screen: PreferenceScreen) = with(screen) { titleRes = R.string.pref_category_general listPreference { key = Keys.lang titleRes = R.string.pref_language entryValues = arrayOf("", "ar", "bg", "de", "en", "es", "fr", "id", "it", "lv", "ms", "nl", "pl", "pt", "pt-BR", "ru", "vi") entries = entryValues.map { value -> val locale = LocaleHelper.getLocaleFromString(value.toString()) locale?.getDisplayName(locale)?.capitalize() ?: context.getString(R.string.system_default) }.toTypedArray() defaultValue = "" summary = "%s" onChange { newValue -> val activity = activity ?: return@onChange false val app = activity.application LocaleHelper.changeLocale(newValue.toString()) LocaleHelper.updateConfiguration(app, app.resources.configuration) activity.recreate() true } } intListPreference { key = Keys.theme titleRes = R.string.pref_theme entriesRes = arrayOf(R.string.light_theme, R.string.dark_theme, R.string.amoled_theme) entryValues = arrayOf("1", "2", "3") defaultValue = "1" summary = "%s" onChange { activity?.recreate() true } } preference { titleRes = R.string.pref_library_columns onClick { LibraryColumnsDialog().showDialog(router) } fun getColumnValue(value: Int): String { return if (value == 0) context.getString(R.string.default_columns) else value.toString() } Observable.combineLatest( preferences.portraitColumns().asObservable(), preferences.landscapeColumns().asObservable(), { portraitCols, landscapeCols -> Pair(portraitCols, landscapeCols) }) .subscribeUntilDestroy { (portraitCols, landscapeCols) -> val portrait = getColumnValue(portraitCols) val landscape = getColumnValue(landscapeCols) summary = "${context.getString(R.string.portrait)}: $portrait, " + "${context.getString(R.string.landscape)}: $landscape" } } intListPreference { key = Keys.startScreen titleRes = R.string.pref_start_screen entriesRes = arrayOf(R.string.label_library, R.string.label_recent_manga, R.string.label_recent_updates) entryValues = arrayOf("1", "2", "3") defaultValue = "1" summary = "%s" } intListPreference { key = Keys.libraryUpdateInterval titleRes = R.string.pref_library_update_interval entriesRes = arrayOf(R.string.update_never, R.string.update_1hour, R.string.update_2hour, R.string.update_3hour, R.string.update_6hour, R.string.update_12hour, R.string.update_24hour, R.string.update_48hour) entryValues = arrayOf("0", "1", "2", "3", "6", "12", "24", "48") defaultValue = "0" summary = "%s" onChange { newValue -> // Always cancel the previous task, it seems that sometimes they are not updated. LibraryUpdateJob.cancelTask() val interval = (newValue as String).toInt() if (interval > 0) { LibraryUpdateJob.setupTask(interval) } true } } multiSelectListPreference { key = Keys.libraryUpdateRestriction titleRes = R.string.pref_library_update_restriction entriesRes = arrayOf(R.string.wifi, R.string.charging) entryValues = arrayOf("wifi", "ac") summaryRes = R.string.pref_library_update_restriction_summary preferences.libraryUpdateInterval().asObservable() .subscribeUntilDestroy { isVisible = it > 0 } onChange { // Post to event looper to allow the preference to be updated. Handler().post { LibraryUpdateJob.setupTask() } true } } switchPreference { key = Keys.updateOnlyNonCompleted titleRes = R.string.pref_update_only_non_completed defaultValue = false } val dbCategories = db.getCategories().executeAsBlocking() multiSelectListPreference { key = Keys.libraryUpdateCategories titleRes = R.string.pref_library_update_categories entries = dbCategories.map { it.name }.toTypedArray() entryValues = dbCategories.map { it.id.toString() }.toTypedArray() preferences.libraryUpdateCategories().asObservable() .subscribeUntilDestroy { val selectedCategories = it .mapNotNull { id -> dbCategories.find { it.id == id.toInt() } } .sortedBy { it.order } summary = if (selectedCategories.isEmpty()) context.getString(R.string.all) else selectedCategories.joinToString { it.name } } } intListPreference { key = Keys.defaultCategory titleRes = R.string.default_category val selectedCategory = dbCategories.find { it.id == preferences.defaultCategory() } entries = arrayOf(context.getString(R.string.default_category_summary)) + dbCategories.map { it.name }.toTypedArray() entryValues = arrayOf("-1") + dbCategories.map { it.id.toString() }.toTypedArray() defaultValue = "-1" summary = selectedCategory?.name ?: context.getString(R.string.default_category_summary) onChange { newValue -> summary = dbCategories.find { it.id == (newValue as String).toInt() }?.name ?: context.getString(R.string.default_category_summary) true } } } class LibraryColumnsDialog : DialogController() { private val preferences: PreferencesHelper = Injekt.get() private var portrait = preferences.portraitColumns().getOrDefault() private var landscape = preferences.landscapeColumns().getOrDefault() override fun onCreateDialog(savedViewState: Bundle?): Dialog { val dialog = MaterialDialog.Builder(activity!!) .title(R.string.pref_library_columns) .customView(R.layout.pref_library_columns, false) .positiveText(android.R.string.ok) .negativeText(android.R.string.cancel) .onPositive { _, _ -> preferences.portraitColumns().set(portrait) preferences.landscapeColumns().set(landscape) } .build() onViewCreated(dialog.view) return dialog } fun onViewCreated(view: View) { with(view.portrait_columns) { displayedValues = arrayOf(context.getString(R.string.default_columns)) + IntRange(1, 10).map(Int::toString) value = portrait setOnValueChangedListener { _, _, newValue -> portrait = newValue } } with(view.landscape_columns) { displayedValues = arrayOf(context.getString(R.string.default_columns)) + IntRange(1, 10).map(Int::toString) value = landscape setOnValueChangedListener { _, _, newValue -> landscape = newValue } } } } }
apache-2.0
aec8ab5adcdd2dff086cf5ff158b1a03
39.880531
100
0.559861
5.17535
false
false
false
false