repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
mdanielwork/intellij-community
platform/lang-impl/src/com/intellij/index/PrebuiltIndexAwareIdIndexer.kt
6
2168
// 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.index import com.intellij.openapi.diagnostic.Logger import com.intellij.psi.impl.cache.impl.id.IdIndexEntry import com.intellij.psi.impl.cache.impl.id.LexingIdIndexer import com.intellij.util.indexing.FileContent import com.intellij.util.io.DataExternalizer import com.intellij.util.io.DataInputOutputUtil import java.io.DataInput import java.io.DataOutput /** * @author traff */ abstract class PrebuiltIndexAwareIdIndexer : PrebuiltIndexProviderBase<Map<IdIndexEntry, Int>>(), LexingIdIndexer { companion object { private val LOG = Logger.getInstance("#com.intellij.index.PrebuiltIndexAwareIdIndexer") const val ID_INDEX_FILE_NAME: String = "id-index" } override val indexName: String get() = ID_INDEX_FILE_NAME override val indexExternalizer: IdIndexMapDataExternalizer get() = IdIndexMapDataExternalizer() override fun map(inputData: FileContent): Map<IdIndexEntry, Int> { val map = get(inputData) return if (map != null) { if (DEBUG_PREBUILT_INDICES) { if (map != idIndexMap(inputData)) { LOG.error("Prebuilt id index differs from actual value for ${inputData.file.path}") } } map } else { idIndexMap(inputData) } } abstract fun idIndexMap(inputData: FileContent): Map<IdIndexEntry, Int> } class IdIndexMapDataExternalizer : DataExternalizer<Map<IdIndexEntry, Int>> { override fun save(out: DataOutput, value: Map<IdIndexEntry, Int>) { DataInputOutputUtil.writeINT(out, value.size) for (e in value.entries) { DataInputOutputUtil.writeINT(out, e.key.wordHashCode) DataInputOutputUtil.writeINT(out, e.value) } } override fun read(`in`: DataInput): Map<IdIndexEntry, Int> { val size = DataInputOutputUtil.readINT(`in`) val map = HashMap<IdIndexEntry, Int>() for (i in 0 until size) { val wordHash = DataInputOutputUtil.readINT(`in`) val value = DataInputOutputUtil.readINT(`in`) map[IdIndexEntry(wordHash)] = value } return map } }
apache-2.0
bbef284de783bbb33adb4d8593023a80
32.875
140
0.720941
4.090566
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/datavalue/internal/DataValueHandler.kt
1
4293
/* * 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.datavalue.internal import java.util.ArrayList import java.util.Arrays import org.hisp.dhis.android.core.arch.db.querybuilders.internal.WhereClauseBuilder import org.hisp.dhis.android.core.arch.db.stores.internal.ObjectWithoutUidStore import org.hisp.dhis.android.core.arch.handlers.internal.HandleAction import org.hisp.dhis.android.core.arch.handlers.internal.ObjectWithoutUidHandlerImpl import org.hisp.dhis.android.core.arch.helpers.CollectionsHelper import org.hisp.dhis.android.core.common.State import org.hisp.dhis.android.core.datavalue.DataValue import org.hisp.dhis.android.core.datavalue.DataValueTableInfo internal class DataValueHandler(store: ObjectWithoutUidStore<DataValue>) : ObjectWithoutUidHandlerImpl<DataValue>( store ) { override fun deleteOrPersist(o: DataValue): HandleAction { return if (CollectionsHelper.isDeleted(o)) { store.deleteWhereIfExists(o) HandleAction.Delete } else { store.updateOrInsertWhere(o) } } override fun beforeCollectionHandled(oCollection: Collection<DataValue>): Collection<DataValue> { val dataValuesPendingToSync = dataValuesPendingToSync val dataValuesToUpdate: MutableList<DataValue> = ArrayList() for (dataValue in oCollection) { if (!containsDataValue(dataValuesPendingToSync, dataValue)) { dataValuesToUpdate.add(dataValue) } } return dataValuesToUpdate } @Suppress("TooGenericExceptionCaught") private fun containsDataValue(dataValues: Collection<DataValue>, target: DataValue): Boolean { return try { for (item in dataValues) { @Suppress("ComplexCondition") if (item.dataElement() == target.dataElement() && item.organisationUnit() == target.organisationUnit() && item.period() == target.period() && item.attributeOptionCombo() == target.attributeOptionCombo() && item.categoryOptionCombo() == target.categoryOptionCombo() ) { return true } } false } catch (e: NullPointerException) { false } } private val dataValuesPendingToSync: List<DataValue> get() { val whereClause = WhereClauseBuilder() .appendNotInKeyStringValues( DataValueTableInfo.Columns.SYNC_STATE, Arrays.asList(State.SYNCED.name, State.SYNCED_VIA_SMS.name) ) .build() return store.selectWhere(whereClause) } }
bsd-3-clause
03cf6240703d4b448c0a8be496f0e787
44.670213
114
0.69392
4.850847
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/segmentedActionBar/SegmentedActionToolbarComponent.kt
2
7725
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.actionSystem.impl.segmentedActionBar import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionButtonLook import com.intellij.openapi.actionSystem.ex.ComboBoxAction import com.intellij.openapi.actionSystem.ex.ComboBoxAction.ComboBoxButton import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.util.ui.JBInsets import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import java.awt.* import javax.swing.JComponent import javax.swing.border.Border open class SegmentedActionToolbarComponent(place: String, group: ActionGroup, val paintBorderForSingleItem: Boolean = true) : ActionToolbarImpl(place, group, true) { companion object { internal const val CONTROL_BAR_PROPERTY = "CONTROL_BAR_PROPERTY" internal const val CONTROL_BAR_FIRST = "CONTROL_BAR_PROPERTY_FIRST" internal const val CONTROL_BAR_LAST = "CONTROL_BAR_PROPERTY_LAST" internal const val CONTROL_BAR_MIDDLE = "CONTROL_BAR_PROPERTY_MIDDLE" internal const val CONTROL_BAR_SINGLE = "CONTROL_BAR_PROPERTY_SINGLE" const val RUN_TOOLBAR_COMPONENT_ACTION = "RUN_TOOLBAR_COMPONENT_ACTION" private val LOG = Logger.getInstance(SegmentedActionToolbarComponent::class.java) internal val segmentedButtonLook = object : ActionButtonLook() { override fun paintBorder(g: Graphics, c: JComponent, state: Int) { } override fun paintBackground(g: Graphics, component: JComponent, state: Int) { SegmentedBarPainter.paintActionButtonBackground(g, component, state) } } fun isCustomBar(component: Component): Boolean { if (component !is JComponent) return false return component.getClientProperty(CONTROL_BAR_PROPERTY)?.let { it != CONTROL_BAR_SINGLE } ?: false } fun paintButtonDecorations(g: Graphics2D, c: JComponent, paint: Paint): Boolean { return SegmentedBarPainter.paintButtonDecorations(g, c, paint) } } init { layoutPolicy = NOWRAP_LAYOUT_POLICY } private var isActive = false private var visibleActions: List<AnAction>? = null override fun getInsets(): Insets { return JBInsets.emptyInsets() } override fun setBorder(border: Border?) { } override fun createCustomComponent(action: CustomComponentAction, presentation: Presentation): JComponent { if (!isActive) { return super.createCustomComponent(action, presentation) } var component = super.createCustomComponent(action, presentation) if (action is ComboBoxAction) { UIUtil.uiTraverser(component).filter(ComboBoxButton::class.java).firstOrNull()?.let { component.remove(it) component = it } } else if (component is ActionButton) { val actionButton = component as ActionButton updateActionButtonLook(actionButton) } component.border = JBUI.Borders.empty() return component } override fun createToolbarButton(action: AnAction, look: ActionButtonLook?, place: String, presentation: Presentation, minimumSize: Dimension): ActionButton { if (!isActive) { return super.createToolbarButton(action, look, place, presentation, minimumSize) } val createToolbarButton = super.createToolbarButton(action, segmentedButtonLook, place, presentation, minimumSize) updateActionButtonLook(createToolbarButton) return createToolbarButton } private fun updateActionButtonLook(actionButton: ActionButton) { actionButton.border = JBUI.Borders.empty(0, 3) actionButton.setLook(segmentedButtonLook) } override fun fillToolBar(actions: List<AnAction>, layoutSecondaries: Boolean) { if (!isActive) { super.fillToolBar(actions, layoutSecondaries) return } val rightAligned: MutableList<AnAction> = ArrayList() for (i in actions.indices) { val action = actions[i] if (action is RightAlignedToolbarAction) { rightAligned.add(action) continue } if (action is CustomComponentAction) { val component = getCustomComponent(action) addMetadata(component, i, actions.size) add(CUSTOM_COMPONENT_CONSTRAINT, component) component.putClientProperty(RUN_TOOLBAR_COMPONENT_ACTION, action) } else { val component = createToolbarButton(action) addMetadata(component, i, actions.size) add(ACTION_BUTTON_CONSTRAINT, component) component.putClientProperty(RUN_TOOLBAR_COMPONENT_ACTION, action) } } } protected open fun isSuitableAction(action: AnAction): Boolean { return true } override fun paintComponent(g: Graphics) { super.paintComponent(g) paintActiveBorder(g) } private fun paintActiveBorder(g: Graphics) { if((isActive || paintBorderForSingleItem) && visibleActions != null) { SegmentedBarPainter.paintActionBarBorder(this, g) } } override fun paintBorder(g: Graphics) { super.paintBorder(g) paintActiveBorder(g) } override fun paint(g: Graphics) { super.paint(g) paintActiveBorder(g) } private fun addMetadata(component: JComponent, index: Int, count: Int) { if (count == 1) { component.putClientProperty(CONTROL_BAR_PROPERTY, CONTROL_BAR_SINGLE) return } val property = when (index) { 0 -> CONTROL_BAR_FIRST count - 1 -> CONTROL_BAR_LAST else -> CONTROL_BAR_MIDDLE } component.putClientProperty(CONTROL_BAR_PROPERTY, property) } protected open fun logNeeded() = false protected fun forceUpdate() { if(logNeeded()) LOG.info("RunToolbar MAIN SLOT forceUpdate") visibleActions?.let { update(true, it) revalidate() repaint() } } override fun actionsUpdated(forced: Boolean, newVisibleActions: List<AnAction>) { visibleActions = newVisibleActions update(forced, newVisibleActions) } private var lastIds: List<String> = emptyList() private fun update(forced: Boolean, newVisibleActions: List<AnAction>) { val filtered = newVisibleActions.filter { isSuitableAction(it) } val ides = newVisibleActions.map { ActionManager.getInstance().getId(it) }.toList() val filteredIds = filtered.map { ActionManager.getInstance().getId(it) }.toList() traceState(lastIds, filteredIds, ides) lastIds = filteredIds isActive = filtered.size > 1 super.actionsUpdated(forced, if (isActive) filtered else newVisibleActions) ApplicationManager.getApplication().messageBus.syncPublisher(ToolbarActionsUpdatedListener.TOPIC).actionsUpdated() } protected open fun traceState(lastIds: List<String>, filteredIds: List<String>, ides: List<String>) { // if(logNeeded() && filteredIds != lastIds) LOG.info("MAIN SLOT new filtered: ${filteredIds}} visible: $ides RunToolbar") } override fun calculateBounds(size2Fit: Dimension, bounds: MutableList<Rectangle>) { bounds.clear() for (i in 0 until componentCount) { bounds.add(Rectangle()) } var offset = 0 for (i in 0 until componentCount) { val d = getChildPreferredSize(i) val r = bounds[i] r.setBounds(insets.left + offset, insets.top, d.width, DEFAULT_MINIMUM_BUTTON_SIZE.height) offset += d.width } } }
apache-2.0
96dc815dbfca3e36e63d869dfeb25777
32.301724
165
0.70835
4.659228
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinMissingForOrWhileBodyFixer.kt
6
1451
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.editor.fixers import com.intellij.lang.SmartEnterProcessorWithFixers import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.editor.KotlinSmartEnterHandler import org.jetbrains.kotlin.psi.KtBlockExpression import org.jetbrains.kotlin.psi.KtForExpression import org.jetbrains.kotlin.psi.KtLoopExpression import org.jetbrains.kotlin.psi.KtWhileExpression class KotlinMissingForOrWhileBodyFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() { override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, element: PsiElement) { if (!(element is KtForExpression || element is KtWhileExpression)) return val loopExpression = element as KtLoopExpression val doc = editor.document val body = loopExpression.body if (body is KtBlockExpression) return if (!loopExpression.isValidLoopCondition()) return if (body != null && body.startLine(doc) == loopExpression.startLine(doc)) return val rParen = loopExpression.rightParenthesis ?: return doc.insertString(rParen.range.end, "{}") } private fun KtLoopExpression.isValidLoopCondition() = leftParenthesis != null && rightParenthesis != null }
apache-2.0
a46d56a5530efd46a758da89c76bb496
40.457143
158
0.769125
4.869128
false
false
false
false
opst-miyatay/LightCalendarView
kotlinsample/src/main/kotlin/jp/co/recruit_mp/android/lightcalendarview/kotlinsample/MainActivity.kt
2
2502
package jp.co.recruit_mp.android.lightcalendarview.kotlinsample import android.os.Bundle import android.os.Handler import android.support.v7.app.AppCompatActivity import android.util.Log import jp.co.recruit_mp.android.lightcalendarview.LightCalendarView import jp.co.recruit_mp.android.lightcalendarview.accent.Accent import jp.co.recruit_mp.android.lightcalendarview.accent.DotAccent import java.text.SimpleDateFormat import java.util.* class MainActivity : AppCompatActivity() { lateinit var calendarView: LightCalendarView private val formatter = SimpleDateFormat("MMMM yyyy", Locale.getDefault()) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) calendarView = findViewById(R.id.calendarView) as? LightCalendarView ?: throw IllegalStateException("calendarView not found") calendarView.apply { monthFrom = Calendar.getInstance().apply { set(Calendar.MONTH, 0) }.time monthTo = Calendar.getInstance().apply { set(Calendar.MONTH, 11) }.time monthCurrent = Calendar.getInstance().time // set the calendar view callbacks onMonthSelected = { date, view -> supportActionBar?.apply { title = formatter.format(date) } // add accents to some days with 1 second delay (simulating I/O delay) Handler().postDelayed({ val cal = Calendar.getInstance() val dates = (1..31).filter { it % 2 == 0 }.map { cal.apply { set(view.month.year + 1900, view.month.month, it) }.time } val map = mutableMapOf<Date, Collection<Accent>>().apply { dates.forEach { date -> val accents = (0..date.date % 3).map { DotAccent(10f, key = "${formatter.format(date)}-$it") } put(date, accents) } } view.setAccents(map) }, 1000) Log.i("MainActivity", "onMonthSelected: date = $date") } onDateSelected = { date -> Log.i("MainActivity", "onDateSelected: date = $date") } } // change the actionbar title supportActionBar?.title = formatter.format(calendarView.monthCurrent) } }
apache-2.0
68df9419a13c0728ff093f270c4be855
38.714286
133
0.589528
4.839458
false
false
false
false
auricgoldfinger/Memento-Namedays
android_mobile/src/main/java/com/alexstyl/specialdates/person/FacebookContactActionsProvider.kt
3
2831
package com.alexstyl.specialdates.person import android.content.res.Resources import android.support.v4.content.res.ResourcesCompat import android.view.View import com.alexstyl.specialdates.R import com.alexstyl.specialdates.Strings import com.alexstyl.specialdates.contact.Contact import com.alexstyl.specialdates.contact.ContactSource.SOURCE_FACEBOOK import java.net.URI class FacebookContactActionsProvider( private val strings: Strings, private val resources: Resources) : ContactActionsProvider { override fun callActionsFor(contact: Contact, actions: ContactActions): List<ContactActionViewModel> { ensureItsAFacebookContact(contact) val action = ContactAction( strings.call(), strings.facebookMessenger(), actions.view(URI.create("fb-messenger://user/" + contact.contactID)) // TODO check what happens if no messenger installed ) return ContactActionViewModel( action, View.VISIBLE, ResourcesCompat.getDrawable(resources, R.drawable.ic_facebook_messenger, null)!!) .toList() } override fun messagingActionsFor(contact: Contact, actions: ContactActions): List<ContactActionViewModel> { ensureItsAFacebookContact(contact) return arrayListOf( goToWallAction(contact, actions), messengerAction(contact, actions)) } private fun messengerAction(contact: Contact, executor: ContactActions): ContactActionViewModel = ContactActionViewModel( ContactAction( strings.viewConversation(), strings.facebookMessenger(), executor.view(URI.create("fb-messenger://user/" + contact.contactID)) ), View.VISIBLE, ResourcesCompat.getDrawable(resources, R.drawable.ic_facebook_messenger, null)!!) private fun goToWallAction(contact: Contact, executor: ContactActions): ContactActionViewModel = ContactActionViewModel( ContactAction( strings.postOnFacebook(), strings.facebook(), executor.view(URI.create("https://www.facebook.com/profile.php?id=" + contact.contactID)) ), View.VISIBLE, ResourcesCompat.getDrawable(resources, R.drawable.ic_f_icon, null)!!) private fun ensureItsAFacebookContact(contact: Contact) { if (contact.source != SOURCE_FACEBOOK) { throw IllegalArgumentException("Can only create actions for Facebook contacts. Asked for [$contact] instead") } } } private fun ContactActionViewModel.toList(): List<ContactActionViewModel> { val arrayList = ArrayList<ContactActionViewModel>() arrayList.add(this) return arrayList }
mit
293a9f107127d8d569d1328ea5b50371
40.632353
137
0.672554
5.262082
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/forge/version/ForgeVersion.kt
1
2645
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.forge.version import com.demonwav.mcdev.util.sortVersions import java.io.IOException import java.net.URL import javax.xml.stream.XMLInputFactory import javax.xml.stream.events.XMLEvent class ForgeVersion private constructor(val versions: List<String>) { val sortedMcVersions: List<String> by lazy { val unsortedVersions = versions.asSequence() .mapNotNull( fun(version: String): String? { val index = version.indexOf('-') if (index == -1) { return null } return version.substring(0, index) } ).distinct() .toList() return@lazy sortVersions(unsortedVersions) } fun getForgeVersions(mcVersion: String): ArrayList<String> { return versions.filterTo(ArrayList()) { it.startsWith(mcVersion) } } companion object { fun downloadData(): ForgeVersion? { try { val url = URL("https://files.minecraftforge.net/maven/net/minecraftforge/forge/maven-metadata.xml") val result = mutableListOf<String>() url.openStream().use { stream -> val inputFactory = XMLInputFactory.newInstance() @Suppress("UNCHECKED_CAST") val reader = inputFactory.createXMLEventReader(stream) as Iterator<XMLEvent> for (event in reader) { if (!event.isStartElement) { continue } val start = event.asStartElement() val name = start.name.localPart if (name != "version") { continue } val versionEvent = reader.next() if (!versionEvent.isCharacters) { continue } val version = versionEvent.asCharacters().data val index = version.indexOf('-') if (index == -1) { continue } result += version } } return ForgeVersion(result) } catch (e: IOException) { e.printStackTrace() } return null } } }
mit
580340f01693057b3bd535c6f165e2f3
32.0625
115
0.485066
5.521921
false
false
false
false
google/intellij-community
plugins/kotlin/code-insight/impl-base/src/org/jetbrains/kotlin/idea/codeinsights/impl/base/applicators/CallableReturnTypeUpdaterApplicator.kt
3
10027
// 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.codeInsight.template.Template import com.intellij.codeInsight.template.TemplateBuilderImpl import com.intellij.codeInsight.template.TemplateEditingAdapter import com.intellij.codeInsight.template.TemplateManager import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiComment import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.components.KtTypeRendererOptions import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.types.KtType import org.jetbrains.kotlin.analysis.api.types.KtTypeNullability import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicatorInput import org.jetbrains.kotlin.idea.codeinsight.api.applicators.applicator import org.jetbrains.kotlin.idea.base.analysis.api.utils.shortenReferences import org.jetbrains.kotlin.idea.codeinsight.utils.ChooseValueExpression import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.CallableReturnTypeUpdaterApplicator.TypeInfo.Companion.createByKtTypes import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.psi.KtCallableDeclaration import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.kotlin.util.bfs object CallableReturnTypeUpdaterApplicator { val applicator = applicator<KtCallableDeclaration, TypeInfo> { familyAndActionName(KotlinBundle.lazyMessage("fix.change.return.type.family")) applyTo { declaration, typeInfo, project, editor -> if (editor == null || !typeInfo.useTemplate || !ApplicationManager.getApplication().isWriteAccessAllowed) { declaration.setType(typeInfo.defaultType, project) } else { setTypeWithTemplate(listOf(declaration to typeInfo).iterator(), project, editor) } } } private fun KtCallableDeclaration.setType(type: TypeInfo.Type, project: Project) { val newTypeRef = if (isProcedure(type)) { null } else { KtPsiFactory(project).createType(type.longTypeRepresentation) } typeReference = newTypeRef typeReference?.let { shortenReferences(it) } } private fun KtCallableDeclaration.isProcedure(type: TypeInfo.Type) = type.isUnit && this is KtFunction && hasBlockBody() /** * @param declarationAndTypes multiple declarations and types that need to be updated. If multiple pairs are passed, the IDE will guide * user to modify them one by one. */ // TODO: add applicator that passes multiple declarations and types, for example, for specifying types of destructuring declarations. private fun setTypeWithTemplate( declarationAndTypes: Iterator<Pair<KtCallableDeclaration, TypeInfo>>, project: Project, editor: Editor ) { if (!declarationAndTypes.hasNext()) return val (declaration: KtCallableDeclaration, typeInfo: TypeInfo) = declarationAndTypes.next() // Set a placeholder type so that it can be referenced declaration.setType(TypeInfo.ANY, project) PsiDocumentManager.getInstance(project).apply { commitAllDocuments() doPostponedOperationsAndUnblockDocument(editor.document) } val newTypeRef = declaration.typeReference ?: return val builder = TemplateBuilderImpl(newTypeRef) builder.replaceElement( newTypeRef, TypeChooseValueExpression(listOf(typeInfo.defaultType) + typeInfo.otherTypes, typeInfo.defaultType) ) editor.caretModel.moveToOffset(newTypeRef.node.startOffset) TemplateManager.getInstance(project).startTemplate( editor, builder.buildInlineTemplate(), object : TemplateEditingAdapter() { override fun templateFinished(template: Template, brokenOff: Boolean) { val typeRef = declaration.typeReference if (typeRef != null && typeRef.isValid) { runWriteAction { shortenReferences(typeRef) setTypeWithTemplate(declarationAndTypes, project, editor) } } } } ) } private class TypeChooseValueExpression( items: List<TypeInfo.Type>, defaultItem: TypeInfo.Type ) : ChooseValueExpression<TypeInfo.Type>(items, defaultItem) { override fun getLookupString(element: TypeInfo.Type): String = element.shortTypeRepresentation override fun getResult(element: TypeInfo.Type): String = element.longTypeRepresentation } fun KtAnalysisSession.getTypeInfo(declaration: KtCallableDeclaration): CallableReturnTypeUpdaterApplicator.TypeInfo { val declarationType = declaration.getReturnKtType() val overriddenTypes = (declaration.getSymbol() as? KtCallableSymbol)?.getDirectlyOverriddenSymbols() ?.map { it.returnType } ?.distinct() ?: emptyList() val cannotBeNull = overriddenTypes.any { !it.canBeNull } val allTypes = (listOf(declarationType) + overriddenTypes) // Here we do BFS manually rather than invoke `getAllSuperTypes` because we have multiple starting points. Simply calling // `getAllSuperTypes` does not work because it would BFS traverse each starting point and put the result together, in which // case, for example, calling `getAllSuperTypes` would put `Any` at middle if one of the super type in the hierarchy has // multiple super types. .bfs { it.getDirectSuperTypes(shouldApproximate = true).iterator() } .map { it.approximateToSuperPublicDenotableOrSelf() } .distinct() .let { types -> when { cannotBeNull -> types.map { it.withNullability(KtTypeNullability.NON_NULLABLE) }.distinct() declarationType.hasFlexibleNullability -> types.flatMap { type -> listOf(type.withNullability(KtTypeNullability.NON_NULLABLE), type.withNullability(KtTypeNullability.NULLABLE)) } else -> types } }.toList() return with(CallableReturnTypeUpdaterApplicator.TypeInfo) { if (ApplicationManager.getApplication().isUnitTestMode) { selectForUnitTest(declaration, allTypes)?.let { return it } } val approximatedDefaultType = declarationType.approximateToSuperPublicDenotableOrSelf().let { if (cannotBeNull) it.withNullability(KtTypeNullability.NON_NULLABLE) else it } createByKtTypes( approximatedDefaultType, allTypes.drop(1), // The first type is always the default type so we drop it. useTemplate = true ) } } // The following logic is copied from FE1.0 at // org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention.Companion#createTypeExpressionForTemplate private fun KtAnalysisSession.selectForUnitTest( declaration: KtCallableDeclaration, allTypes: List<KtType> ): CallableReturnTypeUpdaterApplicator.TypeInfo? { // This helps to be sure no nullable types are suggested if (declaration.containingKtFile.findDescendantOfType<PsiComment>()?.takeIf { it.text == "// CHOOSE_NULLABLE_TYPE_IF_EXISTS" } != null) { val targetType = allTypes.firstOrNull { it.isMarkedNullable } ?: allTypes.first() return createByKtTypes(targetType) } // This helps to be sure something except Nothing is suggested if (declaration.containingKtFile.findDescendantOfType<PsiComment>()?.takeIf { it.text == "// DO_NOT_CHOOSE_NOTHING" } != null ) { // Note that `isNothing` returns true for both `Nothing` and `Nothing?` val targetType = allTypes.firstOrNull { !it.isNothing } ?: allTypes.first() return createByKtTypes(targetType) } return null } class TypeInfo( val defaultType: Type, val otherTypes: List<Type> = emptyList(), val useTemplate: Boolean = false, ) : KotlinApplicatorInput { class Type(val isUnit: Boolean, val longTypeRepresentation: String, val shortTypeRepresentation: String) override fun isValidFor(psi: PsiElement): Boolean = true companion object { fun KtAnalysisSession.createByKtTypes( ktType: KtType, otherTypes: List<KtType> = emptyList(), useTemplate: Boolean = false ): TypeInfo = TypeInfo(createTypeByKtType(ktType), otherTypes.map { createTypeByKtType(it) }, useTemplate) private fun KtAnalysisSession.createTypeByKtType(ktType: KtType): Type = Type( isUnit = ktType.isUnit, longTypeRepresentation = ktType.render(KtTypeRendererOptions.DEFAULT), shortTypeRepresentation = ktType.render(KtTypeRendererOptions.SHORT_NAMES), ) val UNIT = Type(isUnit = true, longTypeRepresentation = "kotlin.Unit", shortTypeRepresentation = "Unit") val ANY = Type(isUnit = false, longTypeRepresentation = "kotlin.Any", shortTypeRepresentation = "Any") } } }
apache-2.0
210462da6aeabf56cd7d4b9519973e62
47.674757
139
0.681959
5.39086
false
false
false
false
google/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/buildtool/MavenSyncConsole.kt
1
24573
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.maven.buildtool import com.intellij.build.BuildProgressListener import com.intellij.build.DefaultBuildDescriptor import com.intellij.build.FilePosition import com.intellij.build.SyncViewManager import com.intellij.build.events.BuildEvent import com.intellij.build.events.EventResult import com.intellij.build.events.MessageEvent import com.intellij.build.events.MessageEventResult import com.intellij.build.events.impl.* import com.intellij.build.issue.BuildIssue import com.intellij.build.issue.BuildIssueQuickFix import com.intellij.execution.ExecutionException import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.externalSystem.issue.BuildIssueException import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType import com.intellij.openapi.externalSystem.util.ExternalSystemUtil import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.pom.Navigatable import com.intellij.util.ExceptionUtil import com.intellij.util.ThreeState import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import org.jetbrains.idea.maven.buildtool.quickfix.OffMavenOfflineModeQuickFix import org.jetbrains.idea.maven.buildtool.quickfix.OpenMavenSettingsQuickFix import org.jetbrains.idea.maven.buildtool.quickfix.UseBundledMavenQuickFix import org.jetbrains.idea.maven.execution.SyncBundle import org.jetbrains.idea.maven.externalSystemIntegration.output.importproject.quickfixes.DownloadArtifactBuildIssue import org.jetbrains.idea.maven.model.MavenProjectProblem import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.project.MavenWorkspaceSettingsComponent import org.jetbrains.idea.maven.server.CannotStartServerException import org.jetbrains.idea.maven.server.MavenServerManager import org.jetbrains.idea.maven.server.MavenServerProgressIndicator import org.jetbrains.idea.maven.utils.MavenLog import org.jetbrains.idea.maven.utils.MavenUtil import java.io.File class MavenSyncConsole(private val myProject: Project) { @Volatile private var mySyncView: BuildProgressListener = BuildProgressListener { _, _ -> } private var mySyncId = createTaskId() private var finished = false private var started = false private var syncTransactionStarted = false private var hasErrors = false private var hasUnresolved = false private val JAVADOC_AND_SOURCE_CLASSIFIERS = setOf("javadoc", "sources", "test-javadoc", "test-sources") private val shownIssues = HashSet<String>() private val myPostponed = ArrayList<() -> Unit>() private var myStartedSet = LinkedHashSet<Pair<Any, String>>() @Synchronized fun startImport(syncView: BuildProgressListener, spec: MavenImportSpec) { if (started) { return } val restartAction: AnAction = object : AnAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabled = !started || finished e.presentation.icon = AllIcons.Actions.Refresh } override fun actionPerformed(e: AnActionEvent) { e.project?.let { MavenProjectsManager.getInstance(it).forceUpdateAllProjectsOrFindAllAvailablePomFiles() } } override fun getActionUpdateThread() = ActionUpdateThread.BGT } started = true finished = false hasErrors = false hasUnresolved = false mySyncView = syncView shownIssues.clear() mySyncId = createTaskId() val descriptor = DefaultBuildDescriptor(mySyncId, SyncBundle.message("maven.sync.title"), myProject.basePath!!, System.currentTimeMillis()) .withRestartAction(restartAction) descriptor.isActivateToolWindowWhenFailed = spec.isExplicitImport descriptor.isActivateToolWindowWhenAdded = ExternalSystemUtil.isNewProject(myProject) descriptor.isNavigateToError = if (spec.isExplicitImport) ThreeState.YES else ThreeState.UNSURE mySyncView.onEvent(mySyncId, StartBuildEventImpl(descriptor, SyncBundle.message("maven.sync.project.title", myProject.name))) debugLog("maven sync: started importing $myProject") myPostponed.forEach(this::doIfImportInProcess) myPostponed.clear() } private fun createTaskId() = ExternalSystemTaskId.create(MavenUtil.SYSTEM_ID, ExternalSystemTaskType.RESOLVE_PROJECT, myProject) fun getTaskId() = mySyncId fun addText(@Nls text: String) = addText(text, true) @Synchronized fun addText(@Nls text: String, stdout: Boolean) = doIfImportInProcess { addText(mySyncId, text, true) } @Synchronized fun addWrapperProgressText(@Nls text: String) = doIfImportInProcess { addText(SyncBundle.message("maven.sync.wrapper"), text, true) } @Synchronized private fun addText(parentId: Any, @Nls text: String, stdout: Boolean) = doIfImportInProcess { if (StringUtil.isEmpty(text)) { return } val toPrint = if (text.endsWith('\n')) text else "$text\n" mySyncView.onEvent(mySyncId, OutputBuildEventImpl(parentId, toPrint, stdout)) } @Synchronized fun addBuildEvent(buildEvent: BuildEvent) = doIfImportInProcess { mySyncView.onEvent(mySyncId, buildEvent) } @Synchronized fun addWarning(@Nls text: String, @Nls description: String) = addWarning(text, description, null) fun addBuildIssue(issue: BuildIssue, kind: MessageEvent.Kind) = doIfImportInProcessOrPostpone { if (!newIssue(issue.title + issue.description)) return@doIfImportInProcessOrPostpone mySyncView.onEvent(mySyncId, BuildIssueEventImpl(mySyncId, issue, kind)) hasErrors = hasErrors || kind == MessageEvent.Kind.ERROR } @Synchronized fun addWarning(@Nls text: String, @Nls description: String, filePosition: FilePosition?) = doIfImportInProcess { if (!newIssue(text + description + filePosition)) return if (filePosition == null) { mySyncView.onEvent(mySyncId, MessageEventImpl(mySyncId, MessageEvent.Kind.WARNING, SyncBundle.message("maven.sync.group.compiler"), text, description)) } else { mySyncView.onEvent(mySyncId, FileMessageEventImpl(mySyncId, MessageEvent.Kind.WARNING, SyncBundle.message("maven.sync.group.compiler"), text, description, filePosition)) } } private fun newIssue(s: String): Boolean { return shownIssues.add(s) } @Synchronized fun finishImport() { debugLog("Maven sync: finishImport") doFinish() } fun terminated(exitCode: Int) = doIfImportInProcess { if (EXIT_CODE_OK == exitCode || EXIT_CODE_SIGTERM == exitCode) doFinish() else doTerminate(exitCode) } private fun doTerminate(exitCode: Int) { if (syncTransactionStarted) { debugLog("Maven sync: sync transaction is still not finished, postpone build finish event") return } val tasks = myStartedSet.toList().asReversed() debugLog("Tasks $tasks are not completed! Force complete") tasks.forEach { completeTask(it.first, it.second, FailureResultImpl(SyncBundle.message("maven.sync.failure.terminated", exitCode))) } mySyncView.onEvent(mySyncId, FinishBuildEventImpl(mySyncId, null, System.currentTimeMillis(), "", FailureResultImpl(SyncBundle.message("maven.sync.failure.terminated", exitCode)))) finished = true started = false } @Synchronized fun startWrapperResolving() { if (!started || finished) { startImport(myProject.getService(SyncViewManager::class.java), MavenImportSpec.EXPLICIT_IMPORT) } startTask(mySyncId, SyncBundle.message("maven.sync.wrapper")) } @Synchronized fun finishWrapperResolving(e: Throwable? = null) { if (e != null) { addBuildIssue(object : BuildIssue { override val title: String = SyncBundle.message("maven.sync.wrapper.failure") override val description: String = SyncBundle.message("maven.sync.wrapper.failure.description", e.localizedMessage, OpenMavenSettingsQuickFix.ID) override val quickFixes: List<BuildIssueQuickFix> = listOf(OpenMavenSettingsQuickFix()) override fun getNavigatable(project: Project): Navigatable? = null }, MessageEvent.Kind.WARNING) } completeTask(mySyncId, SyncBundle.message("maven.sync.wrapper"), SuccessResultImpl()) } @Synchronized fun notifyReadingProblems(file: VirtualFile) = doIfImportInProcess { debugLog("reading problems in $file") hasErrors = true val desc = SyncBundle.message("maven.sync.failure.error.reading.file", file.path) mySyncView.onEvent(mySyncId, FileMessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, SyncBundle.message("maven.sync.group.error"), desc, desc, FilePosition(File(file.path), -1, -1))) } @Synchronized fun showProblem(problem: MavenProjectProblem) = doIfImportInProcess { hasErrors = true val group = SyncBundle.message("maven.sync.group.error") val position = problem.getFilePosition() val message = problem.description ?: SyncBundle.message("maven.sync.failure.error.undefined.message") val detailedMessage = problem.description ?: SyncBundle.message("maven.sync.failure.error.undefined.detailed.message", problem.path) val eventImpl = FileMessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, group, message, detailedMessage, position) mySyncView.onEvent(mySyncId, eventImpl) } private fun MavenProjectProblem.getFilePosition(): FilePosition { val (line, column) = getPositionFromDescription() ?: getPositionFromPath() ?: (-1 to -1) val pathWithoutPosition = path.substringBeforeLast(":${line + 1}:$column") return FilePosition(File(pathWithoutPosition), line, column) } private fun MavenProjectProblem.getPositionFromDescription(): Pair<Int, Int>? { return getPosition(description, Regex("@(\\d+):(\\d+)")) } private fun MavenProjectProblem.getPositionFromPath(): Pair<Int, Int>? { return getPosition(path, Regex(":(\\d+):(\\d+)")) } private fun MavenProjectProblem.getPosition(source: String?, pattern: Regex): Pair<Int, Int>? { if (source == null) return null if (type == MavenProjectProblem.ProblemType.STRUCTURE) { val matchResults = pattern.findAll(source) val matchResult = matchResults.lastOrNull() ?: return null val (_, line, offset) = matchResult.groupValues return line.toInt() - 1 to offset.toInt() } return null } @Synchronized @ApiStatus.Internal fun addException(e: Throwable, progressListener: BuildProgressListener) { if (started && !finished) { MavenLog.LOG.warn(e) hasErrors = true val buildIssueException = ExceptionUtil.findCause(e, BuildIssueException::class.java) if (buildIssueException != null) { addBuildIssue(buildIssueException.buildIssue, MessageEvent.Kind.ERROR) } else { mySyncView.onEvent(mySyncId, createMessageEvent(e)) } } else { this.startImport(progressListener, MavenImportSpec.EXPLICIT_IMPORT) this.addException(e, progressListener) this.finishImport() } } private fun createMessageEvent(e: Throwable): MessageEventImpl { val csse = ExceptionUtil.findCause(e, CannotStartServerException::class.java) if (csse != null) { val cause = ExceptionUtil.findCause(csse, ExecutionException::class.java) if (cause != null) { return MessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, SyncBundle.message("build.event.title.internal.server.error"), getExceptionText(cause), getExceptionText(cause)) } else { return MessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, SyncBundle.message("build.event.title.internal.server.error"), getExceptionText(csse), getExceptionText(csse)) } } return MessageEventImpl(mySyncId, MessageEvent.Kind.ERROR, SyncBundle.message("build.event.title.error"), getExceptionText(e), getExceptionText(e)) } private fun getExceptionText(e: Throwable): @NlsSafe String { if (MavenWorkspaceSettingsComponent.getInstance(myProject).settings.getGeneralSettings().isPrintErrorStackTraces) { return ExceptionUtil.getThrowableText(e) } if (!e.localizedMessage.isNullOrEmpty()) return e.localizedMessage return if (StringUtil.isEmpty(e.message)) SyncBundle.message("build.event.title.error") else e.message!! } fun getListener(type: MavenServerProgressIndicator.ResolveType): ArtifactSyncListener { return when (type) { MavenServerProgressIndicator.ResolveType.PLUGIN -> ArtifactSyncListenerImpl("maven.sync.plugins") MavenServerProgressIndicator.ResolveType.DEPENDENCY -> ArtifactSyncListenerImpl("maven.sync.dependencies") } } @Synchronized private fun doFinish() { if (syncTransactionStarted) { debugLog("Maven sync: sync transaction is still not finished, postpone build finish event") return } val tasks = myStartedSet.toList().asReversed() debugLog("Tasks $tasks are not completed! Force complete") tasks.forEach { completeTask(it.first, it.second, DerivedResultImpl()) } mySyncView.onEvent(mySyncId, FinishBuildEventImpl(mySyncId, null, System.currentTimeMillis(), "", if (hasErrors) FailureResultImpl() else DerivedResultImpl())) attachOfflineQuickFix() finished = true started = false } private fun attachOfflineQuickFix() { try { val generalSettings = MavenWorkspaceSettingsComponent.getInstance(myProject).settings.generalSettings if (hasUnresolved && generalSettings.isWorkOffline) { mySyncView.onEvent(mySyncId, BuildIssueEventImpl(mySyncId, object : BuildIssue { override val title: String = "Dependency Resolution Failed" override val description: String = "<a href=\"${OffMavenOfflineModeQuickFix.ID}\">Switch Off Offline Mode</a>\n" override val quickFixes: List<BuildIssueQuickFix> = listOf(OffMavenOfflineModeQuickFix()) override fun getNavigatable(project: Project): Navigatable? = null }, MessageEvent.Kind.ERROR)) } } catch (ignore: Exception) { } } @Synchronized private fun showError(keyPrefix: String, dependency: String) = doIfImportInProcess { hasErrors = true hasUnresolved = true val umbrellaString = SyncBundle.message("${keyPrefix}.resolve") val errorString = SyncBundle.message("${keyPrefix}.resolve.error", dependency) startTask(mySyncId, umbrellaString) mySyncView.onEvent(mySyncId, MessageEventImpl(umbrellaString, MessageEvent.Kind.ERROR, SyncBundle.message("maven.sync.group.error"), errorString, errorString)) addText(mySyncId, errorString, false) } @Synchronized private fun showBuildIssue(keyPrefix: String, dependency: String, errorMessage: String?) = doIfImportInProcess { hasErrors = true hasUnresolved = true val umbrellaString = SyncBundle.message("${keyPrefix}.resolve") val errorString = SyncBundle.message("${keyPrefix}.resolve.error", dependency) startTask(mySyncId, umbrellaString) val buildIssue = DownloadArtifactBuildIssue.getIssue(errorString, errorMessage ?: errorString) mySyncView.onEvent(mySyncId, BuildIssueEventImpl(umbrellaString, buildIssue, MessageEvent.Kind.ERROR)) addText(mySyncId, errorString, false) } @Synchronized private fun showBuildIssueNode(key: String, buildIssue: BuildIssue) = doIfImportInProcess { hasErrors = true hasUnresolved = true startTask(mySyncId, key) mySyncView.onEvent(mySyncId, BuildIssueEventImpl(key, buildIssue, MessageEvent.Kind.ERROR)) } @Synchronized private fun startTask(parentId: Any, @NlsSafe taskName: String) = doIfImportInProcess { debugLog("Maven sync: start $taskName") if (myStartedSet.add(parentId to taskName)) { mySyncView.onEvent(mySyncId, StartEventImpl(taskName, parentId, System.currentTimeMillis(), taskName)) } } @Synchronized private fun completeTask(parentId: Any, @NlsSafe taskName: String, result: EventResult) = doIfImportInProcess { hasErrors = hasErrors || result is FailureResultImpl debugLog("Maven sync: complete $taskName with $result") if (myStartedSet.remove(parentId to taskName)) { mySyncView.onEvent(mySyncId, FinishEventImpl(taskName, parentId, System.currentTimeMillis(), taskName, result)) } } @Synchronized private fun completeUmbrellaEvents(keyPrefix: String) = doIfImportInProcess { val taskName = SyncBundle.message("${keyPrefix}.resolve") completeTask(mySyncId, taskName, DerivedResultImpl()) } @Synchronized private fun downloadEventStarted(keyPrefix: String, dependency: String) = doIfImportInProcess { val downloadString = SyncBundle.message("${keyPrefix}.download") val downloadArtifactString = SyncBundle.message("${keyPrefix}.artifact.download", dependency) startTask(mySyncId, downloadString) startTask(downloadString, downloadArtifactString) } @Synchronized private fun downloadEventCompleted(keyPrefix: String, dependency: String) = doIfImportInProcess { val downloadString = SyncBundle.message("${keyPrefix}.download") val downloadArtifactString = SyncBundle.message("${keyPrefix}.artifact.download", dependency) addText(downloadArtifactString, downloadArtifactString, true) completeTask(downloadString, downloadArtifactString, SuccessResultImpl(false)) } @Synchronized private fun downloadEventFailed(keyPrefix: String, @NlsSafe dependency: String, @NlsSafe error: String, @NlsSafe stackTrace: String?) = doIfImportInProcess { val downloadString = SyncBundle.message("${keyPrefix}.download") val downloadArtifactString = SyncBundle.message("${keyPrefix}.artifact.download", dependency) if (isJavadocOrSource(dependency)) { addText(downloadArtifactString, SyncBundle.message("maven.sync.failure.dependency.not.found", dependency), true) completeTask(downloadString, downloadArtifactString, object : MessageEventResult { override fun getKind(): MessageEvent.Kind { return MessageEvent.Kind.WARNING } override fun getDetails(): String? { return SyncBundle.message("maven.sync.failure.dependency.not.found", dependency) } }) } else { if (stackTrace != null && Registry.`is`("maven.spy.events.debug")) { addText(downloadArtifactString, stackTrace, false) } else { addText(downloadArtifactString, error, true) } completeTask(downloadString, downloadArtifactString, FailureResultImpl(error)) } } @Synchronized fun showQuickFixBadMaven(message: String, kind: MessageEvent.Kind) { val bundledVersion = MavenServerManager.getMavenVersion(MavenServerManager.BUNDLED_MAVEN_3) mySyncView.onEvent(mySyncId, BuildIssueEventImpl(mySyncId, object : BuildIssue { override val title = SyncBundle.message("maven.sync.version.issue.title") override val description: String = "${message}\n" + "- <a href=\"${OpenMavenSettingsQuickFix.ID}\">" + SyncBundle.message("maven.sync.version.open.settings") + "</a>\n" + "- <a href=\"${UseBundledMavenQuickFix.ID}\">" + SyncBundle.message("maven.sync.version.use.bundled", bundledVersion) + "</a>\n" override val quickFixes: List<BuildIssueQuickFix> = listOf(OpenMavenSettingsQuickFix(), UseBundledMavenQuickFix()) override fun getNavigatable(project: Project): Navigatable? = null }, kind)) } fun <Result> runTask(@NlsSafe taskName: String, task: () -> Result): Result { startTask(mySyncId, taskName) val startTime = System.currentTimeMillis() try { return task().also { completeTask(mySyncId, taskName, SuccessResultImpl()) } } catch (e: Exception) { completeTask(mySyncId, taskName, FailureResultImpl(e)) throw e } finally { MavenLog.LOG.info("[maven import] $taskName took ${System.currentTimeMillis() - startTime}ms") } } @Synchronized fun showQuickFixJDK(version: String) { mySyncView.onEvent(mySyncId, BuildIssueEventImpl(mySyncId, object : BuildIssue { override val title = SyncBundle.message("maven.sync.quickfixes.maven.jdk.version.title") override val description: String = SyncBundle.message("maven.sync.quickfixes.upgrade.to.jdk7", version) + "\n" + "- <a href=\"${OpenMavenSettingsQuickFix.ID}\">" + SyncBundle.message("maven.sync.quickfixes.open.settings") + "</a>\n" override val quickFixes: List<BuildIssueQuickFix> = listOf(OpenMavenSettingsQuickFix()) override fun getNavigatable(project: Project): Navigatable? = null }, MessageEvent.Kind.ERROR)) } private fun isJavadocOrSource(dependency: String): Boolean { val split = dependency.split(':') if (split.size < 4) { return false } val classifier = split.get(2) return JAVADOC_AND_SOURCE_CLASSIFIERS.contains(classifier) } private inline fun doIfImportInProcess(action: () -> Unit) { if (!started || finished) return action.invoke() } private fun doIfImportInProcessOrPostpone(action: () -> Unit) { if (!started || finished) { myPostponed.add(action) } else { action.invoke() } } private inner class ArtifactSyncListenerImpl(val keyPrefix: String) : ArtifactSyncListener { override fun downloadStarted(dependency: String) { downloadEventStarted(keyPrefix, dependency) } override fun downloadCompleted(dependency: String) { downloadEventCompleted(keyPrefix, dependency) } override fun downloadFailed(dependency: String, error: String, stackTrace: String?) { downloadEventFailed(keyPrefix, dependency, error, stackTrace) } override fun finish() { completeUmbrellaEvents(keyPrefix) } override fun showError(dependency: String) { showError(keyPrefix, dependency) } override fun showArtifactBuildIssue(dependency: String, errorMessage: String?) { showBuildIssue(keyPrefix, dependency, errorMessage) } override fun showBuildIssue(dependency: String, buildIssue: BuildIssue) { showBuildIssueNode(keyPrefix, buildIssue) } } companion object { val EXIT_CODE_OK = 0 val EXIT_CODE_SIGTERM = 143 @ApiStatus.Experimental @JvmStatic fun startTransaction(project: Project) { debugLog("Maven sync: start sync transaction") val syncConsole = MavenProjectsManager.getInstance(project).syncConsole synchronized(syncConsole) { syncConsole.syncTransactionStarted = true } } @ApiStatus.Experimental @JvmStatic fun finishTransaction(project: Project) { debugLog("Maven sync: finish sync transaction") val syncConsole = MavenProjectsManager.getInstance(project).syncConsole synchronized(syncConsole) { syncConsole.syncTransactionStarted = false syncConsole.finishImport() } } private fun debugLog(s: String, exception: Throwable? = null) { MavenLog.LOG.debug(s, exception) } } } interface ArtifactSyncListener { fun showError(dependency: String) fun showArtifactBuildIssue(dependency: String, errorMessage: String?) fun showBuildIssue(dependency: String, buildIssue: BuildIssue) fun downloadStarted(dependency: String) fun downloadCompleted(dependency: String) fun downloadFailed(dependency: String, error: String, stackTrace: String?) fun finish() }
apache-2.0
04b965002c3090e5665ba497dd8ff853
40.023372
137
0.712774
4.933347
false
false
false
false
Virtlink/aesi
pie/src/main/kotlin/com/virtlink/dummy/DummyCodeCompletionBuilder.kt
1
2607
package com.virtlink.dummy import com.google.inject.Inject import com.virtlink.editorservices.ISessionManager import com.virtlink.editorservices.Offset import com.virtlink.editorservices.ScopeNames import com.virtlink.editorservices.codecompletion.CompletionInfo import com.virtlink.editorservices.codecompletion.CompletionProposal import com.virtlink.editorservices.codecompletion.ICompletionInfo import com.virtlink.editorservices.resources.IResourceManager import com.virtlink.pie.DocumentReq import com.virtlink.pie.codecompletion.PieCodeCompletionService import mb.pie.runtime.core.BuildContext import mb.pie.runtime.core.Builder import org.slf4j.LoggerFactory import java.net.URI class DummyCodeCompletionBuilder @Inject constructor( private val sessionManager: ISessionManager, private val resourceManager: IResourceManager) : Builder<PieCodeCompletionService.Input, ICompletionInfo> { companion object { @JvmField val id: String = "getCompletionInfo" } override val id = Companion.id private val logger = LoggerFactory.getLogger(DummyCodeCompletionBuilder::class.java) override fun BuildContext.build(input: PieCodeCompletionService.Input): ICompletionInfo = this.getCompletionInfo( input.document, input.caretOffset) private fun BuildContext.getCompletionInfo( document: URI, caretOffset: Offset): ICompletionInfo { logger.info("$document: Completing at $caretOffset.") val content = resourceManager.getContent(document) val version = content?.lastModificationStamp ?: -1 val session = sessionManager.currentSessionId!! require(DocumentReq(document, version, session)) val proposals = listOf( CompletionProposal("Hello", description = "Description string", content = "hello world!", scopes = ScopeNames("meta.field", "meta.static")), CompletionProposal("Local variable", content = "local var", scopes = ScopeNames("meta.variable", "meta.internal")), CompletionProposal("Method", content = "method()", caret = 7, scopes = ScopeNames("meta.method", "meta.abstract", "meta.deprecated", "meta.package")), CompletionProposal("if (then else)") ) // TODO: Determine prefix according to language rules. return CompletionInfo("", proposals) } }
apache-2.0
afa2f2b5806291be1be9d34ef256a235
38.515152
112
0.674722
5.353183
false
false
false
false
google/intellij-community
platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/manage/SourceFolderManagerTest.kt
3
5403
// 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.externalSystem.service.project.manage import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.ModuleTypeId import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.testFramework.HeavyPlatformTestCase import com.intellij.testFramework.PlatformTestUtil import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.storage.VersionedStorageChange import junit.framework.TestCase import org.assertj.core.api.BDDAssertions.then import org.jetbrains.jps.model.java.JavaSourceRootType import java.io.File class SourceFolderManagerTest: HeavyPlatformTestCase() { fun `test source folder is added to content root when created`() { val rootManager = ModuleRootManager.getInstance(module) val modifiableModel = rootManager.modifiableModel modifiableModel.addContentEntry(tempDir.createVirtualDir()) runWriteAction { modifiableModel.commit() } val manager = SourceFolderManager.getInstance(project) as SourceFolderManagerImpl val folderUrl = ModuleRootManager.getInstance(module).contentRootUrls[0] + "/newFolder" val folderFile = File(VfsUtilCore.urlToPath(folderUrl)) manager.addSourceFolder(module, folderUrl, JavaSourceRootType.SOURCE) val file = File(folderFile, "file.txt") FileUtil.writeToFile(file, "SomeContent") LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file) manager.consumeBulkOperationsState { PlatformTestUtil.waitForFuture(it, 1000)} then(rootManager.contentEntries[0].sourceFolders) .hasSize(1) .extracting("url") .containsExactly(folderUrl) } fun `test new content root is created if source folder does not belong to existing one`() { val rootManager = ModuleRootManager.getInstance(module) val dir = createTempDir("contentEntry") createModuleWithContentRoot(dir) val manager:SourceFolderManagerImpl = SourceFolderManager.getInstance(project) as SourceFolderManagerImpl val folderFile = File(dir, "newFolder") val folderUrl = VfsUtilCore.pathToUrl(folderFile.absolutePath) manager.addSourceFolder(module, folderUrl, JavaSourceRootType.SOURCE) val file = File(folderFile, "file.txt") FileUtil.writeToFile(file, "SomeContent") LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file) manager.consumeBulkOperationsState { PlatformTestUtil.waitForFuture(it, 1000)} then(rootManager .contentEntries .flatMap { it.sourceFolders.asList() } .map { it.url }) .containsExactly(folderUrl) } fun `test update source folders execute within single storage diff`() { val manager = SourceFolderManager.getInstance(project) as SourceFolderManagerImpl val firstModuleFolder = createTempDir("foo") val firstModule = createModuleWithContentRoot(firstModuleFolder, "foo") val secondModuleFolder = createTempDir("bar") val secondModule = createModuleWithContentRoot(secondModuleFolder, "bar") var folderFile = File(firstModuleFolder, "newFolder") FileUtil.createDirectory(folderFile) val firstFolderUrl = VfsUtilCore.pathToUrl(folderFile.absolutePath) manager.addSourceFolder(firstModule, firstFolderUrl, JavaSourceRootType.SOURCE) folderFile = File(secondModuleFolder, "newFolder") FileUtil.createDirectory(folderFile) val secondFolderUrl = VfsUtilCore.pathToUrl(folderFile.absolutePath) manager.addSourceFolder(secondModule, secondFolderUrl, JavaSourceRootType.SOURCE) var notificationsCount = 0 val version = WorkspaceModel.getInstance(project).entityStorage.version WorkspaceModelTopics.getInstance(project).subscribeImmediately(project.messageBus.connect(), object : WorkspaceModelChangeListener { override fun changed(event: VersionedStorageChange) { notificationsCount++ } }) LocalFileSystem.getInstance().refresh(false) manager.consumeBulkOperationsState { PlatformTestUtil.waitForFuture(it, 1000)} TestCase.assertTrue(notificationsCount == 1) TestCase.assertTrue(version + 1 == WorkspaceModel.getInstance(project).entityStorage.version) } private fun createModuleWithContentRoot(dir: File, moduleName: String = "topModule"): Module { val moduleManager = ModuleManager.getInstance(project) val modifiableModel = moduleManager.getModifiableModel() val newModule: Module = try { modifiableModel.newModule(dir.toPath().resolve(moduleName).toAbsolutePath(), ModuleTypeId.JAVA_MODULE) } finally { runWriteAction { modifiableModel.commit() } } val modifiableRootModel = ModuleRootManager.getInstance(newModule).modifiableModel try { modifiableRootModel.addContentEntry(VfsUtilCore.pathToUrl(dir.absolutePath)) } finally { runWriteAction { modifiableRootModel.commit() } } return newModule } }
apache-2.0
56abdd32087b5a2e83f463d3c8d90d7b
41.21875
136
0.774385
5.225338
false
true
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/internal/ui/AnimationPanelTestAction.kt
1
24761
// 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.internal.ui import com.intellij.icons.AllIcons import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CustomShortcutSet import com.intellij.openapi.application.ex.ClipboardUtil import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.SystemInfoRt import com.intellij.ui.* import com.intellij.ui.components.ActionLink import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.JBTextArea import com.intellij.ui.components.fields.ExpandableTextField import com.intellij.ui.components.fields.ExtendableTextComponent import com.intellij.ui.components.panels.HorizontalLayout import com.intellij.ui.components.panels.OpaquePanel import com.intellij.ui.components.panels.VerticalLayout import com.intellij.ui.components.panels.Wrapper import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.builder.Cell import com.intellij.ui.hover.HoverStateListener import com.intellij.util.animation.* import com.intellij.util.animation.components.BezierPainter import com.intellij.util.ui.EmptyIcon import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import java.awt.* import java.awt.event.ActionEvent import java.awt.event.ActionListener import java.awt.event.WindowAdapter import java.awt.event.WindowEvent import java.awt.geom.Point2D import java.awt.geom.Rectangle2D import java.lang.Math.PI import java.text.NumberFormat import java.util.function.Consumer import javax.swing.* import javax.swing.border.CompoundBorder import kotlin.math.absoluteValue import kotlin.math.pow internal class AnimationPanelTestAction : DumbAwareAction("Show Animation Panel") { private class DemoPanel(val disposable: Disposable, val bezier: () -> Easing) : BorderLayoutPanel() { val textArea: JBTextArea init { preferredSize = Dimension(600, 300) border = JBUI.Borders.emptyLeft(12) textArea = JBTextArea() createScrollPaneWithAnimatedActions(textArea) } fun load() { loadStage1() } private fun loadStage1() { val baseColor = UIUtil.getTextFieldForeground() val showDemoBtn = JButton("Click to start a demo", AllIcons.Process.Step_1).also { it.border = JBUI.Borders.customLine(baseColor, 1) it.isContentAreaFilled = false it.isOpaque = true } val showTestPageLnk = ActionLink("or load the testing page") addToCenter(OpaquePanel(VerticalLayout(15, SwingConstants.CENTER)).also { it.add(showDemoBtn, VerticalLayout.CENTER) it.add(showTestPageLnk, VerticalLayout.CENTER) val buttonsPanel = JPanel(FlowLayout()).apply { add(JButton("Guess the value").apply { addActionListener { [email protected]() loadStage4() [email protected]() } }) } it.add(buttonsPanel, VerticalLayout.BOTTOM) }) val icons = arrayOf(AllIcons.Process.Step_1, AllIcons.Process.Step_2, AllIcons.Process.Step_3, AllIcons.Process.Step_4, AllIcons.Process.Step_5, AllIcons.Process.Step_6, AllIcons.Process.Step_7, AllIcons.Process.Step_8) val iconAnimator = JBAnimator(disposable).apply { period = 60 isCyclic = true type = JBAnimator.Type.EACH_FRAME ignorePowerSaveMode() } iconAnimator.animate(animation(icons, showDemoBtn::setIcon).apply { duration = iconAnimator.period * icons.size easing = Easing.LINEAR }) val fadeOutElements = listOf( transparent(baseColor) { showDemoBtn.foreground = it showDemoBtn.border = JBUI.Borders.customLine(it, 1) }, animation { val array = showDemoBtn.text.toCharArray() array.shuffle() showDemoBtn.text = String(array) }, transparent(showTestPageLnk.foreground, showTestPageLnk::setForeground).apply { runWhenScheduled { showDemoBtn.icon = EmptyIcon.ICON_16 showDemoBtn.isOpaque = false showDemoBtn.repaint() Disposer.dispose(iconAnimator) } runWhenExpired { removeAll() revalidate() repaint() } } ) showDemoBtn.addActionListener { JBAnimator().animate( fadeOutElements + animation().runWhenExpired { loadStage2() } ) } showTestPageLnk.addActionListener { JBAnimator().animate( fadeOutElements + animation().runWhenExpired { loadTestPage() } ) } UpdateColorsOnHover(showDemoBtn) } private fun loadStage2() { val clicks = 2 val buttonDemo = SpringButtonPanel("Here!", Rectangle(width / 2 - 50, 10, 100, 40), clicks) { [email protected](it) loadStage3() } addToCenter(buttonDemo) val scroller = ComponentUtil.getScrollPane(textArea) ?: error("text area has no scroll pane") if (scroller.parent == null) { textArea.text = """ Hello! Click the button ${clicks + 1} times. """.trimIndent() scroller.preferredSize = Dimension([email protected], 0) addToTop(scroller) } JBAnimator().animate(let { val to = Dimension([email protected], 100) animation(scroller.preferredSize, to, scroller::setPreferredSize) .setEasing(bezier()) .runWhenUpdated { revalidate() repaint() } }) } private fun loadStage3() { val scroller = ComponentUtil.getScrollPane(textArea) ?: error("text area has no scroll pane") if (scroller.parent == null) { textArea.text = "Good start!" scroller.preferredSize = Dimension([email protected], 0) addToTop(scroller) } val oopsText = "Oops... Everything is gone" val sorryText = """ $oopsText To check page scroll options insert a text and press UP or DOWN key. These values are funny: 0.34, 1.56, 0.64, 1 """.trimIndent() JBAnimator().apply { type = JBAnimator.Type.EACH_FRAME animate(makeSequent( animation(scroller.preferredSize, size, scroller::setPreferredSize).apply { duration = 500 delay = 500 easing = bezier() runWhenUpdated { revalidate() repaint() } }, animation(textArea.text, oopsText, textArea::setText).apply { duration = ((textArea.text.length + oopsText.length) * 20).coerceAtMost(5_000) delay = 200 }, animation(oopsText, sorryText, textArea::setText).apply { duration = ((oopsText.length + sorryText.length) * 20).coerceAtMost(7_500) delay = 1000 }, animation(size, Dimension(width, height - 30), scroller::setPreferredSize).apply { delay = 2_500 easing = bezier() runWhenUpdated { revalidate() repaint() } runWhenExpired { val link = ActionLink("Got it! Now, open the test panel") { loadTestPage() } val foreground = link.foreground val transparent = ColorUtil.withAlpha(link.foreground, 0.0) link.foreground = transparent addToBottom(Wrapper(FlowLayout(), link)) animate(transparent(foreground, link::setForeground).apply { easing = easing.reverse() }) } } )) } } private fun loadStage4() { val fields = listOf( JBLabel().apply { font = font.deriveFont(24f) }, JBLabel(UIUtil.ComponentStyle.LARGE), JBLabel(UIUtil.ComponentStyle.REGULAR), JBLabel(UIUtil.ComponentStyle.SMALL), JBLabel(UIUtil.ComponentStyle.MINI), JBLabel(UIUtil.ComponentStyle.MINI), JBLabel(UIUtil.ComponentStyle.MINI), ) val wheel = JPanel(GridLayout(fields.size, 1, 0, 10)) fields.onEach { it.horizontalAlignment = SwingConstants.CENTER wheel.add(it) } fun updateColor(color: RColors) { val colors = RColors.values() fields.forEachIndexed { index, label -> label.text = colors[(color.ordinal + index) % colors.size].toString() } } updateColor(RColors.RED) addToCenter(wheel) addToBottom(JButton("Start").apply { addActionListener(object : ActionListener { val animator = JBAnimator(JBAnimator.Thread.POOLED_THREAD, disposable) val context = AnimationContext<RColors>() var taskId = -1L override fun actionPerformed(e: ActionEvent?) { if (!animator.isRunning(taskId)) { text = "Stop" animator.apply { isCyclic = true type = JBAnimator.Type.EACH_FRAME taskId = animate( Animation.withContext(context, DoubleArrayFunction(RColors.values())).apply { val oneElementTimeOnScreen = 30 easing = Easing.LINEAR duration = RColors.values().size * oneElementTimeOnScreen runWhenUpdated { context.value?.let(::updateColor) } } ) } } else { text = "The ${context.value} wins! Try again!" animator.stop() } } }) }) } private fun loadTestPage() = hideAllComponentsAndRun { val linear = FillPanel("Linear") val custom = FillPanel("Custom") val content = Wrapper(HorizontalLayout(40)).apply { border = JBUI.Borders.empty(0, 40) add(custom, HorizontalLayout.CENTER) add(linear, HorizontalLayout.CENTER) } val animations = listOf( animation(custom::value::set), animation(linear::value::set), animation { content.repaint() } ) val fillers = JBAnimator(JBAnimator.Thread.POOLED_THREAD, disposable) var taskId = -1L addToCenter(AnimationSettings { options, button, info -> if (fillers.isRunning(taskId)) { fillers.stop() return@AnimationSettings } linear.background = options.color custom.background = options.color fillers.period = options.period fillers.isCyclic = options.cyclic fillers.type = options.type animations[0].easing = bezier() animations[1].easing = Easing.LINEAR animations.forEach { animation -> animation.duration = options.duration animation.delay = options.delay animation.easing = animation.easing.freeze( options.freezeBefore / 100.0, options.freezeAfter / 100.0 ) animation.easing = animation.easing.coerceIn( options.coerceMin / 100.0, options.coerceMax / 100.0 ) if (options.inverse) { animation.easing = animation.easing.invert() } if (options.reverse) { animation.easing = animation.easing.reverse() } if (options.mirror) { animation.easing = animation.easing.mirror() } } taskId = fillers.animate(animations + animation().apply { delay = animations.first().finish duration = 0 runWhenExpiredOrCancelled { button.icon = AllIcons.Actions.Execute button.text = "Start Animation" info.text = "updates: %d, duration: %d ms".format(fillers.statistic!!.count, fillers.statistic!!.duration) } }) button.icon = AllIcons.Actions.Suspend button.text = "Stop Animation" }.apply { addToRight(content) }) revalidate() } private fun hideAllComponentsAndRun(afterFinish: () -> Unit) { val remover = mutableListOf<Animation>() val scroller = ComponentUtil.getScrollPane(textArea) components.forEach { comp -> if (scroller === comp) { remover += animation(comp.preferredSize, Dimension(comp.width, 0), comp::setPreferredSize) .setEasing(bezier()) .runWhenUpdated { revalidate() repaint() } remover += animation(textArea.text, "", textArea::setText).setEasing { x -> 1 - (1 - x).pow(4.0) } remover += transparent(textArea.foreground, textArea::setForeground) } else if (comp is Wrapper && comp.targetComponent is ActionLink) { val link = comp.targetComponent as ActionLink remover += transparent(link.foreground, link::setForeground) } } remover += animation().runWhenExpired { removeAll() afterFinish() } remover.forEach { it.duration = 800 } JBAnimator().animate(remover) } private fun createScrollPaneWithAnimatedActions(textArea: JBTextArea): JBScrollPane { val pane = JBScrollPane(textArea) val commonAnimator = JBAnimator(disposable) create("Scroll Down") { val from: Int = pane.verticalScrollBar.value val to: Int = from + pane.visibleRect.height commonAnimator.animate( animation(from, to, pane.verticalScrollBar::setValue) .setDuration(350) .setEasing(bezier()) ) }.registerCustomShortcutSet(CustomShortcutSet.fromString("DOWN"), pane) create("Scroll Up") { val from: Int = pane.verticalScrollBar.value val to: Int = from - pane.visibleRect.height commonAnimator.animate( animation(from, to, pane.verticalScrollBar::setValue) .setDuration(350) .setEasing(bezier()) ) }.registerCustomShortcutSet(CustomShortcutSet.fromString("UP"), pane) return pane } } class Options { var period: Int = 5 var duration: Int = 1000 var delay: Int = 0 var cyclic: Boolean = false var reverse: Boolean = false var inverse: Boolean = false var mirror: Boolean = false var freezeBefore: Int = 0 var freezeAfter: Int = 100 var coerceMin: Int = 0 var coerceMax: Int = 100 var type: JBAnimator.Type = JBAnimator.Type.IN_TIME var color: Color = JBColor(0x9776A9, 0xD0A708) } private class AnimationSettings(val onStart: (Options, customize: JButton, info: JLabel) -> Unit) : BorderLayoutPanel() { private val options = Options() init { val panel = panel { row("Duration:") { spinner(0..60000, 50).bindIntValue(options::duration) } row("Period:") { spinner(1..1000, 1).bindIntValue(options::period) } row("Delay:") { spinner(0..10000, 100).bindIntValue(options::delay) } row { checkBox("Cyclic").bindSelected(options::cyclic) } row { checkBox("Reverse").bindSelected(options::reverse) } row { checkBox("Inverse").bindSelected(options::inverse) } row { checkBox("Mirror").bindSelected(options::mirror) } row("Freeze (%)") { spinner(0..100, 5).bindIntValue(options::freezeBefore) spinner(0..100, 5).bindIntValue(options::freezeAfter) } row("Coerce (%)") { spinner(0..100, 5).bindIntValue(options::coerceMin) spinner(0..100, 5).bindIntValue(options::coerceMax) } row { comboBox(JBAnimator.Type.values().toList(), SimpleListCellRenderer.create { label, value, _ -> label.text = value.toString().split("_").joinToString(" ") { it.toLowerCase().capitalize() } }).bindItem(options::type.toNullableProperty()) } row { link("Change color") { ColorPicker.showColorPickerPopup(null, options.color) { color, _ -> color?.let { options.color = it }} } } row { checkBox("Enable high precision timer").bindSelected( JBAnimatorHelper::isAvailable, JBAnimatorHelper::setAvailable ) }.visible(SystemInfoRt.isWindows) row { cell() } } addToCenter(panel) addToBottom(panel { row { lateinit var info: Cell<JLabel> cell(JButton("Start Animation", AllIcons.Actions.Execute).apply { addActionListener { panel.apply() onStart(options, this@apply, info.component) } }) info = label("") } }) } } private class FillPanel(val description: String) : JComponent() { var value: Double = 1.0 init { preferredSize = Dimension(40, 0) border = JBUI.Borders.empty(40, 5, 40, 0) } override fun paintComponent(g: Graphics) { val g2d = g as Graphics2D val insets = insets val bounds = g2d.clipBounds.apply { height -= insets.top + insets.bottom y += insets.top } val fillHeight = bounds.height * value val fillY = bounds.y + bounds.height - fillHeight.coerceAtLeast(0.0) val rectangle = Rectangle2D.Double(bounds.x.toDouble(), fillY, bounds.width.toDouble(), fillHeight.absoluteValue) g2d.color = background g2d.fill(rectangle) g2d.color = UIUtil.getPanelBackground() g2d.stroke = BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0f, floatArrayOf(3f), 0f) g2d.drawLine(bounds.x, bounds.y, bounds.x + bounds.width, bounds.y) g2d.drawLine(bounds.x, bounds.y + bounds.height / 4, bounds.x + bounds.width, bounds.y + bounds.height / 4) g2d.drawLine(bounds.x, bounds.y + bounds.height / 2, bounds.x + bounds.width, bounds.y + bounds.height / 2) g2d.drawLine(bounds.x, bounds.y + bounds.height * 3 / 4, bounds.x + bounds.width, bounds.y + bounds.height * 3 / 4) g2d.drawLine(bounds.x, bounds.y + bounds.height, bounds.x + bounds.width, bounds.y + bounds.height) val textX = bounds.width val textY = bounds.y + bounds.height g2d.color = UIUtil.getPanelBackground() g2d.font = g2d.font.deriveFont(30f).deriveFont(Font.BOLD) g2d.rotate(-PI / 2, textX.toDouble(), textY.toDouble()) g2d.drawString(description, textX, textY) } } private class BezierEasingPanel : BorderLayoutPanel() { private val painter = BezierPainter(0.215, 0.61, 0.355, 1.0).also(this::addToCenter).apply { border = JBUI.Borders.empty(25) } private val display = ExpandableTextField().also(this::addToTop).apply { isEditable = false text = getControlPoints(painter).joinToString(transform = format::format) border = JBUI.Borders.empty(1) } init { border = JBUI.Borders.customLine(UIUtil.getBoundsColor(), 1) painter.addPropertyChangeListener { e -> if (e.propertyName.endsWith("ControlPoint")) { display.text = getControlPoints(painter).joinToString(transform = format::format) } } display.setExtensions( ExtendableTextComponent.Extension.create(AllIcons.General.Reset, "Reset") { setControlPoints(painter, listOf(0.215, 0.61, 0.355, 1.0)) }, ExtendableTextComponent.Extension.create(AllIcons.Actions.MenuPaste, "Paste from Clipboard") { try { ClipboardUtil.getTextInClipboard()?.let { setControlPoints(painter, parseControlPoints(it)) } } catch (ignore: NumberFormatException) { JBAnimator().animate( animation(UIUtil.getErrorForeground(), UIUtil.getTextFieldForeground(), display::setForeground).apply { duration = 800 easing = Easing { x -> x * x * x } } ) } }) } fun getEasing() = painter.getEasing() private fun getControlPoints(bezierPainter: BezierPainter): List<Double> = listOf( bezierPainter.firstControlPoint.x, bezierPainter.firstControlPoint.y, bezierPainter.secondControlPoint.x, bezierPainter.secondControlPoint.y, ) private fun setControlPoints(bezierPainter: BezierPainter, values: List<Double>) { bezierPainter.firstControlPoint = Point2D.Double(values[0], values[1]) bezierPainter.secondControlPoint = Point2D.Double(values[2], values[3]) } @Throws(java.lang.NumberFormatException::class) private fun parseControlPoints(value: String): List<Double> = value.split(",").also { if (it.size != 4) throw NumberFormatException("Cannot parse $value;") }.map { it.trim().toDouble() } companion object { private val format = NumberFormat.getNumberInstance() } } private class SpringButtonPanel(text: String, start: Rectangle, val until: Int, val onFinish: Consumer<SpringButtonPanel>) : Wrapper() { val button = JButton(text) val animator = JBAnimator().apply { period = 5 type = JBAnimator.Type.IN_TIME } val easing = Easing { x -> 1 + 2.7 * (x - 1).pow(3.0) + 1.7 * (x - 1).pow(2.0) } var turns = 0 init { button.bounds = start button.addActionListener { if (turns >= until) { flyAway() } else { jump() turns++ } } layout = null add(button) } private fun flyAway() { animator.animate( animation(button.bounds, Rectangle(width / 2, 0, 0, 0), button::setBounds).apply { duration = 350 easing = [email protected] runWhenExpired { onFinish.accept(this@SpringButtonPanel) } } ) } private fun jump() { animator.animate( animation(button.bounds, generateBounds(), button::setBounds).apply { duration = 350 easing = [email protected] } ) } private fun generateBounds(): Rectangle { val size = bounds val x = (Math.random() * size.width / 2).toInt() val y = (Math.random() * size.height / 2).toInt() val width = (Math.random() * (size.width - x)).coerceAtLeast(100.0).toInt() val height = (Math.random() * (size.height - y)).coerceAtLeast(24.0).toInt() return Rectangle(x, y, width, height) } } override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun actionPerformed(e: AnActionEvent) { object : DialogWrapper(e.project) { val bezier = BezierEasingPanel() val demo = DemoPanel(disposable, bezier::getEasing) init { title = "Animation Panel Test Action" bezier.border = CompoundBorder(JBUI.Borders.emptyRight(12), bezier.border) setResizable(true) init() window.addWindowListener(object : WindowAdapter() { override fun windowOpened(e: WindowEvent?) { demo.load() window.removeWindowListener(this) } }) } override fun createCenterPanel() = OnePixelSplitter(false, .3f).also { ops -> ops.firstComponent = bezier ops.secondComponent = demo } override fun createActions() = emptyArray<Action>() }.show() } private class UpdateColorsOnHover(private val component: JComponent) : HoverStateListener() { private val backgroundFunction = DoubleColorFunction(component.background, component.foreground) private val foregroundFunction = DoubleColorFunction(component.foreground, component.background) private val helper = ShowHideAnimator(CubicBezierEasing(0.215, 0.61, 0.355, 1.0)) { component.background = backgroundFunction.apply(it) component.foreground = foregroundFunction.apply(it) } init { addTo(component) } override fun hoverChanged(component: Component, hovered: Boolean) = helper.setVisible(hovered) {} } private enum class RColors { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET, } }
apache-2.0
b22253160a5cef745d852475bcab9a76
32.598372
138
0.612051
4.565081
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/titleLabel/CustomDecorationPath.kt
1
4214
// 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.wm.impl.customFrameDecorations.header.titleLabel import com.intellij.ide.RecentProjectsManager import com.intellij.ide.RecentProjectsManagerBase import com.intellij.ide.lightEdit.LightEdit import com.intellij.ide.ui.UISettings import com.intellij.ide.ui.UISettingsListener import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.wm.impl.customFrameDecorations.header.title.CustomHeaderTitle import com.intellij.ui.awt.RelativeRectangle import com.intellij.util.ui.JBUI.CurrentTheme.CustomFrameDecorations import java.awt.Rectangle import java.beans.PropertyChangeListener import javax.swing.JComponent import javax.swing.JFrame internal open class CustomDecorationPath(private val frame: JFrame) : SelectedEditorFilePath(frame), CustomHeaderTitle { companion object { fun createInstance(frame: JFrame): CustomDecorationPath = CustomDecorationPath(frame) } private val projectManagerListener = object : ProjectManagerListener { override fun projectOpened(project: Project) { checkOpenedProjects() } override fun projectClosed(project: Project) { checkOpenedProjects() } } private fun checkOpenedProjects() { val currentProject = project ?: return val manager = RecentProjectsManager.getInstance() as RecentProjectsManagerBase val currentPath = manager.getProjectPath(currentProject) ?: return val currentName = manager.getProjectName(currentPath) val sameNameInRecent = manager.getRecentPaths().any { currentPath != it && currentName == manager.getProjectName(it) } val sameNameInOpen = ProjectManager.getInstance().openProjects.any { val path = manager.getProjectPath(it) ?: return@any false val name = manager.getProjectName(path) currentPath != path && currentName == name } multipleSameNamed = sameNameInRecent || sameNameInOpen } private val titleChangeListener = PropertyChangeListener { updateProjectPath() } override fun getCustomTitle(): String? { if (LightEdit.owns(project)) { return frame.title } return null } override fun setActive(value: Boolean) { val color = if (value) CustomFrameDecorations.titlePaneInfoForeground() else CustomFrameDecorations.titlePaneInactiveInfoForeground() view.foreground = color } override fun getBoundList(): List<RelativeRectangle> { return if (!toolTipNeeded) { emptyList() } else { val hitTestSpots = ArrayList<RelativeRectangle>() hitTestSpots.addAll(getMouseInsetList(label)) hitTestSpots } } override fun installListeners() { super.installListeners() frame.addPropertyChangeListener("title", titleChangeListener) } override fun addAdditionalListeners(disp: Disposable) { super.addAdditionalListeners(disp) project?.let { val busConnection = ApplicationManager.getApplication().messageBus.connect(disp) busConnection.subscribe(ProjectManager.TOPIC, projectManagerListener) busConnection.subscribe(UISettingsListener.TOPIC, UISettingsListener { checkTabPlacement() }) checkTabPlacement() checkOpenedProjects() } } private fun checkTabPlacement() { classPathNeeded = UISettings.getInstance().editorTabPlacement == 0 } override fun unInstallListeners() { super.unInstallListeners() frame.removePropertyChangeListener(titleChangeListener) } private fun getMouseInsetList(view: JComponent, mouseInsets: Int = 1): List<RelativeRectangle> { return listOf( RelativeRectangle(view, Rectangle(0, 0, mouseInsets, view.height)), RelativeRectangle(view, Rectangle(0, 0, view.width, mouseInsets)), RelativeRectangle(view, Rectangle(0, view.height - mouseInsets, view.width, mouseInsets)), RelativeRectangle(view, Rectangle(view.width - mouseInsets, 0, mouseInsets, view.height)) ) } }
apache-2.0
2e3e4365a7e418aeec8790ec2e19dae7
35.327586
137
0.761509
5.089372
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToIndexedFunctionCallIntention.kt
1
5592
// 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.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.codeStyle.CodeStyleManager import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggestionProvider import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNewDeclarationNameValidator import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.getOrCreateParameterList import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class ConvertToIndexedFunctionCallIntention : SelfTargetingRangeIntention<KtCallExpression>( KtCallExpression::class.java, KotlinBundle.lazyMessage("convert.to.indexed.function.call") ) { override fun applicabilityRange(element: KtCallExpression): TextRange? { val callee = element.calleeExpression ?: return null val (functionFqName, newFunctionName) = functions[callee.text] ?: return null if (element.singleLambdaArgumentExpression() == null) return null val context = element.analyze(BodyResolveMode.PARTIAL) if (functionFqName != element.getResolvedCall(context)?.resultingDescriptor?.fqNameOrNull()) return null setTextGetter(KotlinBundle.lazyMessage("convert.to.0", "'$newFunctionName'")) return callee.textRange } override fun applyTo(element: KtCallExpression, editor: Editor?) { val functionName = element.calleeExpression?.text ?: return val (_, newFunctionName) = functions[functionName] ?: return val functionLiteral = element.singleLambdaArgumentExpression()?.functionLiteral ?: return val psiFactory = KtPsiFactory(element.project) val context = element.analyze(BodyResolveMode.PARTIAL) functionLiteral .collectDescendantsOfType<KtReturnExpression> { it.getLabelName() == functionName && it.getTargetFunction(context) == functionLiteral } .forEach { val value = it.returnedExpression val newLabeledReturn = if (value != null) { psiFactory.createExpressionByPattern("return@$newFunctionName $0", value) } else { psiFactory.createExpression("return@$newFunctionName") } it.replace(newLabeledReturn) } val parameterList = functionLiteral.getOrCreateParameterList() val parameters = parameterList.parameters val nameValidator = CollectingNameValidator( filter = Fe10KotlinNewDeclarationNameValidator(functionLiteral, null, KotlinNameSuggestionProvider.ValidatorTarget.PARAMETER) ) val indexParameterName = Fe10KotlinNameSuggester.suggestNameByName("index", nameValidator) val indexParameter = psiFactory.createParameter(indexParameterName) if (parameters.isEmpty()) { parameterList.addParameter(indexParameter) parameterList.addParameter(psiFactory.createParameter("it")) } else { parameterList.addParameterBefore(indexParameter, parameters.first()) } val callOrQualified = element.getQualifiedExpressionForSelector() ?: element val result = callOrQualified.replace( psiFactory.buildExpression { appendCallOrQualifiedExpression(element, newFunctionName) } ) CodeStyleManager.getInstance(element.project).reformat(result) } companion object { private const val indexed = "Indexed" private val functions = listOf( Pair("filter", "filter$indexed"), Pair("filterTo", "filter${indexed}To"), Pair("fold", "fold$indexed"), Pair("foldRight", "foldRight$indexed"), Pair("forEach", "forEach$indexed"), Pair("map", "map$indexed"), Pair("mapNotNull", "map${indexed}NotNull"), Pair("mapNotNullTo", "map${indexed}NotNullTo"), Pair("mapTo", "map${indexed}To"), Pair("onEach", "onEach$indexed"), Pair("reduce", "reduce$indexed"), Pair("reduceOrNull", "reduce${indexed}OrNull"), Pair("reduceRight", "reduceRight$indexed"), Pair("reduceRightOrNull", "reduceRight${indexed}OrNull"), Pair("runningFold", "runningFold$indexed"), Pair("runningReduce", "runningReduce$indexed"), Pair("scan", "scan$indexed"), Pair("scanReduce", "scanReduce$indexed"), ).associate { (functionName, indexedFunctionName) -> functionName to (FqName("kotlin.collections.$functionName") to indexedFunctionName) } } }
apache-2.0
d6357dc01dcd6ec253b7b338a746e7c7
51.261682
158
0.705293
5.42386
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/Point3D.kt
1
1638
package com.nibado.projects.advent import java.lang.Integer.max import java.lang.Integer.min data class Point3D(val x: Int, val y: Int, val z: Int) { constructor() : this(0, 0, 0) fun neighbors() = neighbors(this) operator fun plus(other: Point3D) = Point3D(x + other.x, y + other.y, z + other.z) operator fun minus(other: Point3D) = Point3D(x - other.x, y - other.y, z - other.z) companion object { private val MAX = Point3D(Int.MAX_VALUE, Int.MAX_VALUE, Int.MAX_VALUE) private val MIN = Point3D(Int.MIN_VALUE, Int.MIN_VALUE, Int.MIN_VALUE) private val ORIGIN = Point3D() fun neighbors(p: Point3D): List<Point3D> = (-1..1).flatMap { x -> (-1..1).flatMap { y -> (-1..1) .map { z -> Point3D(x + p.x, y + p.y, z + p.z) } } } .filterNot { (x, y, z) -> x == p.x && y == p.y && z == p.z } fun bounds(points: Collection<Point3D>) = points .fold(MAX to MIN) { (min, max), p -> Point3D(min(min.x, p.x), min(min.y, p.y), min(min.z, p.z)) to Point3D(max(max.x, p.x), max(min.y, p.y), max(max.z, p.z)) } fun points(min: Point3D, max: Point3D): List<Point3D> = (min.x..max.x).flatMap { x -> (min.y..max.y).flatMap { y -> (min.z..max.z).map { z -> Point3D(x, y, z) } } } } } fun Pair<Point3D, Point3D>.points() = let { (min, max) -> Point3D.points(min, max) } fun Collection<Point3D>.bounds() = Point3D.bounds(this)
mit
06af669cb97492e610fd94c908e48dad
37.093023
93
0.504274
2.967391
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/track/timesignature/TimeSignature.kt
2
664
package io.github.chrislo27.rhre3.track.timesignature class TimeSignature(val container: TimeSignatures, val beat: Float, beatsPerMeasure: Int, beatUnit: Int) { companion object { val LOWER_BEATS_PER_MEASURE = 1 val UPPER_BEATS_PER_MEASURE = 64 val NOTE_UNITS = listOf(2, 4, 8, 16).sorted() val DEFAULT_NOTE_UNIT = 4 } val beatsPerMeasure: Int = beatsPerMeasure.coerceAtLeast(1) val beatUnit: Int = beatUnit.coerceAtLeast(1) val noteFraction: Float get() = 4f / beatUnit var measure: Int = 0 val lowerText: String = this.beatUnit.toString() val upperText: String = "${this.beatsPerMeasure}" }
gpl-3.0
78f5c99e1bcdc393942e79172c7b088a
29.181818
106
0.680723
3.648352
false
false
false
false
allotria/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/left/PackagesSmartList.kt
1
16647
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.left import com.intellij.ide.CopyProvider import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.DataProvider import com.intellij.ui.AnimatedIcon import com.intellij.ui.HyperlinkLabel import com.intellij.ui.ListSpeedSearch import com.intellij.ui.PopupHandler import com.intellij.ui.SpeedSearchComparator import com.intellij.ui.components.JBList import com.intellij.util.text.VersionComparatorUtil import com.intellij.util.ui.UIUtil import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.looksLikeGradleVariable import com.jetbrains.packagesearch.intellij.plugin.ui.RiderUI import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.confirmations.PackageOperationsConfirmationDialog import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ExecutablePackageOperation import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageSearchDependency import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageSearchToolWindowModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.asList import java.awt.Component import java.awt.Cursor import java.awt.Point import java.awt.event.FocusAdapter import java.awt.event.FocusEvent import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.util.ArrayList import javax.swing.DefaultListModel import javax.swing.DefaultListSelectionModel import javax.swing.ListSelectionModel class PackagesSmartList(val viewModel: PackageSearchToolWindowModel) : JBList<PackagesSmartItem>(emptyList()), DataProvider, CopyProvider { var transferFocusUp: () -> Unit = { transferFocusBackward() } private val updateContentLock = Object() private val listModel: DefaultListModel<PackagesSmartItem> get() = model as DefaultListModel<PackagesSmartItem> private val headerLinkHandler = createLinkActivationListener(this) private val upgradeAllLink = HyperlinkLabel(PackageSearchBundle.message("packagesearch.ui.toolwindow.actions.upgradeAll.text")).apply { isVisible = false addHyperlinkListener { if (viewModel.upgradeCountInContext.value > 0) { val selectedProjectModule = viewModel.selectedProjectModule.value val selectedRemoteRepository = viewModel.selectedRemoteRepository.value val selectedRemoteRepositoryIds = selectedRemoteRepository.asList() val projectModules = if (selectedProjectModule != null) { listOf(selectedProjectModule) } else { viewModel.projectModules.value } val selectedOnlyStable = viewModel.selectedOnlyStable.value val upgradeRequests = viewModel.preparePackageOperationTargetsFor(projectModules, selectedRemoteRepository) .filter { it.version.isNotBlank() && !looksLikeGradleVariable(it.version) && VersionComparatorUtil.compare(it.version, it.packageSearchDependency.getLatestAvailableVersion( selectedOnlyStable, selectedRemoteRepositoryIds)) < 0 } .sortedBy { it.projectModule.getFullName() } val message = PackageSearchBundle.message("packagesearch.ui.toolwindow.actions.upgradeAll.text") val upgradeRequestsToExecute = PackageOperationsConfirmationDialog.show( viewModel.project, message + (selectedProjectModule?.name?.let { " ${PackageSearchBundle.message("packagesearch.ui.toolwindow.actions.upgradeAll.button.titleSuffix", it)}" } ?: ""), PackageSearchBundle.message("packagesearch.ui.toolwindow.actions.upgradeAll.button.text"), selectedOnlyStable, selectedRemoteRepositoryIds, upgradeRequests) if (upgradeRequestsToExecute.any()) { viewModel.executeOperations(upgradeRequestsToExecute.map { target -> val targetVersion = target.packageSearchDependency.getLatestAvailableVersion( selectedOnlyStable, selectedRemoteRepositoryIds) ?: "" val operation = target.getApplyOperation(targetVersion)!! ExecutablePackageOperation(operation, target, targetVersion) }) } } } } val installedHeader = PackagesSmartItem.Header(PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.installedPackages")) .apply { addHeaderLink(upgradeAllLink) } val availableHeader = PackagesSmartItem.Header(PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.searchResults")) private val packageItems: List<PackagesSmartItem.Package> get() = listModel.elements().toList().filterIsInstance<PackagesSmartItem.Package>() val hasPackageItems: Boolean get() = packageItems.any() val firstPackageIndex: Int get() = listModel.elements().toList().indexOfFirst { it is PackagesSmartItem.Package } private val packageSelectionListeners = ArrayList<(PackageSearchDependency) -> Unit>() init { @Suppress("UnstableApiUsage") // yolo putClientProperty(AnimatedIcon.ANIMATION_IN_RENDERER_ALLOWED, true) cellRenderer = PackagesSmartRenderer(viewModel) selectionModel = BriefItemsSelectionModel() listModel.addElement(installedHeader) listModel.addElement(availableHeader) RiderUI.overrideKeyStroke(this, "jlist:RIGHT", "RIGHT") { transferFocus() } RiderUI.overrideKeyStroke(this, "jlist:ENTER", "ENTER") { transferFocus() } RiderUI.overrideKeyStroke(this, "shift ENTER") { this.transferFocusUp() } RiderUI.addKeyboardPopupHandler(this, "alt ENTER") { items -> val item = items.first() if (item is PackagesSmartItem.Package) PackagesSmartItemPopup(viewModel, item.meta) else null } addListSelectionListener { val item = selectedValue if (selectedIndex >= 0 && item is PackagesSmartItem.Package) { ensureIndexIsVisible(selectedIndex) for (listener in packageSelectionListeners) { listener(item.meta) } } } addFocusListener(object : FocusAdapter() { override fun focusGained(e: FocusEvent?) { if (hasPackageItems && selectedIndex == -1) { selectedIndex = firstPackageIndex } } }) installPopupHandler() addMouseListener(headerLinkHandler) addMouseMotionListener(headerLinkHandler) ListSpeedSearch(this) { if (it is PackagesSmartItem.Package) { it.meta.identifier } else { "" } }.apply { comparator = SpeedSearchComparator(false) } viewModel.searchTerm.advise(viewModel.lifetime) { upgradeAllLink.isVisible = viewModel.upgradeCountInContext.value > 0 && it.isEmpty() } viewModel.upgradeCountInContext.advise(viewModel.lifetime) { if (it > 0 && viewModel.searchTerm.value.isBlank()) { upgradeAllLink.setHyperlinkText(PackageSearchBundle.message("packagesearch.ui.toolwindow.actions.upgradeAll.text.withCount", it)) upgradeAllLink.isVisible = true } else { upgradeAllLink.isVisible = false } } } private fun installPopupHandler() { val list = this list.addMouseListener(object : PopupHandler() { override fun invokePopup(comp: Component?, x: Int, y: Int) { val index = list.locationToIndex(Point(x, y - 1)) if (index != -1) { val element = list.model.getElementAt(index) if (element != null && element is PackagesSmartItem.Package) { if (selectedValue == null || selectedValue as PackagesSmartItem != element) { setSelectedValue(element, true) } val popup = PackagesSmartItemPopup(viewModel, element.meta) popup.show(list, x, y) } } } }) } private fun calcDisplayItems(packages: List<PackageSearchDependency>): List<PackagesSmartItem> { val displayItems = mutableListOf<PackagesSmartItem>() val installedPackages = packages.filter { it.isInstalled } val message = PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.installedPackages.withCount", installedPackages.size) installedHeader.title = message + (viewModel.selectedProjectModule.value?.name ?.let { " ${PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.installedPackages.titleSuffix", it)}" } ?: "") val availablePackages = packages.filterNot { it.isInstalled } availableHeader.title = PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.searchResults.withCount", availablePackages.size) availableHeader.visible = availablePackages.any() || viewModel.searchTerm.value.isNotEmpty() displayItems.add(installedHeader) displayItems.addAll(installedPackages.map { PackagesSmartItem.Package(it) }) displayItems.add(availableHeader) displayItems.addAll(availablePackages.map { PackagesSmartItem.Package(it) }) return displayItems } fun updateAllPackages(packages: List<PackageSearchDependency>) { synchronized(updateContentLock) { val displayItems = calcDisplayItems(packages) // save selected package Id; we have to restore selection after the list rebuilding val selectedPackageIndex = selectedIndex val selectedPackageId = viewModel.selectedPackage.value.apply { if (isEmpty()) { (selectedValue as PackagesSmartItem.Package?)?.meta?.identifier } } var reselected = false for ((index, item) in displayItems.withIndex()) { if (index < listModel.size()) { listModel.set(index, item) } else { listModel.add(index, item) } if (item is PackagesSmartItem.Package && item.meta.identifier == selectedPackageId) { if (index != selectedPackageIndex) { selectedIndex = index } reselected = true } } if (listModel.size() > displayItems.size) { listModel.removeRange(displayItems.size, listModel.size() - 1) } if (!reselected) { // if there is no the old selected package in the new list clearSelection() // we have to clear the selection } } } fun addPackageSelectionListener(listener: (PackageSearchDependency) -> Unit) { packageSelectionListeners.add(listener) } // It is possible to select only package items; fakes and headers should be ignored private inner class BriefItemsSelectionModel : DefaultListSelectionModel() { init { this.selectionMode = ListSelectionModel.SINGLE_SELECTION // TODO: MULTIPLE_INTERVAL_SELECTION support } private fun isPackageItem(index: Int) = listModel.getElementAt(index) is PackagesSmartItem.Package override fun setSelectionInterval(index0: Int, index1: Int) { if (isPackageItem(index0)) { super.setSelectionInterval(index0, index0) return } if (anchorSelectionIndex < index0) { for (i in index0 until listModel.size()) { if (isPackageItem(i)) { super.setSelectionInterval(i, i) return } } } else { for (i in index0 downTo 0) { if (isPackageItem(i)) { super.setSelectionInterval(i, i) return } } super.clearSelection() transferFocusUp() } } } private fun getSelectedPackage(): PackagesSmartItem.Package? = if (this.selectedIndex != -1) { listModel.getElementAt(this.selectedIndex) as? PackagesSmartItem.Package } else { null } override fun getData(dataId: String) = getSelectedPackage()?.getData(dataId, viewModel.selectedProjectModule.value) override fun performCopy(dataContext: DataContext) { getSelectedPackage()?.performCopy(dataContext) } override fun isCopyEnabled(dataContext: DataContext) = getSelectedPackage()?.isCopyEnabled(dataContext) ?: false override fun isCopyVisible(dataContext: DataContext) = getSelectedPackage()?.isCopyVisible(dataContext) ?: false private fun createLinkActivationListener(list: JBList<PackagesSmartItem>) = object : MouseAdapter() { @Suppress("TooGenericExceptionCaught") // Guarding against random runtime failures private val hyperlinkHoverField = try { HyperlinkLabel::class.java.getDeclaredField("myMouseHover") } catch (e: Throwable) { null } private var lastHoveredHyperlinkLabel: HyperlinkLabel? = null private fun trySetHovering(target: HyperlinkLabel?, value: Boolean) { if (target == null) return try { hyperlinkHoverField?.isAccessible = true hyperlinkHoverField?.set(target, value) } catch (ignored: Exception) { // No-op } } override fun mouseMoved(e: MouseEvent) { val hyperlinkLabel = findHyperlinkLabelAt(e.point) if (hyperlinkLabel != null) { if (hyperlinkLabel != lastHoveredHyperlinkLabel) { trySetHovering(lastHoveredHyperlinkLabel, false) trySetHovering(hyperlinkLabel, true) lastHoveredHyperlinkLabel = hyperlinkLabel list.repaint() } UIUtil.setCursor(list, Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)) } else { if (lastHoveredHyperlinkLabel != null) { trySetHovering(lastHoveredHyperlinkLabel, false) lastHoveredHyperlinkLabel = null list.repaint() } UIUtil.setCursor(list, Cursor.getDefaultCursor()) } } override fun mouseClicked(e: MouseEvent) { val hyperlinkLabel = findHyperlinkLabelAt(e.point) if (hyperlinkLabel != null) { trySetHovering(lastHoveredHyperlinkLabel, false) trySetHovering(hyperlinkLabel, false) lastHoveredHyperlinkLabel = null list.repaint() hyperlinkLabel.doClick() } } private fun findHyperlinkLabelAt(point: Point): HyperlinkLabel? { val idx = list.locationToIndex(point) if (idx < 0) return null val cellBounds = list.getCellBounds(idx, idx) if (!cellBounds.contains(point)) return null val item = list.model.getElementAt(idx) as? PackagesSmartItem.Header ?: return null val rendererComponent = list.cellRenderer.getListCellRendererComponent(list, item, idx, true, true) rendererComponent.setBounds(cellBounds.x, cellBounds.y, cellBounds.width, cellBounds.height) UIUtil.layoutRecursively(rendererComponent) val rendererRelativeX = point.x - cellBounds.x val rendererRelativeY = point.y - cellBounds.y val childComponent = UIUtil.getDeepestComponentAt(rendererComponent, rendererRelativeX, rendererRelativeY) if (childComponent is HyperlinkLabel) return childComponent return null } } }
apache-2.0
d1271afb3dfc871056332100131aed93
42.351563
145
0.632667
5.750259
false
false
false
false
JetBrains/teamcity-dnx-plugin
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/agent/runner/WorkflowBuildServiceFactory.kt
1
1393
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"). * See LICENSE in the project root for license information. */ package jetbrains.buildServer.agent.runner import jetbrains.buildServer.RunBuildException import jetbrains.buildServer.agent.AgentBuildRunnerInfo import jetbrains.buildServer.agent.BuildAgentConfiguration import jetbrains.buildServer.agent.BuildRunnerContext import org.springframework.beans.factory.BeanFactory class WorkflowBuildServiceFactory( private val runnerType: String, private val beanFactory: BeanFactory) : MultiCommandBuildSessionFactory, BuildStepContext { private var _runnerContext: BuildRunnerContext? = null override fun createSession(runnerContext: BuildRunnerContext): MultiCommandBuildSession { _runnerContext = runnerContext return beanFactory.getBean(WorkflowSessionImpl::class.java) } override val isAvailable: Boolean get() = _runnerContext != null override val runnerContext: BuildRunnerContext get() = _runnerContext ?: throw RunBuildException("Runner session was not started") override fun getBuildRunnerInfo(): AgentBuildRunnerInfo = object : AgentBuildRunnerInfo { override fun getType(): String = runnerType override fun canRun(config: BuildAgentConfiguration): Boolean = true } }
apache-2.0
03c8ecfc8ae67dc0c90b301b298aa1c5
35.657895
93
0.765255
5.316794
false
true
false
false
genonbeta/TrebleShot
app/src/main/java/org/monora/uprotocol/client/android/fragment/TransferItemFragment.kt
1
8531
/* * Copyright (C) 2021 Veli Tasalı * * 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 2 * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.monora.uprotocol.client.android.fragment import android.content.Context import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.viewModels import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.genonbeta.android.framework.io.DocumentFile import com.genonbeta.android.framework.util.Files import com.google.android.material.bottomsheet.BottomSheetDialogFragment import dagger.assisted.Assisted import dagger.assisted.AssistedFactory import dagger.assisted.AssistedInject import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import org.monora.uprotocol.client.android.R import org.monora.uprotocol.client.android.data.TransferRepository import org.monora.uprotocol.client.android.database.model.Transfer import org.monora.uprotocol.client.android.database.model.UTransferItem import org.monora.uprotocol.client.android.databinding.LayoutTransferItemBinding import org.monora.uprotocol.client.android.databinding.ListTransferItemBinding import org.monora.uprotocol.client.android.protocol.isIncoming import org.monora.uprotocol.client.android.util.Activities import org.monora.uprotocol.client.android.viewmodel.EmptyContentViewModel import org.monora.uprotocol.core.protocol.Direction import org.monora.uprotocol.core.transfer.TransferItem import javax.inject.Inject @AndroidEntryPoint class TransferItemFragment : BottomSheetDialogFragment() { @Inject lateinit var factory: ItemViewModel.Factory private val args: TransferItemFragmentArgs by navArgs() private val viewModel: ItemViewModel by viewModels { ItemViewModel.ModelFactory(factory, args.transfer) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return inflater.inflate(R.layout.layout_transfer_item, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val adapter = ItemAdapter { item, clickType -> when (clickType) { ItemAdapter.ClickType.Default -> viewModel.open(requireContext(), item) ItemAdapter.ClickType.Recover -> viewModel.recover(item) } } val binding = LayoutTransferItemBinding.bind(view) val emptyContentViewModel = EmptyContentViewModel() binding.emptyView.viewModel = emptyContentViewModel binding.emptyView.emptyText.setText(R.string.empty_files_list) binding.emptyView.emptyImage.setImageResource(R.drawable.ic_insert_drive_file_white_24dp) binding.emptyView.executePendingBindings() adapter.setHasStableIds(true) binding.recyclerView.adapter = adapter viewModel.items.observe(viewLifecycleOwner) { adapter.submitList(it) emptyContentViewModel.with(binding.recyclerView, it.isNotEmpty()) } } } class ItemViewModel @AssistedInject internal constructor( private val transferRepository: TransferRepository, @Assisted private val transfer: Transfer, ) : ViewModel() { val items = transferRepository.getTransferItems(transfer.id) fun open(context: Context, item: UTransferItem) { val uri = try { Uri.parse(item.location) } catch (e: Exception) { return } if (item.direction == Direction.Outgoing || item.state == TransferItem.State.Done) { try { Activities.view(context, DocumentFile.fromUri(context, uri)) } catch (e: Exception) { Activities.view(context, uri, item.mimeType) } } } fun recover(item: UTransferItem) { if (item.state == TransferItem.State.InvalidatedTemporarily) { viewModelScope.launch { val originalState = item.state item.state = TransferItem.State.Pending transferRepository.update(item) // The list will not be refreshed if the DiffUtil finds the values are the same, so we give the // original value back (it will be refreshed anyway). item.state = originalState } } } @AssistedFactory interface Factory { fun create(transfer: Transfer): ItemViewModel } class ModelFactory( private val factory: Factory, private val transfer: Transfer, ) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>): T { check(modelClass.isAssignableFrom(ItemViewModel::class.java)) { "Unknown type of view model was requested" } return factory.create(transfer) as T } } } class ItemContentViewModel(val transferItem: UTransferItem, context: Context) { val name = transferItem.name val size = Files.formatLength(transferItem.size, false) val mimeType = transferItem.mimeType val shouldRecover = transferItem.direction.isIncoming && transferItem.state == TransferItem.State.InvalidatedTemporarily val state = context.getString( when (transferItem.state) { TransferItem.State.InvalidatedTemporarily -> R.string.interrupted TransferItem.State.Invalidated -> R.string.removed TransferItem.State.Done -> R.string.completed else -> R.string.pending } ) } class ItemViewHolder( private val clickListener: (item: UTransferItem, clickType: ItemAdapter.ClickType) -> Unit, private val binding: ListTransferItemBinding ) : RecyclerView.ViewHolder(binding.root) { fun bind(transferItem: UTransferItem) { binding.viewModel = ItemContentViewModel(transferItem, binding.root.context) binding.root.setOnClickListener { clickListener(transferItem, ItemAdapter.ClickType.Default) } binding.recoverButton.setOnClickListener { clickListener(transferItem, ItemAdapter.ClickType.Recover) } binding.executePendingBindings() } } class ItemCallback : DiffUtil.ItemCallback<UTransferItem>() { override fun areItemsTheSame(oldItem: UTransferItem, newItem: UTransferItem): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: UTransferItem, newItem: UTransferItem): Boolean { return oldItem.dateModified == newItem.dateModified && oldItem.state == newItem.state } } class ItemAdapter( private val clickListener: (item: UTransferItem, clickType: ClickType) -> Unit, ) : ListAdapter<UTransferItem, ItemViewHolder>(ItemCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder { return ItemViewHolder( clickListener, ListTransferItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) ) } override fun onBindViewHolder(holder: ItemViewHolder, position: Int) { holder.bind(getItem(position)) } override fun getItemViewType(position: Int): Int { return VIEW_TYPE_TRANSFER_ITEM } override fun getItemId(position: Int): Long { return getItem(position).let { it.id + it.groupId } } enum class ClickType { Default, Recover, } companion object { const val VIEW_TYPE_TRANSFER_ITEM = 0 } }
gpl-2.0
2d94b44d82d9a4732e72d21d006abbb5
36.248908
115
0.713365
4.916427
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/js/src/EventLoop.kt
1
1007
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines import kotlin.coroutines.* internal actual fun createEventLoop(): EventLoop = UnconfinedEventLoop() internal actual fun nanoTime(): Long = unsupported() internal class UnconfinedEventLoop : EventLoop() { override fun dispatch(context: CoroutineContext, block: Runnable): Unit = unsupported() } internal actual abstract class EventLoopImplPlatform : EventLoop() { protected actual fun unpark(): Unit = unsupported() protected actual fun reschedule(now: Long, delayedTask: EventLoopImplBase.DelayedTask): Unit = unsupported() } internal actual object DefaultExecutor { public actual fun enqueue(task: Runnable): Unit = unsupported() } private fun unsupported(): Nothing = throw UnsupportedOperationException("runBlocking event loop is not supported") internal actual inline fun platformAutoreleasePool(crossinline block: () -> Unit) = block()
apache-2.0
252953a4335ce07c53ac1ff5907bbead
33.724138
112
0.765641
4.772512
false
false
false
false
F43nd1r/acra-backend
acrarium/src/main/kotlin/com/faendir/acra/rest/RestApiInterface.kt
1
4844
/* * (C) Copyright 2018 Lukas Morawietz (https://github.com/F43nd1r) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.faendir.acra.rest import com.faendir.acra.model.App import com.faendir.acra.model.Bug import com.faendir.acra.model.Report import com.faendir.acra.model.Stacktrace import com.faendir.acra.model.Version import com.faendir.acra.service.DataService import org.springframework.format.annotation.DateTimeFormat import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.security.access.prepost.PreAuthorize import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import java.time.ZonedDateTime /** * @author lukas * @since 23.08.18 */ @RestController @RequestMapping(RestApiInterface.API_PATH) @PreAuthorize("hasRole(T(com.faendir.acra.model.User\$Role).API)") class RestApiInterface(private val dataService: DataService) { @RequestMapping(value = ["apps"], produces = [MediaType.APPLICATION_JSON_VALUE], method = [RequestMethod.GET]) fun listApps(): List<Int> = dataService.getAppIds() @RequestMapping(value = ["apps/{id}"], produces = [MediaType.APPLICATION_JSON_VALUE], method = [RequestMethod.GET]) fun getApp(@PathVariable id: Int): App? = dataService.findApp(id) @RequestMapping(value = ["apps/{id}/bugs"], produces = [MediaType.APPLICATION_JSON_VALUE], method = [RequestMethod.GET]) fun listBugs(@PathVariable id: Int): List<Int> = dataService.findApp(id)?.let { dataService.getBugIds(it) } ?: emptyList() @RequestMapping(value = ["bugs/{id}"], produces = [MediaType.APPLICATION_JSON_VALUE], method = [RequestMethod.GET]) fun getBug(@PathVariable id: Int): Bug? = dataService.findBug(id) @RequestMapping(value = ["bugs/{id}/stacktraces"], produces = [MediaType.APPLICATION_JSON_VALUE], method = [RequestMethod.GET]) fun listStacktraces(@PathVariable id: Int): List<Int> = dataService.findBug(id)?.let { dataService.getStacktraceIds(it) } ?: emptyList() @RequestMapping(value = ["stacktraces/{id}"], produces = [MediaType.APPLICATION_JSON_VALUE], method = [RequestMethod.GET]) fun getStacktrace(@PathVariable id: Int): Stacktrace? = dataService.findStacktrace(id) @RequestMapping(value = ["stacktraces/{id}/reports"], produces = [MediaType.APPLICATION_JSON_VALUE], method = [RequestMethod.GET]) fun listReports(@PathVariable id: Int): List<String> = dataService.findStacktrace(id)?.let { dataService.getReportIds(it) } ?: emptyList() @RequestMapping(value = ["apps/{id}/reports"], produces = [MediaType.APPLICATION_JSON_VALUE], method = [RequestMethod.GET]) fun listReportsOfApp( @PathVariable id: Int, @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) before: ZonedDateTime?, @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) after: ZonedDateTime? ): List<String> = dataService.findApp(id)?.let { dataService.getReportIds(it, before, after) } ?: emptyList() @RequestMapping(value = ["reports/{id}"], produces = [MediaType.APPLICATION_JSON_VALUE], method = [RequestMethod.GET]) fun getReport(@PathVariable id: String): Report? = dataService.findReport(id) @RequestMapping(value = ["apps/{id}/version/upload/{code}"], consumes = [MediaType.TEXT_PLAIN_VALUE], method = [RequestMethod.POST]) fun uploadProguardMapping( @PathVariable id: Int, @PathVariable code: Int, @RequestParam(required = false) name: String?, @RequestBody content: String ): ResponseEntity<*> { val app = dataService.findApp(id) ?: return ResponseEntity.notFound().build<Any>() dataService.storeVersion(dataService.findVersion(app, code)?.also { version -> name?.let { it -> version.name = it } version.mappings = content } ?: Version(app, code, name ?: "N/A", content)) return ResponseEntity.ok().build<Any>() } companion object { const val API_PATH = "api" } }
apache-2.0
f1cffeb87bd9a451c0dae9e037c498aa
50.542553
142
0.729562
4.112054
false
false
false
false
zdary/intellij-community
jvm/jvm-analysis-kotlin-tests/testData/codeInspection/unstableApiUsage/experimental/NoWarningsMembersOfTheSameFile.kt
13
1548
@file:Suppress("UNUSED_PARAMETER") package test; import pkg.AnnotatedClass; class NoWarningsMembersOfTheSameFile { companion object { private var staticField: <warning descr="'pkg.AnnotatedClass' is marked unstable with @ApiStatus.Experimental">AnnotatedClass</warning>? = null; private fun staticReturnType(): <warning descr="'pkg.AnnotatedClass' is marked unstable with @ApiStatus.Experimental">AnnotatedClass</warning>? { return null; } private fun staticParamType(param: <warning descr="'pkg.AnnotatedClass' is marked unstable with @ApiStatus.Experimental">AnnotatedClass</warning>?) { } } private var field: <warning descr="'pkg.AnnotatedClass' is marked unstable with @ApiStatus.Experimental">AnnotatedClass</warning>? = null; private fun returnType(): <warning descr="'pkg.AnnotatedClass' is marked unstable with @ApiStatus.Experimental">AnnotatedClass</warning>? { return null; } private fun paramType(param: <warning descr="'pkg.AnnotatedClass' is marked unstable with @ApiStatus.Experimental">AnnotatedClass</warning>?) { } fun testNoWarningsProducedForMembersOfTheSameClass() { field?.toString(); staticField?.toString(); returnType(); paramType(null); staticReturnType(); staticParamType(null) } private inner class InnerClass { fun testNoWarningsProducedForMembersEnclosingClass() { field.toString(); staticField.toString(); returnType(); paramType(null); staticReturnType(); staticParamType(null) } } }
apache-2.0
996d0b467ead8512ffe3de56e0f45e66
30.612245
153
0.72739
4.883281
false
true
false
false
zdary/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/PluginEnvironment.kt
1
818
package com.jetbrains.packagesearch.intellij.plugin import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.util.NlsSafe internal const val PACKAGE_SEARCH_NOTIFICATION_GROUP_ID = "PACKAGESEARCH.NOTIFICATION" internal class PluginEnvironment { val pluginVersion get() = PluginManagerCore.getPlugin(PluginId.getId(PLUGIN_ID))?.version ?: PackageSearchBundle.message("packagesearch.version.undefined") val ideVersion get() = ApplicationInfo.getInstance().strictVersion val ideBuildNumber get() = ApplicationInfo.getInstance().build companion object { const val PLUGIN_ID = "com.jetbrains.packagesearch.intellij-plugin" } }
apache-2.0
2641062f06690acb31eb562ffd279ef3
30.461538
86
0.762836
4.869048
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/primitiveTypes/kt2251.kt
5
1143
class A(var b: Byte) { fun c(d: Short) = (b + d.toByte()).toChar() } fun box() : String { if(A(10.toByte()).c(20.toShort()) != 30.toByte().toChar()) return "plus failed" var x = 20.toByte() var y = 20.toByte() val foo = { x++ ++x } if(++x != 21.toByte() || x++ != 21.toByte() || foo() != 24.toByte() || x != 24.toByte()) return "shared byte fail" if(++y != 21.toByte() || y++ != 21.toByte() || y != 22.toByte()) return "byte fail" var xs = 20.toShort() var ys = 20.toShort() val foos = { xs++ ++xs } if(++xs != 21.toShort() || xs++ != 21.toShort() || foos() != 24.toShort() || xs != 24.toShort()) return "shared short fail" if(++ys != 21.toShort() || ys++ != 21.toShort() || ys != 22.toShort()) return "short fail" var xc = 20.toChar() var yc = 20.toChar() val fooc = { xc++ ++xc } if(++xc != 21.toChar() || xc++ != 21.toChar() || fooc() != 24.toChar() || xc != 24.toChar()) return "shared char fail" if(++yc != 21.toChar() || yc++ != 21.toChar() || yc != 22.toChar()) return "char fail" return "OK" }
apache-2.0
67121bca22775851acb40a7e37eff7d1
28.307692
127
0.480315
3.114441
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/compileKotlinAgainstKotlin/inlinedConstants.kt
2
941
// IGNORE_BACKEND: NATIVE // FILE: A.kt package constants public const val b: Byte = 100 public const val s: Short = 20000 public const val i: Int = 2000000 public const val l: Long = 2000000000000L public const val f: Float = 3.14f public const val d: Double = 3.14 public const val bb: Boolean = true public const val c: Char = '\u03c0' // pi symbol public const val str: String = ":)" @Retention(AnnotationRetention.RUNTIME) public annotation class AnnotationClass(public val value: String) // FILE: B.kt import constants.* @AnnotationClass("$b $s $i $l $f $d $bb $c $str") class DummyClass() fun box(): String { val klass = DummyClass::class.java val annotationClass = AnnotationClass::class.java val annotation = klass.getAnnotation(annotationClass)!! val value = annotation.value require(value == "100 20000 2000000 2000000000000 3.14 3.14 true \u03c0 :)", { "Annotation value: $value" }) return "OK" }
apache-2.0
4265782c21c374e9b30ef7e198bfab3a
26.676471
112
0.706695
3.524345
false
false
false
false
hannesa2/owncloud-android
owncloudData/src/androidTest/java/com/owncloud/android/data/sharing/shares/db/OCShareDaoTest.kt
2
19875
/** * ownCloud Android client application * * @author David González Verdugo * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.data.sharing.shares.db import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.test.filters.MediumTest import androidx.test.platform.app.InstrumentationRegistry import com.owncloud.android.data.OwncloudDatabase import com.owncloud.android.data.sharing.shares.datasources.implementation.OCLocalShareDataSource.Companion.toEntity import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.testutil.OC_PRIVATE_SHARE import com.owncloud.android.testutil.OC_PUBLIC_SHARE import com.owncloud.android.testutil.livedata.getLastEmittedValue import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Before import org.junit.Rule import org.junit.Test @MediumTest class OCShareDaoTest { @Rule @JvmField val instantExecutorRule = InstantTaskExecutorRule() private lateinit var ocShareDao: OCShareDao private val privateShareTypeValues = listOf( ShareType.USER.value, ShareType.GROUP.value, ShareType.FEDERATED.value ) @Before fun setUp() { val context = InstrumentationRegistry.getInstrumentation().targetContext OwncloudDatabase.switchToInMemory(context) val db: OwncloudDatabase = OwncloudDatabase.getDatabase(context) ocShareDao = db.shareDao() } /****************************************************************************************************** *********************************************** COMMON *********************************************** ******************************************************************************************************/ @Test fun insertEmptySharesList() { ocShareDao.insert(listOf()) val shares = ocShareDao.getSharesAsLiveData( "/Test/", "admin@server", mutableListOf(ShareType.PUBLIC_LINK.value).plus(privateShareTypeValues) ).getLastEmittedValue()!! assertNotNull(shares) assertEquals(0, shares.size) } @Test fun insertSharesFromDifferentFilesAndRead() { ocShareDao.insert( listOf( OC_PUBLIC_SHARE.copy( path = "/Photos/", isFolder = true, name = "Photos folder link", shareLink = "http://server:port/s/1", accountOwner = "admin@server" ).toEntity(), OC_PUBLIC_SHARE.copy( path = "/Photos/image1.jpg", isFolder = false, name = "Image 1 link", shareLink = "http://server:port/s/2", accountOwner = "admin@server" ).toEntity(), OC_PRIVATE_SHARE.copy( path = "/Photos/image2.jpg", isFolder = false, shareWith = "username", sharedWithDisplayName = "John", accountOwner = "admin@server" ).toEntity() ) ) val photosFolderPublicShares = ocShareDao.getSharesAsLiveData( "/Photos/", "admin@server", listOf(ShareType.PUBLIC_LINK.value) ).getLastEmittedValue()!! assertNotNull(photosFolderPublicShares) assertEquals(1, photosFolderPublicShares.size) assertEquals("/Photos/", photosFolderPublicShares[0].path) assertEquals(true, photosFolderPublicShares[0].isFolder) assertEquals("admin@server", photosFolderPublicShares[0].accountOwner) assertEquals("Photos folder link", photosFolderPublicShares[0].name) assertEquals("http://server:port/s/1", photosFolderPublicShares[0].shareLink) val image1PublicShares = ocShareDao.getSharesAsLiveData( "/Photos/image1.jpg", "admin@server", listOf(ShareType.PUBLIC_LINK.value) ).getLastEmittedValue()!! assertNotNull(image1PublicShares) assertEquals(1, image1PublicShares.size) assertEquals("/Photos/image1.jpg", image1PublicShares[0].path) assertEquals(false, image1PublicShares[0].isFolder) assertEquals("admin@server", image1PublicShares[0].accountOwner) assertEquals("Image 1 link", image1PublicShares[0].name) assertEquals("http://server:port/s/2", image1PublicShares[0].shareLink) val image2PrivateShares = ocShareDao.getSharesAsLiveData( "/Photos/image2.jpg", "admin@server", privateShareTypeValues ).getLastEmittedValue()!! assertNotNull(image2PrivateShares) assertEquals(1, image2PrivateShares.size) assertEquals("/Photos/image2.jpg", image2PrivateShares[0].path) assertEquals(false, image2PrivateShares[0].isFolder) assertEquals("admin@server", image1PublicShares[0].accountOwner) assertEquals("username", image2PrivateShares[0].shareWith) assertEquals("John", image2PrivateShares[0].sharedWithDisplayName) } @Test fun insertSharesFromDifferentAccountsAndRead() { ocShareDao.insert( listOf( OC_PUBLIC_SHARE.copy( path = "/Documents/document1.docx", isFolder = false, accountOwner = "user1@server", name = "Document 1 link", shareLink = "http://server:port/s/1" ).toEntity(), OC_PUBLIC_SHARE.copy( path = "/Documents/document1.docx", isFolder = false, accountOwner = "user2@server", name = "Document 1 link", shareLink = "http://server:port/s/2" ).toEntity(), OC_PRIVATE_SHARE.copy( path = "/Documents/document1.docx", isFolder = false, accountOwner = "user3@server", shareWith = "user_name", sharedWithDisplayName = "Patrick" ).toEntity() ) ) val document1PublicSharesForUser1 = ocShareDao.getSharesAsLiveData( "/Documents/document1.docx", "user1@server", listOf(ShareType.PUBLIC_LINK.value) ).getLastEmittedValue()!! assertNotNull(document1PublicSharesForUser1) assertEquals(1, document1PublicSharesForUser1.size) assertEquals("/Documents/document1.docx", document1PublicSharesForUser1[0].path) assertEquals(false, document1PublicSharesForUser1[0].isFolder) assertEquals("user1@server", document1PublicSharesForUser1[0].accountOwner) assertEquals("Document 1 link", document1PublicSharesForUser1[0].name) assertEquals("http://server:port/s/1", document1PublicSharesForUser1[0].shareLink) val document1PublicSharesForUser2 = ocShareDao.getSharesAsLiveData( "/Documents/document1.docx", "user2@server", listOf(ShareType.PUBLIC_LINK.value) ).getLastEmittedValue()!! assertNotNull(document1PublicSharesForUser2) assertEquals(1, document1PublicSharesForUser2.size) assertEquals("/Documents/document1.docx", document1PublicSharesForUser2[0].path) assertEquals(false, document1PublicSharesForUser2[0].isFolder) assertEquals("user2@server", document1PublicSharesForUser2[0].accountOwner) assertEquals("Document 1 link", document1PublicSharesForUser2[0].name) assertEquals("http://server:port/s/2", document1PublicSharesForUser2[0].shareLink) val document1PrivateSharesForUser3 = ocShareDao.getSharesAsLiveData( "/Documents/document1.docx", "user3@server", privateShareTypeValues ).getLastEmittedValue()!! assertNotNull(document1PrivateSharesForUser3) assertEquals(1, document1PrivateSharesForUser3.size) assertEquals("/Documents/document1.docx", document1PrivateSharesForUser3[0].path) assertEquals(false, document1PrivateSharesForUser3[0].isFolder) assertEquals("user3@server", document1PrivateSharesForUser3[0].accountOwner) assertEquals("user_name", document1PrivateSharesForUser3[0].shareWith) assertEquals("Patrick", document1PrivateSharesForUser3[0].sharedWithDisplayName) } @Test fun testAutogenerateId() { ocShareDao.insert( listOf( OC_PUBLIC_SHARE.copy( path = "/Documents/document1.docx", accountOwner = "user1@server", name = "Document 1 link", shareLink = "http://server:port/s/1" ).toEntity(), OC_PUBLIC_SHARE.copy( path = "/Documents/document1.docx", accountOwner = "user1@server", name = "Document 1 link", shareLink = "http://server:port/s/1" ).toEntity() ) ) val sharesWithSameValues = ocShareDao.getSharesAsLiveData( "/Documents/document1.docx", "user1@server", listOf(ShareType.PUBLIC_LINK.value) ).getLastEmittedValue()!! assertNotNull(sharesWithSameValues) assertEquals(2, sharesWithSameValues.size) assertEquals("/Documents/document1.docx", sharesWithSameValues[0].path) assertEquals("/Documents/document1.docx", sharesWithSameValues[1].path) assertEquals(false, sharesWithSameValues[0].isFolder) assertEquals(false, sharesWithSameValues[1].isFolder) assertEquals("user1@server", sharesWithSameValues[0].accountOwner) assertEquals("user1@server", sharesWithSameValues[1].accountOwner) assertEquals("Document 1 link", sharesWithSameValues[0].name) assertEquals("Document 1 link", sharesWithSameValues[1].name) assertEquals("http://server:port/s/1", sharesWithSameValues[0].shareLink) assertEquals("http://server:port/s/1", sharesWithSameValues[1].shareLink) assertNotNull(sharesWithSameValues[0].id) assertNotNull(sharesWithSameValues[1].id) assert(sharesWithSameValues[0].id != sharesWithSameValues[1].id) } /****************************************************************************************************** ******************************************* PRIVATE SHARES ******************************************* ******************************************************************************************************/ @Test fun getNonExistingPrivateShare() { val privateShare = createDefaultPrivateShareEntity() ocShareDao.insert(privateShare) val nonExistingPrivateShare = ocShareDao.getSharesAsLiveData( privateShare.path, "user@server", privateShareTypeValues ).getLastEmittedValue()!! assertNotNull(nonExistingPrivateShare) assertEquals(0, nonExistingPrivateShare.size) } @Test fun replacePrivateShareIfAlreadyExists_exists() { val privateShare = createDefaultPrivateShareEntity() ocShareDao.insert(createDefaultPrivateShareEntity()) val privateShareToReplace = createDefaultPrivateShareEntity(shareWith = "userName") ocShareDao.replaceShares( listOf(privateShareToReplace) ) val textShares = ocShareDao.getSharesAsLiveData( privateShare.path, privateShare.accountOwner, listOf(ShareType.USER.value) ).getLastEmittedValue()!! assertNotNull(textShares) assertEquals(1, textShares.size) assertEquals(privateShareToReplace.shareWith, textShares[0].shareWith) } @Test fun replacePrivateShareIfAlreadyExists_doesNotExist() { val privateShare = createDefaultPrivateShareEntity( shareType = ShareType.GROUP ) ocShareDao.insert(privateShare) val privateShareToReplace = createDefaultPrivateShareEntity( shareType = ShareType.GROUP, shareWith = "userName", path = "/Texts/text2.txt" ) ocShareDao.replaceShares( listOf(privateShareToReplace) ) val text1Shares = ocShareDao.getSharesAsLiveData( privateShare.path, privateShare.accountOwner, listOf(ShareType.GROUP.value) ).getLastEmittedValue()!! assertNotNull(text1Shares) assertEquals(1, text1Shares.size) assertEquals(privateShare.shareWith, text1Shares[0].shareWith) // text2 link didn't exist before, it should not replace the old one but be created val text2Shares = ocShareDao.getSharesAsLiveData( privateShareToReplace.path, privateShareToReplace.accountOwner, listOf(ShareType.GROUP.value) ).getLastEmittedValue()!! assertNotNull(text2Shares) assertEquals(1, text2Shares.size) assertEquals(privateShareToReplace.shareWith, text2Shares[0].shareWith) } @Test fun updatePrivateShare() { val privateShare = createDefaultPrivateShareEntity() ocShareDao.insert(privateShare) ocShareDao.update( createDefaultPrivateShareEntity(permissions = 17) ) val textShares = ocShareDao.getSharesAsLiveData( privateShare.path, privateShare.accountOwner, listOf(ShareType.USER.value) ).getLastEmittedValue()!! assertNotNull(textShares) assertEquals(1, textShares.size) assertEquals(17, textShares[0].permissions) } @Test fun deletePrivateShare() { val privateShare = createDefaultPrivateShareEntity() ocShareDao.insert(createDefaultPrivateShareEntity()) ocShareDao.deleteShare(privateShare.remoteId) val textShares = ocShareDao.getSharesAsLiveData( privateShare.path, privateShare.accountOwner, listOf(ShareType.USER.value) ).getLastEmittedValue()!! assertNotNull(textShares) assertEquals(0, textShares.size) // List of textShares empty after deleting the existing share } private fun createDefaultPrivateShareEntity( shareType: ShareType = ShareType.USER, shareWith: String = "username", path: String = "/Texts/text1.txt", permissions: Int = -1, shareWithDisplayName: String = "Steve" ) = OC_PRIVATE_SHARE.copy( shareType = shareType, shareWith = shareWith, path = path, permissions = permissions, isFolder = false, sharedWithDisplayName = shareWithDisplayName ).toEntity() /****************************************************************************************************** ******************************************* PUBLIC SHARES ******************************************** ******************************************************************************************************/ @Test fun getNonExistingPublicShare() { val publicShare = createDefaultPublicShareEntity() ocShareDao.insert(publicShare) val nonExistingPublicShare = ocShareDao.getSharesAsLiveData( publicShare.path, "user@server", listOf(ShareType.PUBLIC_LINK.value) ).getLastEmittedValue()!! assertNotNull(nonExistingPublicShare) assertEquals(0, nonExistingPublicShare.size) } @Test fun replacePublicShareIfAlreadyExists_exists() { val publicShare = createDefaultPublicShareEntity() ocShareDao.insert(publicShare) val publicShareToReplace = createDefaultPublicShareEntity(name = "Text 2 link") ocShareDao.replaceShares( listOf(publicShareToReplace) ) val textShares = ocShareDao.getSharesAsLiveData( publicShare.path, publicShare.accountOwner, listOf(ShareType.PUBLIC_LINK.value) ).getLastEmittedValue()!! assertNotNull(textShares) assertEquals(1, textShares.size) assertEquals(publicShareToReplace.name, textShares[0].name) } @Test fun replacePublicShareIfAlreadyExists_doesNotExist() { val publicShare = createDefaultPublicShareEntity() ocShareDao.insert(publicShare) val publicShareToReplace = createDefaultPublicShareEntity(path = "/Texts/text2.txt", name = "Text 2 link") ocShareDao.replaceShares( listOf(publicShareToReplace) ) val text1Shares = ocShareDao.getSharesAsLiveData( publicShare.path, publicShare.accountOwner, listOf(ShareType.PUBLIC_LINK.value) ).getLastEmittedValue()!! assertNotNull(text1Shares) assertEquals(1, text1Shares.size) assertEquals(publicShare.name, text1Shares[0].name) // text2 link didn't exist before, it should not replace the old one but be created val text2Shares = ocShareDao.getSharesAsLiveData( publicShareToReplace.path, publicShareToReplace.accountOwner, listOf(ShareType.PUBLIC_LINK.value) ).getLastEmittedValue()!! assertNotNull(text2Shares) assertEquals(1, text2Shares.size) assertEquals(publicShareToReplace.name, text2Shares[0].name) } @Test fun updatePublicShare() { val publicShare = createDefaultPublicShareEntity() ocShareDao.insert(publicShare) val publicShareToUpdate = createDefaultPublicShareEntity(name = "Text 1 link updated", expirationDate = 2000) ocShareDao.update(publicShareToUpdate) val textShares = ocShareDao.getSharesAsLiveData( publicShareToUpdate.path, publicShareToUpdate.accountOwner, listOf(ShareType.PUBLIC_LINK.value) ).getLastEmittedValue()!! assertNotNull(textShares) assertEquals(1, textShares.size) assertEquals(publicShareToUpdate.name, textShares[0].name) assertEquals(publicShareToUpdate.expirationDate, textShares[0].expirationDate) } @Test fun deletePublicShare() { val publicShare = createDefaultPublicShareEntity() ocShareDao.insert(publicShare) ocShareDao.deleteShare(publicShare.remoteId) val textShares = ocShareDao.getSharesAsLiveData( publicShare.path, publicShare.accountOwner, listOf(ShareType.PUBLIC_LINK.value) ).getLastEmittedValue()!! assertNotNull(textShares) assertEquals(0, textShares.size) // List of textShares empty after deleting the existing share } private fun createDefaultPublicShareEntity( path: String = "/Texts/text1.txt", expirationDate: Long = 1000, name: String = "Text 1 link" ) = OC_PUBLIC_SHARE.copy( path = path, expirationDate = expirationDate, isFolder = false, name = name, shareLink = "http://server:port/s/1" ).toEntity() }
gpl-2.0
0e7ebb827f90a434e7e261ba5a0b4362
37.145873
117
0.618698
5.574755
false
false
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt
1
7920
package info.nightscout.androidaps.plugins.source import android.content.Intent import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.db.BgReading import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.interfaces.BgSourceInterface import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import org.json.JSONException import org.json.JSONObject import java.util.* import javax.inject.Inject import javax.inject.Singleton @Singleton class EversensePlugin @Inject constructor( injector: HasAndroidInjector, private val sp: SP, resourceHelper: ResourceHelper, aapsLogger: AAPSLogger, private val dateUtil: DateUtil, private val nsUpload: NSUpload ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) .pluginIcon(R.drawable.ic_eversense) .pluginName(R.string.eversense) .shortName(R.string.eversense_shortname) .preferencesId(R.xml.pref_bgsource) .description(R.string.description_source_eversense), aapsLogger, resourceHelper, injector ), BgSourceInterface { private var sensorBatteryLevel = -1 override fun advancedFilteringSupported(): Boolean { return false } override fun handleNewData(intent: Intent) { if (!isEnabled(PluginType.BGSOURCE)) return val bundle = intent.extras ?: return if (bundle.containsKey("currentCalibrationPhase")) aapsLogger.debug(LTag.BGSOURCE, "currentCalibrationPhase: " + bundle.getString("currentCalibrationPhase")) if (bundle.containsKey("placementModeInProgress")) aapsLogger.debug(LTag.BGSOURCE, "placementModeInProgress: " + bundle.getBoolean("placementModeInProgress")) if (bundle.containsKey("glucoseLevel")) aapsLogger.debug(LTag.BGSOURCE, "glucoseLevel: " + bundle.getInt("glucoseLevel")) if (bundle.containsKey("glucoseTrendDirection")) aapsLogger.debug(LTag.BGSOURCE, "glucoseTrendDirection: " + bundle.getString("glucoseTrendDirection")) if (bundle.containsKey("glucoseTimestamp")) aapsLogger.debug(LTag.BGSOURCE, "glucoseTimestamp: " + dateUtil.dateAndTimeString(bundle.getLong("glucoseTimestamp"))) if (bundle.containsKey("batteryLevel")) { aapsLogger.debug(LTag.BGSOURCE, "batteryLevel: " + bundle.getString("batteryLevel")) //sensorBatteryLevel = bundle.getString("batteryLevel").toInt() // TODO: Philoul: Line to check I don't have eversens so I don't know what kind of information is sent... } if (bundle.containsKey("signalStrength")) aapsLogger.debug(LTag.BGSOURCE, "signalStrength: " + bundle.getString("signalStrength")) if (bundle.containsKey("transmitterVersionNumber")) aapsLogger.debug(LTag.BGSOURCE, "transmitterVersionNumber: " + bundle.getString("transmitterVersionNumber")) if (bundle.containsKey("isXLVersion")) aapsLogger.debug(LTag.BGSOURCE, "isXLVersion: " + bundle.getBoolean("isXLVersion")) if (bundle.containsKey("transmitterModelNumber")) aapsLogger.debug(LTag.BGSOURCE, "transmitterModelNumber: " + bundle.getString("transmitterModelNumber")) if (bundle.containsKey("transmitterSerialNumber")) aapsLogger.debug(LTag.BGSOURCE, "transmitterSerialNumber: " + bundle.getString("transmitterSerialNumber")) if (bundle.containsKey("transmitterAddress")) aapsLogger.debug(LTag.BGSOURCE, "transmitterAddress: " + bundle.getString("transmitterAddress")) if (bundle.containsKey("sensorInsertionTimestamp")) aapsLogger.debug(LTag.BGSOURCE, "sensorInsertionTimestamp: " + dateUtil.dateAndTimeString(bundle.getLong("sensorInsertionTimestamp"))) if (bundle.containsKey("transmitterVersionNumber")) aapsLogger.debug(LTag.BGSOURCE, "transmitterVersionNumber: " + bundle.getString("transmitterVersionNumber")) if (bundle.containsKey("transmitterConnectionState")) aapsLogger.debug(LTag.BGSOURCE, "transmitterConnectionState: " + bundle.getString("transmitterConnectionState")) if (bundle.containsKey("glucoseLevels")) { val glucoseLevels = bundle.getIntArray("glucoseLevels") val glucoseRecordNumbers = bundle.getIntArray("glucoseRecordNumbers") val glucoseTimestamps = bundle.getLongArray("glucoseTimestamps") if (glucoseLevels != null && glucoseRecordNumbers != null && glucoseTimestamps != null) { aapsLogger.debug(LTag.BGSOURCE, "glucoseLevels" + Arrays.toString(glucoseLevels)) aapsLogger.debug(LTag.BGSOURCE, "glucoseRecordNumbers" + Arrays.toString(glucoseRecordNumbers)) aapsLogger.debug(LTag.BGSOURCE, "glucoseTimestamps" + Arrays.toString(glucoseTimestamps)) for (i in glucoseLevels.indices) { val bgReading = BgReading() bgReading.value = glucoseLevels[i].toDouble() bgReading.date = glucoseTimestamps[i] bgReading.raw = 0.0 val isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "Eversense") if (isNew && sp.getBoolean(R.string.key_dexcomg5_nsupload, false)) { nsUpload.uploadBg(bgReading, "AndroidAPS-Eversense") } if (isNew && sp.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { nsUpload.sendToXdrip(bgReading) } } } } if (bundle.containsKey("calibrationGlucoseLevels")) { val calibrationGlucoseLevels = bundle.getIntArray("calibrationGlucoseLevels") val calibrationTimestamps = bundle.getLongArray("calibrationTimestamps") val calibrationRecordNumbers = bundle.getLongArray("calibrationRecordNumbers") if (calibrationGlucoseLevels != null && calibrationTimestamps != null && calibrationRecordNumbers != null) { aapsLogger.debug(LTag.BGSOURCE, "calibrationGlucoseLevels" + Arrays.toString(calibrationGlucoseLevels)) aapsLogger.debug(LTag.BGSOURCE, "calibrationTimestamps" + Arrays.toString(calibrationTimestamps)) aapsLogger.debug(LTag.BGSOURCE, "calibrationRecordNumbers" + Arrays.toString(calibrationRecordNumbers)) for (i in calibrationGlucoseLevels.indices) { try { if (MainApp.getDbHelper().getCareportalEventFromTimestamp(calibrationTimestamps[i]) == null) { val data = JSONObject() data.put("enteredBy", "AndroidAPS-Eversense") data.put("created_at", DateUtil.toISOString(calibrationTimestamps[i])) data.put("eventType", CareportalEvent.BGCHECK) data.put("glucoseType", "Finger") data.put("glucose", calibrationGlucoseLevels[i]) data.put("units", Constants.MGDL) nsUpload.uploadCareportalEntryToNS(data) } } catch (e: JSONException) { aapsLogger.error("Unhandled exception", e) } } } } } override fun getSensorBatteryLevel(): Int { return sensorBatteryLevel } }
agpl-3.0
5e3bdca2d72657f0c5f553d58cc0c7d9
61.865079
194
0.694949
5.073671
false
false
false
false
zdary/intellij-community
java/java-impl/src/com/intellij/lang/jvm/actions/JvmClassIntentionActionGroup.kt
3
3088
// 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.lang.jvm.actions import com.intellij.codeInsight.daemon.QuickFixBundle.message import com.intellij.codeInsight.intention.impl.IntentionActionGroup import com.intellij.ide.util.PsiClassListCellRenderer import com.intellij.lang.Language import com.intellij.lang.jvm.JvmClass import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.ListPopup import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.psi.PsiFile import com.intellij.ui.popup.list.ListPopupImpl open class JvmClassIntentionActionGroup( actions: List<JvmGroupIntentionAction>, private val actionGroup: JvmActionGroup, private val callSiteLanguage: Language ) : IntentionActionGroup<JvmGroupIntentionAction>(actions) { override fun getFamilyName(): String = message("create.member.from.usage.family") override fun getGroupText(actions: List<JvmGroupIntentionAction>): String { actions.mapTo(HashSet()) { it.groupDisplayText }.singleOrNull()?.let { // All actions have the same group text // => use it. return it } actions.find { it.target.sourceElement?.language == callSiteLanguage }?.let { // There is an action with same target language as call site language // => its group text is in our language terms // => use its group text. return it.groupDisplayText } // At this point all actions came from foreign languages and all have different group text. // We don't know how to name them, so we fall back to default text. // We pass some data, so the group can, for example, make use of element name. val renderData = actions.asSequence().mapNotNull { it.renderData }.firstOrNull() return actionGroup.getDisplayText(renderData) } override fun chooseAction(project: Project, editor: Editor, file: PsiFile, actions: List<JvmGroupIntentionAction>, invokeAction: (JvmGroupIntentionAction) -> Unit) { createPopup(project, actions, invokeAction).showInBestPositionFor(editor) } protected fun createPopup(project: Project, actions: List<JvmGroupIntentionAction>, invokeAction: (JvmGroupIntentionAction) -> Unit): ListPopup { val targetActions = actions.groupByTo(LinkedHashMap()) { it.target }.mapValues { (_, actions) -> actions.single() } val step = object : BaseListPopupStep<JvmClass>(message("target.class.chooser.title"), targetActions.keys.toList()) { override fun onChosen(selectedValue: JvmClass, finalChoice: Boolean): PopupStep<*>? { invokeAction(targetActions[selectedValue]!!) return null } } return object : ListPopupImpl(project, step) { // TODO JvmClass renderer override fun getListElementRenderer() = PsiClassListCellRenderer() } } }
apache-2.0
317ab1b35575a07bb0de43d4a91a7eb2
43.753623
147
0.723769
4.802488
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/photoview/PhotoViewActivity.kt
1
4040
package io.github.feelfreelinux.wykopmobilny.ui.modules.photoview import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.Menu import android.view.MenuItem import com.bumptech.glide.request.target.SimpleTarget import com.bumptech.glide.request.transition.Transition import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.base.BaseActivity import io.github.feelfreelinux.wykopmobilny.glide.GlideApp import io.github.feelfreelinux.wykopmobilny.utils.ClipboardHelperApi import io.github.feelfreelinux.wykopmobilny.utils.KotlinGlideRequestListener import io.github.feelfreelinux.wykopmobilny.utils.isVisible import kotlinx.android.synthetic.main.activity_photoview.* import kotlinx.android.synthetic.main.toolbar.* import java.io.File import javax.inject.Inject class PhotoViewActivity : BaseActivity() { companion object { const val URL_EXTRA = "URL" const val SHARE_REQUEST_CODE = 1 fun createIntent(context: Context, imageUrl: String) = Intent(context, PhotoViewActivity::class.java).apply { putExtra(PhotoViewActivity.URL_EXTRA, imageUrl) } } @Inject lateinit var clipboardHelper: ClipboardHelperApi override val enableSwipeBackLayout: Boolean = true // We manually attach it here override val isActivityTransfluent: Boolean = true val url: String by lazy { intent.getStringExtra(URL_EXTRA) } private val photoViewActions by lazy { PhotoViewActions(this) as PhotoViewCallbacks } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_photoview) setSupportActionBar(toolbar) toolbar.setBackgroundResource(R.drawable.gradient_toolbar_up) loadingView.isIndeterminate = true title = null if (url.endsWith(".gif")) { loadGif() } else { loadImage() } supportActionBar?.setDisplayHomeAsUpEnabled(true) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.photoview_menu, menu) menu?.findItem(R.id.action_save_mp4)?.isVisible = false return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_share -> photoViewActions.shareImage(url) R.id.action_save_image -> photoViewActions.saveImage(url) R.id.action_copy_url -> clipboardHelper.copyTextToClipboard(url, "imageUrl") R.id.action_open_browser -> { val i = Intent(Intent.ACTION_VIEW) i.data = Uri.parse(url) startActivity(i) } android.R.id.home -> finish() else -> return super.onOptionsItemSelected(item) } return true } fun loadImage() { image.isVisible = true image.setMinimumDpi(70) image.setMinimumTileDpi(240) gif.isVisible = false GlideApp.with(this).downloadOnly().load(url) .into(object : SimpleTarget<File>() { override fun onResourceReady(resource: File, transition: Transition<in File>?) { loadingView.isVisible = false resource.let { image.setImage(io.github.feelfreelinux.wykopmobilny.ui.modules.photoview.ImageSource.uri(resource.absolutePath)) } } }) } private fun loadGif() { image.isVisible = false gif.isVisible = true GlideApp.with(this).load(url) .listener(KotlinGlideRequestListener({ loadingView?.isVisible = false }, { loadingView?.isVisible = false })) .dontTransform() .override(com.bumptech.glide.request.target.Target.SIZE_ORIGINAL, com.bumptech.glide.request.target.Target.SIZE_ORIGINAL) .into(gif) } }
mit
d08a2fe153decdbe30ce2d8eb7d97b8b
37.485714
136
0.672772
4.681344
false
false
false
false
dpisarenko/econsim-tr01
src/test/java/cc/altruix/econsimtr01/ch03/CmdLineParametersValidatorTests.kt
1
6154
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: [email protected] * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 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. * * econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01.ch03 import org.fest.assertions.Assertions import org.junit.Test import org.mockito.Mockito import java.io.File /** * Created by pisarenko on 14.05.2016. */ class CmdLineParametersValidatorTests { @Test fun validateReturnsFalseOnEmptyArray() { val out = AgrigulturalSimulationCmdLineParametersValidator() val res = out.validate(emptyArray()) Assertions.assertThat(res).isNotNull Assertions.assertThat(res.valid).isFalse() Assertions.assertThat(res.message).isEqualTo(AgrigulturalSimulationCmdLineParametersValidator.USAGE) } @Test fun validateReturnsFalseIfFileNotReadable() { val fname1 = "fname1" val fname2 = "fname2" val args = arrayOf(fname1, fname2) val file1 = File(fname1) val file2 = File(fname2) val out = Mockito.spy(AgrigulturalSimulationCmdLineParametersValidator()) Mockito.doReturn(file1).`when`(out).createFile(fname1) Mockito.doReturn(file2).`when`(out).createFile(fname2) Mockito.doReturn(true).`when`(out).canRead(file1) Mockito.doReturn(false).`when`(out).canRead(file2) // Run method under test val res = out.validate(args) // Verify Assertions.assertThat(res.valid).isFalse() Assertions.assertThat(res.message).isEqualTo("Can't read file '$fname2'") Mockito.verify(out).createFile(fname1) Mockito.verify(out).createFile(fname2) Mockito.verify(out).canRead(file1) Mockito.verify(out).canRead(file2) } @Test fun validateDetectsFilesWithMissingOrIncorrectData() { // Prepare val fname1 = "fname1" val fname2 = "fname2" val args = arrayOf(fname1, fname2) val file1 = File(fname1) val file2 = File(fname2) val out = Mockito.spy(AgrigulturalSimulationCmdLineParametersValidator()) Mockito.doReturn(file1).`when`(out).createFile(fname1) Mockito.doReturn(file2).`when`(out).createFile(fname2) Mockito.doReturn(true).`when`(out).canRead(file1) Mockito.doReturn(true).`when`(out).canRead(file2) val simParamProv1Validity = ValidationResult(true, "") val simParamProv2Validity = ValidationResult(false, "SimParametersProviderError") val simParamProv1 = Mockito.spy(PropertiesFileSimParametersProviderWithPredefinedValResult(file1, simParamProv1Validity)) val simParamProv2 = Mockito.spy(PropertiesFileSimParametersProviderWithPredefinedValResult(file2, simParamProv2Validity)) Mockito.doReturn(simParamProv1).`when`(out).createSimParametersProvider(file1) Mockito.doReturn(simParamProv2).`when`(out).createSimParametersProvider(file2) // Run method under test val res = out.validate(args) // Verify Assertions.assertThat(res.valid).isFalse() Assertions.assertThat(res.message).isEqualTo("File 'fname2' is invalid ('SimParametersProviderError')") Mockito.verify(out).createFile(fname1) Mockito.verify(out).createFile(fname2) Mockito.verify(out).canRead(file1) Mockito.verify(out).canRead(file2) Mockito.verify(out).createSimParametersProvider(file1) Mockito.verify(out).createSimParametersProvider(file2) Mockito.verify(simParamProv1).initAndValidate() Mockito.verify(simParamProv2).initAndValidate() } @Test fun validateReturnsTrueIfEverythingIsCorrect() { // Prepare val fname1 = "fname1" val fname2 = "fname2" val args = arrayOf(fname1, fname2) val file1 = File(fname1) val file2 = File(fname2) val out = Mockito.spy(AgrigulturalSimulationCmdLineParametersValidator()) Mockito.doReturn(file1).`when`(out).createFile(fname1) Mockito.doReturn(file2).`when`(out).createFile(fname2) Mockito.doReturn(true).`when`(out).canRead(file1) Mockito.doReturn(true).`when`(out).canRead(file2) val simParamProv1Validity = ValidationResult(true, "") val simParamProv2Validity = ValidationResult(true, "SimParametersProviderError") val simParamProv1 = Mockito.spy(PropertiesFileSimParametersProviderWithPredefinedValResult(file1, simParamProv2Validity)) val simParamProv2 = Mockito.spy(PropertiesFileSimParametersProviderWithPredefinedValResult(file2, simParamProv2Validity)) Mockito.doReturn(simParamProv1).`when`(out).createSimParametersProvider(file1) Mockito.doReturn(simParamProv2).`when`(out).createSimParametersProvider(file2) // Run method under test val res = out.validate(args) // Verify Assertions.assertThat(res.valid).isTrue() Assertions.assertThat(res.message).isEqualTo("") Mockito.verify(out).createFile(fname1) Mockito.verify(out).createFile(fname2) Mockito.verify(out).canRead(file1) Mockito.verify(out).canRead(file2) Mockito.verify(out).createSimParametersProvider(file1) Mockito.verify(out).createSimParametersProvider(file2) Mockito.verify(simParamProv1).initAndValidate() Mockito.verify(simParamProv2).initAndValidate() } }
gpl-3.0
d29254a3b63657474ccea6833baa8594
43.273381
129
0.70507
4.414634
false
true
false
false
siosio/intellij-community
plugins/completion-ml-ranking/src/com/intellij/completion/ml/settings/MLRankingConfigurable.kt
1
3436
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.completion.ml.settings import com.intellij.internal.ml.completion.RankingModelProvider import com.intellij.completion.ml.MLCompletionBundle import com.intellij.openapi.options.BoundConfigurable import com.intellij.openapi.ui.DialogPanel import com.intellij.ui.ContextHelpLabel import com.intellij.ui.IconManager import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.JBLabel import com.intellij.ui.icons.RowIcon import com.intellij.ui.layout.* import com.intellij.util.IconUtil import com.intellij.completion.ml.CompletionMlRankingIcons import java.awt.Rectangle import javax.swing.Icon class MLRankingConfigurable(private val availableProviders: List<RankingModelProvider>) : BoundConfigurable(MLCompletionBundle.message("ml.completion.settings.group")) { private val settings = CompletionMLRankingSettings.getInstance() companion object { val UP_DOWN_ICON = createUpDownIcon() val RELEVANT_ICON = cropIcon(CompletionMlRankingIcons.RelevantProposal) private fun createUpDownIcon(): Icon { val icon = IconManager.getInstance().createRowIcon(2, RowIcon.Alignment.CENTER) icon.setIcon(cropIcon(CompletionMlRankingIcons.ProposalUp), 0) icon.setIcon(cropIcon(CompletionMlRankingIcons.ProposalDown), 1) return icon } private fun cropIcon(icon: Icon): Icon = IconUtil.cropIcon(icon, Rectangle(4, 0, 8, 16)) } override fun createPanel(): DialogPanel { val providers = availableProviders.distinctBy { it.displayNameInSettings }.sortedBy { it.displayNameInSettings } return panel { var enableRankingCheckbox: CellBuilder<JBCheckBox>? = null titledRow(displayName) { row { cell { enableRankingCheckbox = checkBox(MLCompletionBundle.message("ml.completion.enable"), settings::isRankingEnabled, { settings.isRankingEnabled = it }) ContextHelpLabel.create(MLCompletionBundle.message("ml.completion.enable.help"))() } for (ranker in providers) { row { enableRankingCheckbox?.let { enableRanking -> checkBox(ranker.displayNameInSettings, { settings.isLanguageEnabled(ranker.id) }, { settings.setLanguageEnabled(ranker.id, it) }) .enableIf(enableRanking.selected) } }.apply { if (ranker === providers.last()) largeGapAfter() } } } row { cell { enableRankingCheckbox?.let { enableRanking -> checkBox(MLCompletionBundle.message("ml.completion.show.diff"), { settings.isShowDiffEnabled }, { settings.isShowDiffEnabled = it }).enableIf(enableRanking.selected) JBLabel(UP_DOWN_ICON)() } } } row { cell { enableRankingCheckbox?.let { enableRanking -> checkBox(MLCompletionBundle.message("ml.completion.decorate.relevant"), { settings.isDecorateRelevantEnabled }, { settings.isDecorateRelevantEnabled = it }).enableIf(enableRanking.selected) JBLabel(RELEVANT_ICON)() } } } } } } }
apache-2.0
de0f07e0f1486354bb50f511d158ee00
41.419753
140
0.667928
4.880682
false
false
false
false
StephaneBg/ScoreIt
core/src/main/kotlin/com/sbgapps/scoreit/core/ext/List.kt
1
1013
/* * Copyright 2020 Stéphane Baiget * * 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.sbgapps.scoreit.core.ext @Suppress("UNCHECKED_CAST") inline fun <reified T> List<*>.asListOfType(): List<T> = this as List<T> @Suppress("UNCHECKED_CAST") inline fun <reified T> List<*>.asMutableListOfType(): MutableList<T> = this.toMutableList() as MutableList<T> inline fun <reified E> List<E>.replace(index: Int, element: E): List<E> = this.mapIndexed { i, e -> if (index == i) element else e }
apache-2.0
0c1e3f5b0bef2ac66f8a4594d87aa36a
36.481481
109
0.725296
3.776119
false
false
false
false
androidx/androidx
health/health-services-client/src/main/java/androidx/health/services/client/PassiveListenerService.kt
3
5939
/* * Copyright (C) 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.health.services.client import android.app.Service import android.content.Intent import android.os.IBinder import android.util.Log import androidx.health.services.client.data.DataPoint import androidx.health.services.client.data.DataPointContainer import androidx.health.services.client.data.HealthEvent import androidx.health.services.client.data.PassiveGoal import androidx.health.services.client.data.UserActivityInfo import androidx.health.services.client.impl.IPassiveListenerService import androidx.health.services.client.impl.event.PassiveListenerEvent import androidx.health.services.client.impl.response.HealthEventResponse import androidx.health.services.client.impl.response.PassiveMonitoringGoalResponse import androidx.health.services.client.impl.response.PassiveMonitoringUpdateResponse import androidx.health.services.client.proto.EventsProto.PassiveListenerEvent.EventCase.EVENT_NOT_SET import androidx.health.services.client.proto.EventsProto.PassiveListenerEvent.EventCase.HEALTH_EVENT_RESPONSE import androidx.health.services.client.proto.EventsProto.PassiveListenerEvent.EventCase.PASSIVE_GOAL_RESPONSE import androidx.health.services.client.proto.EventsProto.PassiveListenerEvent.EventCase.PASSIVE_UPDATE_RESPONSE import androidx.health.services.client.proto.EventsProto.PassiveListenerEvent.EventCase.PERMISSION_LOST_RESPONSE /** * Service that enables receiving passive monitoring updates throughout the day when the app may not * be running. * * Health Services will bind to the [PassiveListenerService] to deliver passive monitoring updates * such as data or goal updates. Clients should extend this service and override those methods of * the [PassiveListenerCallback] that they care about. They can then pass in their service to * [PassiveMonitoringClient.setPassiveListenerServiceAsync] to receive data updates. */ @Suppress("UNUSED_PARAMETER") public abstract class PassiveListenerService : Service() { private var wrapper: IPassiveListenerServiceWrapper? = null final override fun onBind(intent: Intent): IBinder? { wrapper = IPassiveListenerServiceWrapper() return wrapper } /** * Called when new [DataPoint]s are generated. * * @param dataPoints a list of new [DataPoint]s generated */ public open fun onNewDataPointsReceived(dataPoints: DataPointContainer) {} /** * Called when new [UserActivityInfo] is generated. * * @param info a new [UserActivityInfo] representing the current state */ public open fun onUserActivityInfoReceived(info: UserActivityInfo) {} /** * Called when a [PassiveGoal] has been completed. * * @param goal the [PassiveGoal] that has been completed */ public open fun onGoalCompleted(goal: PassiveGoal) {} /** * Called when a [HealthEvent] has been detected. * * @param event the [HealthEvent] that has been detected */ public open fun onHealthEventReceived(event: HealthEvent) {} /** * Called when the client has lost permission for the passive listener request. If this happens, * WHS will automatically unregister the client request and stop the relevant sensors. The * client can use this callback to detect the problem and either prompt the user to re-grant the * permissions or re-register while requesting only that which the app does have permission for. */ public open fun onPermissionLost() {} internal inner class IPassiveListenerServiceWrapper : IPassiveListenerService.Stub() { override fun onPassiveListenerEvent(event: PassiveListenerEvent) { val proto = event.proto when (proto.eventCase) { PASSIVE_UPDATE_RESPONSE -> { val response = PassiveMonitoringUpdateResponse(proto.passiveUpdateResponse) if (!response.passiveMonitoringUpdate.dataPoints.dataPoints.isEmpty()) { [email protected]( response.passiveMonitoringUpdate.dataPoints ) } for (userActivityInfo in response.passiveMonitoringUpdate.userActivityInfoUpdates) { [email protected](userActivityInfo) } } PASSIVE_GOAL_RESPONSE -> { val response = PassiveMonitoringGoalResponse(proto.passiveGoalResponse) [email protected](response.passiveGoal) } HEALTH_EVENT_RESPONSE -> { val response = HealthEventResponse(proto.healthEventResponse) [email protected](response.healthEvent) } PERMISSION_LOST_RESPONSE -> { [email protected]() } null, EVENT_NOT_SET -> Log.w(TAG, "Received unknown event ${proto.eventCase}") } } override fun getApiVersion(): Int { return API_VERSION } } private companion object { private const val TAG = "PassiveListenerService" } }
apache-2.0
417079e32c1f7230a5964aa4cd049d1d
42.992593
112
0.710894
5.141991
false
false
false
false
androidx/androidx
room/room-migration/src/main/java/androidx/room/migration/bundle/IndexBundle.kt
3
3729
/* * Copyright (C) 2017 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.room.migration.bundle import androidx.annotation.RestrictTo import androidx.room.Index import com.google.gson.annotations.SerializedName /** * Data class that holds the schema information about a table Index. * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) public open class IndexBundle( @SerializedName("name") public open val name: String, @SerializedName("unique") public open val isUnique: Boolean, @SerializedName("columnNames") public open val columnNames: List<String>?, @SerializedName("orders") public open val orders: List<String>?, @SerializedName("createSql") public open val createSql: String ) : SchemaEquality<IndexBundle> { public companion object { // should match Index.kt public const val DEFAULT_PREFIX: String = "index_" } /** * @deprecated Use {@link #IndexBundle(String, boolean, List, List, String)} */ @Deprecated("Use {@link #IndexBundle(String, boolean, List, List, String)}") public constructor( name: String, unique: Boolean, columnNames: List<String>, createSql: String ) : this(name, unique, columnNames, null, createSql) // Used by GSON @Deprecated("Marked deprecated to avoid usage in the codebase") @SuppressWarnings("unused") private constructor() : this("", false, emptyList(), emptyList(), "") /** * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX) public open fun create(tableName: String): String { return replaceTableName(createSql, tableName) } /** * @param tableName The table name. * @return Create index SQL query that uses the given table name. */ public open fun getCreateSql(tableName: String): String { return replaceTableName(createSql, tableName) } override fun isSchemaEqual(other: IndexBundle): Boolean { if (isUnique != other.isUnique) return false if (name.startsWith(DEFAULT_PREFIX)) { if (!other.name.startsWith(DEFAULT_PREFIX)) { return false } } else if (other.name.startsWith(DEFAULT_PREFIX)) { return false } else if (!name.equals(other.name)) { return false } // order matters if (columnNames?.let { columnNames != other.columnNames } ?: (other.columnNames != null)) { return false } // order matters and null orders is considered equal to all ASC orders, to be backward // compatible with schemas where orders are not present in the schema file val columnsSize = columnNames?.size ?: 0 val orders = if (orders.isNullOrEmpty()) { List(columnsSize) { Index.Order.ASC.name } } else { orders } val otherOrders = if (other.orders.isNullOrEmpty()) { List(columnsSize) { Index.Order.ASC.name } } else { other.orders } if (orders != otherOrders) return false return true } }
apache-2.0
57dc8f0d899e94fab5dbf9394889040d
31.426087
99
0.641727
4.547561
false
false
false
false
androidx/androidx
compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/snapping/RowSnapLayoutInfoProvider.kt
3
2227
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.demos.snapping import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.ScrollState import androidx.compose.foundation.gestures.snapping.SnapLayoutInfoProvider import androidx.compose.ui.unit.Density import kotlin.math.ceil import kotlin.math.floor import kotlin.math.roundToInt @OptIn(ExperimentalFoundationApi::class) fun SnapLayoutInfoProvider( scrollState: ScrollState, itemSize: Density.() -> Float, layoutSize: Density.() -> Float ) = object : SnapLayoutInfoProvider { fun Density.nextFullItemCenter(layoutCenter: Float): Float { val intItemSize = itemSize().roundToInt() return floor((layoutCenter + calculateSnapStepSize()) / itemSize().roundToInt()) * intItemSize } fun Density.previousFullItemCenter(layoutCenter: Float): Float { val intItemSize = itemSize().roundToInt() return ceil((layoutCenter - calculateSnapStepSize()) / itemSize().roundToInt()) * intItemSize } override fun Density.calculateSnappingOffsetBounds(): ClosedFloatingPointRange<Float> { val layoutCenter = layoutSize() / 2f + scrollState.value + calculateSnapStepSize() / 2f val lowerBound = nextFullItemCenter(layoutCenter) - layoutCenter val upperBound = previousFullItemCenter(layoutCenter) - layoutCenter return upperBound.rangeTo(lowerBound) } override fun Density.calculateSnapStepSize(): Float { return itemSize() } override fun Density.calculateApproachOffset(initialVelocity: Float): Float = 0f }
apache-2.0
f2e4d71acd12330f68da54df190ebf51
37.413793
95
0.740458
4.820346
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/keyvalue/DonationsValues.kt
1
18421
package org.thoughtcrime.securesms.keyvalue import androidx.annotation.WorkerThread import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.subjects.BehaviorSubject import io.reactivex.rxjava3.subjects.Subject import org.signal.core.util.logging.Log import org.signal.donations.StripeApi import org.signal.libsignal.zkgroup.InvalidInputException import org.signal.libsignal.zkgroup.VerificationFailedException import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialPresentation import org.signal.libsignal.zkgroup.receipts.ReceiptCredentialRequestContext import org.signal.libsignal.zkgroup.receipts.ReceiptSerial import org.thoughtcrime.securesms.badges.Badges import org.thoughtcrime.securesms.badges.models.Badge import org.thoughtcrime.securesms.database.model.databaseprotos.BadgeList import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.jobs.SubscriptionReceiptRequestResponseJob import org.thoughtcrime.securesms.payments.currency.CurrencyUtil import org.thoughtcrime.securesms.subscription.LevelUpdateOperation import org.thoughtcrime.securesms.subscription.Subscriber import org.thoughtcrime.securesms.util.Util import org.whispersystems.signalservice.api.subscriptions.ActiveSubscription import org.whispersystems.signalservice.api.subscriptions.IdempotencyKey import org.whispersystems.signalservice.api.subscriptions.SubscriberId import org.whispersystems.signalservice.internal.util.JsonUtil import java.security.SecureRandom import java.util.Currency import java.util.Locale import java.util.concurrent.TimeUnit internal class DonationsValues internal constructor(store: KeyValueStore) : SignalStoreValues(store) { companion object { private val TAG = Log.tag(DonationsValues::class.java) private const val KEY_SUBSCRIPTION_CURRENCY_CODE = "donation.currency.code" private const val KEY_CURRENCY_CODE_ONE_TIME = "donation.currency.code.boost" private const val KEY_SUBSCRIBER_ID_PREFIX = "donation.subscriber.id." private const val KEY_LAST_KEEP_ALIVE_LAUNCH = "donation.last.successful.ping" /** * Our last known "end of period" for a subscription. This value is used to determine * when a user should try to redeem a badge for their subscription, and as a hint that * a user has an active subscription. */ private const val KEY_LAST_END_OF_PERIOD_SECONDS = "donation.last.end.of.period" private const val EXPIRED_BADGE = "donation.expired.badge" private const val EXPIRED_GIFT_BADGE = "donation.expired.gift.badge" private const val USER_MANUALLY_CANCELLED = "donation.user.manually.cancelled" private const val KEY_LEVEL_OPERATION_PREFIX = "donation.level.operation." private const val KEY_LEVEL_HISTORY = "donation.level.history" private const val DISPLAY_BADGES_ON_PROFILE = "donation.display.badges.on.profile" private const val SUBSCRIPTION_REDEMPTION_FAILED = "donation.subscription.redemption.failed" private const val SHOULD_CANCEL_SUBSCRIPTION_BEFORE_NEXT_SUBSCRIBE_ATTEMPT = "donation.should.cancel.subscription.before.next.subscribe.attempt" private const val SUBSCRIPTION_CANCELATION_CHARGE_FAILURE = "donation.subscription.cancelation.charge.failure" private const val SUBSCRIPTION_CANCELATION_REASON = "donation.subscription.cancelation.reason" private const val SUBSCRIPTION_CANCELATION_TIMESTAMP = "donation.subscription.cancelation.timestamp" private const val SUBSCRIPTION_CANCELATION_WATERMARK = "donation.subscription.cancelation.watermark" private const val SHOW_CANT_PROCESS_DIALOG = "show.cant.process.dialog" /** * The current request context for subscription. This should be stored until either * it is successfully converted into a response, the end of period changes, or the user * manually cancels the subscription. */ private const val SUBSCRIPTION_CREDENTIAL_REQUEST = "subscription.credential.request" /** * The current response presentation that can be submitted for a badge. This should be * stored until it is successfully redeemed, the end of period changes, or the user * manually cancels their subscription. */ private const val SUBSCRIPTION_CREDENTIAL_RECEIPT = "subscription.credential.receipt" /** * Notes the "end of period" time for the latest subscription that we have started * to get a response presentation for. When this is equal to the latest "end of period" * it can be assumed that we have a request context that can be safely reused. */ private const val SUBSCRIPTION_EOP_STARTED_TO_CONVERT = "subscription.eop.convert" /** * Notes the "end of period" time for the latest subscription that we have started * to redeem a response presentation for. When this is equal to the latest "end of * period" it can be assumed that we have a response presentation that we can submit * to get an active token for. */ private const val SUBSCRIPTION_EOP_STARTED_TO_REDEEM = "subscription.eop.redeem" /** * Notes the "end of period" time for the latest subscription that we have successfully * and fully redeemed a token for. If this is equal to the latest "end of period" it is * assumed that there is no work to be done. */ private const val SUBSCRIPTION_EOP_REDEEMED = "subscription.eop.redeemed" } override fun onFirstEverAppLaunch() = Unit override fun getKeysToIncludeInBackup(): MutableList<String> = mutableListOf( KEY_CURRENCY_CODE_ONE_TIME, KEY_LAST_KEEP_ALIVE_LAUNCH, KEY_LAST_END_OF_PERIOD_SECONDS, SHOULD_CANCEL_SUBSCRIPTION_BEFORE_NEXT_SUBSCRIBE_ATTEMPT, SUBSCRIPTION_CANCELATION_REASON, SUBSCRIPTION_CANCELATION_TIMESTAMP, SUBSCRIPTION_CANCELATION_WATERMARK, SHOW_CANT_PROCESS_DIALOG, SUBSCRIPTION_CREDENTIAL_REQUEST, SUBSCRIPTION_CREDENTIAL_RECEIPT, SUBSCRIPTION_EOP_STARTED_TO_CONVERT, SUBSCRIPTION_EOP_STARTED_TO_REDEEM, SUBSCRIPTION_EOP_REDEEMED ) private val subscriptionCurrencyPublisher: Subject<Currency> by lazy { BehaviorSubject.createDefault(getSubscriptionCurrency()) } val observableSubscriptionCurrency: Observable<Currency> by lazy { subscriptionCurrencyPublisher } private val oneTimeCurrencyPublisher: Subject<Currency> by lazy { BehaviorSubject.createDefault(getOneTimeCurrency()) } val observableOneTimeCurrency: Observable<Currency> by lazy { oneTimeCurrencyPublisher } fun getSubscriptionCurrency(): Currency { val currencyCode = getString(KEY_SUBSCRIPTION_CURRENCY_CODE, null) val currency: Currency? = if (currencyCode == null) { val localeCurrency = CurrencyUtil.getCurrencyByLocale(Locale.getDefault()) if (localeCurrency == null) { val e164: String? = SignalStore.account().e164 if (e164 == null) { null } else { CurrencyUtil.getCurrencyByE164(e164) } } else { localeCurrency } } else { CurrencyUtil.getCurrencyByCurrencyCode(currencyCode) } return if (currency != null && StripeApi.Validation.supportedCurrencyCodes.contains(currency.currencyCode.uppercase(Locale.ROOT))) { currency } else { Currency.getInstance("USD") } } fun getOneTimeCurrency(): Currency { val oneTimeCurrency = getString(KEY_CURRENCY_CODE_ONE_TIME, null) return if (oneTimeCurrency == null) { val currency = getSubscriptionCurrency() setOneTimeCurrency(currency) currency } else { Currency.getInstance(oneTimeCurrency) } } fun setOneTimeCurrency(currency: Currency) { putString(KEY_CURRENCY_CODE_ONE_TIME, currency.currencyCode) oneTimeCurrencyPublisher.onNext(currency) } fun getSubscriber(currency: Currency): Subscriber? { val currencyCode = currency.currencyCode val subscriberIdBytes = getBlob("$KEY_SUBSCRIBER_ID_PREFIX$currencyCode", null) return if (subscriberIdBytes == null) { null } else { Subscriber(SubscriberId.fromBytes(subscriberIdBytes), currencyCode) } } fun getSubscriber(): Subscriber? { return getSubscriber(getSubscriptionCurrency()) } fun requireSubscriber(): Subscriber { return getSubscriber() ?: throw Exception("Subscriber ID is not set.") } fun setSubscriber(subscriber: Subscriber) { Log.i(TAG, "Setting subscriber for currency ${subscriber.currencyCode}", Exception(), true) val currencyCode = subscriber.currencyCode store.beginWrite() .putBlob("$KEY_SUBSCRIBER_ID_PREFIX$currencyCode", subscriber.subscriberId.bytes) .putString(KEY_SUBSCRIPTION_CURRENCY_CODE, currencyCode) .apply() subscriptionCurrencyPublisher.onNext(Currency.getInstance(currencyCode)) } fun getLevelOperation(level: String): LevelUpdateOperation? { val idempotencyKey = getBlob("${KEY_LEVEL_OPERATION_PREFIX}$level", null) return if (idempotencyKey != null) { LevelUpdateOperation(IdempotencyKey.fromBytes(idempotencyKey), level) } else { null } } fun setLevelOperation(levelUpdateOperation: LevelUpdateOperation) { addLevelToHistory(levelUpdateOperation.level) putBlob("$KEY_LEVEL_OPERATION_PREFIX${levelUpdateOperation.level}", levelUpdateOperation.idempotencyKey.bytes) } private fun getLevelHistory(): Set<String> { return getString(KEY_LEVEL_HISTORY, "").split(",").toSet() } private fun addLevelToHistory(level: String) { val levels = getLevelHistory() + level putString(KEY_LEVEL_HISTORY, levels.joinToString(",")) } fun clearLevelOperations() { val levelHistory = getLevelHistory() val write = store.beginWrite() for (level in levelHistory) { write.remove("${KEY_LEVEL_OPERATION_PREFIX}$level") } write.apply() } fun setExpiredBadge(badge: Badge?) { if (badge != null) { putBlob(EXPIRED_BADGE, Badges.toDatabaseBadge(badge).toByteArray()) } else { remove(EXPIRED_BADGE) } } fun getExpiredBadge(): Badge? { val badgeBytes = getBlob(EXPIRED_BADGE, null) ?: return null return Badges.fromDatabaseBadge(BadgeList.Badge.parseFrom(badgeBytes)) } fun setExpiredGiftBadge(badge: Badge?) { if (badge != null) { putBlob(EXPIRED_GIFT_BADGE, Badges.toDatabaseBadge(badge).toByteArray()) } else { remove(EXPIRED_GIFT_BADGE) } } fun getExpiredGiftBadge(): Badge? { val badgeBytes = getBlob(EXPIRED_GIFT_BADGE, null) ?: return null return Badges.fromDatabaseBadge(BadgeList.Badge.parseFrom(badgeBytes)) } fun getLastKeepAliveLaunchTime(): Long { return getLong(KEY_LAST_KEEP_ALIVE_LAUNCH, 0L) } fun setLastKeepAliveLaunchTime(timestamp: Long) { putLong(KEY_LAST_KEEP_ALIVE_LAUNCH, timestamp) } fun getLastEndOfPeriod(): Long { return getLong(KEY_LAST_END_OF_PERIOD_SECONDS, 0L) } fun setLastEndOfPeriod(timestamp: Long) { putLong(KEY_LAST_END_OF_PERIOD_SECONDS, timestamp) } /** * True if the local user is likely a sustainer, otherwise false. Note the term 'likely', because this is based on cached data. Any serious decisions that * rely on this should make a network request to determine subscription status. */ fun isLikelyASustainer(): Boolean { return TimeUnit.SECONDS.toMillis(getLastEndOfPeriod()) > System.currentTimeMillis() } fun isUserManuallyCancelled(): Boolean { return getBoolean(USER_MANUALLY_CANCELLED, false) } fun markUserManuallyCancelled() { putBoolean(USER_MANUALLY_CANCELLED, true) } fun clearUserManuallyCancelled() { remove(USER_MANUALLY_CANCELLED) } fun setDisplayBadgesOnProfile(enabled: Boolean) { putBoolean(DISPLAY_BADGES_ON_PROFILE, enabled) } fun getDisplayBadgesOnProfile(): Boolean { return getBoolean(DISPLAY_BADGES_ON_PROFILE, false) } fun getSubscriptionRedemptionFailed(): Boolean { return getBoolean(SUBSCRIPTION_REDEMPTION_FAILED, false) } fun markSubscriptionRedemptionFailed() { Log.w(TAG, "markSubscriptionRedemptionFailed()", Throwable(), true) putBoolean(SUBSCRIPTION_REDEMPTION_FAILED, true) } fun clearSubscriptionRedemptionFailed() { putBoolean(SUBSCRIPTION_REDEMPTION_FAILED, false) } fun setUnexpectedSubscriptionCancelationChargeFailure(chargeFailure: ActiveSubscription.ChargeFailure?) { if (chargeFailure == null) { remove(SUBSCRIPTION_CANCELATION_CHARGE_FAILURE) } else { putString(SUBSCRIPTION_CANCELATION_CHARGE_FAILURE, JsonUtil.toJson(chargeFailure)) } } fun getUnexpectedSubscriptionCancelationChargeFailure(): ActiveSubscription.ChargeFailure? { val json = getString(SUBSCRIPTION_CANCELATION_CHARGE_FAILURE, null) return if (json.isNullOrEmpty()) { null } else { JsonUtil.fromJson(json, ActiveSubscription.ChargeFailure::class.java) } } var unexpectedSubscriptionCancelationReason: String? by stringValue(SUBSCRIPTION_CANCELATION_REASON, null) var unexpectedSubscriptionCancelationTimestamp: Long by longValue(SUBSCRIPTION_CANCELATION_TIMESTAMP, 0L) var unexpectedSubscriptionCancelationWatermark: Long by longValue(SUBSCRIPTION_CANCELATION_WATERMARK, 0L) @get:JvmName("showCantProcessDialog") var showCantProcessDialog: Boolean by booleanValue(SHOW_CANT_PROCESS_DIALOG, true) /** * Denotes that the previous attempt to subscribe failed in some way. Either an * automatic renewal failed resulting in an unexpected expiration, or payment failed * on Stripe's end. * * Before trying to resubscribe, we should first ensure there are no subscriptions set * on the server. Otherwise, we could get into a situation where the user is unable to * resubscribe. */ var shouldCancelSubscriptionBeforeNextSubscribeAttempt: Boolean get() = getBoolean(SHOULD_CANCEL_SUBSCRIPTION_BEFORE_NEXT_SUBSCRIBE_ATTEMPT, false) set(value) = putBoolean(SHOULD_CANCEL_SUBSCRIPTION_BEFORE_NEXT_SUBSCRIBE_ATTEMPT, value) /** * Consolidates a bunch of data clears that should occur whenever a user manually cancels their * subscription: * * 1. Clears keep-alive flag * 1. Clears level operation * 1. Marks the user as manually cancelled * 1. Clears out unexpected cancelation state * 1. Clears expired badge if it is for a subscription */ @WorkerThread fun updateLocalStateForManualCancellation() { synchronized(SubscriptionReceiptRequestResponseJob.MUTEX) { Log.d(TAG, "[updateLocalStateForManualCancellation] Clearing donation values.") setLastEndOfPeriod(0L) clearLevelOperations() markUserManuallyCancelled() shouldCancelSubscriptionBeforeNextSubscribeAttempt = false setUnexpectedSubscriptionCancelationChargeFailure(null) unexpectedSubscriptionCancelationReason = null unexpectedSubscriptionCancelationTimestamp = 0L clearSubscriptionRequestCredential() clearSubscriptionReceiptCredential() val expiredBadge = getExpiredBadge() if (expiredBadge != null && expiredBadge.isSubscription()) { Log.d(TAG, "[updateLocalStateForManualCancellation] Clearing expired badge.") setExpiredBadge(null) } } } /** * Consolidates a bunch of data clears that should occur whenever a user begins a new subscription: * * 1. Manual cancellation marker * 1. Any set level operations * 1. Unexpected cancelation flags * 1. Expired badge, if it is of a subscription */ @WorkerThread fun updateLocalStateForLocalSubscribe() { synchronized(SubscriptionReceiptRequestResponseJob.MUTEX) { Log.d(TAG, "[updateLocalStateForLocalSubscribe] Clearing donation values.") clearUserManuallyCancelled() clearLevelOperations() shouldCancelSubscriptionBeforeNextSubscribeAttempt = false setUnexpectedSubscriptionCancelationChargeFailure(null) unexpectedSubscriptionCancelationReason = null unexpectedSubscriptionCancelationTimestamp = 0L refreshSubscriptionRequestCredential() clearSubscriptionReceiptCredential() val expiredBadge = getExpiredBadge() if (expiredBadge != null && expiredBadge.isSubscription()) { Log.d(TAG, "[updateLocalStateForLocalSubscribe] Clearing expired badge.") setExpiredBadge(null) } } } fun refreshSubscriptionRequestCredential() { putBlob(SUBSCRIPTION_CREDENTIAL_REQUEST, generateRequestCredential().serialize()) } fun setSubscriptionRequestCredential(requestContext: ReceiptCredentialRequestContext) { putBlob(SUBSCRIPTION_CREDENTIAL_REQUEST, requestContext.serialize()) } fun getSubscriptionRequestCredential(): ReceiptCredentialRequestContext? { val bytes = getBlob(SUBSCRIPTION_CREDENTIAL_REQUEST, null) ?: return null return ReceiptCredentialRequestContext(bytes) } fun clearSubscriptionRequestCredential() { remove(SUBSCRIPTION_CREDENTIAL_REQUEST) } fun setSubscriptionReceiptCredential(receiptCredentialPresentation: ReceiptCredentialPresentation) { putBlob(SUBSCRIPTION_CREDENTIAL_RECEIPT, receiptCredentialPresentation.serialize()) } fun getSubscriptionReceiptCredential(): ReceiptCredentialPresentation? { val bytes = getBlob(SUBSCRIPTION_CREDENTIAL_RECEIPT, null) ?: return null return ReceiptCredentialPresentation(bytes) } fun clearSubscriptionReceiptCredential() { remove(SUBSCRIPTION_CREDENTIAL_RECEIPT) } var subscriptionEndOfPeriodConversionStarted by longValue(SUBSCRIPTION_EOP_STARTED_TO_CONVERT, 0L) var subscriptionEndOfPeriodRedemptionStarted by longValue(SUBSCRIPTION_EOP_STARTED_TO_REDEEM, 0L) var subscriptionEndOfPeriodRedeemed by longValue(SUBSCRIPTION_EOP_REDEEMED, 0L) private fun generateRequestCredential(): ReceiptCredentialRequestContext { Log.d(TAG, "Generating request credentials context for token redemption...", true) val secureRandom = SecureRandom() val randomBytes = Util.getSecretBytes(ReceiptSerial.SIZE) return try { val receiptSerial = ReceiptSerial(randomBytes) val operations = ApplicationDependencies.getClientZkReceiptOperations() operations.createReceiptCredentialRequestContext(secureRandom, receiptSerial) } catch (e: InvalidInputException) { Log.e(TAG, "Failed to create credential.", e) throw AssertionError(e) } catch (e: VerificationFailedException) { Log.e(TAG, "Failed to create credential.", e) throw AssertionError(e) } } }
gpl-3.0
3d63f0fbeced4c10b8edec3cf3cdedc4
38.530043
156
0.752945
4.884911
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/actions/ShowKotlinBytecodeAction.kt
5
1779
// 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.actions import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.wm.ToolWindowAnchor import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.content.ContentFactory import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.internal.KotlinBytecodeToolWindow class ShowKotlinBytecodeAction : AnAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val toolWindowManager = ToolWindowManager.getInstance(project) val toolWindow = toolWindowManager.getToolWindow(TOOLWINDOW_ID) ?: toolWindowManager.registerToolWindow( TOOLWINDOW_ID, false, ToolWindowAnchor.RIGHT, ) .apply { setIcon(KotlinIcons.SMALL_LOGO_13) val contentFactory = ContentFactory.getInstance() contentManager.addContent(contentFactory.createContent(KotlinBytecodeToolWindow(project, this), "", false)) } toolWindow.activate(null) } override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { val file = e.getData(CommonDataKeys.PSI_FILE) e.presentation.isEnabled = e.project != null && file?.fileType == KotlinFileType.INSTANCE } companion object { const val TOOLWINDOW_ID = "Kotlin Bytecode" } }
apache-2.0
0f746106b7a5dec56777d12363c6b33b
38.533333
123
0.731872
4.914365
false
false
false
false
GunoH/intellij-community
platform/platform-api/src/com/intellij/ui/tabs/impl/JBEditorTabPainter.kt
3
2125
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.tabs.impl import com.intellij.ui.ExperimentalUI import com.intellij.ui.tabs.JBTabsPosition import com.intellij.ui.tabs.impl.themes.EditorTabTheme import java.awt.Graphics2D import java.awt.Point import java.awt.Rectangle class JBEditorTabPainter : JBDefaultTabPainter(EditorTabTheme()) { fun paintLeftGap(position: JBTabsPosition, g: Graphics2D, rect: Rectangle, borderThickness: Int) { val maxY = rect.y + rect.height - borderThickness paintBorderLine(g, borderThickness, Point(rect.x, rect.y), Point(rect.x, maxY)) } fun paintRightGap(position: JBTabsPosition, g: Graphics2D, rect: Rectangle, borderThickness: Int) { val maxX = rect.x + rect.width - borderThickness val maxY = rect.y + rect.height - borderThickness paintBorderLine(g, borderThickness, Point(maxX, rect.y), Point(maxX, maxY)) } fun paintTopGap(position: JBTabsPosition, g: Graphics2D, rect: Rectangle, borderThickness: Int) { val maxX = rect.x + rect.width paintBorderLine(g, borderThickness, Point(rect.x, rect.y), Point(maxX, rect.y)) } fun paintBottomGap(position: JBTabsPosition, g: Graphics2D, rect: Rectangle, borderThickness: Int) { val maxX = rect.x + rect.width - borderThickness val maxY = rect.y + rect.height - borderThickness paintBorderLine(g, borderThickness, Point(rect.x, maxY), Point(maxX, maxY)) } override fun underlineRectangle(position: JBTabsPosition, rect: Rectangle, thickness: Int): Rectangle { return when (position) { JBTabsPosition.bottom -> Rectangle(rect.x, rect.y, rect.width, thickness) JBTabsPosition.left -> { if (ExperimentalUI.isNewUI()) { Rectangle(rect.x, rect.y, thickness, rect.height) } else Rectangle(rect.x + rect.width - thickness, rect.y, thickness, rect.height) } JBTabsPosition.right -> Rectangle(rect.x, rect.y, thickness, rect.height) else -> super.underlineRectangle(position, rect, thickness) } } }
apache-2.0
ad862f1d8e2c5232dc123d6e42b44b6f
40.686275
140
0.721882
3.891941
false
false
false
false
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/BaseKotlinConverter.kt
1
36686
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.uast.kotlin import com.intellij.openapi.components.ServiceManager import com.intellij.psi.* import com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.elements.* import org.jetbrains.kotlin.asJava.findFacadeClass import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.kdoc.psi.impl.KDocLink import org.jetbrains.kotlin.kdoc.psi.impl.KDocName import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.utils.addToStdlib.safeAs import org.jetbrains.uast.* import org.jetbrains.uast.expressions.UInjectionHost import org.jetbrains.uast.internal.UElementAlternative import org.jetbrains.uast.internal.accommodate import org.jetbrains.uast.internal.alternative import org.jetbrains.uast.kotlin.psi.* @ApiStatus.Internal interface BaseKotlinConverter { val languagePlugin: UastLanguagePlugin fun unwrapElements(element: PsiElement?): PsiElement? = when (element) { is KtValueArgumentList -> unwrapElements(element.parent) is KtValueArgument -> unwrapElements(element.parent) is KtDeclarationModifierList -> unwrapElements(element.parent) is KtContainerNode -> unwrapElements(element.parent) is KtSimpleNameStringTemplateEntry -> unwrapElements(element.parent) is PsiParameterList -> unwrapElements(element.parent) is KtTypeArgumentList -> unwrapElements(element.parent) is KtTypeProjection -> unwrapElements(element.parent) is KtTypeElement -> unwrapElements(element.parent) is KtSuperTypeList -> unwrapElements(element.parent) is KtFinallySection -> unwrapElements(element.parent) is KtAnnotatedExpression -> unwrapElements(element.parent) is KtWhenConditionWithExpression -> unwrapElements(element.parent) is KDocLink -> unwrapElements(element.parent) is KDocSection -> unwrapElements(element.parent) is KDocTag -> unwrapElements(element.parent) else -> element } fun convertAnnotation( annotationEntry: KtAnnotationEntry, givenParent: UElement? ): UAnnotation { return KotlinUAnnotation(annotationEntry, givenParent) } fun convertDeclaration( element: PsiElement, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): UElement? { fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? = { @Suppress("UNCHECKED_CAST") ctor(element as P, givenParent) } fun <P : PsiElement, K : KtElement> buildKt(ktElement: K, ctor: (P, K, UElement?) -> UElement): () -> UElement? = { @Suppress("UNCHECKED_CAST") ctor(element as P, ktElement, givenParent) } fun <P : PsiElement, K : KtElement> buildKtOpt(ktElement: K?, ctor: (P, K?, UElement?) -> UElement): () -> UElement? = { @Suppress("UNCHECKED_CAST") ctor(element as P, ktElement, givenParent) } fun Array<out Class<out UElement>>.convertToUField(original: PsiField, kotlinOrigin: KtElement?): UElement? = if (original is PsiEnumConstant) el<UEnumConstant>(buildKtOpt(kotlinOrigin, ::KotlinUEnumConstant)) else el<UField>(buildKtOpt(kotlinOrigin, ::KotlinUField)) return with(requiredTypes) { when (element) { is KtLightMethod -> { el<UMethod>(build(KotlinUMethod::create)) } is UastFakeLightMethod -> { el<UMethod> { val ktFunction = element.original if (ktFunction.isLocal) convertDeclaration(ktFunction, givenParent, requiredTypes) else KotlinUMethodWithFakeLightDelegate(ktFunction, element, givenParent) } } is UastFakeLightPrimaryConstructor -> { convertFakeLightConstructorAlternatives(element, givenParent, requiredTypes).firstOrNull() } is KtLightClass -> { when (element.kotlinOrigin) { is KtEnumEntry -> el<UEnumConstant> { convertEnumEntry(element.kotlinOrigin as KtEnumEntry, givenParent) } else -> el<UClass> { KotlinUClass.create(element, givenParent) } } } is KtLightField -> { convertToUField(element, element.kotlinOrigin) } is KtLightFieldForSourceDeclarationSupport -> { // KtLightFieldForDecompiledDeclaration is not a KtLightField convertToUField(element, element.kotlinOrigin) } is KtLightParameter -> { el<UParameter>(buildKtOpt(element.kotlinOrigin, ::KotlinUParameter)) } is UastKotlinPsiParameter -> { el<UParameter>(buildKt(element.ktParameter, ::KotlinUParameter)) } is UastKotlinPsiParameterBase<*> -> { el<UParameter> { element.ktOrigin.safeAs<KtTypeReference>()?.let { convertReceiverParameter(it) } } } is UastKotlinPsiVariable -> { el<ULocalVariable>(buildKt(element.ktElement, ::KotlinULocalVariable)) } is KtEnumEntry -> { el<UEnumConstant> { convertEnumEntry(element, givenParent) } } is KtClassOrObject -> { convertClassOrObject(element, givenParent, this).firstOrNull() } is KtFunction -> { if (element.isLocal) { el<ULambdaExpression> { val parent = element.parent if (parent is KtLambdaExpression) { KotlinULambdaExpression(parent, givenParent) // your parent is the ULambdaExpression } else if (element.name.isNullOrEmpty()) { createLocalFunctionLambdaExpression(element, givenParent) } else { val uDeclarationsExpression = createLocalFunctionDeclaration(element, givenParent) val localFunctionVar = uDeclarationsExpression.declarations.single() as KotlinLocalFunctionUVariable localFunctionVar.uastInitializer } } } else { el<UMethod> { val lightMethod = LightClassUtil.getLightClassMethod(element) if (lightMethod != null) convertDeclaration(lightMethod, givenParent, requiredTypes) else { val ktLightClass = getLightClassForFakeMethod(element) ?: return null KotlinUMethodWithFakeLightDelegate(element, ktLightClass, givenParent) } } } } is KtPropertyAccessor -> { el<UMethod> { val lightMethod = LightClassUtil.getLightClassAccessorMethod(element) ?: return null convertDeclaration(lightMethod, givenParent, requiredTypes) } } is KtProperty -> { if (element.isLocal) { convertPsiElement(element, givenParent, requiredTypes) } else { convertNonLocalProperty(element, givenParent, requiredTypes).firstOrNull() } } is KtParameter -> { convertParameter(element, givenParent, this).firstOrNull() } is KtFile -> { convertKtFile(element, givenParent, this).firstOrNull() } is FakeFileForLightClass -> { el<UFile> { KotlinUFile(element.navigationElement, languagePlugin) } } is KtAnnotationEntry -> { el<UAnnotation>(build(::convertAnnotation)) } is KtCallExpression -> { if (requiredTypes.isAssignableFrom(KotlinUNestedAnnotation::class.java) && !requiredTypes.isAssignableFrom(UCallExpression::class.java) ) { el<UAnnotation> { KotlinUNestedAnnotation.create(element, givenParent) } } else null } is KtLightElementBase -> { element.kotlinOrigin?.let { convertDeclarationOrElement(it, givenParent, requiredTypes) } } is KtDelegatedSuperTypeEntry -> { el<KotlinSupertypeDelegationUExpression> { KotlinSupertypeDelegationUExpression(element, givenParent) } } else -> null } } } fun convertDeclarationOrElement( element: PsiElement, givenParent: UElement?, expectedTypes: Array<out Class<out UElement>> ): UElement? { return if (element is UElement) element else convertDeclaration(element, givenParent, expectedTypes) ?: convertPsiElement(element, givenParent, expectedTypes) } fun convertKtFile( element: KtFile, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): Sequence<UElement> { return requiredTypes.accommodate( // File alternative { KotlinUFile(element, languagePlugin) }, // Facade alternative { element.findFacadeClass()?.let { KotlinUClass.create(it, givenParent) } } ) } fun convertClassOrObject( element: KtClassOrObject, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): Sequence<UElement> { val ktLightClass = element.toLightClass() ?: return emptySequence() val uClass = KotlinUClass.create(ktLightClass, givenParent) return requiredTypes.accommodate( // Class alternative { uClass }, // Object alternative primaryConstructor@{ val primaryConstructor = element.primaryConstructor ?: return@primaryConstructor null uClass.methods.asSequence() .filter { it.sourcePsi == primaryConstructor } .firstOrNull() } ) } fun convertFakeLightConstructorAlternatives( original: UastFakeLightPrimaryConstructor, givenParent: UElement?, expectedTypes: Array<out Class<out UElement>> ): Sequence<UElement> { return expectedTypes.accommodate( alternative { convertDeclaration(original.original, givenParent, expectedTypes) as? UClass }, alternative { KotlinConstructorUMethod(original.original, original, original.original, givenParent) } ) } private fun getLightClassForFakeMethod(original: KtFunction): KtLightClass? { if (original.isLocal) return null return getContainingLightClass(original) } private fun convertToPropertyAlternatives( methods: LightClassUtil.PropertyAccessorsPsiMethods?, givenParent: UElement? ): Array<UElementAlternative<*>> { return if (methods != null) arrayOf( alternative { methods.backingField?.let { KotlinUField(it, getKotlinMemberOrigin(it), givenParent) } }, alternative { methods.getter?.let { convertDeclaration(it, givenParent, arrayOf(UMethod::class.java)) as? UMethod } }, alternative { methods.setter?.let { convertDeclaration(it, givenParent, arrayOf(UMethod::class.java)) as? UMethod } } ) else emptyArray() } fun convertNonLocalProperty( property: KtProperty, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): Sequence<UElement> { return requiredTypes.accommodate( *convertToPropertyAlternatives(LightClassUtil.getLightClassPropertyMethods(property).withInterfaceFallBack(property), givenParent) ) } // a workaround for KT-54679 private fun LightClassUtil.PropertyAccessorsPsiMethods.withInterfaceFallBack(property: KtProperty): LightClassUtil.PropertyAccessorsPsiMethods { if (backingField != null) return this val psiField = property.containingClassOrObject?.toLightClass()?.fields?.find { it is KtLightField && it.kotlinOrigin === property } ?: return this return LightClassUtil.PropertyAccessorsPsiMethods(getter, setter, psiField, emptyList()) } fun convertJvmStaticMethod( function: KtFunction, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): Sequence<UElement> { val functions = LightClassUtil.getLightClassMethods(function) return requiredTypes.accommodate( *functions.map { alternative { convertDeclaration(it, null, arrayOf(UMethod::class.java)) as? UMethod } }.toTypedArray() ) } fun convertParameter( element: KtParameter, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): Sequence<UElement> = requiredTypes.accommodate( alternative uParam@{ when (val ownerFunction = element.ownerFunction) { is KtFunction -> LightClassUtil.getLightClassMethod(ownerFunction) ?: getLightClassForFakeMethod(ownerFunction) ?.takeIf { !it.isAnnotationType } ?.let { UastFakeLightMethod(ownerFunction, it) } is KtPropertyAccessor -> LightClassUtil.getLightClassAccessorMethod(ownerFunction) else -> null }?.let { lightMethod -> val lightParameter = lightMethod.parameterList.parameters.find { it.name == element.name } ?: return@uParam null KotlinUParameter(lightParameter, element, givenParent) } ?: // Of course, it is a hack to pick-up KotlinUParameter from another declaration // instead of creating it directly with `givenParent`, but anyway better than have unexpected nulls here element.parent.parent.safeAs<KtCallableDeclaration>() ?.toUElementOfType<ULambdaExpression>()?.valueParameters ?.find { it.name == element.name } }, alternative catch@{ val uCatchClause = element.parent?.parent?.safeAs<KtCatchClause>()?.toUElementOfType<UCatchClause>() ?: return@catch null uCatchClause.parameters.firstOrNull { it.sourcePsi == element } }, *convertToPropertyAlternatives(LightClassUtil.getLightClassPropertyMethods(element), givenParent) ) private fun convertEnumEntry(original: KtEnumEntry, givenParent: UElement?): UElement? { return LightClassUtil.getLightClassBackingField(original)?.let { psiField -> if (psiField is KtLightField && psiField is PsiEnumConstant) { KotlinUEnumConstant(psiField, psiField.kotlinOrigin, givenParent) } else { null } } } private fun convertReceiverParameter(receiver: KtTypeReference): UParameter? { val call = (receiver.parent as? KtCallableDeclaration) ?: return null if (call.receiverTypeReference != receiver) return null return call.toUElementOfType<UMethod>()?.uastParameters?.firstOrNull() } fun forceUInjectionHost(): Boolean fun convertExpression( expression: KtExpression, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): UExpression? { fun <P : PsiElement> build(ctor: (P, UElement?) -> UExpression): () -> UExpression? { return { @Suppress("UNCHECKED_CAST") ctor(expression as P, givenParent) } } return with(requiredTypes) { when (expression) { is KtVariableDeclaration -> expr<UDeclarationsExpression>(build(::convertVariablesDeclaration)) is KtDestructuringDeclaration -> expr<UDeclarationsExpression> { val declarationsExpression = KotlinUDestructuringDeclarationExpression(givenParent, expression) declarationsExpression.apply { val tempAssignment = KotlinULocalVariable( UastKotlinPsiVariable.create(expression, declarationsExpression), expression, declarationsExpression ) val destructuringAssignments = expression.entries.mapIndexed { i, entry -> val psiFactory = KtPsiFactory(expression.project) val initializer = psiFactory.createAnalyzableExpression( "${tempAssignment.name}.component${i + 1}()", expression.containingFile ) initializer.destructuringDeclarationInitializer = true KotlinULocalVariable( UastKotlinPsiVariable.create(entry, tempAssignment.javaPsi, declarationsExpression, initializer), entry, declarationsExpression ) } declarations = listOf(tempAssignment) + destructuringAssignments } } is KtStringTemplateExpression -> { when { forceUInjectionHost() || requiredTypes.contains(UInjectionHost::class.java) -> { expr<UInjectionHost> { KotlinStringTemplateUPolyadicExpression(expression, givenParent) } } expression.entries.isEmpty() -> { expr<ULiteralExpression> { KotlinStringULiteralExpression(expression, givenParent, "") } } expression.entries.size == 1 -> { convertStringTemplateEntry(expression.entries[0], givenParent, requiredTypes) } else -> { expr<KotlinStringTemplateUPolyadicExpression> { KotlinStringTemplateUPolyadicExpression(expression, givenParent) } } } } is KtCollectionLiteralExpression -> expr<UCallExpression>(build(::KotlinUCollectionLiteralExpression)) is KtConstantExpression -> expr<ULiteralExpression>(build(::KotlinULiteralExpression)) is KtLabeledExpression -> expr<ULabeledExpression>(build(::KotlinULabeledExpression)) is KtParenthesizedExpression -> expr<UParenthesizedExpression>(build(::KotlinUParenthesizedExpression)) is KtBlockExpression -> expr<UBlockExpression> { if (expression.parent is KtFunctionLiteral && expression.parent.parent is KtLambdaExpression && givenParent !is KotlinULambdaExpression ) { KotlinULambdaExpression(expression.parent.parent as KtLambdaExpression, givenParent).body } else KotlinUBlockExpression(expression, givenParent) } is KtReturnExpression -> expr<UReturnExpression>(build(::KotlinUReturnExpression)) is KtThrowExpression -> expr<UThrowExpression>(build(::KotlinUThrowExpression)) is KtTryExpression -> expr<UTryExpression>(build(::KotlinUTryExpression)) is KtBreakExpression -> expr<UBreakExpression>(build(::KotlinUBreakExpression)) is KtContinueExpression -> expr<UContinueExpression>(build(::KotlinUContinueExpression)) is KtDoWhileExpression -> expr<UDoWhileExpression>(build(::KotlinUDoWhileExpression)) is KtWhileExpression -> expr<UWhileExpression>(build(::KotlinUWhileExpression)) is KtForExpression -> expr<UForEachExpression>(build(::KotlinUForEachExpression)) is KtWhenExpression -> expr<USwitchExpression>(build(::KotlinUSwitchExpression)) is KtIfExpression -> expr<UIfExpression>(build(::KotlinUIfExpression)) is KtBinaryExpressionWithTypeRHS -> expr<UBinaryExpressionWithType>(build(::KotlinUBinaryExpressionWithType)) is KtIsExpression -> expr<UBinaryExpressionWithType>(build(::KotlinUTypeCheckExpression)) is KtArrayAccessExpression -> expr<UArrayAccessExpression>(build(::KotlinUArrayAccessExpression)) is KtThisExpression -> expr<UThisExpression>(build(::KotlinUThisExpression)) is KtSuperExpression -> expr<USuperExpression>(build(::KotlinUSuperExpression)) is KtCallableReferenceExpression -> expr<UCallableReferenceExpression>(build(::KotlinUCallableReferenceExpression)) is KtClassLiteralExpression -> expr<UClassLiteralExpression>(build(::KotlinUClassLiteralExpression)) is KtObjectLiteralExpression -> expr<UObjectLiteralExpression>(build(::KotlinUObjectLiteralExpression)) is KtDotQualifiedExpression -> expr<UQualifiedReferenceExpression>(build(::KotlinUQualifiedReferenceExpression)) is KtSafeQualifiedExpression -> expr<UQualifiedReferenceExpression>(build(::KotlinUSafeQualifiedExpression)) is KtSimpleNameExpression -> expr<USimpleNameReferenceExpression>(build(::KotlinUSimpleReferenceExpression)) is KtCallExpression -> expr<UCallExpression>(build(::KotlinUFunctionCallExpression)) is KtBinaryExpression -> { if (expression.operationToken == KtTokens.ELVIS) { expr<UExpressionList>(build(::createElvisExpression)) } else { expr<UBinaryExpression>(build(::KotlinUBinaryExpression)) } } is KtPrefixExpression -> expr<UPrefixExpression>(build(::KotlinUPrefixExpression)) is KtPostfixExpression -> expr<UPostfixExpression>(build(::KotlinUPostfixExpression)) is KtClassOrObject -> expr<UDeclarationsExpression> { expression.toLightClass()?.let { lightClass -> KotlinUDeclarationsExpression(givenParent).apply { declarations = listOf(KotlinUClass.create(lightClass, this)) } } ?: UastEmptyExpression(givenParent) } is KtLambdaExpression -> expr<ULambdaExpression>(build(::KotlinULambdaExpression)) is KtFunction -> { if (expression.name.isNullOrEmpty()) { expr<ULambdaExpression>(build(::createLocalFunctionLambdaExpression)) } else { expr<UDeclarationsExpression>(build(::createLocalFunctionDeclaration)) } } is KtAnnotatedExpression -> { expression.baseExpression ?.let { convertExpression(it, givenParent, requiredTypes) } ?: expr<UExpression>(build(::UnknownKotlinExpression)) } else -> expr<UExpression>(build(::UnknownKotlinExpression)) } } } fun convertStringTemplateEntry( entry: KtStringTemplateEntry, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): UExpression? { return with(requiredTypes) { if (entry is KtStringTemplateEntryWithExpression) { expr<UExpression> { convertOrEmpty(entry.expression, givenParent) } } else { expr<ULiteralExpression> { if (entry is KtEscapeStringTemplateEntry) KotlinStringULiteralExpression(entry, givenParent, entry.unescapedValue) else KotlinStringULiteralExpression(entry, givenParent) } } } } fun convertVariablesDeclaration( psi: KtVariableDeclaration, parent: UElement? ): UDeclarationsExpression { val declarationsExpression = parent as? KotlinUDeclarationsExpression ?: psi.parent.toUElementOfType<UDeclarationsExpression>() as? KotlinUDeclarationsExpression ?: KotlinUDeclarationsExpression( null, parent, psi ) val parentPsiElement = parent?.javaPsi //TODO: looks weird. mb look for the first non-null `javaPsi` in `parents` ? val variable = KotlinUAnnotatedLocalVariable( UastKotlinPsiVariable.create(psi, parentPsiElement, declarationsExpression), psi, declarationsExpression ) { annotationParent -> psi.annotationEntries.map { convertAnnotation(it, annotationParent) } } return declarationsExpression.apply { declarations = listOf(variable) } } fun convertWhenCondition( condition: KtWhenCondition, givenParent: UElement?, requiredType: Array<out Class<out UElement>> ): UExpression? { return with(requiredType) { when (condition) { is KtWhenConditionInRange -> expr<UBinaryExpression> { KotlinCustomUBinaryExpression(condition, givenParent).apply { leftOperand = KotlinStringUSimpleReferenceExpression("it", this) operator = when { condition.isNegated -> KotlinBinaryOperators.NOT_IN else -> KotlinBinaryOperators.IN } rightOperand = convertOrEmpty(condition.rangeExpression, this) } } is KtWhenConditionIsPattern -> expr<UBinaryExpression> { KotlinCustomUBinaryExpressionWithType(condition, givenParent).apply { operand = KotlinStringUSimpleReferenceExpression("it", this) operationKind = when { condition.isNegated -> KotlinBinaryExpressionWithTypeKinds.NEGATED_INSTANCE_CHECK else -> UastBinaryExpressionWithTypeKind.InstanceCheck.INSTANCE } typeReference = condition.typeReference?.let { val service = ServiceManager.getService(BaseKotlinUastResolveProviderService::class.java) KotlinUTypeReferenceExpression(it, this) { service.resolveToType(it, this, boxed = true) ?: UastErrorType } } } } is KtWhenConditionWithExpression -> condition.expression?.let { convertExpression(it, givenParent, requiredType) } else -> expr<UExpression> { UastEmptyExpression(givenParent) } } } } fun convertPsiElement( element: PsiElement?, givenParent: UElement?, requiredTypes: Array<out Class<out UElement>> ): UElement? { if (element == null) return null fun <P : PsiElement> build(ctor: (P, UElement?) -> UElement): () -> UElement? = { @Suppress("UNCHECKED_CAST") ctor(element as P, givenParent) } return with(requiredTypes) { when (element) { is KtParameterList -> { el<UDeclarationsExpression> { val declarationsExpression = KotlinUDeclarationsExpression(element, givenParent, null) declarationsExpression.apply { declarations = element.parameters.mapIndexed { i, p -> KotlinUParameter(UastKotlinPsiParameter.create(p, element, declarationsExpression, i), p, this) } } } } is KtClassBody -> { el<UExpressionList>(build(KotlinUExpressionList.Companion::createClassBody)) } is KtCatchClause -> { el<UCatchClause>(build(::KotlinUCatchClause)) } is KtVariableDeclaration -> { if (element is KtProperty && !element.isLocal) { convertNonLocalProperty(element, givenParent, this).firstOrNull() } else { el<UVariable> { convertVariablesDeclaration(element, givenParent).declarations.singleOrNull() } ?: expr<UDeclarationsExpression> { convertExpression(element, givenParent, requiredTypes) } } } is KtExpression -> { convertExpression(element, givenParent, requiredTypes) } is KtLambdaArgument -> { element.getLambdaExpression()?.let { convertExpression(it, givenParent, requiredTypes) } } is KtLightElementBase -> { when (val expression = element.kotlinOrigin) { is KtExpression -> convertExpression(expression, givenParent, requiredTypes) else -> el<UExpression> { UastEmptyExpression(givenParent) } } } is KtLiteralStringTemplateEntry, is KtEscapeStringTemplateEntry -> { el<ULiteralExpression>(build(::KotlinStringULiteralExpression)) } is KtStringTemplateEntry -> { element.expression?.let { convertExpression(it, givenParent, requiredTypes) } ?: expr<UExpression> { UastEmptyExpression(givenParent) } } is KtWhenEntry -> { el<USwitchClauseExpressionWithBody>(build(::KotlinUSwitchEntry)) } is KtWhenCondition -> { convertWhenCondition(element, givenParent, requiredTypes) } is KtTypeReference -> { requiredTypes.accommodate( alternative { KotlinUTypeReferenceExpression(element, givenParent) }, alternative { convertReceiverParameter(element) } ).firstOrNull() } is KtConstructorDelegationCall -> { el<UCallExpression> { KotlinUFunctionCallExpression(element, givenParent) } } is KtSuperTypeCallEntry -> { val objectLiteralExpression = element.parent.parent.parent.safeAs<KtObjectLiteralExpression>() if (objectLiteralExpression != null) el<UObjectLiteralExpression> { KotlinUObjectLiteralExpression(objectLiteralExpression, givenParent) } else el<UCallExpression> { KotlinUFunctionCallExpression(element, givenParent) } } is KtImportDirective -> { el<UImportStatement>(build(::KotlinUImportStatement)) } is PsiComment -> { el<UComment>(build(::UComment)) } is KDocName -> { if (element.getQualifier() == null) el<USimpleNameReferenceExpression> { element.lastChild?.let { psiIdentifier -> KotlinStringUSimpleReferenceExpression(psiIdentifier.text, givenParent, element, element) } } else el<UQualifiedReferenceExpression>(build(::KotlinDocUQualifiedReferenceExpression)) } is LeafPsiElement -> { when { element.elementType in identifiersTokens -> { if (element.elementType != KtTokens.OBJECT_KEYWORD || element.getParentOfType<KtObjectDeclaration>(false)?.nameIdentifier == null ) el<UIdentifier>(build(::KotlinUIdentifier)) else null } element.elementType in KtTokens.OPERATIONS && element.parent is KtOperationReferenceExpression -> { el<UIdentifier>(build(::KotlinUIdentifier)) } element.elementType == KtTokens.LBRACKET && element.parent is KtCollectionLiteralExpression -> { el<UIdentifier> { UIdentifier( element, KotlinUCollectionLiteralExpression(element.parent as KtCollectionLiteralExpression, null) ) } } else -> null } } else -> null } } } fun createVarargsHolder( arguments: Collection<ValueArgument>, parent: UElement?, ): UExpressionList = KotlinUExpressionList(null, UastSpecialExpressionKind.VARARGS, parent).apply { expressions = arguments.map { convertOrEmpty(it.getArgumentExpression(), parent) } } fun convertOrEmpty(expression: KtExpression?, parent: UElement?): UExpression { return expression?.let { convertExpression(it, parent, DEFAULT_EXPRESSION_TYPES_LIST) } ?: UastEmptyExpression(parent) } fun convertOrNull(expression: KtExpression?, parent: UElement?): UExpression? { return if (expression != null) convertExpression(expression, parent, DEFAULT_EXPRESSION_TYPES_LIST) else null } fun KtPsiFactory.createAnalyzableExpression(text: String, context: PsiElement): KtExpression = createAnalyzableProperty("val x = $text", context).initializer ?: error("Failed to create expression from text: '$text'") fun KtPsiFactory.createAnalyzableProperty(text: String, context: PsiElement): KtProperty = createAnalyzableDeclaration(text, context) fun <TDeclaration : KtDeclaration> KtPsiFactory.createAnalyzableDeclaration(text: String, context: PsiElement): TDeclaration { val file = createAnalyzableFile("dummy.kt", text, context) val declarations = file.declarations assert(declarations.size == 1) { "${declarations.size} declarations in $text" } @Suppress("UNCHECKED_CAST") return declarations.first() as TDeclaration } }
apache-2.0
41a75e0df443ef5b043bf3b81595750f
45.320707
148
0.576242
6.694526
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/ui/actions/styling/MarkdownCreateLinkAction.kt
5
8602
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.ui.actions.styling import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.ex.ClipboardUtil import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.elementType import com.intellij.psi.util.elementsAtOffsetUp import com.intellij.refactoring.suggested.endOffset import com.intellij.refactoring.suggested.startOffset import com.intellij.util.LocalFileUrl import com.intellij.util.Urls import com.intellij.util.io.exists import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.lang.MarkdownElementTypes import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile import org.intellij.plugins.markdown.lang.psi.util.hasType import org.intellij.plugins.markdown.ui.actions.MarkdownActionPlaces import org.intellij.plugins.markdown.ui.actions.MarkdownActionUtil import org.jetbrains.annotations.Nls import java.nio.file.InvalidPathException import java.nio.file.Path internal class MarkdownCreateLinkAction : ToggleAction(), DumbAware { private val wrapActionBaseName: String get() = MarkdownBundle.message("action.Markdown.Styling.CreateLink.text") private val unwrapActionName: String get() = MarkdownBundle.message("action.Markdown.Styling.CreateLink.unwrap.text") private fun obtainWrapActionName(place: String): @Nls String { return when (place) { MarkdownActionPlaces.INSERT_POPUP -> MarkdownBundle.message("action.Markdown.Styling.CreateLink.insert.popup.text") else -> wrapActionBaseName } } override fun isSelected(event: AnActionEvent): Boolean { val editor = MarkdownActionUtil.findMarkdownEditor(event) val file = event.getData(CommonDataKeys.PSI_FILE) if (editor == null || file !is MarkdownFile) { event.presentation.isEnabledAndVisible = false return false } event.presentation.isEnabledAndVisible = true val caretSnapshots = SelectionUtil.obtainCaretSnapshots(this, event) val caretsWithLinksCount = caretSnapshots?.count { it.obtainSelectedLinkElement(file) != null } ?: 0 return when { caretsWithLinksCount == 0 || event.place == ActionPlaces.EDITOR_POPUP -> { event.presentation.isEnabled = !editor.isViewer event.presentation.text = obtainWrapActionName(event.place) event.presentation.description = MarkdownBundle.message( "action.Markdown.Styling.CreateLink.description") false } caretsWithLinksCount == editor.caretModel.caretCount -> { event.presentation.isEnabled = !editor.isViewer event.presentation.text = unwrapActionName event.presentation.description = MarkdownBundle.message( "action.Markdown.Styling.CreateLink.unwrap.description") true } else -> { // some carets are located at links, others are not event.presentation.isEnabled = false false } } } override fun setSelected(event: AnActionEvent, state: Boolean) { val editor = MarkdownActionUtil.findRequiredMarkdownEditor(event) val file = event.getRequiredData(CommonDataKeys.PSI_FILE) if (state) { for (caret in editor.caretModel.allCarets) { wrapSelectionWithLink(caret, editor, file.project) } } else { editor.caretModel.allCarets .sortedBy { -it.offset } .map { caret -> caret to caret.getSelectedLinkElement(file) } .distinctBy { (_, element) -> element } .forEach { (caret, element) -> assert(element != null) if (element == null) return@forEach unwrapLink(element, caret, editor, file.project) } } } override fun update(event: AnActionEvent) { val originalIcon = event.presentation.icon super.update(event) if (ActionPlaces.isPopupPlace(event.place)) { // Restore original icon, as it will be disabled in popups, and we still want to show in GeneratePopup event.presentation.icon = originalIcon } } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } private fun wrapSelectionWithLink(caret: Caret, editor: Editor, project: Project) { val selected = caret.selectedText ?: "" val selectionStart = caret.selectionStart val selectionEnd = caret.selectionEnd val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) val fileArray = file?.let { arrayOf(it) } ?: emptyArray() WriteCommandAction.writeCommandAction(project, *fileArray) .withName(wrapActionBaseName) .run<Nothing> { caret.removeSelection() editor.document.replaceString(selectionStart, selectionEnd, "[$selected]()") caret.moveToOffset(selectionEnd + 3) getLinkDestinationInClipboard(editor)?.let { linkDestination -> val linkStartOffset = caret.offset editor.document.insertString(linkStartOffset, linkDestination) caret.setSelection(linkStartOffset, linkStartOffset + linkDestination.length) } } } private fun getLinkDestinationInClipboard(editor: Editor): String? = ClipboardUtil.getTextInClipboard()?.takeIf { path -> when (Urls.parse(path, asLocalIfNoScheme = true)) { null -> false is LocalFileUrl -> { val relativePath = try { Path.of(path) } catch (e: InvalidPathException) { return@takeIf false } val dir = FileDocumentManager.getInstance().getFile(editor.document)?.parent val absolutePath = dir?.let { Path.of(it.path) }?.resolve(relativePath) absolutePath?.exists() ?: false } else -> true } } private fun unwrapLink(linkElement: PsiElement, caret: Caret, editor: Editor, project: Project) { val linkText = linkElement.children .find { it.elementType == MarkdownElementTypes.LINK_TEXT } ?.text?.drop(1)?.dropLast(1) // unwrap [] ?: "" val start = linkElement.startOffset val newEnd = start + linkText.length // left braket is deleted, so offsets should be shifted 1 position backwards; // they should also match the constraint: start <= offset <= newEnd val selectionStart = maxOf(start, minOf(newEnd, caret.selectionStart - 1)) val selectionEnd = maxOf(start, minOf(newEnd, caret.selectionEnd - 1)) val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) val fileArray = file?.let { arrayOf(it) } ?: emptyArray() WriteCommandAction.writeCommandAction(project, *fileArray) .withName(unwrapActionName) .run<Nothing> { if (selectionStart == selectionEnd) { caret.removeSelection() // so that the floating toolbar is hidden; must be done before text replacement caret.moveCaretRelatively(-1, 0, false, false) } editor.document.replaceString(start, linkElement.endOffset, linkText) if (selectionStart != selectionEnd) caret.setSelection(selectionStart, selectionEnd) } } companion object { private fun SelectionUtil.CaretSnapshot.obtainSelectedLinkElement(file: PsiFile): PsiElement? { return obtainSelectedLinkElement(file, offset, hasSelection, selectionStart, selectionEnd) } private fun Caret.getSelectedLinkElement(file: PsiFile): PsiElement? { return obtainSelectedLinkElement(file, offset, hasSelection(), selectionStart, selectionEnd) } private fun obtainSelectedLinkElement( file: PsiFile, offset: Int, hasSelection: Boolean, selectionStart: Int, selectionEnd: Int ): PsiElement? { val elements = file.elementsAtOffsetUp(selectionStart).asSequence() val (element, _) = elements.find { (element, _) -> element.hasType(MarkdownElementTypes.INLINE_LINK) } ?: return null return element.takeIf { when { hasSelection -> selectionEnd <= element.endOffset else -> offset > element.startOffset // caret should be strictly inside } } } } }
apache-2.0
24dbcc52f2a03288ca29eda9345e0d0c
39.384977
158
0.70844
4.744622
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/containers/BidirectionalMap.kt
9
5877
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.storage.impl.containers import com.intellij.util.SmartList import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap import org.jetbrains.annotations.TestOnly import kotlin.collections.component1 import kotlin.collections.component2 /** * Most of the time this collection stores unique keys and values. Base on this information we can speed up the collection copy * by using [Object2ObjectOpenHashMap.clone] method and only if several keys contain same value we store as list at [valueToKeysMap] * field and at collection copying, we additionally clone only field which contains the list inside */ internal class BidirectionalMap<K, V> private constructor(private val slotsWithList: HashSet<V>, private val keyToValueMap: Object2ObjectOpenHashMap<K, V>, private val valueToKeysMap: Object2ObjectOpenHashMap<V, Any>) : MutableMap<K, V> { constructor() : this(HashSet<V>(), Object2ObjectOpenHashMap<K, V>(), Object2ObjectOpenHashMap<V, Any>()) @Suppress("UNCHECKED_CAST") override fun put(key: K, value: V): V? { val oldValue = keyToValueMap.put(key, value) if (oldValue != null) { if (oldValue == value) { return oldValue } val keys = valueToKeysMap[oldValue]!! if (keys is MutableList<*>) { keys.remove(key) if (keys.size == 1) { valueToKeysMap[oldValue] = keys[0] slotsWithList.remove(oldValue) } else if (keys.isEmpty()) { valueToKeysMap.remove(oldValue) slotsWithList.remove(oldValue) } } else { valueToKeysMap.remove(oldValue) } } val existingKeys = valueToKeysMap[value] if (existingKeys == null) { valueToKeysMap[value] = key return oldValue } if (existingKeys is MutableList<*>) { existingKeys as MutableList<K> existingKeys.add(key) } else { valueToKeysMap[value] = SmartList(existingKeys as K, key) slotsWithList.add(value) } return oldValue } override fun clear() { slotsWithList.clear() keyToValueMap.clear() valueToKeysMap.clear() } @Suppress("UNCHECKED_CAST") fun getKeysByValue(value: V): List<K>? { return valueToKeysMap[value]?.let { keys -> if (keys is MutableList<*>) return@let keys as MutableList<K> return@let SmartList(keys as K) } } override val keys: MutableSet<K> get() = keyToValueMap.keys override val size: Int get() = keyToValueMap.size override fun isEmpty(): Boolean { return keyToValueMap.isEmpty() } override fun containsKey(key: K): Boolean { return keyToValueMap.containsKey(key) } override fun containsValue(value: V): Boolean { return valueToKeysMap.containsKey(value) } override operator fun get(key: K): V? { return keyToValueMap[key] } @Suppress("UNCHECKED_CAST") fun removeValue(v: V) { val keys = valueToKeysMap.remove(v) if (keys != null) { if (keys is MutableList<*>) { for (k in keys) { keyToValueMap.remove(k) } slotsWithList.remove(v) } else { keyToValueMap.remove(keys as K) } } } override fun remove(key: K): V? { val value = keyToValueMap.remove(key) val keys = valueToKeysMap[value] if (keys != null) { if (keys is MutableList<*> && keys.size > 1) { keys.remove(key) if (keys.size == 1) { valueToKeysMap[value] = keys[0] slotsWithList.remove(value) } } else { if (keys is MutableList<*>) slotsWithList.remove(value) valueToKeysMap.remove(value) } } return value } override fun putAll(from: Map<out K, V>) { for ((key, value) in from) { put(key, value) } } override val values: MutableSet<V> get() = valueToKeysMap.keys override val entries: MutableSet<MutableMap.MutableEntry<K, V>> get() = keyToValueMap.entries @Suppress("UNCHECKED_CAST") fun copy(): BidirectionalMap<K, V> { val clonedValueToKeysMap = valueToKeysMap.clone() slotsWithList.forEach { value -> clonedValueToKeysMap[value] = SmartList(valueToKeysMap[value] as MutableList<K>) } return BidirectionalMap(HashSet(slotsWithList), keyToValueMap.clone(), clonedValueToKeysMap) } @TestOnly fun getSlotsWithList() = slotsWithList @TestOnly fun assertConsistency() { assert(keyToValueMap.keys == valueToKeysMap.values.map { if (it is SmartList<*>) return@map it else return@map SmartList(it) }.flatten().toSet()) { "The count of keys in one map does not equal the amount on the second map" } assert(keyToValueMap.values.toSet() == valueToKeysMap.keys) { "The count of values in one map does not equal the amount on the second map" } valueToKeysMap.forEach { (value, keys) -> if (keys is SmartList<*>) { assert(slotsWithList.contains(value)) { "Not registered value: $value with list at slotsWithList collection" } keys.forEach { assert(keyToValueMap.containsKey(it)) { "Key: $it is not registered at keyToValueMap collection" } assert(keyToValueMap[it] == value) { "Value by key: $it is different in collections. Expected: $value but actual ${keyToValueMap[it]}" } } } else { assert(keyToValueMap.containsKey(keys)) { "Key: $keys is not registered at keyToValueMap collection" } assert(keyToValueMap[keys] == value) { "Value by key: $keys is different in collections. Expected: $value but actual ${keyToValueMap[keys]}" } } } } override fun toString(): String { return keyToValueMap.toString() } }
apache-2.0
de1cfcf7b7d0d06c8b6fd912c00efbd6
33.174419
150
0.653905
4.36627
false
false
false
false
jwren/intellij-community
platform/platform-api/src/com/intellij/ide/browsers/BrowserLauncherAppless.kt
1
9724
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.browsers import com.intellij.CommonBundle import com.intellij.Patches import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.CapturingProcessHandler import com.intellij.execution.process.ProcessIOExecutorService import com.intellij.execution.util.ExecUtil import com.intellij.ide.BrowserUtil import com.intellij.ide.GeneralSettings import com.intellij.ide.IdeBundle import com.intellij.model.SideEffectGuard import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VfsUtil import com.intellij.util.PathUtil import com.intellij.util.io.URLUtil import com.intellij.util.ui.GraphicsUtil import java.awt.Desktop import java.awt.GraphicsEnvironment import java.io.File import java.io.IOException import java.net.URI import java.nio.file.Path private val LOG = logger<BrowserLauncherAppless>() open class BrowserLauncherAppless : BrowserLauncher() { companion object { @JvmStatic fun canUseSystemDefaultBrowserPolicy(): Boolean = isDesktopActionSupported(Desktop.Action.BROWSE) || SystemInfo.isMac || SystemInfo.isWindows || SystemInfo.isUnix && SystemInfo.hasXdgOpen() fun isOpenCommandUsed(command: GeneralCommandLine): Boolean = SystemInfo.isMac && ExecUtil.openCommandPath == command.exePath } override fun open(url: String): Unit = openOrBrowse(url, false) override fun browse(file: File) { var path = file.absolutePath if (SystemInfo.isWindows && path[0] != '/') { path = "/$path" } openOrBrowse("${StandardFileSystems.FILE_PROTOCOL_PREFIX}$path", true) } override fun browse(file: Path) { var path = file.toAbsolutePath().toString() if (SystemInfo.isWindows && path[0] != '/') { path = "/$path" } openOrBrowse("${StandardFileSystems.FILE_PROTOCOL_PREFIX}$path", true) } protected open fun openWithExplicitBrowser(url: String, browserPath: String?, project: Project?) { browseUsingPath(url, browserPath, project = project) } protected open fun openOrBrowse(_url: String, browse: Boolean, project: Project? = null) { SideEffectGuard.checkSideEffectAllowed(SideEffectGuard.EffectType.EXEC) val url = signUrl(_url.trim { it <= ' ' }) LOG.debug { "opening [$url]" } if (url.startsWith("mailto:") && isDesktopActionSupported(Desktop.Action.MAIL)) { try { LOG.debug("Trying Desktop#mail") Desktop.getDesktop().mail(URI(url)) } catch (e: Exception) { LOG.warn("[$url]", e) } return } if (!BrowserUtil.isAbsoluteURL(url)) { val file = File(url) if (!browse && isDesktopActionSupported(Desktop.Action.OPEN)) { if (!file.exists()) { showError(IdeBundle.message("error.file.does.not.exist", file.path), project = project) return } try { LOG.debug("Trying Desktop#open") Desktop.getDesktop().open(file) return } catch (e: IOException) { LOG.warn("[$url]", e) } } browse(file) return } val settings = generalSettings if (settings.isUseDefaultBrowser) { openWithDefaultBrowser(url, project) } else { openWithExplicitBrowser(url, settings.browserPath, project = project) } } private fun openWithDefaultBrowser(url: String, project: Project?) { if (desktopBrowse(project, url)) { return } systemOpen(project, url) } private fun desktopBrowse(project: Project?, url: String): Boolean { if (isDesktopActionSupported(Desktop.Action.BROWSE)) { val uri = VfsUtil.toUri(url) if (uri == null) { showError(IdeBundle.message("error.malformed.url", url), project = project) return true } return desktopBrowse(project, uri) } return false } protected open fun desktopBrowse(project: Project?, uri: URI): Boolean { try { LOG.debug("Trying Desktop#browse") Desktop.getDesktop().browse(uri) return true } catch (e: Exception) { LOG.warn("[$uri]", e) // if "No application knows how to open" the URL, there is no sense in retrying with 'open' command return SystemInfo.isMac && e.message!!.contains("Error code: -10814") } } private fun systemOpen(project: Project?, url: String) { val command = defaultBrowserCommand if (command == null) { showError(IdeBundle.message("browser.default.not.supported"), project = project) return } if (url.startsWith("jar:")) return doLaunch(GeneralCommandLine(command).withParameters(url), project) } protected open fun signUrl(url: String): String = url override fun browse(url: String, browser: WebBrowser?, project: Project?) { SideEffectGuard.checkSideEffectAllowed(SideEffectGuard.EffectType.EXEC) val effectiveBrowser = getEffectiveBrowser(browser) // if browser is not passed, UrlOpener should be not used for non-http(s) urls if (effectiveBrowser == null || (browser == null && !url.startsWith(URLUtil.HTTP_PROTOCOL))) { openOrBrowse(url, true, project) } else { UrlOpener.EP_NAME.extensions.any { it.openUrl(effectiveBrowser, signUrl(url), project) } } } override fun browseUsingPath(url: String?, browserPath: String?, browser: WebBrowser?, project: Project?, openInNewWindow: Boolean, additionalParameters: Array<String>): Boolean { SideEffectGuard.checkSideEffectAllowed(SideEffectGuard.EffectType.EXEC) if (url != null && url.startsWith("jar:")) return false val byName = browserPath == null && browser != null val effectivePath = if (byName) PathUtil.toSystemDependentName(browser!!.path) else browserPath val fix: (() -> Unit)? = if (byName) { -> browseUsingPath(url, null, browser!!, project, openInNewWindow, additionalParameters) } else null if (effectivePath.isNullOrBlank()) { val message = browser?.browserNotFoundMessage ?: IdeBundle.message("error.please.specify.path.to.web.browser", CommonBundle.settingsActionPath()) showError(message, browser, project, IdeBundle.message("title.browser.not.found"), fix) return false } val command = BrowserUtil.getOpenBrowserCommand(effectivePath, openInNewWindow).toMutableList() val commandLine = GeneralCommandLine(command) val browserSpecificSettings = browser?.specificSettings if (browserSpecificSettings != null) { commandLine.environment.putAll(browserSpecificSettings.environmentVariables) } val isBrowserPathUsedAsCommand = command.size == 1 if (!isBrowserPathUsedAsCommand && url != null) { commandLine.addParameter(url) } val specific = browserSpecificSettings?.additionalParameters ?: emptyList() if (specific.size + additionalParameters.size > 0) { if (isOpenCommandUsed(commandLine)) { commandLine.addParameter("--args") } commandLine.addParameters(specific) commandLine.addParameters(*additionalParameters) } if (isBrowserPathUsedAsCommand && url != null) { commandLine.addParameter(url) } doLaunch(commandLine, project, browser, fix) return true } private fun doLaunch(command: GeneralCommandLine, project: Project?, browser: WebBrowser? = null, fix: (() -> Unit)? = null) { LOG.debug { command.commandLineString } ProcessIOExecutorService.INSTANCE.execute { try { val output = CapturingProcessHandler.Silent(command).runProcess(10000, false) if (!output.checkSuccess(LOG) && output.exitCode == 1) { @NlsSafe val error = output.stderrLines.firstOrNull() showError(error, browser, project, null, fix) } } catch (e: ExecutionException) { showError(e.message, browser, project, null, fix) } } } protected open fun showError(@NlsContexts.DialogMessage error: String?, browser: WebBrowser? = null, project: Project? = null, @NlsContexts.DialogTitle title: String? = null, fix: (() -> Unit)? = null) { // Not started yet. Not able to show message up. (Could happen in License panel under Linux). LOG.warn(error) } protected open fun getEffectiveBrowser(browser: WebBrowser?): WebBrowser? = browser } private fun isAffectedByDesktopBug(): Boolean = Patches.SUN_BUG_ID_6486393 && (GraphicsEnvironment.isHeadless() || !GraphicsUtil.isProjectorEnvironment()) private fun isDesktopActionSupported(action: Desktop.Action): Boolean = !isAffectedByDesktopBug() && Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(action) private val generalSettings: GeneralSettings get() = (if (ApplicationManager.getApplication() != null) GeneralSettings.getInstance() else null) ?: GeneralSettings() private val defaultBrowserCommand: List<String>? get() = when { SystemInfo.isWindows -> listOf(ExecUtil.windowsShellName, "/c", "start", GeneralCommandLine.inescapableQuote("")) SystemInfo.isMac -> listOf(ExecUtil.openCommandPath) SystemInfo.isUnix && SystemInfo.hasXdgOpen() -> listOf("xdg-open") else -> null }
apache-2.0
5973650a6463542b2df7633009b3ede0
36.544402
205
0.694056
4.541803
false
false
false
false
jwren/intellij-community
java/idea-ui/src/com/intellij/ide/starters/shared/ui/LibrariesSearchTextField.kt
6
2275
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.starters.shared.ui import com.intellij.ide.starters.JavaStartersBundle import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonShortcuts import com.intellij.ui.JBColor import com.intellij.ui.SearchTextField import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBUI import java.awt.Dimension import java.awt.event.KeyEvent import javax.swing.JComponent internal class LibrariesSearchTextField : SearchTextField() { var list: JComponent? = null init { textEditor.putClientProperty("JTextField.Search.Gap", JBUIScale.scale(6)) textEditor.putClientProperty("JTextField.Search.GapEmptyText", JBUIScale.scale(-1)) textEditor.border = JBUI.Borders.empty() textEditor.emptyText.text = JavaStartersBundle.message("hint.library.search") border = JBUI.Borders.customLine(JBColor.border(), 1, 1, 0, 1) } override fun preprocessEventForTextField(event: KeyEvent): Boolean { val keyCode: Int = event.keyCode val id: Int = event.id if ((keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_ENTER) && id == KeyEvent.KEY_PRESSED && handleListEvents(event)) { return true } return super.preprocessEventForTextField(event) } private fun handleListEvents(event: KeyEvent): Boolean { val selectionTracker = list if (selectionTracker != null) { selectionTracker.dispatchEvent(event) return true } return false } override fun getPreferredSize(): Dimension { val size = super.getPreferredSize() size.height = JBUIScale.scale(30) return size } override fun toClearTextOnEscape(): Boolean { object : AnAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabled = text.isNotEmpty() } override fun actionPerformed(e: AnActionEvent) { text = "" } init { isEnabledInModalContext = true } }.registerCustomShortcutSet(CommonShortcuts.ESCAPE, this) return false } }
apache-2.0
f41dca2870265d82deb6af9a10507db3
30.178082
158
0.724835
4.452055
false
false
false
false
jwren/intellij-community
plugins/kotlin/groovy/src/org/jetbrains/kotlin/idea/groovy/inspections/GradleKotlinxCoroutinesDeprecationInspection.kt
1
5567
// 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.groovy.inspections import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.roots.ProjectRootManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.idea.configuration.getWholeModuleGroup import org.jetbrains.kotlin.idea.extensions.gradle.SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS import org.jetbrains.kotlin.idea.inspections.ReplaceStringInDocumentFix import org.jetbrains.kotlin.idea.inspections.migration.DEPRECATED_COROUTINES_LIBRARIES_INFORMATION import org.jetbrains.kotlin.idea.inspections.migration.DeprecatedForKotlinLibInfo import org.jetbrains.kotlin.idea.migration.MigrationInfo import org.jetbrains.kotlin.idea.migration.isLanguageVersionUpdate import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.quickfix.migration.MigrationFix import org.jetbrains.kotlin.idea.versions.LibInfo import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.plugins.groovy.codeInspection.BaseInspection import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression private val LibInfo.gradleMarker get() = "$groupId:$name:" @Suppress("SpellCheckingInspection") class GradleKotlinxCoroutinesDeprecationInspection : BaseInspection(), CleanupLocalInspectionTool, MigrationFix { override fun isApplicable(migrationInfo: MigrationInfo): Boolean { return migrationInfo.isLanguageVersionUpdate(LanguageVersion.KOTLIN_1_2, LanguageVersion.KOTLIN_1_3) } override fun buildVisitor(): BaseInspectionVisitor = DependencyFinder() private open class DependencyFinder : KotlinGradleInspectionVisitor() { override fun visitClosure(closure: GrClosableBlock) { super.visitClosure(closure) val dependenciesCall = closure.getStrictParentOfType<GrMethodCall>() ?: return if (dependenciesCall.invokedExpression.text != "dependencies") return val dependencyEntries = GradleHeuristicHelper.findStatementWithPrefixes(closure, SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS) for (dependencyStatement in dependencyEntries) { for (outdatedInfo in DEPRECATED_COROUTINES_LIBRARIES_INFORMATION) { val dependencyText = dependencyStatement.text val libMarker = outdatedInfo.lib.gradleMarker if (!dependencyText.contains(libMarker)) continue if (!checkKotlinVersion(dependencyStatement.containingFile, outdatedInfo.sinceKotlinLanguageVersion)) { // Same result will be for all invocations in this file, so exit return } val libVersion = DifferentStdlibGradleVersionInspection.getRawResolvedLibVersion( dependencyStatement.containingFile, outdatedInfo.lib.groupId, listOf(outdatedInfo.lib.name) ) ?: DeprecatedGradleDependencyInspection.libraryVersionFromOrderEntry( dependencyStatement.containingFile, outdatedInfo.lib.name ) ?: continue val updatedVersion = outdatedInfo.versionUpdater.updateVersion(libVersion) if (libVersion == updatedVersion) { continue } if (dependencyText.contains(updatedVersion)) { continue } val reportOnElement = reportOnElement(dependencyStatement, outdatedInfo) val fix = if (dependencyText.contains(libVersion)) { ReplaceStringInDocumentFix(reportOnElement, libVersion, updatedVersion) } else { null } registerError( reportOnElement, outdatedInfo.message, if (fix != null) arrayOf(fix) else emptyArray(), ProblemHighlightType.GENERIC_ERROR_OR_WARNING ) break } } } private fun reportOnElement(classpathEntry: GrCallExpression, deprecatedForKotlinInfo: DeprecatedForKotlinLibInfo): PsiElement { val indexOf = classpathEntry.text.indexOf(deprecatedForKotlinInfo.lib.name) if (indexOf < 0) return classpathEntry return classpathEntry.findElementAt(indexOf) ?: classpathEntry } private fun checkKotlinVersion(file: PsiFile, languageVersion: LanguageVersion): Boolean { val module = ProjectRootManager.getInstance(file.project).fileIndex.getModuleForFile(file.virtualFile) ?: return false val moduleGroup = module.getWholeModuleGroup() return moduleGroup.sourceRootModules.any { moduleInGroup -> moduleInGroup.languageVersionSettings.languageVersion >= languageVersion } } } }
apache-2.0
5f5aec9779d0f90561d74f80465c3e45
50.555556
136
0.69427
5.909766
false
false
false
false
vovagrechka/fucking-everything
alraune/alxplatf/src/alraune/alxplatf.kt
1
8664
package alraune import vgrechka.* // XXX Without `: AlTag` compiler crashes // TODO:vgrechka After porting AlTag to Kotlin, check if that helps fun div(): AlTag = AlTag("div") fun span(): AlTag = AlTag("span") fun nav(): AlTag = AlTag("nav") fun taga(): AlTag = AlTag("a") fun tagi(): AlTag = AlTag("i") fun h3(): AlTag = AlTag("h3") fun h4(): AlTag = AlTag("h4") fun ul(): AlTag = AlTag("ul") fun ol(): AlTag = AlTag("ol") fun li(): AlTag = AlTag("li") fun input(): AlTag = AlTag("input") fun textarea(): AlTag = AlTag("textarea") fun select(): AlTag = AlTag("select") fun option(): AlTag = AlTag("option") fun button(): AlTag = AlTag("button") fun label(): AlTag = AlTag("label") fun form(): AlTag = AlTag("form") fun table(): AlTag = AlTag("table") fun tr(): AlTag = AlTag("tr") fun td(): AlTag = AlTag("td") fun hr(): AlTag = AlTag("hr") fun iframe(): AlTag = AlTag("iframe") fun span(s: String): AlTag = span().add(s)!! fun div(s: String): AlTag = div().add(s)!! fun AlTag.with(block: (() -> Unit)?): AlTag { pushTag(this) try { block?.invoke() } finally { popTag() } return this } fun pushTag(tag: AlTag) { _AlTag.getParents().add(tag) } fun popTag() { val parents = _AlTag.getParents() parents.removeAt(parents.lastIndex) } fun oo(x: Renderable?) { if (x != null) _AlTag.addToCurrent(x) } fun oo(x: String?) { // TODO:vgrechka Converting this to rawHtml doesn't seem right if (x != null) _AlTag.addToCurrent(rawHtml(x)) } fun rawHtml(x: String) = object : Renderable { override fun render() = x } fun rawHtml(block: () -> String) = object : Renderable { override fun render() = block() } fun escapeHtml(x: String) = x .replace("&", "&amp;") .replace("<", "&lt;") .replace(">", "&gt;") .replace("'", "&#39;") .replace("\"", "&#34;") enum class Color(val string: String) { // https://www.google.com/design/spec/style/color.html#color-color-palette Black("#000000"), BlackBoot("#333333"), White("#ffffff"), Red50("#ffebee"), Red100("#ffcdd2"), Red200("#ef9a9a"), Red300("#e57373"), Red400("#ef5350"), Red500("#f44336"), Red600("#e53935"), Red700("#d32f2f"), Red800("#c62828"), Red900("#b71c1c"), RedA100("#ff8a80"), RedA200("#ff5252"), RedA400("#ff1744"), RedA700("#d50000"), Pink50("#fce4ec"), Pink100("#f8bbd0"), Pink200("#f48fb1"), Pink300("#f06292"), Pink400("#ec407a"), Pink500("#e91e63"), Pink600("#d81b60"), Pink700("#c2185b"), Pink800("#ad1457"), Pink900("#880e4f"), PinkA100("#ff80ab"), PinkA200("#ff4081"), PinkA400("#f50057"), PinkA700("#c51162"), Purple50("#f3e5f5"), Purple100("#e1bee7"), Purple200("#ce93d8"), Purple300("#ba68c8"), Purple400("#ab47bc"), Purple500("#9c27b0"), Purple600("#8e24aa"), Purple700("#7b1fa2"), Purple800("#6a1b9a"), Purple900("#4a148c"), PurpleA100("#ea80fc"), PurpleA200("#e040fb"), PurpleA400("#d500f9"), PurpleA700("#aa00ff"), DeepPurple50("#ede7f6"), DeepPurple100("#d1c4e9"), DeepPurple200("#b39ddb"), DeepPurple300("#9575cd"), DeepPurple400("#7e57c2"), DeepPurple500("#673ab7"), DeepPurple600("#5e35b1"), DeepPurple700("#512da8"), DeepPurple800("#4527a0"), DeepPurple900("#311b92"), DeepPurpleA100("#b388ff"), DeepPurpleA200("#7c4dff"), DeepPurpleA400("#651fff"), DeepPurpleA700("#6200ea"), Indigo50("#e8eaf6"), Indigo100("#c5cae9"), Indigo200("#9fa8da"), Indigo300("#7986cb"), Indigo400("#5c6bc0"), Indigo500("#3f51b5"), Indigo600("#3949ab"), Indigo700("#303f9f"), Indigo800("#283593"), Indigo900("#1a237e"), IndigoA100("#8c9eff"), IndigoA200("#536dfe"), IndigoA400("#3d5afe"), IndigoA700("#304ffe"), Blue50("#e3f2fd"), Blue100("#bbdefb"), Blue200("#90caf9"), Blue300("#64b5f6"), Blue400("#42a5f5"), Blue500("#2196f3"), Blue600("#1e88e5"), Blue700("#1976d2"), Blue800("#1565c0"), Blue900("#0d47a1"), BlueA100("#82b1ff"), BlueA200("#448aff"), BlueA400("#2979ff"), BlueA700("#2962ff"), LightBlue50("#e1f5fe"), LightBlue100("#b3e5fc"), LightBlue200("#81d4fa"), LightBlue300("#4fc3f7"), LightBlue400("#29b6f6"), LightBlue500("#03a9f4"), LightBlue600("#039be5"), LightBlue700("#0288d1"), LightBlue800("#0277bd"), LightBlue900("#01579b"), LightBlueA100("#80d8ff"), LightBlueA200("#40c4ff"), LightBlueA400("#00b0ff"), LightBlueA700("#0091ea"), Cyan50("#e0f7fa"), Cyan100("#b2ebf2"), Cyan200("#80deea"), Cyan300("#4dd0e1"), Cyan400("#26c6da"), Cyan500("#00bcd4"), Cyan600("#00acc1"), Cyan700("#0097a7"), Cyan800("#00838f"), Cyan900("#006064"), CyanA100("#84ffff"), CyanA200("#18ffff"), CyanA400("#00e5ff"), CyanA700("#00b8d4"), Teal50("#e0f2f1"), Teal100("#b2dfdb"), Teal200("#80cbc4"), Teal300("#4db6ac"), Teal400("#26a69a"), Teal500("#009688"), Teal600("#00897b"), Teal700("#00796b"), Teal800("#00695c"), Teal900("#004d40"), TealA100("#a7ffeb"), TealA200("#64ffda"), TealA400("#1de9b6"), TealA700("#00bfa5"), Green50("#e8f5e9"), Green100("#c8e6c9"), Green200("#a5d6a7"), Green300("#81c784"), Green400("#66bb6a"), Green500("#4caf50"), Green600("#43a047"), Green700("#388e3c"), Green800("#2e7d32"), Green900("#1b5e20"), GreenA100("#b9f6ca"), GreenA200("#69f0ae"), GreenA400("#00e676"), GreenA700("#00c853"), LightGreen50("#f1f8e9"), LightGreen100("#dcedc8"), LightGreen200("#c5e1a5"), LightGreen300("#aed581"), LightGreen400("#9ccc65"), LightGreen500("#8bc34a"), LightGreen600("#7cb342"), LightGreen700("#689f38"), LightGreen800("#558b2f"), LightGreen900("#33691e"), LightGreenA100("#ccff90"), LightGreenA200("#b2ff59"), LightGreenA400("#76ff03"), LightGreenA700("#64dd17"), Lime50("#f9fbe7"), Lime100("#f0f4c3"), Lime200("#e6ee9c"), Lime300("#dce775"), Lime400("#d4e157"), Lime500("#cddc39"), Lime600("#c0ca33"), Lime700("#afb42b"), Lime800("#9e9d24"), Lime900("#827717"), LimeA100("#f4ff81"), LimeA200("#eeff41"), LimeA400("#c6ff00"), LimeA700("#aeea00"), Yellow50("#fffde7"), Yellow100("#fff9c4"), Yellow200("#fff59d"), Yellow300("#fff176"), Yellow400("#ffee58"), Yellow500("#ffeb3b"), Yellow600("#fdd835"), Yellow700("#fbc02d"), Yellow800("#f9a825"), Yellow900("#f57f17"), YellowA100("#ffff8d"), YellowA200("#ffff00"), YellowA400("#ffea00"), YellowA700("#ffd600"), Amber50("#fff8e1"), Amber100("#ffecb3"), Amber200("#ffe082"), Amber300("#ffd54f"), Amber400("#ffca28"), Amber500("#ffc107"), Amber600("#ffb300"), Amber700("#ffa000"), Amber800("#ff8f00"), Amber900("#ff6f00"), AmberA100("#ffe57f"), AmberA200("#ffd740"), AmberA400("#ffc400"), AmberA700("#ffab00"), Orange50("#fff3e0"), Orange100("#ffe0b2"), Orange200("#ffcc80"), Orange300("#ffb74d"), Orange400("#ffa726"), Orange500("#ff9800"), Orange600("#fb8c00"), Orange700("#f57c00"), Orange800("#ef6c00"), Orange900("#e65100"), OrangeA100("#ffd180"), OrangeA200("#ffab40"), OrangeA400("#ff9100"), OrangeA700("#ff6d00"), DeepOrange50("#fbe9e7"), DeepOrange100("#ffccbc"), DeepOrange200("#ffab91"), DeepOrange300("#ff8a65"), DeepOrange400("#ff7043"), DeepOrange500("#ff5722"), DeepOrange600("#f4511e"), DeepOrange700("#e64a19"), DeepOrange800("#d84315"), DeepOrange900("#bf360c"), DeepOrangeA100("#ff9e80"), DeepOrangeA200("#ff6e40"), DeepOrangeA400("#ff3d00"), DeepOrangeA700("#dd2c00"), Brown50("#efebe9"), Brown100("#d7ccc8"), Brown200("#bcaaa4"), Brown300("#a1887f"), Brown400("#8d6e63"), Brown500("#795548"), Brown600("#6d4c41"), Brown700("#5d4037"), Brown800("#4e342e"), Brown900("#3e2723"), Gray50("#fafafa"), Gray100("#f5f5f5"), Gray200("#eeeeee"), Gray300("#e0e0e0"), Gray400("#bdbdbd"), Gray500("#9e9e9e"), Gray600("#757575"), Gray700("#616161"), Gray800("#424242"), Gray900("#212121"), BlueGray50("#eceff1"), BlueGray100("#cfd8dc"), BlueGray200("#b0bec5"), BlueGray300("#90a4ae"), BlueGray400("#78909c"), BlueGray500("#607d8b"), BlueGray600("#546e7a"), BlueGray700("#455a64"), BlueGray800("#37474f"), BlueGray900("#263238"), Red("red"), Green("green"), Blue("blue"), RosyBrown("rosybrown"); override fun toString() = string } fun AlTag.classes(vararg xs: Any?): AlTag = this.className(xs.filterNotNull().joinToString(" ")) object AlBTFConst0 { val bodyMarginTopForNavbar_px: Int = 51 } object FA2 { fun floppyO() = tagi().className("fa fa-floppy-o") } fun elementDataSetName_toDataAttributeName(name: String) = "data-${name.camelToKebab()}" typealias ErrorString = String typealias MaybeErrorString = String? object AlText0 { val rightDoubleAngleQuotation = "»" val rightDoubleAngleQuotationSpaced = " » " val nl2 = "\n\n" val nbsp = "" + (0xa0).toChar() val emdash = "—" val endash = "–" val threeQuotes = "\"\"\"" val times = "×" val ellipsis = "…" val leftRightArrow = "↔" val rightArrow = "→" } object AlXplatfConst { val __procName by myName() }
apache-2.0
967a90d5a5b6c8b9dfda30da0b06e2f9
55.914474
370
0.652873
2.984132
false
false
false
false
smmribeiro/intellij-community
plugins/devkit/devkit-kotlin-tests/testSrc/org/jetbrains/idea/devkit/kotlin/inspections/KtUElementAsPsiInspectionTest.kt
13
4398
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.idea.devkit.kotlin.inspections import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase import org.jetbrains.idea.devkit.inspections.UElementAsPsiInspection class KtUElementAsPsiInspectionTest : LightJavaCodeInsightFixtureTestCase() { override fun setUp() { super.setUp() myFixture.addClass("package org.jetbrains.uast; public interface UElement {}") myFixture.addClass("""package com.intellij.psi; public interface PsiElement { | PsiElement getParent(); |}""".trimMargin()) myFixture.addClass("package com.intellij.psi; public interface PsiClass extends PsiElement {}") myFixture.addClass("""package org.jetbrains.uast; public interface UClass extends UElement, com.intellij.psi.PsiClass { | void uClassMethod(); |}""".trimMargin()) myFixture.enableInspections(UElementAsPsiInspection()) } fun testPassAsPsiClass() { myFixture.configureByText("UastUsage.kt", """ import org.jetbrains.uast.UClass; import com.intellij.psi.PsiClass; class UastUsage { fun processUClassCaller(uClass: UClass){ processUClass(uClass); } fun processUClass(uClass: UClass){ processPsiClass(<warning descr="Usage of UElement as PsiElement is not recommended">uClass</warning>); } fun processPsiClass(psiClass: PsiClass){ psiClass.toString() } } """.trimIndent()) myFixture.testHighlighting("UastUsage.kt") } fun testExtensionMethods() { myFixture.configureByText("UastUsage.kt", """ import org.jetbrains.uast.*; import com.intellij.psi.*; class UastUsage { fun processUClassCaller(psiElement: PsiElement, uClass: UClass){ this.process(psiElement, uClass) uClass.process(<warning>uClass</warning>, uClass) } fun Any.process(psiClass: PsiElement, uElement: UElement?){ psiClass.toString(); uElement.toString() } } """.trimIndent()) myFixture.testHighlighting("UastUsage.kt") } fun testAssignment() { myFixture.configureByText("UastUsage.kt", """ import org.jetbrains.uast.UClass; import com.intellij.psi.PsiClass; class UastUsage { var psiClass:PsiClass; constructor(uClass: UClass){ psiClass = <warning descr="Usage of UElement as PsiElement is not recommended">uClass</warning>; val localPsiClass:PsiClass = <warning descr="Usage of UElement as PsiElement is not recommended">uClass</warning>; localPsiClass.toString() } } """.trimIndent()) myFixture.testHighlighting("UastUsage.kt") } fun testCast() { myFixture.configureByText("UastUsage.kt", """ import org.jetbrains.uast.*; import com.intellij.psi.PsiClass; class UastUsage { constructor(uElement: UElement){ (<warning descr="Usage of UElement as PsiElement is not recommended">uElement</warning> as? PsiClass).toString(); (uElement as? UClass).toString(); } } """.trimIndent()) myFixture.testHighlighting("UastUsage.kt") } fun testCallParentMethod() { myFixture.configureByText("UastUsage.kt", """ import org.jetbrains.uast.UClass; import com.intellij.psi.PsiClass; class UastUsage { fun foo(uClass: UClass){ uClass.<warning descr="Usage of UElement as PsiElement is not recommended">getParent()</warning>; uClass.uClassMethod(); } } """.trimIndent()) myFixture.testHighlighting("UastUsage.kt") } fun testImplementAndCallParentMethod() { myFixture.configureByText("UastUsage.kt", """ import org.jetbrains.uast.UClass; import com.intellij.psi.*; class UastUsage { fun foo(){ val impl = UClassImpl(); impl.<warning descr="Usage of UElement as PsiElement is not recommended">getParent()</warning>; impl.uClassMethod(); } } class UClassImpl: UClass { override fun getParent():PsiClass? = null override fun uClassMethod(){ } } """.trimIndent()) myFixture.testHighlighting("UastUsage.kt") } }
apache-2.0
7275fb5471b0a1fb6a13f245ca1b0545
28.52349
149
0.655753
4.992054
false
true
false
false
smmribeiro/intellij-community
java/java-impl/src/com/intellij/lang/java/actions/ChangeMethodParameters.kt
11
3288
// 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.lang.java.actions import com.intellij.codeInsight.daemon.QuickFixBundle import com.intellij.lang.jvm.actions.ChangeParametersRequest import com.intellij.lang.jvm.actions.ExpectedParameter import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* internal class ChangeMethodParameters(target: PsiMethod, override val request: ChangeParametersRequest) : CreateTargetAction<PsiMethod>( target, request) { override fun getText(): String { val helper = JvmPsiConversionHelper.getInstance(target.project) val parametersString = request.expectedParameters.joinToString(", ", "(", ")") { val psiType = helper.convertType(it.expectedTypes.first().theType) val name = it.semanticNames.first() "${psiType.presentableText} $name" } val shortenParameterString = StringUtil.shortenTextWithEllipsis(parametersString, 30, 5) return QuickFixBundle.message("change.method.parameters.text", shortenParameterString) } override fun getFamilyName(): String = QuickFixBundle.message("change.method.parameters.family") override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { val factory = PsiElementFactory.getInstance(project) val helper = JvmPsiConversionHelper.getInstance(target.project) tailrec fun updateParameters(currentParameters: List<PsiParameter>, expectedParameters: List<ExpectedParameter>) { val currentHead = currentParameters.firstOrNull() val expectedHead = expectedParameters.firstOrNull() if (expectedHead == null) { currentParameters.forEach(PsiParameter::delete) return } if (expectedHead is ChangeParametersRequest.ExistingParameterWrapper) { if (expectedHead.existingParameter == currentHead) return updateParameters(currentParameters.subList(1, currentParameters.size), expectedParameters.subList(1, expectedParameters.size)) else throw UnsupportedOperationException("processing of existing params in different order is not implemented yet") } val name = expectedHead.semanticNames.first() val psiType = helper.convertType(expectedHead.expectedTypes.first().theType) val newParameter = factory.createParameter(name, psiType) // #addAnnotationToModifierList adds annotations to the start of the modifier list instead of its end, // reversing the list "nullifies" this behaviour, thus preserving the original annotations order for (annotationRequest in expectedHead.expectedAnnotations.reversed()) { CreateAnnotationAction.addAnnotationToModifierList(newParameter.modifierList!!, annotationRequest) } if (currentHead == null) target.parameterList.add(newParameter) else target.parameterList.addBefore(newParameter, currentHead) updateParameters(currentParameters, expectedParameters.subList(1, expectedParameters.size)) } updateParameters(target.parameterList.parameters.toList(), request.expectedParameters) } }
apache-2.0
2705aad4e55838fca3fbabfbcaaf3b74
43.432432
140
0.754562
5.2608
false
false
false
false
ThiagoGarciaAlves/intellij-community
java/java-impl/src/com/intellij/lang/java/request/CreateMethodFromJavaUsageRequest.kt
3
1656
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.lang.java.request import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils.guessExpectedTypes import com.intellij.codeInsight.daemon.impl.quickfix.CreateMethodFromUsageFix.hasErrorsInArgumentList import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.CreateMethodRequest import com.intellij.lang.jvm.actions.ExpectedTypes import com.intellij.psi.* import com.intellij.psi.util.parentOfType import com.intellij.psi.util.parents import com.intellij.util.withPrevious internal class CreateMethodFromJavaUsageRequest( methodCall: PsiMethodCallExpression, override val modifiers: Collection<JvmModifier> ) : CreateExecutableFromJavaUsageRequest<PsiMethodCallExpression>(methodCall), CreateMethodRequest { override val isValid: Boolean get() { val call = callPointer.element ?: return false call.methodExpression.referenceName ?: return false return !hasErrorsInArgumentList(call) } override val methodName: String get() = call.methodExpression.referenceName!! override val returnType: ExpectedTypes get() = guessExpectedTypes(call, call.parent is PsiStatement).map(::ExpectedJavaType) fun getAnchor(targetClass: PsiClass): PsiElement? { val enclosingMember = call.parentOfType(PsiMethod::class, PsiField::class, PsiClassInitializer::class) ?: return null for ((parent, lastParent) in enclosingMember.parents().withPrevious()) { if (parent == targetClass) return lastParent } return null } }
apache-2.0
055a69a2985741726bfe5412e6fa68dd
43.756757
140
0.794686
4.8
false
false
false
false
aosp-mirror/platform_frameworks_support
room/compiler/src/main/kotlin/androidx/room/solver/CodeGenScope.kt
1
2418
/* * Copyright (C) 2016 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.room.solver import androidx.room.writer.ClassWriter import com.google.common.annotations.VisibleForTesting import com.squareup.javapoet.CodeBlock /** * Defines a code generation scope where we can provide temporary variables, global variables etc */ class CodeGenScope(val writer: ClassWriter) { private var tmpVarIndices = mutableMapOf<String, Int>() private var builder: CodeBlock.Builder? = null companion object { const val TMP_VAR_DEFAULT_PREFIX = "_tmp" const val CLASS_PROPERTY_PREFIX = "__" @VisibleForTesting fun _tmpVar(index: Int) = _tmpVar(TMP_VAR_DEFAULT_PREFIX, index) fun _tmpVar(prefix: String, index: Int) = "$prefix${if (index == 0) "" else "_$index"}" } fun builder(): CodeBlock.Builder { if (builder == null) { builder = CodeBlock.builder() } return builder!! } fun getTmpVar(): String { return getTmpVar(TMP_VAR_DEFAULT_PREFIX) } fun getTmpVar(prefix: String): String { if (!prefix.startsWith("_")) { throw IllegalArgumentException("tmp variable prefixes should start with _") } if (prefix.startsWith(CLASS_PROPERTY_PREFIX)) { throw IllegalArgumentException("cannot use $CLASS_PROPERTY_PREFIX for tmp variables") } val index = tmpVarIndices.getOrElse(prefix) { 0 } val result = _tmpVar(prefix, index) tmpVarIndices.put(prefix, index + 1) return result } fun generate() = builder().build().toString() /** * copies all variable indices but excludes generated code. */ fun fork(): CodeGenScope { val forked = CodeGenScope(writer) forked.tmpVarIndices.putAll(tmpVarIndices) return forked } }
apache-2.0
a05be167ffa8a02a97354211acb956bb
33.056338
97
0.666253
4.412409
false
false
false
false
intrigus/jtransc
jtransc-core/src/com/jtransc/ast/ast_dump.kt
1
5963
package com.jtransc.ast import com.jtransc.error.invalidOp import com.jtransc.error.noImpl import com.jtransc.text.Indenter import com.jtransc.text.Indenter.Companion //fun AstBody.dump() = dump(this) fun dump(types: AstTypes, body: AstBody): Indenter { return Indenter { for (local in body.locals) { line(javaDump(body.types, local.type) + " " + local.name + ";") } line(dump(types, body.stm)) } } fun dump(types: AstTypes, expr: AstStm.Box?): Indenter { return dump(types, expr?.value) } fun dump(types: AstTypes, stm: AstStm?): Indenter { return Indenter { when (stm) { null -> { } is AstStm.STMS -> { if (stm.stms.size == 1) { line(dump(types, stm.stms.first())) } else { line("{") indent { for (s in stm.stms) line(dump(types, s)) } line("}") } } is AstStm.STM_LABEL -> line(":" + stm.label.name) is AstStm.SET_LOCAL -> line(stm.local.name + " = " + dump(types, stm.expr) + ";") is AstStm.SET_FIELD_INSTANCE -> line(dump(types, stm.left) + "." + stm.field.name + " = " + dump(types, stm.expr) + ";") is AstStm.SET_ARRAY_LITERALS -> line(dump(types, stm.array) + "[${stm.startIndex}..${stm.startIndex + stm.values.size - 1}] = ${stm.values.map { dump(types, it) }};") is AstStm.STM_EXPR -> line(dump(types, stm.expr) + ";") is AstStm.IF_GOTO -> line("if (" + dump(types, stm.cond) + ") goto " + stm.label.name + ";") is AstStm.GOTO -> line("goto " + stm.label.name + ";") is AstStm.RETURN -> line("return " + dump(types, stm.retval) + ";") is AstStm.RETURN_VOID -> line("return;") //is AstStm.CALL_INSTANCE -> line("call") is AstStm.SET_FIELD_STATIC -> line(stm.clazz.fqname + "." + stm.field.name + " = " + dump(types, stm.expr) + ";") is AstStm.SET_ARRAY -> line(dump(types, stm.array) + "[" + dump(types, stm.index) + "] = " + dump(types, stm.expr) + ";") is AstStm.LINE -> { //line("LINE(${stm.line})") } is AstStm.NOP -> line("NOP(${stm.reason})") is AstStm.CONTINUE -> line("continue;") is AstStm.BREAK -> line("break;") is AstStm.THROW -> line("throw ${dump(types, stm.exception)};") is AstStm.IF -> line("if (${dump(types, stm.cond)})") { line(dump(types, stm.strue)) } is AstStm.IF_ELSE -> { line("if (${dump(types, stm.cond)})") { line(dump(types, stm.strue)) } line("else") { line(dump(types, stm.sfalse)) } } is AstStm.WHILE -> { line("while (${dump(types, stm.cond)})") { line(dump(types, stm.iter)) } } is AstStm.SWITCH -> { line("switch (${dump(types, stm.subject)})") { for ((indices, case) in stm.cases) line("case ${indices.joinToString(", ")}: ${dump(types, case)}") line("default: ${dump(types, stm.default)}") } } is AstStm.SWITCH_GOTO -> { line("switch (${dump(types, stm.subject)})") { for ((indices, case) in stm.cases) line("case ${indices.joinToString(", ")}: goto $case;") line("default: goto ${stm.default};") } } is AstStm.MONITOR_ENTER -> line("MONITOR_ENTER(${dump(types, stm.expr)})") is AstStm.MONITOR_EXIT -> line("MONITOR_EXIT(${dump(types, stm.expr)})") else -> noImpl("$stm") } } } fun dump(types: AstTypes, expr: AstExpr.Box?): String { return dump(types, expr?.value) } fun AstExpr?.exprDump(types: AstTypes) = dump(types, this) fun List<AstStm>.dump(types: AstTypes) = dump(types, this.stm()) fun AstStm.dump(types: AstTypes) = dump(types, this) fun AstExpr.dump(types: AstTypes) = dump(types, this) fun dump(types: AstTypes, expr: AstExpr?): String { return when (expr) { null -> "" is AstExpr.BINOP -> { "(" + dump(types, expr.left) + " " + expr.op.symbol + " " + dump(types, expr.right) + ")" } is AstExpr.UNOP -> "(" + expr.op.symbol + dump(types, expr.right) + ")" is AstExpr.LITERAL -> { val value = expr.value when (value) { is String -> "\"$value\"" else -> "$value" } } is AstExpr.LocalExpr -> expr.name is AstExpr.CAUGHT_EXCEPTION -> "__expr" is AstExpr.ARRAY_LENGTH -> "(${dump(types, expr.array)}).length" is AstExpr.ARRAY_ACCESS -> dump(types, expr.array) + "[" + dump(types, expr.index) + "]" is AstExpr.FIELD_INSTANCE_ACCESS -> dump(types, expr.expr) + "." + expr.field.name is AstExpr.FIELD_STATIC_ACCESS -> "" + expr.clazzName + "." + expr.field.name is AstExpr.BaseCast -> "((" + javaDump(types, expr.to) + ")" + dump(types, expr.subject) + ")" is AstExpr.INSTANCE_OF -> "(" + dump(types, expr.expr) + " instance of " + javaDump(types, expr.checkType) + ")" is AstExpr.NEW -> "new " + expr.target.fqname + "()" is AstExpr.NEW_WITH_CONSTRUCTOR -> dump(types, AstExpr.CALL_INSTANCE(AstExpr.NEW(expr.type), expr.constructor, expr.args.map { it.value }, isSpecial = false)) is AstExpr.TERNARY -> dump(types, expr.cond) + " ? " + dump(types, expr.etrue) + " : " + dump(types, expr.efalse) //is AstExpr.REF -> "REF(" + dump(expr.expr) + ")" is AstExpr.NEW_ARRAY -> "new " + expr.arrayType.element + "[" + expr.counts.map { dump(types, it) }.joinToString(", ") + "]" is AstExpr.CALL_BASE -> { val args = expr.args.map { dump(types, it) } val argsString = args.joinToString(", "); when (expr) { is AstExpr.CALL_INSTANCE -> (if (expr.isSpecial) "special." else "") + dump(types, expr.obj) + "." + expr.method.name + "($argsString)" is AstExpr.CALL_SUPER -> "super.${expr.method.name}($argsString)" is AstExpr.CALL_STATIC -> expr.clazz.fqname + "." + expr.method.name + "($argsString)" else -> invalidOp } } else -> noImpl("$expr") } } fun javaDump(types: AstTypes, type: AstType?): String { return when (type) { null -> "null" is AstType.VOID -> "void" is AstType.BYTE -> "byte" is AstType.SHORT -> "short" is AstType.CHAR -> "char" is AstType.INT -> "int" is AstType.LONG -> "long" is AstType.FLOAT -> "float" is AstType.DOUBLE -> "double" is AstType.ARRAY -> javaDump(types, type.element) + "[]" is AstType.REF -> type.fqname else -> type.mangleExt() } }
apache-2.0
25b7f466c16df1c4681c37b448f2d118
37.727273
169
0.606742
3.002518
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/psi/impl/mixins/SkinStringLiteralMixin.kt
1
3675
package com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.impl.mixins import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinPropertyName import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.SkinStringLiteral import com.gmail.blueboxware.libgdxplugin.filetypes.skin.psi.impl.SkinValueImpl import com.gmail.blueboxware.libgdxplugin.filetypes.skin.references.SkinFileReference import com.gmail.blueboxware.libgdxplugin.filetypes.skin.references.SkinResourceReference import com.gmail.blueboxware.libgdxplugin.filetypes.skin.utils.factory import com.gmail.blueboxware.libgdxplugin.filetypes.skin.utils.stripQuotes import com.gmail.blueboxware.libgdxplugin.filetypes.skin.utils.unescape import com.gmail.blueboxware.libgdxplugin.utils.* import com.intellij.lang.ASTNode import com.intellij.psi.PsiPrimitiveType import com.intellij.psi.PsiReference import com.intellij.psi.util.CachedValue /* * Copyright 2016 Blue Box Ware * * 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. */ abstract class SkinStringLiteralMixin(node: ASTNode) : SkinStringLiteral, SkinValueImpl(node) { private var lastHash: Int? = null private var lastString: String? = null override fun getValue(): String { val newHash = text.hashCode() if (lastHash == newHash) { return lastString ?: "" } val str = text.stripQuotes().unescape() lastHash = newHash lastString = str return str } override fun asPropertyName(): SkinPropertyName? = this.parent as? SkinPropertyName override fun isBoolean(): Boolean = text == "true" || text == "false" override fun getReference(): PsiReference? = getCachedValue(REFERENCE_KEY, null) { val containingObjectType = property?.containingObject?.resolveToTypeString() if ( (containingObjectType == BITMAPFONT_CLASS_NAME && property?.name == PROPERTY_NAME_FONT_FILE) || (containingObjectType == FREETYPE_FONT_PARAMETER_CLASS_NAME && property?.name == "font") ) { return@getCachedValue SkinFileReference(this, containingFile) } else { resolveToType().let { type -> if ( isBoolean && type?.canonicalText == "java.lang.Boolean" || type?.canonicalText == "java.lang.Integer" || type is PsiPrimitiveType || type == null ) { return@getCachedValue null } else if (type.isStringType(this)) { if (containingObjectType != TINTED_DRAWABLE_CLASS_NAME || property?.name != PROPERTY_NAME_TINTED_DRAWABLE_NAME) { return@getCachedValue null } } } } return@getCachedValue SkinResourceReference(this) } override fun setValue(string: String) { factory()?.createStringLiteral(string, isQuoted)?.let { replace(it) } } override fun isQuoted(): Boolean = text.firstOrNull() == '\"' companion object { val REFERENCE_KEY = key<CachedValue<PsiReference?>>("reference") } }
apache-2.0
cc407b5585d494cd55f0d2868035bf58
37.684211
133
0.674286
4.699488
false
false
false
false
eurofurence/ef-app_android
app/src/main/kotlin/org/eurofurence/connavigator/ui/dialogs/EventDialog.kt
1
3025
package org.eurofurence.connavigator.ui.dialogs import android.content.Context import android.content.Intent import android.provider.CalendarContract import androidx.core.content.ContextCompat.startActivity import com.pawegio.kandroid.IntentFor import io.swagger.client.model.EventRecord import org.eurofurence.connavigator.R import org.eurofurence.connavigator.events.EventFavoriteBroadcast import org.eurofurence.connavigator.database.Db import org.eurofurence.connavigator.services.AnalyticsService import org.eurofurence.connavigator.ui.filters.end import org.eurofurence.connavigator.ui.filters.start import org.eurofurence.connavigator.util.extensions.jsonObjects import org.eurofurence.connavigator.util.extensions.shareString import org.jetbrains.anko.* /** * Shows an event dialog */ fun AnkoLogger.eventDialog(context: Context, event: EventRecord, db: Db, favoriteCallback: ((Boolean) -> Unit)? = null) { val isFavorite = db.faves.contains(event.id) val options = listOf( if (!isFavorite) context.getString(R.string.event_add_to_favorites) else context.getString(R.string.event_remove_from_favorites), context.getString(R.string.event_share_export_to_calendar), context.getString(R.string.event_share_event) ) return context.selector( context.getString(R.string.event_options_for, event.title), options ) { _, position -> when (position) { 0 -> { debug { "Favouriting event for user" } context.sendBroadcast(IntentFor<EventFavoriteBroadcast>(context).apply { jsonObjects["event"] = event }) favoriteCallback?.invoke(!isFavorite) context.toast(context.getString(R.string.event_changed_status)) } 1 -> { debug { "Writing event to calendar" } val calendarIntent = Intent(Intent.ACTION_INSERT) AnalyticsService.event(AnalyticsService.Category.EVENT, AnalyticsService.Action.EXPORT_CALENDAR, event.title) calendarIntent.type = "vnd.android.cursor.item/event" calendarIntent.putExtra(CalendarContract.Events.TITLE, event.title) calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, event.start.millis) calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, event.end.millis) calendarIntent.putExtra(CalendarContract.Events.EVENT_LOCATION, db.toRoom(event)?.name) calendarIntent.putExtra(CalendarContract.Events.DESCRIPTION, event.description) startActivity(context, calendarIntent, null) } 2 -> { debug { "Sharing event" } AnalyticsService.event(AnalyticsService.Category.EVENT, AnalyticsService.Action.SHARED, event.title) //share context.share(event.shareString(context!!), context.getString(R.string.event_share_event)) } } } }
mit
5e3983a3f844d425660b64aae8a26f08
43.5
141
0.690909
4.61128
false
false
false
false
NLPIE/BioMedICUS
biomedicus-core/src/main/kotlin/edu/umn/biomedicus/modification/Modifiers.kt
1
2543
/* * Copyright (c) 2018 Regents of the University of Minnesota. * * 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 edu.umn.biomedicus.modification import edu.umn.nlpengine.Label import edu.umn.nlpengine.LabelMetadata import edu.umn.nlpengine.SystemModule import edu.umn.nlpengine.TextRange class ModifiersModule : SystemModule() { override fun setup() { addLabelClass<ModificationCue>() addLabelClass<Historical>() addLabelClass<Negated>() addLabelClass<Probable>() } } interface DictionaryTermModifier : TextRange { val cueTerms: List<ModificationCue> } @LabelMetadata(classpath = "biomedicus.v2", distinct = true) data class ModificationCue(override val startIndex: Int, override val endIndex: Int) : Label() { constructor(textRange: TextRange): this(textRange.startIndex, textRange.endIndex) } @LabelMetadata(classpath = "biomedicus.v2", distinct = true) data class Historical( override val startIndex: Int, override val endIndex: Int, override val cueTerms: List<ModificationCue> ) : Label(), DictionaryTermModifier { constructor(textRange: TextRange, cueTerms: List<ModificationCue>): this(textRange.startIndex, textRange.endIndex, cueTerms) } @LabelMetadata(classpath = "biomedicus.v2", distinct = true) data class Negated( override val startIndex: Int, override val endIndex: Int, override val cueTerms: List<ModificationCue> ) : Label(), DictionaryTermModifier { constructor(textRange: TextRange, cueTerms: List<ModificationCue>): this(textRange.startIndex, textRange.endIndex, cueTerms) } @LabelMetadata(classpath = "biomedicus.v2", distinct = true) data class Probable( override val startIndex: Int, override val endIndex: Int, override val cueTerms: List<ModificationCue> ) : Label(), DictionaryTermModifier { constructor(textRange: TextRange, cueTerms: List<ModificationCue>): this(textRange.startIndex, textRange.endIndex, cueTerms) }
apache-2.0
30689bd7fbadb48bbb8140d8bc13ce6c
35.342857
96
0.729847
4.516874
false
false
false
false
timrs2998/pdf-builder
src/main/kotlin/com/github/timrs2998/pdfbuilder/style/Padding.kt
1
250
package com.github.timrs2998.pdfbuilder.style data class Padding( val top: Float = 0f, val right: Float = 0f, val bottom: Float = 0f, val left: Float = 0f) { companion object { @JvmStatic val ZERO = Padding(0f, 0f, 0f, 0f) } }
gpl-3.0
31964554c016ae3a3d05a2b6e2406a4c
16.857143
45
0.64
2.840909
false
false
false
false
SoulBeaver/SpriteSheetProcessor
src/test/java/com/sbg/rpg/packing/common/extensions/ImageUtilsSpec.kt
1
5077
package com.sbg.rpg.packing.common.extensions import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import java.awt.Color import java.awt.Dimension import java.awt.image.BufferedImage import java.nio.file.Paths import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotEquals object ImageUtilsSpec : Spek({ given("An image") { val imageUrl = this.javaClass.classLoader.getResource("unpacker/SingleSprite.png")!! on("converting to a BufferedImage") { val original = Paths.get(imageUrl.toURI()).readImage() it("does not perform a conversion if the common is already of type BufferedImage and has the same color type") { val expected = original.toBufferedImage() assertEquals(original.type, expected.type, "Expected original and expected to be identical.") } it("converts the common type from ARGB to [something]") { val expected = original.toBufferedImage(BufferedImage.TYPE_3BYTE_BGR) assertNotEquals(expected.type, original.type, "Expected converted BufferedImage to have a different type than original.") assertEquals(BufferedImage.TYPE_3BYTE_BGR, expected.type) } } on("that needs to have a copy made") { val original = Paths.get(imageUrl.toURI()).readImage() it("should create a deep copy") { val copy = original.copy() assertFalse(original == copy) } it("should be an exact replica of the original") { val copy = original.copy() assertEquals(original.width, copy.width) assertEquals(original.height, copy.height) for (y in 0..copy.height - 1) { for (x in 0..copy.width - 1) { val originalAtXY = original.getRGB(x, y) val copyAtXY = copy.getRGB(x, y) assertEquals(originalAtXY, copyAtXY, "The copied common is not identical to the original.") } } } } } given("A 200x200 common") { val imageUrl = this.javaClass.classLoader.getResource("unpacker/200x200.png")!! on("looping through it") { val image = Paths.get(imageUrl.toURI()).readImage() it("should loop fourty-thousand times") { var counter = 0 for (pixel in image) counter += 1 assertEquals(40_000, counter, "Expected to loop through 40k pixels, but was $counter") } } } given("A 200x200 common") { val imageUrl = this.javaClass.classLoader.getResource("unpacker/200x200.png")!! on("creating a simple copy") { val image = Paths.get(imageUrl.toURI()).readImage() val copy = image.copy() it("should be distinct") { assertFalse(copy == image) } it("should contain the same content") { for (pixel in copy) assertEquals(pixel.color, Color(image.getRGB(pixel.point.x, pixel.point.y))) } } on("creating a larger copy with black border") { val image = Paths.get(imageUrl.toURI()).readImage() val copyWithBorder = image.copyWithBorder( Dimension(image.width + 10, image.height + 10), Color.BLACK ) it("should be 210x210 large") { assertEquals(210, copyWithBorder.width, "Expected width of border copy to be 210, but was ${copyWithBorder.width}") assertEquals(210, copyWithBorder.height, "Expected width of border copy to be 210, but was ${copyWithBorder.height}") } it("should have a 5 pixel wide border on all sides") { for (y in 0..4) { for (x in 0 until copyWithBorder.width) { assertEquals(Color.BLACK, Color(copyWithBorder.getRGB(x, y))) } } for (y in 205..209) { for (x in 0 until copyWithBorder.width) { assertEquals(Color.BLACK, Color(copyWithBorder.getRGB(x, y))) } } for (x in 0..4) { for (y in 0 until copyWithBorder.height) { assertEquals(Color.BLACK, Color(copyWithBorder.getRGB(x, y))) } } for (x in 205..209) { for (y in 0 until copyWithBorder.height) { assertEquals(Color.BLACK, Color(copyWithBorder.getRGB(x, y))) } } } } } })
apache-2.0
d53217b16da169655afb438439857df4
35.014184
137
0.534765
4.881731
false
false
false
false
jabbink/PokemonGoBot
src/main/kotlin/ink/abb/pogo/scraper/util/data/PokedexData.kt
3
934
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package ink.abb.pogo.scraper.util.data import POGOProtos.Data.PokedexEntryOuterClass data class PokedexEntry( var timesEncountered: Int? = null, var timeCaptured: Int? = null, var pokemonName: String? = null, var pokemonNumber: Int? = null ) { fun buildFromEntry(entry: PokedexEntryOuterClass.PokedexEntry): PokedexEntry { this.timesEncountered = entry.timesEncountered this.timeCaptured = entry.timesCaptured this.pokemonName = entry.pokemonId.name this.pokemonNumber = entry.pokemonId.number return this } }
gpl-3.0
faf80bae5e513669f17e0e7fb9071a0c
31.206897
97
0.717345
4.42654
false
false
false
false
klose911/klose911.github.io
src/kotlin/src/tutorial/coroutine/flow/FlowCombine.kt
1
1188
package tutorial.coroutine.flow import kotlinx.coroutines.delay import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking fun main() = runBlocking { // val nums = (1..3).asFlow().onEach { delay(300) } // 发射数字 1..3,间隔 300 毫秒 // val strs = flowOf("one", "two", "three").onEach { delay(400) } // 每 400 毫秒发射一次字符串 // val startTime = System.currentTimeMillis() // 记录开始的时间 // nums.zip(strs) { a, b -> "$a -> $b" } // 使用“zip”组合单个字符串 // .collect { value -> // 收集并打印 // println("$value at ${System.currentTimeMillis() - startTime} ms from start") // } val nums = (1..3).asFlow().onEach { delay(300) } // 发射数字 1..3,间隔 300 毫秒 val strs = flowOf("one", "two", "three").onEach { delay(400) } // 每 400 毫秒发射一次字符串 val startTime = System.currentTimeMillis() // 记录开始的时间 nums.combine(strs) { a, b -> "$a -> $b" } // 使用“combine”组合单个字符串 .collect { value -> // 收集并打印 println("$value at ${System.currentTimeMillis() - startTime} ms from start") } }
bsd-2-clause
a12e95b94e0ffa9493e50b4582101d9e
43.391304
90
0.602941
3.300971
false
false
false
false
klose911/klose911.github.io
src/kotlin/src/tutorial/collections/operation/ModificationSample.kt
1
1420
package tutorial.collections.operation fun main() { val numbers1 = mutableListOf(1, 2, 3, 4) numbers1.add(5) println(numbers1) // [1, 2, 3, 4, 5] val numbers2 = mutableListOf(1, 2, 5, 6) numbers2.addAll(arrayOf(7, 8)) println(numbers2) // [1, 2, 5, 6, 7, 8] numbers2.addAll(2, setOf(3, 4)) println(numbers2) // [1, 2, 3, 4, 5, 6, 7, 8] val numbers3 = mutableListOf("one", "two") numbers3 += "three" println(numbers3) // [one, two, three] numbers3 += listOf("four", "five") println(numbers3) // [one, two, three, four, five] val numbers4 = mutableListOf(1, 2, 3, 4, 3) numbers4.remove(3) // 删除了第一个 `3` println(numbers4) // [1, 2, 4, 3] numbers4.remove(5) // 什么都没删除 println(numbers4) // [1, 2, 4, 3] val numbers5 = mutableListOf(1, 2, 3, 4) println(numbers5) // [1, 2, 3, 4] numbers5.retainAll { it >= 3 } println(numbers5) // [3, 4] numbers5.clear() println(numbers5) // [] val numbersSet = mutableSetOf("one", "two", "three", "four") numbersSet.removeAll(setOf("one", "two")) println(numbersSet) // [three, four] val numbers6 = mutableListOf("one", "two", "three", "three", "four") numbers6 -= "three" println(numbers6) // [one, two, three, four] numbers6 -= listOf("four", "five") println(numbers6) // [one, two, three] }
bsd-2-clause
d7edfcd22c281597a92a3c30e40ffd0d
31.488372
72
0.570917
3.021645
false
false
false
false
davidwhitman/deep-link-launcher
app/src/main/kotlin/com/thunderclouddev/deeplink/ui/home/HomeController.kt
1
14785
package com.thunderclouddev.deeplink.ui.home import android.animation.Animator import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.databinding.DataBindingUtil import android.support.v4.content.res.ResourcesCompat import android.support.v7.app.AlertDialog import android.support.v7.widget.LinearLayoutManager import android.text.Editable import android.text.InputType import android.text.TextWatcher import android.view.* import android.view.inputmethod.EditorInfo import android.widget.EditText import android.widget.Toast import com.bluelinelabs.conductor.RouterTransaction import com.thunderclouddev.deeplink.BaseApp import com.thunderclouddev.deeplink.R import com.thunderclouddev.deeplink.data.DeepLinkDatabase import com.thunderclouddev.deeplink.data.DeepLinkHistory import com.thunderclouddev.deeplink.data.DeepLinkInfo import com.thunderclouddev.deeplink.databinding.HomeViewBinding import com.thunderclouddev.deeplink.logging.timberkt.TimberKt import com.thunderclouddev.deeplink.ui.* import com.thunderclouddev.deeplink.ui.about.AboutController import com.thunderclouddev.deeplink.ui.edit.EditLinkDialog import com.thunderclouddev.deeplink.ui.qrcode.ViewQrCodeController import com.thunderclouddev.deeplink.ui.scanner.QrScannerController import com.thunderclouddev.deeplink.utils.* import javax.inject.Inject class HomeController : BaseController() { @Inject lateinit var deepLinkHistory: DeepLinkHistory @Inject lateinit var deepLinkLauncher: DeepLinkLauncher @Inject lateinit var jsonSerializer: JsonSerializer private var adapter: DeepLinkListAdapter? = null // TODO Don't store this in the activity, rotation will killlll it private var deepLinkViewModels: List<DeepLinkViewModel> = emptyList() private val listComparator = DeepLinkViewModel.DefaultComparator() private lateinit var binding: HomeViewBinding private var databaseListenerId: Int = 0 init { setHasOptionsMenu(true) BaseApp.component.inject(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View { super.onCreateView(inflater, container) binding = DataBindingUtil.inflate(inflater, R.layout.home_view, container, false) getActionBar().setTitle(R.string.title_activity_deep_link_history) // Alphabetical sorting for now adapter = DeepLinkListAdapter(activity!!, listComparator, createMenuItemListener(), createListItemListener()) configureListView() configureInputs() binding.deepLinkBtnGo.setOnClickListener { launchDeepLink() } binding.deepLinkPaste.setOnClickListener { pasteFromClipboard() } binding.homeFab.setOnClickListener { EditLinkDialog.Creator().newInstance().show(activity!!.fragmentManager, "EditDialogTag") } return binding.root } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.main, menu) super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.menu_scan -> { router.pushController(RouterTransaction.with(QrScannerController())) true } R.id.menu_about -> { router.pushController(RouterTransaction.with(AboutController())) true } else -> super.onOptionsItemSelected(item) } } override fun onAttach(view: View) { super.onAttach(view) binding.progressWheel.visibility = View.VISIBLE databaseListenerId = deepLinkHistory.addListener(databaseListener) } override fun onDetach(view: View) { deepLinkHistory.removeListener(databaseListenerId) super.onDetach(view) } override fun handleBack() = if (binding.deepLinkEditTextInput.text.isNullOrBlank()) { super.handleBack() } else { binding.deepLinkEditTextInput.setText(String.empty) true } private fun launchDeepLink() { val deepLinkUri = binding.deepLinkEditTextInput.text.toString().trim().getOrNullIfBlank() if (deepLinkUri.isUri()) { val uri = Uri.parse(deepLinkUri) if (!deepLinkLauncher.resolveAndFire(uri.toString(), activity!!)) { Utilities.raiseError("${activity!!.getString(R.string.error_no_activity_resolved)}: $uri", activity!!) } } else { Utilities.raiseError("${activity!!.getString(R.string.error_improper_uri)}: $deepLinkUri", activity!!) } } private fun configureListView() { binding.deepLinkList.layoutManager = LinearLayoutManager(activity!!) binding.deepLinkList.adapter = adapter binding.deepLinkList.itemAnimator } private fun showConfirmShortcutDialog(info: DeepLinkInfo) { val builder = AlertDialog.Builder(activity!!) val input = EditText(activity!!) input.inputType = InputType.TYPE_CLASS_TEXT if (info.label.isNotNullOrBlank()) { input.setText(info.label) input.setSelection(info.label?.length ?: 0) } builder.setView(input) builder.setMessage(activity!!.getString(R.string.placeShortcut_title)) builder.setNegativeButton(R.string.placeShortcut_cancel, null) builder.setPositiveButton(R.string.placeShortcut_ok) { dialog, buttonId -> val shortcutAdded = Utilities.addShortcut(info, activity!!, input.text.toString()) if (shortcutAdded) { Toast.makeText(activity, R.string.placeShortcut_success, Toast.LENGTH_LONG).show() } else { Toast.makeText(activity, R.string.placeShortcut_failure, Toast.LENGTH_LONG).show() } dialog?.dismiss() } builder.show() // Set editText margin val margin = activity!!.resources.getDimensionPixelOffset(R.dimen.spacingMedium) (input.layoutParams as ViewGroup.MarginLayoutParams).setMargins(margin, 0, margin, 0) } private fun configureInputs() { val accentColor = ResourcesCompat.getColor(activity!!.resources, R.color.accent, activity!!.theme) val disabledColor = ResourcesCompat.getColor(activity!!.resources, R.color.grayDark, activity!!.theme) binding.deepLinkEditTextInput.requestFocus() binding.deepLinkEditTextInput.setOnEditorActionListener { textView, actionId, keyEvent -> if (isDoneKey(actionId)) { launchDeepLink() true } else false } binding.deepLinkBtnClearInput.setOnClickListener { binding.deepLinkEditTextInput.text.clear() } binding.deepLinkEditTextInput.addTextChangedListener(object : TextWatcher { var oldText: String = String.empty override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) { oldText = charSequence.toString().trim() } override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) { val deepLinkString = charSequence.toString() updateListFilter(deepLinkString) val activityVal = activity ?: return val isOldStringValidUriWithHandlingActivity = isValidUriWithHandlingActivity(oldText, activityVal.packageManager) val isNewStringValidUriWithHandlingActivity = isValidUriWithHandlingActivity(deepLinkString.trim(), activityVal.packageManager) val didValidityChange = isOldStringValidUriWithHandlingActivity xor isNewStringValidUriWithHandlingActivity if (didValidityChange) { // animation! if (isNewStringValidUriWithHandlingActivity) { binding.deepLinkBtnGoForAnims.visibility = View.VISIBLE val fadeAnim = ObjectAnimator.ofFloat(binding.deepLinkBtnGoForAnims, "alpha", 1f, 0f) val scaleXAnim = ObjectAnimator.ofFloat(binding.deepLinkBtnGoForAnims, "scaleX", 1f, 2.5f) val scaleYAnim = ObjectAnimator.ofFloat(binding.deepLinkBtnGoForAnims, "scaleY", 1f, 2.5f) val animSet = AnimatorSet() animSet.playTogether(fadeAnim, scaleXAnim, scaleYAnim) animSet.duration = 160 animSet.start() animSet.addListener(object : Animator.AnimatorListener { override fun onAnimationEnd(p0: Animator?) { animSet.removeListener(this) binding.deepLinkBtnGoForAnims.visibility = View.GONE binding.deepLinkBtnGoForAnims.clearAnimation() } override fun onAnimationCancel(p0: Animator?) { } override fun onAnimationStart(p0: Animator?) { } override fun onAnimationRepeat(p0: Animator?) { } }) } binding.deepLinkBtnGo.drawable.tint(if (isNewStringValidUriWithHandlingActivity) accentColor else disabledColor) } binding.deepLinkBtnClearInput.visibility = if (charSequence.isEmpty()) View.INVISIBLE else View.VISIBLE } override fun afterTextChanged(s: Editable?) {} }) // Set disabled by default binding.deepLinkBtnGo.drawable.tint(disabledColor) } private fun updateListFilter(newDeepLinkString: String) { adapter!!.stringToHighlight = newDeepLinkString adapter!!.edit() .replaceAll(deepLinkViewModels .filter { it.deepLinkInfo.deepLink.contains(newDeepLinkString, ignoreCase = true) }) .commit() binding.deepLinkList.scrollToPosition(0) } private fun isValidUriWithHandlingActivity(deepLinkText: String, packageManager: PackageManager) = deepLinkText.isUri() && Utilities.createDeepLinkIntent(Uri.parse(deepLinkText)).hasAnyHandlingActivity(packageManager) private fun pasteFromClipboard() { val clipboardManager = activity!!.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager if (!binding.deepLinkEditTextInput.text.toString().isUri() && clipboardManager.hasPrimaryClip()) { val clipItem = clipboardManager.primaryClip.getItemAt(0) if (clipItem != null) { if (clipItem.text != null) { val clipBoardText = clipItem.text.toString() setAndSelectInput(clipBoardText) } else if (clipItem.uri != null) { val clipBoardText = clipItem.uri.toString() setAndSelectInput(clipBoardText) } } } } private val databaseListener: DeepLinkDatabase.Listener get() = object : DeepLinkDatabase.Listener { override fun onDataChanged(dataSnapshot: List<DeepLinkInfo>) { binding.progressWheel.visibility = View.GONE deepLinkViewModels = dataSnapshot.map(::DeepLinkViewModel) updateListFilter(binding.deepLinkEditTextInput.text.toString()) } } private fun isDoneKey(actionId: Int): Boolean { return actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_NEXT } private fun setAndSelectInput(text: String) { binding.deepLinkEditTextInput.setText(text) binding.deepLinkEditTextInput.setSelection(text.length) } private fun createMenuItemListener(): DeepLinkListAdapter.MenuItemListener { return object : DeepLinkListAdapter.MenuItemListener { override fun onMenuItemClick(menuItem: MenuItem, deepLinkViewModel: DeepLinkViewModel): Boolean { val deepLinkInfo = deepLinkViewModel.deepLinkInfo when (menuItem.itemId) { R.id.menu_list_item_edit -> EditLinkDialog.Creator().newInstance(deepLinkInfo) .show(activity!!.fragmentManager, "EditDialogTag") R.id.menu_list_item_qr -> router.pushController( RouterTransaction.with(ViewQrCodeController(deepLinkInfo))) R.id.menu_list_item_delete -> { deepLinkHistory.removeLink(deepLinkInfo.id) adapter!!.edit().remove(deepLinkViewModel).commit() } R.id.menu_list_item_createShortcut -> showConfirmShortcutDialog(deepLinkInfo) R.id.menulist_item_copyToClipboard -> { try { val clipboard = activity!!.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager clipboard.primaryClip = ClipData.newPlainText(deepLinkInfo.deepLink, deepLinkInfo.deepLink) Toast.makeText(activity!!, activity!!.getString(R.string.copiedToClipboard), Toast.LENGTH_SHORT).show() } catch (ignored: Exception) { TimberKt.e(ignored, { "Failed to copy text ${deepLinkInfo.deepLink} to clipboard." }) } } R.id.menu_list_item_share -> { startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).apply { this.putExtra(Intent.EXTRA_TEXT, deepLinkInfo.deepLink) this.type = "text/plain" }, activity!!.getString(R.string.list_item_share_chooserTitle))) } } return true } } } private fun createListItemListener(): BaseRecyclerViewAdapter.OnClickListener<DeepLinkViewModel> { return object : BaseRecyclerViewAdapter.OnClickListener<DeepLinkViewModel> { override fun onItemClick(item: DeepLinkViewModel) { deepLinkLauncher.resolveAndFire(item.deepLinkInfo.deepLink, activity!!) } } } }
gpl-3.0
c935a3ffd6ab6d4ed47073e9ef65f30c
41.982558
143
0.640379
5.48405
false
false
false
false
google/xplat
j2kt/jre/java/common/javaemul/lang/JavaAbstractCollection.kt
1
2239
/* * Copyright 2022 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 javaemul.lang abstract class JavaAbstractCollection<E> : AbstractMutableCollection<E>(), JavaCollection<E> { override fun addAll(c: Collection<E>): Boolean = super<JavaCollection>.addAll(c) override fun contains(e: E): Boolean = super<JavaCollection>.contains(e) override fun containsAll(c: Collection<E>): Boolean = super<JavaCollection>.containsAll(c) override fun remove(e: E): Boolean = super<JavaCollection>.remove(e) override fun removeAll(c: Collection<E>): Boolean = super<JavaCollection>.removeAll(c) override fun retainAll(c: Collection<E>): Boolean = super<JavaCollection>.retainAll(c) override fun add(e: E): Boolean = throw UnsupportedOperationException() override fun clear(): Unit = throw UnsupportedOperationException() override fun java_addAll(c: MutableCollection<out E>): Boolean = super<AbstractMutableCollection>.addAll(c) @Suppress("UNCHECKED_CAST") override fun java_contains(a: Any?): Boolean = super<AbstractMutableCollection>.contains(a as E) @Suppress("UNCHECKED_CAST") override fun java_containsAll(c: MutableCollection<*>): Boolean = super<AbstractMutableCollection>.containsAll(c as MutableCollection<E>) @Suppress("UNCHECKED_CAST") override fun java_remove(a: Any?): Boolean = throw UnsupportedOperationException() @Suppress("UNCHECKED_CAST") override fun java_removeAll(c: MutableCollection<*>): Boolean = super<AbstractMutableCollection>.removeAll(c as MutableCollection<E>) @Suppress("UNCHECKED_CAST") override fun java_retainAll(c: MutableCollection<*>): Boolean = super<AbstractMutableCollection>.retainAll(c as MutableCollection<E>) }
apache-2.0
5b038c2f441e1742fa89bbf735ca6808
39.709091
98
0.753908
4.50503
false
false
false
false
DevCharly/kotlin-ant-dsl
src/main/kotlin/com/devcharly/kotlin/ant/selectors/orselector.kt
1
5439
/* * Copyright 2016 Karl Tauber * * 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.devcharly.kotlin.ant import org.apache.tools.ant.types.selectors.AndSelector import org.apache.tools.ant.types.selectors.ContainsRegexpSelector import org.apache.tools.ant.types.selectors.ContainsSelector import org.apache.tools.ant.types.selectors.DateSelector import org.apache.tools.ant.types.selectors.DependSelector import org.apache.tools.ant.types.selectors.DepthSelector import org.apache.tools.ant.types.selectors.DifferentSelector import org.apache.tools.ant.types.selectors.ExecutableSelector import org.apache.tools.ant.types.selectors.ExtendSelector import org.apache.tools.ant.types.selectors.FileSelector import org.apache.tools.ant.types.selectors.FilenameSelector import org.apache.tools.ant.types.selectors.MajoritySelector import org.apache.tools.ant.types.selectors.NoneSelector import org.apache.tools.ant.types.selectors.NotSelector import org.apache.tools.ant.types.selectors.OrSelector import org.apache.tools.ant.types.selectors.OwnedBySelector import org.apache.tools.ant.types.selectors.PresentSelector import org.apache.tools.ant.types.selectors.ReadableSelector import org.apache.tools.ant.types.selectors.SelectSelector import org.apache.tools.ant.types.selectors.SizeSelector import org.apache.tools.ant.types.selectors.SymlinkSelector import org.apache.tools.ant.types.selectors.TypeSelector import org.apache.tools.ant.types.selectors.WritableSelector import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector /****************************************************************************** DO NOT EDIT - this file was generated ******************************************************************************/ interface IOrSelectorNested : INestedComponent { fun or( error: String? = null, nested: (KOrSelector.() -> Unit)? = null) { _addOrSelector(OrSelector().apply { component.project.setProjectReference(this); _init(error, nested) }) } fun _addOrSelector(value: OrSelector) } fun OrSelector._init( error: String?, nested: (KOrSelector.() -> Unit)?) { if (error != null) setError(error) if (nested != null) nested(KOrSelector(this)) } class KOrSelector(override val component: OrSelector) : IFileSelectorNested, ISelectSelectorNested, IAndSelectorNested, IOrSelectorNested, INotSelectorNested, INoneSelectorNested, IMajoritySelectorNested, IDateSelectorNested, ISizeSelectorNested, IFilenameSelectorNested, IExtendSelectorNested, IContainsSelectorNested, IPresentSelectorNested, IDepthSelectorNested, IDependSelectorNested, IDifferentSelectorNested, ITypeSelectorNested, IContainsRegexpSelectorNested, IModifiedSelectorNested, IReadableSelectorNested, IWritableSelectorNested, IExecutableSelectorNested, ISymlinkSelectorNested, IOwnedBySelectorNested { override fun _addFileSelector(value: FileSelector) = component.add(value) override fun _addSelectSelector(value: SelectSelector) = component.addSelector(value) override fun _addAndSelector(value: AndSelector) = component.addAnd(value) override fun _addOrSelector(value: OrSelector) = component.addOr(value) override fun _addNotSelector(value: NotSelector) = component.addNot(value) override fun _addNoneSelector(value: NoneSelector) = component.addNone(value) override fun _addMajoritySelector(value: MajoritySelector) = component.addMajority(value) override fun _addDateSelector(value: DateSelector) = component.addDate(value) override fun _addSizeSelector(value: SizeSelector) = component.addSize(value) override fun _addFilenameSelector(value: FilenameSelector) = component.addFilename(value) override fun _addExtendSelector(value: ExtendSelector) = component.addCustom(value) override fun _addContainsSelector(value: ContainsSelector) = component.addContains(value) override fun _addPresentSelector(value: PresentSelector) = component.addPresent(value) override fun _addDepthSelector(value: DepthSelector) = component.addDepth(value) override fun _addDependSelector(value: DependSelector) = component.addDepend(value) override fun _addDifferentSelector(value: DifferentSelector) = component.addDifferent(value) override fun _addTypeSelector(value: TypeSelector) = component.addType(value) override fun _addContainsRegexpSelector(value: ContainsRegexpSelector) = component.addContainsRegexp(value) override fun _addModifiedSelector(value: ModifiedSelector) = component.addModified(value) override fun _addReadableSelector(value: ReadableSelector) = component.addReadable(value) override fun _addWritableSelector(value: WritableSelector) = component.addWritable(value) override fun _addExecutableSelector(value: ExecutableSelector) = component.addExecutable(value) override fun _addSymlinkSelector(value: SymlinkSelector) = component.addSymlink(value) override fun _addOwnedBySelector(value: OwnedBySelector) = component.addOwnedBy(value) }
apache-2.0
e7ea67a714038ff2bf1f00fff223171a
43.581967
108
0.793344
4.049888
false
false
false
false
JackParisi/DroidBox
droidbox/src/main/java/com/github/giacomoparisi/droidbox/binding/TextAdapter.kt
1
2836
package com.github.giacomoparisi.droidbox.binding import androidx.databinding.BindingAdapter import android.graphics.Paint import android.text.Html import android.widget.TextView import com.github.giacomoparisi.droidbox.utility.formatDateString import java.util.* /** * Created by Giacomo Parisi on 11/09/2017. * https://github.com/giacomoParisi */ /** * * Format and set an HTML text in the textView * * @param view The textView that need the html text * @param html The html string */ @BindingAdapter("text_html") fun bindTextHtml(view: TextView, html: String?) { if (html != null) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { view.text = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY) } else { view.text = Html.fromHtml(html) } } } /** * * Set text from resource id * * @param view The textView that need the text * @param res id of the resource */ @BindingAdapter("text_res") fun bindTextRes(view: TextView, res: Int?) = if (res != null && res != 0) { view.setText(res) } else { view.setText("") } /** * * Underline the text * * @param view The text view that has the text to underline * @param enable Set to true to enable underline */ @BindingAdapter("text_underline") fun bindTextUnderline(view: TextView, enable: Boolean) { if (enable) { view.paintFlags = view.paintFlags or Paint.UNDERLINE_TEXT_FLAG } else { view.paintFlags = view.paintFlags xor Paint.UNDERLINE_TEXT_FLAG } } /** * * Change the date format of a date string, from original to target, and set it as text in the view * * @param view The text view that need the formatted date * @param date The date that needs to be formatted in the target format * @param originalFormat The original date format * @param targetFormat The target format of the date desired for viewing * @param originalLocale The locale object of the original date, used for parsing the original date (default is current phone locale) * @param targetLocale The locale object for the target date, used for the conversion (default is current phone locale) */ @BindingAdapter( "text_date", "text_date_placeholder", "text_date_error_placeholder", "text_date_original_format", "text_date_target_format", "text_date_original_locale", "text_date_target_locale", requireAll = false) fun bindTextDate( view: TextView, date: String?, placeholder: String?, errorPlaceholder: String?, originalFormat: String?, targetFormat: String?, originalLocale: Locale?, targetLocale: Locale?) { view.text = formatDateString(date, placeholder, errorPlaceholder, originalFormat, targetFormat, originalLocale, targetLocale) }
apache-2.0
bd7bd2540e50a8938838d9310648244d
28.852632
133
0.684767
3.971989
false
false
false
false
nisrulz/android-examples
GitVersioning/app/src/main/java/github/nisrulz/example/git_versioning/ui/theme/Theme.kt
1
1139
package github.nisrulz.example.git_versioning.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun GitVersioningTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit ) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
apache-2.0
b5d09e6adcb12f521b80f676d10e95cb
23.255319
54
0.703248
4.76569
false
false
false
false
robinverduijn/gradle
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/NamedDomainObjectContainerExtensionsTest.kt
1
9126
package org.gradle.kotlin.dsl import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.inOrder import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import org.gradle.api.Action import org.gradle.api.NamedDomainObjectContainer import org.gradle.api.NamedDomainObjectProvider import org.gradle.api.PolymorphicDomainObjectContainer import org.gradle.api.Task import org.gradle.api.tasks.Delete import org.gradle.api.tasks.JavaExec import org.gradle.api.tasks.TaskContainer import org.gradle.kotlin.dsl.support.uncheckedCast import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.CoreMatchers.sameInstance import org.hamcrest.MatcherAssert.assertThat import org.junit.Test class NamedDomainObjectContainerExtensionsTest { data class DomainObject(var foo: String? = null, var bar: Boolean? = null) @Test fun `can use monomorphic container api`() { val alice = DomainObject() val bob = DomainObject() val john = DomainObject() val marty = mockDomainObjectProviderFor(DomainObject()) val doc = mockDomainObjectProviderFor(DomainObject()) val container = mock<NamedDomainObjectContainer<DomainObject>> { on { getByName("alice") } doReturn alice on { create("bob") } doReturn bob on { maybeCreate("john") } doReturn john on { named("marty") } doReturn marty on { register("doc") } doReturn doc } // regular syntax container.getByName("alice") { it.foo = "alice-foo" } container.create("bob") { it.foo = "bob-foo" } container.maybeCreate("john") container.named("marty") container.register("doc") // invoke syntax container { getByName("alice") { it.foo = "alice-foo" } create("bob") { it.foo = "bob-foo" } maybeCreate("john") named("marty") register("doc") } } @Test fun `can use polymorphic container api`() { val alice = DomainObjectBase.Foo() val bob = DomainObjectBase.Bar() val default = DomainObjectBase.Default() val marty = DomainObjectBase.Foo() val martyProvider = mockDomainObjectProviderFor(marty) val doc = DomainObjectBase.Bar() val docProvider = mockDomainObjectProviderFor<DomainObjectBase>(doc) val docProviderAsBarProvider = uncheckedCast<NamedDomainObjectProvider<DomainObjectBase.Bar>>(docProvider) val container = mock<PolymorphicDomainObjectContainer<DomainObjectBase>> { on { getByName("alice") } doReturn alice on { maybeCreate("alice", DomainObjectBase.Foo::class.java) } doReturn alice on { create(eq("bob"), eq(DomainObjectBase.Bar::class.java), any<Action<DomainObjectBase.Bar>>()) } doReturn bob on { create("john", DomainObjectBase.Default::class.java) } doReturn default onNamedWithAction("marty", DomainObjectBase.Foo::class, martyProvider) on { register(eq("doc"), eq(DomainObjectBase.Bar::class.java)) } doReturn docProviderAsBarProvider onRegisterWithAction("doc", DomainObjectBase.Bar::class, docProviderAsBarProvider) } // regular syntax container.getByName<DomainObjectBase.Foo>("alice") { foo = "alice-foo-2" } container.maybeCreate<DomainObjectBase.Foo>("alice") container.create<DomainObjectBase.Bar>("bob") { bar = true } container.create("john") container.named("marty", DomainObjectBase.Foo::class) { foo = "marty-foo" } container.named<DomainObjectBase.Foo>("marty") { foo = "marty-foo-2" } container.register<DomainObjectBase.Bar>("doc") { bar = true } // invoke syntax container { getByName<DomainObjectBase.Foo>("alice") { foo = "alice-foo-2" } maybeCreate<DomainObjectBase.Foo>("alice") create<DomainObjectBase.Bar>("bob") { bar = true } create("john") named("marty", DomainObjectBase.Foo::class) { foo = "marty-foo" } named<DomainObjectBase.Foo>("marty") { foo = "marty-foo-2" } register<DomainObjectBase.Bar>("doc") { bar = true } } } @Test fun `can configure monomorphic container`() { val alice = DomainObject() val aliceProvider = mockDomainObjectProviderFor(alice) val bob = DomainObject() val bobProvider = mockDomainObjectProviderFor(bob) val container = mock<NamedDomainObjectContainer<DomainObject>> { on { named("alice") } doReturn aliceProvider on { named("bob") } doReturn bobProvider } container { "alice" { foo = "alice-foo" } "alice" { // will configure the same object as the previous block bar = true } "bob" { foo = "bob-foo" bar = false } } assertThat( alice, equalTo(DomainObject("alice-foo", true))) assertThat( bob, equalTo(DomainObject("bob-foo", false))) } sealed class DomainObjectBase { data class Foo(var foo: String? = null) : DomainObjectBase() data class Bar(var bar: Boolean? = null) : DomainObjectBase() data class Default(val isDefault: Boolean = true) : DomainObjectBase() } @Test fun `can configure polymorphic container`() { val alice = DomainObjectBase.Foo() val aliceProvider = mockDomainObjectProviderFor(alice) val bob = DomainObjectBase.Bar() val bobProvider = mockDomainObjectProviderFor(bob) val default: DomainObjectBase = DomainObjectBase.Default() val defaultProvider = mockDomainObjectProviderFor(default) val container = mock<PolymorphicDomainObjectContainer<DomainObjectBase>> { onNamedWithAction("alice", DomainObjectBase.Foo::class, aliceProvider) on { named(eq("bob"), eq(DomainObjectBase.Bar::class.java)) } doReturn bobProvider on { named(eq("jim")) } doReturn defaultProvider on { named(eq("steve")) } doReturn defaultProvider } container { val a = "alice"(DomainObjectBase.Foo::class) { foo = "foo" } val b = "bob"(type = DomainObjectBase.Bar::class) val j = "jim" {} val s = "steve"() // can invoke without a block, but must invoke assertThat(a.get(), sameInstance(alice)) assertThat(b.get(), sameInstance(bob)) assertThat(j.get(), sameInstance(default)) assertThat(s.get(), sameInstance(default)) } assertThat( alice, equalTo(DomainObjectBase.Foo("foo"))) assertThat( bob, equalTo(DomainObjectBase.Bar())) } @Test fun `can create and configure tasks`() { val clean = mock<Delete>() val cleanProvider = mockTaskProviderFor(clean) val tasks = mock<TaskContainer> { on { create(eq("clean"), eq(Delete::class.java), any<Action<Delete>>()) } doReturn clean on { getByName("clean") } doReturn clean onNamedWithAction("clean", Delete::class, cleanProvider) } tasks { create<Delete>("clean") { delete("some") } getByName<Delete>("clean") { delete("stuff") } "clean"(type = Delete::class) { delete("things") } } tasks.getByName<Delete>("clean") { delete("build") } inOrder(clean) { verify(clean).delete("stuff") verify(clean).delete("things") verify(clean).delete("build") } } @Test fun `can create element within configuration block via delegated property`() { val tasks = mock<TaskContainer> { on { create("hello") } doReturn mock<Task>() } tasks { @Suppress("unused_variable") val hello by creating } verify(tasks).create("hello") } @Test fun `can get element of specific type within configuration block via delegated property`() { val task = mock<JavaExec>() val tasks = mock<TaskContainer> { on { getByName("hello") } doReturn task } @Suppress("unused_variable") tasks { val hello by getting(JavaExec::class) } verify(tasks).getByName("hello") } }
apache-2.0
abcb89a83f93fa2b00b85c6b3acdee33
30.797909
124
0.579005
5.058758
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/smartspace/CardPagerAdapter.kt
1
3489
package app.lawnchair.smartspace import android.content.Context import android.util.SparseArray import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.viewpager.widget.PagerAdapter import app.lawnchair.smartspace.model.SmartspaceTarget import com.android.launcher3.R import com.android.launcher3.util.Themes class CardPagerAdapter(context: Context) : PagerAdapter() { private val currentTextColor = Themes.getAttrColor(context, R.attr.workspaceTextColor) private val targets = mutableListOf<SmartspaceTarget>() private var smartspaceTargets = targets private val holders = SparseArray<ViewHolder>() fun setTargets(newTargets: List<SmartspaceTarget>) { targets.clear() targets.addAll(newTargets) notifyDataSetChanged() } override fun instantiateItem(container: ViewGroup, position: Int): ViewHolder { val target = smartspaceTargets[position] val card = createBaseCard(container, getFeatureType(target)) val viewHolder = ViewHolder(position, card, target) onBindViewHolder(viewHolder) container.addView(card) holders.put(position, viewHolder) return viewHolder } override fun destroyItem(container: ViewGroup, position: Int, obj: Any) { val viewHolder = obj as ViewHolder container.removeView(viewHolder.card) if (holders[position] == viewHolder) { holders.remove(position) } } fun getCardAtPosition(position: Int) = holders[position]?.card override fun getItemPosition(obj: Any): Int { val viewHolder = obj as ViewHolder val target = getTargetAtPosition(viewHolder.position) if (viewHolder.target === target) { return POSITION_UNCHANGED } if (target == null || getFeatureType(target) !== getFeatureType(viewHolder.target) || target.id != viewHolder.target.id ) { return POSITION_NONE } viewHolder.target = target onBindViewHolder(viewHolder) return POSITION_UNCHANGED } private fun getTargetAtPosition(position: Int): SmartspaceTarget? { if (position !in 0 until smartspaceTargets.size) { return null } return smartspaceTargets[position] } private fun onBindViewHolder(viewHolder: ViewHolder) { val target = smartspaceTargets[viewHolder.position] val card = viewHolder.card card.setSmartspaceTarget(target, smartspaceTargets.size > 1) card.setPrimaryTextColor(currentTextColor) } override fun getCount() = smartspaceTargets.size override fun isViewFromObject(view: View, obj: Any): Boolean { return view === (obj as ViewHolder).card } private fun createBaseCard( container: ViewGroup, featureType: SmartspaceTarget.FeatureType ): BcSmartspaceCard { val layout = when (featureType) { SmartspaceTarget.FeatureType.FEATURE_WEATHER -> R.layout.smartspace_card_date else -> R.layout.smartspace_card } return LayoutInflater.from(container.context) .inflate(layout, container, false) as BcSmartspaceCard } private fun getFeatureType(target: SmartspaceTarget) = target.featureType class ViewHolder internal constructor( val position: Int, val card: BcSmartspaceCard, var target: SmartspaceTarget ) }
gpl-3.0
eedd4c7c92fc99df1b17204235c84c45
33.205882
90
0.684437
5.049204
false
false
false
false
googlemaps/android-samples
ApiDemos/kotlin/app/src/v3/java/com/example/kotlindemos/polyline/PolylineSpansControlFragment.kt
1
7395
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.kotlindemos.polyline import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CompoundButton import android.widget.RadioGroup import android.widget.SeekBar import android.widget.TextView import com.example.kotlindemos.R import com.google.android.libraries.maps.model.BitmapDescriptorFactory import com.google.android.libraries.maps.model.Polyline import com.google.android.libraries.maps.model.StrokeStyle import com.google.android.libraries.maps.model.StyleSpan import com.google.android.libraries.maps.model.TextureStyle /** * Fragment with span count UI controls for [com.google.android.libraries.maps.model.Polyline], to * be used in ViewPager. * * * When span count is updated from the slider, the selected polyline will be updated with that * number of spans. Each span will either have polyline color or the inverted color, and span * lengths are equally divided by number of segments in the polyline. */ class PolylineSpansControlFragment : PolylineControlFragment(), SeekBar.OnSeekBarChangeListener, RadioGroup.OnCheckedChangeListener { private lateinit var spanCountBar: SeekBar private lateinit var spanCountTextView: TextView private lateinit var gradientToggle: CompoundButton private lateinit var polylineStampStyleRadioGroup: RadioGroup private var spanCount = 0 private val polylineSpanCounts = mutableMapOf<Polyline, Int>() private val polylineGradientStates = mutableMapOf<Polyline, Boolean>() private var isLiteMode = false private var selectedStampStyleId = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) isLiteMode = arguments?.getBoolean(IS_LITE_MODE_KEY) ?: false } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, bundle: Bundle?): View { val view = inflater.inflate(R.layout.polyline_spans_control_fragment, container, false) spanCountBar = view.findViewById(R.id.spansSeekBar) spanCountBar.max = SPAN_COUNT_MAX spanCountBar.setOnSeekBarChangeListener(this) spanCountTextView = view.findViewById(R.id.spansTextView) gradientToggle = view.findViewById(R.id.gradientToggle) gradientToggle.setOnCheckedChangeListener { _, isChecked -> polyline?.let { polylineGradientStates[it] = isChecked } updateSpans() } polylineStampStyleRadioGroup = view.findViewById(R.id.polyline_stamp_style_radio_group) polylineStampStyleRadioGroup.visibility = View.INVISIBLE if (isLiteMode) { gradientToggle.visibility = View.INVISIBLE polylineStampStyleRadioGroup.visibility = View.INVISIBLE } polylineSpanCounts.clear() polylineGradientStates.clear() selectedStampStyleId = 0 polylineStampStyleRadioGroup.setOnCheckedChangeListener(this) return view } override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { spanCount = progress polyline?.let { polylineSpanCounts.put(it, spanCount) } spanCountTextView.text = spanCount.toString() updateSpans() } private fun generateSpans(count: Int): List<StyleSpan> { val polyline = polyline ?: return emptyList() val invertedPolylineColor: Int = polyline.color xor 0x00ffffff val newSpans = mutableListOf<StyleSpan>() for (i in 0 until count) { val color = if (i % 2 == 0) polyline.color else invertedPolylineColor val segmentCount = (polyline.points.size - 1).toDouble() / count val strokeStyleBuilder: StrokeStyle.Builder = if (gradientToggle.isChecked) StrokeStyle.gradientBuilder(polyline.color, invertedPolylineColor) else StrokeStyle.colorBuilder(color) if (selectedStampStyleId == R.id.polyline_texture_style) { strokeStyleBuilder.stamp( TextureStyle.newBuilder(BitmapDescriptorFactory.fromResource(R.drawable.ook)) .build()) } newSpans.add(StyleSpan(strokeStyleBuilder.build(), segmentCount)) } return newSpans } private fun updateSpans() { val polyline = polyline ?: return polyline.setSpans(generateSpans(spanCount)) } override fun onStartTrackingTouch(seekBar: SeekBar?) { // Don't do anything here. } override fun onStopTrackingTouch(seekBar: SeekBar?) { // Don't do anything here. } override fun refresh() { val polyline = polyline if (polyline == null) { spanCountBar.isEnabled = false spanCountBar.progress = 0 spanCountTextView.text = "" gradientToggle.isChecked = false gradientToggle.isEnabled = false polylineStampStyleRadioGroup.clearCheck() polylineStampStyleRadioGroup.isEnabled = false return } if (!polylineSpanCounts.containsKey(polyline)) { polylineSpanCounts[polyline] = 0 } if (!polylineGradientStates.containsKey(polyline)) { polylineGradientStates[polyline] = false } spanCountBar.isEnabled = true spanCountBar.progress = polylineSpanCounts[polyline] ?: 0 spanCountTextView.text = polylineSpanCounts[polyline].toString() if (!isLiteMode) { gradientToggle.isEnabled = true gradientToggle.isChecked = polylineGradientStates[polyline] ?: false polylineStampStyleRadioGroup.isEnabled = true polylineStampStyleRadioGroup.check(selectedStampStyleId) } } override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) { selectedStampStyleId = checkedId updateSpans() } /** * Resets the span states of a polyline. * * * Because there's no getter for polyline spans, this is needed for the polyline demo * activity * to update span control UI components. */ fun resetSpanState(polyline: Polyline?) { polylineSpanCounts.remove(polyline) polylineGradientStates.remove(polyline) } companion object { private const val IS_LITE_MODE_KEY = "isLiteMode" private const val SPAN_COUNT_MAX = 20 fun newInstance(isLiteMode: Boolean): PolylineSpansControlFragment { val polylineSpansControlFragment = PolylineSpansControlFragment() val args = Bundle() args.putBoolean(IS_LITE_MODE_KEY, isLiteMode) polylineSpansControlFragment.arguments = args return polylineSpansControlFragment } } }
apache-2.0
a93eee4ff1d56e123d5859042ba26c2c
39.637363
191
0.692901
5.255864
false
false
false
false
icarumbas/bagel
core/src/ru/icarumbas/bagel/engine/world/RoomWorld.kt
1
1627
package ru.icarumbas.bagel.engine.world import ru.icarumbas.bagel.engine.io.RoomInfo import ru.icarumbas.bagel.engine.io.WorldIO import ru.icarumbas.bagel.engine.io.WorldInfo import ru.icarumbas.bagel.engine.resources.ResourceManager import ru.icarumbas.bagel.view.renderer.MapRenderer class RoomWorld( private val assets: ResourceManager, private val mapRenderer: MapRenderer ) { lateinit var rooms: ArrayList<Room> lateinit var mesh: Array<IntArray> var currentMapId = -10 set(value) { field = value mapRenderer.renderer.map = assets.getTiledMap(rooms[value].path) } fun createNewWorld(){ RoomWorldCreator(50, assets).also { rooms = it.createWorld() mesh = it.mesh } } fun loadWorld(worldIO: WorldIO){ with (worldIO.loadWorldInfo()) { [email protected] = rooms [email protected] = mesh } } fun saveWorld(worldIO: WorldIO){ with(worldIO) { saveInfo(WorldInfo(rooms, mesh)) saveInfo(RoomInfo(canContinue = true)) } } fun getMapPath(id: Int = currentMapId) = rooms[id].path fun getRoomWidth(id: Int = currentMapId) = rooms[id].width fun getRoomHeight(id: Int = currentMapId) = rooms[id].height fun getRoomPass(pass: Int, id: Int = currentMapId) = rooms[id].passes[pass] fun getRoomMeshCoordinate(cell: Int, id: Int = currentMapId) = rooms[id].meshCoords[cell] fun getRoomForMeshCoordinate(x: Int, y: Int) = rooms.find { it.meshCoords[0] == x && it.meshCoords[1] == y } }
apache-2.0
ab74daf8b9fa194ff26342b807c14930
26.59322
112
0.648433
3.883055
false
false
false
false
icarumbas/bagel
core/src/ru/icarumbas/bagel/engine/components/other/AIComponent.kt
1
464
package ru.icarumbas.bagel.engine.components.other import com.badlogic.ashley.core.Component import com.badlogic.ashley.core.Entity class AIComponent(var refreshSpeed: Float, var attackDistance: Float, var entityTarget: Entity) : Component { var isTargetRight: Boolean = true var isTargetHigher: Boolean = true var isTargetNear: Boolean = false var isTargetEqualX: Boolean = false var appeared: Boolean = false var coldown: Float = 0f }
apache-2.0
29600f1eba5295f5ec89c6ba19361756
30
109
0.758621
4.106195
false
false
false
false
chrisbanes/tivi
common/ui/compose/src/main/java/app/tivi/common/compose/EntryGrid.kt
1
8524
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 app.tivi.common.compose import androidx.compose.animation.Crossfade import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.ContentAlpha import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.LocalContentAlpha import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.paging.LoadState import androidx.paging.compose.LazyPagingItems import app.tivi.common.compose.theme.AppBarAlphas import app.tivi.common.compose.ui.PlaceholderPosterCard import app.tivi.common.compose.ui.PosterCard import app.tivi.common.compose.ui.RefreshButton import app.tivi.common.compose.ui.SwipeDismissSnackbarHost import app.tivi.common.compose.ui.plus import app.tivi.data.Entry import app.tivi.data.resultentities.EntryWithShow import com.google.accompanist.insets.ui.Scaffold import com.google.accompanist.insets.ui.TopAppBar import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.SwipeRefreshIndicator import com.google.accompanist.swiperefresh.rememberSwipeRefreshState import app.tivi.common.ui.resources.R as UiR @OptIn(ExperimentalFoundationApi::class) @Composable fun <E : Entry> EntryGrid( lazyPagingItems: LazyPagingItems<out EntryWithShow<E>>, title: String, onNavigateUp: () -> Unit, onOpenShowDetails: (Long) -> Unit, modifier: Modifier = Modifier ) { val scaffoldState = rememberScaffoldState() lazyPagingItems.loadState.prependErrorOrNull()?.let { message -> LaunchedEffect(message) { scaffoldState.snackbarHostState.showSnackbar(message.message) } } lazyPagingItems.loadState.appendErrorOrNull()?.let { message -> LaunchedEffect(message) { scaffoldState.snackbarHostState.showSnackbar(message.message) } } lazyPagingItems.loadState.refreshErrorOrNull()?.let { message -> LaunchedEffect(message) { scaffoldState.snackbarHostState.showSnackbar(message.message) } } Scaffold( scaffoldState = scaffoldState, topBar = { EntryGridAppBar( title = title, onNavigateUp = onNavigateUp, refreshing = lazyPagingItems.loadState.refresh == LoadState.Loading, onRefreshActionClick = { lazyPagingItems.refresh() }, modifier = Modifier.fillMaxWidth() ) }, snackbarHost = { snackbarHostState -> SwipeDismissSnackbarHost( hostState = snackbarHostState, modifier = Modifier .padding(horizontal = Layout.bodyMargin) .fillMaxWidth() ) }, modifier = modifier ) { paddingValues -> SwipeRefresh( state = rememberSwipeRefreshState( isRefreshing = lazyPagingItems.loadState.refresh == LoadState.Loading ), onRefresh = { lazyPagingItems.refresh() }, indicatorPadding = paddingValues, indicator = { state, trigger -> SwipeRefreshIndicator( state = state, refreshTriggerDistance = trigger, scale = true ) } ) { val columns = Layout.columns val bodyMargin = Layout.bodyMargin val gutter = Layout.gutter LazyVerticalGrid( columns = GridCells.Fixed(columns / 2), contentPadding = paddingValues + PaddingValues(horizontal = bodyMargin, vertical = gutter), horizontalArrangement = Arrangement.spacedBy(gutter), verticalArrangement = Arrangement.spacedBy(gutter), modifier = Modifier .bodyWidth() .fillMaxHeight() ) { items( items = lazyPagingItems, key = { it.show.id } ) { entry -> val mod = Modifier .animateItemPlacement() .aspectRatio(2 / 3f) .fillMaxWidth() if (entry != null) { PosterCard( show = entry.show, poster = entry.poster, onClick = { onOpenShowDetails(entry.show.id) }, modifier = mod ) } else { PlaceholderPosterCard(mod) } } if (lazyPagingItems.loadState.append == LoadState.Loading) { fullSpanItem { Box( Modifier .fillMaxWidth() .padding(24.dp) ) { CircularProgressIndicator(Modifier.align(Alignment.Center)) } } } } } } } @Composable private fun EntryGridAppBar( title: String, refreshing: Boolean, onNavigateUp: () -> Unit, onRefreshActionClick: () -> Unit, modifier: Modifier = Modifier ) { TopAppBar( navigationIcon = { IconButton(onClick = onNavigateUp) { Icon( Icons.Default.ArrowBack, contentDescription = stringResource(UiR.string.cd_navigate_up) ) } }, backgroundColor = MaterialTheme.colors.surface.copy( alpha = AppBarAlphas.translucentBarAlpha() ), contentColor = MaterialTheme.colors.onSurface, contentPadding = WindowInsets.statusBars.asPaddingValues(), modifier = modifier, title = { Text(text = title) }, actions = { CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { // This button refresh allows screen-readers, etc to trigger a refresh. // We only show the button to trigger a refresh, not to indicate that // we're currently refreshing, otherwise we have 4 indicators showing the // same thing. Crossfade( targetState = refreshing, modifier = Modifier.align(Alignment.CenterVertically) ) { isRefreshing -> if (!isRefreshing) { RefreshButton(onClick = onRefreshActionClick) } } } } ) }
apache-2.0
295c4bb3d10d7d023c8c1d72ddfe28c2
37.745455
89
0.62283
5.517152
false
false
false
false
alygin/intellij-rust
toml/src/main/kotlin/org/toml/ide/TomlCommenter.kt
14
504
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.toml.ide import com.intellij.lang.Commenter class TomlCommenter : Commenter { override fun getLineCommentPrefix(): String = "#" override fun getBlockCommentPrefix(): String? = null override fun getBlockCommentSuffix(): String? = null override fun getCommentedBlockCommentPrefix(): String? = null override fun getCommentedBlockCommentSuffix(): String? = null }
mit
268dff7fc0b81902f97c406bde0bd77e
27
69
0.736111
4.8
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/RsArrayExpr.kt
8
774
/* * 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.RsArrayExpr import org.rust.lang.core.psi.RsExpr /** * Extracts the expression that defines the array initializer. */ val RsArrayExpr.initializer: RsExpr? get() = if (semicolon != null && exprList.size == 2) exprList[0] else null /** * Extracts the expression that defines the size of an array. */ val RsArrayExpr.sizeExpr: RsExpr? get() = if (semicolon != null && exprList.size == 2) exprList[1] else null /** * Extracts the expression list that defines the elements of an array. */ val RsArrayExpr.arrayElements: List<RsExpr>? get() = if (semicolon == null) exprList else null
mit
764cb9307306b0460c3201e4743c16a8
27.666667
78
0.70801
3.721154
false
false
false
false
weibaohui/korm
src/main/kotlin/com/sdibt/korm/core/oql/TableNameField.kt
1
2365
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sdibt.korm.core.oql import com.sdibt.korm.core.entity.EntityBase /** * 表名称字段类型。OQL内部使用 */ class TableNameField { /** * 获取表名称 */ val name: String? get() { return entity.tableName() } /** * 原始字段名 */ var field: String /** * 关联的实体类 */ var entity: EntityBase /** * 在一系列字段使用中的索引号或者当前字段在实体类字段名字数组中的索引 */ var index: Int = 0 /** * 字段对应的值 */ var fieldValue: Any? = null /** * 在sql语句中使用的字段名 */ var sqlFieldName: String? = null get() { if (field == null) { return this.field } else { return field } } constructor(field: String, entity: EntityBase) { this.field = field this.entity = entity } constructor(field: String, entity: EntityBase, index: Int) { this.field = field this.entity = entity this.index = index } constructor(field: String, entity: EntityBase, fieldValue: Any?) { this.field = field this.entity = entity this.fieldValue = fieldValue } constructor(field: String, entity: EntityBase, index: Int, fieldValue: Any?) { this.field = field this.entity = entity this.index = index this.fieldValue = fieldValue } }
apache-2.0
cdd7b5a25238c1c4a8a36259ad1a642d
21.773196
82
0.60344
4.06814
false
false
false
false
Raniz85/ffbe-grinder
src/main/kotlin/se/raneland/ffbe/state/transition/ImageRegionTransitionTest.kt
1
1196
/* * Copyright (c) 2017, Daniel Raniz Raneland */ package se.raneland.ffbe.state.transition import mu.KLogging import se.raneland.ffbe.image.ImageRegion import se.raneland.ffbe.state.GameState import java.nio.file.Files import java.nio.file.Paths import javax.imageio.ImageIO /** * @author Raniz * @since 2017-04-14. */ class ImageRegionTransitionTest : TransitionTest { companion object : KLogging() val region: ImageRegion val name: String constructor(name: String, x: Int, y: Int) { this.name = name val path = Paths.get(name).takeIf { Files.exists(it) } val image = if (path != null) { ImageIO.read(path.toUri().toURL()) } else { val stream = ImageRegionTransitionTest::class.java.getResourceAsStream("/images/${name}") ?: error("Image ${name} could not be found") stream.use { ImageIO.read(it) } } region = ImageRegion(image, x, y) } override fun matches(gameState: GameState): Boolean { logger.trace("Testing image region ${name}@(${region.x},${region.y}) against game state") return region.matches(gameState.screen) } }
mit
ebb7a43a49d8629c2f3fa3b0542ca75e
25.577778
146
0.636288
3.895765
false
true
false
false
http4k/http4k
http4k-opentelemetry/src/test/kotlin/org/http4k/filter/helpers.kt
1
3281
package org.http4k.filter import com.natpryce.hamkrest.MatchResult import com.natpryce.hamkrest.Matcher import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.sdk.OpenTelemetrySdk import io.opentelemetry.sdk.metrics.SdkMeterProvider import io.opentelemetry.sdk.metrics.data.MetricData import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader import org.http4k.core.Method import org.http4k.core.Status /** * Use the InMemory exporter to get the recorded metrics from the global state. */ val inMemoryMetricReader: InMemoryMetricReader = InMemoryMetricReader.create() fun setupOpenTelemetryMeterProvider() { inMemoryMetricReader.collectAllMetrics() OpenTelemetrySdk.builder() .setMeterProvider( SdkMeterProvider.builder() .registerMetricReader(inMemoryMetricReader) .build() ) .buildAndRegisterGlobal() } fun exportMetricsFromOpenTelemetry(): List<MetricData> = inMemoryMetricReader.collectAllMetrics().toList() fun hasRequestTimer(count: Int, value: Double, attributes: Attributes, name: String = "http.server.request.latency") = object : Matcher<List<MetricData>> { override val description = name override fun invoke(actual: List<MetricData>): MatchResult { val summary = actual .first { it.name == name } .histogramData .points .first { it.attributes == attributes } return if ( summary.count != count.toLong() && summary.epochNanos - summary.startEpochNanos == value.toLong() ) MatchResult.Mismatch(actual.toString()) else MatchResult.Match } } fun hasRequestCounter(count: Int, attributes: Attributes, name: String = "http.server.request.count") = object : Matcher<List<MetricData>> { override val description = name override fun invoke(actual: List<MetricData>): MatchResult { val counter = actual .first { it.name == name } .longSumData .points .first { it.attributes == attributes } return if (counter.value == count.toLong()) MatchResult.Match else MatchResult.Mismatch(actual.toString()) } } fun hasNoRequestCounter(method: Method, path: String, status: Status) = object : Matcher<List<MetricData>> { override val description = "http.server.request.count" override fun invoke(actual: List<MetricData>): MatchResult = if (actual.find { it.name == description } ?.longSumData ?.points ?.any { it.attributes == Attributes.of( AttributeKey.stringKey("path"), path, AttributeKey.stringKey("method"), method.name, AttributeKey.stringKey("status"), status.code.toString() ) } != true) MatchResult.Match else MatchResult.Mismatch(actual.toString()) }
apache-2.0
acdbd8c934ac472a87d3766622714e9b
37.6
118
0.607742
5.166929
false
false
false
false
rei-m/android_hyakuninisshu
feature/corecomponent/src/main/java/me/rei_m/hyakuninisshu/feature/corecomponent/widget/ad/AdViewObserver.kt
1
4100
/* * Copyright (c) 2020. Rei Matsushita * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ /* ktlint-disable package-name */ package me.rei_m.hyakuninisshu.feature.corecomponent.widget.ad import android.os.Build import android.util.DisplayMetrics import android.view.View import android.widget.FrameLayout import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import com.google.android.gms.ads.AdListener import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.AdSize import com.google.android.gms.ads.AdView import me.rei_m.hyakuninisshu.feature.corecomponent.R import me.rei_m.hyakuninisshu.feature.corecomponent.di.ActivityScope import javax.inject.Inject @ActivityScope class AdViewObserver @Inject constructor() : LifecycleObserver { private var adView: AdView? = null private var isLoadedAd = false fun showAd(activity: AppCompatActivity, container: FrameLayout) { setup(activity, container) adView?.let { if (!it.isLoading && !isLoadedAd) { loadAd() } it.visibility = View.VISIBLE } } fun hideAd() { adView?.visibility = View.GONE } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun releaseAd() { adView?.destroy() adView = null } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun resumeAd() { adView?.resume() } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun pauseAd() { adView?.pause() } private fun setup(activity: AppCompatActivity, container: FrameLayout) { if (adView == null) { val adView = AdView(activity).apply { adUnitId = activity.getString(R.string.banner_ad_unit_id) setAdSize(calcAdSize(activity, container)) adListener = object : AdListener() { override fun onAdLoaded() { super.onAdLoaded() isLoadedAd = true } } } container.addView(adView) this.adView = adView } } private fun loadAd() { val adRequest = AdRequest.Builder().build() adView?.loadAd(adRequest) } private fun calcAdSize(activity: AppCompatActivity, container: FrameLayout): AdSize { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val windowManager = activity.windowManager val metrics = windowManager.currentWindowMetrics val bounds = metrics.bounds var adWidthPixels = container.width.toFloat() if (adWidthPixels == 0f) { adWidthPixels = bounds.width().toFloat() } val density = container.resources.displayMetrics.density val adWidth = (adWidthPixels / density).toInt() AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize( activity, adWidth ) } else { val windowManager = activity.windowManager val display = windowManager.defaultDisplay val outMetrics = DisplayMetrics() display.getMetrics(outMetrics) val density = outMetrics.density val adWidthPixels = outMetrics.widthPixels.toFloat() val adWidth = (adWidthPixels / density).toInt() AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(activity, adWidth) } } }
apache-2.0
ccfb041e2db6c7fb3d85e7465dc833d3
33.166667
112
0.648537
4.829211
false
false
false
false
vitoling/HiWeather
src/main/kotlin/com/vito/work/weather/service/spider/AQICityPageProcessor.kt
1
1197
package com.vito.work.weather.service.spider import com.vito.work.weather.util.http.BusinessError import com.vito.work.weather.util.http.BusinessException import org.slf4j.LoggerFactory import us.codecraft.webmagic.Page import us.codecraft.webmagic.Site import us.codecraft.webmagic.processor.PageProcessor /** * Created by lingzhiyuan. * Date : 16/4/17. * Time : 下午11:30. * Description: * */ class AQICityPageProcessor : PageProcessor { companion object { val logger = LoggerFactory.getLogger(AQIViewPageProcessor::class.java) } private var site: Site = Site.me() .setSleepTime(5) .setRetryTimes(5) .setCycleRetryTimes(5) override fun getSite(): Site? { return site } override fun process(page: Page?) { val html = page?.html val path1 = "//div[@class='meta']/ul/li/span[@class='td-2nd']/a" if (html == null || html.xpath(path1).all().size == 0) { throw BusinessException(BusinessError.ERROR_TARGET_PAGE_NOT_FOUND) } page?.putField("urls", html.xpath("$path1/@href").all()) page?.putField("titles", html.xpath("$path1/text()").all()) } }
gpl-3.0
3b139486173bee92311394c77a3d2f63
26.136364
78
0.649623
3.62614
false
false
false
false
openMF/android-client
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/grouplist/GroupListPresenter.kt
1
2874
package com.mifos.mifosxdroid.online.grouplist import com.mifos.api.DataManager import com.mifos.mifosxdroid.base.BasePresenter import com.mifos.objects.group.CenterWithAssociations import com.mifos.objects.group.GroupWithAssociations import rx.Subscriber import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import javax.inject.Inject /** * Created by Rajan Maurya on 06/06/16. */ class GroupListPresenter @Inject constructor(private val mDataManager: DataManager) : BasePresenter<GroupListMvpView?>() { private var mSubscription: Subscription? = null override fun attachView(mvpView: GroupListMvpView?) { super.attachView(mvpView) } override fun detachView() { super.detachView() if (mSubscription != null) mSubscription!!.unsubscribe() } fun loadGroupByCenter(id: Int) { checkViewAttached() mvpView!!.showProgressbar(true) if (mSubscription != null) mSubscription!!.unsubscribe() mSubscription = mDataManager.getGroupsByCenter(id) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(object : Subscriber<CenterWithAssociations?>() { override fun onCompleted() { mvpView!!.showProgressbar(false) } override fun onError(e: Throwable) { mvpView!!.showProgressbar(false) mvpView!!.showFetchingError("Failed to load GroupList") } override fun onNext(centerWithAssociations: CenterWithAssociations?) { mvpView!!.showProgressbar(false) mvpView!!.showGroupList(centerWithAssociations) } }) } fun loadGroups(groupid: Int) { checkViewAttached() mvpView!!.showProgressbar(true) if (mSubscription != null) mSubscription!!.unsubscribe() mSubscription = mDataManager.getGroups(groupid) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(object : Subscriber<GroupWithAssociations?>() { override fun onCompleted() { mvpView!!.showProgressbar(false) } override fun onError(e: Throwable) { mvpView!!.showProgressbar(false) mvpView!!.showFetchingError("Failed to load Groups") } override fun onNext(groupWithAssociations: GroupWithAssociations?) { mvpView!!.showProgressbar(false) mvpView!!.showGroups(groupWithAssociations) } }) } }
mpl-2.0
e4275548dcecc8004ed7a5fa9a4b19af
37.333333
122
0.597077
5.950311
false
false
false
false
dexbleeker/hamersapp
hamersapp/src/main/java/nl/ecci/hamers/ui/activities/NewReviewActivity.kt
1
4464
package nl.ecci.hamers.ui.activities import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Button import android.widget.DatePicker import android.widget.SeekBar import android.widget.Toast import com.android.volley.VolleyError import kotlinx.android.synthetic.main.activity_general.* import kotlinx.android.synthetic.main.stub_new_review.* import nl.ecci.hamers.R import nl.ecci.hamers.data.Loader import nl.ecci.hamers.data.PostCallback import nl.ecci.hamers.models.Beer import nl.ecci.hamers.models.Review import nl.ecci.hamers.ui.fragments.DatePickerFragment import nl.ecci.hamers.utils.DataUtils import nl.ecci.hamers.utils.Utils import org.json.JSONException import org.json.JSONObject import java.text.SimpleDateFormat import java.util.* class NewReviewActivity : HamersNewItemActivity() { private var beer: Beer? = null private var review: Review? = null private var rating = 1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initToolbar() stub.layoutResource = R.layout.stub_new_review stub.inflate() val dateButton = findViewById<Button>(R.id.pick_date_button) val calendar = Calendar.getInstance() val dateFormat = SimpleDateFormat("dd-MM-yyyy", MainActivity.locale) beer = DataUtils.getBeer(this, intent.getIntExtra(Beer.BEER, 1)) review = gson.fromJson<Review>(intent.getStringExtra(Review.REVIEW), Review::class.java) review_title.text = beer!!.name ratingseekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, rating: Int, fromUser: Boolean) { [email protected] = rating + 1 review_rating.text = String.format("Cijfer: %s", [email protected]) } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) if (review != null) { setTitle(R.string.review_update) review_body.setText(review!!.description) ratingseekbar.progress = review!!.rating - 1 dateButton.text = dateFormat.format(review!!.proefdatum) } else { dateButton.text = dateFormat.format(calendar.time) } } override fun onResume() { super.onResume() setTitle(R.string.new_review) } fun showDatePickerDialog(v: View) { val datePicker = DatePickerFragment() datePicker.show(supportFragmentManager, "proefdatum") } override fun postItem() { val reviewBody = this.review_body.text.toString() val date = pick_date_button.text.toString() if (reviewBody.length > 2) { val body = JSONObject() try { body.put("beer_id", beer!!.id) body.put("description", reviewBody) body.put("rating", rating) body.put("proefdatum", Utils.parseDate(date)) var reviewID = -1 if (review != null) { reviewID = review!!.id } Loader.postOrPatchData(this, Loader.REVIEWURL, body, reviewID, object : PostCallback { override fun onSuccess(response: JSONObject) { val returnIntent = Intent() returnIntent.putExtra(SingleBeerActivity.reviewBody, reviewBody) returnIntent.putExtra(SingleBeerActivity.reviewRating, rating) setResult(Activity.RESULT_OK, returnIntent) finish() } override fun onError(error: VolleyError) { disableLoadingAnimation() } }) } catch (ignored: JSONException) { } } else { disableLoadingAnimation() Toast.makeText(this, getString(R.string.missing_fields), Toast.LENGTH_LONG).show() } } override fun onDateSet(datePicker: DatePicker?, year: Int, month: Int, day: Int) { val date = day.toString() + "-" + (month + 1) + "-" + year if (supportFragmentManager.findFragmentByTag("proefdatum") != null) { pick_date_button?.text = date } } }
gpl-3.0
1ed682197f649cb56b1cf7c878e25614
34.149606
102
0.62612
4.606811
false
false
false
false
xingyuli/swordess-jsondb
src/main/kotlin/org/swordess/persistence/json/IdMetadata.kt
2
2251
/* * The MIT License (MIT) * * Copyright (c) 2016 Vic Lau * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.swordess.persistence.json import java.lang.reflect.Method class IdMetadata(val getter: Method) { val propertyName: String val setter: Method init { propertyName = determinePropertyName(getter) setter = determineSetter() } private fun determinePropertyName(getter: Method): String = if (getter.name.startsWith("get")) { getter.name.substring(3).decapitalize() } else if (getter.name.startsWith("is")) { getter.name.substring(2).decapitalize() } else { throw RuntimeException("unable to determine property name for $getter") } private fun determineSetter(): Method = try { getter.declaringClass.getDeclaredMethod("set" + propertyName.capitalize(), getter.returnType) } catch (e: NoSuchMethodException) { throw RuntimeException("no setter was found for property $propertyName, please add a setter") } override fun toString() = "{ propertyName=$propertyName }" }
mit
4317044fd89a349a3d33ecc96b55e007
37.827586
109
0.683696
4.84086
false
false
false
false
microg/android_packages_apps_GmsCore
play-services-core/src/main/kotlin/org/microg/gms/ui/PushNotificationAppPreferencesFragment.kt
1
5849
/* * SPDX-FileCopyrightText: 2020, microG Project Team * SPDX-License-Identifier: Apache-2.0 */ package org.microg.gms.ui import android.os.Bundle import android.text.format.DateUtils import androidx.appcompat.app.AlertDialog import androidx.lifecycle.lifecycleScope import androidx.preference.Preference import androidx.preference.PreferenceCategory import androidx.preference.PreferenceFragmentCompat import androidx.preference.TwoStatePreference import com.google.android.gms.R import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.microg.gms.gcm.GcmDatabase import org.microg.gms.gcm.PushRegisterManager class PushNotificationAppPreferencesFragment : PreferenceFragmentCompat() { private lateinit var wakeForDelivery: TwoStatePreference private lateinit var allowRegister: TwoStatePreference private lateinit var status: Preference private lateinit var unregister: Preference private lateinit var unregisterCat: PreferenceCategory private lateinit var database: GcmDatabase private val packageName: String? get() = arguments?.getString("package") override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.preferences_push_notifications_app) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) database = GcmDatabase(context) } override fun onBindPreferences() { wakeForDelivery = preferenceScreen.findPreference("pref_push_app_wake_for_delivery") ?: wakeForDelivery allowRegister = preferenceScreen.findPreference("pref_push_app_allow_register") ?: allowRegister unregister = preferenceScreen.findPreference("pref_push_app_unregister") ?: unregister unregisterCat = preferenceScreen.findPreference("prefcat_push_app_unregister") ?: unregisterCat status = preferenceScreen.findPreference("pref_push_app_status") ?: status wakeForDelivery.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> database.setAppWakeForDelivery(packageName, newValue as Boolean) database.close() true } allowRegister.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> val enabled = newValue as? Boolean ?: return@OnPreferenceChangeListener false if (!enabled) { val registrations = packageName?.let { database.getRegistrationsByApp(it) } ?: emptyList() if (registrations.isNotEmpty()) { showUnregisterConfirm(R.string.gcm_unregister_after_deny_message) } } database.setAppAllowRegister(packageName, enabled) database.close() true } unregister.onPreferenceClickListener = Preference.OnPreferenceClickListener { showUnregisterConfirm(R.string.gcm_unregister_confirm_message) true } } private fun showUnregisterConfirm(unregisterConfirmDesc: Int) { val pm = requireContext().packageManager val applicationInfo = pm.getApplicationInfoIfExists(packageName) AlertDialog.Builder(requireContext()) .setTitle(getString(R.string.gcm_unregister_confirm_title, applicationInfo?.loadLabel(pm) ?: packageName)) .setMessage(unregisterConfirmDesc) .setPositiveButton(android.R.string.yes) { _, _ -> unregister() } .setNegativeButton(android.R.string.no) { _, _ -> }.show() } private fun unregister() { lifecycleScope.launchWhenResumed { withContext(Dispatchers.IO) { for (registration in database.getRegistrationsByApp(packageName)) { PushRegisterManager.unregister(context, registration.packageName, registration.signature, null, null) } } updateDetails() } } override fun onResume() { super.onResume() updateDetails() } private fun updateDetails() { lifecycleScope.launchWhenResumed { val app = packageName?.let { database.getApp(it) } wakeForDelivery.isChecked = app?.wakeForDelivery ?: true allowRegister.isChecked = app?.allowRegister ?: true val registrations = packageName?.let { database.getRegistrationsByApp(it) } ?: emptyList() unregisterCat.isVisible = registrations.isNotEmpty() val sb = StringBuilder() if ((app?.totalMessageCount ?: 0L) == 0L) { sb.append(getString(R.string.gcm_no_message_yet)) } else { sb.append(getString(R.string.gcm_messages_counter, app?.totalMessageCount, app?.totalMessageBytes)) if (app?.lastMessageTimestamp != 0L) { sb.append("\n").append(getString(R.string.gcm_last_message_at, DateUtils.getRelativeDateTimeString(context, app?.lastMessageTimestamp ?: 0L, DateUtils.MINUTE_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, DateUtils.FORMAT_SHOW_TIME))) } } for (registration in registrations) { sb.append("\n") if (registration.timestamp == 0L) { sb.append(getString(R.string.gcm_registered)) } else { sb.append(getString(R.string.gcm_registered_since, DateUtils.getRelativeDateTimeString(context, registration.timestamp, DateUtils.MINUTE_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, DateUtils.FORMAT_SHOW_TIME))) } } status.summary = sb.toString() database.close() } } override fun onPause() { super.onPause() database.close() } }
apache-2.0
7d140634b7d8e7f71c53e684dd55a55c
42.649254
244
0.666439
5.189885
false
false
false
false
pdvrieze/ProcessManager
PMEditor/src/main/java/nl/adaptivity/process/ui/activity/UserTaskEditorFragment.kt
1
15334
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.ui.activity import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.animation.ValueAnimator.AnimatorUpdateListener import android.databinding.DataBindingUtil import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.View.MeasureSpec import android.view.ViewGroup import android.view.animation.AccelerateDecelerateInterpolator import net.devrieze.util.isNullOrEmpty import net.devrieze.util.toArrayList import net.devrieze.util.collection.replaceBy import nl.adaptivity.android.recyclerview.ClickableAdapter import nl.adaptivity.android.recyclerview.ClickableAdapter.OnItemClickListener import nl.adaptivity.process.diagram.DrawableActivity import nl.adaptivity.process.diagram.android.ParcelableActivity import nl.adaptivity.process.diagram.android.getUserTask import nl.adaptivity.process.editor.android.R import nl.adaptivity.process.editor.android.databinding.FragmentUserTaskEditorBinding import nl.adaptivity.process.processModel.XmlDefineType import nl.adaptivity.process.processModel.XmlResultType import nl.adaptivity.process.tasks.EditableUserTask import nl.adaptivity.process.tasks.TaskItem import nl.adaptivity.process.tasks.items.LabelItem import nl.adaptivity.process.tasks.items.ListItem import nl.adaptivity.process.tasks.items.PasswordItem import nl.adaptivity.process.tasks.items.TextItem import nl.adaptivity.process.ui.UIConstants import nl.adaptivity.process.ui.activity.UserTaskEditAdapter.ItemViewHolder import nl.adaptivity.process.util.CharSequenceDecorator import nl.adaptivity.process.util.Constants import nl.adaptivity.process.util.ModifySequence import nl.adaptivity.process.util.VariableReference.ResultReference import nl.adaptivity.xmlutil.SimpleNamespaceContext import nl.adaptivity.xmlutil.XmlException import nl.adaptivity.xmlutil.XmlReader import java.util.* /** * A placeholder fragment containing a simple view. */ class UserTaskEditorFragment : Fragment(), OnItemClickListener<ItemViewHolder>, CharSequenceDecorator { private lateinit var binding: FragmentUserTaskEditorBinding private lateinit var taskEditAdapter: UserTaskEditAdapter private lateinit var activity: DrawableActivity.Builder /** The list of possible variables to use in here. */ private var variables: List<ResultReference>? = null /** * From the fragment, retrieve a parcelable activity. * * @return The parcelable activity that represents the activity state. */ // TODO use existing prefix instead of hardcoded val parcelableResult: ParcelableActivity get() { val items = taskEditAdapter.content val editableUserTask: EditableUserTask if (activity.message == null) { editableUserTask = EditableUserTask(null, null, null, items) } else { editableUserTask = activity.getUserTask() ?: EditableUserTask(null, null, null, items) editableUserTask.setItems(items) } for (item in items) { if (!(item.isReadOnly || isNullOrEmpty(item.name) || item.name is ModifySequence)) { val result = getResultFor(Constants.USER_MESSAGE_HANDLER_NS_PREFIX, item.name.toString()) if (result == null) { val newResult = XmlResultType(getResultName("r_" + item.name), getResultPath( Constants.USER_MESSAGE_HANDLER_NS_PREFIX, item.name.toString()), null as CharArray?, SimpleNamespaceContext( Constants.USER_MESSAGE_HANDLER_NS_PREFIX, Constants.USER_MESSAGE_HANDLER_NS)) activity.results.add(newResult) } } } activity.message = editableUserTask.asMessage() return ParcelableActivity(this.activity) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_user_task_editor, container, false) binding.handler = this val view = binding.root val fab = view.findViewById<View>(R.id.fab) as FloatingActionButton fab.setOnClickListener { toggleFabMenu() } taskEditAdapter = UserTaskEditAdapter(this) binding.content.adapter = taskEditAdapter taskEditAdapter.onItemClickListener = this val ac: ParcelableActivity? if (savedInstanceState != null && savedInstanceState.containsKey(UIConstants.KEY_ACTIVITY)) { ac = savedInstanceState.getParcelable(UIConstants.KEY_ACTIVITY) } else if (arguments?.containsKey(UIConstants.KEY_ACTIVITY)==true) { ac = arguments!!.getParcelable(UIConstants.KEY_ACTIVITY) } else { ac = null } variables = arguments?.getParcelableArrayList(UIConstants.KEY_VARIABLES) ?: emptyList() if (ac != null) { activity = ac.builder() val EditableUserTask = ac.getUserTask() if (EditableUserTask != null) { taskEditAdapter.setItems(EditableUserTask.items) } } return view } private fun toggleFabMenu() { if (binding.fabMenu.visibility == View.VISIBLE) { hideFabMenu() } else { showFabMenu() } } private fun showFabMenu() { binding.fabMenu.visibility = View.VISIBLE binding.fabMenu.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)) val startHeight = binding.fab.measuredHeight val startWidth = binding.fab.measuredWidth val targetWidth = binding.fabMenu.measuredWidth val targetHeight = binding.fabMenu.measuredHeight binding.fabMenu.pivotX = (targetWidth - startWidth / 2).toFloat() binding.fabMenu.pivotY = targetHeight.toFloat() val menuAnimator = ValueAnimator.ofFloat(0f, 1f) menuAnimator.interpolator = AccelerateDecelerateInterpolator() menuAnimator.addUpdateListener(object : AnimatorUpdateListener { internal var oldImage = true override fun onAnimationUpdate(animation: ValueAnimator) { val animatedFraction = animation.animatedFraction binding.fabMenu.scaleX = (startWidth + (targetWidth - startWidth) * animatedFraction) / targetWidth binding.fabMenu.scaleY = (startHeight + (targetHeight - startHeight) * animatedFraction) / targetHeight if (oldImage && animatedFraction > 0.5f) { binding.fab.setImageResource(R.drawable.ic_clear_black_24dp) oldImage = false } } }) menuAnimator.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { binding.fabMenu.scaleX = 1f binding.fabMenu.scaleY = 1f } }) menuAnimator.duration = ANIMATION_DURATION.toLong() menuAnimator.start() } private fun hideFabMenu() { // TODO animate this binding.fabMenu.visibility = View.VISIBLE binding.fabMenu.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)) val targetHeight = binding.fab.measuredHeight val targetWidth = binding.fab.measuredWidth val startWidth = binding.fabMenu.measuredWidth val startHeight = binding.fabMenu.measuredHeight binding.fabMenu.pivotX = (startWidth - targetWidth / 2).toFloat() binding.fabMenu.pivotY = startHeight.toFloat() val menuAnimator = ValueAnimator.ofFloat(0f, 1f) menuAnimator.interpolator = AccelerateDecelerateInterpolator() menuAnimator.addUpdateListener(object : AnimatorUpdateListener { internal var oldImage = true override fun onAnimationUpdate(animation: ValueAnimator) { val animatedFraction = animation.animatedFraction binding.fabMenu.scaleX = (startWidth + (targetWidth - startWidth) * animatedFraction) / startWidth binding.fabMenu.scaleY = (startHeight + (targetHeight - startHeight) * animatedFraction) / startHeight if (oldImage && animatedFraction > 0.5f) { binding.fab.setImageResource(R.drawable.ic_action_new) oldImage = false } } }) menuAnimator.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { binding.fabMenu.scaleX = 1f binding.fabMenu.scaleY = 1f binding.fabMenu.visibility = View.GONE } }) menuAnimator.duration = ANIMATION_DURATION.toLong() menuAnimator.start() } override fun decorate(sequence: CharSequence): CharSequence { if (sequence is ModifySequence) { val idefine = activity.getDefine(sequence.variableName.toString()) ?: throw IllegalArgumentException( "Invalid state") val define = XmlDefineType(idefine) try { val bodyStreamReader = define.bodyStreamReader return toLightSpanned(bodyStreamReader, define) } catch (e: XmlException) { throw RuntimeException(e) } } else { return sequence } } @Throws(XmlException::class) private fun toLightSpanned(bodyStreamReader: XmlReader, define: XmlDefineType): CharSequence { return VariableSpan.getSpanned(getActivity(), bodyStreamReader, define, VARSPAN_LIGHT_BORDER_ID) } fun onFabMenuItemClicked(v: View) { hideFabMenu() val name: String? = null // TODO use a dialog to ask for a name. when (v.id) { R.id.fabMenuLabel -> { taskEditAdapter.addItem(LabelItem(name, null)) ItemEditDialogFragment.newInstance(taskEditAdapter.getItem(taskEditAdapter.itemCount - 1), variables, activity.defines, taskEditAdapter.itemCount - 1) .show(fragmentManager, "itemdialog") } R.id.fabMenuList -> { taskEditAdapter.addItem(ListItem(name, "list", null, ArrayList<String>())) ItemEditDialogFragment.newInstance(taskEditAdapter.getItem(taskEditAdapter.itemCount - 1), variables, activity.defines, taskEditAdapter.itemCount - 1) .show(fragmentManager, "itemdialog") } R.id.fabMenuOther -> { } R.id.fabMenuPassword -> { taskEditAdapter.addItem(PasswordItem(name, "password", null)) ItemEditDialogFragment.newInstance(taskEditAdapter.getItem(taskEditAdapter.itemCount - 1), variables, activity.defines, taskEditAdapter.itemCount - 1) .show(fragmentManager, "itemdialog") } R.id.fabMenuText -> { taskEditAdapter.addItem(TextItem(name, "text", null, ArrayList<String>())) ItemEditDialogFragment.newInstance(taskEditAdapter.getItem(taskEditAdapter.itemCount - 1), variables, activity.defines, taskEditAdapter.itemCount - 1) .show(fragmentManager, "itemdialog") } } } override fun onClickItem(adapter: ClickableAdapter<*>, viewHolder: ItemViewHolder): Boolean { ItemEditDialogFragment.newInstance(taskEditAdapter.getItem(viewHolder.adapterPosition), variables, activity.defines, viewHolder.adapterPosition) .show(fragmentManager, "itemdialog") return true } fun updateItem(itemNo: Int, newItem: TaskItem) { taskEditAdapter.setItem(itemNo, newItem) } fun updateDefine(define: XmlDefineType) { activity.defines.replaceBy(define) } /** * Get a result that is a simple output result for the task value. * * @param name The name of the value * @return The first matching result, or null, if none found. */ private fun getResultFor(prefix: String, name: String): XmlResultType? { val xpath = getResultPath(prefix, name) return activity.results.firstOrNull() { it.content?.let { content -> content.isNotEmpty() && xpath == it.getPath() } == true } ?.let { XmlResultType(it) } } private fun getResultPath(prefix: String, valueName: String): String { return "/" + prefix + "result/value[@name='" + valueName + "']/text()" } private fun getResultName(candidate: String): String { val activity = activity if (activity.getResult(candidate) == null) { return candidate } return (2..Int.MAX_VALUE).asSequence() .map { "$candidate$it" } .first { activity.getResult(it)==null } } companion object { const val ANIMATION_DURATION = 200 private const val VARSPAN_LIGHT_BORDER_ID = R.drawable.varspan_border_light fun newInstance(activity: ParcelableActivity, variables: Collection<ResultReference>): UserTaskEditorFragment { val args = Bundle(2) args.putParcelable(UIConstants.KEY_ACTIVITY, activity) args.putParcelableArrayList(UIConstants.KEY_VARIABLES, toArrayList(variables)) val fragment = UserTaskEditorFragment() fragment.arguments = args return fragment } } }
lgpl-3.0
691f8fc7802e05363b59370794139967
43.705539
134
0.636038
5.433735
false
false
false
false
SirWellington/alchemy-http
src/test/java/tech/sirwellington/alchemy/http/AlchemyHttpTest.kt
1
4581
/* * Copyright © 2019. Sir Wellington. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tech.sirwellington.alchemy.http import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.argumentCaptor import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.notNullValue import org.junit.Assert.assertEquals import org.junit.Assert.assertThat import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import tech.sirwellington.alchemy.generator.CollectionGenerators import tech.sirwellington.alchemy.generator.StringGenerators.Companion.alphabeticStrings import tech.sirwellington.alchemy.test.junit.ThrowableAssertion.assertThrows import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner import tech.sirwellington.alchemy.test.junit.runners.GenerateString import tech.sirwellington.alchemy.test.junit.runners.Repeat import java.util.concurrent.Executor import java.util.concurrent.TimeUnit /** * * @author SirWellington */ @RunWith(AlchemyTestRunner::class) class AlchemyHttpTest { @Mock private lateinit var stateMachine: AlchemyHttpStateMachine @Mock private lateinit var step1: AlchemyRequestSteps.Step1 @Mock private lateinit var executor: Executor private lateinit var defaultHeaders: Map<String, String> @GenerateString private lateinit var headerKey: String @GenerateString private lateinit var headerValue: String private lateinit var instance: AlchemyHttpImpl @Before fun setUp() { defaultHeaders = CollectionGenerators.mapOf(alphabeticStrings(), alphabeticStrings(), 20) instance = AlchemyHttpImpl(defaultHeaders, stateMachine) } @Repeat(100) @Test fun testUsingDefaultHeader() { val result = instance.usingDefaultHeader(headerKey, headerValue) assertThat(result, notNullValue()) assertTrue(result.defaultHeaders.containsKey(headerKey)) assertEquals(result.defaultHeaders[headerKey], headerValue) } @Test @Throws(Exception::class) fun testUsingDefaultHeaderWithEmptyKey() { assertThrows { instance.usingDefaultHeader("", headerValue) } .isInstanceOf(IllegalArgumentException::class.java) } @Test fun testGetDefaultHeaders() { val result = instance.defaultHeaders assertThat(result, equalTo(defaultHeaders)) } @Test fun testGo() { whenever(stateMachine.begin(any())).thenReturn(step1) val step = instance.go() assertThat(step, equalTo(step1)) val captor = argumentCaptor<HttpRequest>() verify(stateMachine).begin(captor.capture()) val request = captor.firstValue assertThat(request, notNullValue()) assertThat(request.method, notNullValue()) assertThat(request.requestHeaders, notNullValue()) } @Test fun testNewDefaultInstance() { val result = AlchemyHttp.newDefaultInstance() assertThat(result, notNullValue()) } @Test fun testNewInstance() { val result = AlchemyHttp.newInstance(executor, defaultHeaders) assertThat(result, notNullValue()) //Edge cases assertThrows { AlchemyHttp.newInstance(executor, defaultHeaders, -1, TimeUnit.SECONDS) }.isInstanceOf(IllegalArgumentException::class.java) } @Test fun testNewBuilder() { val result = AlchemyHttp.newBuilder() assertThat(result, notNullValue()) val client = result .usingExecutor(executor) .usingDefaultHeaders(defaultHeaders) .build() assertThat(client, notNullValue()) defaultHeaders.forEach { key, value -> assertTrue(client.defaultHeaders[key] == value) } } }
apache-2.0
6352e6c16d526dd486a1c6d2dd4346f7
28.358974
147
0.7
5.010941
false
true
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/view/custom/passphrase/keyboard/keyboardLayouts/KeyboardLayout.kt
1
3988
/* * Copyright (c) 2017. Toshi Inc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.toshi.view.custom.passphrase.keyboard.keyboardLayouts abstract class KeyboardLayout { enum class Action { BACKSPACE, SHIFT, SPACEBAR, RETURN, LANGUAGE } enum class Layout { QWERTY, ABCDEF, QWERTZ, AZERTY; } companion object { const val FIRST_ROW = 0 const val SECOND_ROW = 1 const val THIRD_ROW = 2 const val FOURTH_ROW = 3 fun getLayout(layout: Layout): KeyboardLayout { return when (layout) { Layout.QWERTY -> Qwerty() Layout.ABCDEF -> Abcdef() Layout.QWERTZ -> Qwertz() Layout.AZERTY -> Azerty() } } } abstract fun isLastChatOnRow(key: Any): Boolean abstract fun getLayout(): List<Row> class Qwerty : KeyboardLayout() { override fun getLayout() = listOf( Row(listOf("q", "w", "e", "r", "t", "y", "u", "i", "o", "p")), Row(listOf("a", "s", "d", "f", "g", "h", "j", "k", "l")), Row(listOf(Action.SHIFT, "z", "x", "c", "v", "b", "n", "m", Action.BACKSPACE)), Row(listOf(Action.LANGUAGE, Action.SPACEBAR, Action.RETURN)) ) override fun isLastChatOnRow(key: Any): Boolean { return key == "p" || key == "l" || key == Action.BACKSPACE || key == Action.RETURN } } class Abcdef : KeyboardLayout() { override fun getLayout() = listOf( Row(listOf("a", "b", "c", "d", "e", "f", "g", "h", "i", "j")), Row(listOf("k", "l", "m", "n", "o", "p", "q", "r", "s")), Row(listOf(Action.SHIFT, "t", "u", "v", "w", "x", "y", "z", Action.BACKSPACE)), Row(listOf(Action.LANGUAGE, Action.SPACEBAR, Action.RETURN)) ) override fun isLastChatOnRow(key: Any): Boolean { return key == "j" || key == "s" || key == Action.BACKSPACE || key == Action.RETURN } } class Qwertz : KeyboardLayout() { override fun getLayout() = listOf( Row(listOf("q", "w", "e", "r", "t", "z", "u", "i", "o", "p")), Row(listOf("a", "s", "d", "f", "g", "h", "j", "k", "l")), Row(listOf(Action.SHIFT, "y", "x", "c", "v", "b", "n", "m", Action.BACKSPACE)), Row(listOf(Action.LANGUAGE, Action.SPACEBAR, Action.RETURN)) ) override fun isLastChatOnRow(key: Any): Boolean { return key == "p" || key == "l" || key == Action.BACKSPACE || key == Action.RETURN } } class Azerty : KeyboardLayout() { override fun getLayout() = listOf( Row(listOf("a", "z", "e", "r", "t", "y", "u", "i", "o", "p")), Row(listOf("q", "s", "d", "f", "g", "h", "j", "k", "l")), Row(listOf(Action.SHIFT, "m", "w", "x", "c", "v", "b", "n", Action.BACKSPACE)), Row(listOf(Action.LANGUAGE, Action.SPACEBAR, Action.RETURN)) ) override fun isLastChatOnRow(key: Any): Boolean { return key == "p" || key == "l" || key == Action.BACKSPACE || key == Action.RETURN } } } data class Row( val list: List<Any> = emptyList() )
gpl-3.0
39f0ceaf09dbb0222d1aba45e3752764
34.936937
95
0.515296
3.662075
false
false
false
false
shkschneider/android_Skeleton
core/src/main/kotlin/me/shkschneider/skeleton/ui/widget/AutoImageViewWidth.kt
1
937
package me.shkschneider.skeleton.ui.widget import android.content.Context import android.util.AttributeSet import android.view.View import androidx.appcompat.widget.AppCompatImageView // <http://stackoverflow.com/a/12283909> class AutoImageViewWidth : AppCompatImageView { var ratio = 1.1.toFloat() constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr) override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val drawable = drawable ?: run { super.onMeasure(widthMeasureSpec, heightMeasureSpec) return } val width = View.MeasureSpec.getSize(widthMeasureSpec) val height = Math.ceil((width.toFloat() * drawable.intrinsicHeight.toFloat() / drawable.intrinsicWidth.toFloat()).toDouble()).toInt() setMeasuredDimension((ratio * width).toInt(), (ratio * height).toInt()) } }
apache-2.0
bc7c4132e1d6a20a44b76b5ed937b330
36.48
141
0.716115
4.615764
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
example/src/test/java/org/wordpress/android/fluxc/wc/data/CountryTestUtils.kt
2
1354
package org.wordpress.android.fluxc.wc.data import org.wordpress.android.fluxc.model.data.WCLocationModel import org.wordpress.android.fluxc.network.rest.wpcom.wc.data.WCDataRestClient.CountryApiResponse import org.wordpress.android.fluxc.network.rest.wpcom.wc.data.WCDataRestClient.CountryApiResponse.State object CountryTestUtils { private fun generateSampleCountry( code: String = "", name: String = "", parentCode: String = "" ): WCLocationModel { return WCLocationModel().apply { this.code = code this.name = name this.parentCode = parentCode } } fun generateCountries(): List<WCLocationModel> { return listOf( generateSampleCountry("CA", "Canada"), generateSampleCountry("ON", "Ontario", parentCode = "CA"), generateSampleCountry("BC", "British Columbia", parentCode = "CA"), generateSampleCountry("CZ", "Czech Republic") ) } fun generateCountryApiResponse(): List<CountryApiResponse> { return listOf( CountryApiResponse("CA", "Canada", listOf( State("ON", "Ontario"), State("BC", "British Columbia") ) ), CountryApiResponse("CZ", "Czech Republic", emptyList()) ) } }
gpl-2.0
8e63e59c1bb2c54001ad04ff6ab9a4a9
33.717949
103
0.610783
4.801418
false
false
false
false
Kotlin/kotlinx.serialization
formats/hocon/src/main/kotlin/kotlinx/serialization/hocon/HoconEncoder.kt
1
5428
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.hocon import com.typesafe.config.* import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* import kotlinx.serialization.internal.* import kotlinx.serialization.modules.* @ExperimentalSerializationApi internal abstract class AbstractHoconEncoder( private val hocon: Hocon, private val valueConsumer: (ConfigValue) -> Unit, ) : NamedValueEncoder() { override val serializersModule: SerializersModule get() = hocon.serializersModule private var writeDiscriminator: Boolean = false override fun elementName(descriptor: SerialDescriptor, index: Int): String { return descriptor.getConventionElementName(index, hocon.useConfigNamingConvention) } override fun composeName(parentName: String, childName: String): String = childName protected abstract fun encodeTaggedConfigValue(tag: String, value: ConfigValue) protected abstract fun getCurrent(): ConfigValue override fun encodeTaggedValue(tag: String, value: Any) = encodeTaggedConfigValue(tag, configValueOf(value)) override fun encodeTaggedNull(tag: String) = encodeTaggedConfigValue(tag, configValueOf(null)) override fun encodeTaggedChar(tag: String, value: Char) = encodeTaggedString(tag, value.toString()) override fun encodeTaggedEnum(tag: String, enumDescriptor: SerialDescriptor, ordinal: Int) { encodeTaggedString(tag, enumDescriptor.getElementName(ordinal)) } override fun shouldEncodeElementDefault(descriptor: SerialDescriptor, index: Int): Boolean = hocon.encodeDefaults override fun <T> encodeSerializableValue(serializer: SerializationStrategy<T>, value: T) { if (serializer !is AbstractPolymorphicSerializer<*> || hocon.useArrayPolymorphism) { serializer.serialize(this, value) return } @Suppress("UNCHECKED_CAST") val casted = serializer as AbstractPolymorphicSerializer<Any> val actualSerializer = casted.findPolymorphicSerializer(this, value as Any) writeDiscriminator = true actualSerializer.serialize(this, value) } override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder { val consumer = if (currentTagOrNull == null) valueConsumer else { value -> encodeTaggedConfigValue(currentTag, value) } val kind = descriptor.hoconKind(hocon.useArrayPolymorphism) return when { kind.listLike -> HoconConfigListEncoder(hocon, consumer) kind.objLike -> HoconConfigEncoder(hocon, consumer) kind == StructureKind.MAP -> HoconConfigMapEncoder(hocon, consumer) else -> this }.also { encoder -> if (writeDiscriminator) { encoder.encodeTaggedString(hocon.classDiscriminator, descriptor.serialName) writeDiscriminator = false } } } override fun endEncode(descriptor: SerialDescriptor) { valueConsumer(getCurrent()) } private fun configValueOf(value: Any?) = ConfigValueFactory.fromAnyRef(value) } @ExperimentalSerializationApi internal class HoconConfigEncoder(hocon: Hocon, configConsumer: (ConfigValue) -> Unit) : AbstractHoconEncoder(hocon, configConsumer) { private val configMap = mutableMapOf<String, ConfigValue>() override fun encodeTaggedConfigValue(tag: String, value: ConfigValue) { configMap[tag] = value } override fun getCurrent(): ConfigValue = ConfigValueFactory.fromMap(configMap) } @ExperimentalSerializationApi internal class HoconConfigListEncoder(hocon: Hocon, configConsumer: (ConfigValue) -> Unit) : AbstractHoconEncoder(hocon, configConsumer) { private val values = mutableListOf<ConfigValue>() override fun elementName(descriptor: SerialDescriptor, index: Int): String = index.toString() override fun encodeTaggedConfigValue(tag: String, value: ConfigValue) { values.add(tag.toInt(), value) } override fun getCurrent(): ConfigValue = ConfigValueFactory.fromIterable(values) } @ExperimentalSerializationApi internal class HoconConfigMapEncoder(hocon: Hocon, configConsumer: (ConfigValue) -> Unit) : AbstractHoconEncoder(hocon, configConsumer) { private val configMap = mutableMapOf<String, ConfigValue>() private lateinit var key: String private var isKey: Boolean = true override fun encodeTaggedConfigValue(tag: String, value: ConfigValue) { if (isKey) { key = when (value.valueType()) { ConfigValueType.OBJECT, ConfigValueType.LIST -> throw InvalidKeyKindException(value) else -> value.unwrappedNullable().toString() } isKey = false } else { configMap[key] = value isKey = true } } override fun getCurrent(): ConfigValue = ConfigValueFactory.fromMap(configMap) // Without cast to `Any?` Kotlin will assume unwrapped value as non-nullable by default // and will call `Any.toString()` instead of extension-function `Any?.toString()`. // We can't cast value in place using `(value.unwrapped() as Any?).toString()` because of warning "No cast needed". private fun ConfigValue.unwrappedNullable(): Any? = unwrapped() }
apache-2.0
28d9e932c2381078c0345fe330e53434
37.771429
119
0.712786
5.154796
false
true
false
false
HuttonICS/buntata-app
app/src/main/java/uk/ac/hutton/ics/buntata/activity/DatasourceActivity.kt
2
2856
/* * Copyright 2016 Information & Computational Sciences, The James Hutton Institute * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.ac.hutton.ics.buntata.activity import android.app.Activity import android.os.Build import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v4.content.ContextCompat import android.view.MenuItem import butterknife.ButterKnife import uk.ac.hutton.ics.buntata.R import uk.ac.hutton.ics.buntata.util.PreferenceUtils import uk.ac.hutton.ics.buntata.util.SnackbarUtils /** * The [DatasourceActivity] contains the [uk.ac.hutton.ics.buntata.fragment.DatasourceFragment]. It's used to select the data source. * @author Sebastian Raubach */ class DatasourceActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ButterKnife.bind(this) /* Prompt the user to select at least one data source */ if (!PreferenceUtils.getPreferenceAsBoolean(this, PreferenceUtils.PREFS_AT_LEAST_ONE_DATASOURCE, false)) SnackbarUtils.show(findViewById(android.R.id.content), R.string.snackbar_select_datasource, Snackbar.LENGTH_LONG) setSupportActionBar(toolbar) /* Set the toolbar as the action bar */ /* Set the title */ supportActionBar?.setTitle(R.string.title_activity_datasource) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setHomeButtonEnabled(true) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) window.statusBarColor = ContextCompat.getColor(this, R.color.colorPrimaryDark) } override fun getLayoutId(): Int? = R.layout.activity_datasource override fun getToolbarId(): Int? = R.id.toolbar override fun onBackPressed() { val newDatasourceId = PreferenceUtils.getPreferenceAsInt(this, PreferenceUtils.PREFS_SELECTED_DATASOURCE_ID, -1) if (newDatasourceId != -1) setResult(Activity.RESULT_OK) super.onBackPressed() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { onBackPressed() return true } else -> return super.onOptionsItemSelected(item) } } }
apache-2.0
bb8ed436bfd9fb971782a9ec93c95191
35.151899
133
0.713585
4.407407
false
false
false
false
sabi0/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/GithubApiRequest.kt
2
6712
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.api import com.google.gson.reflect.TypeToken import com.intellij.util.ThrowableConvertor import org.jetbrains.plugins.github.api.data.GithubResponsePage import org.jetbrains.plugins.github.api.data.GithubSearchResult import java.io.IOException /** * Represents an API request with strictly defined response type */ sealed class GithubApiRequest<T>(val url: String) { var operationName: String? = null abstract val acceptMimeType: String? @Throws(IOException::class) abstract fun extractResult(response: GithubApiResponse): T fun withOperationName(name: String): GithubApiRequest<T> { operationName = name return this } abstract class Get<T> @JvmOverloads constructor(url: String, override val acceptMimeType: String? = null) : GithubApiRequest<T>(url) { abstract class Optional<T> @JvmOverloads constructor(url: String, acceptMimeType: String? = null) : Get<T?>(url, acceptMimeType) { companion object { inline fun <reified T> json(url: String): Optional<T> = Json(url, T::class.java) } open class Json<T>(url: String, clazz: Class<T>) : Optional<T>(url, GithubApiContentHelper.V3_JSON_MIME_TYPE) { private val typeToken = TypeToken.get(clazz) override fun extractResult(response: GithubApiResponse): T = parseJsonResponse(response, typeToken) } } companion object { inline fun <reified T> json(url: String): Get<T> = Json(url, T::class.java) inline fun <reified T> jsonList(url: String): Get<List<T>> = JsonList(url, T::class.java) inline fun <reified T> jsonPage(url: String): Get<GithubResponsePage<T>> = JsonPage(url, T::class.java) inline fun <reified T> jsonSearchPage(url: String): Get<GithubResponsePage<T>> = JsonSearchPage(url, T::class.java) } open class Json<T>(url: String, clazz: Class<T>) : Get<T>(url, GithubApiContentHelper.V3_JSON_MIME_TYPE) { private val typeToken = TypeToken.get(clazz) override fun extractResult(response: GithubApiResponse): T = parseJsonResponse(response, typeToken) } open class JsonList<T>(url: String, clazz: Class<T>) : Get<List<T>>(url, GithubApiContentHelper.V3_JSON_MIME_TYPE) { private val typeToken = TypeToken.getParameterized(List::class.java, clazz) as TypeToken<List<T>> override fun extractResult(response: GithubApiResponse): List<T> = parseJsonResponse(response, typeToken) } open class JsonPage<T>(url: String, clazz: Class<T>) : Get<GithubResponsePage<T>>(url, GithubApiContentHelper.V3_JSON_MIME_TYPE) { private val typeToken = TypeToken.getParameterized(List::class.java, clazz) as TypeToken<List<T>> override fun extractResult(response: GithubApiResponse): GithubResponsePage<T> { return GithubResponsePage.parseFromHeader(parseJsonResponse(response, typeToken), response.findHeader(GithubResponsePage.HEADER_NAME)) } } open class JsonSearchPage<T>(url: String, clazz: Class<T>) : Get<GithubResponsePage<T>>(url, GithubApiContentHelper.V3_JSON_MIME_TYPE) { private val typeToken = TypeToken.getParameterized(GithubSearchResult::class.java, clazz) as TypeToken<GithubSearchResult<T>> override fun extractResult(response: GithubApiResponse): GithubResponsePage<T> { return GithubResponsePage.parseFromHeader(parseJsonResponse(response, typeToken).items, response.findHeader(GithubResponsePage.HEADER_NAME)) } } } abstract class Head<T> @JvmOverloads constructor(url: String, override val acceptMimeType: String? = null) : GithubApiRequest<T>(url) abstract class WithBody<T>(url: String) : GithubApiRequest<T>(url) { abstract val body: String abstract val bodyMimeType: String } abstract class Post<T> @JvmOverloads constructor(override val body: String, override val bodyMimeType: String, url: String, override val acceptMimeType: String? = null) : GithubApiRequest.WithBody<T>(url) { companion object { inline fun <reified T> json(url: String, body: Any): Post<T> = Json(url, body, T::class.java) } open class Json<T>(url: String, body: Any, clazz: Class<T>) : Post<T>(GithubApiContentHelper.toJson(body), GithubApiContentHelper.JSON_MIME_TYPE, url, GithubApiContentHelper.V3_JSON_MIME_TYPE) { private val typeToken = TypeToken.get(clazz) override fun extractResult(response: GithubApiResponse): T = parseJsonResponse(response, typeToken) } } abstract class Patch<T> @JvmOverloads constructor(override val body: String, override val bodyMimeType: String, url: String, override val acceptMimeType: String? = null) : GithubApiRequest.WithBody<T>(url) { companion object { inline fun <reified T> json(url: String, body: Any): Post<T> = Json(url, body, T::class.java) } open class Json<T>(url: String, body: Any, clazz: Class<T>) : Post<T>(GithubApiContentHelper.toJson(body), GithubApiContentHelper.JSON_MIME_TYPE, url, GithubApiContentHelper.V3_JSON_MIME_TYPE) { private val typeToken = TypeToken.get(clazz) override fun extractResult(response: GithubApiResponse): T = parseJsonResponse(response, typeToken) } } open class Delete(url: String) : GithubApiRequest<Unit>(url) { override val acceptMimeType: String? = null override fun extractResult(response: GithubApiResponse) {} } companion object { private fun <T> parseJsonResponse(response: GithubApiResponse, typeToken: TypeToken<T>): T { return response.readBody(ThrowableConvertor { GithubApiContentHelper.readJson(it, typeToken) }) } } }
apache-2.0
3b577dc73e6f3bdeb04143fd9b5eddef
48.718519
140
0.62053
4.888565
false
false
false
false
jrenner/kotlin-algorithms-ds
src/datastructs/fundamental/bag/ArrayBag.kt
1
1785
package datastructs.fundamental.bag import java.util.ArrayList import util.plus import util.NonNullArrayIterator /** A Bag with a backing array */ public class ArrayBag<T> : Bag<T> { private val DEFAULT_INIT_CAPACITY = 8 private val EXPAND_MULTIPLE = 1.5f private var items = Array<Any?>(DEFAULT_INIT_CAPACITY, { null }) as Array<T?> override fun iterator(): Iterator<T> { return NonNullArrayIterator<T>(items) } private inner class BagIterator<T> : Iterator<T> { var head = 0 val lastNull = items.lastIndexOf(null) override fun next(): T { return items[head++] as T; } override fun hasNext(): Boolean { return items[head] != null } } override fun add(item: T) { for (i in items.indices) { if (items[i] == null) { items[i] = item return } } // array out of space, expand it items = items.copyOf((items.size * EXPAND_MULTIPLE).toInt()) as Array<T?> add(item) } override fun size(): Int { var result = items.indexOf(null) if (result == -1) { result = capacity() } return result } fun capacity(): Int { return items.size } val capacity: Int get() = capacity() fun toList() : List<T> { val arrayList = ArrayList<T>() for (item in items) { if (item != null) arrayList.add(item) } return arrayList } override fun details() { var c = 0 val sb = StringBuilder() sb + "ArrayBag, size: ${size()}, capacity: ${capacity()}\n" items.forEach { sb + "\t[$c]: $it\n";c++ } print(sb.toString()) } }
apache-2.0
a9a21a3d2b84298ad4112585e2016043
23.805556
81
0.532773
4.047619
false
false
false
false
RoverPlatform/rover-android
experiences/src/main/kotlin/io/rover/sdk/experiences/services/MeasurementService.kt
1
6877
package io.rover.sdk.experiences.services import android.annotation.SuppressLint import android.graphics.Paint import android.graphics.Typeface import android.os.Build import android.text.Layout import android.text.SpannableString import android.text.StaticLayout import android.text.TextPaint import android.util.DisplayMetrics import io.rover.sdk.experiences.ui.blocks.barcode.BarcodeViewModelInterface import io.rover.sdk.experiences.ui.blocks.concerns.text.Font import io.rover.sdk.experiences.ui.blocks.concerns.text.FontAppearance import io.rover.sdk.experiences.ui.blocks.concerns.text.RichTextToSpannedTransformer import io.rover.sdk.experiences.ui.dpAsPx import io.rover.sdk.experiences.ui.pxAsDp internal class MeasurementService( private val displayMetrics: DisplayMetrics, private val richTextToSpannedTransformer: RichTextToSpannedTransformer, private val barcodeRenderingService: BarcodeRenderingService ) { // Snap the given Dp value to the nearest pixel, returning the equivalent Dp value. The goal // here is to ensure when the resulting Dp value is converted to a Px value (for the same // density), no rounding will need to occur to yield an exact Px value (since Px values cannot // be fractional). This is useful because we do not want to accrue rounding errors downstream. fun snapToPixValue(dpValue: Int): Float { return dpValue.dpAsPx(displayMetrics).pxAsDp(displayMetrics) } fun measureHeightNeededForMultiLineTextInTextView( text: String, fontAppearance: FontAppearance, width: Float, textViewLineSpacing: Float = 1.0f ): Float { val spanned = SpannableString(text) val paint = TextPaint().apply { textSize = fontAppearance.fontSize * displayMetrics.scaledDensity typeface = Typeface.create(fontAppearance.font.fontFamily, fontAppearance.font.fontStyle) textAlign = fontAppearance.align } val textLayoutAlign = when (fontAppearance.align) { Paint.Align.CENTER -> Layout.Alignment.ALIGN_CENTER Paint.Align.LEFT -> Layout.Alignment.ALIGN_NORMAL Paint.Align.RIGHT -> Layout.Alignment.ALIGN_OPPOSITE } val layout = StaticLayout(spanned, paint, width.dpAsPx(displayMetrics), textLayoutAlign, textViewLineSpacing, 0f, true) return layout.height.pxAsDp(displayMetrics) } /** * Measure how much height a given bit of Unicode [richText] (with optional HTML tags such as * strong, italic, and underline) will require if soft wrapped to the given [width] and * [fontAppearance] ultimately meant to be displayed using an Android View. * * [boldFontAppearance] provides any font size or font-family modifications that should be * applied to bold text ( with no changes to colour or alignment). This allows for nuanced * control of bold span styling. * * Returns the height needed to accommodate the text at the given width, in dps. */ @SuppressLint("NewApi") fun measureHeightNeededForRichText( richText: String, fontAppearance: FontAppearance, boldFontAppearance: Font, width: Float ): Float { val spanned = richTextToSpannedTransformer.transform(richText, boldFontAppearance) val paint = TextPaint().apply { textSize = fontAppearance.fontSize.toFloat() * displayMetrics.scaledDensity typeface = Typeface.create( fontAppearance.font.fontFamily, fontAppearance.font.fontStyle ) textAlign = fontAppearance.align isAntiAlias = true } val textLayoutAlign = when (fontAppearance.align) { Paint.Align.CENTER -> Layout.Alignment.ALIGN_CENTER Paint.Align.LEFT -> Layout.Alignment.ALIGN_NORMAL Paint.Align.RIGHT -> Layout.Alignment.ALIGN_OPPOSITE } // now ask Android's StaticLayout to measure the needed height of the text soft-wrapped to // the width. val layout = if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)) { StaticLayout .Builder.obtain(spanned, 0, spanned.length, paint, width.dpAsPx(displayMetrics)) .setAlignment(textLayoutAlign) .setLineSpacing(0f, 1.0f) // includePad ensures we don't clip off any of the ligatures that extend down past // the rule line. .setIncludePad(true) // Experiences app does not appear to wrap text on text blocks. This seems particularly // important for short, tight blocks. .setHyphenationFrequency(Layout.HYPHENATION_FREQUENCY_NONE) .build() } else { // On Android before 23 have to use the older interface for setting up a StaticLayout, // with which we sadly cannot configure it without hyphenation turned on, but this // only really effects edge cases anyway. StaticLayout( spanned, paint, width.dpAsPx(displayMetrics), textLayoutAlign, 1.0f, 0f, // includePad ensures we don't clip off any of the ligatures that extend down past // the rule line. true ) } // log.v("Measured ${richText.lines().size} lines of text as needing ${layout.height} px") return (layout.height + layout.topPadding + layout.bottomPadding).pxAsDp(displayMetrics) } /** * Measure how much height a given bit of Unicode [text] will require if rendered as a barcode * in the given format. * * [type] specifies what format of barcode should be used, namely * [BarcodeViewModelInterface.BarcodeType]. Note that what length and sort of text is valid * depends on the type. * * Returns the height needed to accommodate the barcode, at the correct aspect, at the given * width, in dps. */ fun measureHeightNeededForBarcode( text: String, type: BarcodeViewModelInterface.BarcodeType, width: Float ): Float { return barcodeRenderingService.measureHeightNeededForBarcode( text, when (type) { BarcodeViewModelInterface.BarcodeType.Aztec -> BarcodeRenderingService.Format.Aztec BarcodeViewModelInterface.BarcodeType.Code128 -> BarcodeRenderingService.Format.Code128 BarcodeViewModelInterface.BarcodeType.PDF417 -> BarcodeRenderingService.Format.Pdf417 BarcodeViewModelInterface.BarcodeType.QrCode -> BarcodeRenderingService.Format.QrCode }, width ) } }
apache-2.0
95db229896e971809e657c0895dc51e0
43.083333
104
0.663516
5.027047
false
false
false
false
asamm/locus-api
locus-api-android-sample/src/main/java/com/asamm/locus/api/sample/pages/MapFragment.kt
1
6623
/** * Created by menion on 25/01/2018. * This code is part of Locus project from Asamm Software, s. r. o. */ package com.asamm.locus.api.sample.pages import android.annotation.SuppressLint import android.app.Dialog import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.os.Bundle import android.view.GestureDetector import android.view.Gravity import android.view.MotionEvent import android.widget.FrameLayout import android.widget.ImageView import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import locus.api.android.ActionMapTools import locus.api.android.MapPreviewParams import locus.api.android.objects.LocusVersion import locus.api.android.utils.LocusUtils import locus.api.objects.extra.Location import locus.api.utils.Logger class MapFragment : DialogFragment() { // current version private lateinit var lv: LocusVersion // base map view drawer private lateinit var mapView: MapView // detector for gestures private var detector: GestureDetector? = null // base dimension private val imgDimen = 512 // handler for map loading private var loader: Thread? = null // total applied map offset in X dimension private var mapOffsetX = 0 // total applied map offset in Y dimension private var mapOffsetY = 0 override fun onAttach(ctx: Context) { super.onAttach(ctx) lv = LocusUtils.getActiveVersion(ctx) ?: throw IllegalStateException("No active Locus-based application") } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { // prepare container for a map val container = object : FrameLayout(activity!!) { @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { // request reload for up-event only val action = event.action and MotionEvent.ACTION_MASK if (action == MotionEvent.ACTION_UP) { loadMap() } // handle event return if (detector?.onTouchEvent(event) == true) { true } else { super.onTouchEvent(event) } } } mapView = MapView(activity!!) mapView.layoutParams = FrameLayout.LayoutParams(2 * imgDimen, 3 * imgDimen) .apply { gravity = Gravity.CENTER } mapView.post { loadMap() } container.addView(mapView) // setup handler initializeHandler() // create and display dialog return AlertDialog.Builder(activity!!) .setTitle("Map preview") .setMessage("") .setView(container) .setPositiveButton("Close") { _, _ -> } .create() } private fun initializeHandler() { detector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() { override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean { loader = null mapOffsetX += distanceX.toInt() mapOffsetY += distanceY.toInt() mapView.offsetX += distanceX.toInt() mapView.offsetY += distanceY.toInt() mapView.invalidate() return true } override fun onDown(event: MotionEvent): Boolean { return true } override fun onFling(event1: MotionEvent, event2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { return true } }) } override fun onStop() { super.onStop() // stop loader loader = null } /** * Perform load of map preview. */ private fun loadMap() { loader = Thread(Runnable { Logger.logD("MapFragment", "loadMap()") // prepare parameters val params = MapPreviewParams().apply { locCenter = Location(52.35, 1.5) zoom = 14 offsetX = mapOffsetX offsetY = mapOffsetY widthPx = mapView.width heightPx = mapView.height densityDpi = resources.displayMetrics.densityDpi // test rotation // rotate = true // rotation = 30 } // get and display preview val result = ActionMapTools.getMapPreview(activity!!, lv, params) if (Thread.currentThread() == loader) { activity?.runOnUiThread { if (result != null && result.isValid()) { (dialog as AlertDialog).setMessage("Missing tiles: ${result.numOfNotYetLoadedTiles}") mapView.img = result.getAsImage() mapView.offsetX = 0 mapView.offsetY = 0 mapView.invalidate() // call recursively if missing tiles if (result.numOfNotYetLoadedTiles > 0) { Thread.sleep(2000) loadMap() } } else { (dialog as AlertDialog).setMessage("Unable to obtain map preview") } } } else { Logger.logD("MapFragment", "old request invalid") } }) loader?.start() } inner class MapView(ctx: Context) : ImageView(ctx) { // map image to draw var img: Bitmap? = null // temporary offset for draw in X axis var offsetX: Int = 0 // temporary offset for draw in Y axis var offsetY: Int = 0 // paint object for a text private val paintText = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.RED textSize = 18.0f textAlign = Paint.Align.CENTER } override fun onDraw(c: Canvas) { super.onDraw(c) // draw empty view if (img == null) { c.drawText("Loading map ...", width / 2.0f, height / 2.0f, paintText) return } // draw map c.drawBitmap(img!!, -1.0f * offsetX, -1.0f * offsetY, null) } } }
mit
2d3f19fe786fd2757d5e9e3018510d0d
31.630542
114
0.552922
5.235573
false
false
false
false
jasonwyatt/AsyncListUtil-Example
app/src/main/java/co/jasonwyatt/asynclistutil_example/SQLiteItemSource.kt
1
920
package co.jasonwyatt.asynclistutil_example import android.annotation.SuppressLint import android.database.Cursor import android.database.sqlite.SQLiteDatabase class SQLiteItemSource(val database: SQLiteDatabase) : ItemSource { private var _cursor: Cursor? = null private val cursor: Cursor @SuppressLint("Recycle") get() { if (_cursor == null || _cursor?.isClosed != false) { _cursor = database.rawQuery("SELECT title, content FROM data", null) } return _cursor ?: throw AssertionError("Set to null or closed by another thread") } override fun getCount() = cursor.count override fun getItem(position: Int): Item { cursor.moveToPosition(position) return Item(cursor) } override fun close() { _cursor?.close() } } private fun Item(c: Cursor): Item = Item(c.getString(0), c.getString(1))
unlicense
28db177eb6570951d56bf212e6ec3ef4
29.666667
93
0.651087
4.36019
false
false
false
false
RanKKI/PSNine
app/src/main/java/xyz/rankki/psnine/ui/topic/TopicAdapter.kt
1
8646
package xyz.rankki.psnine.ui.topic import android.content.Context import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import android.webkit.WebView import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.bumptech.glide.request.target.Target import org.jetbrains.anko.* import xyz.rankki.psnine.R import xyz.rankki.psnine.base.BaseTopicModel import xyz.rankki.psnine.common.config.PSNineTypes import xyz.rankki.psnine.model.topic.Gene import xyz.rankki.psnine.model.topic.Home import xyz.rankki.psnine.model.topic.Reply import xyz.rankki.psnine.ui.anko.* import xyz.rankki.psnine.utils.HtmlUtil import java.io.BufferedReader import java.io.InputStreamReader class TopicAdapter(private val mContext: Context) : RecyclerView.Adapter<TopicAdapter.ViewHolder>() { companion object { const val Type_Header = 10 const val Type_MoreReplies = 11 const val Type_Reply = 12 const val Type_Image = 13 const val Type_Game = 14 } private val _ankoContext = AnkoContext.createReusable(mContext, this) private var _topic: BaseTopicModel? = null private var _replies: ArrayList<Reply> = ArrayList() private var _replyPositionOffset = 0 private var _imagePositionOffset = 0 private var _gamesPositionOffset = 0 private var _images: ArrayList<Gene.Image> = ArrayList() private var _games: ArrayList<Home.Game> = ArrayList() fun updateTopic(topic: BaseTopicModel) { doAsync { _topic = topic _replyPositionOffset = -1 when (_topic?.getType()) { PSNineTypes.Gene -> { val gene = _topic!! as Gene _replyPositionOffset -= gene.images.size _images = gene.images _imagePositionOffset = -1 } PSNineTypes.Home -> { val home = _topic!! as Home _replyPositionOffset -= home.games.size _games = home.games _gamesPositionOffset = -1 _gamesPositionOffset -= _imagePositionOffset } } uiThread { notifyItemRangeChanged(0, itemCount) } } } fun updateReplies(replies: ArrayList<Reply>) { doAsync { val start: Int = itemCount _replies.addAll(replies) uiThread { notifyItemRangeInserted(start, _replies.size) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return when (viewType) { Type_Header -> HeaderViewHolder(TopicHeaderUI<TopicAdapter>().createView(_ankoContext)) Type_MoreReplies -> MoreRepliesViewHolder(TopicMoreRepliesUI<TopicAdapter>().createView(_ankoContext)) Type_Image -> ImageViewHolder(ImageUI<TopicAdapter>().createView(_ankoContext)) Type_Game -> GameViewHolder(GameUI<TopicAdapter>().createView(_ankoContext)) else -> ReplyViewHolder(TopicReplyUI<TopicAdapter>().createView(_ankoContext)) } } override fun getItemCount(): Int { return doAsyncResult { if (_topic === null) { return@doAsyncResult 0 } var count = 1 // Header view count += _images.size // add Gene Images Views count += _games.size count += _replies.size // add replies's size return@doAsyncResult count }.get() } override fun onBindViewHolder(holder: ViewHolder, position: Int) { when (getItemViewType(position)) { Type_Header -> { val viewHolder: HeaderViewHolder = holder as HeaderViewHolder viewHolder.tvUsername.text = _topic!!.getUsername() Glide.with(mContext).load(_topic!!.getAvatar()).into(viewHolder.ivAvatar) if (_topic!!.getType() == PSNineTypes.Gene || !(_topic!!.usingWebView())) { viewHolder.wvContent.visibility = View.GONE viewHolder.tvContent.visibility = View.VISIBLE HtmlUtil.fromHtml(mContext, _topic!!.getContent(), viewHolder.tvContent) } else { viewHolder.wvContent.visibility = View.VISIBLE viewHolder.tvContent.visibility = View.GONE doAsync { val inputStream = mContext.resources.openRawResource(R.raw.p9css) val css = BufferedReader(InputStreamReader(inputStream)) .readLines().joinToString("\n") val content = "<html><head><style>$css</style></head><body>${_topic!!.getContent()}</body></html>" uiThread { viewHolder.wvContent.loadData(content, "text/html", "utf-8") } } } } Type_Image -> { val imagePosition: Int = _imagePositionOffset + position val viewHolder: ImageViewHolder = holder as ImageViewHolder val requestOptions = RequestOptions() requestOptions.override(Target.SIZE_ORIGINAL) Glide.with(mContext) .setDefaultRequestOptions(requestOptions) .load((_topic!! as Gene).images[imagePosition].url) .into(viewHolder.ivImage) } Type_Game -> { val viewHolder: GameViewHolder = holder as GameViewHolder val game: Home.Game = _games[_gamesPositionOffset + position] viewHolder.tvGameEdition.text = game.gameEdition viewHolder.tvGameName.text = game.gameName viewHolder.tvGameTrophy.text = game.gameTrophy Glide.with(mContext).load(game.gameAvatar).into(viewHolder.ivGameAvatar) if (game.gameComment !== "") { viewHolder.tvComment.visibility = View.VISIBLE viewHolder.tvComment.text = game.gameComment } } Type_MoreReplies -> { } Type_Reply -> { val viewHolder: ReplyViewHolder = holder as ReplyViewHolder val reply: Reply = _replies[_replyPositionOffset + position] viewHolder.tvUsername.text = reply.username Glide.with(mContext).load(reply.avatar).into(viewHolder.ivAvatar) HtmlUtil.fromHtml(mContext, reply.content, viewHolder.tvContent) } } } override fun getItemViewType(position: Int): Int { return doAsyncResult { if (position == 0) { return@doAsyncResult Type_Header } else if (position <= _images.size) { return@doAsyncResult Type_Image } else if (_images.size < position && position <= _games.size + _images.size) { return@doAsyncResult Type_Game } else { return@doAsyncResult Type_Reply } }.get() } open class ViewHolder(view: View) : RecyclerView.ViewHolder(view) class HeaderViewHolder(mView: View) : ViewHolder(mView) { val tvUsername: TextView = mView.find(TopicHeaderUI.ID_Username) val tvContent: TextView = mView.find(TopicHeaderUI.ID_Content) val ivAvatar: ImageView = mView.find(TopicHeaderUI.ID_Avatar) val wvContent: WebView = mView.find(TopicHeaderUI.ID_Content_WebView) } class ReplyViewHolder(mView: View) : ViewHolder(mView) { val tvUsername: TextView = mView.find(TopicReplyUI.ID_Username) val tvContent: TextView = mView.find(TopicReplyUI.ID_Content) val ivAvatar: ImageView = mView.find(TopicReplyUI.ID_Avatar) } class MoreRepliesViewHolder(mView: View) : ViewHolder(mView) class ImageViewHolder(mView: View) : ViewHolder(mView) { val ivImage: ImageView = mView.find(ImageUI.ID_Image) } class GameViewHolder(mView: View) : ViewHolder(mView) { val tvGameName: TextView = mView.find(GameUI.ID_GameName) val tvGameTrophy: TextView = mView.find(GameUI.ID_Trophy) val tvGameEdition: TextView = mView.find(GameUI.ID_Edition) val tvComment: TextView = mView.find(GameUI.ID_Comment) val ivGameAvatar: ImageView = mView.find(GameUI.ID_GameAvatar) } }
apache-2.0
2848a410916753615df2e221b4709bc9
39.596244
122
0.599584
4.954728
false
false
false
false
AoEiuV020/PaNovel
api/src/main/java/cc/aoeiuv020/panovel/api/site/guanshuwang.kt
1
2266
package cc.aoeiuv020.panovel.api.site import cc.aoeiuv020.base.jar.textList import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext import cc.aoeiuv020.panovel.api.firstThreeIntPattern import cc.aoeiuv020.panovel.api.firstTwoIntPattern /** * Created by AoEiuV020 on 2018.06.03-18:12:36. */ class Guanshuwang : DslJsoupNovelContext() {init { reason = "搜索403了," upkeep = false site { name = "官术网" baseUrl = "https://www.guanshu.cc" logo = "https://www.guanshu.cc/images/logo.gif" } search { get { // https://www.biyuwu.cc/search.php?q=%E4%BF%AE%E7%9C%9F url = "/search.php" data { "q" to it } } document { items("body > div.result-list > div") { name("> div.result-game-item-detail > h3 > a") author("> div.result-game-item-detail > div > p:nth-child(1) > span:nth-child(2)") } } } // http://www.3dllc.cc/html/86/86047/ bookIdRegex = firstTwoIntPattern detailPageTemplate = "/html/%s/" detail { document { novel { name("#info > h1") author("#info > p:nth-child(2)", block = pickString("作\\s*者:(\\S*)")) } image("#fmimg > img") update("#info > p:nth-child(4)", format = "yyyy-MM-dd HH:mm:ss", block = pickString("最后更新:(.*)")) introduction("#intro") } } chapters { document { /* <a href="/book/1196/443990.html">第一章 觉醒日</a> */ items("#list > dl > dd > a") lastUpdate("#info > p:nth-child(4)", format = "yyyy-MM-dd HH:mm:ss", block = pickString("最后更新:(.*)")) } } // http://www.3dllc.cc/html/86/86047/2336.html bookIdWithChapterIdRegex = firstThreeIntPattern contentPageTemplate = "/html/%s.html" content { document { items("#content", block = { e -> // 这网站正文第一行开关都有个utf8bom,不会被当成空白符过滤掉, e.textList().map { it.removePrefix("\ufeff").trimStart() } }) } } } }
gpl-3.0
11afb2459a0d1a228544a847e3dade6e
29.914286
113
0.519871
3.44586
false
false
false
false
fallGamlet/DnestrCinema
KinotirApi/src/main/java/com/kinotir/api/mappers/HtmlFilmDetailMapper.kt
1
2705
package com.kinotir.api.mappers import com.kinotir.api.FilmDetailsJson import com.kinotir.api.ImageUrlJson import org.jsoup.Jsoup import org.jsoup.select.Elements internal class HtmlFilmDetailMapper : Mapper<String?, FilmDetailsJson?> { private val dateMapper = MovieDateMapper() override fun map(src: String?): FilmDetailsJson? { val doc = src?.let { Jsoup.parse(it) } ?: return null val info = doc.select(".film .info").first() ?: return null val result = FilmDetailsJson( posterUrl = info.select(">.additional-poster>.image>img")?.attr("src"), buyTicketLink = doc.select("a.buy-ticket-btn").attr("href"), description = info.select(".description")?.text() ) parseFeatures(info.select(".features"), result) parseImages(info.select(".slider"), result) parseTrailers(info.select(".trailer"), result) return result } private fun parseFeatures(src: Elements?, destination: FilmDetailsJson) { src?.select(">li") ?.forEach { val key = it.select("label")?.text()?.trim()?.toLowerCase() ?: "" val value = it.select("div")?.text()?.trim() ?: "" when { key.contains("старт") -> destination.pubDate = dateMapper.map(value) key.contains("страна") -> destination.country = value key.contains("режисер") -> destination.director = value key.contains("сценарий") -> destination.scenario = value key.contains("в ролях") -> destination.actors = value key.contains("жанр") -> destination.genre = value key.contains("бюджет") -> destination.budget = value key.contains("возраст") -> destination.ageLimit = value key.contains("продолжительность") -> destination.duration = value } } } private fun parseImages(src: Elements?, destination: FilmDetailsJson) { destination.imageUrls = src?.select(">a") ?.mapNotNull { val bigImg = it.attr("href") ?: "" val smallImg = it.select("img")?.attr("src") ?: "" if (smallImg.isBlank()) null else ImageUrlJson(bigImg, smallImg) } ?: emptyList() } private fun parseTrailers(src: Elements?, destination: FilmDetailsJson) { destination.trailerUrls = src?.select(">iframe") ?.mapNotNull { it.attr("src") } ?.filter { it.isNotBlank() } ?: emptyList() } }
gpl-3.0
1060cfcc5a333b5721b068fa069cebe2
40.888889
88
0.56726
4.495741
false
false
false
false
arturbosch/detekt
detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/wrappers/SpacingAroundKeyword.kt
1
729
package io.gitlab.arturbosch.detekt.formatting.wrappers import com.pinterest.ktlint.ruleset.standard.SpacingAroundKeywordRule import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault import io.gitlab.arturbosch.detekt.api.internal.AutoCorrectable import io.gitlab.arturbosch.detekt.formatting.FormattingRule /** * See <a href="https://ktlint.github.io/#rule-spacing">ktlint-website</a> for documentation. */ @ActiveByDefault(since = "1.0.0") @AutoCorrectable(since = "1.0.0") class SpacingAroundKeyword(config: Config) : FormattingRule(config) { override val wrapping = SpacingAroundKeywordRule() override val issue = issueFor("Reports spaces around keywords") }
apache-2.0
68dbf1b54b5abf0419844aad69725e87
39.5
93
0.798354
4.027624
false
true
false
false
wiltonlazary/kotlin-native
samples/html5Canvas/src/httpServerMain/kotlin/HttpServer.kt
3
1992
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ @file:JvmName("HttpServer") package sample.html5canvas.httpserver import io.ktor.application.call import io.ktor.http.ContentType import io.ktor.http.content.LocalFileContent import io.ktor.http.content.default import io.ktor.http.content.files import io.ktor.http.content.static import io.ktor.response.respond import io.ktor.routing.get import io.ktor.routing.routing import io.ktor.server.engine.embeddedServer import io.ktor.server.netty.Netty import java.io.File fun main(args: Array<String>) { check(args.size == 1) { "Invalid number of arguments: $args.\nExpected one argument with content root." } val contentRoot = File(args[0]) check(contentRoot.isDirectory) { "Invalid content root: $contentRoot." } println( """ IMPORTANT: Please open http://localhost:8080/ in your browser! To stop embedded HTTP server use Ctrl+C (Cmd+C for Mac OS X). """.trimIndent() ) val server = embeddedServer(Netty, 8080) { routing { val wasm = "build/bin/html5Canvas/releaseExecutable/html5Canvas.wasm" get(wasm) { // TODO: ktor as of now doesn't know about 'application/wasm'. // The newer browsers (firefox and chrome at least) don't allow // 'application/octet-stream' for wasm anymore. // We provide the proper content type here and, // at the same time, put it into the ktor database. // Remove this whole get() clause when ktor fix is available. call.respond(LocalFileContent(File(wasm), ContentType("application", "wasm"))) } static("/") { files(contentRoot) default("index.html") } } } server.start(wait = true) }
apache-2.0
4d0b30d0e3d8b638dd840b5017d573ca
32.762712
109
0.637048
4.193684
false
false
false
false
chimbori/crux
src/main/kotlin/com/chimbori/crux/plugins/GoogleUrlRewriter.kt
1
619
package com.chimbori.crux.plugins import com.chimbori.crux.api.Rewriter import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull public class GoogleUrlRewriter : Rewriter { private fun canRewrite(url: HttpUrl) = url.host.endsWith(".google.com") && url.encodedPath == "/url" override fun rewrite(url: HttpUrl): HttpUrl { if (!canRewrite(url)) return url var outputUrl: HttpUrl = url do { outputUrl = (outputUrl.queryParameter("q") ?: outputUrl.queryParameter("url")) ?.toHttpUrlOrNull() ?: outputUrl } while (canRewrite(outputUrl)) return outputUrl } }
apache-2.0
351707ff1d6416f404f7db8a807d6f4b
28.47619
102
0.705977
4.182432
false
false
false
false
olonho/carkot
translator/src/test/kotlin/tests/stress_test_1/stress_test_1.kt
1
11361
class RouteRequest private constructor (var distances: IntArray, var angles: IntArray) { //========== Properties =========== //repeated int32 distances = 1 //repeated int32 angles = 2 var errorCode: Int = 0 //========== Serialization methods =========== fun writeTo (output: CodedOutputStream) { //repeated int32 distances = 1 if (distances.size > 0) { output.writeTag(1, WireType.LENGTH_DELIMITED) var arrayByteSize = 0 if (distances.size != 0) { do { var arraySize = 0 var i = 0 while (i < distances.size) { arraySize += WireFormat.getInt32SizeNoTag(distances[i]) i += 1 } arrayByteSize += arraySize } while(false) } output.writeInt32NoTag(arrayByteSize) do { var i = 0 while (i < distances.size) { output.writeInt32NoTag (distances[i]) i += 1 } } while(false) } //repeated int32 angles = 2 if (angles.size > 0) { output.writeTag(2, WireType.LENGTH_DELIMITED) var arrayByteSize = 0 if (angles.size != 0) { do { var arraySize = 0 var i = 0 while (i < angles.size) { arraySize += WireFormat.getInt32SizeNoTag(angles[i]) i += 1 } arrayByteSize += arraySize } while(false) } output.writeInt32NoTag(arrayByteSize) do { var i = 0 while (i < angles.size) { output.writeInt32NoTag (angles[i]) i += 1 } } while(false) } } fun mergeWith (other: RouteRequest) { distances = distances.plus((other.distances)) angles = angles.plus((other.angles)) this.errorCode = other.errorCode } fun mergeFromWithSize (input: CodedInputStream, expectedSize: Int) { val builder = RouteRequest.BuilderRouteRequest(IntArray(0), IntArray(0)) mergeWith(builder.parseFromWithSize(input, expectedSize).build()) } fun mergeFrom (input: CodedInputStream) { val builder = RouteRequest.BuilderRouteRequest(IntArray(0), IntArray(0)) mergeWith(builder.parseFrom(input).build()) } //========== Size-related methods =========== fun getSize(fieldNumber: Int): Int { var size = 0 if (distances.size != 0) { do { var arraySize = 0 size += WireFormat.getTagSize(1, WireType.LENGTH_DELIMITED) var i = 0 while (i < distances.size) { arraySize += WireFormat.getInt32SizeNoTag(distances[i]) i += 1 } size += arraySize size += WireFormat.getInt32SizeNoTag(arraySize) } while(false) } if (angles.size != 0) { do { var arraySize = 0 size += WireFormat.getTagSize(2, WireType.LENGTH_DELIMITED) var i = 0 while (i < angles.size) { arraySize += WireFormat.getInt32SizeNoTag(angles[i]) i += 1 } size += arraySize size += WireFormat.getInt32SizeNoTag(arraySize) } while(false) } size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED) return size } fun getSizeNoTag(): Int { var size = 0 if (distances.size != 0) { do { var arraySize = 0 size += WireFormat.getTagSize(1, WireType.LENGTH_DELIMITED) var i = 0 while (i < distances.size) { arraySize += WireFormat.getInt32SizeNoTag(distances[i]) i += 1 } size += arraySize size += WireFormat.getInt32SizeNoTag(arraySize) } while(false) } if (angles.size != 0) { do { var arraySize = 0 size += WireFormat.getTagSize(2, WireType.LENGTH_DELIMITED) var i = 0 while (i < angles.size) { arraySize += WireFormat.getInt32SizeNoTag(angles[i]) i += 1 } size += arraySize size += WireFormat.getInt32SizeNoTag(arraySize) } while(false) } return size } //========== Builder =========== class BuilderRouteRequest constructor (var distances: IntArray, var angles: IntArray) { //========== Properties =========== //repeated int32 distances = 1 fun setDistances(value: IntArray): RouteRequest.BuilderRouteRequest { distances = value return this } fun setdistancesByIndex(index: Int, value: Int): RouteRequest.BuilderRouteRequest { distances[index] = value return this } //repeated int32 angles = 2 fun setAngles(value: IntArray): RouteRequest.BuilderRouteRequest { angles = value return this } fun setanglesByIndex(index: Int, value: Int): RouteRequest.BuilderRouteRequest { angles[index] = value return this } var errorCode: Int = 0 //========== Serialization methods =========== fun writeTo (output: CodedOutputStream) { //repeated int32 distances = 1 if (distances.size > 0) { output.writeTag(1, WireType.LENGTH_DELIMITED) var arrayByteSize = 0 if (distances.size != 0) { do { var arraySize = 0 var i = 0 while (i < distances.size) { arraySize += WireFormat.getInt32SizeNoTag(distances[i]) i += 1 } arrayByteSize += arraySize } while(false) } output.writeInt32NoTag(arrayByteSize) do { var i = 0 while (i < distances.size) { output.writeInt32NoTag (distances[i]) i += 1 } } while(false) } //repeated int32 angles = 2 if (angles.size > 0) { output.writeTag(2, WireType.LENGTH_DELIMITED) var arrayByteSize = 0 if (angles.size != 0) { do { var arraySize = 0 var i = 0 while (i < angles.size) { arraySize += WireFormat.getInt32SizeNoTag(angles[i]) i += 1 } arrayByteSize += arraySize } while(false) } output.writeInt32NoTag(arrayByteSize) do { var i = 0 while (i < angles.size) { output.writeInt32NoTag (angles[i]) i += 1 } } while(false) } } //========== Mutating methods =========== fun build(): RouteRequest { val res = RouteRequest(distances, angles) res.errorCode = errorCode return res } fun parseFieldFrom(input: CodedInputStream): Boolean { if (input.isAtEnd()) { return false } val tag = input.readInt32NoTag() if (tag == 0) { return false } val fieldNumber = WireFormat.getTagFieldNumber(tag) val wireType = WireFormat.getTagWireType(tag) when(fieldNumber) { 1 -> { if (wireType.id != WireType.LENGTH_DELIMITED.id) { errorCode = 1 return false } val expectedByteSize = input.readInt32NoTag() var newArray = IntArray(0) var readSize = 0 do { var i = 0 while(readSize < expectedByteSize) { val tmp = IntArray(1) tmp[0] = input.readInt32NoTag() newArray = newArray.plus(tmp) readSize += WireFormat.getInt32SizeNoTag(tmp[0]) } distances = newArray } while (false) } 2 -> { if (wireType.id != WireType.LENGTH_DELIMITED.id) { errorCode = 1 return false } val expectedByteSize = input.readInt32NoTag() var newArray = IntArray(0) var readSize = 0 do { var i = 0 while(readSize < expectedByteSize) { val tmp = IntArray(1) tmp[0] = input.readInt32NoTag() newArray = newArray.plus(tmp) readSize += WireFormat.getInt32SizeNoTag(tmp[0]) } angles = newArray } while (false) } else -> errorCode = 4 } return true } fun parseFromWithSize(input: CodedInputStream, expectedSize: Int): RouteRequest.BuilderRouteRequest { while(getSizeNoTag() < expectedSize) { parseFieldFrom(input) } if (getSizeNoTag() > expectedSize) { errorCode = 2 } return this } fun parseFrom(input: CodedInputStream): RouteRequest.BuilderRouteRequest { while(parseFieldFrom(input)) {} return this } //========== Size-related methods =========== fun getSize(fieldNumber: Int): Int { var size = 0 if (distances.size != 0) { do { var arraySize = 0 size += WireFormat.getTagSize(1, WireType.LENGTH_DELIMITED) var i = 0 while (i < distances.size) { arraySize += WireFormat.getInt32SizeNoTag(distances[i]) i += 1 } size += arraySize size += WireFormat.getInt32SizeNoTag(arraySize) } while(false) } if (angles.size != 0) { do { var arraySize = 0 size += WireFormat.getTagSize(2, WireType.LENGTH_DELIMITED) var i = 0 while (i < angles.size) { arraySize += WireFormat.getInt32SizeNoTag(angles[i]) i += 1 } size += arraySize size += WireFormat.getInt32SizeNoTag(arraySize) } while(false) } size += WireFormat.getVarint32Size(size) + WireFormat.getTagSize(fieldNumber, WireType.LENGTH_DELIMITED) return size } fun getSizeNoTag(): Int { var size = 0 if (distances.size != 0) { do { var arraySize = 0 size += WireFormat.getTagSize(1, WireType.LENGTH_DELIMITED) var i = 0 while (i < distances.size) { arraySize += WireFormat.getInt32SizeNoTag(distances[i]) i += 1 } size += arraySize size += WireFormat.getInt32SizeNoTag(arraySize) } while(false) } if (angles.size != 0) { do { var arraySize = 0 size += WireFormat.getTagSize(2, WireType.LENGTH_DELIMITED) var i = 0 while (i < angles.size) { arraySize += WireFormat.getInt32SizeNoTag(angles[i]) i += 1 } size += arraySize size += WireFormat.getInt32SizeNoTag(arraySize) } while(false) } return size } } } fun echoProto() { var i = 0 while (i < 100) { val route = readRoute() go(route) i++ } } fun receiveByteArray(): ByteArray { val result = ByteArray(10) result[0] = 10 result[1] = 4 result[2] = 232.toByte() result[3] = 7 result[4] = 232.toByte() result[5] = 7 result[6] = 18 result[7] = 2 result[8] = 0 result[9] = 0 return result } fun readRoute(): RouteRequest { val buffer = receiveByteArray() val stream = CodedInputStream(buffer) val result = RouteRequest.BuilderRouteRequest(IntArray(0), IntArray(0)).parseFrom(stream).build() return result } fun wait(i: Int) { } fun go(request: RouteRequest) { val times = request.distances var j = 0 while (j < times.size) { val time = times[j] wait(time) j++ } }
mit
9cbb8809a40fc1d205681d100ba5e1b9
26.444444
110
0.542734
4.471074
false
false
false
false
StephaneBg/ScoreItProject
ui/src/main/java/com/sbgapps/scoreit/ui/model/Game.kt
1
657
package com.sbgapps.scoreit.ui.model class Game(players: List<Player>, laps: List<UniversalLap>) { val achievement: List<Achievement> init { achievement = mutableListOf() players.forEachIndexed { indexPlayer, player -> val points = mutableListOf<Int>() points += 0 laps.forEachIndexed { index, lap -> points += points[index] + lap.points[indexPlayer] } achievement.add(Pair(player, points)) } } fun getScore(player: Player): Int = achievement.first { it.first == player }.second.last() } typealias Achievement = Pair<Player, List<Int>>
apache-2.0
05cb247f18cd9306872b275a6bf671f8
27.608696
94
0.607306
4.439189
false
false
false
false