repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
SimonVT/cathode
cathode-provider/src/main/java/net/simonvt/cathode/provider/entity/ItemTypeString.kt
1
275
package net.simonvt.cathode.provider.entity object ItemTypeString { const val SHOW = "show" const val SEASON = "season" const val EPISODE = "episode" const val MOVIE = "movie" const val PERSON = "person" const val LIST = "list" const val COMMENT = "comment" }
apache-2.0
d97cdc2ceab92122ff17ca9d01cdbea5
24
43
0.698182
3.618421
false
false
false
false
cfig/Android_boot_image_editor
bbootimg/src/main/kotlin/avb/desc/KernelCmdlineDescriptor.kt
1
3134
// Copyright 2021 [email protected] // // 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 avb.desc import cfig.helper.Helper import cc.cfig.io.Struct import java.io.InputStream class KernelCmdlineDescriptor( var flags: Int = 0, var cmdlineLength: Int = 0, var cmdline: String = "") : Descriptor(TAG, 0, 0) { var flagsInterpretation: String = "" get() { var ret = "" if (this.flags and flagHashTreeEnabled == flagHashTreeEnabled) { ret += "$flagHashTreeEnabled: hashTree Enabled" } else if (this.flags and flagHashTreeDisabled == flagHashTreeDisabled) { ret += "$flagHashTreeDisabled: hashTree Disabled" } return ret } @Throws(IllegalArgumentException::class) constructor(data: InputStream, seq: Int = 0) : this() { val info = Struct(FORMAT_STRING).unpack(data) this.tag = (info[0] as ULong).toLong() this.num_bytes_following = (info[1] as ULong).toLong() this.flags = (info[2] as UInt).toInt() this.cmdlineLength = (info[3] as UInt).toInt() this.sequence = seq val expectedSize = Helper.round_to_multiple(SIZE - 16 + this.cmdlineLength, 8) if ((this.tag != TAG) || (this.num_bytes_following != expectedSize.toLong())) { throw IllegalArgumentException("Given data does not look like a kernel cmdline descriptor") } this.cmdline = Struct("${this.cmdlineLength}s").unpack(data)[0] as String } override fun encode(): ByteArray { val num_bytes_following = SIZE - 16 + cmdline.toByteArray().size val nbf_with_padding = Helper.round_to_multiple(num_bytes_following.toLong(), 8) val padding_size = nbf_with_padding - num_bytes_following val desc = Struct(FORMAT_STRING).pack( TAG, nbf_with_padding, this.flags, cmdline.length) val padding = Struct("${padding_size}x").pack(null) return Helper.join(desc, cmdline.toByteArray(), padding) } companion object { const val TAG: Long = 3L const val SIZE = 24 const val FORMAT_STRING = "!2Q2L" //# tag, num_bytes_following (descriptor header), flags, cmdline length (bytes) //AVB_KERNEL_CMDLINE_FLAGS_USE_ONLY_IF_HASHTREE_NOT_DISABLED const val flagHashTreeEnabled = 1 //AVB_KERNEL_CMDLINE_FLAGS_USE_ONLY_IF_HASHTREE_DISABLED const val flagHashTreeDisabled = 2 init { check(SIZE == Struct(FORMAT_STRING).calcSize()) } } }
apache-2.0
91a0f6c56e5cd3ba0fc837f08c3c6e18
39.179487
121
0.633057
4.075423
false
false
false
false
asamm/locus-api
locus-api-android/src/main/java/locus/api/android/features/sendToApp/SendToAppHelper.kt
1
3641
/**************************************************************************** * * Created by menion on 06.04.2021. * Copyright (c) 2021. All rights reserved. * * This file is part of the Asamm team software. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * ***************************************************************************/ package locus.api.android.features.sendToApp import android.content.Context import android.net.Uri import locus.api.objects.Storable import locus.api.utils.Logger import locus.api.utils.Utils import java.io.DataInputStream import java.io.DataOutputStream import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.util.* object SendToAppHelper { // tag for logger private const val TAG = "SendToAppHelper" //************************************************* // FILESYSTEM //************************************************* // SEND DATA /** * Get cache directory used for sending content to Locus app. * * @param ctx current context * @param filename own name of the file or auto-generated */ fun getCacheFile(ctx: Context, filename: String = "${System.currentTimeMillis()}.lb"): File { // get filepath val dir = File(ctx.cacheDir, "shared") dir.mkdirs() // return generated file return File(dir, filename) } internal fun sendDataWriteOnCard(file: File, writer: DataOutputStream.() -> Unit): Boolean { // prepare output var dos: DataOutputStream? = null try { file.parentFile!!.mkdirs() // delete previous file if (file.exists()) { file.delete() } // create stream dos = DataOutputStream(FileOutputStream(file, false)) // write current version writer(dos) dos.flush() return true } catch (e: Exception) { Logger.logE(TAG, "sendDataWriteOnCard($file, $writer)", e) return false } finally { Utils.closeStream(dos) } } // RECEIVE DATA /** * Read data stored in certain path. This method is deprecated and should not be used. Instead * use new method over FileUri system. */ @Deprecated (message = "Use system over FileUri") internal inline fun <reified T : Storable> readDataFromPath(filepath: String): List<T> { // check file val file = File(filepath) if (!file.exists() || !file.isFile) { return ArrayList() } var dis: DataInputStream? = null try { dis = DataInputStream(FileInputStream(file)) return Storable.readList(T::class.java, dis) } catch (e: Exception) { Logger.logE(TAG, "readDataFromPath($filepath)", e) } finally { Utils.closeStream(dis) } return ArrayList() } /** * Read data from the supplied [fileUri] source. */ internal inline fun <reified T : Storable> readDataFromUri(ctx: Context, fileUri: Uri): List<T> { var dis: DataInputStream? = null try { dis = DataInputStream(ctx.contentResolver.openInputStream(fileUri)) return Storable.readList(T::class.java, dis) } catch (e: Exception) { Logger.logE(TAG, "readDataFromUri($fileUri)", e) } finally { Utils.closeStream(dis) } return listOf() } }
mit
a3fcded2535d464f72979a03cc432278
29.35
101
0.558638
4.69201
false
false
false
false
hartwigmedical/hmftools
teal/src/main/kotlin/com/hartwig/hmftools/teal/telbam/BamRecordWriter.kt
1
8403
package com.hartwig.hmftools.teal.telbam import com.hartwig.hmftools.teal.ReadGroup import com.hartwig.hmftools.teal.TealUtils.hasTelomericContent import com.hartwig.hmftools.teal.TealUtils.openSamReader import htsjdk.samtools.SAMFileWriter import htsjdk.samtools.SAMFileWriterFactory import htsjdk.samtools.SAMRecord import htsjdk.samtools.SAMTag import java.lang.IllegalStateException import java.lang.InterruptedException import java.lang.Runnable import java.util.HashMap import java.util.concurrent.BlockingQueue import java.util.zip.GZIPOutputStream import kotlin.jvm.Volatile import org.apache.logging.log4j.Level import org.apache.logging.log4j.LogManager import tech.tablesaw.api.BooleanColumn import tech.tablesaw.api.IntColumn import tech.tablesaw.api.StringColumn import tech.tablesaw.api.Table import tech.tablesaw.io.csv.CsvWriteOptions class TelBamRecord { var samRecord: SAMRecord? = null var hasTeloContent = false var poison = false } class BamRecordWriter(config: TelbamParams, private val mTelBamRecordQ: BlockingQueue<TelBamRecord>, private val mIncompleteReadNames: MutableSet<String>) : Runnable { private val logger = LogManager.getLogger(javaClass) private val mIncompleteReadGroups: MutableMap<String, ReadGroup> = HashMap() private val mReadDataTable = Table.create("ReadData") private val mBamFileWriter: SAMFileWriter private var mNumCompletedGroups = 0 var numAcceptedReads = 0 private set @Volatile private var mProcessingMateRegions = false private val mReadDataCsvPath: String? override fun run() { while (true) { val task: TelBamRecord = try { mTelBamRecordQ.take() } catch (e: InterruptedException) { break } if (task.poison) { break } processReadRecord(task.samRecord!!, task.hasTeloContent) } } val incompleteReadGroups: Map<String, ReadGroup> get() = mIncompleteReadGroups fun setProcessingMissingReadRegions(b: Boolean) { mProcessingMateRegions = b } fun finish() { // we write out the final incomplete group mIncompleteReadGroups.values.forEach({ rg -> writeReadGroup(rg) }) for (rg in mIncompleteReadGroups.values) { logger.warn("incomplete read group: id={}, is complete={}", rg.name, rg.isComplete(Level.WARN)) for (r in rg.Reads) { logger.warn( "record({}) cigar({}) neg strand({}) suppl flag({}) suppl attr({})", r, r.cigarString, r.readNegativeStrandFlag, r.supplementaryAlignmentFlag, r.getStringAttribute(SAMTag.SA.name)) } for (r in rg.SupplementaryReads) { logger.warn( "supplementary({}) cigar({}) neg strand({}) suppl flag({}) suppl attr({})", r, r.cigarString, r.readNegativeStrandFlag, r.supplementaryAlignmentFlag, r.getStringAttribute(SAMTag.SA.name)) } } mBamFileWriter.close() writeReadDataToTsv() logger.info( "wrote {} read groups, complete({}), incomplete({})", mNumCompletedGroups + mIncompleteReadGroups.size, mNumCompletedGroups, mIncompleteReadGroups.size) } private fun processReadRecord(record: SAMRecord, hasTelomereContent: Boolean) { var readGroup = mIncompleteReadGroups[record.readName] if (readGroup == null) { if (mProcessingMateRegions) { // do not create a new group if we are doing mate regions // the group would have already been created and written out return } if (hasTelomereContent) { // cache if new readGroup = ReadGroup(record.readName) mIncompleteReadGroups[record.readName] = readGroup mIncompleteReadNames.add(readGroup.name) } else { return } } if (!readGroup.contains(record)) { acceptRead(readGroup, record) } assert(readGroup.invariant()) if (readGroup.isComplete()) processCompleteReadGroup(readGroup) } private fun acceptRead(readGroup: ReadGroup, record: SAMRecord) { assert(!readGroup.contains(record)) if (readGroup.acceptRead(record)) { ++numAcceptedReads } } private fun processCompleteReadGroup(readGroup: ReadGroup) { if (mIncompleteReadGroups.remove(readGroup.name) != null) { mIncompleteReadNames.remove(readGroup.name) if (readGroup.Reads.size > 2) { logger.debug("read group size: {}", readGroup.Reads.size) } writeReadGroup(readGroup) ++mNumCompletedGroups } } fun writeReadGroup(readGroup: ReadGroup) { for (record in readGroup.allReads) { addReadDataTableRow(record, readGroup.isComplete()) } for (samRecord in readGroup.allReads) { mBamFileWriter.addAlignment(samRecord) } } private fun setReadDataTableColumns() { // add all the columns we need for the CSV mReadDataTable.addColumns( StringColumn.create("readId"), StringColumn.create("chromosome"), IntColumn.create("posStart"), IntColumn.create("posEnd"), StringColumn.create("mateChr"), IntColumn.create("matePosStart"), BooleanColumn.create("hasTeloContent"), StringColumn.create("cigar"), IntColumn.create("insertSize"), BooleanColumn.create("firstInPair"), BooleanColumn.create("unmapped"), BooleanColumn.create("mateUnmapped"), BooleanColumn.create("isSupplementary"), IntColumn.create("flags"), StringColumn.create("suppData"), BooleanColumn.create("completeFrag")) } private fun addReadDataTableRow(record: SAMRecord, readGroupIsComplete: Boolean) { val row = mReadDataTable.appendRow() row.setString("readId", record.readName) row.setString("chromosome", record.referenceName) row.setInt("posStart", record.alignmentStart) row.setInt("posEnd", record.alignmentEnd) row.setString("mateChr", record.mateReferenceName) row.setInt("matePosStart", record.mateAlignmentStart) row.setBoolean("hasTeloContent", hasTelomericContent(record.readString)) row.setString("cigar", record.cigarString) row.setInt("insertSize", record.inferredInsertSize) row.setBoolean("firstInPair", record.firstOfPairFlag) row.setBoolean("unmapped", record.readUnmappedFlag) row.setBoolean("mateUnmapped", record.mateUnmappedFlag) row.setBoolean("isSupplementary", record.supplementaryAlignmentFlag) row.setInt("flags", record.flags) row.setString("suppData", record.getStringAttribute(SAMTag.SA.name) ?: "") row.setBoolean("completeFrag", readGroupIsComplete) } private fun writeReadDataToTsv() { if (mReadDataCsvPath == null) return GZIPOutputStream(java.io.FileOutputStream(mReadDataCsvPath, false)).use { outputStream -> try { val writeOptions = CsvWriteOptions .builder(outputStream) .separator('\t').build() mReadDataTable.write().csv(writeOptions) } catch (e: java.io.IOException) { throw IllegalStateException("Could not save to tsv file: " + mReadDataCsvPath + ": " + e.message) } } } init { val samReader = openSamReader(config) val telbamPath = config.telbamFile mBamFileWriter = SAMFileWriterFactory().makeBAMWriter(samReader.fileHeader, false, java.io.File(telbamPath)) mReadDataCsvPath = config.tsvFile setReadDataTableColumns() } }
gpl-3.0
5d9308b735788ba189566f72231470e6
33.727273
116
0.615613
4.611965
false
false
false
false
FHannes/intellij-community
platform/script-debugger/protocol/protocol-model-generator/src/TypeMap.kt
8
1645
package org.jetbrains.protocolModelGenerator import gnu.trove.THashMap import java.util.* /** * Keeps track of all referenced types. * A type may be used and resolved (generated or hard-coded). */ internal class TypeMap { private val map = THashMap<Pair<String, String>, TypeData>() var domainGeneratorMap: Map<String, DomainGenerator>? = null private val typesToGenerate = ArrayDeque<StandaloneTypeBinding>() fun resolve(domainName: String, typeName: String, direction: TypeData.Direction): BoxableType? { val domainGenerator = domainGeneratorMap!!.get(domainName) if (domainGenerator == null) { val qName = "$domainName.$typeName"; if (qName == "IO.StreamHandle" || qName == "Security.SecurityState" || qName == "Security.CertificateId" || qName == "Emulation.ScreenOrientation" ) { return BoxableType.ANY_STRING // ignore } throw RuntimeException("Failed to find domain generator: $domainName for type $typeName") } return direction.get(getTypeData(domainName, typeName)).resolve(this, domainGenerator) } fun addTypeToGenerate(binding: StandaloneTypeBinding) { typesToGenerate.offer(binding) } fun generateRequestedTypes() { // size may grow during iteration val createdTypes = HashSet<CharSequence>() while (typesToGenerate.isNotEmpty()) { val binding = typesToGenerate.poll() if (createdTypes.add(binding.getJavaType().fullText)) { binding.generate() } } } fun getTypeData(domainName: String, typeName: String) = map.getOrPut(Pair(domainName, typeName)) { TypeData(typeName) } }
apache-2.0
0c500cefc029d1634415428dbce4598d
32.571429
121
0.697264
4.556787
false
false
false
false
tomhenne/Jerusalem
src/main/java/de/esymetric/jerusalem/ownDataRepresentation/geoData/Position.kt
1
219
package de.esymetric.jerusalem.ownDataRepresentation.geoData class Position { var latitude = 0.0 var longitude = 0.0 var altitude = 0.0 var elapsedTimeSec = 0 var nrOfTransitions: Byte = 0 }
apache-2.0
feeac00c405c4998dc0aaaecad3da892
22.555556
60
0.680365
3.981818
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/view/VLCDividerItemDecoration.kt
1
2785
package org.videolan.vlc.gui.view import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.RecyclerView open class VLCDividerItemDecoration(private val context: Context, private val orientation: Int, private val dividerDrawable: Drawable) : DividerItemDecoration(context, orientation) { private val bounds = Rect() init { setDrawable(dividerDrawable) } override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { if (parent.layoutManager == null || dividerDrawable == null) { return } if (orientation == VERTICAL) { drawVertical(c, parent) } else { drawHorizontal(c, parent) } } private fun drawVertical(canvas: Canvas, parent: RecyclerView) { canvas.save() val left: Int val right: Int if (parent.clipToPadding) { left = parent.paddingLeft right = parent.width - parent.paddingRight canvas.clipRect(left, parent.paddingTop, right, parent.height - parent.paddingBottom) } else { left = 0 right = parent.width } val childCount = parent.childCount - 1 for (i in 0 until childCount) { val child = parent.getChildAt(i) parent.getDecoratedBoundsWithMargins(child, bounds) val bottom = bounds.bottom + Math.round(child.translationY) val top = bottom - dividerDrawable.intrinsicHeight dividerDrawable.setBounds(left, top, right, bottom) dividerDrawable.draw(canvas) } canvas.restore() } private fun drawHorizontal(canvas: Canvas, parent: RecyclerView) { canvas.save() val top: Int val bottom: Int if (parent.clipToPadding) { top = parent.paddingTop bottom = parent.height - parent.paddingBottom canvas.clipRect(parent.paddingLeft, top, parent.width - parent.paddingRight, bottom) } else { top = 0 bottom = parent.height } val childCount = parent.childCount - 1 for (i in 0 until childCount) { val child = parent.getChildAt(i) parent.layoutManager!!.getDecoratedBoundsWithMargins(child, bounds) val right = bounds.right + Math.round(child.translationX) val left = right - dividerDrawable.intrinsicWidth dividerDrawable.setBounds(left, top, right, bottom) dividerDrawable.draw(canvas) } canvas.restore() } }
gpl-2.0
7e6939b93f17c252fb3cc6e6e40e943c
32.97561
182
0.620467
4.937943
false
false
false
false
TeamAmaze/AmazeFileManager
app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/texteditor/write/WriteTextFileTask.kt
1
3644
/* * Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager 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.amaze.filemanager.asynchronous.asynctasks.texteditor.write import android.content.Context import android.widget.Toast import androidx.activity.viewModels import androidx.annotation.MainThread import androidx.annotation.StringRes import com.amaze.filemanager.R import com.amaze.filemanager.asynchronous.asynctasks.Task import com.amaze.filemanager.fileoperations.exceptions.ShellNotRunningException import com.amaze.filemanager.fileoperations.exceptions.StreamNotFoundException import com.amaze.filemanager.ui.activities.texteditor.TextEditorActivity import com.amaze.filemanager.ui.activities.texteditor.TextEditorActivityViewModel import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.IOException import java.lang.ref.WeakReference class WriteTextFileTask( activity: TextEditorActivity, private val editTextString: String, private val textEditorActivityWR: WeakReference<TextEditorActivity>, private val appContextWR: WeakReference<Context> ) : Task<Unit, WriteTextFileCallable> { private var log: Logger = LoggerFactory.getLogger(WriteTextFileTask::class.java) private val task: WriteTextFileCallable init { val viewModel: TextEditorActivityViewModel by activity.viewModels() task = WriteTextFileCallable( activity, activity.contentResolver, viewModel.file, editTextString, viewModel.cacheFile, activity.isRootExplorer ) } override fun getTask(): WriteTextFileCallable = task @MainThread override fun onError(error: Throwable) { log.error("Error on text write", error) val applicationContext = appContextWR.get() ?: return @StringRes val errorMessage: Int = when (error) { is StreamNotFoundException -> { R.string.error_file_not_found } is IOException -> { R.string.error_io } is ShellNotRunningException -> { R.string.root_failure } else -> { R.string.error } } Toast.makeText(applicationContext, errorMessage, Toast.LENGTH_SHORT).show() } @MainThread override fun onFinish(value: Unit) { val applicationContext = appContextWR.get() ?: return Toast.makeText(applicationContext, R.string.done, Toast.LENGTH_SHORT).show() val textEditorActivity = textEditorActivityWR.get() ?: return val viewModel: TextEditorActivityViewModel by textEditorActivity.viewModels() viewModel.original = editTextString viewModel.modified = false textEditorActivity.invalidateOptionsMenu() } }
gpl-3.0
1eb3c150691fdb80a43ca90c006928c8
36.56701
107
0.714599
4.720207
false
false
false
false
tasks/tasks
app/src/androidTest/java/com/todoroo/astrid/adapter/CaldavManualSortTaskAdapterTest.kt
1
8238
package com.todoroo.astrid.adapter import com.natpryce.makeiteasy.MakeItEasy.with import com.natpryce.makeiteasy.PropertyValue import com.todoroo.astrid.api.CaldavFilter import com.todoroo.astrid.dao.TaskDao import com.todoroo.astrid.data.Task import dagger.hilt.android.testing.HiltAndroidTest import dagger.hilt.android.testing.UninstallModules import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test import org.tasks.LocalBroadcastManager import org.tasks.R import org.tasks.data.CaldavCalendar import org.tasks.data.CaldavDao import org.tasks.data.GoogleTaskDao import org.tasks.data.TaskContainer import org.tasks.data.TaskListQuery.getQuery import org.tasks.injection.InjectingTestCase import org.tasks.injection.ProductionModule import org.tasks.makers.CaldavTaskMaker.CALENDAR import org.tasks.makers.CaldavTaskMaker.REMOTE_PARENT import org.tasks.makers.CaldavTaskMaker.TASK import org.tasks.makers.CaldavTaskMaker.newCaldavTask import org.tasks.makers.TaskMaker.CREATION_TIME import org.tasks.makers.TaskMaker.PARENT import org.tasks.makers.TaskMaker.newTask import org.tasks.preferences.Preferences import org.tasks.time.DateTime import javax.inject.Inject @UninstallModules(ProductionModule::class) @HiltAndroidTest class CaldavManualSortTaskAdapterTest : InjectingTestCase() { @Inject lateinit var googleTaskDao: GoogleTaskDao @Inject lateinit var taskDao: TaskDao @Inject lateinit var caldavDao: CaldavDao @Inject lateinit var preferences: Preferences @Inject lateinit var localBroadcastManager: LocalBroadcastManager private lateinit var adapter: CaldavManualSortTaskAdapter private val tasks = ArrayList<TaskContainer>() private val filter = CaldavFilter(CaldavCalendar("calendar", "1234")) private val dataSource = object : TaskAdapterDataSource { override fun getItem(position: Int) = tasks[position] override fun getTaskCount() = tasks.size } @Before override fun setUp() { super.setUp() preferences.clear() preferences.setBoolean(R.string.p_manual_sort, true) tasks.clear() adapter = CaldavManualSortTaskAdapter(googleTaskDao, caldavDao, taskDao, localBroadcastManager) adapter.setDataSource(dataSource) } @Test fun moveToSamePositionIsNoop() { val created = DateTime(2020, 5, 17, 9, 53, 17) addTask(with(CREATION_TIME, created)) addTask(with(CREATION_TIME, created.plusSeconds(1))) move(0, 0) checkOrder(null, 0) checkOrder(null, 1) } @Test fun moveTaskToTopOfList() { val created = DateTime(2020, 5, 17, 9, 53, 17) addTask(with(CREATION_TIME, created)) addTask(with(CREATION_TIME, created.plusSeconds(1))) move(1, 0) checkOrder(created.minusSeconds(1), 1) checkOrder(null, 0) } @Test fun moveTaskToBottomOfList() { val created = DateTime(2020, 5, 17, 9, 53, 17) addTask(with(CREATION_TIME, created)) addTask(with(CREATION_TIME, created.plusSeconds(1))) move(0, 1) checkOrder(null, 1) checkOrder(created.plusSeconds(2), 0) } @Test fun moveDownToMiddleOfList() { val created = DateTime(2020, 5, 17, 9, 53, 17) addTask(with(CREATION_TIME, created)) addTask(with(CREATION_TIME, created.plusSeconds(1))) addTask(with(CREATION_TIME, created.plusSeconds(2))) addTask(with(CREATION_TIME, created.plusSeconds(3))) addTask(with(CREATION_TIME, created.plusSeconds(4))) move(0, 2) checkOrder(null, 1) checkOrder(null, 2) checkOrder(created.plusSeconds(3), 0) checkOrder(created.plusSeconds(4), 3) checkOrder(created.plusSeconds(5), 4) } @Test fun moveUpToMiddleOfList() { val created = DateTime(2020, 5, 17, 9, 53, 17) addTask(with(CREATION_TIME, created)) addTask(with(CREATION_TIME, created.plusSeconds(1))) addTask(with(CREATION_TIME, created.plusSeconds(2))) addTask(with(CREATION_TIME, created.plusSeconds(3))) addTask(with(CREATION_TIME, created.plusSeconds(4))) move(3, 1) checkOrder(null, 0) checkOrder(created.plusSeconds(1), 3) checkOrder(created.plusSeconds(2), 1) checkOrder(created.plusSeconds(3), 2) checkOrder(null, 4) } @Test fun moveDownNoShiftRequired() { val created = DateTime(2020, 5, 17, 9, 53, 17) addTask(with(CREATION_TIME, created)) addTask(with(CREATION_TIME, created.plusSeconds(1))) addTask(with(CREATION_TIME, created.plusSeconds(3))) addTask(with(CREATION_TIME, created.plusSeconds(4))) move(0, 1) checkOrder(null, 1) checkOrder(created.plusSeconds(2), 0) checkOrder(null, 2) checkOrder(null, 3) } @Test fun moveUpNoShiftRequired() { val created = DateTime(2020, 5, 17, 9, 53, 17) addTask(with(CREATION_TIME, created)) addTask(with(CREATION_TIME, created.plusSeconds(2))) addTask(with(CREATION_TIME, created.plusSeconds(3))) addTask(with(CREATION_TIME, created.plusSeconds(4))) move(2, 1) checkOrder(null, 0) checkOrder(created.plusSeconds(1), 2) checkOrder(null, 1) checkOrder(null, 3) } @Test fun moveToNewSubtask() { val created = DateTime(2020, 5, 17, 9, 53, 17) addTask(with(CREATION_TIME, created)) addTask(with(CREATION_TIME, created.plusSeconds(2))) move(1, 1, 1) checkOrder(null, 0) checkOrder(null, 1) } @Test fun moveToTopOfExistingSubtasks() { val created = DateTime(2020, 5, 17, 9, 53, 17) val parent = addTask(with(CREATION_TIME, created)) addTask(with(CREATION_TIME, created.plusSeconds(5)), with(PARENT, parent)) addTask(with(CREATION_TIME, created.plusSeconds(2))) move(2, 1, 1) checkOrder(null, 0) checkOrder(created.plusSeconds(4), 2) checkOrder(null, 1) } @Test fun indentingChangesParent() { val created = DateTime(2020, 5, 17, 9, 53, 17) addTask(with(CREATION_TIME, created)) addTask(with(CREATION_TIME, created.plusSeconds(2))) move(1, 1, 1) assertEquals(tasks[0].id, tasks[1].parent) } @Test fun deindentLastMultiLevelSubtask() { val created = DateTime(2020, 5, 17, 9, 53, 17) val grandparent = addTask(with(CREATION_TIME, created)) val parent = addTask(with(CREATION_TIME, created.plusSeconds(5)), with(PARENT, grandparent)) addTask(with(CREATION_TIME, created.plusSeconds(1)), with(PARENT, parent)) addTask(with(CREATION_TIME, created.plusSeconds(2)), with(PARENT, parent)) move(3, 3, 1) assertEquals(grandparent, tasks[3].parent) checkOrder(created.plusSeconds(6), 3) } private fun move(from: Int, to: Int, indent: Int = 0) = runBlocking { tasks.addAll(taskDao.fetchTasks { getQuery(preferences, filter, it) }) val adjustedTo = if (from < to) to + 1 else to // match DragAndDropRecyclerAdapter behavior adapter.moved(from, adjustedTo, indent) } private fun checkOrder(dateTime: DateTime, index: Int) = checkOrder(dateTime.toAppleEpoch(), index) private fun checkOrder(order: Long?, index: Int) = runBlocking { val sortOrder = caldavDao.getTask(adapter.getTask(index).id)!!.order if (order == null) { assertNull(sortOrder) } else { assertEquals(order, sortOrder) } } private fun addTask(vararg properties: PropertyValue<in Task?, *>): Long = runBlocking { val task = newTask(*properties) taskDao.createNew(task) val remoteParent = if (task.parent > 0) caldavDao.getRemoteIdForTask(task.parent) else null caldavDao.insert( newCaldavTask( with(TASK, task.id), with(CALENDAR, "1234"), with(REMOTE_PARENT, remoteParent))) task.id } }
gpl-3.0
ca293f766ac35b06b81a1c4faca3116c
32.49187
103
0.663753
3.945402
false
true
false
false
rcgroot/open-gpstracker-ng
studio/base/src/main/java/nl/sogeti/android/gpstracker/ng/base/common/controllers/content/ContentController.kt
1
1829
package nl.sogeti.android.gpstracker.ng.base.common.controllers.content import android.content.Context import android.net.Uri import android.os.Handler import android.os.Looper import javax.inject.Inject /** * Control the observing and monitoring for a observable uri content. */ class ContentController @Inject constructor(private val context: Context) { private var listener: Listener? = null private val contentObserver = ContentObserver() fun registerObserver(listener: Listener, toUri: Uri?) { contentObserver.unregister() this.listener = listener contentObserver.register(toUri) } fun unregisterObserver() { contentObserver.unregister() this.listener = null } private inner class ContentObserver : android.database.ContentObserver(Handler(Looper.getMainLooper())) { private var registeredUri: Uri? = null fun register(uri: Uri?) { unregister() registeredUri = uri if (uri != null && uri.lastPathSegment != NO_CONTENT_ID.toString()) { context.contentResolver.registerContentObserver(uri, true, this) } } fun unregister() { val uri = registeredUri if (uri != null && uri.lastPathSegment != NO_CONTENT_ID.toString()) { context.contentResolver.unregisterContentObserver(contentObserver) registeredUri = null } } override fun onChange(selfChange: Boolean, changedUri: Uri) { registeredUri?.let { listener?.onChangeUriContent(it, changedUri) } } } interface Listener { fun onChangeUriContent(contentUri: Uri, changesUri: Uri) } companion object { const val NO_CONTENT_ID = -1L } }
gpl-3.0
0e678d24e9d188d9056c48fcb3aee0ec
27.578125
109
0.636413
4.890374
false
false
false
false
ExMCL/ExMCL
ExMCL Mod Installer/src/main/kotlin/com/n9mtq4/exmcl/modinstaller/ui/PatchingWindow.kt
1
1817
/* * MIT License * * Copyright (c) 2016 Will (n9Mtq4) Bresnahan * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.n9mtq4.exmcl.modinstaller.ui import java.awt.Component import javax.swing.JDialog import javax.swing.JProgressBar /** * Created by will on 3/8/16 at 2:46 PM. * * @author Will "n9Mtq4" Bresnahan */ class PatchingWindow(val parent: Component) : JDialog() { private val progress: JProgressBar init { title = "Patching Minecraft" defaultCloseOperation = DO_NOTHING_ON_CLOSE this.progress = JProgressBar(0, 100) progress.isIndeterminate = true add(progress) forceUpdate() } internal fun forceUpdate() { pack() isVisible = true setSize(300, size.height) isResizable = false setLocationRelativeTo(parent) } }
mit
20121617a0c153fb6b47f6eb032ddab0
28.306452
81
0.739681
4.028825
false
false
false
false
ashdavies/data-binding
mobile/src/main/kotlin/io/ashdavies/playground/conferences/ConferencesRepository.kt
1
1114
package io.ashdavies.playground.conferences import androidx.lifecycle.LiveData import androidx.paging.DataSource import androidx.paging.LivePagedListBuilder import androidx.paging.PagedList import io.ashdavies.playground.github.ConferenceDao import io.ashdavies.playground.network.Conference import kotlinx.coroutines.CoroutineScope internal class ConferencesRepository( private val dao: ConferenceDao, private val service: ConferencesService ) { fun conferences(scope: CoroutineScope): ConferencesViewState { val factory: DataSource.Factory<Int, Conference> = dao.conferences() val callback = ConferencesBoundaryCallback(dao, scope, service) val config: PagedList.Config = PagedList.Config.Builder() .setPageSize(PAGE_SIZE) .setEnablePlaceholders(true) .setPrefetchDistance(50) .build() val data: LiveData<PagedList<Conference>> = LivePagedListBuilder(factory, config) .setBoundaryCallback(callback) .build() return ConferencesViewState(data, callback.error) } companion object { private const val PAGE_SIZE = 20 } }
apache-2.0
f18e5956076a9ab5a3692c7c62690d40
29.108108
85
0.762118
4.565574
false
true
false
false
bailuk/AAT
aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/util/GtkTimer.kt
1
532
package ch.bailu.aat_gtk.util import ch.bailu.aat_lib.util.Timer import ch.bailu.gtk.GTK import ch.bailu.gtk.glib.Glib class GtkTimer : Timer { private var run: Runnable? = null private val timeout = Glib.OnSourceFunc { val r = run if (r is Runnable) { r.run() } GTK.FALSE } override fun kick(run: Runnable, interval: Long) { this.run = run Glib.timeoutAdd(interval.toInt(), timeout, null) } override fun cancel() { run = null } }
gpl-3.0
2b68b088e5502023fbbdf9546ce17de4
19.461538
56
0.588346
3.432258
false
false
false
false
bailuk/AAT
aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/view/solid/PreferencesStackView.kt
1
1863
package ch.bailu.aat_gtk.view.solid import ch.bailu.aat_gtk.config.Layout import ch.bailu.aat_gtk.lib.extensions.margin import ch.bailu.aat_gtk.view.UiController import ch.bailu.aat_gtk.view.stack.LazyStackView import ch.bailu.aat_gtk.view.stack.StackViewSelector import ch.bailu.aat_lib.preferences.StorageInterface import ch.bailu.aat_lib.preferences.general.SolidPresetCount import ch.bailu.aat_lib.resources.Res import ch.bailu.aat_lib.resources.ToDo import ch.bailu.gtk.GTK import ch.bailu.gtk.gtk.* import ch.bailu.gtk.type.Str class PreferencesStackView(controller: UiController, storage: StorageInterface, app: Application, window: Window) { private val stack = LazyStackView(Stack().apply { margin(Layout.margin) hexpand = GTK.TRUE vexpand = GTK.TRUE transitionType = StackTransitionType.CROSSFADE },"preferences-stack", storage).apply { add(Res.str().p_general()) { GeneralPreferencesView(storage, app, window).scrolled } for (i in 0 until SolidPresetCount.DEFAULT) { val activity = ActivityPreferencesView(storage, i) add(activity.title) { activity.scrolled } } add(Res.str().p_map()) { MapPreferencesView(storage, app, window).scrolled } } val layout = Box(Orientation.VERTICAL, 0) private val box = Box(Orientation.HORIZONTAL, 0) private val selector = StackViewSelector(stack) init { val back = Button.newWithLabelButton(Str(ToDo.translate("Back"))) back.margin(Layout.margin) back.onClicked { controller.back() } box.append(back) box.append(selector.combo) layout.append(box) layout.append(stack.widget) layout.show() } fun showMap() { stack.show(stack.lastIndex()) } }
gpl-3.0
3cf604ebb5350fbb0c044416e30df864
29.540984
115
0.670424
3.865145
false
false
false
false
aglne/mycollab
mycollab-scheduler/src/main/java/com/mycollab/schedule/spring/DefaultScheduleConfiguration.kt
3
3347
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.schedule.spring import com.mycollab.configuration.IDeploymentMode import com.mycollab.module.project.schedule.email.service.OverdueProjectTicketsNotificationJob import com.mycollab.schedule.AutowiringSpringBeanJobFactory import com.mycollab.schedule.jobs.LiveInstanceMonitorJob import com.mycollab.schedule.jobs.ProjectSendingRelayEmailNotificationJob import org.quartz.CronTrigger import org.quartz.Scheduler import org.quartz.Trigger import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.ApplicationContext import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.scheduling.quartz.CronTriggerFactoryBean import org.springframework.scheduling.quartz.JobDetailFactoryBean import org.springframework.scheduling.quartz.SchedulerFactoryBean import java.util.* import javax.sql.DataSource /** * @author MyCollab Ltd. * @since 4.6.0 */ @Configuration class DefaultScheduleConfiguration { @Bean fun projectSendRelayNotificationEmailJob(): JobDetailFactoryBean { val bean = JobDetailFactoryBean() bean.setDurability(true) bean.setJobClass(ProjectSendingRelayEmailNotificationJob::class.java) return bean } @Bean fun projectOverdueAssignmentsNotificationEmailJob(): JobDetailFactoryBean { val bean = JobDetailFactoryBean() bean.setDurability(true) bean.setJobClass(OverdueProjectTicketsNotificationJob::class.java) return bean } @Bean fun liveInstanceMonitorJobBean(): JobDetailFactoryBean { val bean = JobDetailFactoryBean() bean.setDurability(true) bean.setJobClass(LiveInstanceMonitorJob::class.java) return bean } @Bean fun projectSendRelayNotificationEmailTrigger(): CronTriggerFactoryBean { val bean = CronTriggerFactoryBean() bean.setJobDetail(projectSendRelayNotificationEmailJob().`object`!!) bean.setCronExpression("0 * * * * ?") return bean } @Bean fun projectOverdueAssignmentsNotificationEmailTrigger(): CronTriggerFactoryBean { val bean = CronTriggerFactoryBean() bean.setJobDetail(projectOverdueAssignmentsNotificationEmailJob().`object`!!) bean.setCronExpression("0 0 0 * * ?") return bean } @Bean fun liveInstanceMonitorTrigger(): CronTriggerFactoryBean { val bean = CronTriggerFactoryBean() bean.setJobDetail(liveInstanceMonitorJobBean().`object`!!) bean.setCronExpression("0 0 6 * * ?") return bean } }
agpl-3.0
200c9230c0bd063cdee5d54f21e96da5
35.769231
94
0.753437
4.540027
false
false
false
false
lambdasoup/watchlater
app/src/main/java/com/lambdasoup/watchlater/data/IntentResolverRepository.kt
1
3267
/* * Copyright (c) 2015 - 2022 * * Maximilian Hille <[email protected]> * Juliane Lehmann <[email protected]> * * This file is part of Watch Later. * * Watch Later 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. * * Watch Later 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 Watch Later. If not, see <http://www.gnu.org/licenses/>. */ package com.lambdasoup.watchlater.data import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.content.pm.verify.domain.DomainVerificationManager import android.content.pm.verify.domain.DomainVerificationUserState import android.net.Uri import android.os.Build import androidx.annotation.RequiresApi import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData class IntentResolverRepository( private val context: Context, private val packageManager: PackageManager, ) { private val _resolverState = MutableLiveData<ResolverProblems>() fun getResolverState(): LiveData<ResolverProblems> { return _resolverState } fun update() { _resolverState.value = ResolverProblems( watchLaterIsDefault = watchLaterIsDefault(), verifiedDomainsMissing = if (Build.VERSION.SDK_INT >= 31) { domainVerificationMissing() } else { 0 } ) } @RequiresApi(31) private fun domainVerificationMissing(): Int { val domainVerificationManager = context.getSystemService(DomainVerificationManager::class.java) val wlState = domainVerificationManager.getDomainVerificationUserState(context.packageName) ?: throw RuntimeException("app does not declare any domains") val watchlater = wlState.hostToStateMap.count { entry -> entry.value == DomainVerificationUserState.DOMAIN_STATE_NONE } return watchlater } private fun watchLaterIsDefault(): Boolean { val resolveIntent = Intent(Intent.ACTION_VIEW, Uri.parse(EXAMPLE_URI)) val resolveInfo = packageManager.resolveActivity(resolveIntent, PackageManager.MATCH_DEFAULT_ONLY) return when (resolveInfo?.activityInfo?.name) { // youtube is set as default app to launch with, no chooser ACTIVITY_WATCHLATER -> true // some unknown app is set as the default app to launch with, without chooser. else -> false } } data class ResolverProblems( val watchLaterIsDefault: Boolean, val verifiedDomainsMissing: Int, ) companion object { private const val ACTIVITY_WATCHLATER = "com.lambdasoup.watchlater.ui.add.AddActivity" private const val EXAMPLE_URI = "https://www.youtube.com/watch?v=tntOCGkgt98" } }
gpl-3.0
0f7924ffc73b00dac47ffd3db7e72318
34.51087
99
0.701867
4.680516
false
false
false
false
langara/MyIntent
myfragments/src/main/java/pl/mareklangiewicz/myfragments/MyDrawableTestsFragment.kt
1
7477
package pl.mareklangiewicz.myfragments import android.animation.ObjectAnimator import android.os.Bundle import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.LinearInterpolator import android.widget.FrameLayout import android.widget.SeekBar import androidx.cardview.widget.CardView import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.mf_my_dawable_tests_fragment.grid_view import kotlinx.android.synthetic.main.mf_my_dawable_tests_fragment.seek_bar_level import kotlinx.android.synthetic.main.mf_my_dawable_tests_fragment.seek_bar_stroke_width import pl.mareklangiewicz.mydrawables.MyArrowDrawable import pl.mareklangiewicz.mydrawables.MyCheckDrawable import pl.mareklangiewicz.mydrawables.MyLessDrawable import pl.mareklangiewicz.mydrawables.MyMagicLinesDrawable import pl.mareklangiewicz.mydrawables.MyPlayStopDrawable import pl.mareklangiewicz.mydrawables.MyPlusDrawable import pl.mareklangiewicz.myutils.e import pl.mareklangiewicz.upue.e import pl.mareklangiewicz.myutils.i import pl.mareklangiewicz.myutils.w class MyDrawableTestsFragment : MyFragment(), View.OnClickListener, SeekBar.OnSeekBarChangeListener { private val drawables = arrayOf( MyPlusDrawable().apply { color = 0xff00a000.toInt(); rotateTo = 180f }, MyPlusDrawable().apply { colorFrom = 0xffc00000.toInt(); colorTo = 0xff0000c0.toInt(); rotateTo = 90f }, MyPlusDrawable().apply { color = 0xff00a000.toInt(); rotateTo = -360f }, MyArrowDrawable().apply { color = 0xff008080.toInt(); rotateFrom = -180f }, MyArrowDrawable().apply { color = 0xff008000.toInt(); rotateFrom = 180f }, MyArrowDrawable().apply { color = 0xff808000.toInt(); rotateFrom = 360f }, MyPlayStopDrawable().apply { colorFrom = 0xff0000c0.toInt(); colorTo = 0xffc00000.toInt(); rotateTo = 180f }, MyPlayStopDrawable().apply { colorFrom = 0xff0000c0.toInt(); colorTo = 0xffc00000.toInt(); rotateTo = 90f }, MyCheckDrawable().apply { colorFrom = 0xff00f000.toInt(); colorTo = 0xfff00000.toInt(); rotateTo = 90f }, MyCheckDrawable().apply { colorFrom = 0xff00a000.toInt(); colorTo = 0xffa00000.toInt(); rotateTo = 180f }, MyCheckDrawable().apply { colorFrom = 0xff00c000.toInt(); colorTo = 0xffc00000.toInt(); rotateTo = -180f }, MyCheckDrawable().apply { colorFrom = 0xff0000f0.toInt(); colorTo = 0xfff00000.toInt(); rotateTo = 360f }, MyLessDrawable().apply { color = 0xffa000a0.toInt(); rotateFrom = -180f }, MyLessDrawable().apply { color = 0xff8000a0.toInt(); rotateTo = 180f }, MyLessDrawable().apply { color = 0xff20a050.toInt(); rotateTo = 360f }, MyMagicLinesDrawable().apply { setLines(0, 3000, 3000, 6000, 6000, 9000, 9000, 10000, 0, 10000); color = 0x400000a0 }, MyMagicLinesDrawable().apply { setRandomLines(2); color = 0x400000a0 }, MyMagicLinesDrawable().apply { setRandomLines(5); color = 0x400000a0 }, MyMagicLinesDrawable().apply { setRandomLines(10); color = 0x400000a0 }, MyMagicLinesDrawable().apply { setRandomLines(8); colorFrom = 0x000000a0; colorTo = 0x600000a0 }, MyMagicLinesDrawable().apply { color = 0x400000a0 }, MyMagicLinesDrawable().apply { color = 0x400000a0 } ) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) //just for logging return inflater.inflate(R.layout.mf_my_dawable_tests_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) seek_bar_level.setOnSeekBarChangeListener(this) seek_bar_stroke_width.setOnSeekBarChangeListener(this) seek_bar_stroke_width.progress = 12 grid_view.layoutManager = GridLayoutManager(activity, 4) grid_view.adapter = MyAdapter() } override fun onResume() { super.onResume() val d = MyCheckDrawable().apply { strokeWidth = 6f; colorFrom = 0xff0000f0.toInt(); colorTo = 0xff00f000.toInt(); rotateTo = 360f } manager?.fab?.setImageDrawable(d) manager?.fab?.setOnClickListener { ObjectAnimator.ofInt(d, "level", 0, 10000, 10000, 0).setDuration(7000).start() log.w("[SNACK]FAB Clicked!") } manager?.fab?.show() } override fun onPause() { manager?.fab?.setOnClickListener(null) manager?.fab?.hide() super.onPause() } override fun onDestroyView() { grid_view.adapter = null super.onDestroyView() } override fun onClick(v: View) { val tag = v.getTag(R.id.mf_tag_animator) if (tag is ObjectAnimator) tag.start() } override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { if (seekBar === seek_bar_level) { for (drawable in drawables) drawable.level = progress } else if (seekBar === seek_bar_stroke_width) { for (drawable in drawables) drawable.strokeWidth = progress.toFloat() } } override fun onStartTrackingTouch(seekBar: SeekBar) { } override fun onStopTrackingTouch(seekBar: SeekBar) { if (seekBar === seek_bar_level) log.i(String.format("level = %d", seekBar.progress)) else if (seekBar === seek_bar_stroke_width) log.i(String.format("stroke width = %d", seekBar.progress)) else log.e("Unknown seek bar.") } private class MyViewHolder(v: View, val content: View) : RecyclerView.ViewHolder(v) private inner class MyAdapter() : RecyclerView.Adapter<MyViewHolder>() { init { setHasStableIds(true) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val content = View(activity) val contentparams = FrameLayout.LayoutParams(200, 200) contentparams.gravity = Gravity.CENTER content.layoutParams = contentparams val card = CardView(activity!!) val cardparams = ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) cardparams.setMargins(8, 8, 8, 8) card.layoutParams = cardparams card.addView(content) return MyViewHolder(card, content) } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { val content = holder.content val drawable = drawables[position] val animator = ObjectAnimator.ofInt(drawable, "level", 0, 10000, 10000, 0) animator.duration = 3000 animator.interpolator = LinearInterpolator() content.background = drawable content.setTag(R.id.mf_tag_animator, animator) content.setOnClickListener(this@MyDrawableTestsFragment) } override fun getItemCount(): Int { return drawables.size } override fun getItemId(position: Int): Long { return position.toLong() // our array is constant. } } }
apache-2.0
1963888c24501ec5a4f20a7440dc2e40
44.042169
139
0.671392
4.270131
false
false
false
false
mctoyama/PixelClient
src/main/kotlin/org/pixelndice/table/pixelclient/ds/Account.kt
1
1641
package org.pixelndice.table.pixelclient.ds import org.pixelndice.table.pixelprotocol.Protobuf import java.util.* /** * Account * * Account class for PixelClient * * @author Marcelo Costa Toyama * * @property id user id * @property email user email * @property name user name * @property password user password * @property isAllowed true if user is allowed to play the campaign game * */ open class Account { var id: Int = 0 var name: String = "" var email: String = "" var password: String = "" var isAllowed: Boolean = true override fun toString(): String { return "$name: $email" } override fun equals(other: Any?): Boolean { if (other == null) return false if (other !is Account) return false if (other === this) return true if( other.id == 0 || this.id == 0) return false return this.id == other.id } override fun hashCode(): Int { return Objects.hash(id) } fun toProtobuf(): Protobuf.Account.Builder{ val account = Protobuf.Account.newBuilder() account.id = this.id account.name = this.name account.email = this.email account.isAllowed = this.isAllowed return account } companion object { fun fromProtobuf(packet: Protobuf.Account): Account{ val account = Account() account.id = packet.id account.name = packet.name account.email = packet.email account.isAllowed = packet.isAllowed return account } } }
bsd-2-clause
35ac6266a20bf47675dbce1d20fd2d3f
20.038462
72
0.588665
4.41129
false
false
false
false
shlusiak/Freebloks-Android
app/src/main/java/de/saschahlusiak/freebloks/preferences/HeadersFragment.kt
1
2103
package de.saschahlusiak.freebloks.preferences import android.content.Intent import android.os.Bundle import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.TwoStatePreference import de.saschahlusiak.freebloks.Global import de.saschahlusiak.freebloks.R import de.saschahlusiak.freebloks.donate.DonateActivity /** * The headers for [SettingsActivity] if in multi pane mode */ class HeadersFragment : PreferenceFragmentCompat() { private lateinit var headers: List<TwoStatePreference?> override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.preferences_headers, rootKey) headers = listOf( findPreference(SettingsFragment.SCREEN_INTERFACE), findPreference(SettingsFragment.SCREEN_DISPLAY), findPreference(SettingsFragment.SCREEN_MISC), findPreference(SettingsFragment.SCREEN_STATISTICS), findPreference(SettingsFragment.SCREEN_ABOUT) ) headers.forEach { pref -> pref?.setOnPreferenceClickListener { onPreferenceClick(pref) } } // donate is not a TwoStatePreference findPreference<Preference>(SettingsFragment.SCREEN_DONATE)?.apply { if (Global.IS_VIP) { isVisible = false } else { setOnPreferenceClickListener { val intent = Intent(requireContext(), DonateActivity::class.java) startActivity(intent) true } } } arguments?.getString(SettingsFragment.KEY_SCREEN)?.let { setChecked(it) } } private fun onPreferenceClick(pref: TwoStatePreference): Boolean { setChecked(pref.key) // fall through to default handler return false } private fun setChecked(key: String) { // uncheck all others headers.forEach { it?.isChecked = false } findPreference<TwoStatePreference>(key)?.isChecked = true } }
gpl-2.0
aa1bb5a60b9dcc6784f0b4f20c1c5e32
32.396825
85
0.666191
5.548813
false
false
false
false
stripe/stripe-android
paymentsheet/src/main/java/com/stripe/android/paymentsheet/PaymentSheetListFragment.kt
1
1187
package com.stripe.android.paymentsheet import androidx.fragment.app.activityViewModels internal class PaymentSheetListFragment() : BasePaymentMethodsListFragment( canClickSelectedItem = false ) { private val activityViewModel by activityViewModels<PaymentSheetViewModel> { PaymentSheetViewModel.Factory { requireNotNull( requireArguments().getParcelable(PaymentSheetActivity.EXTRA_STARTER_ARGS) ) } } override val sheetViewModel: PaymentSheetViewModel by lazy { activityViewModel } override fun transitionToAddPaymentMethod() { activityViewModel.transitionTo( PaymentSheetViewModel.TransitionTarget.AddPaymentMethodFull(config) ) } override fun onResume() { super.onResume() sheetViewModel.headerText.value = getString( if ( sheetViewModel.isLinkEnabled.value == true || sheetViewModel.isGooglePayReady.value == true ) { R.string.stripe_paymentsheet_pay_using } else { R.string.stripe_paymentsheet_select_payment_method } ) } }
mit
51ee910f16fee0bb93f689b4ae2d6118
30.236842
89
0.651222
5.7343
false
false
false
false
android/xAnd11
app/src/main/java/org/monksanctum/xand11/ui/LifecyclePreferenceFragment.kt
1
2174
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.monksanctum.xand11.ui import androidx.preference.PreferenceFragment import androidx.preference.Preference import androidx.preference.PreferenceGroup import androidx.preference.PreferenceScreen abstract class LifecyclePreferenceFragment : PreferenceFragment() { override fun onResume() { super.onResume() resumePreferences(preferenceScreen) } private fun resumePreferences(preference: PreferenceGroup?) { if (preference == null) { return } for (i in 0 until preference.preferenceCount) { val child = preference.getPreference(i) if (child is LifecyclePreference) { (child as LifecyclePreference).onResume() } if (child is PreferenceGroup) { resumePreferences(child) } } } override fun onPause() { super.onPause() pausePreferences(preferenceScreen) } private fun pausePreferences(preference: PreferenceGroup?) { if (preference == null) { return } for (i in 0 until preference.preferenceCount) { val child = preference.getPreference(i) if (child is LifecyclePreference) { (child as LifecyclePreference).onPause() } if (child is PreferenceGroup) { pausePreferences(child) } } } interface LifecyclePreference { fun onResume() fun onPause() } }
apache-2.0
a7ae7cf322624f7d49f4b3ddd9209b4a
29.970588
75
0.623275
5.009217
false
false
false
false
AndroidX/androidx
compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/text/input/CursorAnchorInfoBuilder.kt
3
2827
/* * 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.ui.text.input import android.graphics.Matrix import android.view.inputmethod.CursorAnchorInfo import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.style.ResolvedTextDirection /** * Helper function to build [CursorAnchorInfo](https://developer.android.com/reference/android/view/inputmethod/CursorAnchorInfo). * * @param textFieldValue required to set text, composition and selection information into the * CursorAnchorInfo. * @param textLayoutResult TextLayoutResult for the [textFieldValue] used to enter cursor and * character information * @param matrix Matrix used to convert local coordinates to global coordinates. */ internal fun CursorAnchorInfo.Builder.build( textFieldValue: TextFieldValue, textLayoutResult: TextLayoutResult, matrix: Matrix ): CursorAnchorInfo { reset() setMatrix(matrix) val selectionStart = textFieldValue.selection.min val selectionEnd = textFieldValue.selection.max setSelectionRange(selectionStart, selectionEnd) setInsertionMarker(selectionStart, textLayoutResult) // set composition val compositionStart = textFieldValue.composition?.min ?: -1 val compositionEnd = textFieldValue.composition?.max ?: -1 if (compositionStart in 0 until compositionEnd) { setComposingText( compositionStart, textFieldValue.text.subSequence(compositionStart, compositionEnd) ) } return build() } private fun CursorAnchorInfo.Builder.setInsertionMarker( selectionStart: Int, textLayoutResult: TextLayoutResult ): CursorAnchorInfo.Builder { if (selectionStart < 0) return this val cursorRect = textLayoutResult.getCursorRect(selectionStart) val isRtl = textLayoutResult.getBidiRunDirection(selectionStart) == ResolvedTextDirection.Rtl var flags = 0 if (isRtl) flags = flags or CursorAnchorInfo.FLAG_IS_RTL // Sets the location of the text insertion point (zero width cursor) as a rectangle in local // coordinates. setInsertionMarkerLocation( cursorRect.left, cursorRect.top, cursorRect.bottom, cursorRect.bottom, flags ) return this }
apache-2.0
cbcd33373cb37b22fa1ade8f648c1bb3
32.270588
130
0.747789
4.727425
false
false
false
false
erickok/borefts2015
android/app/src/main/java/nl/brouwerijdemolen/borefts2013/gui/BoreftsActivity.kt
1
5465
package nl.brouwerijdemolen.borefts2013.gui import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentStatePagerAdapter import androidx.viewpager.widget.ViewPager import com.google.android.material.snackbar.Snackbar import kotlinx.android.synthetic.main.activity_main.* import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import nl.brouwerijdemolen.borefts2013.R import nl.brouwerijdemolen.borefts2013.ext.startLink import nl.brouwerijdemolen.borefts2013.gui.components.AppRater import nl.brouwerijdemolen.borefts2013.gui.components.Exporter import nl.brouwerijdemolen.borefts2013.gui.components.getMolenString import nl.brouwerijdemolen.borefts2013.gui.screens.* import org.koin.android.ext.android.inject import java.io.File class BoreftsActivity : AppCompatActivity() { private val appRater: AppRater by inject() private val infoFragment by lazy { InfoFragment() } private val brewersFragment by lazy { BrewersFragment() } private val stylesFragment by lazy { StylesFragment() } private val starsFragment by lazy { StarsFragment() } private val twitterFragment by lazy { TwitterFragment() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setupViewPager() setupToolbar() hitAppRater() } private fun setupToolbar() { title_text.text = getMolenString(title_text.text) title_toobar.inflateMenu(R.menu.activity_start) // Only show refresh button on Twitter page tabs_viewpager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { val refreshMenuItem = title_toobar.menu.findItem(R.id.action_refresh) override fun onPageScrollStateChanged(state: Int) = Unit override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) = Unit override fun onPageSelected(position: Int) { refreshMenuItem.isVisible = position == 4 } }) // Handle toolbar menu clicks title_toobar.setOnMenuItemClickListener { when (it.itemId) { R.id.action_refresh -> twitterFragment.refreshFeed() R.id.action_export -> prepareBeersExport() R.id.action_sendcorrection -> prepareCorrectionEmail() R.id.action_about -> AboutFragment().show(supportFragmentManager, "about") } true } } private fun setupViewPager() { tabs_viewpager.adapter = TabsAdapter() tabs_tablayout.setupWithViewPager(tabs_viewpager) } private fun hitAppRater() { appRater.hit() if (appRater.shouldShow()) { Snackbar.make(tabs_viewpager, R.string.rate_title, 5_000).apply { setActionTextColor(ContextCompat.getColor(this@BoreftsActivity, R.color.yellow)) setAction(R.string.rate_confirm) { appRater.block() startLink(Uri.parse("market://details?id=nl.brouwerijdemolen.borefts2013")) } show() } } } private fun prepareBeersExport() = GlobalScope.launch { val csv = File(cacheDir, "export/borefts2019_export.csv") Exporter().writeTo(csv) val content = FileProvider.getUriForFile(this@BoreftsActivity, "nl.brouwerijdemolen.borefts2013.fileprovider", csv) val shareIntent = Intent(Intent.ACTION_SEND) .setDataAndType(content, "text/csv") .setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) .putExtra(Intent.EXTRA_STREAM, content) startActivity(Intent.createChooser(shareIntent, getString(R.string.action_export))) } private fun prepareCorrectionEmail() { val startEmail = Intent(Intent.ACTION_SEND).apply { type = "message/rfc822" putExtra(Intent.EXTRA_EMAIL, arrayOf("[email protected]")) putExtra(Intent.EXTRA_SUBJECT, "Borefts 2019 Android app correction") } try { startActivity(startEmail) } catch (e: ActivityNotFoundException) { // Ignore; normal devices always have an app to send emails, but at least do not crash } } inner class TabsAdapter : FragmentStatePagerAdapter(supportFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) { override fun getCount() = 5 override fun getItem(position: Int): Fragment { return when (position) { 0 -> infoFragment 1 -> brewersFragment 2 -> stylesFragment 3 -> starsFragment else -> twitterFragment } } override fun getPageTitle(position: Int): CharSequence? { return when (position) { 0 -> getString(R.string.action_info) 1 -> getString(R.string.action_brewers) 2 -> getString(R.string.action_styles) 3 -> getString(R.string.action_stars) else -> getString(R.string.action_twitter) } } } }
gpl-3.0
00ca689e8e1067306f37a372b4bea999
38.316547
123
0.661482
4.748045
false
false
false
false
erickok/borefts2015
android/app/src/main/java/nl/brouwerijdemolen/borefts2013/gui/screens/MapActivity.kt
1
5205
package nl.brouwerijdemolen.borefts2013.gui.screens import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.os.Handler import android.util.TypedValue import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMapOptions import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.LatLng import com.google.android.material.snackbar.Snackbar import kotlinx.android.synthetic.main.activity_map.* import nl.brouwerijdemolen.borefts2013.R import nl.brouwerijdemolen.borefts2013.ext.KEY_ARGS import nl.brouwerijdemolen.borefts2013.ext.arg import nl.brouwerijdemolen.borefts2013.ext.observeNonNull import nl.brouwerijdemolen.borefts2013.gui.components.ResourceProvider import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf class MapActivity : AppCompatActivity() { private val mapViewModel: MapViewModel by viewModel(parameters = { parametersOf(arg(KEY_ARGS)) }) private val res: ResourceProvider by inject() private lateinit var mapView: BoreftsMapView @SuppressLint("MissingPermission") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_map) title_toolbar.setNavigationIcon(R.drawable.ic_back) title_toolbar.setNavigationOnClickListener { finish() } // If we have no location access, ask for the runtime permission (unless marked as never ask again) if (!hasLocationPermission()) { Snackbar.make(map_holder, R.string.general_location_permission, Snackbar.LENGTH_INDEFINITE).apply { setActionTextColor(res.getColor(R.color.yellow)) setAction(R.string.general_location_ok) { ActivityCompat.requestPermissions(this@MapActivity, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_PERMISSION) } show() } } mapView = BoreftsMapView(this, GoogleMapOptions()).apply { onCreate(savedInstanceState) getMapAsync { // Pad map controls below action bar val actionBarValue = TypedValue() theme.resolveAttribute(R.attr.actionBarSize, actionBarValue, true) it.setPadding(0, TypedValue.complexToDimensionPixelSize(actionBarValue.data, resources.displayMetrics), 0, 0) // Start camera on festival terrain it.moveCamera(CameraUpdateFactory.newCameraPosition( CameraPosition.Builder() .target(LatLng(52.085114, 4.740697)) .zoom(17.1f) .bearing(6f).build())) // Show location permission request if we do not have it if (hasLocationPermission()) { it.isMyLocationEnabled = true } // Navigation it.uiSettings.isCompassEnabled = true handleInfoWindowClicks(mapViewModel::openBrewer) // Schedule zooming to festival terrain Handler().postDelayed({ it.animateCamera(CameraUpdateFactory.newCameraPosition( CameraPosition.Builder().target(LatLng(52.084515, 4.739977)).zoom(18f).bearing(3.3f).build())) }, 1500) } } map_holder.addView(mapView) mapViewModel.state.observeNonNull(this) { if (it is MapUiModel.Success) { mapView.showBrewers(it.brewers, it.focusBrewerId) mapView.showAreas(it.areas) mapView.showPois(it.pois, it.focusPoiId) } } } private fun hasLocationPermission(): Boolean { return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED } override fun onStart() { super.onStart() mapView.onStart() } override fun onResume() { super.onResume() mapView.onResume() } override fun onPause() { super.onPause() mapView.onPause() } override fun onStop() { super.onStop() mapView.onStop() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) mapView.onSaveInstanceState(outState) } override fun onDestroy() { super.onDestroy() mapView.onDestroy() } companion object { private const val REQUEST_PERMISSION = 0 operator fun invoke(context: Context, focusBrewerId: Int? = null, focusPoiId: String? = null): Intent = Intent(context, MapActivity::class.java).putExtra(KEY_ARGS, MapViewModelArgs(focusBrewerId, focusPoiId)) } }
gpl-3.0
d51132b5552cd18605d6e24d36bc6f1a
37.272059
142
0.66244
4.85541
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/relocation/BringIntoViewResponder.kt
3
15114
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.relocation import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.geometry.Rect import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.modifier.ModifierLocalProvider import androidx.compose.ui.modifier.ProvidableModifierLocal import androidx.compose.ui.platform.debugInspectorInfo import kotlinx.coroutines.Job import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.job import kotlinx.coroutines.launch /** * A parent that can respond to [bringChildIntoView] requests from its children, and scroll so that * the item is visible on screen. To apply a responder to an element, pass it to the * [bringIntoViewResponder] modifier. * * When a component calls [BringIntoViewRequester.bringIntoView], the * [BringIntoView ModifierLocal][ModifierLocalBringIntoViewParent] is read to gain access to the * [BringIntoViewResponder], which is responsible for, in order: * * 1. Calculating a rectangle that its parent responder should bring into view by returning it from * [calculateRectForParent]. * 2. Performing any scroll or other layout adjustments needed to ensure the requested rectangle is * brought into view in [bringChildIntoView]. * * Here is a sample defining a custom [BringIntoViewResponder]: * @sample androidx.compose.foundation.samples.BringIntoViewResponderSample * * Here is a sample where a composable is brought into view: * @sample androidx.compose.foundation.samples.BringIntoViewSample * * Here is a sample where a part of a composable is brought into view: * @sample androidx.compose.foundation.samples.BringPartOfComposableIntoViewSample * * @see BringIntoViewRequester */ @ExperimentalFoundationApi interface BringIntoViewResponder { /** * Return the rectangle in this node that should be brought into view by this node's parent, * in coordinates relative to this node. If this node needs to adjust itself to bring * [localRect] into view, the returned rectangle should be the destination rectangle that * [localRect] will eventually occupy once this node's content is adjusted. * * @param localRect The rectangle that should be brought into view, relative to this node. This * will be the same rectangle passed to [bringChildIntoView]. * @return The rectangle in this node that should be brought into view itself, relative to this * node. If this node needs to scroll to bring [localRect] into view, the returned rectangle * should be the destination rectangle that [localRect] will eventually occupy, once the * scrolling animation is finished. */ @ExperimentalFoundationApi fun calculateRectForParent(localRect: Rect): Rect /** * Bring this specified rectangle into bounds by making this scrollable parent scroll * appropriately. * * This method should ensure that only one call is being handled at a time. If you use Compose's * `Animatable` you get this for free, since it will cancel the previous animation when a new * one is started while preserving velocity. * * @param localRect A function returning the rectangle that should be brought into view, * relative to this node. This is the same rectangle that will have been passed to * [calculateRectForParent]. The function may return a different value over time, if the bounds * of the request change while the request is being processed. If the rectangle cannot be * calculated, e.g. because the [LayoutCoordinates] are not attached, return null. */ @ExperimentalFoundationApi suspend fun bringChildIntoView(localRect: () -> Rect?) } /** * A parent that can respond to [BringIntoViewRequester] requests from its children, and scroll so * that the item is visible on screen. See [BringIntoViewResponder] for more details about how * this mechanism works. * * @sample androidx.compose.foundation.samples.BringIntoViewResponderSample * @sample androidx.compose.foundation.samples.BringIntoViewSample * * @see BringIntoViewRequester */ @ExperimentalFoundationApi fun Modifier.bringIntoViewResponder( responder: BringIntoViewResponder ): Modifier = composed(debugInspectorInfo { name = "bringIntoViewResponder" properties["responder"] = responder }) { val defaultParent = rememberDefaultBringIntoViewParent() val modifier = remember(defaultParent) { BringIntoViewResponderModifier(defaultParent) } modifier.responder = responder return@composed modifier } /** * A modifier that holds state and modifier implementations for [bringIntoViewResponder]. It has * access to the next [BringIntoViewParent] via [BringIntoViewChildModifier] and additionally * provides itself as the [BringIntoViewParent] for subsequent modifiers. This class is responsible * for recursively propagating requests up the responder chain. */ @OptIn(ExperimentalFoundationApi::class) private class BringIntoViewResponderModifier( defaultParent: BringIntoViewParent ) : BringIntoViewChildModifier(defaultParent), ModifierLocalProvider<BringIntoViewParent?>, BringIntoViewParent { lateinit var responder: BringIntoViewResponder override val key: ProvidableModifierLocal<BringIntoViewParent?> get() = ModifierLocalBringIntoViewParent override val value: BringIntoViewParent get() = this /** * Stores the rectangle and coroutine [Job] of the newest request to be handled by * [bringChildIntoView]. * * This property is not guarded by a lock since requests should only be made on the main thread. * * ## Request queuing * * When multiple requests are received concurrently, i.e. a new request comes in before the * previous one finished, they are put in a queue. The queue is implicit – this property only * stores a reference to the tail of the queue. The head of the queue is the oldest request that * hasn't finished executing yet. Each subsequent request in the queue waits for the previous * request to finish by [joining][Job.join] on its [Job]. When the oldest request finishes (or * is cancelled), it is "removed" from the queue by simply returning from [bringChildIntoView]. * This completes its job, which resumes the next request, and makes that the new "head". When * the last request finishes it "clears" the queue by setting this property to null. * * ## Interruption * * There is one case not covered above: If a request comes in for a rectangle that is * not [fully-overlapped][completelyOverlaps] by the previous request, the new request will * "interrupt" all previous requests and indirectly remove them from the queue. The reason only * overlapping requests are queued is because if rectangle A contains rectangle B, then when A * is fully on screen, then B is also fully on screen. By satisfying A first, both A and B can * be satisfied in a single call to the [BringIntoViewResponder]. If B were to interrupt A, A * might never be fully brought into view (see b/216790855). * * Interruption works by immediately dispatching the new request to the * [BringIntoViewResponder]. Note that this class does not actually cancel the previously- * running request's [Job] – the responder is responsible for cancelling any in-progress request * and immediately start handling the new one. In particular, if the responder is using * Compose's animation, the animation will handle cancellation itself and preserve velocity. * When the previously-running request is cancelled, its job will complete and the next request * in the queue will try to run. However, it will see that another request was already * dispatched, and return early, completing its job as well. Etc etc until all requests that * were received before the interrupting one have returned from their [bringChildIntoView] * calls. * * The way a request determines if it's been interrupted is by comparing the previous request * to the value of [newestDispatchedRequest]. [newestDispatchedRequest] is only set just before * the [BringIntoViewResponder] is called. */ private var newestReceivedRequest: Pair<Rect, Job>? = null /** * The last queued request to have been sent to the [BringIntoViewResponder], or null if no * requests are in progress. */ private var newestDispatchedRequest: Pair<Rect, Job>? = null /** * Responds to a child's request by first converting [boundsProvider] into this node's [LayoutCoordinates] * and then, concurrently, calling the [responder] and the [parent] to handle the request. */ override suspend fun bringChildIntoView( childCoordinates: LayoutCoordinates, boundsProvider: () -> Rect? ) { coroutineScope { val layoutCoordinates = layoutCoordinates ?: return@coroutineScope if (!childCoordinates.isAttached) return@coroutineScope // TODO(b/241591211) Read the request's bounds lazily in case they change. val localRect = layoutCoordinates.localRectOf( sourceCoordinates = childCoordinates, rect = boundsProvider() ?: return@coroutineScope ) // Immediately make this request the tail of the queue, before suspending, so that // any requests that come in while suspended will join on this one. // Note that this job is not the caller's job, since coroutineScope introduces a child // job. // For more information about how requests are queued, see the kdoc on newestRequest. val requestJob = coroutineContext.job val thisRequest = Pair(localRect, requestJob) val previousRequest = newestReceivedRequest newestReceivedRequest = thisRequest try { // In the simplest case there are no ongoing requests, so just dispatch. if (previousRequest == null || // If there's an ongoing request but it won't satisfy this request, then // interrupt it. !previousRequest.first.completelyOverlaps(localRect) ) { dispatchRequest(thisRequest, layoutCoordinates) return@coroutineScope } // The previous request completely overlaps this one, so wait for it to finish since // it will probably satisfy this request. // Note that even if the previous request fails or is cancelled, join will return // normally. It could be cancelled either because a newer job interrupted it, or // because the caller/sender of that request was cancelled. previousRequest.second.join() // If a newer request interrupted this one while we were waiting, then it will have // already dispatched so we should consider this request cancelled and not dispatch. if (newestDispatchedRequest === previousRequest) { // Any requests queued up previously to us have finished, and nothing new came // in while we were waiting. dispatchRequest(thisRequest, layoutCoordinates) } } finally { // Only the last job in the queue should clear the dispatched request, since if // there's another job waiting to start it needs to know what the last dispatched // request was. if (newestDispatchedRequest === newestReceivedRequest) { newestDispatchedRequest = null } // Only the last job in the queue should clear the queue. if (newestReceivedRequest === thisRequest) { newestReceivedRequest = null } } } } /** * Marks [request] as the [newestDispatchedRequest] and then dispatches it to both the * [responder] and the [parent]. */ private suspend fun dispatchRequest( request: Pair<Rect, Job>, layoutCoordinates: LayoutCoordinates ) { newestDispatchedRequest = request val localRect = request.first val parentRect = responder.calculateRectForParent(localRect) coroutineScope { // For the item to be visible, if needs to be in the viewport of all its // ancestors. // Note: For now we run both of these concurrently, but in the future we could // make this configurable. (The child relocation could be executed before the // parent, or parent before the child). launch { // Bring the requested Child into this parent's view. // TODO(b/241591211) Read the request's bounds lazily in case they change. responder.bringChildIntoView { localRect } } // TODO I think this needs to be in launch, since if the parent is cancelled (this // throws a CE) due to animation interruption, the child should continue animating. // TODO(b/241591211) Read the request's bounds lazily in case they change. parent.bringChildIntoView(layoutCoordinates) { parentRect } } // Don't try to null out newestDispatchedRequest here, bringChildIntoView will take care of // that. } } /** * Translates [rect], specified in [sourceCoordinates], into this [LayoutCoordinates]. */ private fun LayoutCoordinates.localRectOf( sourceCoordinates: LayoutCoordinates, rect: Rect ): Rect { // Translate the supplied layout coordinates into the coordinate system of this parent. val localRect = localBoundingBoxOf(sourceCoordinates, clipBounds = false) // Translate the rect to this parent's local coordinates. return rect.translate(localRect.topLeft) } /** * Returns true if [other] is fully contained inside this [Rect], using inclusive bound checks. */ private fun Rect.completelyOverlaps(other: Rect): Boolean { return left <= other.left && top <= other.top && right >= other.right && bottom >= other.bottom }
apache-2.0
abdd46c0b48f873fcd1ed3e52600e10b
47.277955
110
0.700397
4.907437
false
false
false
false
androidx/androidx
navigation/integration-tests/testapp/src/main/java/androidx/navigation/testapp/MainFragment.kt
3
2647
/* * 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.navigation.testapp import android.graphics.Color import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.core.view.ViewCompat import androidx.fragment.app.Fragment import androidx.navigation.fragment.FragmentNavigatorExtras import androidx.navigation.fragment.findNavController /** * Fragment used to show how to navigate to another destination */ class MainFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.main_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val tv = view.findViewById<TextView>(R.id.text) val myarg = arguments?.getString("myarg") tv.text = myarg view.setBackgroundColor( if (myarg == "one") { Color.GREEN } else if (myarg == "two") { Color.RED } else if (myarg == "three") { Color.YELLOW } else if (myarg == "four") { Color.GRAY } else if (myarg == "five") { Color.MAGENTA } else { Color.RED } ) val b = view.findViewById<Button>(R.id.next_button) ViewCompat.setTransitionName(b, "next") b.setOnClickListener { findNavController().navigate( R.id.next, null, null, FragmentNavigatorExtras(b to "next") ) } view.findViewById<Button>(R.id.learn_more).setOnClickListener { val args = Bundle().apply { putString("myarg", myarg) } findNavController().navigate(R.id.learn_more, args, null) } } }
apache-2.0
80cf976a72cba842a48e595343abe57f
31.679012
75
0.633925
4.517065
false
false
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/ide/toolwindow/ElmErrorTreeViewPanel.kt
1
1546
package org.elm.ide.toolwindow import com.intellij.ide.errorTreeView.NewErrorTreeViewPanel import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.ToolWindowManager import com.intellij.util.ui.tree.TreeUtil import kotlinx.coroutines.Runnable import javax.swing.event.TreeSelectionListener class ElmErrorTreeViewPanel(project: Project, helpId: String?, createExitAction: Boolean, createToolbar: Boolean) : NewErrorTreeViewPanel(project, helpId, createExitAction, createToolbar) { val messages = mutableListOf<String>() init { connectFriendlyMessages(project) } override fun expandAll() { TreeUtil.expandAll(myTree, Runnable { }) } fun addErrorMessage(type: Int, text: Array<out String>, file: VirtualFile?, line: Int, column: Int, html: String) { super.addMessage(type, text, file, line, column, null) messages.add(html) } private fun addSelectionListener(tsl: TreeSelectionListener) { myTree.addTreeSelectionListener(tsl) } private fun connectFriendlyMessages(project: Project) { ToolWindowManager.getInstance(project).getToolWindow("Friendly Messages")?.let { val reportUI = (it.contentManager.contents[0].component as ReportPanel).reportUI val selectionListener = ErrorTreeSelectionListener(messages, reportUI, it) addSelectionListener(selectionListener) reportUI.background = background reportUI.text = "" } } }
mit
81fa685148134741e72cbbce3f74f5da
36.707317
189
0.729625
4.60119
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/openal/ALBinding.kt
1
3278
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.openal import java.io.PrintWriter import org.lwjgl.generator.* import java.util.* private val CAPABILITIES_CLASS = "ALCapabilities" private val ALBinding = Generator.register(object : APIBinding(OPENAL_PACKAGE, CAPABILITIES_CLASS, callingConvention = CallingConvention.DEFAULT) { init { Generator.registerTLS( "org.lwjgl.openal.*", "public ALCapabilities capsAL;" ) } override val hasCapabilities: Boolean get() = true override fun shouldCheckFunctionAddress(function: NativeClassFunction): Boolean = function.nativeClass.templateName != "AL10" override fun generateFunctionAddress(writer: PrintWriter, function: NativeClassFunction) { writer.println("\t\tlong $FUNCTION_ADDRESS = AL.getCapabilities().${function.name};") } override fun PrintWriter.generateFunctionSetup(nativeClass: NativeClass) { println("\n\tstatic boolean isAvailable($CAPABILITIES_CLASS caps) {") print("\t\treturn checkFunctions(") nativeClass.printPointers(this, { "caps.${it.name}" }) println(");") println("\t}") } init { documentation = "Defines the capabilities of an OpenAL context." } override fun PrintWriter.generateJava() { generateJavaPreamble() println("public final class $CAPABILITIES_CLASS {\n") val classes = super.getClasses { o1, o2 -> val isAL1 = o1.templateName.startsWith("AL") val isAL2 = o2.templateName.startsWith("AL") if ( isAL1 xor isAL2 ) (if ( isAL1 ) -1 else 1) else o1.templateName.compareTo(o2.templateName, ignoreCase = true) } val classesWithFunctions = classes.filter { it.hasNativeFunctions } val addresses = classesWithFunctions .map { it.functions } .flatten() .toSortedSet(Comparator<NativeClassFunction> { o1, o2 -> o1.name.compareTo(o2.name) }) println("\tpublic final long") println(addresses.map { it.name }.joinToString(",\n\t\t", prefix = "\t\t", postfix = ";\n")) classes.forEach { println(it.getCapabilityJavadoc()) println("\tpublic final boolean ${it.capName("AL")};") } println("\n\t$CAPABILITIES_CLASS(FunctionProvider provider, Set<String> ext) {") println(addresses.map { "${it.name} = provider.getFunctionAddress(${it.functionAddress});" }.joinToString("\n\t\t", prefix = "\t\t", postfix = "\n")) for (extension in classes) { val capName = extension.capName("AL") print("\t\t$capName = ext.contains(\"$capName\")") if ( extension.hasNativeFunctions ) print(" && AL.checkExtension(\"$capName\", ${if ( capName == extension.className ) "$OPENAL_PACKAGE.${extension.className}" else extension.className}.isAvailable(this))") println(";") } println("\t}") print("}") } }) // DSL Extensions fun String.nativeClassAL(templateName: String, prefixTemplate: String = "AL", postfix: String = "", init: (NativeClass.() -> Unit)? = null) = nativeClass(OPENAL_PACKAGE, templateName, prefix = "AL", prefixTemplate = prefixTemplate, postfix = postfix, binding = ALBinding, init = init) val NativeClass.specLinkOpenALSoft: String get() = url("http://kcat.strangesoft.net/openal-extensions/$templateName.txt", templateName) val NativeClass.extensionName: String get() = "{@code ${prefixTemplate}_$templateName}"
bsd-3-clause
35700340c04b39ea2f36b98dbcf71543
33.882979
174
0.712325
3.750572
false
false
false
false
wealthfront/magellan
magellan-sample-advanced/src/main/java/com/wealthfront/magellan/sample/advanced/views/LoadingLayout.kt
1
1099
package com.wealthfront.magellan.sample.advanced.views import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.annotation.AttrRes import androidx.annotation.StyleRes import com.wealthfront.magellan.sample.advanced.databinding.LoadingLayoutBinding class LoadingLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr: Int = 0, @StyleRes defStyleRes: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr, defStyleRes) { private val binding = LoadingLayoutBinding.inflate(LayoutInflater.from(context), this, true) override fun addView(child: View, index: Int, params: ViewGroup.LayoutParams) { if (childCount == 0) { super.addView(child, index, params) } else { binding.content.addView(child, index, params) } } fun showLoading() { binding.progressBar.visibility = View.VISIBLE } fun hideLoading() { binding.progressBar.visibility = View.GONE } }
apache-2.0
553d5fc194f1a50312fc7ed6e1f7c1f2
28.702703
94
0.764331
4.309804
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/chat/prv/Participant.kt
2
870
package me.proxer.app.chat.prv import android.os.Parcel import android.os.Parcelable import me.proxer.app.util.extension.readStringSafely /** * @author Ruben Gees */ data class Participant(val username: String, val image: String = "") : Parcelable { companion object { @Suppress("unused") @JvmField val CREATOR = object : Parcelable.Creator<Participant> { override fun createFromParcel(parcel: Parcel) = Participant(parcel) override fun newArray(size: Int): Array<Participant?> = arrayOfNulls(size) } } constructor(parcel: Parcel) : this( parcel.readStringSafely(), parcel.readStringSafely() ) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(username) parcel.writeString(image) } override fun describeContents() = 0 }
gpl-3.0
4f26a5c4c91a418257d52bafc87d1c11
26.1875
86
0.664368
4.53125
false
true
false
false
esofthead/mycollab
mycollab-services-community/src/test/java/com/mycollab/module/ecm/dao/ContentJcrDaoTest.kt
3
7442
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * mycollab-services-community - Parent pom providing dependency and plugin management for applications built with Maven * Copyright © 2017 MyCollab ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.ecm.dao import com.mycollab.core.UserInvalidInputException import com.mycollab.module.ecm.domain.Content import com.mycollab.module.ecm.domain.Folder import com.mycollab.module.ecm.service.ContentJcrDao import com.mycollab.test.spring.IntegrationServiceTest import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.tuple import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.junit.jupiter.SpringExtension @ExtendWith(SpringExtension::class) class ContentJcrDaoTest : IntegrationServiceTest() { @Autowired private lateinit var contentJcrDao: ContentJcrDao @BeforeEach fun setup() { val pageContent = Content("example/a") pageContent.createdBy = "hainguyen" pageContent.title = "page example" pageContent.description = "aaa" contentJcrDao.saveContent(pageContent, "hainguyen") } @AfterEach fun tearDown() { contentJcrDao.removeResource("") } @Test fun testGetContent() { val content = contentJcrDao.getResource("example/a") as Content assertThat(content.path).isEqualTo("example/a") assertThat(content.title).isEqualTo("page example") assertThat(content.description).isEqualTo("aaa") } @Test fun testRemoveContent() { contentJcrDao.removeResource("example/a/b") val content = contentJcrDao.getResource("example/a/b") assertThat(content).isNull() } @Test fun testSaveOverride() { val pageContent = Content("a/b/xyz.mycollabtext") pageContent.createdBy = "hainguyen" pageContent.title = "page example" pageContent.description = "aaa" contentJcrDao.saveContent(pageContent, "abc") val resource = contentJcrDao.getResource("a/b/xyz.mycollabtext") as Content assertThat(resource.path).isEqualTo("a/b/xyz.mycollabtext") } @Test fun testSaveInvalidContentName() { val pageContent = Content("a/b/http-//anchoragesnowmobileclub.com/trail_report/weather-for-turnagain/") pageContent.createdBy = "hainguyen" pageContent.title = "page example" pageContent.description = "aaa" Assertions.assertThrows(UserInvalidInputException::class.java) { contentJcrDao.saveContent(pageContent, "abc") } } @Test fun testCreateFolder() { val folder = Folder("a/b/c") contentJcrDao.createFolder(folder, "abc") val resource = contentJcrDao.getResource("a/b/c") assertThat(resource).isExactlyInstanceOf(Folder::class.java) assertThat(resource!!.path).isEqualTo("a/b/c") } @Test fun testGetResources() { val pageContent = Content("example/b") pageContent.createdBy = "hainguyen" pageContent.title = "page example2" pageContent.description = "aaa2" contentJcrDao.saveContent(pageContent, "hainguyen") val resources = contentJcrDao.getResources("example") assertThat(resources?.size).isEqualTo(2) assertThat(resources).extracting("path", "title").contains( tuple("example/a", "page example"), tuple("example/b", "page example2")) } @Test fun testGetSubFolders() { val folder = Folder("a/b/c") contentJcrDao.createFolder(folder, "abc") val folder2 = Folder("a/b/c2") contentJcrDao.createFolder(folder2, "abc") val folder3 = Folder("a/b/c3") contentJcrDao.createFolder(folder3, "abc") val subFolders = contentJcrDao.getSubFolders("a/b") assertThat(subFolders?.size).isEqualTo(3) assertThat(subFolders).extracting("path").contains("a/b/c", "a/b/c2", "a/b/c3") } @Test fun testRenameContent() { contentJcrDao.rename("example/a", "example/x") val content = contentJcrDao.getResource("example/x") as Content assertThat(content.path).isEqualTo("example/x") assertThat(content.title).isEqualTo("page example") assertThat(content.description).isEqualTo("aaa") } @Test fun testRenameFolder() { val folder = Folder("a/b/c") contentJcrDao.createFolder(folder, "abc") contentJcrDao.rename("a/b/c", "a/b/d") val resource = contentJcrDao.getResource("a/b/d") assertThat(resource).isExactlyInstanceOf(Folder::class.java) assertThat(resource!!.path).isEqualTo("a/b/d") } @Test fun testMoveResource() { val folder = Folder("xy/yz/zx") contentJcrDao.createFolder(folder, "abc") contentJcrDao.moveResource("xy/yz/zx", "ab/bc/ca") val resource = contentJcrDao.getResource("ab/bc/ca") assertThat(resource).isExactlyInstanceOf(Folder::class.java) assertThat(resource!!.path).isEqualTo("ab/bc/ca") } @Test fun testGetContents() { val pageContent = Content("example/e/a") pageContent.createdBy = "hainguyen" pageContent.title = "page example2" pageContent.description = "aaa2" contentJcrDao.saveContent(pageContent, "hainguyen") val pageContent2 = Content("example/e/b") pageContent2.createdBy = "hainguyen" pageContent2.title = "page example3" pageContent2.description = "aaa2" contentJcrDao.saveContent(pageContent2, "hainguyen") val contents = contentJcrDao.getContents("example/e") assertThat(contents?.size).isEqualTo(2) assertThat(contents).extracting("path", "title").contains( tuple("example/e/a", "page example2"), tuple("example/e/b", "page example3")) } }
agpl-3.0
55bdc51a9130feb3f55001e49540966a
35.470588
111
0.683468
4.07225
false
true
false
false
tasomaniac/OpenLinkWith
app/src/main/java/com/tasomaniac/openwith/util/CallerPackageExtractor.kt
1
2266
package com.tasomaniac.openwith.util import android.app.usage.UsageStats import android.app.usage.UsageStatsManager import android.content.Context import android.text.format.DateUtils import androidx.core.app.ShareCompat import androidx.core.content.getSystemService import com.tasomaniac.openwith.BuildConfig import com.tasomaniac.openwith.ShareToOpenWith import dagger.Provides sealed class CallerPackageExtractor { abstract fun extract(): String? @dagger.Module class Module { @Provides fun callerPackageExtractor( shareToOpenWith: ShareToOpenWith, callerPackagePreferences: CallerPackagePreferences ): CallerPackageExtractor { val callerPackage = ShareCompat.getCallingPackage(shareToOpenWith) return when { callerPackagePreferences.isEnabled.not() -> EmptyExtractor callerPackage != null -> SimpleExtractor(callerPackage) else -> LollipopExtractor(shareToOpenWith) } } } } private object EmptyExtractor : CallerPackageExtractor() { override fun extract(): String? = null } private class SimpleExtractor(private val callerPackage: String?) : CallerPackageExtractor() { override fun extract(): String? { return callerPackage } } private class LollipopExtractor(context: Context) : CallerPackageExtractor() { private val usageStatsManager = context.getSystemService<UsageStatsManager>() override fun extract() = usageStatsManager?.recentUsageStats()?.mostRecentPackage() private fun UsageStatsManager.recentUsageStats(): List<UsageStats>? { return try { val time = System.currentTimeMillis() queryUsageStats( UsageStatsManager.INTERVAL_DAILY, time - TEN_SECONDS, time ) } catch (ignored: Exception) { null } } private fun List<UsageStats>.mostRecentPackage() = filter { it.packageName !in listOf(BuildConfig.APPLICATION_ID, "android") }.maxByOrNull { it.lastTimeUsed }?.packageName companion object { private const val TEN_SECONDS = 10 * DateUtils.SECOND_IN_MILLIS } }
apache-2.0
7ac260156e0334ec0665025bd9add14f
28.815789
94
0.674316
5.197248
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xpath/test/uk/co/reecedunn/intellij/plugin/xpath/tests/lang/editor/parameters/XPathParameterInfoHandlerTest.kt
1
45575
/* * Copyright (C) 2019 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xpath.tests.lang.editor.parameters import com.intellij.openapi.extensions.PluginId import com.intellij.testFramework.utils.parameterInfo.MockUpdateParameterInfoContext import org.hamcrest.CoreMatchers.* import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import uk.co.reecedunn.intellij.plugin.core.sequences.walkTree import uk.co.reecedunn.intellij.plugin.core.tests.assertion.assertThat import uk.co.reecedunn.intellij.plugin.core.tests.lang.parameterInfo.MockCreateParameterInfoContext import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathArgumentList import uk.co.reecedunn.intellij.plugin.xpath.lang.editor.parameters.XPathParameterInfoHandler import uk.co.reecedunn.intellij.plugin.xpath.tests.parser.ParserTestCase import uk.co.reecedunn.intellij.plugin.xpm.optree.function.XpmFunctionDeclaration @Suppress("RedundantVisibilityModifier") @DisplayName("IntelliJ - Custom Language Support - Parameter Info - XPath ParameterInfoHandler") class XPathParameterInfoHandlerTest : ParserTestCase() { override val pluginId: PluginId = PluginId.getId("XPathParameterInfoHandlerTest") private val parameterInfoHandler = XPathParameterInfoHandler() @Nested @DisplayName("find element for parameter info") internal inner class FindElementForParameterInfo { @Nested @DisplayName("XPath 3.1 EBNF (63) FunctionCall") internal inner class FunctionCall { @Test @DisplayName("XPath 3.1 EBNF (112) EQName ; XPath 3.1 EBNF (123) NCName") fun ncname() { val context = createParameterInfoContext("abs(2)", 4) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.highlightedElement, `is`(nullValue())) assertThat(context.parameterListStart, `is`(4)) val items = context.itemsToShow!!.map { it as XpmFunctionDeclaration } assertThat(items.size, `is`(0)) val hint = context as MockCreateParameterInfoContext assertThat(hint.showHintElement, `is`(nullValue())) assertThat(hint.showHintOffset, `is`(0)) assertThat(hint.showHintHandler, `is`(nullValue())) } @Test @DisplayName("XPath 3.1 EBNF (112) EQName ; XPath 3.1 EBNF (122) QName") fun qname() { val context = createParameterInfoContext("fn:abs(2)", 7) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.highlightedElement, `is`(nullValue())) assertThat(context.parameterListStart, `is`(7)) val items = context.itemsToShow!!.map { it as XpmFunctionDeclaration } assertThat(items.size, `is`(0)) val hint = context as MockCreateParameterInfoContext assertThat(hint.showHintElement, `is`(nullValue())) assertThat(hint.showHintOffset, `is`(0)) assertThat(hint.showHintHandler, `is`(nullValue())) } @Test @DisplayName("XPath 3.1 EBNF (112) EQName ; XPath 3.1 EBNF (117) URIQualifiedName") fun uriQualifiedName() { val context = createParameterInfoContext("Q{http://www.w3.org/2005/xpath-functions}abs(2)", 45) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.highlightedElement, `is`(nullValue())) assertThat(context.parameterListStart, `is`(45)) val items = context.itemsToShow!!.map { it as XpmFunctionDeclaration } assertThat(items.size, `is`(0)) val hint = context as MockCreateParameterInfoContext assertThat(hint.showHintElement, `is`(nullValue())) assertThat(hint.showHintOffset, `is`(0)) assertThat(hint.showHintHandler, `is`(nullValue())) } } @Nested @DisplayName("XPath 3.1 EBNF (49) PostfixExpr") internal inner class PostfixExpr { @Test @DisplayName("XPath 3.1 EBNF (59) VarRef") fun varRef() { val context = createParameterInfoContext("let \$a := abs#1 return \$a(2)", 26) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.highlightedElement, `is`(nullValue())) assertThat(context.parameterListStart, `is`(26)) val items = context.itemsToShow!!.map { it as XpmFunctionDeclaration } assertThat(items.size, `is`(0)) val hint = context as MockCreateParameterInfoContext assertThat(hint.showHintElement, `is`(nullValue())) assertThat(hint.showHintOffset, `is`(0)) assertThat(hint.showHintHandler, `is`(nullValue())) } @Test @DisplayName("XPath 3.1 EBNF (67) NamedFunctionRef") fun namedFunctionRef() { val context = createParameterInfoContext("abs#1(2)", 6) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.highlightedElement, `is`(nullValue())) assertThat(context.parameterListStart, `is`(6)) val items = context.itemsToShow!!.map { it as XpmFunctionDeclaration } assertThat(items.size, `is`(0)) val hint = context as MockCreateParameterInfoContext assertThat(hint.showHintElement, `is`(nullValue())) assertThat(hint.showHintOffset, `is`(0)) assertThat(hint.showHintHandler, `is`(nullValue())) } } @Nested @DisplayName("XPath 3.1 EBNF (29) ArrowExpr ; XPath 3.1 EBNF (55) ArrowFunctionSpecifier") internal inner class ArrowExpr { @Test @DisplayName("XPath 3.1 EBNF (59) VarRef") fun varRef() { val context = createParameterInfoContext("let \$a := abs#1 return 2 => \$a()", 31) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.highlightedElement, `is`(nullValue())) assertThat(context.parameterListStart, `is`(31)) val items = context.itemsToShow!!.map { it as XpmFunctionDeclaration } assertThat(items.size, `is`(0)) val hint = context as MockCreateParameterInfoContext assertThat(hint.showHintElement, `is`(nullValue())) assertThat(hint.showHintOffset, `is`(0)) assertThat(hint.showHintHandler, `is`(nullValue())) } @Test @DisplayName("XPath 3.1 EBNF (112) EQName ; XPath 3.1 EBNF (123) NCName") fun ncname() { val context = createParameterInfoContext("2 => abs()", 9) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.highlightedElement, `is`(nullValue())) assertThat(context.parameterListStart, `is`(9)) val items = context.itemsToShow!!.map { it as XpmFunctionDeclaration } assertThat(items.size, `is`(0)) val hint = context as MockCreateParameterInfoContext assertThat(hint.showHintElement, `is`(nullValue())) assertThat(hint.showHintOffset, `is`(0)) assertThat(hint.showHintHandler, `is`(nullValue())) } @Test @DisplayName("XPath 3.1 EBNF (112) EQName ; XPath 3.1 EBNF (122) QName") fun qname() { val context = createParameterInfoContext("2 => fn:abs()", 12) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.highlightedElement, `is`(nullValue())) assertThat(context.parameterListStart, `is`(12)) val items = context.itemsToShow!!.map { it as XpmFunctionDeclaration } assertThat(items.size, `is`(0)) val hint = context as MockCreateParameterInfoContext assertThat(hint.showHintElement, `is`(nullValue())) assertThat(hint.showHintOffset, `is`(0)) assertThat(hint.showHintHandler, `is`(nullValue())) } @Test @DisplayName("XPath 3.1 EBNF (112) EQName ; XPath 3.1 EBNF (117) URIQualifiedName") fun uriQualifiedName() { val context = createParameterInfoContext("2 => Q{http://www.w3.org/2005/xpath-functions}abs()", 50) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.highlightedElement, `is`(nullValue())) assertThat(context.parameterListStart, `is`(50)) val items = context.itemsToShow!!.map { it as XpmFunctionDeclaration } assertThat(items.size, `is`(0)) val hint = context as MockCreateParameterInfoContext assertThat(hint.showHintElement, `is`(nullValue())) assertThat(hint.showHintOffset, `is`(0)) assertThat(hint.showHintHandler, `is`(nullValue())) } @Test @DisplayName("XPath 3.1 EBNF (61) ParenthesizedExpr") fun parenthesizedExpr() { val context = createParameterInfoContext("2 => (fn:abs#1)()", 16) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.highlightedElement, `is`(nullValue())) assertThat(context.parameterListStart, `is`(16)) val items = context.itemsToShow!!.map { it as XpmFunctionDeclaration } assertThat(items.size, `is`(0)) val hint = context as MockCreateParameterInfoContext assertThat(hint.showHintElement, `is`(nullValue())) assertThat(hint.showHintOffset, `is`(0)) assertThat(hint.showHintHandler, `is`(nullValue())) } } } @Nested @DisplayName("find element for updating parameter info") internal inner class FindElementForUpdatingParameterInfo { @Nested @DisplayName("XPath 3.1 EBNF (63) FunctionCall") internal inner class FunctionCall { @Test @DisplayName("XPath 3.1 EBNF (112) EQName ; XPath 3.1 EBNF (123) NCName") fun ncname() { val context = updateParameterInfoContext("abs(2)", 4) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForUpdatingParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(4)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(0)) } @Test @DisplayName("XPath 3.1 EBNF (112) EQName ; XPath 3.1 EBNF (122) QName") fun qname() { val context = updateParameterInfoContext("fn:abs(2)", 7) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForUpdatingParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(7)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(0)) } @Test @DisplayName("XPath 3.1 EBNF (112) EQName ; XPath 3.1 EBNF (117) URIQualifiedName") fun uriQualifiedName() { val context = updateParameterInfoContext("Q{http://www.w3.org/2005/xpath-functions}abs(2)", 45) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForUpdatingParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(45)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(0)) } } @Nested @DisplayName("XPath 3.1 EBNF (49) PostfixExpr") internal inner class PostfixExpr { @Test @DisplayName("XPath 3.1 EBNF (59) VarRef") fun varRef() { val context = updateParameterInfoContext("let \$a := abs#1 return \$a(2)", 26) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForUpdatingParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(26)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(0)) } @Test @DisplayName("XPath 3.1 EBNF (67) NamedFunctionRef") fun namedFunctionRef() { val context = updateParameterInfoContext("abs#1(2)", 6) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForUpdatingParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(6)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(0)) } } @Nested @DisplayName("XPath 3.1 EBNF (29) ArrowExpr ; XPath 3.1 EBNF (55) ArrowFunctionSpecifier") internal inner class ArrowExpr { @Test @DisplayName("XPath 3.1 EBNF (59) VarRef") fun varRef() { val context = updateParameterInfoContext("let \$a := abs#1 return 2 => \$a()", 31) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForUpdatingParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(31)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(0)) } @Test @DisplayName("XPath 3.1 EBNF (112) EQName ; XPath 3.1 EBNF (123) NCName") fun ncname() { val context = updateParameterInfoContext("2 => abs()", 9) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForUpdatingParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(9)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(0)) } @Test @DisplayName("XPath 3.1 EBNF (112) EQName ; XPath 3.1 EBNF (122) QName") fun qname() { val context = updateParameterInfoContext("2 => fn:abs()", 12) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForUpdatingParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(12)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(0)) } @Test @DisplayName("XPath 3.1 EBNF (112) EQName ; XPath 3.1 EBNF (117) URIQualifiedName") fun uriQualifiedName() { val context = updateParameterInfoContext("2 => Q{http://www.w3.org/2005/xpath-functions}abs()", 50) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForUpdatingParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(50)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(0)) } @Test @DisplayName("XPath 3.1 EBNF (61) ParenthesizedExpr") fun parenthesizedExpr() { val context = updateParameterInfoContext("2 => (fn:abs#1)()", 16) val args = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() val item = parameterInfoHandler.findElementForUpdatingParameterInfo(context) assertThat(item, `is`(sameInstance(args))) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(16)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(0)) } } } @Nested @DisplayName("show parameter info") internal inner class ShowParameterInfo { @Test @DisplayName("XPath 3.1 EBNF (63) FunctionCall") fun functionCall() { val context = createParameterInfoContext("abs(2)", 4) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.showParameterInfo(function, context) assertThat(context.highlightedElement, `is`(nullValue())) assertThat(context.parameterListStart, `is`(4)) assertThat(context.itemsToShow, `is`(nullValue())) val hint = context as MockCreateParameterInfoContext assertThat(hint.showHintElement, `is`(sameInstance(function))) assertThat(hint.showHintOffset, `is`(3)) assertThat(hint.showHintHandler, `is`(sameInstance(parameterInfoHandler))) } @Test @DisplayName("XPath 3.1 EBNF (49) PostfixExpr") fun postfixExpr() { val context = createParameterInfoContext("abs#1(2)", 6) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.showParameterInfo(function, context) assertThat(context.highlightedElement, `is`(nullValue())) assertThat(context.parameterListStart, `is`(6)) assertThat(context.itemsToShow, `is`(nullValue())) val hint = context as MockCreateParameterInfoContext assertThat(hint.showHintElement, `is`(sameInstance(function))) assertThat(hint.showHintOffset, `is`(5)) assertThat(hint.showHintHandler, `is`(sameInstance(parameterInfoHandler))) } @Test @DisplayName("XPath 3.1 EBNF (29) ArrowExpr ; XPath 3.1 EBNF (55) ArrowFunctionSpecifier") fun arrowExpr() { val context = createParameterInfoContext("2 => abs()", 9) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.showParameterInfo(function, context) assertThat(context.highlightedElement, `is`(nullValue())) assertThat(context.parameterListStart, `is`(9)) assertThat(context.itemsToShow, `is`(nullValue())) val hint = context as MockCreateParameterInfoContext assertThat(hint.showHintElement, `is`(sameInstance(function))) assertThat(hint.showHintOffset, `is`(8)) assertThat(hint.showHintHandler, `is`(sameInstance(parameterInfoHandler))) } } @Nested @DisplayName("update parameter info") internal inner class UpdateParameterInfo { @Nested @DisplayName("XPath 3.1 EBNF (63) FunctionCall") internal inner class FunctionCall { @Test @DisplayName("empty arguments") fun empty() { val context = updateParameterInfoContext("concat()", 7) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.updateParameterInfo(function, context) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(7)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(0)) } @Test @DisplayName("single argument") fun single() { val context = updateParameterInfoContext("concat(1)", 7) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.updateParameterInfo(function, context) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(7)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(0)) } @Test @DisplayName("first argument") fun first() { val context = updateParameterInfoContext("concat(1, 2, 3, 4, 5)", 7) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.updateParameterInfo(function, context) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(7)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(0)) } @Test @DisplayName("second argument") fun second() { val context = updateParameterInfoContext("concat(1, 2, 3, 4, 5)", 10) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.updateParameterInfo(function, context) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(10)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(1)) } @Test @DisplayName("last argument") fun last() { val context = updateParameterInfoContext("concat(1, 2, 3, 4, 5)", 19) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.updateParameterInfo(function, context) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(19)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(4)) } } @Nested @DisplayName("XPath 3.1 EBNF (49) PostfixExpr") internal inner class PostfixExpr { @Test @DisplayName("empty arguments") fun empty() { val context = updateParameterInfoContext("concat#1()", 9) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.updateParameterInfo(function, context) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(9)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(0)) } @Test @DisplayName("single argument") fun single() { val context = updateParameterInfoContext("concat#1(1)", 9) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.updateParameterInfo(function, context) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(9)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(0)) } @Test @DisplayName("first argument") fun first() { val context = updateParameterInfoContext("concat#1(1, 2, 3, 4, 5)", 9) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.updateParameterInfo(function, context) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(9)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(0)) } @Test @DisplayName("second argument") fun second() { val context = updateParameterInfoContext("concat#1(1, 2, 3, 4, 5)", 12) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.updateParameterInfo(function, context) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(12)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(1)) } @Test @DisplayName("last argument") fun last() { val context = updateParameterInfoContext("concat#2(1, 2, 3, 4, 5)", 21) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.updateParameterInfo(function, context) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(21)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(4)) } } @Nested @DisplayName("XPath 3.1 EBNF (29) ArrowExpr ; XPath 3.1 EBNF (55) ArrowFunctionSpecifier") internal inner class ArrowExpr { @Test @DisplayName("empty arguments") fun empty() { val context = updateParameterInfoContext("1 => concat()", 12) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.updateParameterInfo(function, context) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(12)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(1)) } @Test @DisplayName("single argument") fun single() { val context = updateParameterInfoContext("1 => concat(1)", 12) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.updateParameterInfo(function, context) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(12)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(1)) } @Test @DisplayName("first argument") fun first() { val context = updateParameterInfoContext("2 => concat(1, 2, 3, 4, 5)", 12) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.updateParameterInfo(function, context) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(12)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(1)) } @Test @DisplayName("second argument") fun second() { val context = updateParameterInfoContext("2 => concat(1, 2, 3, 4, 5)", 15) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.updateParameterInfo(function, context) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(15)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(2)) } @Test @DisplayName("last argument") fun last() { val context = updateParameterInfoContext("2 => concat(1, 2, 3, 4, 5)", 24) val function = context.file.walkTree().filterIsInstance<XPathArgumentList>().first() parameterInfoHandler.updateParameterInfo(function, context) assertThat(context.parameterOwner, `is`(nullValue())) assertThat(context.highlightedParameter, `is`(nullValue())) assertThat(context.objectsToView.size, `is`(0)) assertThat(context.parameterListStart, `is`(24)) assertThat(context.isPreservedOnHintHidden, `is`(false)) assertThat(context.isInnermostContext, `is`(false)) assertThat(context.isUIComponentEnabled(0), `is`(false)) assertThat(context.isUIComponentEnabled(1), `is`(false)) val update = context as MockUpdateParameterInfoContext assertThat(update.isSingleParameterInfo, `is`(false)) assertThat(update.currentParameter, `is`(5)) } } } }
apache-2.0
dc7eb24928b8aa2d7a64e68bf89acf0c
48.217063
115
0.609413
5.111024
false
true
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/map/QuestsMapFragment.kt
1
12185
package de.westnordost.streetcomplete.map import android.graphics.PointF import android.graphics.RectF import android.os.Bundle import android.view.animation.AccelerateDecelerateInterpolator import android.view.animation.DecelerateInterpolator import com.mapzen.tangram.MapData import com.mapzen.tangram.SceneUpdate import com.mapzen.tangram.geometry.Point import de.westnordost.osmapi.map.data.LatLon import de.westnordost.streetcomplete.Injector import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.quest.QuestGroup import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementGeometry import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementPolygonsGeometry import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementPolylinesGeometry import de.westnordost.streetcomplete.data.quest.Quest import de.westnordost.streetcomplete.ktx.getBitmapDrawable import de.westnordost.streetcomplete.ktx.toDp import de.westnordost.streetcomplete.ktx.toPx import de.westnordost.streetcomplete.map.QuestPinLayerManager.Companion.MARKER_QUEST_GROUP import de.westnordost.streetcomplete.map.QuestPinLayerManager.Companion.MARKER_QUEST_ID import de.westnordost.streetcomplete.map.tangram.CameraPosition import de.westnordost.streetcomplete.map.tangram.Marker import de.westnordost.streetcomplete.map.tangram.toLngLat import de.westnordost.streetcomplete.map.tangram.toTangramGeometry import de.westnordost.streetcomplete.util.distanceTo import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.* import javax.inject.Inject import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.roundToLong /** Manages a map that shows the quest pins, quest geometry */ class QuestsMapFragment : LocationAwareMapFragment() { @Inject internal lateinit var spriteSheet: TangramQuestSpriteSheet @Inject internal lateinit var questPinLayerManager: QuestPinLayerManager // layers private var questsLayer: MapData? = null private var geometryLayer: MapData? = null private var selectedQuestPinsLayer: MapData? = null private val questSelectionMarkers: MutableList<Marker> = mutableListOf() // markers: LatLon -> Marker Id private val markerIds: MutableMap<LatLon, Long> = HashMap() // for restoring position private var cameraPositionBeforeShowingQuest: CameraPosition? = null interface Listener { fun onClickedQuest(questGroup: QuestGroup, questId: Long) fun onClickedMapAt(position: LatLon, clickAreaSizeInMeters: Double) } private val listener: Listener? get() = parentFragment as? Listener ?: activity as? Listener /* ------------------------------------ Lifecycle ------------------------------------------- */ init { Injector.applicationComponent.inject(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) lifecycle.addObserver(questPinLayerManager) questPinLayerManager.mapFragment = this } override fun onMapReady() { controller?.setPickRadius(1f) geometryLayer = controller?.addDataLayer(GEOMETRY_LAYER) questsLayer = controller?.addDataLayer(QUESTS_LAYER) selectedQuestPinsLayer = controller?.addDataLayer(SELECTED_QUESTS_LAYER) questPinLayerManager.questsLayer = questsLayer super.onMapReady() } override fun onMapIsChanging(position: LatLon, rotation: Float, tilt: Float, zoom: Float) { super.onMapIsChanging(position, rotation, tilt, zoom) questPinLayerManager.onNewScreenPosition() } override fun onDestroy() { super.onDestroy() geometryLayer = null questsLayer = null selectedQuestPinsLayer = null questSelectionMarkers.clear() } /* ------------------------------------- Map setup ------------------------------------------ */ override suspend fun getSceneUpdates(): List<SceneUpdate> { return super.getSceneUpdates() + withContext(Dispatchers.IO) { spriteSheet.sceneUpdates } } /* -------------------------------- Picking quest pins -------------------------------------- */ override fun onSingleTapConfirmed(x: Float, y: Float): Boolean { launch { val pickResult = controller?.pickLabel(x, y) val pickedQuestId = pickResult?.properties?.get(MARKER_QUEST_ID)?.toLong() val pickedQuestGroup = pickResult?.properties?.get(MARKER_QUEST_GROUP)?.let { QuestGroup.valueOf(it) } if (pickedQuestId != null && pickedQuestGroup != null) { listener?.onClickedQuest(pickedQuestGroup, pickedQuestId) } else { val pickMarkerResult = controller?.pickMarker(x,y) if (pickMarkerResult == null) { onClickedMap(x, y) } } } return true } private fun onClickedMap(x: Float, y: Float) { val context = context ?: return val clickPos = controller?.screenPositionToLatLon(PointF(x, y)) ?: return val fingerRadius = CLICK_AREA_SIZE_IN_DP.toFloat().toPx(context) / 2 val fingerEdgeClickPos = controller?.screenPositionToLatLon(PointF(x + fingerRadius, y)) ?: return val fingerRadiusInMeters = clickPos.distanceTo(fingerEdgeClickPos) listener?.onClickedMapAt(clickPos, fingerRadiusInMeters) } /* --------------------------------- Focusing on quest -------------------------------------- */ fun startFocusQuest(quest: Quest, offset: RectF) { zoomAndMoveToContain(quest.geometry, offset) showQuestSelectionMarkers(quest.markerLocations) putSelectedQuestPins(quest) putQuestGeometry(quest.geometry) } /** Clear focus on current quest but do not return to normal view yet */ fun clearFocusQuest() { removeQuestGeometry() clearMarkersForCurrentQuest() hideQuestSelectionMarkers() removeSelectedQuestPins() } fun endFocusQuest() { clearFocusQuest() restoreCameraPosition() centerCurrentPositionIfFollowing() } private fun zoomAndMoveToContain(g: ElementGeometry, offset: RectF) { val controller = controller ?: return val pos = controller.getEnclosingCameraPosition(g.getBounds(), offset) ?: return val currentPos = controller.cameraPosition val targetZoom = min(pos.zoom, 20f) // do not zoom in if the element is already nicely in the view if (screenAreaContains(g, RectF()) && targetZoom - currentPos.zoom < 2) return cameraPositionBeforeShowingQuest = currentPos val zoomTime = max(450L, (abs(currentPos.zoom - targetZoom) * 300).roundToLong()) controller.updateCameraPosition(zoomTime, DecelerateInterpolator()) { position = pos.position zoom = targetZoom } } private fun screenAreaContains(g: ElementGeometry, offset: RectF): Boolean { val controller = controller ?: return false val p = PointF() return when (g) { is ElementPolylinesGeometry -> g.polylines is ElementPolygonsGeometry -> g.polygons else -> listOf(listOf(g.center)) }.flatten().all { val isContained = controller.latLonToScreenPosition(it, p, false) isContained && p.x >= offset.left && p.x <= mapView.width - offset.right && p.y >= offset.top && p.y <= mapView.height - offset.bottom } } private fun restoreCameraPosition() { val controller = controller ?: return val pos = cameraPositionBeforeShowingQuest if (pos != null) { val currentPos = controller.cameraPosition val zoomTime = max(300L, (abs(currentPos.zoom - pos.zoom) * 300).roundToLong()) controller.updateCameraPosition(zoomTime, AccelerateDecelerateInterpolator()) { position = pos.position zoom = pos.zoom tilt = pos.tilt rotation = pos.rotation } } cameraPositionBeforeShowingQuest = null } /* -------------------------------------- Quest Pins --------------------------------------- */ var isShowingQuestPins: Boolean get() = questPinLayerManager.isVisible set(value) { questPinLayerManager.isVisible = value } /* --------------------------------- Selected quest pins ----------------------------------- */ private fun createQuestSelectionMarker(): Marker? { val ctx = context ?: return null val frame = ctx.resources.getBitmapDrawable(R.drawable.quest_selection_ring) val w = frame.intrinsicWidth.toFloat().toDp(ctx) val h = frame.intrinsicHeight.toFloat().toDp(ctx) val marker = controller?.addMarker() ?: return null marker.setStylingFromString( "{ style: 'quest-selection', color: 'white', size: [${w}px, ${h}px], flat: false, collide: false, offset: ['0px', '-38px'] }" ) marker.setDrawable(frame) return marker } private fun showQuestSelectionMarkers(positions: Collection<LatLon>) { while (positions.size > questSelectionMarkers.size) { val marker = createQuestSelectionMarker() ?: return questSelectionMarkers.add(marker) } positions.forEachIndexed { index, pos -> val marker = questSelectionMarkers[index] marker.setPoint(pos) marker.isVisible = true } } private fun hideQuestSelectionMarkers() { questSelectionMarkers.forEach { it.isVisible = false } } private fun putSelectedQuestPins(quest: Quest) { val questIconName = resources.getResourceEntryName(quest.type.icon) val positions = quest.markerLocations val points = positions.map { position -> val properties = mapOf( "type" to "point", "kind" to questIconName ) Point(position.toLngLat(), properties) } selectedQuestPinsLayer?.setFeatures(points) } private fun removeSelectedQuestPins() { selectedQuestPinsLayer?.clear() } /* ------------------------------ Geometry for current quest ------------------------------- */ private fun putQuestGeometry(geometry: ElementGeometry) { geometryLayer?.setFeatures(geometry.toTangramGeometry()) } private fun removeQuestGeometry() { geometryLayer?.clear() } /* ------------------------- Markers for current quest (split way) ------------------------- */ fun putMarkerForCurrentQuest(pos: LatLon) { deleteMarkerForCurrentQuest(pos) val marker = controller?.addMarker() ?: return marker.setDrawable(R.drawable.crosshair_marker) marker.setStylingFromString("{ style: 'points', color: 'white', size: 48px, order: 2000, collide: false }") marker.setPoint(pos) markerIds[pos] = marker.markerId } fun deleteMarkerForCurrentQuest(pos: LatLon) { val markerId = markerIds[pos] ?: return controller?.removeMarker(markerId) markerIds.remove(pos) } fun clearMarkersForCurrentQuest() { for (markerId in markerIds.values) { controller?.removeMarker(markerId) } markerIds.clear() } /* --------------------------------- Position tracking -------------------------------------- */ override fun shouldCenterCurrentPosition(): Boolean { // don't center position while displaying a quest return super.shouldCenterCurrentPosition() && cameraPositionBeforeShowingQuest == null } companion object { // see streetcomplete.yaml for the definitions of the below layers private const val GEOMETRY_LAYER = "streetcomplete_geometry" private const val QUESTS_LAYER = "streetcomplete_quests" private const val SELECTED_QUESTS_LAYER = "streetcomplete_selected_quests" private const val CLICK_AREA_SIZE_IN_DP = 48 } }
gpl-3.0
2bcf5b11a3aa4993ee2531e29bdfb60d
37.68254
137
0.646697
4.889647
false
false
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/utils/ui/TargetBgProfileGraph.kt
1
5002
package info.nightscout.androidaps.utils.ui import android.content.Context import android.util.AttributeSet import com.jjoe64.graphview.DefaultLabelFormatter import com.jjoe64.graphview.GraphView import info.nightscout.androidaps.core.R import info.nightscout.androidaps.interfaces.GlucoseUnit import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.plugins.general.overview.graphExtensions.AreaGraphSeries import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DoubleDataPoint import info.nightscout.androidaps.utils.Round import java.text.NumberFormat import kotlin.math.max import kotlin.math.min class TargetBgProfileGraph : GraphView { constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) fun show(profile: Profile) { removeAllSeries() val targetArray: MutableList<DoubleDataPoint> = ArrayList() var maxValue = 0.0 val units = profile.units for (hour in 0..23) { val valueLow = Profile.fromMgdlToUnits(profile.getTargetLowMgdlTimeFromMidnight(hour * 60 * 60), units) val valueHigh = Profile.fromMgdlToUnits(profile.getTargetHighMgdlTimeFromMidnight(hour * 60 * 60), units) maxValue = max(maxValue, valueHigh) targetArray.add(DoubleDataPoint(hour.toDouble(), valueLow, valueHigh)) targetArray.add(DoubleDataPoint((hour + 1).toDouble(), valueLow, valueHigh)) } val targetDataPoints: Array<DoubleDataPoint> = Array(targetArray.size) { i -> targetArray[i] } val targetSeries: AreaGraphSeries<DoubleDataPoint> = AreaGraphSeries(targetDataPoints) addSeries(targetSeries) targetSeries.isDrawBackground = true viewport.isXAxisBoundsManual = true viewport.setMinX(0.0) viewport.setMaxX(24.0) viewport.isYAxisBoundsManual = true viewport.setMinY(0.0) viewport.setMaxY(Round.ceilTo(maxValue * 1.1, 0.5)) gridLabelRenderer.numHorizontalLabels = 13 gridLabelRenderer.verticalLabelsColor = targetSeries.color val nf: NumberFormat = NumberFormat.getInstance() nf.maximumFractionDigits = if (units == GlucoseUnit.MMOL) 1 else 0 gridLabelRenderer.labelFormatter = DefaultLabelFormatter(nf, nf) } fun show(profile1: Profile, profile2: Profile) { removeAllSeries() val targetArray1: MutableList<DoubleDataPoint> = ArrayList() var minValue = 1000.0 var maxValue = 0.0 val units = profile1.units for (hour in 0..23) { val valueLow = Profile.fromMgdlToUnits(profile1.getTargetLowMgdlTimeFromMidnight(hour * 60 * 60), units) val valueHigh = Profile.fromMgdlToUnits(profile1.getTargetHighMgdlTimeFromMidnight(hour * 60 * 60), units) minValue = min(minValue, valueLow) maxValue = max(maxValue, valueHigh) targetArray1.add(DoubleDataPoint(hour.toDouble(), valueLow, valueHigh)) targetArray1.add(DoubleDataPoint((hour + 1).toDouble(), valueLow, valueHigh)) } val targetDataPoints1: Array<DoubleDataPoint> = Array(targetArray1.size) { i -> targetArray1[i] } val targetSeries1: AreaGraphSeries<DoubleDataPoint> = AreaGraphSeries(targetDataPoints1) addSeries(targetSeries1) targetSeries1.isDrawBackground = true val targetArray2: MutableList<DoubleDataPoint> = ArrayList() for (hour in 0..23) { val valueLow = Profile.fromMgdlToUnits(profile2.getTargetLowMgdlTimeFromMidnight(hour * 60 * 60), units) val valueHigh = Profile.fromMgdlToUnits(profile2.getTargetHighMgdlTimeFromMidnight(hour * 60 * 60), units) minValue = min(minValue, valueLow) maxValue = max(maxValue, valueHigh) targetArray2.add(DoubleDataPoint(hour.toDouble(), valueLow, valueHigh)) targetArray2.add(DoubleDataPoint((hour + 1).toDouble(), valueLow, valueHigh)) } val targetDataPoints2: Array<DoubleDataPoint> = Array(targetArray2.size) { i -> targetArray2[i] } val targetSeries2: AreaGraphSeries<DoubleDataPoint> = AreaGraphSeries(targetDataPoints2) addSeries(targetSeries2) targetSeries2.isDrawBackground = false targetSeries2.color = context.getColor(R.color.examinedProfile) viewport.isXAxisBoundsManual = true viewport.setMinX(0.0) viewport.setMaxX(24.0) viewport.isYAxisBoundsManual = true viewport.setMinY(Round.floorTo(minValue / 1.1, 0.5)) viewport.setMaxY(Round.ceilTo(maxValue * 1.1, 0.5)) gridLabelRenderer.numHorizontalLabels = 13 gridLabelRenderer.verticalLabelsColor = targetSeries1.color val nf: NumberFormat = NumberFormat.getInstance() nf.maximumFractionDigits = if (units == GlucoseUnit.MMOL) 1 else 0 gridLabelRenderer.labelFormatter = DefaultLabelFormatter(nf, nf) } }
agpl-3.0
94d8a0ccfee2075946b1a5d2b6686330
48.039216
118
0.709116
4.242578
false
false
false
false
prt2121/android-workspace
Everywhere/app/src/main/kotlin/com/prt2121/everywhere/meetup/MeetupUtils.kt
1
2194
package com.prt2121.everywhere.meetup import android.location.Location import com.prt2121.everywhere.Rx import com.prt2121.everywhere.TokenStorage import com.prt2121.everywhere.meetup.model.Group import com.prt2121.summon.location.UserLocation import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.GsonConverterFactory import retrofit2.Retrofit import retrofit2.RxJavaCallAdapterFactory import rx.Observable import java.util.* /** * Created by pt2121 on 1/23/16. */ object MeetupUtils { fun groupsByLatLng(token: Observable<String>, location: Observable<Location>, radius: Int = 10): Observable<ArrayList<Group>> { val service = MeetupUtils.meetupService() return location .doOnNext { println("it == null ${it == null}") } .filter { it != null } .flatMap { loc -> token.flatMap { service.groupsByLatLong("Bearer $it", loc.latitude, loc.longitude, radius, "25") } } .compose(Rx.applySchedulers<ArrayList<Group>>()) } fun groups(token: Observable<String>, lat: Double, lng: Double, radius: Int = 10): Observable<ArrayList<Group>> { val service = MeetupUtils.meetupService() return token.flatMap { service.groupsByLatLong("Bearer $it", lat, lng, radius, "25") } .compose(Rx.applySchedulers<ArrayList<Group>>()) } fun groups(token: Observable<String>): Observable<ArrayList<Group>> { val service = MeetupUtils.meetupService() return token.flatMap { service.groupsByZip("Bearer $it", "10003", "1", "25") } .compose(Rx.applySchedulers<ArrayList<Group>>()) } fun meetupService(): MeetupService { val logging = HttpLoggingInterceptor() logging.setLevel(HttpLoggingInterceptor.Level.BODY) val client = OkHttpClient.Builder() .addInterceptor(logging) .build() val retrofit = Retrofit.Builder() .baseUrl("https://api.meetup.com") .client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build() val service = retrofit.create(MeetupService::class.java) return service } }
apache-2.0
814bd2d8243f6c0c63abb0b66757e7b0
33.296875
129
0.698268
4.268482
false
false
false
false
yyYank/Kebab
src/main/kotlin/js/JavascriptInterface.kt
1
1313
package js import kebab.core.Browser import kebab.exception.GebException import org.openqa.selenium.JavascriptExecutor /** * Created by yy_yank on 2016/12/25. */ class JavascriptInterface(val browser: Browser?) { private fun execjs(script: String, args: List<JavascriptExecutor>?) { val driver = browser?.config?.driver if (!(driver is JavascriptExecutor)) { throw GebException("driver '$driver' can not execute javascript") } driver.executeScript(script, args) } fun propertyMissing(name: String) { execjs("return $name;", null) } fun methodMissing(name: String, args: List<JavascriptExecutor>) { execjs("return ${name}.apply(window, arguments)", args) } fun exec(args: Pair<String, Array<JavascriptExecutor>>) { val (script, jsArgs) = if (args.second.size == 1) { val jsArgs = arrayListOf<JavascriptExecutor>() Pair(args.second[0], jsArgs) } else { val jsArgs = args.second.dropLast(args.second.size - 2) Pair(args.first, jsArgs) } if (!(script is CharSequence)) { throw IllegalArgumentException("The last argument to the js function must be string-like") } execjs(script.toString(), jsArgs) } }
apache-2.0
65b7abaa2a5d8e17cae8dd024c676735
26.354167
102
0.62757
4.155063
false
false
false
false
pyamsoft/pydroid
ui/src/main/java/com/pyamsoft/pydroid/ui/internal/billing/BillingViewModeler.kt
1
2422
/* * Copyright 2022 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.pydroid.ui.internal.billing import com.pyamsoft.highlander.highlander import com.pyamsoft.pydroid.arch.AbstractViewModeler import com.pyamsoft.pydroid.billing.BillingInteractor import com.pyamsoft.pydroid.bootstrap.changelog.ChangeLogInteractor import com.pyamsoft.pydroid.core.Logger import com.pyamsoft.pydroid.ui.internal.app.AppProvider import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch internal class BillingViewModeler internal constructor( private val state: MutableBillingViewState, private val changeLogInteractor: ChangeLogInteractor, private val interactor: BillingInteractor, private val provider: AppProvider, ) : AbstractViewModeler<BillingViewState>(state) { private val refreshRunner = highlander<Unit>( context = Dispatchers.IO, ) { interactor.refresh() } internal fun bind(scope: CoroutineScope) { scope.launch(context = Dispatchers.Main) { val displayName = changeLogInteractor.getDisplayName() state.apply { name = displayName icon = provider.applicationIcon } } scope.launch(context = Dispatchers.Main) { interactor.watchSkuList { status, list -> Logger.d("SKU list updated: $status $list") state.apply { connected = status skuList = list.sortedBy { it.price } } } } scope.launch(context = Dispatchers.Main) { interactor.watchErrors { error -> Logger.e(error, "Billing error received") state.error = error } } } internal fun handleClearError() { state.error = null } internal fun handleRefresh(scope: CoroutineScope) { scope.launch(context = Dispatchers.Main) { refreshRunner.call() } } }
apache-2.0
7ac20538bc99df8505d9c76ed1a7ce7d
30.051282
75
0.715524
4.371841
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/impl/DefaultVBox.kt
1
3204
package org.hexworks.zircon.internal.component.impl import org.hexworks.cobalt.events.api.DisposeSubscription import org.hexworks.cobalt.events.api.KeepSubscription import org.hexworks.cobalt.events.api.subscribeTo import org.hexworks.zircon.api.behavior.TitleOverride import org.hexworks.zircon.api.component.ColorTheme import org.hexworks.zircon.api.component.Component import org.hexworks.zircon.api.component.VBox import org.hexworks.zircon.api.component.data.ComponentMetadata import org.hexworks.zircon.api.component.renderer.ComponentRenderingStrategy import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.internal.component.InternalAttachedComponent import org.hexworks.zircon.internal.component.InternalComponent import org.hexworks.zircon.internal.event.ZirconEvent.ComponentRemoved import kotlin.jvm.Synchronized class DefaultVBox internal constructor( componentMetadata: ComponentMetadata, initialTitle: String, private val spacing: Int, renderingStrategy: ComponentRenderingStrategy<VBox> ) : VBox, DefaultContainer( metadata = componentMetadata, renderer = renderingStrategy ), TitleOverride by TitleOverride.create(initialTitle) { private var filledUntil = Position.create(0, 0) private var availableSpace = contentSize.toRect() override val remainingSpace: Int get() = availableSpace.height @Synchronized override fun addComponent(component: Component): InternalAttachedComponent { require(component is InternalComponent) { "The supplied component does not implement required interface: InternalComponent." } checkAvailableSpace(component) val finalSpacing = if (children.isEmpty()) 0 else spacing val finalHeight = component.height + finalSpacing component.moveDownBy(filledUntil.y + finalSpacing) filledUntil = filledUntil.withRelativeY(finalHeight) availableSpace = availableSpace.withRelativeHeight(-finalHeight) return VBoxAttachmentDecorator(super<DefaultContainer>.addComponent(component)) } private inner class VBoxAttachmentDecorator( val attachedComponent: InternalAttachedComponent ) : InternalAttachedComponent by attachedComponent { override fun detach(): Component { reorganizeComponents(attachedComponent.component) return attachedComponent.detach() } } private fun reorganizeComponents(component: Component) { val height = component.height val delta = height + if (children.isEmpty()) 0 else spacing val y = component.position.y children.filter { it.position.y > y }.forEach { it.moveUpBy(delta) } filledUntil = filledUntil.withRelativeY(-delta) availableSpace = availableSpace.withRelativeHeight(delta) } override fun convertColorTheme(colorTheme: ColorTheme) = colorTheme.toContainerStyle() private fun checkAvailableSpace(component: Component) = require(availableSpace.containsBoundable(component.rect)) { "There is not enough space ${availableSpace.size} left in $this to add $component as a child." } }
apache-2.0
f1b3ff2f2bfe51afbda3f4c937d3304d
40.076923
106
0.748439
4.861912
false
false
false
false
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/features/output/OutputSelectionDialog.kt
1
5060
package com.kelsos.mbrc.features.output import android.annotation.SuppressLint import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.ProgressBar import android.widget.Spinner import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.core.view.isInvisible import androidx.core.view.isVisible import androidx.fragment.app.DialogFragment import androidx.fragment.app.FragmentManager import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.kelsos.mbrc.R import com.kelsos.mbrc.di.modules.obtainViewModel import toothpick.Scope import toothpick.Toothpick class OutputSelectionDialog() : DialogFragment(), View.OnTouchListener { private var touchInitiated: Boolean = false private lateinit var fm: FragmentManager private lateinit var dialog: AlertDialog private lateinit var availableOutputs: Spinner private lateinit var loadingProgress: ProgressBar private lateinit var errorMessage: TextView private var scope: Scope? = null private val onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { } override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { if (!touchInitiated) { return } val selectedOutput = availableOutputs.adapter.getItem(position) as String viewModel.setOutput(selectedOutput) touchInitiated = false } } private lateinit var viewModel: OutputSelectionViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) scope = Toothpick.openScopes(requireActivity().application, this) Toothpick.inject(this, scope) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel.outputs.observe(this) { update(it) } viewModel.selection.observe(this) { val adapter = availableOutputs.adapter as ArrayAdapter<*> for (position in 0 until adapter.count) { if (it == adapter.getItem(position)) { availableOutputs.setSelection(position, false) break } } } viewModel.events.observe(this) { if (it.handled) { return@observe } it.handled = true when (it) { OutputSelectionResult.Success -> { availableOutputs.isVisible = true errorMessage.isInvisible = true } else -> error(it) } } viewModel.reload() } @SuppressLint("InflateParams") override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val context = requireContext() val inflater = LayoutInflater.from(context) val view = inflater.inflate(R.layout.dialog__output_selection, null, false) availableOutputs = view.findViewById(R.id.output_selection__available_outputs) loadingProgress = view.findViewById(R.id.output_selection__loading_outputs) errorMessage = view.findViewById(R.id.output_selection__error_message) viewModel = obtainViewModel(OutputSelectionViewModel::class.java) dialog = MaterialAlertDialogBuilder(context) .setTitle(R.string.output_selection__select_output) .setView(view) .setNeutralButton(R.string.output_selection__close_dialog) { dialogInterface, _ -> dialogInterface.dismiss() } .create() return dialog } override fun onDestroy() { Toothpick.closeScope(this) super.onDestroy() } override fun onTouch(view: View?, event: MotionEvent?): Boolean { touchInitiated = true return view?.performClick() == true } private fun update(data: List<String>) { availableOutputs.onItemSelectedListener = null availableOutputs.setOnTouchListener(null) val outputAdapter = ArrayAdapter( requireContext(), R.layout.item__output_device, R.id.output_selection__output_device, data ) availableOutputs.adapter = outputAdapter availableOutputs.onItemSelectedListener = onItemSelectedListener availableOutputs.setOnTouchListener(this) loadingProgress.isVisible = false availableOutputs.isVisible = true } fun error(result: OutputSelectionResult) { val resId = when (result) { OutputSelectionResult.ConnectionError -> R.string.output_selection__connection_error else -> R.string.output_selection__generic_error } errorMessage.setText(resId) loadingProgress.isVisible = false availableOutputs.isInvisible = true errorMessage.isVisible = true } override fun dismiss() { dialog.dismiss() } fun show() { show(fm, TAG) } companion object { private const val TAG = "output_selection_dialog" fun create(fm: FragmentManager): OutputSelectionDialog { val dialog = OutputSelectionDialog() dialog.fm = fm return dialog } } }
gpl-3.0
84d662c6637b3db4743275f5fe10f969
29.299401
96
0.724704
4.733396
false
false
false
false
mdaniel/intellij-community
platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/ModuleBridgeLoaderService.kt
1
5454
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.ide.impl.legacyBridge.module import com.intellij.diagnostic.Activity import com.intellij.diagnostic.ActivityCategory import com.intellij.diagnostic.StartUpMeasurer import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.EDT import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.impl.ProjectServiceContainerInitializedListener import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.platform.PlatformProjectOpenProcessor.Companion.PROJECT_LOADED_FROM_CACHE_BUT_HAS_NO_MODULES import com.intellij.workspaceModel.ide.JpsProjectLoadedListener import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.ide.impl.WorkspaceModelImpl import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsProjectModelSynchronizer import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl import com.intellij.workspaceModel.ide.impl.legacyBridge.project.ProjectRootManagerBridge import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleEntity import kotlinx.coroutines.* internal class ModuleBridgeLoaderService(private val project: Project) { companion object { private val LOG = logger<ModuleBridgeLoaderService>() } private var storeToEntitySources: Pair<EntityStorage, List<EntitySource>>? = null private var activity: Activity? = null private val loadModuleJob: Job init { if (project.isDefault) { loadModuleJob = CompletableDeferred(value = null) } else { val projectModelSynchronizer = JpsProjectModelSynchronizer.getInstance(project) if (projectModelSynchronizer == null) { loadModuleJob = CompletableDeferred(value = null) } else { val workspaceModel = WorkspaceModel.getInstance(project) as WorkspaceModelImpl if (workspaceModel.loadedFromCache) { if (projectModelSynchronizer.hasNoSerializedJpsModules()) { LOG.warn("Loaded from cache, but no serialized modules found. Workspace model cache will be ignored, project structure will be recreated.") workspaceModel.ignoreCache() // sets `WorkspaceModelImpl#loadedFromCache` to `false` project.putUserData(PROJECT_LOADED_FROM_CACHE_BUT_HAS_NO_MODULES, true) } activity = StartUpMeasurer.startActivity("modules loading with cache", ActivityCategory.DEFAULT) loadModuleJob = project.coroutineScope.async { loadModules() } } else { LOG.info("Workspace model loaded without cache. Loading real project state into workspace model. ${Thread.currentThread()}") activity = StartUpMeasurer.startActivity("modules loading without cache", ActivityCategory.DEFAULT) storeToEntitySources = projectModelSynchronizer.loadProjectToEmptyStorage(project) loadModuleJob = CompletableDeferred(value = null) } } } } private suspend fun loadModules() { val childActivity = activity?.startChild("modules instantiation") val moduleManager = ModuleManager.getInstance(project) as ModuleManagerComponentBridge val entities = moduleManager.entityStore.current.entities(ModuleEntity::class.java) moduleManager.loadModules(entities) childActivity?.setDescription("modules count: ${moduleManager.modules.size}") childActivity?.end() val librariesActivity = StartUpMeasurer.startActivity("libraries instantiation", ActivityCategory.DEFAULT) (LibraryTablesRegistrar.getInstance().getLibraryTable(project) as ProjectLibraryTableBridgeImpl).loadLibraries() librariesActivity.end() activity?.end() activity = null } internal class ModuleBridgeProjectServiceInitializedListener : ProjectServiceContainerInitializedListener { override suspend fun serviceCreated(project: Project) { LOG.debug { "Project component initialized" } val workspaceModel = WorkspaceModel.getInstance(project) as WorkspaceModelImpl val moduleLoaderService = project.service<ModuleBridgeLoaderService>() moduleLoaderService.loadModuleJob.join() if (!workspaceModel.loadedFromCache) { val projectModelSynchronizer = JpsProjectModelSynchronizer.getInstance(project) ?: return projectModelSynchronizer.applyLoadedStorage(moduleLoaderService.storeToEntitySources) project.messageBus.syncPublisher(JpsProjectLoadedListener.LOADED).loaded() moduleLoaderService.storeToEntitySources = null moduleLoaderService.loadModules() } withContext(Dispatchers.EDT) { ApplicationManager.getApplication().runWriteAction { (ProjectRootManager.getInstance(project) as ProjectRootManagerBridge).setupTrackedLibrariesAndJdks() } } WorkspaceModelTopics.getInstance(project).notifyModulesAreLoaded() } } }
apache-2.0
3aae97411008d7e832add18e6b17c624
48.144144
151
0.780895
5.336595
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/hints/KotlinReferencesTypeHintsProvider.kt
2
4817
// 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.codeInsight.hints import com.intellij.codeInsight.hints.ChangeListener import com.intellij.codeInsight.hints.ImmediateConfigurable import com.intellij.codeInsight.hints.InlayGroup import com.intellij.codeInsight.hints.SettingsKey import com.intellij.ui.layout.* import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import javax.swing.JComponent class KotlinReferencesTypeHintsProvider : KotlinAbstractHintsProvider<KotlinReferencesTypeHintsProvider.Settings>() { data class Settings( var propertyType: Boolean = false, var localVariableType: Boolean = false, var functionReturnType: Boolean = false, var parameterType: Boolean = false ): HintsSettings() { override fun isEnabled(hintType: HintType) = when(hintType) { HintType.PROPERTY_HINT -> propertyType HintType.LOCAL_VARIABLE_HINT -> localVariableType HintType.FUNCTION_HINT -> functionReturnType HintType.PARAMETER_TYPE_HINT -> parameterType else -> false } override fun enable(hintType: HintType, enable: Boolean) = when(hintType) { HintType.PROPERTY_HINT -> propertyType = enable HintType.LOCAL_VARIABLE_HINT -> localVariableType = enable HintType.FUNCTION_HINT -> functionReturnType = enable HintType.PARAMETER_TYPE_HINT -> parameterType = enable else -> Unit } } override val key: SettingsKey<Settings> = SettingsKey("kotlin.references.types.hints") override val name: String = KotlinBundle.message("hints.settings.types") override val group: InlayGroup get() = InlayGroup.TYPES_GROUP override fun createConfigurable(settings: Settings): ImmediateConfigurable { return object : ImmediateConfigurable { override fun createComponent(listener: ChangeListener): JComponent = panel {} override val mainCheckboxText: String = KotlinBundle.message("hints.settings.common.items") override val cases: List<ImmediateConfigurable.Case> get() = listOf( ImmediateConfigurable.Case( KotlinBundle.message("hints.settings.types.property"), "hints.type.property", settings::propertyType, KotlinBundle.message("inlay.kotlin.references.types.hints.hints.type.property") ), ImmediateConfigurable.Case( KotlinBundle.message("hints.settings.types.variable"), "hints.type.variable", settings::localVariableType, KotlinBundle.message("inlay.kotlin.references.types.hints.hints.type.variable") ), ImmediateConfigurable.Case( KotlinBundle.message("hints.settings.types.return"), "hints.type.function.return", settings::functionReturnType, KotlinBundle.message("inlay.kotlin.references.types.hints.hints.type.function.return") ), ImmediateConfigurable.Case( KotlinBundle.message("hints.settings.types.parameter"), "hints.type.function.parameter", settings::parameterType, KotlinBundle.message("inlay.kotlin.references.types.hints.hints.type.function.parameter") ), ) } } override val description: String get() = KotlinBundle.message("inlay.kotlin.references.types.hints") override fun createSettings(): Settings = Settings() override fun isElementSupported(resolved: HintType?, settings: Settings): Boolean { return when (resolved) { HintType.PROPERTY_HINT -> settings.propertyType HintType.LOCAL_VARIABLE_HINT -> settings.localVariableType HintType.FUNCTION_HINT -> settings.functionReturnType HintType.PARAMETER_TYPE_HINT -> settings.parameterType else -> false } } override fun isHintSupported(hintType: HintType): Boolean = hintType == HintType.PROPERTY_HINT || hintType == HintType.LOCAL_VARIABLE_HINT || hintType == HintType.FUNCTION_HINT || hintType == HintType.PARAMETER_TYPE_HINT override val previewText: String? = null }
apache-2.0
a028317a05a4dd7c3862b6bce769755e
46.70297
120
0.610546
5.687131
false
true
false
false
mdaniel/intellij-community
plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/search/ideaExtensions/KotlinReferencesSearcher.kt
1
23463
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.search.ideaExtensions import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.QueryExecutorBase import com.intellij.openapi.application.ReadAction import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.psi.impl.cache.CacheManager import com.intellij.psi.search.* import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.util.Processor import com.intellij.util.concurrency.annotations.RequiresReadLock import com.intellij.util.containers.nullize import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.LightClassUtil.getLightClassMethods import org.jetbrains.kotlin.asJava.LightClassUtil.getLightClassPropertyMethods import org.jetbrains.kotlin.asJava.LightClassUtil.getLightFieldForCompanionObject import org.jetbrains.kotlin.asJava.elements.KtLightField import org.jetbrains.kotlin.asJava.elements.KtLightMember import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.asJava.elements.KtLightParameter import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.asJava.toLightElements import org.jetbrains.kotlin.idea.base.util.allScope import org.jetbrains.kotlin.idea.base.util.restrictToKotlinSources import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesSupport.Companion.sourcesAndLibraries import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.dataClassComponentMethodName import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.expectedDeclarationIfAny import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.filterDataClassComponentsIfDisabled import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.isExpectDeclaration import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.search.* import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions.Companion.Empty import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions.Companion.calculateEffectiveScope import org.jetbrains.kotlin.idea.search.usagesSearch.operators.OperatorReferenceSearcher import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.utils.addToStdlib.ifTrue import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.util.concurrent.Callable data class KotlinReferencesSearchOptions( val acceptCallableOverrides: Boolean = false, val acceptOverloads: Boolean = false, val acceptExtensionsOfDeclarationClass: Boolean = false, val acceptCompanionObjectMembers: Boolean = false, val acceptImportAlias: Boolean = true, val searchForComponentConventions: Boolean = true, val searchForOperatorConventions: Boolean = true, val searchNamedArguments: Boolean = true, val searchForExpectedUsages: Boolean = true ) { fun anyEnabled(): Boolean = acceptCallableOverrides || acceptOverloads || acceptExtensionsOfDeclarationClass companion object { val Empty = KotlinReferencesSearchOptions() internal fun calculateEffectiveScope( elementToSearch: PsiNamedElement, parameters: ReferencesSearch.SearchParameters ): SearchScope { val kotlinOptions = (parameters as? KotlinAwareReferencesSearchParameters)?.kotlinOptions ?: Empty val elements = if (elementToSearch is KtDeclaration && !isOnlyKotlinSearch(parameters.scopeDeterminedByUser)) { elementToSearch.toLightElements().filterDataClassComponentsIfDisabled(kotlinOptions).nullize() } else { null } ?: listOf(elementToSearch) return elements.fold(parameters.effectiveSearchScope) { scope, e -> scope.unionSafe(parameters.effectiveSearchScope(e)) } } private fun SearchScope.unionSafe(other: SearchScope): SearchScope { if (this is LocalSearchScope && this.scope.isEmpty()) { return other } if (other is LocalSearchScope && other.scope.isEmpty()) { return this } return this.union(other) } } } interface KotlinAwareReferencesSearchParameters { val kotlinOptions: KotlinReferencesSearchOptions } class KotlinReferencesSearchParameters( elementToSearch: PsiElement, scope: SearchScope = runReadAction { elementToSearch.project.allScope() }, ignoreAccessScope: Boolean = false, optimizer: SearchRequestCollector? = null, override val kotlinOptions: KotlinReferencesSearchOptions = Empty ) : ReferencesSearch.SearchParameters(elementToSearch, scope, ignoreAccessScope, optimizer), KotlinAwareReferencesSearchParameters class KotlinMethodReferencesSearchParameters( elementToSearch: PsiMethod, scope: SearchScope = runReadAction { elementToSearch.project.allScope() }, strictSignatureSearch: Boolean = true, override val kotlinOptions: KotlinReferencesSearchOptions = Empty ) : MethodReferencesSearch.SearchParameters(elementToSearch, scope, strictSignatureSearch), KotlinAwareReferencesSearchParameters class KotlinAliasedImportedElementSearcher : QueryExecutorBase<PsiReference, ReferencesSearch.SearchParameters>() { override fun processQuery(parameters: ReferencesSearch.SearchParameters, consumer: Processor<in PsiReference?>) { val kotlinOptions = (parameters as? KotlinAwareReferencesSearchParameters)?.kotlinOptions ?: Empty if (!kotlinOptions.acceptImportAlias) return val queryFunction = ReadAction.nonBlocking(Callable { val element = parameters.elementToSearch if (!element.isValid) return@Callable null val unwrappedElement = element.namedUnwrappedElement ?: return@Callable null val name = unwrappedElement.name if (name == null || StringUtil.isEmptyOrSpaces(name)) return@Callable null val effectiveSearchScope = calculateEffectiveScope(unwrappedElement, parameters) val collector = parameters.optimizer val session = collector.searchSession val function = { collector.searchWord( name, effectiveSearchScope, UsageSearchContext.IN_CODE, true, element, AliasProcessor(element, session) ) } function }).inSmartMode(parameters.project) .executeSynchronously() queryFunction?.invoke() } private class AliasProcessor( private val myTarget: PsiElement, private val mySession: SearchSession ) : RequestResultProcessor(myTarget) { override fun processTextOccurrence(element: PsiElement, offsetInElement: Int, consumer: Processor<in PsiReference>): Boolean { val importStatement = element.parent as? KtImportDirective ?: return true val importAlias = importStatement.alias?.name ?: return true val reference = importStatement.importedReference?.getQualifiedElementSelector()?.mainReference ?: return true if (!reference.isReferenceTo(myTarget)) { return true } val collector = SearchRequestCollector(mySession) val fileScope: SearchScope = LocalSearchScope(element.containingFile) collector.searchWord(importAlias, fileScope, UsageSearchContext.IN_CODE, true, myTarget) return PsiSearchHelper.getInstance(element.project).processRequests(collector, consumer) } } } class KotlinReferencesSearcher : QueryExecutorBase<PsiReference, ReferencesSearch.SearchParameters>() { override fun processQuery(queryParameters: ReferencesSearch.SearchParameters, consumer: Processor<in PsiReference>) { val processor = QueryProcessor(queryParameters, consumer) processor.process() processor.executeLongRunningTasks() } private class QueryProcessor(val queryParameters: ReferencesSearch.SearchParameters, val consumer: Processor<in PsiReference>) { private val kotlinOptions = queryParameters.safeAs<KotlinAwareReferencesSearchParameters>()?.kotlinOptions ?: Empty private val longTasks = mutableListOf<() -> Unit>() fun executeLongRunningTasks() { longTasks.forEach { ProgressManager.checkCanceled() it() } } fun process() { var element: SmartPsiElementPointer<PsiElement>? = null var classNameForCompanionObject: String? = null val (elementToSearchPointer: SmartPsiElementPointer<PsiNamedElement>, effectiveSearchScope) = ReadAction.nonBlocking(Callable { val psiElement = queryParameters.elementToSearch if (!psiElement.isValid) return@Callable null val unwrappedElement = psiElement.namedUnwrappedElement ?: return@Callable null val elementToSearch = if (kotlinOptions.searchForExpectedUsages && unwrappedElement is KtDeclaration && unwrappedElement.hasActualModifier()) { unwrappedElement.expectedDeclarationIfAny() as? PsiNamedElement } else { null } ?: unwrappedElement val effectiveSearchScope = calculateEffectiveScope(elementToSearch, queryParameters) element = SmartPointerManager.createPointer(psiElement) classNameForCompanionObject = elementToSearch.getClassNameForCompanionObject() SmartPointerManager.createPointer(elementToSearch) to effectiveSearchScope }).inSmartMode(queryParameters.project) .executeSynchronously() ?: return runReadAction { element?.element } ?: return runReadAction { elementToSearchPointer.element?.let { elementToSearch -> val refFilter: (PsiReference) -> Boolean = when (elementToSearch) { is KtParameter -> ({ ref: PsiReference -> !ref.isNamedArgumentReference()/* they are processed later*/ }) else -> ({ true }) } val resultProcessor = KotlinRequestResultProcessor(elementToSearch, filter = refFilter, options = kotlinOptions) if (kotlinOptions.anyEnabled() || elementToSearch is KtNamedDeclaration && elementToSearch.isExpectDeclaration()) { elementToSearch.name?.let { name -> longTasks.add { // Check difference with default scope runReadAction { elementToSearchPointer.element }?.let { elementToSearch -> queryParameters.optimizer.searchWord( name, effectiveSearchScope, UsageSearchContext.IN_CODE, true, elementToSearch, resultProcessor ) } } } } classNameForCompanionObject?.let { name -> longTasks.add { runReadAction { elementToSearchPointer.element }?.let { elementToSearch -> queryParameters.optimizer.searchWord( name, effectiveSearchScope, UsageSearchContext.ANY, true, elementToSearch, resultProcessor ) } } } } if (elementToSearchPointer.element is KtParameter && kotlinOptions.searchNamedArguments) { longTasks.add { ReadAction.nonBlocking(Callable { elementToSearchPointer.element.safeAs<KtParameter>()?.let(::searchNamedArguments) }).executeSynchronously() } } if (!(elementToSearchPointer.element is KtElement && runReadAction { isOnlyKotlinSearch(effectiveSearchScope) })) { longTasks.add { ReadAction.nonBlocking(Callable { element?.element?.let(::searchLightElements) }).executeSynchronously() } } element?.element?.takeIf { it is KtFunction || it is PsiMethod }?.let { _ -> element?.element?.let { OperatorReferenceSearcher.create( it, effectiveSearchScope, consumer, queryParameters.optimizer, kotlinOptions ) } ?.let { searcher -> longTasks.add { searcher.run() } } } } if (kotlinOptions.searchForComponentConventions) { element?.let(::searchForComponentConventions) } } private fun PsiNamedElement.getClassNameForCompanionObject(): String? = (this is KtObjectDeclaration && this.isCompanion()) .ifTrue { getNonStrictParentOfType<KtClass>()?.name } private fun searchNamedArguments(parameter: KtParameter) { val parameterName = parameter.name ?: return val function = parameter.ownerFunction as? KtFunction ?: return if (function.nameAsName?.isSpecial != false) return val project = function.project var namedArgsScope = function.useScope.intersectWith(queryParameters.scopeDeterminedByUser) if (namedArgsScope is GlobalSearchScope) { namedArgsScope = sourcesAndLibraries(namedArgsScope, project) val filesWithFunctionName = CacheManager.getInstance(project).getVirtualFilesWithWord( function.name!!, UsageSearchContext.IN_CODE, namedArgsScope, true ) namedArgsScope = GlobalSearchScope.filesScope(project, filesWithFunctionName.asList()) } val processor = KotlinRequestResultProcessor(parameter, filter = { it.isNamedArgumentReference() }) queryParameters.optimizer.searchWord( parameterName, namedArgsScope, KOTLIN_NAMED_ARGUMENT_SEARCH_CONTEXT, true, parameter, processor ) } @RequiresReadLock private fun searchLightElements(element: PsiElement) { when (element) { is KtClassOrObject -> { processKtClassOrObject(element) } is KtNamedFunction, is KtSecondaryConstructor -> { (element as KtFunction).name?.let { getLightClassMethods(element).forEach(::searchNamedElement) } processStaticsFromCompanionObject(element) } is KtProperty -> { val propertyDeclarations = getLightClassPropertyMethods(element).allDeclarations propertyDeclarations.forEach(::searchNamedElement) processStaticsFromCompanionObject(element) } is KtParameter -> { searchPropertyAccessorMethods(element) if (element.getStrictParentOfType<KtPrimaryConstructor>() != null) { // Simple parameters without val and var shouldn't be processed here because of local search scope val parameterDeclarations = getLightClassPropertyMethods(element).allDeclarations parameterDeclarations.filterDataClassComponentsIfDisabled(kotlinOptions).forEach(::searchNamedElement) } } is KtLightMethod -> { val declaration = element.kotlinOrigin if (declaration is KtProperty || (declaration is KtParameter && declaration.hasValOrVar())) { searchNamedElement(declaration as PsiNamedElement) processStaticsFromCompanionObject(declaration) } else if (declaration is KtPropertyAccessor) { val property = declaration.getStrictParentOfType<KtProperty>() searchNamedElement(property) } else if (declaration is KtFunction) { processStaticsFromCompanionObject(declaration) if (element.isMangled) { searchNamedElement(declaration) { it.restrictToKotlinSources() } } } } is KtLightParameter -> { val origin = element.kotlinOrigin ?: return searchPropertyAccessorMethods(origin) } } } @RequiresReadLock private fun searchPropertyAccessorMethods(origin: KtParameter) { origin.toLightElements().filterDataClassComponentsIfDisabled(kotlinOptions).forEach(::searchNamedElement) } @RequiresReadLock private fun processKtClassOrObject(element: KtClassOrObject) { val className = element.name ?: return val lightClass = element.toLightClass() ?: return searchNamedElement(lightClass, className) if (element is KtObjectDeclaration && element.isCompanion()) { getLightFieldForCompanionObject(element)?.let(::searchNamedElement) if (kotlinOptions.acceptCompanionObjectMembers) { val originLightClass = element.getStrictParentOfType<KtClass>()?.toLightClass() if (originLightClass != null) { val lightDeclarations: List<KtLightMember<*>?> = originLightClass.methods.map { it as? KtLightMethod } + originLightClass.fields.map { it as? KtLightField } for (declaration in element.declarations) { lightDeclarations .firstOrNull { it?.kotlinOrigin == declaration } ?.let(::searchNamedElement) } } } } } private fun searchForComponentConventions(elementPointer: SmartPsiElementPointer<PsiElement>) { ReadAction.nonBlocking(Callable { when (val element = elementPointer.element) { is KtParameter -> { val componentMethodName = element.dataClassComponentMethodName ?: return@Callable val containingClass = element.getStrictParentOfType<KtClassOrObject>()?.toLightClass() ?: return@Callable searchDataClassComponentUsages( containingClass = containingClass, componentMethodName = componentMethodName, kotlinOptions = kotlinOptions ) } is KtLightParameter -> { val componentMethodName = element.kotlinOrigin?.dataClassComponentMethodName ?: return@Callable val containingClass = element.method.containingClass ?: return@Callable searchDataClassComponentUsages( containingClass = containingClass, componentMethodName = componentMethodName, kotlinOptions = kotlinOptions ) } else -> return@Callable } }).executeSynchronously() } @RequiresReadLock private fun searchDataClassComponentUsages( containingClass: KtLightClass, componentMethodName: String, kotlinOptions: KotlinReferencesSearchOptions ) { assertReadAccessAllowed() containingClass.methods.firstOrNull { it.name == componentMethodName && it.parameterList.parametersCount == 0 }?.let { searchNamedElement(it) OperatorReferenceSearcher.create( it, queryParameters.effectiveSearchScope, consumer, queryParameters.optimizer, kotlinOptions )?.let { searcher -> longTasks.add { searcher.run() } } } } @RequiresReadLock private fun processStaticsFromCompanionObject(element: KtDeclaration) { findStaticMethodsFromCompanionObject(element).forEach(::searchNamedElement) } private fun findStaticMethodsFromCompanionObject(declaration: KtDeclaration): List<PsiMethod> { val originObject = declaration.parents .dropWhile { it is KtClassBody } .firstOrNull() as? KtObjectDeclaration ?: return emptyList() if (!originObject.isCompanion()) return emptyList() val originClass = originObject.getStrictParentOfType<KtClass>() val originLightClass = originClass?.toLightClass() ?: return emptyList() val allMethods = originLightClass.allMethods return allMethods.filter { it is KtLightMethod && it.kotlinOrigin == declaration } } @RequiresReadLock private fun searchNamedElement( element: PsiNamedElement?, name: String? = null, modifyScope: ((SearchScope) -> SearchScope)? = null ) { assertReadAccessAllowed() element ?: return val nameToUse = name ?: element.name ?: return val baseScope = queryParameters.effectiveSearchScope(element) val scope = if (modifyScope != null) modifyScope(baseScope) else baseScope val context = UsageSearchContext.IN_CODE + UsageSearchContext.IN_FOREIGN_LANGUAGES + UsageSearchContext.IN_COMMENTS val resultProcessor = KotlinRequestResultProcessor( element, queryParameters.elementToSearch.namedUnwrappedElement ?: element, options = kotlinOptions ) queryParameters.optimizer.searchWord(nameToUse, scope, context.toShort(), true, element, resultProcessor) } private fun assertReadAccessAllowed() { ApplicationManager.getApplication().assertReadAccessAllowed() } private fun PsiReference.isNamedArgumentReference(): Boolean { return this is KtSimpleNameReference && expression.parent is KtValueArgumentName } } }
apache-2.0
a42e61c76bdec72902cc2fe201d1c65a
47.678423
158
0.636491
6.415915
false
false
false
false
benjamin-bader/thrifty
thrifty-schema/src/main/kotlin/com/microsoft/thrifty/schema/parser/ThriftListener.kt
1
27429
/* * Thrifty * * Copyright (c) Microsoft Corporation * * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.schema.parser import com.microsoft.thrifty.schema.ErrorReporter import com.microsoft.thrifty.schema.Location import com.microsoft.thrifty.schema.NamespaceScope import com.microsoft.thrifty.schema.Requiredness import com.microsoft.thrifty.schema.antlr.AntlrThriftBaseListener import com.microsoft.thrifty.schema.antlr.AntlrThriftLexer import com.microsoft.thrifty.schema.antlr.AntlrThriftParser import org.antlr.v4.runtime.CommonTokenStream import org.antlr.v4.runtime.Lexer import org.antlr.v4.runtime.ParserRuleContext import org.antlr.v4.runtime.Token import org.antlr.v4.runtime.tree.ErrorNode import org.antlr.v4.runtime.tree.TerminalNode import java.util.BitSet /** * A set of callbacks that, when used with a [org.antlr.v4.runtime.tree.ParseTreeWalker], * assemble a [ThriftFileElement] from an [AntlrThriftParser]. * * Instances of this class are single-use; after walking a parse tree, it will contain * that parser's state as thrifty-schema parser elements. * * @param tokenStream the same token stream used with the corresponding [AntlrThriftParser]; * this stream will be queried for "hidden" tokens containing parsed doc * comments. * @param errorReporter an error reporting mechanism, used to communicate errors during parsing. * @param location a location pointing at the beginning of the file being parsed. */ internal class ThriftListener( private val tokenStream: CommonTokenStream, private val errorReporter: ErrorReporter, private val location: Location ) : AntlrThriftBaseListener() { // We need to record which comment tokens have been treated as trailing documentation, // so that scanning for leading doc tokens for subsequent elements knows where to stop. // We can do this with a bitset tracking token indices of trailing-comment tokens. private val trailingDocTokenIndexes = BitSet(INITIAL_BITSET_CAPACITY) private val includes = mutableListOf<IncludeElement>() private val namespaces = mutableListOf<NamespaceElement>() private val enums = mutableListOf<EnumElement>() private val typedefs = mutableListOf<TypedefElement>() private val structs = mutableListOf<StructElement>() private val unions = mutableListOf<StructElement>() private val exceptions = mutableListOf<StructElement>() private val consts = mutableListOf<ConstElement>() private val services = mutableListOf<ServiceElement>() fun buildFileElement(): ThriftFileElement { // Default JVM subtypes to the JVM namespace if present namespaces.find { it.scope == NamespaceScope.JVM }?.let { jvmElement -> NamespaceScope.jvmMembers().subtract(namespaces.map { it.scope }).forEach { subType -> namespaces.add(jvmElement.copy(scope = subType)) } } return ThriftFileElement( location = location, includes = includes, namespaces = namespaces, typedefs = typedefs, enums = enums, structs = structs, unions = unions, exceptions = exceptions, constants = consts, services = services ) } override fun exitInclude(ctx: AntlrThriftParser.IncludeContext) { val pathNode = ctx.LITERAL() val path = unquote(locationOf(pathNode), pathNode.text, false) includes.add(IncludeElement(locationOf(ctx), false, path)) } override fun exitCppInclude(ctx: AntlrThriftParser.CppIncludeContext) { val pathNode = ctx.LITERAL() val path = unquote(locationOf(pathNode), pathNode.text, false) includes.add(IncludeElement(locationOf(ctx), true, path)) } override fun exitStandardNamespace(ctx: AntlrThriftParser.StandardNamespaceContext) { val scopeName = ctx.namespaceScope().text val name = ctx.ns.text val annotations = annotationsFromAntlr(ctx.annotationList()) val scope = NamespaceScope.forThriftName(scopeName) if (scope == null) { errorReporter.warn(locationOf(ctx.namespaceScope()), "Unknown namespace scope '$scopeName'") return } val element = NamespaceElement( location = locationOf(ctx), scope = scope, namespace = name, annotations = annotations) namespaces.add(element) } override fun exitPhpNamespace(ctx: AntlrThriftParser.PhpNamespaceContext) { val element = NamespaceElement( locationOf(ctx), scope = NamespaceScope.PHP, namespace = unquote(locationOf(ctx.LITERAL()), ctx.LITERAL().text), annotations = annotationsFromAntlr(ctx.annotationList())) namespaces.add(element) } override fun exitXsdNamespace(ctx: AntlrThriftParser.XsdNamespaceContext) { errorReporter.error(locationOf(ctx), "'xsd_namespace' is unsupported") } override fun exitSenum(ctx: AntlrThriftParser.SenumContext) { errorReporter.error(locationOf(ctx), "'senum' is unsupported; use 'enum' instead") } override fun exitEnumDef(ctx: AntlrThriftParser.EnumDefContext) { val enumName = ctx.IDENTIFIER().text var nextValue = 0 val values = mutableSetOf<Int>() val members = ArrayList<EnumMemberElement>(ctx.enumMember().size) for (memberContext in ctx.enumMember()) { var value = nextValue val valueToken = memberContext.INTEGER() if (valueToken != null) { value = parseInt(valueToken) } if (!values.add(value)) { errorReporter.error(locationOf(memberContext), "duplicate enum value: $value") continue } nextValue = value + 1 val element = EnumMemberElement( location = locationOf(memberContext), name = memberContext.IDENTIFIER().text, value = value, documentation = formatJavadoc(memberContext), annotations = annotationsFromAntlr(memberContext.annotationList())) members.add(element) } val doc = formatJavadoc(ctx) val element = EnumElement( location = locationOf(ctx), name = enumName, documentation = doc, annotations = annotationsFromAntlr(ctx.annotationList()), members = members) enums.add(element) } override fun exitStructDef(ctx: AntlrThriftParser.StructDefContext) { val name = ctx.IDENTIFIER().text val fields = parseFieldList(ctx.field()) val element = StructElement( location = locationOf(ctx), name = name, fields = fields, type = StructElement.Type.STRUCT, documentation = formatJavadoc(ctx), annotations = annotationsFromAntlr(ctx.annotationList())) structs.add(element) } override fun exitUnionDef(ctx: AntlrThriftParser.UnionDefContext) { val name = ctx.IDENTIFIER().text val fields = parseFieldList(ctx.field()) for (i in fields.indices) { val element = fields[i] if (element.requiredness == Requiredness.REQUIRED) { val fieldContext = ctx.field(i) errorReporter.error(locationOf(fieldContext), "unions cannot have required fields") } } val element = StructElement( location = locationOf(ctx), name = name, fields = fields, type = StructElement.Type.UNION, documentation = formatJavadoc(ctx), annotations = annotationsFromAntlr(ctx.annotationList())) unions.add(element) } override fun exitExceptionDef(ctx: AntlrThriftParser.ExceptionDefContext) { val name = ctx.IDENTIFIER().text val fields = parseFieldList(ctx.field()) val element = StructElement( location = locationOf(ctx), name = name, fields = fields, type = StructElement.Type.EXCEPTION, documentation = formatJavadoc(ctx), annotations = annotationsFromAntlr(ctx.annotationList())) exceptions.add(element) } private fun parseFieldList( contexts: List<AntlrThriftParser.FieldContext>, defaultRequiredness: Requiredness = Requiredness.DEFAULT): List<FieldElement> { val fields = mutableListOf<FieldElement>() val ids = mutableSetOf<Int>() var nextValue = 1 for (fieldContext in contexts) { val element = parseField(nextValue, fieldContext, defaultRequiredness) if (element != null) { fields += element if (!ids.add(element.fieldId)) { errorReporter.error(locationOf(fieldContext), "duplicate field ID: ${element.fieldId}") } if (element.fieldId <= 0) { errorReporter.error(locationOf(fieldContext), "field ID must be greater than zero") } if (element.fieldId >= nextValue) { nextValue = element.fieldId + 1 } } else { // assert-fail here? ++nextValue // this represents an error condition } } return fields } private fun parseField( defaultValue: Int, ctx: AntlrThriftParser.FieldContext, defaultRequiredness: Requiredness): FieldElement? { val fieldId = ctx.INTEGER()?.let { parseInt(it) } ?: defaultValue val fieldName = ctx.IDENTIFIER().text val requiredness = if (ctx.requiredness() != null) { when { ctx.requiredness().text == "required" -> Requiredness.REQUIRED ctx.requiredness().text == "optional" -> Requiredness.OPTIONAL else -> throw AssertionError("Unexpected requiredness value: " + ctx.requiredness().text) } } else { defaultRequiredness } return FieldElement( location = locationOf(ctx), documentation = formatJavadoc(ctx), fieldId = fieldId, requiredness = requiredness, type = typeElementOf(ctx.fieldType()), name = fieldName, annotations = annotationsFromAntlr(ctx.annotationList()), constValue = constValueElementOf(ctx.constValue())) } override fun exitTypedef(ctx: AntlrThriftParser.TypedefContext) { val oldType = typeElementOf(ctx.fieldType()) val typedef = TypedefElement( location = locationOf(ctx), documentation = formatJavadoc(ctx), annotations = annotationsFromAntlr(ctx.annotationList()), oldType = oldType, newName = ctx.IDENTIFIER().text) typedefs.add(typedef) } override fun exitConstDef(ctx: AntlrThriftParser.ConstDefContext) { val constValue = constValueElementOf(ctx.constValue()) if (constValue == null) { errorReporter.error( locationOf(ctx.constValue()), "Invalid const value") return } val element = ConstElement( location = locationOf(ctx), documentation = formatJavadoc(ctx), type = typeElementOf(ctx.fieldType()), name = ctx.IDENTIFIER().text, value = constValue) consts.add(element) } override fun exitServiceDef(ctx: AntlrThriftParser.ServiceDefContext) { val name = ctx.name.text val extendsService = if (ctx.superType != null) { val superType = typeElementOf(ctx.superType) if (superType !is ScalarTypeElement) { errorReporter.error(locationOf(ctx), "services cannot extend collections") return } superType } else { null } val service = ServiceElement( location = locationOf(ctx), name = name, functions = parseFunctionList(ctx.function()), extendsService = extendsService, documentation = formatJavadoc(ctx), annotations = annotationsFromAntlr(ctx.annotationList()) ) services.add(service) } private fun parseFunctionList(functionContexts: List<AntlrThriftParser.FunctionContext>): List<FunctionElement> { val functions = mutableListOf<FunctionElement>() for (ctx in functionContexts) { val name = ctx.IDENTIFIER().text val returnType = if (ctx.fieldType() != null) { typeElementOf(ctx.fieldType()) } else { val token = ctx.getToken(AntlrThriftLexer.VOID, 0) ?: throw AssertionError("Function has no return type, and no VOID token - grammar error") val loc = locationOf(token) // Do people actually annotate 'void'? We'll find out! ScalarTypeElement(loc, "void", null) } val isOneway = ctx.ONEWAY() != null val maybeThrowsList = ctx.throwsList()?.let { parseFieldList(it.fieldList().field()) } val function = FunctionElement( location = locationOf(ctx), oneWay = isOneway, returnType = returnType, name = name, documentation = formatJavadoc(ctx), annotations = annotationsFromAntlr(ctx.annotationList()), params = parseFieldList(ctx.fieldList().field(), Requiredness.REQUIRED), exceptions = maybeThrowsList ?: emptyList() ) functions += function } return functions } // region Utilities private fun annotationsFromAntlr(ctx: AntlrThriftParser.AnnotationListContext?): AnnotationElement? { if (ctx == null) { return null } val annotations = mutableMapOf<String, String>() for (annotationContext in ctx.annotation()) { val name = annotationContext.IDENTIFIER().text annotations[name] = if (annotationContext.LITERAL() != null) { unquote(locationOf(annotationContext.LITERAL()), annotationContext.LITERAL().text) } else { "true" } } return AnnotationElement(locationOf(ctx), annotations) } private fun locationOf(ctx: ParserRuleContext): Location { return locationOf(ctx.getStart()) } private fun locationOf(node: TerminalNode): Location { return locationOf(node.symbol) } private fun locationOf(token: Token): Location { val line = token.line val col = token.charPositionInLine + 1 // Location.col is 1-based, Token.col is 0-based return location.at(line, col) } private fun unquote(location: Location, literal: String, processEscapes: Boolean = true): String { val chars = literal.toCharArray() val startChar = chars[0] val endChar = chars[chars.size - 1] if (startChar != endChar || startChar != '\'' && startChar != '"') { throw AssertionError("Incorrect UNESCAPED_LITERAL rule: $literal") } val sb = StringBuilder(literal.length - 2) var i = 1 val end = chars.size - 1 while (i < end) { val c = chars[i++] if (processEscapes && c == '\\') { if (i == end) { errorReporter.error(location, "Unterminated literal") break } val escape = chars[i++] when (escape) { 'a' -> sb.append(0x7.toChar()) 'b' -> sb.append('\b') 'f' -> sb.append('\u000C') 'n' -> sb.append('\n') 'r' -> sb.append('\r') 't' -> sb.append('\t') 'v' -> sb.append(0xB.toChar()) '\\' -> sb.append('\\') 'u' -> throw UnsupportedOperationException("unicode escapes not yet implemented") else -> if (escape == startChar) { sb.append(startChar) } else { errorReporter.error(location, "invalid escape character: $escape") } } } else { sb.append(c) } } return sb.toString() } private fun typeElementOf(context: AntlrThriftParser.FieldTypeContext): TypeElement { if (context.baseType() != null) { if (context.baseType().text == "slist") { errorReporter.error(locationOf(context), "slist is unsupported; use list<string> instead") } return ScalarTypeElement( locationOf(context), context.baseType().text, annotationsFromAntlr(context.annotationList())) } if (context.IDENTIFIER() != null) { return ScalarTypeElement( locationOf(context), context.IDENTIFIER().text, annotationsFromAntlr(context.annotationList())) } if (context.containerType() != null) { val containerContext = context.containerType() if (containerContext.mapType() != null) { val keyType = typeElementOf(containerContext.mapType().key) val valueType = typeElementOf(containerContext.mapType().value) return MapTypeElement( locationOf(containerContext.mapType()), keyType, valueType, annotationsFromAntlr(context.annotationList())) } if (containerContext.setType() != null) { return SetTypeElement( locationOf(containerContext.setType()), typeElementOf(containerContext.setType().fieldType()), annotationsFromAntlr(context.annotationList())) } if (containerContext.listType() != null) { return ListTypeElement( locationOf(containerContext.listType()), typeElementOf(containerContext.listType().fieldType()), annotationsFromAntlr(context.annotationList())) } throw AssertionError("Unexpected container type - grammar error!") } throw AssertionError("Unexpected type - grammar error!") } private fun constValueElementOf(ctx: AntlrThriftParser.ConstValueContext?): ConstValueElement? { if (ctx == null) { return null } if (ctx.INTEGER() != null) { try { val value = parseLong(ctx.INTEGER()) return IntValueElement(locationOf(ctx), ctx.INTEGER().text, value) } catch (e: NumberFormatException) { throw AssertionError("Invalid integer accepted by ANTLR grammar: " + ctx.INTEGER().text) } } if (ctx.DOUBLE() != null) { val text = ctx.DOUBLE().text try { val value = java.lang.Double.parseDouble(text) return DoubleValueElement(locationOf(ctx), ctx.DOUBLE().text, value) } catch (e: NumberFormatException) { throw AssertionError("Invalid double accepted by ANTLR grammar: $text") } } if (ctx.LITERAL() != null) { val text = unquote(locationOf(ctx.LITERAL() as TerminalNode), ctx.LITERAL().text) return LiteralValueElement(locationOf(ctx), ctx.LITERAL().text, text) } if (ctx.IDENTIFIER() != null) { val id = ctx.IDENTIFIER().text return IdentifierValueElement(locationOf(ctx), ctx.IDENTIFIER().text, id) } if (ctx.constList() != null) { val values = mutableListOf<ConstValueElement>() for (valueContext in ctx.constList().constValue()) { values.add(constValueElementOf(valueContext)!!) } return ListValueElement(locationOf(ctx), ctx.constList().text, values) } if (ctx.constMap() != null) { val values = mutableMapOf<ConstValueElement, ConstValueElement>() for (entry in ctx.constMap().constMapEntry()) { val key = constValueElementOf(entry.key) val value = constValueElementOf(entry.value) values.put(key!!, value!!) } return MapValueElement(locationOf(ctx), ctx.constMap().text, values) } throw AssertionError("unreachable") } private fun formatJavadoc(context: ParserRuleContext): String { return formatJavadoc( getLeadingComments(context.getStart()) + getTrailingComments(context.getStop())) } private fun getLeadingComments(token: Token): List<Token> { val hiddenTokens = tokenStream.getHiddenTokensToLeft(token.tokenIndex, Lexer.HIDDEN) return hiddenTokens?.filter { it.isComment && !trailingDocTokenIndexes.get(it.tokenIndex) } ?: emptyList() } /** * Read comments following the given token, until the first newline is encountered. * * INVARIANT: * Assumes that the parse tree is being walked top-down, left to right! * * Trailing-doc tokens are marked as such, so that subsequent searches for "leading" * doc don't grab tokens already used as "trailing" doc. If the walk order is *not* * top-down, left-to-right, then the assumption underpinning the separation of leading * and trailing comments is broken. * * @param endToken the token from which to search for trailing comment tokens. * @return a list, possibly empty, of all trailing comment tokens. */ private fun getTrailingComments(endToken: Token): List<Token> { val hiddenTokens = tokenStream.getHiddenTokensToRight(endToken.tokenIndex, Lexer.HIDDEN) if (hiddenTokens != null && hiddenTokens.isNotEmpty()) { val maybeTrailingDoc = hiddenTokens.first() // only one trailing comment is possible if (maybeTrailingDoc.isComment) { trailingDocTokenIndexes.set(maybeTrailingDoc.tokenIndex) return listOf<Token>(maybeTrailingDoc) } } return emptyList() } companion object { // A number of tokens that should comfortably accommodate most input files // without wildly re-allocating. Estimated based on the ClientTestThrift // and TestThrift files, which contain around ~1200 tokens each. private const val INITIAL_BITSET_CAPACITY = 2048 } // endregion } private val Token.isComment: Boolean get() { return when (this.type) { AntlrThriftLexer.SLASH_SLASH_COMMENT, AntlrThriftLexer.HASH_COMMENT, AntlrThriftLexer.MULTILINE_COMMENT -> true else -> false } } private fun formatJavadoc(commentTokens: List<Token>): String { val sb = StringBuilder() for (token in commentTokens) { val text = token.text when (token.type) { AntlrThriftLexer.SLASH_SLASH_COMMENT -> formatSingleLineComment(sb, text, "//") AntlrThriftLexer.HASH_COMMENT -> formatSingleLineComment(sb, text, "#") AntlrThriftLexer.MULTILINE_COMMENT -> formatMultilineComment(sb, text) else -> { // wat val symbolicName = AntlrThriftParser.VOCABULARY.getSymbolicName(token.type) val literalName = AntlrThriftParser.VOCABULARY.getLiteralName(token.type) val tokenNumber = "${token.type}" error("Unexpected comment-token type: ${symbolicName ?: literalName ?: tokenNumber}") } } } return sb.toString().trim { it <= ' ' }.let { doc -> if (doc.isNotEmpty() && !doc.endsWith("\n")) { doc + "\n" } else { doc } } } private fun formatSingleLineComment(sb: StringBuilder, text: String, prefix: String) { var start = prefix.length var end = text.length while (start < end && Character.isWhitespace(text[start])) { ++start } while (end > start && Character.isWhitespace(text[end - 1])) { --end } if (start != end) { sb.append(text.substring(start, end)) } sb.append("\n") } private fun formatMultilineComment(sb: StringBuilder, text: String) { val chars = text.toCharArray() var pos = "/*".length val length = chars.size var isStartOfLine = true while (pos + 1 < length) { val c = chars[pos] if (c == '*' && chars[pos + 1] == '/') { sb.append("\n") return } if (c == '\n') { sb.append(c) isStartOfLine = true } else if (!isStartOfLine) { sb.append(c) } else if (c == '*') { // skip a single subsequent space, if it exists if (chars[pos + 1] == ' ') { pos += 1 } isStartOfLine = false } else if (!Character.isWhitespace(c)) { sb.append(c) isStartOfLine = false } ++pos } } private fun parseInt(node: TerminalNode): Int { return parseInt(node.symbol) } private fun parseInt(token: Token): Int { var text = token.text var radix = 10 if (text.startsWith("0x") || text.startsWith("0X")) { radix = 16 text = text.substring(2) } return Integer.parseInt(text, radix) } private fun parseLong(node: TerminalNode): Long = parseLong(node.symbol) private fun parseLong(token: Token): Long { val text: String val radix: Int if (token.text.startsWith("0x", ignoreCase = true)) { text = token.text.substring(2) radix = 16 } else { text = token.text radix = 10 } return java.lang.Long.parseLong(text, radix) }
apache-2.0
80356a6968719396c579ae042aa88134
34.483829
117
0.587991
4.870206
false
false
false
false
JetBrains/teamcity-nuget-support
nuget-agent/src/jetbrains/buildServer/nuget/agent/index/NugetPackageIndexer.kt
1
4466
package jetbrains.buildServer.nuget.agent.index import com.intellij.openapi.diagnostic.Logger import jetbrains.buildServer.agent.* import jetbrains.buildServer.agent.impl.artifacts.ArtifactsBuilderAdapter import jetbrains.buildServer.agent.impl.artifacts.ArtifactsCollection import jetbrains.buildServer.nuget.common.FeedConstants import jetbrains.buildServer.nuget.common.NuGetServerConstants import jetbrains.buildServer.nuget.common.index.NuGetPackageData import jetbrains.buildServer.nuget.common.index.ODataDataFormat import jetbrains.buildServer.nuget.common.index.PackageAnalyzer import jetbrains.buildServer.nuget.common.index.PackageConstants.TEAMCITY_ARTIFACT_RELPATH import jetbrains.buildServer.nuget.common.index.PackageConstants.TEAMCITY_BUILD_TYPE_ID import jetbrains.buildServer.nuget.feedReader.NuGetPackageAttributes.* import jetbrains.buildServer.util.EventDispatcher import java.io.File import java.util.* class NugetPackageIndexer(dispatcher: EventDispatcher<AgentLifeCycleListener>, private val packageAnalyzer: PackageAnalyzer, private val packagePublisher: NuGetPackagePublisher, private val pathProvider: NuGetPackagePathProvider) : ArtifactsBuilderAdapter() { private var myIndexingEnabled = false private val myPackages = arrayListOf<NuGetPackageData>() private lateinit var myBuildType: String private lateinit var myLogger: BuildProgressLogger init { dispatcher.addListener(object : AgentLifeCycleAdapter() { override fun buildStarted(runningBuild: AgentRunningBuild) { myPackages.clear() myIndexingEnabled = runningBuild.sharedConfigParameters[NuGetServerConstants.FEED_AGENT_SIDE_INDEXING]?.toBoolean() ?: false myBuildType = runningBuild.buildTypeId myLogger = runningBuild.buildLogger } override fun afterAtrifactsPublished(runningBuild: AgentRunningBuild, status: BuildFinishedStatus) { try { packagePublisher.publishPackages(myPackages) } catch (e: Exception) { val message = "Failed to write NuGet packages metadata" myLogger.warning("$message: ${e.message}") LOG.warnAndDebugDetails(message, e) } } }) } override fun afterCollectingFiles(artifacts: MutableList<ArtifactsCollection>) { if (!myIndexingEnabled) { return } getPackages(artifacts).forEach { (file, path) -> pathProvider.getArtifactPath(path, file.name)?.let { packagePath -> try { val metadata = readMetadata(file, packagePath) myPackages.add(NuGetPackageData(packagePath, metadata)) } catch (e: Exception) { val message = "Failed to read NuGet package $packagePath contents" myLogger.warning("$message: ${e.message}") LOG.warnAndDebugDetails(message, e) } } } } private fun readMetadata(file: File, packagePath: String): MutableMap<String, String> { val metadata = file.inputStream().use { packageAnalyzer.analyzePackage(it) } file.inputStream().use { metadata[PACKAGE_HASH] = packageAnalyzer.getSha512Hash(it) metadata[PACKAGE_HASH_ALGORITHM] = PackageAnalyzer.SHA512 } val created = ODataDataFormat.formatDate(Date()) metadata[CREATED] = created metadata[LAST_UPDATED] = created metadata[PUBLISHED] = created metadata[PACKAGE_SIZE] = file.length().toString() metadata[TEAMCITY_ARTIFACT_RELPATH] = packagePath metadata[TEAMCITY_BUILD_TYPE_ID] = myBuildType return metadata } private fun getPackages(artifactsCollections: List<ArtifactsCollection>): Map<File, String> { val result = HashMap<File, String>() artifactsCollections.forEach { it.filePathMap.forEach { (artifact, path) -> if (FeedConstants.PACKAGE_FILE_NAME_FILTER.accept(artifact.path)) { result[artifact] = path } } } return result } companion object { private val LOG = Logger.getInstance(NugetPackageIndexer::class.java.name) } }
apache-2.0
caa4a48c68341890e0e8e7f9d88e1214
41.132075
140
0.661666
4.984375
false
false
false
false
vickychijwani/kotlin-koans-android
app/src/main/code/me/vickychijwani/kotlinkoans/util/dom_utils.kt
1
1317
package me.vickychijwani.kotlinkoans.util import org.w3c.dom.NamedNodeMap import org.w3c.dom.Node import org.w3c.dom.NodeList import java.io.StringWriter class NodeIterator(val nodeList: NodeList) : Iterator<Node> { var current = -1 override fun hasNext() = (current+1) < nodeList.length override fun next(): Node = nodeList.item(++current) } operator fun NodeList.iterator() = NodeIterator(this) class AttributeIterator(val namedNodeMap: NamedNodeMap) : Iterator<Node> { var current = -1 override fun hasNext() = (current+1) < namedNodeMap.length override fun next(): Node = namedNodeMap.item(++current) } operator fun NamedNodeMap.iterator() = AttributeIterator(this) val Node.outerHTML: String get() { return when (nodeName) { "#comment", "#text" -> nodeValue else -> { val html = StringWriter() html.append("<$nodeName") for (attr in attributes) { html.append(" ${attr.nodeName}=\"${attr.nodeValue}\"") } html.append(">") for (child in childNodes) { html.append(child.outerHTML) } html.append("</$nodeName>") return html.toString() } } }
mit
45e6c2fe8b289999c674e83942882c6f
29.627907
74
0.583144
4.234727
false
false
false
false
GunoH/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/ResizeController.kt
2
3511
package org.jetbrains.plugins.notebooks.visualization.r.inlays import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.impl.FontInfo import com.intellij.openapi.editor.impl.view.EditorPainter import com.intellij.openapi.editor.impl.view.FontLayoutService import com.intellij.util.ui.JBUI import java.awt.Component import java.awt.Cursor import java.awt.Dimension import java.awt.Point import java.awt.event.MouseEvent import java.awt.event.MouseListener import java.awt.event.MouseMotionListener import javax.swing.SwingUtilities import kotlin.math.abs /** Realizes resize of InlayComponent by dragging resize icon in right bottom corner of component. */ class ResizeController( private val component: Component, private val editor: Editor, private val deltaSize: (dx: Int, dy: Int) -> Unit = component::swingDeltaSize, ) : MouseListener, MouseMotionListener { private var prevPoint: Point? = null private enum class ScaleMode { NONE, N /*, W, NW*/ } private var scaleMode = ScaleMode.NONE private val nResizeCursor = Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR) private val defaultCursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR) private fun setCursor(cursor: Cursor) { if (component.cursor != cursor) { component.cursor = cursor } } override fun mouseReleased(e: MouseEvent?) { // Snapping to right margin. if (EditorPainter.isMarginShown(editor) && prevPoint != null) { val font = editor.colorsScheme.getFont(EditorFontType.PLAIN) val context = FontInfo.getFontRenderContext(editor.contentComponent) val fm = FontInfo.getFontMetrics(font, context) val width = FontLayoutService.getInstance().charWidth2D(fm, ' '.code) val rightMargin = editor.settings.getRightMargin(editor.project) * width SwingUtilities.convertPointFromScreen(prevPoint!!, editor.contentComponent) if (abs(prevPoint!!.x - rightMargin) < JBUI.scale(40)) { deltaSize(rightMargin.toInt() - prevPoint!!.x, 0) SwingUtilities.invokeLater { component.revalidate() component.repaint() } } } prevPoint = null scaleMode = ScaleMode.NONE } override fun mousePressed(e: MouseEvent) { val correctedHeight = component.height - InlayDimensions.bottomBorder scaleMode = if (e.point.y > correctedHeight) { ScaleMode.N } else { return } prevPoint = e.locationOnScreen } override fun mouseDragged(e: MouseEvent?) { if (prevPoint == null) { return } val locationOnScreen = e!!.locationOnScreen val dy = if (scaleMode == ScaleMode.N) locationOnScreen.y - prevPoint!!.y else 0 deltaSize(0, dy) prevPoint = locationOnScreen } override fun mouseMoved(e: MouseEvent) { if (scaleMode != ScaleMode.NONE) { return } val correctedHeight = component.height - InlayDimensions.bottomBorder setCursor(if (e.point.y > correctedHeight) nResizeCursor else defaultCursor) } override fun mouseExited(e: MouseEvent) { if (scaleMode == ScaleMode.NONE) { setCursor(defaultCursor) } } override fun mouseClicked(e: MouseEvent): Unit = Unit override fun mouseEntered(e: MouseEvent): Unit = Unit } private fun Component.swingDeltaSize(dx: Int, dy: Int) { val oldSize = size size = Dimension(oldSize.width + dx, oldSize.height + dy) preferredSize = size revalidate() repaint() }
apache-2.0
699cf7c7ccf1dfbc53744a8b2b8966b3
27.322581
101
0.718599
4.14033
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/KotlinLineMarkerProvider.kt
3
23091
// 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.highlighter.markers import com.intellij.codeInsight.daemon.* import com.intellij.codeInsight.daemon.impl.LineMarkerNavigator import com.intellij.codeInsight.daemon.impl.MarkerType import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator import com.intellij.codeInsight.navigation.BackgroundUpdaterTask import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.colors.CodeInsightColors import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.openapi.editor.markup.SeparatorPlacement import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.DumbService import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.psi.search.searches.ClassInheritorsSearch import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.asJava.classes.KtFakeLightMethod import org.jetbrains.kotlin.asJava.toFakeLightClass import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter import org.jetbrains.kotlin.idea.base.projectStructure.matches import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.core.isInheritable import org.jetbrains.kotlin.idea.core.isOverridable import org.jetbrains.kotlin.idea.editor.fixers.startLine import org.jetbrains.kotlin.idea.search.declarationsSearch.toPossiblyFakeLightMethods import org.jetbrains.kotlin.idea.util.hasAtLeastOneActual import org.jetbrains.kotlin.idea.util.hasMatchingExpected import org.jetbrains.kotlin.idea.util.isEffectivelyActual import org.jetbrains.kotlin.idea.util.isExpectDeclaration import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments import java.awt.event.MouseEvent import javax.swing.ListCellRenderer class KotlinLineMarkerProvider : LineMarkerProviderDescriptor() { override fun getName() = KotlinBundle.message("highlighter.name.kotlin.line.markers") override fun getOptions(): Array<Option> = KotlinLineMarkerOptions.options override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<PsiElement>? { if (DaemonCodeAnalyzerSettings.getInstance().SHOW_METHOD_SEPARATORS) { if (element.canHaveSeparator()) { val prevSibling = element.getPrevSiblingIgnoringWhitespaceAndComments() if (prevSibling.canHaveSeparator() && (element.wantsSeparator() || prevSibling?.wantsSeparator() == true) ) { return createLineSeparatorByElement(element) } } } return null } private fun PsiElement?.canHaveSeparator() = this is KtFunction || this is KtClassInitializer || (this is KtProperty && !isLocal) || ((this is KtObjectDeclaration && this.isCompanion())) private fun PsiElement.wantsSeparator() = this is KtFunction || StringUtil.getLineBreakCount(text) > 0 private fun createLineSeparatorByElement(element: PsiElement): LineMarkerInfo<PsiElement> { val anchor = PsiTreeUtil.getDeepestFirst(element) val info = LineMarkerInfo(anchor, anchor.textRange) info.separatorColor = EditorColorsManager.getInstance().globalScheme.getColor(CodeInsightColors.METHOD_SEPARATORS_COLOR) info.separatorPlacement = SeparatorPlacement.TOP return info } override fun collectSlowLineMarkers(elements: List<PsiElement>, result: LineMarkerInfos) { if (elements.isEmpty()) return if (KotlinLineMarkerOptions.options.none { option -> option.isEnabled }) return val first = elements.first() if (DumbService.getInstance(first.project).isDumb || !RootKindFilter.projectAndLibrarySources.matches(first)) return val functions = hashSetOf<KtNamedFunction>() val properties = hashSetOf<KtNamedDeclaration>() val declarations = hashSetOf<KtNamedDeclaration>() for (leaf in elements) { ProgressManager.checkCanceled() if (leaf !is PsiIdentifier && leaf.firstChild != null) continue val element = leaf.parent as? KtNamedDeclaration ?: continue if (!declarations.add(element)) continue when (element) { is KtClass -> { collectInheritedClassMarker(element, result) collectHighlightingColorsMarkers(element, result) } is KtNamedFunction -> { functions.add(element) collectSuperDeclarationMarkers(element, result) } is KtProperty -> { properties.add(element) collectSuperDeclarationMarkers(element, result) } is KtParameter -> { if (element.hasValOrVar()) { properties.add(element) collectSuperDeclarationMarkers(element, result) } } } collectMultiplatformMarkers(element, result) } collectOverriddenFunctions(functions, result) collectOverriddenPropertyAccessors(properties, result) } } data class NavigationPopupDescriptor( val targets: Collection<NavigatablePsiElement>, @NlsContexts.PopupTitle val title: String, @NlsContexts.TabTitle val findUsagesTitle: String, val renderer: ListCellRenderer<in NavigatablePsiElement>, val updater: BackgroundUpdaterTask? = null ) { fun showPopup(e: MouseEvent) { PsiElementListNavigator.openTargets(e, targets.toTypedArray(), title, findUsagesTitle, renderer, updater) } } interface TestableLineMarkerNavigator { fun getTargetsPopupDescriptor(element: PsiElement?): NavigationPopupDescriptor? } val SUBCLASSED_CLASS = object : MarkerType( "SUBCLASSED_CLASS", { getPsiClass(it)?.let(::getModuleSpecificSubclassedClassTooltip) }, object : LineMarkerNavigator() { override fun browse(e: MouseEvent, element: PsiElement?) { buildNavigateToClassInheritorsPopup(e, element)?.showPopup(e) } }) { override fun getNavigationHandler(): GutterIconNavigationHandler<PsiElement> { val superHandler = super.getNavigationHandler() return object : GutterIconNavigationHandler<PsiElement>, TestableLineMarkerNavigator { override fun navigate(e: MouseEvent?, elt: PsiElement?) { superHandler.navigate(e, elt) } override fun getTargetsPopupDescriptor(element: PsiElement?) = buildNavigateToClassInheritorsPopup(null, element) } } } val OVERRIDDEN_FUNCTION = object : MarkerType( "OVERRIDDEN_FUNCTION", { getPsiMethod(it)?.let(::getOverriddenMethodTooltip) }, object : LineMarkerNavigator() { override fun browse(e: MouseEvent?, element: PsiElement?) { e?.let { buildNavigateToOverriddenMethodPopup(e, element)?.showPopup(e) } } }) { override fun getNavigationHandler(): GutterIconNavigationHandler<PsiElement> { val superHandler = super.getNavigationHandler() return object : GutterIconNavigationHandler<PsiElement>, TestableLineMarkerNavigator { override fun navigate(e: MouseEvent?, elt: PsiElement?) { superHandler.navigate(e, elt) } override fun getTargetsPopupDescriptor(element: PsiElement?) = buildNavigateToOverriddenMethodPopup(null, element) } } } val OVERRIDDEN_PROPERTY = object : MarkerType( "OVERRIDDEN_PROPERTY", { it?.let { getOverriddenPropertyTooltip(it.parent as KtNamedDeclaration) } }, object : LineMarkerNavigator() { override fun browse(e: MouseEvent?, element: PsiElement?) { e?.let { buildNavigateToPropertyOverriddenDeclarationsPopup(e, element)?.showPopup(e) } } }) { override fun getNavigationHandler(): GutterIconNavigationHandler<PsiElement> { val superHandler = super.getNavigationHandler() return object : GutterIconNavigationHandler<PsiElement>, TestableLineMarkerNavigator { override fun navigate(e: MouseEvent?, elt: PsiElement?) { superHandler.navigate(e, elt) } override fun getTargetsPopupDescriptor(element: PsiElement?) = buildNavigateToPropertyOverriddenDeclarationsPopup(null, element) } } } val PsiElement.markerDeclaration get() = (this as? KtDeclaration) ?: (parent as? KtDeclaration) private val PLATFORM_ACTUAL = object : MarkerType( "PLATFORM_ACTUAL", { element -> element?.markerDeclaration?.let { getPlatformActualTooltip(it) } }, object : LineMarkerNavigator() { override fun browse(e: MouseEvent?, element: PsiElement?) { e?.let { buildNavigateToActualDeclarationsPopup(element)?.showPopup(e) } } }) { override fun getNavigationHandler(): GutterIconNavigationHandler<PsiElement> { val superHandler = super.getNavigationHandler() return object : GutterIconNavigationHandler<PsiElement>, TestableLineMarkerNavigator { override fun navigate(e: MouseEvent?, elt: PsiElement?) { superHandler.navigate(e, elt) } override fun getTargetsPopupDescriptor(element: PsiElement?): NavigationPopupDescriptor? { return buildNavigateToActualDeclarationsPopup(element) } } } } private val EXPECTED_DECLARATION = object : MarkerType( "EXPECTED_DECLARATION", { element -> element?.markerDeclaration?.let { getExpectedDeclarationTooltip(it) } }, object : LineMarkerNavigator() { override fun browse(e: MouseEvent?, element: PsiElement?) { e?.let { buildNavigateToExpectedDeclarationsPopup(element)?.showPopup(e) } } }) { override fun getNavigationHandler(): GutterIconNavigationHandler<PsiElement> { val superHandler = super.getNavigationHandler() return object : GutterIconNavigationHandler<PsiElement>, TestableLineMarkerNavigator { override fun navigate(e: MouseEvent?, elt: PsiElement?) { superHandler.navigate(e, elt) } override fun getTargetsPopupDescriptor(element: PsiElement?): NavigationPopupDescriptor? { return buildNavigateToExpectedDeclarationsPopup(element) } } } } private fun isImplementsAndNotOverrides( descriptor: CallableMemberDescriptor, overriddenMembers: Collection<CallableMemberDescriptor> ): Boolean = descriptor.modality != Modality.ABSTRACT && overriddenMembers.all { it.modality == Modality.ABSTRACT } private fun collectSuperDeclarationMarkers(declaration: KtDeclaration, result: LineMarkerInfos) { if (!(KotlinLineMarkerOptions.implementingOption.isEnabled || KotlinLineMarkerOptions.overridingOption.isEnabled)) return assert(declaration is KtNamedFunction || declaration is KtProperty || declaration is KtParameter) declaration as KtNamedDeclaration // implied by assert if (!declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return val resolveWithParents = resolveDeclarationWithParents(declaration) if (resolveWithParents.overriddenDescriptors.isEmpty()) return val implements = isImplementsAndNotOverrides(resolveWithParents.descriptor!!, resolveWithParents.overriddenDescriptors) val anchor = declaration.nameAnchor() // NOTE: Don't store descriptors in line markers because line markers are not deleted while editing other files and this can prevent // clearing the whole BindingTrace. val gutter = if (implements) KotlinLineMarkerOptions.implementingOption else KotlinLineMarkerOptions.overridingOption val lineMarkerInfo = LineMarkerInfo( anchor, anchor.textRange, gutter.icon!!, SuperDeclarationMarkerTooltip, SuperDeclarationMarkerNavigationHandler(), GutterIconRenderer.Alignment.RIGHT, ) { gutter.name } NavigateAction.setNavigateAction( lineMarkerInfo, if (declaration is KtNamedFunction) KotlinBundle.message("highlighter.action.text.go.to.super.method") else KotlinBundle.message("highlighter.action.text.go.to.super.property"), IdeActions.ACTION_GOTO_SUPER ) result.add(lineMarkerInfo) } private fun collectInheritedClassMarker(element: KtClass, result: LineMarkerInfos) { if (!(KotlinLineMarkerOptions.implementedOption.isEnabled || KotlinLineMarkerOptions.overriddenOption.isEnabled)) return if (!element.isInheritable()) { return } val lightClass = element.toLightClass() ?: element.toFakeLightClass() if (ClassInheritorsSearch.search(lightClass, false).findFirst() == null) return val anchor = element.nameIdentifier ?: element val gutter = if (element.isInterface()) KotlinLineMarkerOptions.implementedOption else KotlinLineMarkerOptions.overriddenOption val icon = gutter.icon ?: return val lineMarkerInfo = OverriddenMergeableLineMarkerInfo( anchor, anchor.textRange, icon, SUBCLASSED_CLASS.tooltip, SUBCLASSED_CLASS.navigationHandler, GutterIconRenderer.Alignment.RIGHT ) { gutter.name } NavigateAction.setNavigateAction( lineMarkerInfo, if (element.isInterface()) KotlinBundle.message("highlighter.action.text.go.to.implementations") else KotlinBundle.message("highlighter.action.text.go.to.subclasses"), IdeActions.ACTION_GOTO_IMPLEMENTATION ) result.add(lineMarkerInfo) } private fun collectOverriddenPropertyAccessors( properties: Collection<KtNamedDeclaration>, result: LineMarkerInfos ) { if (!(KotlinLineMarkerOptions.implementedOption.isEnabled || KotlinLineMarkerOptions.overriddenOption.isEnabled)) return val mappingToJava = HashMap<PsiElement, KtNamedDeclaration>() for (property in properties) { if (property.isOverridable()) { property.toPossiblyFakeLightMethods().forEach { mappingToJava[it] = property } mappingToJava[property] = property } } val classes = collectContainingClasses(mappingToJava.keys.filterIsInstance<PsiMethod>()) for (property in getOverriddenDeclarations(mappingToJava, classes)) { ProgressManager.checkCanceled() val anchor = (property as? PsiNameIdentifierOwner)?.nameIdentifier ?: property val gutter = if (isImplemented(property)) KotlinLineMarkerOptions.implementedOption else KotlinLineMarkerOptions.overriddenOption val lineMarkerInfo = OverriddenMergeableLineMarkerInfo( anchor, anchor.textRange, gutter.icon!!, OVERRIDDEN_PROPERTY.tooltip, OVERRIDDEN_PROPERTY.navigationHandler, GutterIconRenderer.Alignment.RIGHT, ) { gutter.name } NavigateAction.setNavigateAction( lineMarkerInfo, KotlinBundle.message("highlighter.action.text.go.to.overridden.properties"), IdeActions.ACTION_GOTO_IMPLEMENTATION ) result.add(lineMarkerInfo) } } private val KtNamedDeclaration.expectOrActualAnchor get() = nameIdentifier ?: when (this) { is KtConstructor<*> -> getConstructorKeyword() ?: valueParameterList?.leftParenthesis is KtObjectDeclaration -> getObjectKeyword() else -> null } ?: this private fun collectMultiplatformMarkers( declaration: KtNamedDeclaration, result: LineMarkerInfos ) { if (KotlinLineMarkerOptions.actualOption.isEnabled) { if (declaration.isExpectDeclaration()) { collectActualMarkers(declaration, result) return } } if (KotlinLineMarkerOptions.expectOption.isEnabled) { if (!declaration.isExpectDeclaration() && declaration.isEffectivelyActual()) { collectExpectedMarkers(declaration, result) return } } } private fun Document.areAnchorsOnOneLine( first: KtNamedDeclaration, second: KtNamedDeclaration? ): Boolean { if (second == null) return false val firstAnchor = first.expectOrActualAnchor val secondAnchor = second.expectOrActualAnchor return firstAnchor.startLine(this) == secondAnchor.startLine(this) } private fun KtNamedDeclaration.requiresNoMarkers( document: Document? = PsiDocumentManager.getInstance(project).getDocument(containingFile) ): Boolean { when (this) { is KtPrimaryConstructor -> return true is KtParameter, is KtEnumEntry -> { if (document?.areAnchorsOnOneLine(this, containingClassOrObject) == true) { return true } if (this is KtEnumEntry) { val enumEntries = containingClassOrObject?.body?.enumEntries.orEmpty() val previousEnumEntry = enumEntries.getOrNull(enumEntries.indexOf(this) - 1) if (document?.areAnchorsOnOneLine(this, previousEnumEntry) == true) { return true } } if (this is KtParameter && hasValOrVar()) { val parameters = containingClassOrObject?.primaryConstructorParameters.orEmpty() val previousParameter = parameters.getOrNull(parameters.indexOf(this) - 1) if (document?.areAnchorsOnOneLine(this, previousParameter) == true) { return true } } } } return false } internal fun KtDeclaration.findMarkerBoundDeclarations(): Sequence<KtNamedDeclaration> { if (this !is KtClass && this !is KtParameter) return emptySequence() val document = PsiDocumentManager.getInstance(project).getDocument(containingFile) fun <T : KtNamedDeclaration> Sequence<T>.takeBound(bound: KtNamedDeclaration) = takeWhile { document?.areAnchorsOnOneLine(bound, it) == true } return when (this) { is KtParameter -> { val propertyParameters = takeIf { hasValOrVar() }?.containingClassOrObject ?.primaryConstructorParameters ?: return emptySequence() propertyParameters.asSequence().dropWhile { it !== this }.drop(1).takeBound(this).filter { it.hasValOrVar() } } is KtEnumEntry -> { val enumEntries = containingClassOrObject?.body?.enumEntries ?: return emptySequence() enumEntries.asSequence().dropWhile { it !== this }.drop(1).takeBound(this) } is KtClass -> { val boundParameters = primaryConstructor?.valueParameters ?.asSequence() ?.takeBound(this) ?.filter { it.hasValOrVar() } .orEmpty() val boundEnumEntries = this.takeIf { isEnum() }?.body?.enumEntries?.asSequence()?.takeBound(this).orEmpty() boundParameters + boundEnumEntries } else -> emptySequence() } } private fun collectActualMarkers( declaration: KtNamedDeclaration, result: LineMarkerInfos ) { val gutter = KotlinLineMarkerOptions.actualOption if (!gutter.isEnabled) return if (declaration.requiresNoMarkers()) return if (!declaration.hasAtLeastOneActual()) return val anchor = declaration.expectOrActualAnchor val lineMarkerInfo = LineMarkerInfo( anchor, anchor.textRange, gutter.icon!!, PLATFORM_ACTUAL.tooltip, PLATFORM_ACTUAL.navigationHandler, GutterIconRenderer.Alignment.RIGHT, ) { gutter.name } NavigateAction.setNavigateAction( lineMarkerInfo, KotlinBundle.message("highlighter.action.text.go.to.actual.declarations"), IdeActions.ACTION_GOTO_IMPLEMENTATION ) result.add(lineMarkerInfo) } private fun collectExpectedMarkers( declaration: KtNamedDeclaration, result: LineMarkerInfos ) { if (!KotlinLineMarkerOptions.expectOption.isEnabled) return if (declaration.requiresNoMarkers()) return if (!declaration.hasMatchingExpected()) return val anchor = declaration.expectOrActualAnchor val gutter = KotlinLineMarkerOptions.expectOption val lineMarkerInfo = LineMarkerInfo( anchor, anchor.textRange, gutter.icon!!, EXPECTED_DECLARATION.tooltip, EXPECTED_DECLARATION.navigationHandler, GutterIconRenderer.Alignment.RIGHT, ) { gutter.name } NavigateAction.setNavigateAction( lineMarkerInfo, KotlinBundle.message("highlighter.action.text.go.to.expected.declaration"), null ) result.add(lineMarkerInfo) } private fun collectOverriddenFunctions(functions: Collection<KtNamedFunction>, result: LineMarkerInfos) { if (!(KotlinLineMarkerOptions.implementedOption.isEnabled || KotlinLineMarkerOptions.overriddenOption.isEnabled)) { return } val mappingToJava = HashMap<PsiElement, KtNamedFunction>() for (function in functions) { if (function.isOverridable()) { val method = LightClassUtil.getLightClassMethod(function) ?: KtFakeLightMethod.get(function) if (method != null) { mappingToJava[method] = function } mappingToJava[function] = function } } val classes = collectContainingClasses(mappingToJava.keys.filterIsInstance<PsiMethod>()) for (function in getOverriddenDeclarations(mappingToJava, classes)) { ProgressManager.checkCanceled() val anchor = function.nameAnchor() val gutter = if (isImplemented(function)) KotlinLineMarkerOptions.implementedOption else KotlinLineMarkerOptions.overriddenOption val lineMarkerInfo = LineMarkerInfo( anchor, anchor.textRange, gutter.icon!!, OVERRIDDEN_FUNCTION.tooltip, OVERRIDDEN_FUNCTION.navigationHandler, GutterIconRenderer.Alignment.RIGHT, ) { gutter.name } NavigateAction.setNavigateAction( lineMarkerInfo, KotlinBundle.message("highlighter.action.text.go.to.overridden.methods"), IdeActions.ACTION_GOTO_IMPLEMENTATION ) result.add(lineMarkerInfo) } } private fun KtNamedDeclaration.nameAnchor(): PsiElement = nameIdentifier ?: PsiTreeUtil.getDeepestVisibleFirst(this) ?: this
apache-2.0
0004ccaf25276f0866748fab6a965270
39.229965
158
0.696289
5.303399
false
false
false
false
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinLazyUBlockExpression.kt
4
1298
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin import com.intellij.psi.PsiElement import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.psi.KtAnonymousInitializer import org.jetbrains.uast.* @ApiStatus.Internal class KotlinLazyUBlockExpression( override val uastParent: UElement?, expressionProducer: (expressionParent: UElement) -> List<UExpression> ) : UBlockExpression { override val psi: PsiElement? get() = null override val javaPsi: PsiElement? get() = null override val sourcePsi: PsiElement? get() = null override val uAnnotations: List<UAnnotation> = emptyList() override val expressions by lz { expressionProducer(this) } companion object { fun create(initializers: List<KtAnonymousInitializer>, uastParent: UElement): UBlockExpression { val languagePlugin = uastParent.getLanguagePlugin() return KotlinLazyUBlockExpression(uastParent) { expressionParent -> initializers.map { languagePlugin.convertOpt(it.body, expressionParent) ?: UastEmptyExpression(expressionParent) } } } } }
apache-2.0
23600ebe34c655aa89a682012ad784e5
40.870968
158
0.718798
5.031008
false
false
false
false
jk1/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/DefaultWebServerPathHandler.kt
5
6050
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.builtInWebServer import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.io.endsWithName import com.intellij.openapi.util.io.endsWithSlash import com.intellij.openapi.util.io.getParentPath import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VFileProperty import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PathUtilRt import com.intellij.util.io.* import io.netty.channel.Channel import io.netty.channel.ChannelHandlerContext import io.netty.handler.codec.http.FullHttpRequest import io.netty.handler.codec.http.HttpRequest import io.netty.handler.codec.http.HttpResponseStatus import org.jetbrains.io.orInSafeMode import org.jetbrains.io.send import java.nio.file.Path import java.nio.file.Paths import java.util.regex.Pattern val chromeVersionFromUserAgent: Pattern = Pattern.compile(" Chrome/([\\d.]+) ") private class DefaultWebServerPathHandler : WebServerPathHandler() { override fun process(path: String, project: Project, request: FullHttpRequest, context: ChannelHandlerContext, projectName: String, decodedRawPath: String, isCustomHost: Boolean): Boolean { val channel = context.channel() val isSignedRequest = request.isSignedRequest() val extraHeaders = validateToken(request, channel, isSignedRequest) ?: return true val pathToFileManager = WebServerPathToFileManager.getInstance(project) var pathInfo = pathToFileManager.pathToInfoCache.getIfPresent(path) if (pathInfo == null || !pathInfo.isValid) { pathInfo = pathToFileManager.doFindByRelativePath(path, defaultPathQuery) if (pathInfo == null) { HttpResponseStatus.NOT_FOUND.send(channel, request, extraHeaders = extraHeaders) return true } pathToFileManager.pathToInfoCache.put(path, pathInfo) } var indexUsed = false if (pathInfo.isDirectory()) { var indexVirtualFile: VirtualFile? = null var indexFile: Path? = null if (pathInfo.file == null) { indexFile = findIndexFile(pathInfo.ioFile!!) } else { indexVirtualFile = findIndexFile(pathInfo.file!!) } if (indexFile == null && indexVirtualFile == null) { HttpResponseStatus.NOT_FOUND.send(channel, request, extraHeaders = extraHeaders) return true } // we must redirect only after index file check to not expose directory status if (!endsWithSlash(decodedRawPath)) { redirectToDirectory(request, channel, if (isCustomHost) path else "$projectName/$path", extraHeaders) return true } indexUsed = true pathInfo = PathInfo(indexFile, indexVirtualFile, pathInfo.root, pathInfo.moduleName, pathInfo.isLibrary) pathToFileManager.pathToInfoCache.put(path, pathInfo) } val userAgent = request.userAgent if (!isSignedRequest && userAgent != null && request.isRegularBrowser() && request.origin == null && request.referrer == null) { val matcher = chromeVersionFromUserAgent.matcher(userAgent) if (matcher.find() && StringUtil.compareVersionNumbers(matcher.group(1), "51") < 0 && !canBeAccessedDirectly(pathInfo.name)) { HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request) return true } } if (!indexUsed && !endsWithName(path, pathInfo.name)) { if (endsWithSlash(decodedRawPath)) { indexUsed = true } else { // FallbackResource feature in action, /login requested, /index.php retrieved, we must not redirect /login to /login/ val parentPath = getParentPath(pathInfo.path) if (parentPath != null && endsWithName(path, PathUtilRt.getFileName(parentPath))) { redirectToDirectory(request, channel, if (isCustomHost) path else "$projectName/$path", extraHeaders) return true } } } if (!checkAccess(pathInfo, channel, request)) { return true } val canonicalPath = if (indexUsed) "$path/${pathInfo.name}" else path for (fileHandler in WebServerFileHandler.EP_NAME.extensions) { LOG.runAndLogException { if (fileHandler.process(pathInfo, canonicalPath, project, request, channel, if (isCustomHost) null else projectName, extraHeaders)) { return true } } } // we registered as a last handler, so, we should just return 404 and send extra headers HttpResponseStatus.NOT_FOUND.send(channel, request, extraHeaders = extraHeaders) return true } } private fun checkAccess(pathInfo: PathInfo, channel: Channel, request: HttpRequest): Boolean { if (pathInfo.ioFile != null || pathInfo.file!!.isInLocalFileSystem) { val file = pathInfo.ioFile ?: Paths.get(pathInfo.file!!.path) if (file.isDirectory()) { HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request) return false } else if (!hasAccess(file)) { // we check only file, but all directories in the path because of https://youtrack.jetbrains.com/issue/WEB-21594 HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request) return false } } else if (pathInfo.file!!.`is`(VFileProperty.HIDDEN)) { HttpResponseStatus.FORBIDDEN.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request) return false } return true } private fun canBeAccessedDirectly(path: String): Boolean { for (fileHandler in WebServerFileHandler.EP_NAME.extensions) { for (ext in fileHandler.pageFileExtensions) { if (FileUtilRt.extensionEquals(path, ext)) { return true } } } return false }
apache-2.0
9e644301fcb2f0cc055c5ea56269e89a
38.809211
141
0.705455
4.66821
false
false
false
false
NiciDieNase/chaosflix
common/src/main/java/de/nicidienase/chaosflix/common/userdata/entities/progress/PlaybackProgress.kt
1
607
package de.nicidienase.chaosflix.common.userdata.entities.progress import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey import java.util.Date @Entity(tableName = "playback_progress", indices = [Index(value = ["event_guid"], unique = true)]) data class PlaybackProgress( @PrimaryKey(autoGenerate = true) val id: Long = 0, @ColumnInfo(name = "event_guid") var eventGuid: String, var progress: Long, @ColumnInfo(name = "watch_date") val watchDate: Long ) { val date: Date get() = Date(watchDate) }
mit
cf637c51fb649fa4e444cb547180c13d
26.590909
66
0.708402
3.746914
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/i18n/I18nElementFactory.kt
1
4530
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.i18n import com.demonwav.mcdev.i18n.lang.I18nFile import com.demonwav.mcdev.i18n.lang.I18nFileType import com.demonwav.mcdev.i18n.lang.gen.psi.I18nEntry import com.demonwav.mcdev.i18n.lang.gen.psi.I18nTypes import com.demonwav.mcdev.util.applyWriteAction import com.demonwav.mcdev.util.mcDomain import com.intellij.ide.DataManager import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileFactory import com.intellij.psi.PsiManager import com.intellij.psi.search.FileTypeIndex import com.intellij.psi.search.GlobalSearchScope import java.util.Locale object I18nElementFactory { fun addTranslation(module: Module?, name: String, value: String?) { if (module == null || value == null) { return } fun write(files: Iterable<VirtualFile>) { for (file in files) { val simpleFile = PsiManager.getInstance(module.project).findFile(file) if (simpleFile is I18nFile) { simpleFile.applyWriteAction { add(createLineEnding(project)) add(createEntry(project, name, value)) } } } } val files = FileTypeIndex.getFiles(I18nFileType, GlobalSearchScope.moduleScope(module)) if (files.count { it.nameWithoutExtension.toLowerCase(Locale.ROOT) == I18nConstants.DEFAULT_LOCALE } > 1) { val choices = files.mapNotNull { it.mcDomain }.distinct().sorted() DataManager.getInstance().dataContextFromFocusAsync.onSuccess { JBPopupFactory.getInstance() .createPopupChooserBuilder(choices) .setTitle("Choose resource domain") .setAdText("There are multiple resource domains with localization files, choose one for this translation.") .setItemChosenCallback { val validPattern = Regex("^.*?/assets/${Regex.escape(it)}/lang.*?\$") write(files.filter { validPattern.matches(it.path) }) } .createPopup() .showInBestPositionFor(it) } } else { write(files) } } fun assembleElements(project: Project, elements: Collection<I18nEntry>, keepComments: Int): List<PsiElement> { val result = mutableListOf<PsiElement>() val withComments = elements.associate { it to gatherComments(it, keepComments) } for ((entry, comments) in withComments) { for (comment in comments.asReversed()) { result.add(createComment(project, comment)) result.add(createLineEnding(project)) } result.add(createEntry(project, entry.key, entry.value)) result.add(createLineEnding(project)) } return result } private tailrec fun gatherComments(element: PsiElement, maxDepth: Int, acc: MutableList<String> = mutableListOf(), depth: Int = 0): List<String> { if (maxDepth != 0 && depth >= maxDepth) { return acc } val prev = element.prevSibling ?: return acc if (prev.node.elementType != I18nTypes.LINE_ENDING) { return acc } val prevLine = prev.prevSibling ?: return acc if (prevLine.node.elementType != I18nTypes.COMMENT) { return acc } acc.add(prevLine.text.substring(1).trim()) return gatherComments(prevLine, maxDepth, acc, depth + 1) } fun createFile(project: Project, text: String): I18nFile { return PsiFileFactory.getInstance(project).createFileFromText("name", I18nFileType, text) as I18nFile } fun createComment(project: Project, text: String): PsiElement { val file = createFile(project, "# $text") return file.firstChild } fun createEntry(project: Project, key: String, value: String = ""): I18nEntry { val file = createFile(project, "$key=$value") return file.firstChild as I18nEntry } fun createLineEnding(project: Project): PsiElement { val file = createFile(project, "\n") return file.firstChild } }
mit
ef649d48a1cdd126e88c7579b88543cb
38.051724
150
0.631788
4.436827
false
false
false
false
neva-dev/javarel-framework
storage/store/src/main/kotlin/com/neva/javarel/storage/store/impl/EntityObjectFactory.kt
1
2095
package com.neva.javarel.storage.store.impl import com.mongodb.DBObject import org.mongodb.morphia.annotations.ConstructorArgs import org.mongodb.morphia.mapping.DefaultCreator import org.mongodb.morphia.mapping.MappedField import org.mongodb.morphia.mapping.Mapper /** * Use pre-loaded entity classes while creating objects. Do not use class loader. */ class EntityObjectFactory(val classes: Set<Class<*>>) : DefaultCreator() { override fun <T : Any?> createInstance(clazz: Class<T>?, dbObj: DBObject): T { var c: Class<T>? = getClass(dbObj) if (c == null) { c = clazz } return createInstance(c) } override fun createInstance(mapper: Mapper, mf: MappedField, dbObj: DBObject): Any { var c: Class<*>? = getClass<Any>(dbObj) if (c == null) { c = if (mf.isSingleValue) mf.concreteType else mf.subClass } try { return createInstance(c, dbObj) } catch (e: RuntimeException) { val argAnn = mf.getAnnotation(ConstructorArgs::class.java) ?: throw e val args = arrayOfNulls<Any>(argAnn.value.size) val argTypes = arrayOfNulls<Class<*>>(argAnn.value.size) for (i in 0..argAnn.value.size - 1) { val `val` = dbObj.get(argAnn.value[i]) args[i] = `val` argTypes[i] = `val`.javaClass } try { val constructor = c!!.getDeclaredConstructor(*argTypes) constructor.isAccessible = true return constructor.newInstance(*args) } catch (ex: Exception) { throw RuntimeException(ex) } } } @Suppress("UNCHECKED_CAST") private fun <T> getClass(dbObj: DBObject): Class<T>? { var result: Class<T>? = null if (dbObj.containsField(Mapper.CLASS_NAME_FIELDNAME)) { val className = dbObj.get(Mapper.CLASS_NAME_FIELDNAME) as String result = classes.find { it.name == className } as Class<T> } return result } }
apache-2.0
e892891e00d3bf29039ac15f3f2b6008
32.269841
88
0.592363
4.107843
false
false
false
false
google/android-fhir
workflow/src/main/java/com/google/android/fhir/workflow/FhirEngineRetrieveProvider.kt
1
8651
/* * Copyright 2022 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 com.google.android.fhir.workflow import ca.uhn.fhir.rest.gclient.DateClientParam import ca.uhn.fhir.rest.gclient.NumberClientParam import ca.uhn.fhir.rest.gclient.ReferenceClientParam import ca.uhn.fhir.rest.gclient.StringClientParam import ca.uhn.fhir.rest.gclient.TokenClientParam import ca.uhn.fhir.rest.param.ParamPrefixEnum import com.google.android.fhir.FhirEngine import com.google.android.fhir.db.ResourceNotFoundException import com.google.android.fhir.search.Search import com.google.android.fhir.search.filter.TokenParamFilterCriterion import com.google.android.fhir.search.query.XFhirQueryTranslator.applyFilterParam import java.math.BigDecimal import java.util.Date import kotlinx.coroutines.runBlocking import org.hl7.fhir.r4.model.Coding import org.hl7.fhir.r4.model.DateTimeType import org.hl7.fhir.r4.model.Enumerations import org.hl7.fhir.r4.model.Resource import org.hl7.fhir.r4.model.ResourceType import org.opencds.cqf.cql.engine.retrieve.TerminologyAwareRetrieveProvider import org.opencds.cqf.cql.engine.runtime.Code import org.opencds.cqf.cql.engine.runtime.DateTime import org.opencds.cqf.cql.engine.runtime.Interval import org.opencds.cqf.cql.engine.terminology.ValueSetInfo class FhirEngineRetrieveProvider(private val fhirEngine: FhirEngine) : TerminologyAwareRetrieveProvider() { override fun retrieve( context: String?, contextPath: String?, contextValue: Any?, dataType: String?, templateId: String?, codePath: String?, codes: MutableIterable<Code>?, valueSet: String?, datePath: String?, dateLowPath: String?, dateHighPath: String?, dateRange: Interval? ): Iterable<Any> { return runBlocking { if (dataType == null) { emptyList() } else if (contextPath == "id" && contextValue == null) { emptyList() } else if (contextPath == "id" && contextValue != null) { listOfNotNull( safeGet(fhirEngine, ResourceType.fromCode(dataType), "$contextValue"), safeGet(fhirEngine, ResourceType.fromCode(dataType), "urn:uuid:$contextValue"), safeGet(fhirEngine, ResourceType.fromCode(dataType), "urn:oid:$contextValue") ) } else if (codePath == "id" && codes != null) { codes.mapNotNull { safeGet(fhirEngine, ResourceType.fromCode(dataType), it.code) } } else { val search = Search(ResourceType.fromCode(dataType)) // filter by context filterByContext(context, contextPath, contextValue, dataType, search) // filter by code in codes filterByCode(codePath, codes, search) // filter by code into valueSet filterByValueSet(codePath, valueSet, search) // filter by date in range filterByDateRange(datePath, dateLowPath, dateHighPath, dateRange, search) fhirEngine.search(search) } } } private fun filterByDateRange( datePath: String?, dateLowPath: String?, dateHighPath: String?, dateRange: Interval?, search: Search ) { if (datePath != null && dateRange?.low != null) { search.filter( DateClientParam(datePath), { prefix = if (dateRange.lowClosed) ParamPrefixEnum.GREATERTHAN_OR_EQUALS else ParamPrefixEnum.GREATERTHAN value = of(DateTimeType(convertDate(dateRange.low))) } ) } if (datePath != null && dateRange?.high != null) { search.filter( DateClientParam(datePath), { prefix = if (dateRange.highClosed) ParamPrefixEnum.LESSTHAN_OR_EQUALS else ParamPrefixEnum.LESSTHAN value = of(DateTimeType(convertDate(dateRange.high))) } ) } if (dateLowPath != null && dateRange?.low != null) { search.filter( DateClientParam(dateLowPath), { prefix = if (dateRange.lowClosed) ParamPrefixEnum.GREATERTHAN_OR_EQUALS else ParamPrefixEnum.GREATERTHAN value = of(DateTimeType(convertDate(dateRange.low))) } ) } if (dateHighPath != null && dateRange?.high != null) { search.filter( DateClientParam(dateHighPath), { prefix = if (dateRange.highClosed) ParamPrefixEnum.LESSTHAN_OR_EQUALS else ParamPrefixEnum.LESSTHAN value = of(DateTimeType(convertDate(dateRange.high))) } ) } } private fun convertDate(obj: Any): Date { return when (obj) { is Date -> obj is DateTime -> obj.toJavaDate() else -> throw UnsupportedOperationException( "FhirEngineRetrieveProvider doesn't know " + "how to convert (${obj.javaClass.name}) into a java.util.Date" ) } } private fun filterByCode(codePath: String?, codes: Iterable<Code>?, search: Search) { if (codes == null || codePath == null) return val inCodes = codes.map { val apply: TokenParamFilterCriterion.() -> Unit = { this.value = of(Coding(it.system, it.code, it.display)) } apply } if (inCodes.isNotEmpty()) search.filter(TokenClientParam(codePath), *inCodes.toTypedArray()) } private fun filterByValueSet(codePath: String?, valueSetUrl: String?, search: Search) { if (valueSetUrl == null || codePath == null) return val valueSet = terminologyProvider.expand(ValueSetInfo().withId(valueSetUrl)) val inCodes = valueSet.map { val apply: TokenParamFilterCriterion.() -> Unit = { this.value = of(Coding(it.system, it.code, it.display)) } apply } if (inCodes.isNotEmpty()) search.filter(TokenClientParam(codePath), *inCodes.toTypedArray()) } private fun filterByContext( context: String?, contextPath: String?, contextValue: Any?, dataType: String, search: Search, ) { if (context == null || contextPath == null || contextValue == null) return // Finds the SearchParamDefinition annotation that matches the incoming contextPath val ann = findSearchParamDefinition(dataType, contextPath) if (ann != null) { // If found, uses the applyFilterParam if (ann.type == Enumerations.SearchParamType.REFERENCE) { search.filter( ReferenceClientParam(ann.name), { value = "$context/$contextValue" }, { value = "urn:uuid:$contextValue" }, { value = "urn:oid:$contextValue" } ) } else { search.applyFilterParam(ann, "$contextValue") } } else { // Tries to identify the right param class by type when (contextValue) { is String -> search.filter(StringClientParam(contextPath), { value = contextValue }) is DateTimeType -> search.filter(DateClientParam(contextPath), { value = of(contextValue) }) is BigDecimal -> search.filter(NumberClientParam(contextPath), { value = contextValue }) else -> throw UnsupportedOperationException( "FhirEngineRetrieveProvider doesn't know " + "how to search for $dataType.$contextPath = $contextValue" + "(${contextValue.javaClass.name}) and get $context" ) } } } private suspend fun safeGet(fhirEngine: FhirEngine, type: ResourceType, id: String): Resource? { return try { fhirEngine.get(type, id) } catch (e: ResourceNotFoundException) { null } } private fun findSearchParamDefinition(dataType: String, path: String) = getClass(dataType) .fields .asSequence() .mapNotNull { it.getAnnotation(ca.uhn.fhir.model.api.annotation.SearchParamDefinition::class.java) } .filter { it.path == "$dataType.$path" } .map { com.google.android.fhir.index.SearchParamDefinition( it.name, Enumerations.SearchParamType.fromCode(it.type), it.path ) } .firstOrNull() private fun getClass(dataType: String): Class<*> { return Class.forName("org.hl7.fhir.r4.model.$dataType") } }
apache-2.0
1d410058fb5c27ed278da74df8bf4fc7
32.531008
100
0.658652
4.177209
false
false
false
false
jguerinet/MyMartlet-Android
app/src/main/java/model/Term.kt
2
3873
/* * Copyright 2014-2019 Julien Guerinet * * 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.guerinet.mymartlet.model import android.content.Context import com.guerinet.mymartlet.util.Constants import com.guerinet.mymartlet.util.extensions.get import com.guerinet.mymartlet.util.firestore import org.threeten.bp.LocalDate import java.io.Serializable /** * One class term, consisting of a season and a year * @author Julien Guerinet * @since 1.0.0 * * @property season Term [Season] * @property year Term year */ @Suppress("EqualsOrHashCode") class Term(val season: Season, val year: Int) : Serializable { /** * Term Id, for parsing errors */ val id = "${season.title} $year" /** * Returns true if the current term if after the given [term], false otherwise */ fun isAfter(term: Term): Boolean = when { // Year after year > term.year -> true // Year Before year < term.year -> false // Same year: check the semesters else -> season.number.toInt() > term.season.number.toInt() } /** * Returns the String representation of this term, using the [context] */ fun getString(context: Context): String = "${season.getString(context)} $year" /** * Returns the term in the format used by McGill */ override fun toString(): String = year.toString() + season.number override fun equals(other: Any?): Boolean { if (other !is Term) { return false } return season == other.season && year == other.year } companion object { /** * Returns the term from the [term] in the MGill String format (Ex: 199901 is Winter 1999) */ fun parseMcGillTerm(term: String): Term { // Split it into the year and the season val year = Integer.parseInt(term.substring(0, 4)) val season = Season.getSeasonFromNumber(term.substring(4)) return Term(season, year) } /** * Returns a parsed term from the [term] String */ fun parseTerm(term: String): Term { val termParts = term.trim().split(" ") return Term(Season.getSeasonFromTitle(termParts[0]), termParts[1].toInt()) } /** * Returns today's corresponding term */ fun currentTerm(): Term { val today = LocalDate.now() val year = today.year return when (today.monthValue) { in 9..12 -> Term(Season.FALL, year) in 1..4 -> Term(Season.WINTER, year) else -> Term(Season.SUMMER, year) } } /** * Loads the registration [Term]s from the Firestore */ suspend fun loadRegistrationTerms(): List<Term> = firestore.get(Constants.Firebase.REGISTRATION_TERMS) { // Load and parse the season val season = try { Season.getSeasonFromTitle(it["season"] as? String) } catch (e: Exception) { null } val year = it["year"] as? Long // If the season or year is null, something went wrong during parsing so don't continue return@get if (season != null && year != null) Term(season, year.toInt()) else null } } }
apache-2.0
edc78e5373d48614764e5d685354c4d7
30.745902
112
0.60315
4.317726
false
false
false
false
mdanielwork/intellij-community
plugins/github/src/org/jetbrains/plugins/github/GithubOpenInBrowserFromAnnotationActionGroup.kt
4
1814
// 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 import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.vcs.annotate.FileAnnotation import com.intellij.openapi.vcs.annotate.UpToDateLineNumberListener import git4idea.GitUtil import org.jetbrains.plugins.github.api.GithubRepositoryPath import org.jetbrains.plugins.github.util.GithubGitHelper class GithubOpenInBrowserFromAnnotationActionGroup(val annotation: FileAnnotation) : GithubOpenInBrowserActionGroup(), UpToDateLineNumberListener { private var myLineNumber = -1 override fun getData(dataContext: DataContext): Pair<Set<GithubRepositoryPath>, Data>? { if (myLineNumber < 0) return null val project = dataContext.getData(CommonDataKeys.PROJECT) val virtualFile = dataContext.getData(CommonDataKeys.VIRTUAL_FILE) if (project == null || virtualFile == null) return null FileDocumentManager.getInstance().getDocument(virtualFile) ?: return null val repository = GitUtil.getRepositoryManager(project).getRepositoryForFileQuick(virtualFile) if (repository == null) return null val accessibleRepositories = service<GithubGitHelper>().getPossibleRepositories(repository) if (accessibleRepositories.isEmpty()) return null val revisionHash = annotation.getLineRevisionNumber(myLineNumber)?.asString() if (revisionHash == null) return null return accessibleRepositories to Data.Revision(project, revisionHash) } override fun consume(integer: Int) { myLineNumber = integer } }
apache-2.0
17ce9000d26161a58ce4fd2a98739d3b
41.186047
140
0.802095
4.902703
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/formatter/KotlinCodeStylePropertyAccessor.kt
6
1181
// 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.formatter import com.intellij.application.options.codeStyle.properties.CodeStyleChoiceList import com.intellij.application.options.codeStyle.properties.CodeStylePropertyAccessor import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings import org.jetbrains.kotlin.idea.util.applyKotlinCodeStyle class KotlinCodeStylePropertyAccessor(private val kotlinCodeStyle: KotlinCodeStyleSettings) : CodeStylePropertyAccessor<String>(), CodeStyleChoiceList { override fun set(extVal: String): Boolean = applyKotlinCodeStyle(extVal, kotlinCodeStyle.container) override fun get(): String? = kotlinCodeStyle.container.kotlinCodeStyleDefaults() override fun parseString(string: String): String = string override fun valueToString(value: String): String = value override fun getChoices(): List<String> = listOf(KotlinStyleGuideCodeStyle.CODE_STYLE_ID, KotlinObsoleteCodeStyle.CODE_STYLE_ID) override fun getPropertyName(): String = "code_style_defaults" }
apache-2.0
2482d4d5bc9e79c1a4e76f8007c96029
61.210526
158
0.813717
4.686508
false
false
false
false
android/location-samples
LocationUpdatesBackgroundKotlin/app/src/main/java/com/google/android/gms/location/sample/locationupdatesbackgroundkotlin/Utils.kt
2
1981
/* * Copyright (C) 2020 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gms.location.sample.locationupdatesbackgroundkotlin import android.Manifest import android.content.Context import android.content.pm.PackageManager import androidx.core.app.ActivityCompat import androidx.fragment.app.Fragment import com.google.android.material.snackbar.Snackbar /** * Helper functions to simplify permission checks/requests. */ fun Context.hasPermission(permission: String): Boolean { // Background permissions didn't exit prior to Q, so it's approved by default. if (permission == Manifest.permission.ACCESS_BACKGROUND_LOCATION && android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.Q) { return true } return ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED } /** * Requests permission and if the user denied a previous request, but didn't check * "Don't ask again", we provide additional rationale. * * Note: The Snackbar should have an action to request the permission. */ fun Fragment.requestPermissionWithRationale( permission: String, requestCode: Int, snackbar: Snackbar ) { val provideRationale = shouldShowRequestPermissionRationale(permission) if (provideRationale) { snackbar.show() } else { requestPermissions(arrayOf(permission), requestCode) } }
apache-2.0
4119c53cfc30b359f895dc60574a0338
33.155172
82
0.744069
4.441704
false
false
false
false
mapzen/android
samples/mapzen-sample/src/main/java/mapzen/com/sdksampleapp/activities/MainActivity.kt
1
4379
package mapzen.com.sdksampleapp.activities import android.content.Intent import android.os.Bundle import android.preference.PreferenceManager import android.support.design.widget.BottomNavigationView import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.widget.HorizontalScrollView import android.widget.LinearLayout import android.widget.TextView import kotterknife.bindView import mapzen.com.sdksampleapp.R import mapzen.com.sdksampleapp.controllers.MainController import mapzen.com.sdksampleapp.fragments.BaseFragment import mapzen.com.sdksampleapp.models.Sample import mapzen.com.sdksampleapp.presenters.MainPresenter import javax.inject.Inject /** * Entry point for the sample app. Displays bottom navigation bar with top scroll view for * interaction with different SDK use cases. */ class MainActivity : BaseActivity(), MainController { val navigationView: BottomNavigationView by bindView(R.id.navigation) val scrollContent: LinearLayout by bindView(R.id.scrollContent) val scrollView: HorizontalScrollView by bindView(R.id.scrollView) @Inject lateinit var presenter: MainPresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mainApplication.appComponent.inject(this) presenter.controller = this presenter.onCreate() PreferenceManager.setDefaultValues(this, R.xml.preferences, false) } override fun onDestroy() { presenter.onDestroy() super.onDestroy() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.activity_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { presenter.onOptionsItemSelected(item?.itemId) return true } override fun selectSampleView(sample: Sample) { (0..scrollContent.childCount) .filter { it -> scrollContent.getChildAt(it) is TextView } .map { scrollContent.getChildAt(it) } .forEach { it.isSelected = (it.tag == sample) } } override fun setupNavigationItemSelectedListener() { navigationView.setOnNavigationItemSelectedListener { item -> presenter.onNavBarItemSelected(item.itemId) true } } override fun cleanupNavigationItemSelectedListener() { navigationView.setOnNavigationItemSelectedListener(null) } override fun clearScrollViewSamples() { scrollContent.removeAllViews() } override fun cleanupSampleFragment() { val fragment = supportFragmentManager.findFragmentById(R.id.fragment) as? BaseFragment fragment?.let { fragment.cleanup() } } override fun removeSampleFragment() { val fragment = supportFragmentManager.findFragmentById(R.id.fragment) as? BaseFragment fragment?.let { supportFragmentManager.beginTransaction().remove(it).commit() } } override fun setupSampleFragment(sample: Sample) { val fragment = sample.fragmentClass.java.newInstance() supportFragmentManager.beginTransaction().replace(R.id.fragment, fragment).commit() } override fun setScrollViewSamples(samples: Array<Sample>?) { if (samples == null) { return } for (sample in samples) { val inflater = LayoutInflater.from(this) val textView = inflater.inflate(R.layout.text_row, null) as TextView textView.text = presenter.getTitleText(sample) textView.setOnClickListener { view -> scrollView.smoothScrollTo(view.x.toInt(), 0) val sample = view.tag as Sample presenter.onSampleSelected(sample) } textView.tag = presenter.getTag(sample) val layoutParams = LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT) if (sample != samples[samples.size - 1]) { val rightMargin = resources.getDimensionPixelSize(R.dimen.padding) layoutParams.setMargins(0, 0, rightMargin, 0) } scrollContent.addView(textView, layoutParams) } } override fun cleanupScrollItemClickListeners() { (0..scrollContent.childCount) .filter { it -> scrollContent.getChildAt(it) is TextView } .map { scrollContent.getChildAt(it) as TextView } .forEach { it.setOnClickListener(null) } } override fun openSettings() { val intent = Intent(this, SettingsActivity::class.java) startActivity(intent) } }
apache-2.0
311e02f4a50b8ba9cd39ba61bafab6bc
33.480315
90
0.7504
4.673426
false
false
false
false
MGaetan89/ShowsRage
app/src/main/kotlin/com/mgaetan89/showsrage/presenter/SchedulePresenter.kt
1
2240
package com.mgaetan89.showsrage.presenter import android.content.Context import android.text.format.DateUtils import com.mgaetan89.showsrage.extension.getLocalizedTime import com.mgaetan89.showsrage.extension.toRelativeDate import com.mgaetan89.showsrage.model.ImageType import com.mgaetan89.showsrage.model.Indexer import com.mgaetan89.showsrage.model.Schedule import com.mgaetan89.showsrage.network.SickRageApi class SchedulePresenter(val schedule: Schedule?, val context: Context?) { private fun getAirDate(): CharSequence? { val schedule = this._getSchedule() ?: return null val airDate = schedule.airDate if (airDate.isEmpty()) { return null } return airDate.toRelativeDate("yyyy-MM-dd", DateUtils.DAY_IN_MILLIS) } fun getAirDateTime(): CharSequence? { val airDate = this.getAirDate() val airTime = this.getAirTime() if (airDate == null && airTime == null) { return null } if (airDate != null) { return if (airTime != null) "$airDate, $airTime" else airDate } return airTime } private fun getAirTime(): CharSequence? { val schedule = this._getSchedule() ?: return null if (this.context == null) { return null } val airDate = schedule.airDate val airTime = this.getAirTimeOnly() if (airDate.isEmpty() || airTime.isNullOrEmpty()) { return null } return this.context.getLocalizedTime("$airDate $airTime", "yyyy-MM-dd K:mm a") } fun getEpisode() = this._getSchedule()?.episode ?: 0 fun getNetwork() = this._getSchedule()?.network ?: "" fun getPosterUrl(): String { val schedule = this._getSchedule() ?: return "" return SickRageApi.instance.getImageUrl(ImageType.POSTER, schedule.tvDbId, Indexer.TVDB) } fun getQuality() = this._getSchedule()?.quality ?: "" fun getSeason() = this._getSchedule()?.season ?: 0 fun getShowName() = this._getSchedule()?.showName ?: "" internal fun getAirTimeOnly(): String? { val schedule = this._getSchedule() ?: return null val airTime = schedule.airs if (airTime.isEmpty()) { return null } return airTime.replaceFirst("(?i)^(monday|tuesday|wednesday|thursday|friday|saturday|sunday) ".toRegex(), "") } internal fun _getSchedule() = if (this.schedule?.isValid == true) this.schedule else null }
apache-2.0
f3f5c3f0b634ff6f5854b35200904d1e
25.666667
111
0.714286
3.561208
false
false
false
false
sachil/Essence
app/src/main/java/xyz/sachil/essence/fragment/adapter/diff/TypeDataDiffUtil.kt
1
623
package xyz.sachil.essence.fragment.adapter.diff import androidx.recyclerview.widget.DiffUtil import xyz.sachil.essence.model.net.bean.TypeData class TypeDataDiffUtil : DiffUtil.ItemCallback<TypeData>() { override fun areItemsTheSame(oldItem: TypeData, newItem: TypeData): Boolean = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: TypeData, newItem: TypeData): Boolean = (oldItem.title == newItem.title && oldItem.author == newItem.author && oldItem.viewCounts == newItem.viewCounts && oldItem.likeCounts == newItem.likeCounts) }
apache-2.0
91173eedf1e3c5b758a389df6bea65ad
38
84
0.70305
4.755725
false
false
false
false
zanata/zanata-platform
server/services/src/test/java/org/zanata/liquibase/custom/MigrateSeamTextToCommonMarkTest.kt
1
12941
/* * Copyright 2015, Red Hat, Inc. and individual contributors as indicated by the * @author tags. See the copyright.txt file in the distribution for a full * listing of individual contributors. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF * site: http://www.fsf.org. */ package org.zanata.liquibase.custom import antlr.ANTLRException import antlr.RecognitionException import liquibase.logging.core.DefaultLogger import org.apache.commons.lang3.StringUtils import org.jsoup.Jsoup import org.jsoup.nodes.Document.OutputSettings import org.jsoup.nodes.Element import org.jsoup.nodes.Node import org.jsoup.nodes.TextNode import org.jsoup.select.NodeTraversor import org.jsoup.select.NodeVisitor import org.junit.Assert import org.junit.ComparisonFailure import org.junit.Test import org.zanata.util.CommonMarkRenderer import org.zanata.seam.text.SeamTextLexer import org.zanata.seam.text.SeamTextParser import org.zanata.util.WebJars // non-breaking spaces private val NBSP_CHAR = "\u00A0" private val NBSP_ENTITY = "&nbsp;" /** * @author Sean Flanigan <a href="mailto:[email protected]">[email protected]</a> */ class MigrateSeamTextToCommonMarkTest { private val logger = DefaultLogger() private fun stripNonBreakSpace(text: String) = text.replace(NBSP_CHAR, " ").replace(NBSP_ENTITY, " ") private fun convertToHtml(seamText: String): String { val strippedSeamText = stripNonBreakSpace(seamText) val parser = SeamTextParser(SeamTextLexer(strippedSeamText.reader())) parser.startRule() return parser.toString() } private fun convertToCommonMark(seamText: String, name: String) = MigrateSeamTextToCommonMark.convertToCommonMark(seamText, name, logger) private val cmRenderer = CommonMarkRenderer(WebJars()).apply { postConstruct() } private val jsoupSettings = OutputSettings().prettyPrint(true).indentAmount(2) private val nodeCleaner = NodeTraversor(object : NodeVisitor { override fun head(node: Node, depth: Int) { } override fun tail(node: Node, depth: Int) { if (node is Element) { // remove class="seamTextPara" etc node.removeAttr("class") node.removeAttr("id") } else if (node is TextNode) { if (node.isBlank) { // trim empty text nodes node.text("") } else { val oldText = node.text() // replace nbsp with ordinary space val text = oldText.replace(NBSP_CHAR, " ") // and trim node.text(text.trim()) } } } }) /** * Replaces `tt` with `code`, strips out `class` and `id`, trims * whitespace and removes blank text nodes. */ fun clean(body: Element) { body.select("tt").tagName("code") body.select("i").tagName("em") nodeCleaner.traverse(body) } /** * Prettifies the HTML and normalises some of the minor differences * between Seam Text's rendering and CommonMark's. */ fun normalise(html: String): String { // 1. replace Seam's <q> elements with simple quote characters (") // 2. replace Seam's (often erroneous) underlining with underscores. // 3. replace CM's <pre><code> with <pre> ala Seam val someTagsRemoved = html.replace("</?q>".toRegex(), "\"").replace("</?u>".toRegex(), "_").replace("<pre><code>", "<pre>").replace("</code></pre>", "</pre>") val body = Jsoup.parse(someTagsRemoved).outputSettings(jsoupSettings).body() clean(body) val souped = body.html() // CommonMark sometimes puts <p></p> elements around block-level // elements like address, which Jsoup converts to an empty para // before and after. They doesn't seem to affect rendering in // browsers though, so we ignore them. val noEmptyParas = souped.replace("""\s*<p>\s*</p>""".toRegex(), "") // Remove paras because Seam sometimes fails to wrap inline elements in <p></p> // Convert em to * because CommonMark ignores markdown inside <p> (converter limitation) // Convert _* and *_ to ** because converter does not convert strong emphasis to *** (converter limitation) val moreCleaning = noEmptyParas.replace("</?p>".toRegex(), "").replace("</?em>".toRegex(), "*").replace("_*", "**").replace("*_", "**") val stripped = StringUtils.strip(moreCleaning) return stripped } private fun eprintln() { System.err.println() } private fun eprintln(arg: String?) { System.err.println(arg) } /** * Checks that the HTML rendering of the Seam Text is (almost) the same as * the HTML rendering of the CommonMark after conversion from Seam Text. */ private fun verifyConversion(name: String, seamText: String, expectedCM: String) { var commonMark = "" var seamToHtml = "" var commonMarkToHtml = "" var prettySeamHtml = "" var prettyCMHtml = "" try { commonMark = convertToCommonMark(seamText, name) Assert.assertEquals(expectedCM, commonMark) seamToHtml = convertToHtml(seamText) prettySeamHtml = normalise(seamToHtml) commonMarkToHtml = cmRenderer.renderToHtmlUnsafe(commonMark) prettyCMHtml = normalise(commonMarkToHtml) Assert.assertEquals(prettySeamHtml, prettyCMHtml) } catch (e: ComparisonFailure) { eprintln("$name:") eprintln("Seam Text: $seamText") eprintln("CommonMark: $commonMark") eprintln("Seam Text HTML: $seamToHtml") eprintln("Pretty Seam HTML: $prettySeamHtml") eprintln("CommonMark HTML: $commonMarkToHtml") eprintln("CommonMark HTML normalised: $prettyCMHtml") throw e } catch (e: ANTLRException) { eprintln(name + ":") eprintln() eprintln(e.message) if (e is RecognitionException) { eprintln("line=${e.line} col=${e.column}") if (e.line >= 0) { // seamText.reader().forEachLine { eprintln(it) } eprintln(seamText.reader().readLines().get(e.line)) eprintln(" ".repeat(e.column) + "^") eprintln("-".repeat(e.column) + "|") } else { seamText.reader().readLines().take(10).forEach { eprintln(it) } } } else { seamText.reader().readLines().take(10).forEach { eprintln(it) } } eprintln() eprintln("\n") eprintln("\n") eprintln("\n") throw e } } @Test fun `compact Seam Text`() { val seamText = """ It's easy to make *emphasis*, |monospace|, ~deleted text~, super^scripts^ or _underlines_. +This is a big heading You *must* have some text following a heading! ++This is a smaller heading This is the first paragraph. We can split it across multiple lines, but we must end it with a blank line. This is the second paragraph. An ordered list: #first item #second item #and even the /third/ item An unordered list: =an item =another item The other guy said: "Nyeah nyeah-nee /nyeah/ nyeah!" But what do you think he means by "nyeah-nee"? You can write down equations like 2\*3\=6 and HTML tags like \<body\> using the escape character: \\. My code doesn't work: `for (int i=0; i<100; i--) { doSomething(); }` Any ideas? Go to the Seam website at [=>http://jboss.org/schema/seam]. Go to [the Seam website=>http://jboss.org/schema/seam]. You might want to link to <a href="http://jboss.org/schema/seam">something cool</a>, or even include an image: <img src="/logo.jpg"/> <table> <tr><td>First name:</td><td>Gavin</td></tr> <tr><td>Last name:</td><td>King</td></tr> </table> """ val expectedCM = """<!-- The following text was converted from Seam Text to CommonMark by Zanata. Some formatting changes may have occurred. --> It's easy to make *emphasis*, `monospace`, <del>deleted text</del>, super<sup>scripts</sup> or <u>underlines</u>. # This is a big heading You *must* have some text following a heading! ## This is a smaller heading This is the first paragraph. We can split it across multiple lines, but we must end it with a blank line. This is the second paragraph. An ordered list: 1. first item 1. second item 1. and even the /third/ item An unordered list: * an item * another item The other guy said: <blockquote class="seamTextBlockquote"> Nyeah nyeah-nee /nyeah/ nyeah! </blockquote> But what do you think he means by "nyeah-nee"? You can write down equations like 2*3=6 and HTML tags like &lt;body&gt; using the escape character: \\. My code doesn't work: <pre><code> for (int i=0; i&lt;100; i--) { doSomething(); } </code></pre> Any ideas? Go to the Seam website at [](http://jboss.org/schema/seam). Go to [the Seam website](http://jboss.org/schema/seam). You might want to link to <a href="http://jboss.org/schema/seam">something cool</a>, or even include an image: <img src="/logo.jpg"/> <table> <tr><td>First name:</td><td>Gavin</td></tr> <tr><td>Last name:</td><td>King</td></tr> </table> """ verifyConversion("compressedSeamText", seamText, expectedCM) } @Test fun `ordinary Seam Text`() { val seamText = """ It's easy to make *emphasis*, |monospace|, ~deleted text~, super^scripts^ or _underlines_. +This is a big heading You *must* have some text following a heading! ++This is a smaller heading This is the first paragraph. We can split it across multiple lines, but we must end it with a blank line. This is the second paragraph. An ordered list: #first item #second item #and even the /third/ item An unordered list: =an item =another item The other guy said: "Nyeah nyeah-nee /nyeah/ nyeah!" But what do you think he means by "nyeah-nee"? You can write down equations like 2\*3\=6 and HTML tags like \<body\> using the escape character: \\. My code doesn't work: `for (int i=0; i<100; i--) { doSomething(); }` Any ideas? Go to the Seam website at [=>http://jboss.org/schema/seam]. Go to [the Seam website=>http://jboss.org/schema/seam]. You might want to link to <a href="http://jboss.org/schema/seam">something cool</a>, or even include an image: <img src="/logo.jpg"/> <table> <tr><td>First name:</td><td>Gavin</td></tr> <tr><td>Last name:</td><td>King</td></tr> </table> """ val expectedCM = """<!-- The following text was converted from Seam Text to CommonMark by Zanata. Some formatting changes may have occurred. --> It's easy to make *emphasis*, `monospace`, <del>deleted text</del>, super<sup>scripts</sup> or <u>underlines</u>. # This is a big heading You *must* have some text following a heading! ## This is a smaller heading This is the first paragraph. We can split it across multiple lines, but we must end it with a blank line. This is the second paragraph. An ordered list: 1. first item 1. second item 1. and even the /third/ item An unordered list: * an item * another item The other guy said: <blockquote class="seamTextBlockquote"> Nyeah nyeah-nee /nyeah/ nyeah! </blockquote> But what do you think he means by "nyeah-nee"? You can write down equations like 2*3=6 and HTML tags like &lt;body&gt; using the escape character: \\. My code doesn't work: <pre><code> for (int i=0; i&lt;100; i--) { doSomething(); } </code></pre> Any ideas? Go to the Seam website at [](http://jboss.org/schema/seam). Go to [the Seam website](http://jboss.org/schema/seam). You might want to link to <a href="http://jboss.org/schema/seam">something cool</a>, or even include an image: <img src="/logo.jpg"/> <table> <tr><td>First name:</td><td>Gavin</td></tr> <tr><td>Last name:</td><td>King</td></tr> </table> """ verifyConversion("generalSeamText", seamText, expectedCM) } }
lgpl-2.1
8416972f9d3a07e5a9732e4956e57f07
25.090726
166
0.640136
3.598721
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/internal/makeBackup/CreateIncrementalCompilationBackup.kt
1
7859
// 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.internal.makeBackup import com.intellij.compiler.server.BuildManager import com.intellij.history.core.RevisionsCollector import com.intellij.history.integration.LocalHistoryImpl import com.intellij.history.integration.patches.PatchCreator import com.intellij.ide.IdeBundle import com.intellij.ide.actions.RevealFileAction import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.runReadAction import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageDialogBuilder.Companion.okCancel import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.changes.Change import com.intellij.util.WaitForProgressToShow import com.intellij.util.io.ZipUtil import org.jetbrains.kotlin.idea.KotlinJvmBundle import java.io.File import java.io.FileOutputStream import java.text.SimpleDateFormat import java.util.* import java.util.zip.ZipOutputStream class CreateIncrementalCompilationBackup : AnAction(KotlinJvmBundle.message("create.backup.for.debugging.kotlin.incremental.compilation")) { companion object { const val BACKUP_DIR_NAME = ".backup" const val PATCHES_TO_CREATE = 5 const val PATCHES_FRACTION = .25 const val LOGS_FRACTION = .05 const val PROJECT_SYSTEM_FRACTION = .05 const val ZIP_FRACTION = 1.0 - PATCHES_FRACTION - LOGS_FRACTION - PROJECT_SYSTEM_FRACTION } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val projectBaseDir = File(project.baseDir!!.path) val backupDir = File(FileUtil.createTempDirectory("makeBackup", null), BACKUP_DIR_NAME) ProgressManager.getInstance().run( object : Task.Backgroundable( project, KotlinJvmBundle.message("creating.backup.for.debugging.kotlin.incremental.compilation"), true ) { override fun run(indicator: ProgressIndicator) { createPatches(backupDir, project, indicator) copyLogs(backupDir, indicator) copyProjectSystemDir(backupDir, project, indicator) zipProjectDir(backupDir, project, projectBaseDir, indicator) } } ) } @Suppress("HardCodedStringLiteral") private fun createPatches(backupDir: File, project: Project, indicator: ProgressIndicator) { runReadAction { val localHistoryImpl = LocalHistoryImpl.getInstanceImpl()!! val gateway = localHistoryImpl.gateway!! val localHistoryFacade = localHistoryImpl.facade val revisionsCollector = RevisionsCollector( localHistoryFacade, gateway.createTransientRootEntry(), project.baseDir!!.path, project.locationHash, null ) var patchesCreated = 0 val patchesDir = File(backupDir, "patches") patchesDir.mkdirs() val revisions = revisionsCollector.result!! for (rev in revisions) { val label = rev.label if (label != null && label.startsWith(HISTORY_LABEL_PREFIX)) { val patchFile = File(patchesDir, label.removePrefix(HISTORY_LABEL_PREFIX) + ".patch") indicator.text = KotlinJvmBundle.message("creating.patch.0", patchFile) indicator.fraction = PATCHES_FRACTION * patchesCreated / PATCHES_TO_CREATE val differences = revisions[0].getDifferencesWith(rev)!! val changes = differences.map { d -> Change(d.getLeftContentRevision(gateway), d.getRightContentRevision(gateway)) } PatchCreator.create(project, changes, patchFile.toPath(), false, null) if (++patchesCreated >= PATCHES_TO_CREATE) { break } } } } } private fun copyLogs(backupDir: File, indicator: ProgressIndicator) { indicator.text = KotlinJvmBundle.message("copying.logs") indicator.fraction = PATCHES_FRACTION val logsDir = File(backupDir, "logs") FileUtil.copyDir(File(PathManager.getLogPath()), logsDir) indicator.fraction = PATCHES_FRACTION + LOGS_FRACTION } private fun copyProjectSystemDir(backupDir: File, project: Project, indicator: ProgressIndicator) { indicator.text = KotlinJvmBundle.message("copying.project.s.system.dir") indicator.fraction = PATCHES_FRACTION val projectSystemDir = File(backupDir, "project-system") FileUtil.copyDir(BuildManager.getInstance().getProjectSystemDirectory(project)!!, projectSystemDir) indicator.fraction = PATCHES_FRACTION + LOGS_FRACTION + PROJECT_SYSTEM_FRACTION } private fun zipProjectDir(backupDir: File, project: Project, projectDir: File, indicator: ProgressIndicator) { // files and relative paths val files = ArrayList<Pair<File, String>>() // files and relative paths var totalBytes = 0L for (dir in listOf(projectDir, backupDir.parentFile!!)) { FileUtil.processFilesRecursively( dir, /*processor*/ { if (it!!.isFile && !it.name.endsWith(".hprof") && !(it.name.startsWith("make_backup_") && it.name.endsWith(".zip")) ) { indicator.text = KotlinJvmBundle.message("scanning.project.dir.0", it) files.add(Pair(it, FileUtil.getRelativePath(dir, it)!!)) totalBytes += it.length() } true }, /*directoryFilter*/ { val name = it!!.name name != ".git" && name != "out" } ) } val backupFile = File(projectDir, "make_backup_" + SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(Date()) + ".zip") val zos = ZipOutputStream(FileOutputStream(backupFile)) var processedBytes = 0L zos.use { for ((file, relativePath) in files) { indicator.text = KotlinJvmBundle.message("adding.file.to.backup.0", relativePath) indicator.fraction = PATCHES_FRACTION + LOGS_FRACTION + processedBytes.toDouble() / totalBytes * ZIP_FRACTION ZipUtil.addFileToZip(zos, file, relativePath, null, null) processedBytes += file.length() } } FileUtil.delete(backupDir) WaitForProgressToShow.runOrInvokeLaterAboveProgress( { val confirmed = okCancel( KotlinJvmBundle.message("created.backup"), KotlinJvmBundle.message("successfully.created.backup.0", backupFile.absolutePath) ) .yesText(RevealFileAction.getActionName(null)) .noText(IdeBundle.message("action.close")) .icon(Messages.getInformationIcon()) .ask(project) if (confirmed) { RevealFileAction.openFile(backupFile) } }, null, project ) } }
apache-2.0
0a486a7cd9bbbec95009be24b43e397a
39.096939
140
0.619926
5.073596
false
false
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/jdkDownloader/RuntimeChooserDialog.kt
2
8349
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.projectRoots.impl.jdkDownloader import com.intellij.icons.AllIcons import com.intellij.lang.LangBundle import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.invokeLater import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.HtmlChunk import com.intellij.ui.JBColor import com.intellij.ui.SimpleColoredComponent import com.intellij.ui.components.JBLabel import com.intellij.ui.layout.* import com.intellij.util.castSafelyTo import com.intellij.util.io.isDirectory import com.intellij.util.ui.JBUI import com.intellij.util.ui.components.BorderLayoutPanel import java.awt.datatransfer.DataFlavor import java.awt.event.WindowAdapter import java.awt.event.WindowEvent import java.nio.file.Path import java.nio.file.Paths import javax.swing.JComponent import javax.swing.JPanel import javax.swing.SwingConstants sealed class RuntimeChooserDialogResult { object Cancel : RuntimeChooserDialogResult() object UseDefault: RuntimeChooserDialogResult() data class DownloadAndUse(val item: JdkItem, val path: Path) : RuntimeChooserDialogResult() data class UseCustomJdk(val name: String, val path: Path) : RuntimeChooserDialogResult() } class RuntimeChooserDialog( private val project: Project?, private val model: RuntimeChooserModel, ) : DialogWrapper(project), DataProvider { private val USE_DEFAULT_RUNTIME_CODE = NEXT_USER_EXIT_CODE + 42 private lateinit var jdkInstallDirSelector: TextFieldWithBrowseButton private lateinit var jdkCombobox: ComboBox<RuntimeChooserItem> init { title = LangBundle.message("dialog.title.choose.ide.runtime") setResizable(false) init() initClipboardListener() } private fun initClipboardListener() { val knownPaths = mutableSetOf<String>() val clipboardUpdateAction = { val newPath = runCatching { CopyPasteManager.getInstance().contents?.getTransferData(DataFlavor.stringFlavor) as? String }.getOrNull() if (newPath != null && newPath.isNotBlank() && knownPaths.add(newPath)) { RuntimeChooserCustom.importDetectedItem(newPath.trim(), model) } } val windowListener = object: WindowAdapter() { override fun windowActivated(e: WindowEvent?) { invokeLater(ModalityState.any()) { clipboardUpdateAction() } } } window?.let { window -> window.addWindowListener(windowListener) Disposer.register(disposable) { window.removeWindowListener(windowListener) } } clipboardUpdateAction() } override fun getData(dataId: String): Any? { return RuntimeChooserCustom.jdkDownloaderExtensionProvider.getData(dataId) } override fun createSouthAdditionalPanel(): JPanel { return BorderLayoutPanel().apply { addToCenter( createJButtonForAction( DialogWrapperExitAction( LangBundle.message("dialog.button.choose.ide.runtime.useDefault"), USE_DEFAULT_RUNTIME_CODE) ) ) } } fun showDialogAndGetResult() : RuntimeChooserDialogResult { show() if (exitCode == USE_DEFAULT_RUNTIME_CODE) { return RuntimeChooserDialogResult.UseDefault } if (isOK) run { val jdkItem = jdkCombobox.selectedItem.castSafelyTo<RuntimeChooserDownloadableItem>()?.item ?: return@run val path = model.getInstallPathFromText(jdkItem, jdkInstallDirSelector.text) return RuntimeChooserDialogResult.DownloadAndUse(jdkItem, path) } if (isOK) run { val jdkItem = jdkCombobox.selectedItem.castSafelyTo<RuntimeChooserCustomItem>() ?: return@run val home = Paths.get(jdkItem.homeDir) if (home.isDirectory()) { return RuntimeChooserDialogResult.UseCustomJdk(listOfNotNull(jdkItem.displayName, jdkItem.version).joinToString(" "), home) } } return RuntimeChooserDialogResult.Cancel } override fun createTitlePane(): JComponent { return BorderLayoutPanel().apply { val customLine = when { SystemInfo.isWindows -> JBUI.Borders.customLine(JBColor.border(), 1, 0, 1, 0) else -> JBUI.Borders.customLineBottom(JBColor.border()) } border = JBUI.Borders.merge(JBUI.Borders.empty(10), customLine, true) background = JBUI.CurrentTheme.Notification.BACKGROUND foreground = JBUI.CurrentTheme.Notification.FOREGROUND addToCenter(JBLabel().apply { icon = AllIcons.General.Warning verticalTextPosition = SwingConstants.TOP text = HtmlChunk .html() .addText(LangBundle.message("dialog.label.choose.ide.runtime.warn")) .toString() }) withPreferredWidth(400) } } override fun createCenterPanel(): JComponent { jdkCombobox = object : ComboBox<RuntimeChooserItem>(model.mainComboBoxModel) { init { isSwingPopup = false setMinimumAndPreferredWidth(400) setRenderer(RuntimeChooserPresenter()) } override fun setSelectedItem(anObject: Any?) { if (anObject !is RuntimeChooserItem) return if (anObject is RuntimeChooserAddCustomItem) { RuntimeChooserCustom .createSdkChooserPopup(jdkCombobox, [email protected]) ?.showUnderneathOf(jdkCombobox) return } if (anObject is RuntimeChooserDownloadableItem || anObject is RuntimeChooserCustomItem || anObject is RuntimeChooserCurrentItem) { super.setSelectedItem(anObject) } } } return panel { row(LangBundle.message("dialog.label.choose.ide.runtime.current")) { val control = SimpleColoredComponent() control().constraints(growX) model.currentRuntime.getAndSubscribe(disposable) { control.clear() if (it != null) { RuntimeChooserPresenter.run { control.presetCurrentRuntime(it) } } } } row(LangBundle.message("dialog.label.choose.ide.runtime.combo")) { jdkCombobox.invoke(growX) } //download row row(LangBundle.message("dialog.label.choose.ide.runtime.location")) { jdkInstallDirSelector = textFieldWithBrowseButton( project = project, browseDialogTitle = LangBundle.message("dialog.title.choose.ide.runtime.select.path.to.install.jdk"), fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor() ).constraints(growX) .comment(LangBundle.message("dialog.message.choose.ide.runtime.select.path.to.install.jdk")) .component val updateLocation = { when(val item = jdkCombobox.selectedItem){ is RuntimeChooserDownloadableItem -> { jdkInstallDirSelector.text = model.getDefaultInstallPathFor(item.item) jdkInstallDirSelector.setButtonEnabled(true) jdkInstallDirSelector.isEditable = true jdkInstallDirSelector.setButtonVisible(true) } is RuntimeChooserItemWithFixedLocation -> { jdkInstallDirSelector.text = FileUtil.getLocationRelativeToUserHome(item.homeDir, false) jdkInstallDirSelector.setButtonEnabled(false) jdkInstallDirSelector.isEditable = false jdkInstallDirSelector.setButtonVisible(false) } else -> { jdkInstallDirSelector.text = "" jdkInstallDirSelector.setButtonEnabled(false) jdkInstallDirSelector.isEditable = false jdkInstallDirSelector.setButtonVisible(false) } } } updateLocation() jdkCombobox.addItemListener { updateLocation() } } } } }
apache-2.0
0aa3454255f35e9492a992accdf3d2d0
35.142857
140
0.703677
4.817657
false
false
false
false
allotria/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/statistics/MavenSettingsCollector.kt
4
6104
// 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.idea.maven.statistics import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.beans.newBooleanMetric import com.intellij.internal.statistic.beans.newMetric import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector import com.intellij.openapi.externalSystem.statistics.ExternalSystemUsagesCollector import com.intellij.openapi.project.ExternalStorageConfigurationManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Version import org.jetbrains.idea.maven.execution.MavenExternalParameters.resolveMavenHome import org.jetbrains.idea.maven.execution.MavenRunner import org.jetbrains.idea.maven.project.MavenImportingSettings import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.utils.MavenUtil class MavenSettingsCollector : ProjectUsagesCollector() { override fun getGroupId() = "build.maven.state" override fun getMetrics(project: Project): Set<MetricEvent> { val manager = MavenProjectsManager.getInstance(project) if (!manager.isMavenizedProject) return emptySet() val usages = mutableSetOf<MetricEvent>() // to have a total users base line to calculate pertentages of settings usages.add(newBooleanMetric("hasMavenProject", true)) // Main page val generalSettings = manager.generalSettings usages.add(newMetric("checksumPolicy", generalSettings.checksumPolicy)) usages.add(newMetric("failureBehavior", generalSettings.failureBehavior)) usages.add(newBooleanMetric("alwaysUpdateSnapshots", generalSettings.isAlwaysUpdateSnapshots)) usages.add(newBooleanMetric("nonRecursive", generalSettings.isNonRecursive)) usages.add(newBooleanMetric("printErrorStackTraces", generalSettings.isPrintErrorStackTraces)) usages.add(newBooleanMetric("usePluginRegistry", generalSettings.isUsePluginRegistry)) usages.add(newBooleanMetric("workOffline", generalSettings.isWorkOffline)) usages.add(newMetric("outputLevel", generalSettings.outputLevel)) usages.add(newMetric("pluginUpdatePolicy", generalSettings.pluginUpdatePolicy)) @Suppress("DEPRECATION") usages.add(newMetric("loggingLevel", generalSettings.loggingLevel)) try { var mavenVersion = MavenUtil.getMavenVersion(resolveMavenHome(generalSettings, project, null)) mavenVersion = mavenVersion?.let { Version.parseVersion(it)?.toCompactString() } ?: "unknown" usages.add(newMetric("mavenVersion", mavenVersion)) } catch (ignore: Exception) { // ignore invalid maven home configuration } usages.add(newBooleanMetric("localRepository", generalSettings.localRepository.isNotBlank())) usages.add(newBooleanMetric("userSettingsFile", generalSettings.userSettingsFile.isNotBlank())) // Importing page val importingSettings = manager.importingSettings usages.add(newBooleanMetric("lookForNested", importingSettings.isLookForNested)) usages.add(newBooleanMetric("dedicatedModuleDir", importingSettings.dedicatedModuleDir.isNotBlank())) usages.add(newBooleanMetric("storeProjectFilesExternally", ExternalStorageConfigurationManager.getInstance(project).isEnabled)) usages.add(newBooleanMetric("autoDetectCompiler", importingSettings.isAutoDetectCompiler)) usages.add(newBooleanMetric("createModulesForAggregators", importingSettings.isCreateModulesForAggregators)) usages.add(newBooleanMetric("createModuleGroups", importingSettings.isCreateModuleGroups)) usages.add(newBooleanMetric("keepSourceFolders", importingSettings.isKeepSourceFolders)) usages.add(newBooleanMetric("excludeTargetFolder", importingSettings.isExcludeTargetFolder)) usages.add(newBooleanMetric("useMavenOutput", importingSettings.isUseMavenOutput)) usages.add(newMetric("generatedSourcesFolder", importingSettings.generatedSourcesFolder)) usages.add(newMetric("updateFoldersOnImportPhase", importingSettings.updateFoldersOnImportPhase)) usages.add(newBooleanMetric("downloadDocsAutomatically", importingSettings.isDownloadDocsAutomatically)) usages.add(newBooleanMetric("downloadSourcesAutomatically", importingSettings.isDownloadSourcesAutomatically)) usages.add(newBooleanMetric("customDependencyTypes", MavenImportingSettings.DEFAULT_DEPENDENCY_TYPES != importingSettings.dependencyTypes)) usages.add(ExternalSystemUsagesCollector.getJRETypeUsage("jdkTypeForImporter", importingSettings.jdkForImporter)) usages.add(ExternalSystemUsagesCollector.getJREVersionUsage(project, "jdkVersionForImporter", importingSettings.jdkForImporter)) usages.add(newBooleanMetric("hasVmOptionsForImporter", importingSettings.vmOptionsForImporter.isNotBlank())) // Ignored Files page usages.add(newBooleanMetric("hasIgnoredFiles", manager.ignoredFilesPaths.isNotEmpty())) usages.add(newBooleanMetric("hasIgnoredPatterns", manager.ignoredFilesPatterns.isNotEmpty())) // Runner page val runnerSettings = MavenRunner.getInstance(project).settings usages.add(newBooleanMetric("delegateBuildRun", runnerSettings.isDelegateBuildToMaven)) usages.add(newBooleanMetric("runMavenInBackground", runnerSettings.isRunMavenInBackground)) usages.add(ExternalSystemUsagesCollector.getJRETypeUsage("runnerJreType", runnerSettings.jreName)) usages.add(ExternalSystemUsagesCollector.getJREVersionUsage(project, "runnerJreVersion", runnerSettings.jreName)) usages.add(newBooleanMetric("hasRunnerVmOptions", runnerSettings.vmOptions.isNotBlank())) usages.add(newBooleanMetric("hasRunnerEnvVariables", !runnerSettings.environmentProperties.isNullOrEmpty())) usages.add(newBooleanMetric("passParentEnv", runnerSettings.isPassParentEnv)) usages.add(newBooleanMetric("skipTests", runnerSettings.isSkipTests)) usages.add(newBooleanMetric("hasRunnerMavenProperties", !runnerSettings.mavenProperties.isNullOrEmpty())) return usages } }
apache-2.0
adfa4b0110e2a52aa6863482c6059fe0
62.583333
140
0.81422
5.217094
false
false
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/navigation/impl/TargetPresentationBuilderImpl.kt
3
2140
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.navigation.impl import com.intellij.navigation.TargetPresentation import com.intellij.navigation.TargetPresentationBuilder import com.intellij.openapi.editor.markup.TextAttributes import org.jetbrains.annotations.Nls import java.awt.Color import javax.swing.Icon /** * `data` class for `#copy` method */ internal data class TargetPresentationBuilderImpl( override val backgroundColor: Color? = null, override val icon: Icon? = null, override val presentableText: @Nls String, override val presentableTextAttributes: TextAttributes? = null, override val containerText: @Nls String? = null, override val containerTextAttributes: TextAttributes? = null, override val locationText: @Nls String? = null, override val locationIcon: Icon? = null, ) : TargetPresentationBuilder, TargetPresentation { override fun presentation(): TargetPresentation = this override fun backgroundColor(color: Color?): TargetPresentationBuilder { return copy(backgroundColor = color) } override fun icon(icon: Icon?): TargetPresentationBuilder { return copy(icon = icon) } override fun presentableTextAttributes(attributes: TextAttributes?): TargetPresentationBuilder { return copy(presentableTextAttributes = attributes) } override fun containerText(text: String?): TargetPresentationBuilder { return copy(containerText = text) } override fun containerText(text: String?, attributes: TextAttributes?): TargetPresentationBuilder { return copy(containerText = text, containerTextAttributes = attributes) } override fun containerTextAttributes(attributes: TextAttributes?): TargetPresentationBuilder { return copy(containerTextAttributes = attributes) } override fun locationText(text: String?): TargetPresentationBuilder { return copy(locationText = text) } override fun locationText(text: String?, icon: Icon?): TargetPresentationBuilder { return copy(locationText = text, locationIcon = icon) } }
apache-2.0
bff873932a047af3d47e6aafc7ac649c
35.896552
140
0.776168
4.976744
false
false
false
false
Kotlin/kotlinx.coroutines
reactive/kotlinx-coroutines-rx2/test/ObservableExceptionHandlingTest.kt
1
4262
/* * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.rx2 import io.reactivex.exceptions.* import kotlinx.coroutines.* import org.junit.* import org.junit.Test import java.util.concurrent.* import kotlin.test.* class ObservableExceptionHandlingTest : TestBase() { @Before fun setup() { ignoreLostThreads("RxComputationThreadPool-", "RxCachedWorkerPoolEvictor-", "RxSchedulerPurge-") } private inline fun <reified T : Throwable> handler(expect: Int) = { t: Throwable -> assertTrue(t is UndeliverableException && t.cause is T, "$t") expect(expect) } private fun cehUnreached() = CoroutineExceptionHandler { _, _ -> expectUnreached() } @Test fun testException() = withExceptionHandler({ expectUnreached() }) { rxObservable<Int>(Dispatchers.Unconfined + cehUnreached()) { expect(1) throw TestException() }.subscribe({ expectUnreached() }, { expect(2) // Reported to onError }) finish(3) } @Test fun testFatalException() = withExceptionHandler({ expectUnreached() }) { rxObservable<Int>(Dispatchers.Unconfined + cehUnreached()) { expect(1) throw LinkageError() }.subscribe({ expectUnreached() }, { expect(2) }) finish(3) } @Test fun testExceptionAsynchronous() = withExceptionHandler({ expectUnreached() }) { rxObservable<Int>(Dispatchers.Unconfined) { expect(1) throw TestException() }.publish() .refCount() .subscribe({ expectUnreached() }, { expect(2) // Reported to onError }) finish(3) } @Test fun testFatalExceptionAsynchronous() = withExceptionHandler({ expectUnreached() }) { rxObservable<Int>(Dispatchers.Unconfined) { expect(1) throw LinkageError() }.publish() .refCount() .subscribe({ expectUnreached() }, { expect(2) // Fatal exceptions are not treated in a special manner }) finish(3) } @Test fun testFatalExceptionFromSubscribe() = withExceptionHandler(handler<LinkageError>(3)) { val latch = CountDownLatch(1) rxObservable(Dispatchers.Unconfined) { expect(1) val result = trySend(Unit) val exception = result.exceptionOrNull() assertTrue(exception is UndeliverableException) assertTrue(exception.cause is LinkageError) assertTrue(isClosedForSend) expect(4) latch.countDown() }.subscribe({ expect(2) throw LinkageError() }, { expectUnreached() }) // Unreached because RxJava bubbles up fatal exceptions, causing `onNext` to throw. latch.await() finish(5) } @Test fun testExceptionFromSubscribe() = withExceptionHandler({ expectUnreached() }) { rxObservable(Dispatchers.Unconfined) { expect(1) send(Unit) }.subscribe({ expect(2) throw TestException() }, { expect(3) }) finish(4) } @Test fun testAsynchronousExceptionFromSubscribe() = withExceptionHandler({ expectUnreached() }) { rxObservable(Dispatchers.Unconfined) { expect(1) send(Unit) }.publish() .refCount() .subscribe({ expect(2) throw RuntimeException() }, { expect(3) }) finish(4) } @Test fun testAsynchronousFatalExceptionFromSubscribe() = withExceptionHandler(handler<LinkageError>(3)) { rxObservable(Dispatchers.Unconfined) { expect(1) send(Unit) }.publish() .refCount() .subscribe({ expect(2) throw LinkageError() }, { expectUnreached() }) // Unreached because RxJava bubbles up fatal exceptions, causing `onNext` to throw. finish(4) } }
apache-2.0
ca7de0a37100ea6fcee8df3c3108043c
28.804196
121
0.564993
5.008226
false
true
false
false
meowy/komrade
src/main/kotlin/pounces/komrade/api/TelegramBase.kt
1
7684
package pounces.komrade.api import com.google.common.cache.CacheBuilder import com.google.common.cache.CacheLoader import com.google.common.util.concurrent.RateLimiter import com.squareup.okhttp.RequestBody import pounces.komrade.api.data.* import rx.Observable import java.util.concurrent.TimeUnit open class TelegramBase constructor(val api: TelegramApi) { private val globalSendRateLimiter = RateLimiter.create(Constants.GLOBAL_MESSAGES_PER_SECOND) private val perChatRateLimiters = CacheBuilder.newBuilder() .expireAfterAccess(10, TimeUnit.SECONDS) .build(object : CacheLoader<String, RateLimiter>() { override fun load(key: String): RateLimiter = RateLimiter.create(Constants.MESSAGES_PER_CHAT_PER_SECOND) }) private fun <T> throttle(chatId: Any, func: () -> T): T { globalSendRateLimiter.acquire() perChatRateLimiters.get(chatId.toString()).acquire() return func() } fun getUpdates( offset: Int? = null, limit: Int? = null, timeout: Int? = null ): Observable<Response<List<Update>>> = api.getUpdates(offset, limit, timeout) fun setWebhook( url: String = "", certificate: String? = null ): Observable<Response<Boolean>> { return if (certificate != null) { api.setWebhook(url, certificate) } else { api.setWebhook(url) } } fun getMe(): Observable<Response<User>> = api.apiGetMe(); fun sendMessage( chatId: Any, text: String, parseMode: String? = null, disableWebPagePreview: Boolean? = null, replyToMessageId: Int? = null, replyMarkup: ReplyMarkup? = null ): Observable<Response<Message>> = throttle(chatId) { api.sendMessage(chatId.toString(), text, parseMode, disableWebPagePreview, replyToMessageId, replyMarkup) } // Kotlin slash Java's type safety + "Integer or String" as type for an API request -> // either an awful amount of overloads, or ignoring type safety. fun forwardMessage( chatId: Any, fromChatId: Any, messageId: Int ): Observable<Response<Message>> = throttle(chatId) { api.forwardMessage(chatId.toString(), fromChatId.toString(), messageId) } fun sendPhoto( chatId: Any, photo: RequestBody, caption: String? = null, replyToMessageId: Int? = null, replyMarkup: ReplyMarkup? = null ): Observable<Response<Message>> = throttle(chatId) { api.sendPhoto(chatId.toString(), photo, caption, replyToMessageId, replyMarkup) } fun sendPhoto( chatId: Any, photo: String, caption: String? = null, replyToMessageId: Int? = null, replyMarkup: ReplyMarkup? = null ): Observable<Response<Message>> = throttle(chatId) { api.sendPhoto(chatId.toString(), photo, caption, replyToMessageId, replyMarkup) } fun sendAudio( chatId: Any, audio: RequestBody, duration: Int? = null, performer: String? = null, title: String? = null, replyToMessageId: Int? = null, replyMarkup: ReplyMarkup? = null ): Observable<Response<Message>> = throttle(chatId) { api.sendAudio(chatId.toString(), audio, duration, performer, title, replyToMessageId, replyMarkup) } fun sendAudio( chatId: Any, audio: String, duration: Int? = null, performer: String? = null, title: String? = null, replyToMessageId: Int? = null, replyMarkup: ReplyMarkup? = null ): Observable<Response<Message>> = throttle(chatId) { api.sendAudio(chatId.toString(), audio, duration, performer, title, replyToMessageId, replyMarkup) } fun sendDocument( chatId: Any, duration: RequestBody, replyToMessageId: Int? = null, replyMarkup: ReplyMarkup? = null ): Observable<Response<Message>> = throttle(chatId) { api.sendDocument(chatId.toString(), duration, replyToMessageId, replyMarkup) } fun sendDocument( chatId: Any, duration: String, replyToMessageId: Int? = null, replyMarkup: ReplyMarkup? = null ): Observable<Response<Message>> = throttle(chatId) { api.sendDocument(chatId.toString(), duration, replyToMessageId, replyMarkup) } fun sendSticker( chatId: Any, sticker: RequestBody, replyToMessageId: Int? = null, replyMarkup: ReplyMarkup? = null ): Observable<Response<Message>> = throttle(chatId) { api.sendSticker(chatId.toString(), sticker, replyToMessageId, replyMarkup) } fun sendSticker( chatId: Any, sticker: String, replyToMessageId: Int? = null, replyMarkup: ReplyMarkup? = null ): Observable<Response<Message>> = throttle(chatId) { api.sendSticker(chatId.toString(), sticker, replyToMessageId, replyMarkup) } fun sendVideo( chatId: Any, video: RequestBody, duration: Int? = null, caption: String? = null, replyToMessageId: Int? = null, replyMarkup: ReplyMarkup? = null ): Observable<Response<Message>> = throttle(chatId) { api.sendVideo(chatId.toString(), video, duration, caption, replyToMessageId, replyMarkup) } fun sendVideo( chatId: Any, video: String, duration: Int? = null, caption: String? = null, replyToMessageId: Int? = null, replyMarkup: ReplyMarkup? = null ): Observable<Response<Message>> = throttle(chatId) { api.sendVideo(chatId.toString(), video, duration, caption, replyToMessageId, replyMarkup) } fun sendVoice( chatId: Any, voice: RequestBody, duration: Int? = null, replyToMessageId: Int? = null, replyMarkup: ReplyMarkup? = null ): Observable<Response<Message>> = throttle(chatId) { api.sendVoice(chatId.toString(), voice, duration, replyToMessageId, replyMarkup) } fun sendVoice( chatId: Any, voice: String, duration: Int? = null, replyToMessageId: Int? = null, replyMarkup: ReplyMarkup? = null ): Observable<Response<Message>> = throttle(chatId) { api.sendVoice(chatId.toString(), voice, duration, replyToMessageId, replyMarkup) } fun sendLocation( chatId: Any, latitude: Float, longitude: Float, replyToMessageId: Int? = null, replyMarkup: ReplyMarkup? = null ): Observable<Response<Message>> = throttle(chatId) { api.sendLocation(chatId.toString(), latitude, longitude, replyToMessageId, replyMarkup) } fun sendChatAction( chatId: Any, action: String ): Observable<Response<Unit>> = throttle(chatId) { api.sendChatAction(chatId.toString(), action) } fun getUserProfilePhotos( userId: Int, offset: Int? = null, limit: Int? = null ): Observable<Response<UserProfilePhotos>> = api.getUserProfilePhotos(userId, offset, limit) fun getFile( fileId: String ): Observable<Response<File>> = api.getFile(fileId) }
mit
07249c537742e773d9c47095eaf2d491
36.852217
138
0.594872
4.626129
false
false
false
false
anthonycr/Lightning-Browser
app/src/main/java/acr/browser/lightning/browser/tab/TabWebChromeClient.kt
1
9709
package acr.browser.lightning.browser.tab import acr.browser.lightning.R import acr.browser.lightning.browser.di.DiskScheduler import acr.browser.lightning.dialog.BrowserDialog import acr.browser.lightning.dialog.DialogItem import acr.browser.lightning.extensions.color import acr.browser.lightning.extensions.resizeAndShow import acr.browser.lightning.favicon.FaviconModel import acr.browser.lightning.preference.UserPreferences import acr.browser.lightning.utils.Option import acr.browser.lightning.utils.Utils import acr.browser.lightning.browser.webrtc.WebRtcPermissionsModel import acr.browser.lightning.browser.webrtc.WebRtcPermissionsView import android.Manifest import android.app.Activity import android.content.Intent import android.graphics.Bitmap import android.graphics.Color import android.net.Uri import android.os.Message import android.view.View import android.webkit.GeolocationPermissions import android.webkit.PermissionRequest import android.webkit.ValueCallback import android.webkit.WebChromeClient import android.webkit.WebView import androidx.activity.result.ActivityResult import androidx.appcompat.app.AlertDialog import androidx.palette.graphics.Palette import com.anthonycr.grant.PermissionsManager import com.anthonycr.grant.PermissionsResultAction import io.reactivex.Scheduler import io.reactivex.subjects.BehaviorSubject import io.reactivex.subjects.PublishSubject import javax.inject.Inject /** * A [WebChromeClient] that supports the tab adaptation. */ class TabWebChromeClient @Inject constructor( private val activity: Activity, private val faviconModel: FaviconModel, @DiskScheduler private val diskScheduler: Scheduler, private val userPreferences: UserPreferences, private val webRtcPermissionsModel: WebRtcPermissionsModel ) : WebChromeClient(), WebRtcPermissionsView { private val defaultColor = activity.color(R.color.primary_color) private val geoLocationPermissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION) /** * Emits changes to the page loading progress. */ val progressObservable: PublishSubject<Int> = PublishSubject.create() /** * Emits changes to the page title. */ val titleObservable: PublishSubject<String> = PublishSubject.create() /** * Emits changes to the page favicon. Always emits the last emitted favicon. */ val faviconObservable: BehaviorSubject<Option<Bitmap>> = BehaviorSubject.create() /** * Emits create window requests. */ val createWindowObservable: PublishSubject<TabInitializer> = PublishSubject.create() /** * Emits close window requests. */ val closeWindowObservable: PublishSubject<Unit> = PublishSubject.create() /** * Emits changes to the thematic color of the current page. */ val colorChangeObservable: BehaviorSubject<Int> = BehaviorSubject.createDefault(defaultColor) /** * Emits requests to open the file chooser for upload. */ val fileChooserObservable: PublishSubject<Intent> = PublishSubject.create() /** * Emits requests to show a custom view (i.e. full screen video). */ val showCustomViewObservable: PublishSubject<View> = PublishSubject.create() /** * Emits requests to hide the custom view that was shown prior. */ val hideCustomViewObservable: PublishSubject<Unit> = PublishSubject.create() private var filePathCallback: ValueCallback<Array<Uri>>? = null private var customViewCallback: CustomViewCallback? = null /** * Handle the [activityResult] that was returned by the file chooser. */ fun onResult(activityResult: ActivityResult) { val resultCode = activityResult.resultCode val intent = activityResult.data val result = FileChooserParams.parseResult(resultCode, intent) filePathCallback?.onReceiveValue(result) filePathCallback = null } /** * Notify the client that we have manually hidden the custom view. */ fun hideCustomView() { customViewCallback?.onCustomViewHidden() customViewCallback = null } override fun onCreateWindow( view: WebView, isDialog: Boolean, isUserGesture: Boolean, resultMsg: Message ): Boolean { createWindowObservable.onNext(ResultMessageInitializer(resultMsg)) return true } override fun onCloseWindow(window: WebView) { closeWindowObservable.onNext(Unit) } override fun onProgressChanged(view: WebView, newProgress: Int) { progressObservable.onNext(newProgress) } override fun onReceivedTitle(view: WebView, title: String) { titleObservable.onNext(title) faviconObservable.onNext(Option.None) generateColorAndPropagate(null) } override fun onReceivedIcon(view: WebView, icon: Bitmap) { faviconObservable.onNext(Option.Some(icon)) val url = view.url ?: return faviconModel.cacheFaviconForUrl(icon, url) .subscribeOn(diskScheduler) .subscribe() generateColorAndPropagate(icon) } private fun generateColorAndPropagate(favicon: Bitmap?) { val icon = favicon ?: return run { colorChangeObservable.onNext(defaultColor) } Palette.from(icon).generate { palette -> // OR with opaque black to remove transparency glitches val color = Color.BLACK or (palette?.getDominantColor(defaultColor) ?: defaultColor) // Lighten up the dark color if it is too dark val finalColor = if (Utils.isColorTooDark(color)) { Utils.mixTwoColors(defaultColor, color, 0.25f) } else { color } colorChangeObservable.onNext(finalColor) } } override fun onShowFileChooser( webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams ): Boolean { // Ensure that previously set callbacks are resolved. this.filePathCallback?.onReceiveValue(null) this.filePathCallback = null this.filePathCallback = filePathCallback fileChooserParams.createIntent().let(fileChooserObservable::onNext) return true } override fun onShowCustomView(view: View, callback: CustomViewCallback) { customViewCallback = callback showCustomViewObservable.onNext(view) } override fun onHideCustomView() { hideCustomViewObservable.onNext(Unit) customViewCallback = null } override fun requestPermissions(permissions: Set<String>, onGrant: (Boolean) -> Unit) { val missingPermissions = permissions .filter { PermissionsManager.getInstance().hasPermission(activity, it) } if (missingPermissions.isEmpty()) { onGrant(true) } else { PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult( activity, missingPermissions.toTypedArray(), object : PermissionsResultAction() { override fun onGranted() = onGrant(true) override fun onDenied(permission: String?) = onGrant(false) } ) } } override fun requestResources( source: String, resources: Array<String>, onGrant: (Boolean) -> Unit ) { activity.runOnUiThread { val resourcesString = resources.joinToString(separator = "\n") BrowserDialog.showPositiveNegativeDialog( activity = activity, title = R.string.title_permission_request, message = R.string.message_permission_request, messageArguments = arrayOf(source, resourcesString), positiveButton = DialogItem(title = R.string.action_allow) { onGrant(true) }, negativeButton = DialogItem(title = R.string.action_dont_allow) { onGrant(false) }, onCancel = { onGrant(false) } ) } } override fun onPermissionRequest(request: PermissionRequest) { if (userPreferences.webRtcEnabled) { webRtcPermissionsModel.requestPermission(request, this) } else { request.deny() } } override fun onGeolocationPermissionsShowPrompt( origin: String, callback: GeolocationPermissions.Callback ) = PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult( activity, geoLocationPermissions, object : PermissionsResultAction() { override fun onGranted() { val remember = true AlertDialog.Builder(activity).apply { setTitle(activity.getString(R.string.location)) val org = if (origin.length > 50) { "${origin.subSequence(0, 50)}..." } else { origin } setMessage(org + activity.getString(R.string.message_location)) setCancelable(true) setPositiveButton(activity.getString(R.string.action_allow)) { _, _ -> callback.invoke(origin, true, remember) } setNegativeButton(activity.getString(R.string.action_dont_allow)) { _, _ -> callback.invoke(origin, false, remember) } }.resizeAndShow() } //TODO show message and/or turn off setting override fun onDenied(permission: String) = Unit }) }
mpl-2.0
e9147a3a82441ab1a180b093ef3d37e9
34.694853
99
0.666289
5.080586
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/properties/getDelegate/overrideDelegatedByDelegated.kt
2
1063
// IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.reflect.KProperty import kotlin.reflect.jvm.isAccessible import kotlin.test.* class Delegate(val value: String) { operator fun getValue(instance: Any?, property: KProperty<*>) = value } open class Base { open val x: String by Delegate("Base") } class Derived : Base() { override val x: String by Delegate("Derived") } fun check(expected: String, delegate: Any?) { if (delegate == null) throw AssertionError("getDelegate returned null") assertEquals(expected, (delegate as Delegate).value) } fun box(): String { val base = Base() val derived = Derived() check("Base", (Base::x).apply { isAccessible = true }.getDelegate(base)) check("Base", (base::x).apply { isAccessible = true }.getDelegate()) check("Derived", (Derived::x).apply { isAccessible = true }.getDelegate(derived)) check("Derived", (derived::x).apply { isAccessible = true }.getDelegate()) check("Base", (Base::x).apply { isAccessible = true }.getDelegate(derived)) return "OK" }
apache-2.0
e6d06665976b0fd8c57ae808c56253dd
27.72973
85
0.678269
3.951673
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/ranges/literal/maxValueToMaxValue.kt
2
1913
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS // TODO: muted automatically, investigate should it be ran for NATIVE or not // IGNORE_BACKEND: NATIVE // Auto-generated by org.jetbrains.kotlin.generators.tests.GenerateRangesCodegenTestData. DO NOT EDIT! // WITH_RUNTIME import java.lang.Integer.MAX_VALUE as MaxI import java.lang.Integer.MIN_VALUE as MinI import java.lang.Byte.MAX_VALUE as MaxB import java.lang.Byte.MIN_VALUE as MinB import java.lang.Short.MAX_VALUE as MaxS import java.lang.Short.MIN_VALUE as MinS import java.lang.Long.MAX_VALUE as MaxL import java.lang.Long.MIN_VALUE as MinL import java.lang.Character.MAX_VALUE as MaxC import java.lang.Character.MIN_VALUE as MinC fun box(): String { val list1 = ArrayList<Int>() for (i in MaxI..MaxI) { list1.add(i) if (list1.size > 23) break } if (list1 != listOf<Int>(MaxI)) { return "Wrong elements for MaxI..MaxI: $list1" } val list2 = ArrayList<Int>() for (i in MaxB..MaxB) { list2.add(i) if (list2.size > 23) break } if (list2 != listOf<Int>(MaxB.toInt())) { return "Wrong elements for MaxB..MaxB: $list2" } val list3 = ArrayList<Int>() for (i in MaxS..MaxS) { list3.add(i) if (list3.size > 23) break } if (list3 != listOf<Int>(MaxS.toInt())) { return "Wrong elements for MaxS..MaxS: $list3" } val list4 = ArrayList<Long>() for (i in MaxL..MaxL) { list4.add(i) if (list4.size > 23) break } if (list4 != listOf<Long>(MaxL)) { return "Wrong elements for MaxL..MaxL: $list4" } val list5 = ArrayList<Char>() for (i in MaxC..MaxC) { list5.add(i) if (list5.size > 23) break } if (list5 != listOf<Char>(MaxC)) { return "Wrong elements for MaxC..MaxC: $list5" } return "OK" }
apache-2.0
76089eb1a2ecd41db55529dd1be270d6
26.724638
102
0.626764
3.231419
false
false
false
false
chromeos/video-composition-sample
VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/media/encoder/Muxer.kt
1
1986
/* * Copyright (c) 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 * * 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 dev.chromeos.videocompositionsample.presentation.media.encoder import android.media.MediaCodec import android.media.MediaFormat import android.media.MediaMuxer import java.io.File import java.nio.ByteBuffer class Muxer(outputFile: File, outputFormat: Int, private val totalTracks: Int) { private lateinit var muxer: MediaMuxer private var trackCounter = 0 var isStarted = false private val isReadyToStart: Boolean get() = trackCounter == totalTracks init { try { muxer = MediaMuxer(outputFile.toString(), outputFormat) } catch (e: Exception) { e.printStackTrace() } } @Synchronized fun addTrack(format: MediaFormat): Int { val trackIndex = muxer.addTrack(format) trackCounter++ if (isReadyToStart) { muxer.start() isStarted = true } return trackIndex } @Synchronized fun writeSampleData(trackIndex: Int, byteBuf: ByteBuffer, bufferInfo: MediaCodec.BufferInfo) { muxer.writeSampleData(trackIndex, byteBuf, bufferInfo) } @Synchronized fun release() { if (isStarted) { isStarted = false try { muxer.stop() muxer.release() trackCounter = 0 } catch (e: Exception) { } } } }
apache-2.0
aea7506bbc88d08f4c7248c6e1701161
27.385714
98
0.645519
4.462921
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/coroutines/noSuspensionPoints.kt
2
490
// WITH_RUNTIME // WITH_COROUTINES import helpers.* import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* fun builder(c: suspend () -> Int): Int { var res = 0 c.startCoroutine(handleResultContinuation { res = it }) return res } fun box(): String { var result = "" val handledResult = builder { result = "OK" 56 } if (handledResult != 56) return "fail 1: $handledResult" return result }
apache-2.0
f68b82a2c06c995ef95ef4786665cf44
16.5
60
0.626531
4.049587
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveValVarFromParameterFix.kt
2
1590
// 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.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtValVarKeywordOwner import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext class RemoveValVarFromParameterFix(element: KtValVarKeywordOwner) : KotlinQuickFixAction<KtValVarKeywordOwner>(element) { private val varOrVal: String init { val valOrVarNode = element.valOrVarKeyword ?: throw AssertionError("Val or var node not found for " + element.getElementTextWithContext()) varOrVal = valOrVarNode.text } override fun getFamilyName() = KotlinBundle.message("remove.val.var.from.parameter") override fun getText(): String { val element = element ?: return "" val varOrVal = element.valOrVarKeyword?.text ?: return familyName return KotlinBundle.message("remove.0.from.parameter", varOrVal) } override fun invoke(project: Project, editor: Editor?, file: KtFile) { element?.valOrVarKeyword?.delete() } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic) = RemoveValVarFromParameterFix(diagnostic.psiElement.parent as KtValVarKeywordOwner) } }
apache-2.0
a84c3590c78c607861288a311fb68440
40.842105
158
0.753459
4.760479
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceTypeAlias/ui/IntroduceTypeAliasParameterTablePanel.kt
6
1321
// 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.refactoring.introduce.introduceTypeAlias.ui import org.jetbrains.kotlin.idea.refactoring.introduce.introduceTypeAlias.TypeParameter import org.jetbrains.kotlin.idea.refactoring.introduce.ui.AbstractParameterTablePanel open class IntroduceTypeAliasParameterTablePanel : AbstractParameterTablePanel<TypeParameter, IntroduceTypeAliasParameterTablePanel.TypeParameterInfo>() { class TypeParameterInfo( originalParameter: TypeParameter ) : AbstractParameterTablePanel.AbstractParameterInfo<TypeParameter>(originalParameter) { init { name = originalParameter.name } override fun toParameter() = originalParameter.copy(name) } fun init(parameters: List<TypeParameter>) { parameterInfos = parameters.mapTo(ArrayList(), ::TypeParameterInfo) super.init() } override fun isCheckMarkColumnEditable() = false val selectedTypeParameterInfos: List<TypeParameterInfo> get() = parameterInfos.filter { it.isEnabled } val selectedTypeParameters: List<TypeParameter> get() = selectedTypeParameterInfos.map { it.toParameter() } }
apache-2.0
549cc2363b0c1c8ecf9face79096d548
40.3125
158
0.76003
5.080769
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/frontend/api/fir/utils/EnclosingDeclarationContext.kt
2
4215
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.frontend.api.fir.utils import com.intellij.psi.util.parentsOfType import org.jetbrains.kotlin.fir.declarations.FirFile import org.jetbrains.kotlin.idea.fir.low.level.api.api.FirModuleResolveState import org.jetbrains.kotlin.idea.fir.low.level.api.api.LowLevelFirApiFacadeForCompletion import org.jetbrains.kotlin.idea.fir.low.level.api.util.originalDeclaration import org.jetbrains.kotlin.idea.util.getElementTextInContext import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType internal sealed class EnclosingDeclarationContext { companion object { fun detect(originalFile: KtFile, positionInFakeFile: KtElement): EnclosingDeclarationContext { val fakeFunction = positionInFakeFile.getNonStrictParentOfType<KtNamedFunction>() if (fakeFunction != null) { val originalFunction = originalFile.findDeclarationOfTypeAt<KtNamedFunction>(fakeFunction.textOffset) ?: error("Cannot find original function matching to ${fakeFunction.getElementTextInContext()} in $originalFile") recordOriginalDeclaration(originalFunction, fakeFunction) return FunctionContext(fakeFunction, originalFunction) } val fakeProperty = positionInFakeFile.parentsOfType<KtProperty>().firstOrNull { !it.isLocal } if (fakeProperty != null) { val originalProperty = originalFile.findDeclarationOfTypeAt<KtProperty>(fakeProperty.textOffset) ?: error("Cannot find original property matching to ${fakeProperty.getElementTextInContext()} in $originalFile") recordOriginalDeclaration(originalProperty, fakeProperty) return PropertyContext(fakeProperty, originalProperty) } error("Cannot find enclosing declaration for ${positionInFakeFile.getElementTextInContext()}") } private fun recordOriginalDeclaration(originalDeclaration: KtNamedDeclaration, fakeDeclaration: KtNamedDeclaration) { require(!fakeDeclaration.isPhysical) require(originalDeclaration.containingKtFile !== fakeDeclaration.containingKtFile) val originalDeclrationParents = originalDeclaration.parentsOfType<KtDeclaration>().toList() val fakeDeclarationParents = fakeDeclaration.parentsOfType<KtDeclaration>().toList() originalDeclrationParents.zip(fakeDeclarationParents) { original, fake -> fake.originalDeclaration = original } } } } internal class FunctionContext( val fakeEnclosingFunction: KtNamedFunction, val originalEnclosingFunction: KtNamedFunction ) : EnclosingDeclarationContext() internal class PropertyContext( val fakeEnclosingProperty: KtProperty, val originalEnclosingProperty: KtProperty ) : EnclosingDeclarationContext() internal val EnclosingDeclarationContext.fakeEnclosingDeclaration: KtCallableDeclaration get() = when (this) { is FunctionContext -> fakeEnclosingFunction is PropertyContext -> fakeEnclosingProperty } internal fun EnclosingDeclarationContext.recordCompletionContext(originalFirFile: FirFile, firResolveState: FirModuleResolveState) { when (this) { is FunctionContext -> LowLevelFirApiFacadeForCompletion.recordCompletionContextForFunction( originalFirFile, fakeEnclosingFunction, originalEnclosingFunction, state = firResolveState ) is PropertyContext -> LowLevelFirApiFacadeForCompletion.recordCompletionContextForProperty( originalFirFile, fakeEnclosingProperty, originalEnclosingProperty, state = firResolveState ) } } private inline fun <reified T : KtElement> KtFile.findDeclarationOfTypeAt(offset: Int): T? = findElementAt(offset) ?.getNonStrictParentOfType<T>() ?.takeIf { it.textOffset == offset }
apache-2.0
94836187baf86901c8d2347253a76925
46.359551
132
0.732859
5.403846
false
false
false
false
kickstarter/android-oss
app/src/test/java/com/kickstarter/models/ShippingRulesEnvelopeTest.kt
1
1902
package com.kickstarter.models import com.kickstarter.KSRobolectricTestCase import com.kickstarter.mock.factories.ShippingRuleFactory import com.kickstarter.mock.factories.ShippingRulesEnvelopeFactory import com.kickstarter.services.apiresponses.ShippingRulesEnvelope import org.junit.Test class ShippingRulesEnvelopeTest : KSRobolectricTestCase() { @Test fun testDefaultInit() { val shippingRulesList = listOf( ShippingRuleFactory.usShippingRule(), ShippingRuleFactory.germanyShippingRule(), ShippingRuleFactory.mexicoShippingRule() ) val shippingRulesEnvelope = ShippingRulesEnvelope.builder() .shippingRules( shippingRulesList ) .build() assertEquals(shippingRulesEnvelope.shippingRules(), shippingRulesList) } @Test fun testDefaultToBuilder() { val shippingRulesList = listOf( ShippingRuleFactory.usShippingRule(), ShippingRuleFactory.germanyShippingRule(), ShippingRuleFactory.mexicoShippingRule() ) val shippingRulesEnvelope = ShippingRulesEnvelope.builder().build().toBuilder().shippingRules(shippingRulesList).build() assertEquals(shippingRulesEnvelope.shippingRules(), shippingRulesList) } @Test fun testShippingRulesEnvelope_equalFalse() { val shippingRulesEnvelope = ShippingRulesEnvelope.builder().build() val shippingRulesEnvelope2 = ShippingRulesEnvelopeFactory.shippingRules() assertFalse(shippingRulesEnvelope == shippingRulesEnvelope2) } @Test fun testShippingRulesEnvelope_equalTrue() { val shippingRulesEnvelope1 = ShippingRulesEnvelope.builder().build() val shippingRulesEnvelope2 = ShippingRulesEnvelope.builder().build() assertEquals(shippingRulesEnvelope1, shippingRulesEnvelope2) } }
apache-2.0
32b29acc012c29355ad5664fafedee79
34.222222
128
0.722397
6.65035
false
true
false
false
tensorflow/examples
lite/examples/object_detection/android/app/src/main/java/org/tensorflow/lite/examples/objectdetection/OverlayView.kt
1
3979
/* * Copyright 2022 The TensorFlow Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tensorflow.lite.examples.objectdetection import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Rect import android.graphics.RectF import android.util.AttributeSet import android.view.View import androidx.core.content.ContextCompat import java.util.LinkedList import kotlin.math.max import org.tensorflow.lite.task.vision.detector.Detection class OverlayView(context: Context?, attrs: AttributeSet?) : View(context, attrs) { private var results: List<Detection> = LinkedList<Detection>() private var boxPaint = Paint() private var textBackgroundPaint = Paint() private var textPaint = Paint() private var scaleFactor: Float = 1f private var bounds = Rect() init { initPaints() } fun clear() { textPaint.reset() textBackgroundPaint.reset() boxPaint.reset() invalidate() initPaints() } private fun initPaints() { textBackgroundPaint.color = Color.BLACK textBackgroundPaint.style = Paint.Style.FILL textBackgroundPaint.textSize = 50f textPaint.color = Color.WHITE textPaint.style = Paint.Style.FILL textPaint.textSize = 50f boxPaint.color = ContextCompat.getColor(context!!, R.color.bounding_box_color) boxPaint.strokeWidth = 8F boxPaint.style = Paint.Style.STROKE } override fun draw(canvas: Canvas) { super.draw(canvas) for (result in results) { val boundingBox = result.boundingBox val top = boundingBox.top * scaleFactor val bottom = boundingBox.bottom * scaleFactor val left = boundingBox.left * scaleFactor val right = boundingBox.right * scaleFactor // Draw bounding box around detected objects val drawableRect = RectF(left, top, right, bottom) canvas.drawRect(drawableRect, boxPaint) // Create text to display alongside detected objects val drawableText = result.categories[0].label + " " + String.format("%.2f", result.categories[0].score) // Draw rect behind display text textBackgroundPaint.getTextBounds(drawableText, 0, drawableText.length, bounds) val textWidth = bounds.width() val textHeight = bounds.height() canvas.drawRect( left, top, left + textWidth + Companion.BOUNDING_RECT_TEXT_PADDING, top + textHeight + Companion.BOUNDING_RECT_TEXT_PADDING, textBackgroundPaint ) // Draw text for detected object canvas.drawText(drawableText, left, top + bounds.height(), textPaint) } } fun setResults( detectionResults: MutableList<Detection>, imageHeight: Int, imageWidth: Int, ) { results = detectionResults // PreviewView is in FILL_START mode. So we need to scale up the bounding box to match with // the size that the captured images will be displayed. scaleFactor = max(width * 1f / imageWidth, height * 1f / imageHeight) } companion object { private const val BOUNDING_RECT_TEXT_PADDING = 8 } }
apache-2.0
00eddea983092afe041b2c0c14ea657f
31.884298
99
0.655944
4.720047
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceCollectionCountWithSizeInspection.kt
2
2401
// 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.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.inspections.collections.isCalling import org.jetbrains.kotlin.idea.inspections.collections.receiverType import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.callExpressionVisitor import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class ReplaceCollectionCountWithSizeInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return callExpressionVisitor(fun(callExpression: KtCallExpression) { if (callExpression.calleeExpression?.text != "count" || callExpression.valueArguments.isNotEmpty()) return val context = callExpression.analyze(BodyResolveMode.PARTIAL) if (!callExpression.isCalling(FqName("kotlin.collections.count"))) return val receiverType = callExpression.receiverType(context) ?: return if (KotlinBuiltIns.isIterableOrNullableIterable(receiverType)) return holder.registerProblem( callExpression, KotlinBundle.message("could.be.replaced.with.size"), ReplaceCollectionCountWithSizeQuickFix() ) }) } } class ReplaceCollectionCountWithSizeQuickFix : LocalQuickFix { override fun getName() = KotlinBundle.message("replace.collection.count.with.size.quick.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as KtCallExpression element.replace(KtPsiFactory(element).createExpression("size")) } }
apache-2.0
ba0dfcc8858039cc0dba2bd42c201d1a
48
120
0.778426
5.086864
false
false
false
false
siosio/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/run/configuration/MavenDistributionsInfo.kt
1
4113
// 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.idea.maven.execution.run.configuration import com.intellij.ide.util.BrowseFilesListener import com.intellij.openapi.externalSystem.service.ui.distribution.AbstractDistributionInfo import com.intellij.openapi.externalSystem.service.ui.distribution.DistributionInfo import com.intellij.openapi.externalSystem.service.ui.distribution.DistributionsInfo import com.intellij.openapi.externalSystem.service.ui.distribution.LocalDistributionInfo import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.util.io.FileUtil import com.intellij.util.containers.addIfNotNull import com.intellij.util.ui.JBUI import org.jetbrains.idea.maven.project.MavenConfigurableBundle import org.jetbrains.idea.maven.project.MavenProjectBundle import org.jetbrains.idea.maven.server.MavenServerManager import org.jetbrains.idea.maven.utils.MavenUtil class MavenDistributionsInfo : DistributionsInfo { override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.distribution.name") override val settingsHint: String = MavenConfigurableBundle.message("maven.run.configuration.distribution.hint") override val comboBoxPreferredWidth: Int = JBUI.scale(120) override val comboBoxActionName: String = MavenConfigurableBundle.message("maven.run.configuration.specify.distribution.action.name") override val fileChooserTitle: String = MavenProjectBundle.message("maven.select.maven.home.directory") override val fileChooserDescription: String? = null override val fileChooserDescriptor: FileChooserDescriptor = BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR override val distributions: List<DistributionInfo> by lazy { ArrayList<DistributionInfo>().apply { addIfNotNull(asDistributionInfo(MavenServerManager.BUNDLED_MAVEN_3)) addIfNotNull(asDistributionInfo(MavenServerManager.WRAPPED_MAVEN)) val mavenHomeDirectory = MavenUtil.resolveMavenHomeDirectory(null) val bundledMavenHomeDirectory = MavenUtil.resolveMavenHomeDirectory(MavenServerManager.BUNDLED_MAVEN_3) if (mavenHomeDirectory != null && !FileUtil.filesEqual(mavenHomeDirectory, bundledMavenHomeDirectory)) { addIfNotNull(asDistributionInfo(mavenHomeDirectory.path)) } } } open class BundledDistributionInfo(version: String) : AbstractDistributionInfo() { override val name: String = MavenConfigurableBundle.message("maven.run.configuration.bundled.distribution.name", version) override val description: String = MavenConfigurableBundle.message("maven.run.configuration.bundled.distribution.description") } class Bundled2DistributionInfo(version: String?) : BundledDistributionInfo(version ?: "2") class Bundled3DistributionInfo(version: String?) : BundledDistributionInfo(version ?: "3") class WrappedDistributionInfo : AbstractDistributionInfo() { override val name: String = MavenProjectBundle.message("maven.wrapper.version.title") override val description: String? = null } companion object { fun asDistributionInfo(mavenHome: String): DistributionInfo { val version = MavenServerManager.getMavenVersion(mavenHome) return when (mavenHome) { MavenServerManager.BUNDLED_MAVEN_2 -> Bundled2DistributionInfo(version) MavenServerManager.BUNDLED_MAVEN_3 -> Bundled3DistributionInfo(version) MavenServerManager.WRAPPED_MAVEN -> WrappedDistributionInfo() else -> LocalDistributionInfo(mavenHome) } } fun asMavenHome(distribution: DistributionInfo): String { return when (distribution) { is Bundled2DistributionInfo -> MavenServerManager.BUNDLED_MAVEN_2 is Bundled3DistributionInfo -> MavenServerManager.BUNDLED_MAVEN_3 is WrappedDistributionInfo -> MavenServerManager.WRAPPED_MAVEN is LocalDistributionInfo -> distribution.path else -> throw NoWhenBranchMatchedException(distribution.javaClass.toString()) } } } }
apache-2.0
9e7858947cdd95b160646bfaec7ed89d
53.853333
158
0.799173
5.102978
false
true
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderSettingsDialog.kt
2
3743
package eu.kanade.tachiyomi.ui.reader import android.app.Dialog import android.os.Bundle import android.support.v4.app.DialogFragment import android.view.View import com.afollestad.materialdialogs.MaterialDialog import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.util.plusAssign import eu.kanade.tachiyomi.widget.IgnoreFirstSpinnerListener import kotlinx.android.synthetic.main.dialog_reader_settings.view.* import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.subscriptions.CompositeSubscription import uy.kohesive.injekt.injectLazy import java.util.concurrent.TimeUnit.MILLISECONDS class ReaderSettingsDialog : DialogFragment() { private val preferences by injectLazy<PreferencesHelper>() private lateinit var subscriptions: CompositeSubscription override fun onCreateDialog(savedState: Bundle?): Dialog { val dialog = MaterialDialog.Builder(activity) .title(R.string.label_settings) .customView(R.layout.dialog_reader_settings, true) .positiveText(android.R.string.ok) .build() subscriptions = CompositeSubscription() onViewCreated(dialog.view, savedState) return dialog } override fun onViewCreated(view: View, savedState: Bundle?) = with(view) { viewer.onItemSelectedListener = IgnoreFirstSpinnerListener { position -> subscriptions += Observable.timer(250, MILLISECONDS, AndroidSchedulers.mainThread()) .subscribe { (activity as ReaderActivity).presenter.updateMangaViewer(position) activity.recreate() } } viewer.setSelection((activity as ReaderActivity).presenter.manga.viewer, false) rotation_mode.onItemSelectedListener = IgnoreFirstSpinnerListener { position -> subscriptions += Observable.timer(250, MILLISECONDS) .subscribe { preferences.rotation().set(position + 1) } } rotation_mode.setSelection(preferences.rotation().getOrDefault() - 1, false) scale_type.onItemSelectedListener = IgnoreFirstSpinnerListener { position -> preferences.imageScaleType().set(position + 1) } scale_type.setSelection(preferences.imageScaleType().getOrDefault() - 1, false) zoom_start.onItemSelectedListener = IgnoreFirstSpinnerListener { position -> preferences.zoomStart().set(position + 1) } zoom_start.setSelection(preferences.zoomStart().getOrDefault() - 1, false) image_decoder.onItemSelectedListener = IgnoreFirstSpinnerListener { position -> preferences.imageDecoder().set(position) } image_decoder.setSelection(preferences.imageDecoder().getOrDefault(), false) background_color.onItemSelectedListener = IgnoreFirstSpinnerListener { position -> preferences.readerTheme().set(position) } background_color.setSelection(preferences.readerTheme().getOrDefault(), false) show_page_number.isChecked = preferences.showPageNumber().getOrDefault() show_page_number.setOnCheckedChangeListener { v, isChecked -> preferences.showPageNumber().set(isChecked) } fullscreen.isChecked = preferences.fullscreen().getOrDefault() fullscreen.setOnCheckedChangeListener { v, isChecked -> preferences.fullscreen().set(isChecked) } } override fun onDestroyView() { subscriptions.unsubscribe() super.onDestroyView() } }
gpl-3.0
0cefa11b18cf685b5a922523e523d0f4
39.258065
96
0.69276
5.3017
false
false
false
false
GunoH/intellij-community
plugins/eclipse/src/org/jetbrains/idea/eclipse/config/EmlFileLoader.kt
2
9970
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.eclipse.config import com.intellij.openapi.components.ExpandMacroToPathMap import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.workspaceModel.ide.toPath import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.addContentRootEntity import com.intellij.workspaceModel.storage.bridgeEntities.addJavaModuleSettingsEntity import com.intellij.workspaceModel.storage.bridgeEntities.addJavaSourceRootEntity import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.bridgeEntities.asJavaSourceRoot import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jdom.Element import org.jetbrains.idea.eclipse.IdeaXml import org.jetbrains.idea.eclipse.conversion.EPathUtil import org.jetbrains.idea.eclipse.conversion.IdeaSpecificSettings import org.jetbrains.jps.model.serialization.java.JpsJavaModelSerializerExtension import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer import org.jetbrains.jps.util.JpsPathUtil /** * Loads additional module configuration from *.eml file to [ModuleEntity] */ internal class EmlFileLoader( private val module: ModuleEntity, private val builder: MutableEntityStorage, private val expandMacroToPathMap: ExpandMacroToPathMap, private val virtualFileManager: VirtualFileUrlManager ) { fun loadEml(emlTag: Element, contentRoot: ContentRootEntity) { loadCustomJavaSettings(emlTag) loadContentEntries(emlTag, contentRoot) loadJdkSettings(emlTag) loadDependencies(emlTag) } private fun loadDependencies(emlTag: Element) { val moduleLibraries = module.dependencies.asSequence().filterIsInstance<ModuleDependencyItem.Exportable.LibraryDependency>() .mapNotNull { it.library.resolve(builder) } .filter { it.tableId is LibraryTableId.ModuleLibraryTableId } .associateBy { it.name } val libraryScopes = HashMap<String, ModuleDependencyItem.DependencyScope>() emlTag.getChildren("lib").forEach { libTag -> val name = libTag.getAttributeValue("name")!! libraryScopes[name] = libTag.getScope() val moduleLibrary = moduleLibraries[name] if (moduleLibrary != null) { loadModuleLibrary(libTag, moduleLibrary) } } val moduleScopes = emlTag.getChildren("module").associateBy( { it.getAttributeValue("name") }, { it.getScope() } ) builder.modifyEntity(module) { val result = mutableListOf<ModuleDependencyItem>() dependencies.mapTo(result) { dep -> when (dep) { is ModuleDependencyItem.Exportable.LibraryDependency -> libraryScopes[dep.library.name]?.let { dep.copy(scope = it) } ?: dep is ModuleDependencyItem.Exportable.ModuleDependency -> moduleScopes[dep.module.name]?.let { dep.copy(scope = it) } ?: dep else -> dep } } dependencies = result } } private fun Element.getScope(): ModuleDependencyItem.DependencyScope { return getAttributeValue("scope")?.let { try { ModuleDependencyItem.DependencyScope.valueOf(it) } catch (e: IllegalArgumentException) { null } } ?: ModuleDependencyItem.DependencyScope.COMPILE } private fun loadModuleLibrary(libTag: Element, library: LibraryEntity) { val eclipseSrcRoot = library.roots.firstOrNull { it.type.name == OrderRootType.SOURCES.name() } val rootsToRemove = HashSet<LibraryRoot>() val rootsToAdd = ArrayList<LibraryRoot>() libTag.getChildren(IdeaSpecificSettings.SRCROOT_ATTR).forEach { rootTag -> val url = rootTag.getAttributeValue("url") val bindAttribute = rootTag.getAttributeValue(IdeaSpecificSettings.SRCROOT_BIND_ATTR) if (bindAttribute != null && !bindAttribute.toBoolean()) { rootsToAdd.add(LibraryRoot(virtualFileManager.fromUrl(url!!), LibraryRootTypeId.SOURCES)) } else if (eclipseSrcRoot != null && url != eclipseSrcRoot.url.url && EPathUtil.areUrlsPointTheSame(url, eclipseSrcRoot.url.url)) { rootsToAdd.add(LibraryRoot(virtualFileManager.fromUrl(url!!), LibraryRootTypeId.SOURCES)) rootsToRemove.add(eclipseSrcRoot) } } libTag.getChildren(IdeaSpecificSettings.JAVADOCROOT_ATTR).mapTo(rootsToAdd) { LibraryRoot(virtualFileManager.fromUrl(it.getAttributeValue("url")!!), EclipseModuleRootsSerializer.JAVADOC_TYPE) } fun updateRoots(tagName: String, rootType: String) { libTag.getChildren(tagName).forEach { rootTag -> val root = expandMacroToPathMap.substitute(rootTag.getAttributeValue(IdeaSpecificSettings.PROJECT_RELATED)!!, SystemInfo.isFileSystemCaseSensitive) library.roots.forEach { libRoot -> if (libRoot !in rootsToRemove && libRoot.type.name == rootType && EPathUtil.areUrlsPointTheSame(root, libRoot.url.url)) { rootsToRemove.add(libRoot) rootsToAdd.add(LibraryRoot(virtualFileManager.fromUrl(root), LibraryRootTypeId(rootType))) } } } } updateRoots(IdeaSpecificSettings.RELATIVE_MODULE_SRC, OrderRootType.SOURCES.name()) updateRoots(IdeaSpecificSettings.RELATIVE_MODULE_CLS, OrderRootType.CLASSES.name()) updateRoots(IdeaSpecificSettings.RELATIVE_MODULE_JAVADOC, "JAVADOC") if (rootsToAdd.isNotEmpty() || rootsToRemove.isNotEmpty()) { builder.modifyEntity(library) { roots.removeAll(rootsToRemove) roots.addAll(rootsToAdd) } } } private fun loadJdkSettings(emlTag: Element) { val sdkItem = if (emlTag.getAttributeValue(IdeaSpecificSettings.INHERIT_JDK).toBoolean()) { ModuleDependencyItem.InheritedSdkDependency } else { emlTag.getAttributeValue("jdk") ?.let { ModuleDependencyItem.SdkDependency(it, "JavaSDK") } } if (sdkItem != null) { builder.modifyEntity(module) { val newDependencies = dependencies.map { when (it) { is ModuleDependencyItem.SdkDependency -> sdkItem ModuleDependencyItem.InheritedSdkDependency -> sdkItem else -> it } } as MutableList<ModuleDependencyItem> dependencies = if (newDependencies.size < dependencies.size) { val result = mutableListOf<ModuleDependencyItem>(ModuleDependencyItem.InheritedSdkDependency) result.addAll(newDependencies) result } else newDependencies } } } private fun loadCustomJavaSettings(emlTag: Element) { val javaSettings = module.javaSettings ?: builder.addJavaModuleSettingsEntity(true, true, null, null, null, module, module.entitySource) builder.modifyEntity(javaSettings) { val testOutputElement = emlTag.getChild(IdeaXml.OUTPUT_TEST_TAG) if (testOutputElement != null) { compilerOutputForTests = testOutputElement.getAttributeValue(IdeaXml.URL_ATTR)?.let { virtualFileManager.fromUrl(it) } } val inheritedOutput = emlTag.getAttributeValue(JpsJavaModelSerializerExtension.INHERIT_COMPILER_OUTPUT_ATTRIBUTE) if (inheritedOutput.toBoolean()) { inheritedCompilerOutput = true } excludeOutput = emlTag.getChild(IdeaXml.EXCLUDE_OUTPUT_TAG) != null languageLevelId = emlTag.getAttributeValue("LANGUAGE_LEVEL") } } private fun loadContentEntries(emlTag: Element, contentRoot: ContentRootEntity) { val entriesElements = emlTag.getChildren(IdeaXml.CONTENT_ENTRY_TAG) if (entriesElements.isNotEmpty()) { entriesElements.forEach { val url = virtualFileManager.fromUrl(it.getAttributeValue(IdeaXml.URL_ATTR)!!) val contentRootEntity = contentRoot.module.contentRoots.firstOrNull { it.url == url } ?: builder.addContentRootEntity(url, emptyList(), emptyList(), module) loadContentEntry(it, contentRootEntity) } } else { loadContentEntry(emlTag, contentRoot) } } private fun loadContentEntry(contentEntryTag: Element, entity: ContentRootEntity) { val testSourceFolders = contentEntryTag.getChildren(IdeaXml.TEST_FOLDER_TAG).mapTo(HashSet()) { it.getAttributeValue(IdeaXml.URL_ATTR) } val packagePrefixes = contentEntryTag.getChildren(IdeaXml.PACKAGE_PREFIX_TAG).associateBy( { it.getAttributeValue(IdeaXml.URL_ATTR)!! }, { it.getAttributeValue(IdeaXml.PACKAGE_PREFIX_VALUE_ATTR)!! } ) for (sourceRoot in entity.sourceRoots) { val url = sourceRoot.url.url val isForTests = url in testSourceFolders val rootType = if (isForTests) JpsModuleRootModelSerializer.JAVA_TEST_ROOT_TYPE_ID else JpsModuleRootModelSerializer.JAVA_SOURCE_ROOT_TYPE_ID if (rootType != sourceRoot.rootType) { builder.modifyEntity(sourceRoot) { this.rootType = rootType } } val packagePrefix = packagePrefixes[url] if (packagePrefix != null) { val javaRootProperties = sourceRoot.asJavaSourceRoot() if (javaRootProperties != null) { builder.modifyEntity(javaRootProperties) { this.packagePrefix = packagePrefix } } else { builder.addJavaSourceRootEntity(sourceRoot, false, packagePrefix) } } } val excludedUrls = contentEntryTag.getChildren(IdeaXml.EXCLUDE_FOLDER_TAG) .mapNotNull { it.getAttributeValue(IdeaXml.URL_ATTR) } .filter { FileUtil.isAncestor(entity.url.toPath().toFile(), JpsPathUtil.urlToFile(it), false) } .map { virtualFileManager.fromUrl(it) } if (excludedUrls.isNotEmpty()) { builder.modifyEntity(entity) { this.excludedUrls += excludedUrls.map { ExcludeUrlEntity(it, entitySource) } } } } }
apache-2.0
ac394a63cee3fd2ff2aad7a10b1b4c68
42.352174
155
0.719057
4.70283
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/ChangePropertyAfter.kt
13
380
open class A { open var s: String = 1 } class AA : A() { override var s: String = 1 } class B : J() { override var s: String = 1 } fun test() { with(A()) { val t = s s = 3 } with(AA()) { val t = s s = 3 } with(J()) { val t = s s = 3 } with(B()) { val t = s s = 3 } }
apache-2.0
915a47fbe141233e5a0e3dffcc4960a8
10.545455
30
0.352632
3.015873
false
false
false
false
dowenliu-xyz/ketcd
ketcd-core/src/main/kotlin/xyz/dowenliu/ketcd/option/GetOption.kt
1
7010
package xyz.dowenliu.ketcd.option import com.google.protobuf.ByteString import xyz.dowenliu.ketcd.api.RangeRequest import xyz.dowenliu.ketcd.kv.FROM_KEY import xyz.dowenliu.ketcd.kv.NULL_KEY import xyz.dowenliu.ketcd.kv.prefixKeyOf /** * The options for get operation. * * create at 2017/4/15 * @author liufl * @since 0.1.0 * * @property endKey The end key of the get request. If it is not [ByteString.EMPTY], * the get request will return the keys from _key_ to _endKey_ (exclusive). * * If end key is '\u0000' ([FROM_KEY]), the range is all keys >= key. (--from-key) * * If the end key is one bit larger than the given key, then it gets all keys with the prefix * (the given key). (--prefix). You can get it with [prefixKeyOf] function. * * If both key and end key are '\u0000' ([NULL_KEY] and [FROM_KEY]), it returns all keys. * * @property limit The maximum number of keys to return for a get request. No limit when it's lower than or equal zero. * @property revision The revision to use for the get request. * - If the revision is less or equal to zero, the get is over the newest key-value store. * - If the revision has been compacted, ErrCompacted is returned as a response. * @property sortOrder Order to sort the returned key value pairs. * @property sortTarget Field to sort the key value pairs by the provided [sortOrder]. * @property serializable Is the get request a serializable get request. * Get requests are linearizable by default. For better performance, a serializable get * request is served locally without needing to reach consensus with other nodes in the cluster. * @property keysOnly Flag to only return keys. * @property countOnly Flag to only return count of the keys. */ class GetOption private constructor(val endKey: ByteString, val limit: Long, val revision: Long, val sortOrder: RangeRequest.SortOrder, val sortTarget: RangeRequest.SortTarget, val serializable: Boolean, val keysOnly: Boolean, val countOnly: Boolean) { /** * Companion object of [GetOption] */ companion object { /** * The default get options. */ @JvmStatic val DEFAULT = newBuilder().build() /** * Create a builder to construct options for get operation. * * @return builder */ @JvmStatic fun newBuilder(): Builder = Builder() } /** * Builder to construct [GetOption]. */ class Builder internal constructor() { private var limit = 0L private var revision = 0L private var sortOrder = RangeRequest.SortOrder.NONE private var sortTarget = RangeRequest.SortTarget.KEY private var serializable = false private var keysOnly = false private var countOnly = false private var endKey: ByteString = ByteString.EMPTY /** * Limit the number of keys to return for a get request. By default is 0 - no limitation. * * @param limit the maximum number of keys to return for a get request. * No limit when it's lower than or equal zero. * @return this builder to train */ fun withLimit(limit: Long): Builder { this.limit = limit return this } /** * Provide the revision to use for the get request. * - If the revision is less or equal to zero, the get is over the newest key-value store. * - If the revision has been compacted, ErrCompacted is returned as a response. * * @param revision the revision to get. * @return this builder to train. */ fun withRevision(revision: Long): Builder { this.revision = revision return this } /** * Sort the return key value pairs in the provided _order_ * * @param order order to sort the returned key value pairs * @return this builder to train. */ fun withSortOrder(order: RangeRequest.SortOrder): Builder { this.sortOrder = order return this } /** * Sort the return key value pairs in the provided _field_ * * @param field field to sort the key value pairs by the provided [withSortOrder] * @return this builder to train */ fun withSortField(field: RangeRequest.SortTarget): Builder { this.sortTarget = field return this } /** * Set the get request to be a serializable get request. * * Get requests are linearizable by default. For better performance, a serializable get * request is served locally without needing to reach consensus with other nodes in the cluster. * * @param serializable is the get request a serializable get request. * @return this builder to train. */ fun withSerializable(serializable: Boolean): Builder { this.serializable = serializable return this } /** * Set the get request to only return keys. * * @param keysOnly flag to only return keys. * @return this builder to train. */ fun withKeysOnly(keysOnly: Boolean): Builder { this.keysOnly = keysOnly return this } /** * Set the get request to only return count of the keys. * * @param countOnly flag to only return count of the keys. * @return this builder to train. */ fun withCountOnly(countOnly: Boolean): Builder { this.countOnly = countOnly return this } /** * Set the end key of the get request. If it is not [ByteString.EMPTY], * the get request will return the keys from _key_ to _endKey_ (exclusive). * * If end key is '\u0000' ([FROM_KEY]), the range is all keys >= key. (--from-key) * * If the end key is one bit larger than the given key, then it gets all keys with the prefix * (the given key). (--prefix). You can get it with [prefixKeyOf] function. * * If both key and end key are '\u0000' ([NULL_KEY] and [FROM_KEY]), it returns all keys. * * @param endKey end key * @return this builder to train. */ fun withRange(endKey: ByteString): Builder { this.endKey = endKey return this } /** * Build the get options * * @return the get options */ fun build(): GetOption = GetOption(endKey, limit, revision, sortOrder, sortTarget, serializable, keysOnly, countOnly) } }
apache-2.0
9a06fd260496193b406543b8e7f5c3c1
36.693548
119
0.59087
4.636243
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/find/actions/SearchTarget2UsageTarget.kt
1
3954
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:Suppress("DEPRECATION") package com.intellij.find.actions import com.intellij.find.usages.api.SearchTarget import com.intellij.find.usages.api.UsageHandler import com.intellij.find.usages.impl.AllSearchOptions import com.intellij.model.Pointer import com.intellij.navigation.ItemPresentation import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.KeyboardShortcut import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.usageView.UsageViewBundle import com.intellij.usageView.UsageViewUtil import com.intellij.usages.ConfigurableUsageTarget import com.intellij.usages.UsageTarget import com.intellij.usages.UsageView import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import javax.swing.Icon @ApiStatus.Internal class SearchTarget2UsageTarget<O>( private val project: Project, target: SearchTarget, private val allOptions: AllSearchOptions<O> ) : UsageTarget, DataProvider, ConfigurableUsageTarget { private val myPointer: Pointer<out SearchTarget> = target.createPointer() override fun isValid(): Boolean = myPointer.dereference() != null // ----- presentation ----- private var myItemPresentation: ItemPresentation = getItemPresentation(target) override fun update() { val target = myPointer.dereference() ?: return myItemPresentation = getItemPresentation(target) } private fun getItemPresentation(target: SearchTarget): ItemPresentation { val presentation = target.presentation return object : ItemPresentation { override fun getIcon(unused: Boolean): Icon? = presentation.icon override fun getPresentableText(): String = presentation.presentableText override fun getLocationString(): String = presentation.locationText ?: "" } } override fun getPresentation(): ItemPresentation = myItemPresentation override fun isReadOnly(): Boolean = false // TODO used in Usage View displayed by refactorings // ----- Navigatable & NavigationItem ----- // TODO Symbol navigation override fun canNavigate(): Boolean = false override fun canNavigateToSource(): Boolean = false override fun getName(): String? = null override fun navigate(requestFocus: Boolean) = Unit // ----- actions ----- override fun getShortcut(): KeyboardShortcut? = UsageViewUtil.getShowUsagesWithSettingsShortcut() override fun getLongDescriptiveName(): @Nls String { val target = myPointer.dereference() ?: return UsageViewBundle.message("node.invalid") @Suppress("UNCHECKED_CAST") val usageHandler = target.usageHandler as UsageHandler<O> return UsageViewBundle.message( "search.title.0.in.1", usageHandler.getSearchString(allOptions), allOptions.options.searchScope.displayName ) } override fun showSettings() { val target = myPointer.dereference() ?: return @Suppress("UNCHECKED_CAST") val usageHandler = target.usageHandler as UsageHandler<O> val dialog = UsageOptionsDialog(project, target.displayString, usageHandler, allOptions, target.showScopeChooser(), true) if (!dialog.showAndGet()) { return } val newOptions = dialog.result() findUsages(project, target, usageHandler, newOptions) } override fun findUsages(): Unit = error("must not be called") override fun findUsagesInEditor(editor: FileEditor): Unit = error("must not be called") override fun highlightUsages(file: PsiFile, editor: Editor, clearHighlights: Boolean): Unit = error("must not be called") // ----- data context ----- override fun getData(dataId: String): Any? { if (UsageView.USAGE_SCOPE.`is`(dataId)) { return allOptions.options.searchScope } return null } }
apache-2.0
90c60da0ef09ac17884f835639641348
37.398058
140
0.75999
4.684834
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/customize/transferSettings/providers/vscode/parsers/StorageParser.kt
3
3998
package com.intellij.ide.customize.transferSettings.providers.vscode.parsers import com.fasterxml.jackson.core.JsonFactory import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.databind.node.JsonNodeType import com.fasterxml.jackson.databind.node.ObjectNode import com.intellij.ide.RecentProjectMetaInfo import com.intellij.ide.customize.transferSettings.db.KnownColorSchemes import com.intellij.ide.customize.transferSettings.db.KnownLafs import com.intellij.ide.customize.transferSettings.models.RecentPathInfo import com.intellij.ide.customize.transferSettings.models.Settings import com.intellij.ide.customize.transferSettings.providers.vscode.mappings.ThemesMappings import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.SystemInfo import com.jetbrains.rd.util.URI import java.io.File import java.nio.file.Path import kotlin.io.path.absolutePathString class StorageParser(private val settings: Settings) { private val logger = logger<StorageParser>() companion object { private const val OPENED_PATHS = "openedPathsList" private const val WORKSPACES = "workspaces" private const val WORKSPACES_2 = "${WORKSPACES}2" private const val WORKSPACES_3 = "${WORKSPACES}3" private const val THEME = "theme" internal fun parsePath(uri: String): RecentPathInfo? { val path = Path.of(URI(uri)) ?: return null val modifiedTime = path.toFile().listFiles()?.maxByOrNull { it.lastModified() }?.lastModified() val info = RecentProjectMetaInfo().apply { projectOpenTimestamp = modifiedTime ?: 0 buildTimestamp = projectOpenTimestamp displayName = path.fileName.toString() } return RecentPathInfo(workaroundWindowsIssue(path.absolutePathString()), info) } /** * Workaround until IDEA-270493 is fixed */ private fun workaroundWindowsIssue(input: String): String { if (!SystemInfo.isWindows) return input if (input.length < 3) return input if (input[1] != ':') return input return "${input[0].uppercase()}${input.subSequence(1, input.length)}" } } fun process(file: File) = try { logger.info("Processing a storage file: $file") val root = ObjectMapper(JsonFactory().enable(JsonParser.Feature.ALLOW_COMMENTS)).readTree(file) as? ObjectNode ?: error("Unexpected JSON data; expected: ${JsonNodeType.OBJECT}") processRecentProjects(root) processThemeAndScheme(root) } catch (t: Throwable) { logger.warn(t) } private fun processRecentProjects(root: ObjectNode) { try { val openedPaths = root[OPENED_PATHS] as? ObjectNode ?: return val flatList = openedPaths.toList().flatMap { (it as ArrayNode).toList() } val workspacesNew = try { flatList.mapNotNull { it["folderUri"] }.mapNotNull { it.textValue() } } catch (t: Throwable) { null } val workspacesOld = try { flatList.mapNotNull { it.textValue() ?: return@mapNotNull null } } catch (t: Throwable) { null } val workspaces = if (!workspacesNew.isNullOrEmpty()) workspacesNew else workspacesOld ?: return workspaces.forEach { uri -> try { val res = parsePath(uri) if (res != null) { settings.recentProjects.add(res) } } catch (t: Throwable) { logger.warn(t) } } } catch (t: Throwable) { logger.warn(t) } } private fun processThemeAndScheme(root: ObjectNode) { try { val theme = root[THEME]?.textValue() ?: return val laf = ThemesMappings.themeMap(theme) settings.laf = laf settings.syntaxScheme = when (laf) { KnownLafs.Light -> KnownColorSchemes.Light else -> KnownColorSchemes.Darcula } } catch (t: Throwable) { logger.warn(t) } } }
apache-2.0
11a003e001df04690b4d886d03f4677d
31.512195
114
0.686093
4.244161
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinKPMGradleModelBuilder.kt
1
2790
// 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.gradleTooling import org.gradle.api.Project import org.jetbrains.kotlin.idea.gradleTooling.builders.KotlinModuleBuilder import org.jetbrains.kotlin.idea.gradleTooling.builders.KotlinProjectModelSettingsBuilder import org.jetbrains.kotlin.idea.gradleTooling.reflect.KotlinKpmExtensionReflection import org.jetbrains.plugins.gradle.tooling.AbstractModelBuilderService import org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder import org.jetbrains.plugins.gradle.tooling.ModelBuilderContext class KotlinKPMGradleModelBuilder : AbstractModelBuilderService() { override fun canBuild(modelName: String?): Boolean = modelName == KotlinKPMGradleModel::class.java.name override fun getErrorMessageBuilder(project: Project, e: Exception): ErrorMessageBuilder = ErrorMessageBuilder .create(project, e, "Gradle import errors") .withDescription("Unable to build Kotlin PM20 project configuration") override fun buildAll(modelName: String, project: Project, context: ModelBuilderContext): KotlinKPMGradleModel? { try { val kpmExtension = project.kpmExtension ?: return null val kpmExtensionReflection = KotlinKpmExtensionReflection(kpmExtension) val kpmProjectSettings = KotlinProjectModelSettingsBuilder.buildComponent(kpmExtensionReflection) ?: return null val kotlinNativeHome = KotlinNativeHomeEvaluator.getKotlinNativeHome(project) ?: KotlinMPPGradleModel.NO_KOTLIN_NATIVE_HOME val importingContext = KotlinProjectModelImportingContext(project, kpmExtension.javaClass.classLoader) val kpmModules = kpmExtensionReflection.modules.orEmpty().mapNotNull { originModule -> KotlinModuleBuilder.buildComponent(originModule, importingContext.withFragmentCache()) } return KotlinKPMGradleModelImpl(kpmModules, kpmProjectSettings, kotlinNativeHome) } catch (throwable: Throwable) { project.logger.error("Failed building KotlinKPMGradleModel", throwable) throw throwable } } companion object { private const val KPM_GRADLE_PLUGIN_ID = "org.jetbrains.kotlin.multiplatform.pm20" private const val KPM_EXTENSION_CLASS_NAME = "org.jetbrains.kotlin.gradle.plugin.mpp.pm20.KotlinPm20ProjectExtension" private val Project.kpmPlugin get() = project.plugins.findPlugin(KPM_GRADLE_PLUGIN_ID) private val Project.kpmExtension get() = kpmPlugin?.javaClass?.classLoader?.loadClassOrNull(KPM_EXTENSION_CLASS_NAME)?.let { project.extensions.findByType(it) } } }
apache-2.0
26cb3e8f67d97bb1bcdce4ca4d58d391
58.361702
158
0.763082
4.920635
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/test/testData/stepping/custom/lambdaBreakpoints.kt
9
1455
package lambdaBreakpoints fun foo(f1: () -> Unit, f2: () -> Unit = {}, f3: () -> Unit = {}, f4: () -> Unit = {}) { f1() f2() f3() f4() } fun f1() = println() fun f2() = println() fun f3() = println() fun f4() = println() fun main() { // STEP_INTO: 1 // RESUME: 1 //Breakpoint!, lambdaOrdinal = 1 foo({ f1() }) // STEP_INTO: 1 // RESUME: 1 //Breakpoint!, lambdaOrdinal = 1 foo({ f1() }, { f2() }) // STEP_INTO: 1 // RESUME: 1 //Breakpoint!, lambdaOrdinal = 2 foo({ f1() }, { f2() }) foo( // STEP_INTO: 1 // RESUME: 1 //Breakpoint!, lambdaOrdinal = 1 { f1() }, { f2() } ) foo( { f1() }, // STEP_INTO: 1 // RESUME: 1 //Breakpoint!, lambdaOrdinal = 1 { f2() } ) foo( // STEP_INTO: 1 // RESUME: 1 //Breakpoint!, lambdaOrdinal = 1 { f1() }, { f2() }, { f3() }, { f4() } ) foo( // STEP_INTO: 1 // RESUME: 1 //Breakpoint!, lambdaOrdinal = 2 { f1() }, { f2() }, { f3() }, { f4() } ) foo( { f1() }, { f2() }, // STEP_INTO: 1 // RESUME: 1 //Breakpoint!, lambdaOrdinal = 1 { f3() }, { f4() } ) foo( { f1() }, { f2() }, // STEP_INTO: 1 // RESUME: 1 //Breakpoint!, lambdaOrdinal = 2 { f3() }, { f4() } ) }
apache-2.0
4e25a4df98123464669f81bd5539306e
17.653846
88
0.380756
3.211921
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/frontend-api/src/org/jetbrains/kotlin/idea/frontend/api/KtAnalysisSessionProvider.kt
1
3581
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.frontend.api import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.util.NlsContexts import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.KtElement @RequiresOptIn("To use analysis session, consider using analyze/analyzeWithReadAction/analyseInModalWindow methods") annotation class InvalidWayOfUsingAnalysisSession /** * Provides [KtAnalysisSession] by [contextElement] * Should not be used directly, consider using [analyze]/[analyzeWithReadAction]/[analyseInModalWindow] instead */ @InvalidWayOfUsingAnalysisSession abstract class KtAnalysisSessionProvider { @InvalidWayOfUsingAnalysisSession abstract fun getAnalysisSessionFor(contextElement: KtElement): KtAnalysisSession } @InvalidWayOfUsingAnalysisSession fun getAnalysisSessionFor(contextElement: KtElement): KtAnalysisSession = contextElement.project.getService(KtAnalysisSessionProvider::class.java).getAnalysisSessionFor(contextElement) /** * Execute given [action] in [KtAnalysisSession] context * Uses [contextElement] to get a module from which you would like to see the other modules * Usually [contextElement] is some element form the module you currently analysing now * * Should not be called from EDT thread * Should be called from read action * To analyse something from EDT thread, consider using [analyseInModalWindow] * * @see KtAnalysisSession * @see analyzeWithReadAction */ @OptIn(InvalidWayOfUsingAnalysisSession::class) inline fun <R> analyze(contextElement: KtElement, action: KtAnalysisSession.() -> R): R = getAnalysisSessionFor(contextElement).action() /** * Execute given [action] in [KtAnalysisSession] context like [analyze] does but execute it in read action * Uses [contextElement] to get a module from which you would like to see the other modules * Usually [contextElement] is some element form the module you currently analysing now * * Should be called from read action * To analyse something from EDT thread, consider using [analyseInModalWindow] * If you are already in read action, consider using [analyze] * * @see KtAnalysisSession * @see analyze */ inline fun <R> analyzeWithReadAction( contextElement: KtElement, crossinline action: KtAnalysisSession.() -> R ): R = runReadAction { analyze(contextElement, action) } /** * Show a modal window with a progress bar and specified [windowTitle] * and execute given [action] task with [KtAnalysisSession] context * If [action] throws some exception, then [analyseInModalWindow] will rethrow it * Should be executed from EDT only * If you want to analyse something from non-EDT thread, consider using [analyze]/[analyzeWithReadAction] */ inline fun <R> analyseInModalWindow( contextElement: KtElement, @NlsContexts.DialogTitle windowTitle: String, crossinline action: KtAnalysisSession.() -> R ): R { ApplicationManager.getApplication().assertIsDispatchThread() val task = object : Task.WithResult<R, Exception>(contextElement.project, windowTitle, /*canBeCancelled*/ true) { override fun compute(indicator: ProgressIndicator): R = analyzeWithReadAction(contextElement) { action() } } task.queue() return task.result }
apache-2.0
57d5d33d774ccfd3e588bfe6d9785254
40.651163
117
0.783022
4.626615
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/refactoringTesting/MoveRefactoringUtils.kt
6
3052
// 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.actions.internal.refactoringTesting import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import java.lang.reflect.Method internal fun <T> lazyPub(initializer: () -> T) = lazy(LazyThreadSafetyMode.PUBLICATION, initializer) internal fun gitReset(project: Project, projectRoot: VirtualFile) { fun ClassLoader.loadClassOrThrow(name: String) = loadClass(name) ?: error("$name not loaded") fun Class<*>.loadMethodOrThrow(name: String, vararg arguments: Class<*>): Method { return try { getMethod(name, *arguments) } catch (e: NoSuchMethodException) { error("${this.name}::$name not loaded") } } val loader = PluginManagerCore.getPlugin(PluginId.getId("Git4Idea"))?.pluginClassLoader ?: error("Git plugin is not found") val gitCls = loader.loadClassOrThrow("git4idea.commands.Git") val gitLineHandlerCls = loader.loadClassOrThrow("git4idea.commands.GitLineHandler") val gitCommandCls = loader.loadClassOrThrow("git4idea.commands.GitCommand") val gitCommandResultCls = loader.loadClassOrThrow("git4idea.commands.GitCommandResult") val gitLineHandlerCtor = gitLineHandlerCls.getConstructor(Project::class.java, VirtualFile::class.java, gitCommandCls) ?: error( "git4idea.commands.GitLineHandler::ctor not loaded" ) val runCommand = gitCls.loadMethodOrThrow("runCommand", gitLineHandlerCls) val getExitCode = gitCommandResultCls.loadMethodOrThrow("getExitCode") val gitLineHandlerAddParameters = gitLineHandlerCls.loadMethodOrThrow("addParameters", List::class.java) val gitCommandReset = gitCommandCls.getField("RESET")?.get(null) ?: error("git4idea.commands.GitCommand.RESET not loaded") val resetLineHandler = gitLineHandlerCtor.newInstance(project, projectRoot, gitCommandReset) gitLineHandlerAddParameters.invoke(resetLineHandler, listOf("--hard", "HEAD")) val gitService = ApplicationManager.getApplication().getService(gitCls) val runCommandResult = runCommand.invoke(gitService, resetLineHandler) val gitResetResultCode = getExitCode.invoke(runCommandResult) as Int if (gitResetResultCode == 0) { VfsUtil.markDirtyAndRefresh(false, true, false, projectRoot) //GitRepositoryManager.getInstance(project).updateRepository(d.getGitRoot()) } else { error("Git reset failed") } } inline fun edtExecute(crossinline body: () -> Unit) { ApplicationManager.getApplication().invokeAndWait { body() } } inline fun readAction(crossinline body: () -> Unit) { ApplicationManager.getApplication().runReadAction { body() } }
apache-2.0
ebd6154d208523419817b50b3a3526b8
43.897059
158
0.749017
4.603318
false
false
false
false
smmribeiro/intellij-community
python/src/com/jetbrains/python/codeInsight/mlcompletion/PyElementFeatureProvider.kt
5
6425
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.codeInsight.mlcompletion import com.intellij.codeInsight.completion.CompletionLocation import com.intellij.codeInsight.completion.ml.ContextFeatures import com.intellij.codeInsight.completion.ml.ElementFeatureProvider import com.intellij.codeInsight.completion.ml.MLFeatureValue import com.intellij.codeInsight.lookup.LookupElement import com.jetbrains.python.codeInsight.completion.PyMultipleArgumentsCompletionContributor import com.jetbrains.python.codeInsight.mlcompletion.prev2calls.PyPrevCallsCompletionFeatures import com.jetbrains.python.psi.PyParameter class PyElementFeatureProvider : ElementFeatureProvider { override fun getName(): String = "python" override fun calculateFeatures(element: LookupElement, location: CompletionLocation, contextFeatures: ContextFeatures): Map<String, MLFeatureValue> { val result = HashMap<String, MLFeatureValue>() val lookupString = element.lookupString val locationPsi = location.completionParameters.position val lookupPsiElement = element.psiElement PyCompletionFeatures.getPyLookupElementInfo(element)?.let { info -> result["kind"] = MLFeatureValue.categorical(info.kind) result["is_builtins"] = MLFeatureValue.binary(info.isBuiltins) PyCompletionFeatures.getNumberOfOccurrencesInScope(info.kind, contextFeatures, lookupString)?.let { result["number_of_occurrences_in_scope"] = MLFeatureValue.numerical(it) } PyCompletionFeatures.getBuiltinPopularityFeature(lookupString, info.isBuiltins)?.let { result["builtin_popularity"] = MLFeatureValue.numerical(it) } } PyCompletionFeatures.getKeywordId(lookupString)?.let { result["keyword_id"] = MLFeatureValue.numerical(it) } result["is_dict_key"] = MLFeatureValue.binary(PyCompletionFeatures.isDictKey(element)) result["is_takes_parameter_self"] = MLFeatureValue.binary(PyCompletionFeatures.isTakesParameterSelf(element)) result["underscore_type"] = MLFeatureValue.categorical(PyCompletionFeatures.getElementNameUnderscoreType(lookupString)) result["number_of_tokens"] = MLFeatureValue.numerical(PyNamesMatchingMlCompletionFeatures.getNumTokensFeature(lookupString)) result["element_is_py_file"] = MLFeatureValue.binary(PyCompletionFeatures.isPsiElementIsPyFile(element)) result["element_is_psi_directory"] = MLFeatureValue.binary(PyCompletionFeatures.isPsiElementIsPsiDirectory(element)) result.putAll(PyCompletionFeatures.getElementPsiLocationFeatures(element, location)) PyCompletionFeatures.getElementModuleCompletionFeatures(element)?.let { with(it) { result["element_module_is_std_lib"] = MLFeatureValue.binary(isFromStdLib) result["can_find_element_module"] = MLFeatureValue.binary(canFindModule) } } PyImportCompletionFeatures.getImportPopularityFeature(locationPsi, lookupString)?.let { result["import_popularity"] = MLFeatureValue.numerical(it) } PyImportCompletionFeatures.getElementImportPathFeatures(element, location)?.let { with (it) { result["is_imported"] = MLFeatureValue.binary(isImported) result["num_components_in_import_path"] = MLFeatureValue.numerical(numComponents) result["num_private_components_in_import_path"] = MLFeatureValue.numerical(numPrivateComponents) }} PyNamesMatchingMlCompletionFeatures.getPyFunClassFileBodyMatchingFeatures(contextFeatures, element.lookupString)?.let { with(it) { result["scope_num_names"] = MLFeatureValue.numerical(numScopeNames) result["scope_num_different_names"] = MLFeatureValue.numerical(numScopeDifferentNames) result["scope_num_matches"] = MLFeatureValue.numerical(sumMatches) result["scope_num_tokens_matches"] = MLFeatureValue.numerical(sumTokensMatches) }} PyNamesMatchingMlCompletionFeatures.getPySameLineMatchingFeatures(contextFeatures, element.lookupString)?.let { with(it) { result["same_line_num_names"] = MLFeatureValue.numerical(numScopeNames) result["same_line_num_different_names"] = MLFeatureValue.numerical(numScopeDifferentNames) result["same_line_num_matches"] = MLFeatureValue.numerical(sumMatches) result["same_line_num_tokens_matches"] = MLFeatureValue.numerical(sumTokensMatches) }} PyNamesMatchingMlCompletionFeatures.getMatchingWithReceiverFeatures(contextFeatures, element)?.let { with(it) { result["receiver_name_matches"] = MLFeatureValue.binary(matchesWithReceiver) result["receiver_num_matched_tokens"] = MLFeatureValue.numerical(numMatchedTokens) result["receiver_tokens_num"] = MLFeatureValue.numerical(receiverTokensNum) }} result.putAll(PyNamesMatchingMlCompletionFeatures.getMatchingWithEnclosingMethodFeatures(contextFeatures, element)) if (lookupString.endsWith("Warning")) result["is_warning"] = MLFeatureValue.binary(true) if (lookupString.endsWith("Error")) result["is_error"] = MLFeatureValue.binary(true) if (lookupString.endsWith("Exception")) result["is_exception"] = MLFeatureValue.binary(true) if (lookupString.endsWith("s")) result["ends_with_s"] = MLFeatureValue.binary(true) if (lookupPsiElement is PyParameter && lookupPsiElement.isSelf) result["is_self"] = MLFeatureValue.binary(true) contextFeatures.getUserData(PyPrevCallsCompletionFeatures.PREV_CALLS_CONTEXT_INFO_KEY)?.let { contextInfo -> PyPrevCallsCompletionFeatures.getResult(lookupString, contextInfo)?.let { with (it) { when { primaryWeight != null -> result["prev_2_calls_primary_weight"] = MLFeatureValue.numerical(primaryWeight!!) weightOneCall != null -> result["prev_2_calls_weight_one_call"] = MLFeatureValue.numerical(weightOneCall!!) weightSecondaryTwoCalls != null -> result["prev_2_calls_weight_secondary_two_calls"] = MLFeatureValue.numerical(weightSecondaryTwoCalls!!) weightEmptyPrevCalls != null -> result["prev_2_calls_weight_empty_prev_calls"] = MLFeatureValue.numerical(weightEmptyPrevCalls!!) } }} } element.getUserData(PyMultipleArgumentsCompletionContributor.MULTIPLE_ARGUMENTS_VARIANT_KEY)?.let { result["is_multiple_arguments"] = MLFeatureValue.binary(true) } return result } }
apache-2.0
939a51968e58bf9337c7f2c3ff5d2d61
57.418182
148
0.764669
4.622302
false
false
false
false
mminke/pv-datalogger
pvdatavisualizer/src/main/kotlin/nl/kataru/pvdata/core/InverterService.kt
1
7839
package nl.kataru.pvdata.core import com.mongodb.client.MongoDatabase import nl.kataru.pvdata.accounts.Account import org.bson.Document import org.bson.types.Decimal128 import org.bson.types.ObjectId import java.util.* import javax.inject.Inject open class InverterService @Inject constructor(private var mongoDatabase: MongoDatabase) { private val COLLECTION_INVERTERS = "inverters" private val COLLECTION_MEASUREMENTS = "measurements" /** * Create a new inverter entry in persistent storage. * @return a inverter instance containing the id of the newly created entry. * @throws IllegalArgumentException if an inverter with the given serial number already exists. * @throws RuntimeException if something went wrong while inserting the document and a new id could not be obtained. */ fun createUsingAccount(inverter: Inverter, account: Account): Inverter { if (findBySerialNumberUsingAccount(inverter.serialNumber, account).isPresent) { throw IllegalArgumentException("Inverter with serialnumber already exists") } val inverterWithOwner = inverter.copy(owner = account.id) val document = transformToDocument(inverterWithOwner) val dbCollection = mongoDatabase.getCollection(COLLECTION_INVERTERS) dbCollection?.insertOne(document) val objectId = document.getObjectId("_id") if (objectId != null) { return transformToInverter(document) } else { throw RuntimeException("Unknown error occured, no id generated for new instance") } } fun save(account: Account) { throw UnsupportedOperationException("Not yet implemented") } fun findAllUsingAccount(account: Account): Set<Inverter> { val results = HashSet<Inverter>() val collection = mongoDatabase.getCollection(COLLECTION_INVERTERS) val query = Document() query.append("owner", account.id) val documents = collection!!.find(query) for (document in documents) { val inverter = transformToInverter(document) results.add(inverter) } return results } fun findByIdUsingAccount(id: String, account: Account): Optional<Inverter> { val collection = mongoDatabase.getCollection(COLLECTION_INVERTERS) val query = Document() query.append("_id", ObjectId(id)) query.append("owner", account.id) val document = collection!!.find(query)?.first() ?: return Optional.empty() val inverter = transformToInverter(document) return Optional.of(inverter) } fun findBySerialNumberUsingAccount(serialNumber: String, account: Account): Optional<Inverter> { val collection = mongoDatabase.getCollection(COLLECTION_INVERTERS) val query = Document() query.append("serialnumber", serialNumber) query.append("owner", account.id) val document = collection!!.find(query)?.first() ?: return Optional.empty() val inverter = transformToInverter(document) return Optional.of(inverter) } fun deleteWithIdUsingAccount(id: String, account: Account): Boolean { val collection = mongoDatabase.getCollection(COLLECTION_INVERTERS) val query = Document() query.append("_id", ObjectId(id)) query.append("owner", account.id) val result = collection!!.deleteOne(query) if (result.deletedCount == 1L) { return true } else { return false } } fun createMeasurementUsingAccount(inverterMeasurement: InverterMeasurement, account: Account): InverterMeasurement { if (!findByIdUsingAccount(inverterMeasurement.inverterId, account).isPresent) { throw SecurityException("Inverter ${inverterMeasurement.inverterId} not owned by account ${account.id}.") } if (findMeasurementByTimestampForInverter(inverterMeasurement.timestamp, inverterMeasurement.inverterId).isPresent) { throw IllegalArgumentException("Measurement for the timestamp ${inverterMeasurement.timestamp} already exists") } val document = transformToDocument(inverterMeasurement) val dbCollection = mongoDatabase.getCollection(COLLECTION_MEASUREMENTS) dbCollection?.insertOne(document) val objectId = document.getObjectId("_id") if (objectId != null) { return transformToMeasurement(document) } else { throw RuntimeException("Unknown error occured, no id generated for new instance") } } fun findMeasurementByTimestampForInverter(timestamp: Long, inverterId: String): Optional<InverterMeasurement> { val collection = mongoDatabase.getCollection(COLLECTION_MEASUREMENTS) val query = Document() query.append("timestamp", timestamp) query.append("inverterId", inverterId) val document = collection!!.find(query)?.first() ?: return Optional.empty() val measurement = transformToMeasurement(document) return Optional.of(measurement) } fun transformToDocument(inverter: Inverter): Document { val document: Document = Document() with(inverter) { if (!id.isNullOrBlank()) { document.append("_id", ObjectId(id)) } document.append("serialnumber", serialNumber) document.append("brand", brand) document.append("type", type) document.append("ratedPower", ratedPower) document.append("owner", inverter.owner) } return document } fun transformToInverter(document: Document): Inverter { with(document) { val id = getObjectId("_id").toString() val serialNumber = getString("serialnumber") val brand = getString("brand") ?: "Unknown" val type = getString("type") ?: "Unknown" val ratedPower = getInteger("ratedPower") ?: -1 val owner = getString("owner") val inverter = Inverter(id, serialNumber, brand, type, ratedPower, owner) return inverter } } fun transformToDocument(inverterMeasurement: InverterMeasurement): Document { val document: Document = Document() with(inverterMeasurement) { if (!id.isNullOrBlank()) { document.append("_id", ObjectId(id)) } document.append("inverterId", inverterId) document.append("timestamp", timestamp) document.append("temperature", Decimal128(temperature)) document.append("yieldToday", Decimal128(yieldToday)) document.append("yieldTotal", Decimal128(yieldTotal)) document.append("totalOperatingHours", Decimal128(totalOperatingHours)) document.append("rawData", rawData) } return document } fun transformToMeasurement(document: Document): InverterMeasurement { with(document) { val id = getObjectId("_id").toString() val inverterId = getString("inverterId") val timestamp = getLong("timestamp") val temperature = (get("temperature") as Decimal128).bigDecimalValue() val yieldToday = ((get("yieldToday") ?: Decimal128(-1)) as Decimal128).bigDecimalValue() val yieldTotal = ((get("yieldTotal") ?: Decimal128(-1)) as Decimal128).bigDecimalValue() val totalOperatingHours = ((get("totalOperatingHours") ?: Decimal128(-1)) as Decimal128).bigDecimalValue() val rawData = getString("rawData") val measurement = InverterMeasurement(id, inverterId, timestamp, temperature, yieldToday, yieldTotal, totalOperatingHours, rawData) return measurement } } }
agpl-3.0
8c4d045312ca1afb3b0e91fd267ea460
39.2
143
0.658757
4.850866
false
false
false
false
SDILogin/RouteTracker
app/src/main/java/me/sdidev/simpleroutetracker/db/DbRouteRepository.kt
1
2151
package me.sdidev.simpleroutetracker.db import io.reactivex.Single import me.sdidev.simpleroutetracker.core.Position import me.sdidev.simpleroutetracker.core.Route class DbRouteRepository(private val dbOpenHelper: DbOpenHelper) : RouteRepository { override fun create(route: Route): Route? { if (!dbOpenHelper.isOpen) return null val dbPositions = route.positions.map { position -> DbPosition(position) } val dbRoute = DbRoute() dbOpenHelper.getRouteDao().create(dbRoute) dbPositions.forEach { dbPosition -> dbOpenHelper.getPositionDao().createIfNotExists(dbPosition) dbOpenHelper.getRoutePositionJoinDao().create(DbRoutePosition(dbRoute, dbPosition)) } return Route(dbRoute.id, route.positions) } override fun read(): Single<List<Route>> { if (dbOpenHelper.isOpen) { return Single .just(dbOpenHelper.getRoutePositionJoinDao().queryForAll()) .map{ routesWithPositions -> val routeIds = routesWithPositions.map { item -> item.route.id }.distinct() val routes: List<Route> = routeIds.map { routeId -> val positionIds = routesWithPositions .filter { routeWithPosition -> routeWithPosition.route.id == routeId } .map { routeWithPosition -> routeWithPosition.position.latLngKey } val positions = positions(positionIds) val dbRoute = dbOpenHelper.getRouteDao().queryForId(routeId) Route(dbRoute.id, positions) } routes } } else { return Single.error { RuntimeException("Database is closed") } } } private fun positions(positionIds: List<String>): List<Position> { return positionIds.map { id -> val dbPosition = dbOpenHelper.getPositionDao().queryForId(id) Position(dbPosition.latitude, dbPosition.longitude) } } }
mit
51a2b43b000016276745185220148732
39.584906
106
0.592748
5.025701
false
false
false
false
timakden/advent-of-code
src/main/kotlin/ru/timakden/aoc/year2016/day02/Puzzle.kt
1
1893
package ru.timakden.aoc.year2016.day02 import ru.timakden.aoc.util.Constants.Part import ru.timakden.aoc.util.Constants.Part.PART_ONE import ru.timakden.aoc.util.Constants.Part.PART_TWO import ru.timakden.aoc.util.measure import kotlin.time.ExperimentalTime @ExperimentalTime fun main() { measure { println("Part One: ${solve(input, PART_ONE)}") println("Part Two: ${solve(input, PART_TWO)}") } } fun solve(input: List<String>, part: Part): String { var point = if (part == PART_ONE) Pair(1, 1) else Pair(2, 0) val list = mutableListOf<Char>() input.forEach { point = goToTheNextPoint(point, it, part) if (part == PART_ONE) list.add(keypadPartOne[point.first][point.second]) else list.add(keypadPartTwo[point.first][point.second]) } return list.joinToString("") } private val keypadPartOne = arrayOf( charArrayOf('1', '2', '3'), charArrayOf('4', '5', '6'), charArrayOf('7', '8', '9') ) private val keypadPartTwo = arrayOf( charArrayOf(' ', ' ', '1', ' ', ' '), charArrayOf(' ', '2', '3', '4', ' '), charArrayOf('5', '6', '7', '8', '9'), charArrayOf(' ', 'A', 'B', 'C', ' '), charArrayOf(' ', ' ', 'D', ' ', ' ') ) private fun goToTheNextPoint(point: Pair<Int, Int>, instruction: String, part: Part): Pair<Int, Int> { var x = point.second var y = point.first instruction.forEach { when (it) { 'U' -> if (!(y == 0 || (part == PART_TWO && keypadPartTwo[y - 1][x] == ' '))) y-- 'D' -> if ((part == PART_ONE && y != 2) || (part == PART_TWO && y != 4 && keypadPartTwo[y + 1][x] != ' ')) y++ 'R' -> if ((part == PART_ONE && x != 2) || (part == PART_TWO && x != 4 && keypadPartTwo[y][x + 1] != ' ')) x++ 'L' -> if (!(x == 0 || (part == PART_TWO && keypadPartTwo[y][x - 1] == ' '))) x-- } } return y to x }
apache-2.0
7c39e4e0b5717aea2faee3af5a846f20
31.084746
122
0.548864
3.123762
false
false
false
false
hazuki0x0/YuzuBrowser
module/download/src/main/java/jp/hazuki/yuzubrowser/download/ui/fragment/SaveWebArchiveDialog.kt
1
6329
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.download.ui.fragment import android.app.Activity import android.app.Dialog import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Button import android.widget.CheckBox import android.widget.EditText import androidx.appcompat.app.AlertDialog import androidx.documentfile.provider.DocumentFile import androidx.fragment.app.DialogFragment import jp.hazuki.yuzubrowser.core.MIME_TYPE_HTML import jp.hazuki.yuzubrowser.core.MIME_TYPE_MHTML import jp.hazuki.yuzubrowser.core.utility.storage.toDocumentFile import jp.hazuki.yuzubrowser.core.utility.utils.createUniqueFileName import jp.hazuki.yuzubrowser.download.R import jp.hazuki.yuzubrowser.download.TMP_FILE_SUFFIX import jp.hazuki.yuzubrowser.download.core.data.DownloadFile import jp.hazuki.yuzubrowser.download.core.data.DownloadRequest import jp.hazuki.yuzubrowser.download.core.utils.guessDownloadFileName import jp.hazuki.yuzubrowser.download.download import jp.hazuki.yuzubrowser.download.getDownloadDocumentFile import jp.hazuki.yuzubrowser.webview.CustomWebView class SaveWebArchiveDialog : DialogFragment() { private var listener: OnSaveWebViewListener? = null private lateinit var root: androidx.documentfile.provider.DocumentFile private lateinit var folderButton: Button override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val activity = activity ?: throw IllegalStateException() val arguments = arguments ?: throw IllegalArgumentException() val view = View.inflate(activity, R.layout.dialog_download, null) val filenameEditText = view.findViewById<EditText>(R.id.filenameEditText) val saveArchiveCheckBox = view.findViewById<CheckBox>(R.id.saveArchiveCheckBox) folderButton = view.findViewById(R.id.folderButton) saveArchiveCheckBox.visibility = View.VISIBLE val file = arguments.getParcelable<DownloadFile>(ARG_FILE) ?: throw IllegalArgumentException() root = activity.getDownloadDocumentFile() val name = file.name ?: "index$EXT_HTML" filenameEditText.setText(name) view.findViewById<View>(R.id.editor).visibility = View.VISIBLE view.findViewById<View>(R.id.loading).visibility = View.GONE folderButton.text = root.name folderButton.setOnClickListener { startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), REQUEST_FOLDER) } saveArchiveCheckBox.setOnCheckedChangeListener { _, isChecked -> if (isChecked) { filenameEditText.setText(guessDownloadFileName(root, file.url, null, MIME_TYPE_MHTML, EXT_MHTML)) } else { filenameEditText.setText(guessDownloadFileName(root, file.url, null, MIME_TYPE_HTML, EXT_HTML)) } } return AlertDialog.Builder(activity) .setTitle(R.string.download) .setView(view) .setPositiveButton(android.R.string.ok) { _, _ -> val act = getActivity() ?: return@setPositiveButton val input = filenameEditText.text.toString() if (input.isEmpty()) return@setPositiveButton val newFileName = createUniqueFileName(root, input, TMP_FILE_SUFFIX) file.name = newFileName if (saveArchiveCheckBox.isChecked) { listener?.onSaveWebViewToFile(root, file, arguments.getInt(ARG_NO)) } else { act.download(root.uri, file, null) } dismiss() } .setNegativeButton(android.R.string.cancel, null) .show() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { val activity = activity ?: return when (requestCode) { REQUEST_FOLDER -> { if (resultCode != Activity.RESULT_OK || data == null) return val uri = data.data ?: return root = uri.toDocumentFile(activity) folderButton.text = root.name } } } override fun onAttach(context: Context) { super.onAttach(context) listener = activity as? OnSaveWebViewListener } override fun onDetach() { super.onDetach() listener = null } companion object { private const val EXT_MHTML = ".mhtml" private const val EXT_HTML = ".html" private const val ARG_FILE = "file" private const val ARG_NO = "no" private const val REQUEST_FOLDER = 1 operator fun invoke(file: DownloadFile): SaveWebArchiveDialog { return SaveWebArchiveDialog().apply { arguments = Bundle().apply { putParcelable(ARG_FILE, file) } } } operator fun invoke(context: Context, url: String, webView: CustomWebView, webViewNo: Int): SaveWebArchiveDialog { val name = guessDownloadFileName(context.getDownloadDocumentFile(), url, null, MIME_TYPE_HTML, null) return SaveWebArchiveDialog().apply { arguments = Bundle().apply { putParcelable(ARG_FILE, DownloadFile(url, name, DownloadRequest(null, webView.webSettings.userAgentString, EXT_HTML))) putInt(ARG_NO, webViewNo) } } } } interface OnSaveWebViewListener { fun onSaveWebViewToFile(root: DocumentFile, file: DownloadFile, webViewNo: Int) } }
apache-2.0
50dda470535dc04cc336afe1d0834214
36.672619
122
0.657766
4.747937
false
false
false
false
badoualy/kotlogram
sample/src/main/kotlin/com/github/badoualy/telegram/sample/GetHistorySample.kt
1
2419
package com.github.badoualy.telegram.sample import com.github.badoualy.telegram.api.Kotlogram import com.github.badoualy.telegram.api.utils.id import com.github.badoualy.telegram.api.utils.toInputPeer import com.github.badoualy.telegram.sample.config.Config import com.github.badoualy.telegram.sample.config.FileApiStorage import com.github.badoualy.telegram.tl.api.* import com.github.badoualy.telegram.tl.core.TLObject import com.github.badoualy.telegram.tl.exception.RpcErrorException import java.io.IOException object GetHistorySample { @JvmStatic fun main(args: Array<String>) { // This is a synchronous client, that will block until the response arrive (or until timeout) val client = Kotlogram.getDefaultClient(Config.application, FileApiStorage()) // How many messages we want to get (same than dialogs, there is a cap) // (Telegram has an internal max, your value will be capped) val count = 10 // You can start making requests try { val tlAbsDialogs = client.messagesGetDialogs(false, 0, 0, TLInputPeerEmpty(), 1) val tlAbsPeer = tlAbsDialogs.dialogs[0].peer val tlPeerObj: TLObject = if (tlAbsPeer is TLPeerUser) tlAbsDialogs.users.first { it.id == tlAbsPeer.id } else tlAbsDialogs.chats.first { it.id == tlAbsPeer.id } // Retrieve inputPeer to get message history val inputPeer = when (tlPeerObj) { is TLUser -> tlPeerObj.toInputPeer() is TLAbsChat -> tlPeerObj.toInputPeer() else -> null } ?: TLInputPeerEmpty() val tlAbsMessages = client.messagesGetHistory(inputPeer, 0, 0, 0, count, 0, 0) // Note: first message in the list is most recent tlAbsMessages.messages.reversed().forEach { val messageContent = if (it is TLMessage) it.message else if (it is TLMessageService) "Service: ${it.action}" else "Empty message (TLMessageEmpty)" println(messageContent) } } catch (e: RpcErrorException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } finally { client.close() // Important, do not forget this, or your process won't finish } } }
mit
3a9a9fcee676c4387e63204fdb18c767
42.214286
101
0.633733
4.32737
false
true
false
false
grote/Transportr
app/src/androidTest/java/de/grobox/transportr/ScreengrabTest.kt
1
5691
/* * Transportr * * Copyright (c) 2013 - 2021 Torsten Grote * * 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 de.grobox.transportr import android.util.Log import androidx.annotation.CallSuper import androidx.test.core.app.ApplicationProvider import de.grobox.transportr.locations.WrapLocation import de.schildbach.pte.NetworkId import de.schildbach.pte.dto.LocationType.STATION import org.junit.Before import org.junit.ClassRule import tools.fastlane.screengrab.Screengrab import tools.fastlane.screengrab.UiAutomatorScreenshotStrategy import tools.fastlane.screengrab.locale.LocaleTestRule import tools.fastlane.screengrab.locale.LocaleUtil.getTestLocale import java.util.* abstract class ScreengrabTest { companion object { @JvmField @ClassRule val localeTestRule = LocaleTestRule() } private val app = ApplicationProvider.getApplicationContext<TestApplication>() val component = app.component as TestComponent @Before @CallSuper open fun setUp() { Screengrab.setDefaultScreenshotStrategy(UiAutomatorScreenshotStrategy()) } val networkId: NetworkId = when(getTestLocale()) { Locale.FRANCE -> NetworkId.PARIS Locale.US -> NetworkId.TLEM Locale.forLanguageTag("pt-BR") -> NetworkId.BRAZIL else -> NetworkId.DB } val departureStation = when(networkId) { NetworkId.PARIS -> "Gare De Lyon" NetworkId.TLEM -> "Waterloo Station" NetworkId.BRAZIL -> "Republica" else -> "Berlin Hbf" } protected fun getFrom(i: Int): WrapLocation = when(networkId) { NetworkId.PARIS -> when(i) { 0 -> WrapLocation(STATION, "stop_area:OIF:SA:8739305", 48857298, 2293270, "Paris", "Champ De Mars Tour Eiffel", null) 1 -> WrapLocation(STATION, "stop_area:OIF:SA:8739100", 48842481, 2321783, "Paris", "Gare Montparnasse", null) 2 -> WrapLocation(STATION, "stop_area:OIF:SA:8727100", 48880372, 2356597, null, "Gare Du Nord", null) else -> throw RuntimeException() } NetworkId.TLEM -> when(i) { 0 -> WrapLocation(STATION, "1000119", 51503449, -152036, "London", "Hyde Park Corner", null) 1 -> getLocation("Blackfriars Pier") 2 -> getLocation("Moorgate") else -> throw RuntimeException() } NetworkId.BRAZIL -> when(i) { 0 -> WrapLocation(STATION, "stop_point:OSA:SP:2600672", -23555071, -46662131, "São Paulo", "Paulista", null) 1 -> getLocation("Pinheiros") 2 -> getLocation("Vila Madalena") else -> throw RuntimeException() } else -> when(i) { 0 -> WrapLocation(STATION, "8011155", 52521481, 13410962, null, "Berlin Alexanderplatz", null) 1 -> getLocation("Zoologischer Garten") 2 -> getLocation("Kottbusser Tor") else -> throw RuntimeException() } } protected fun getTo(i: Int): WrapLocation = when(networkId) { NetworkId.PARIS -> when(i) { 0 -> WrapLocation(STATION, "stop_area:OIF:SA:8711300", 48876241, 2358326, "Paris", "Gare De L'est", null) 1 -> WrapLocation(STATION, "stop_area:OIF:SA:8754730", 48860751, 2325874, "Paris", "Musée D'orsay", null) 2 -> WrapLocation(STATION, "stop_area:OIF:SA:59290", 48866800, 2334338, "Paris", "Pyramides", null) else -> throw RuntimeException() } NetworkId.TLEM -> when(i) { 0 -> WrapLocation(STATION, "1000238", 51509829, -76797, "London", "Tower Hill", null) 1 -> getLocation("Westminster") 2 -> getLocation("Temple") else -> throw RuntimeException() } NetworkId.BRAZIL -> when(i) { 0 -> WrapLocation(STATION, "stop_point:OSA:SP:18876", -23543118, -46589599, "São Paulo", "Belem", null) 1 -> getLocation("Trianon Masp") 2 -> getLocation("Anhangabaú") else -> throw RuntimeException() } else -> when(i) { 0 -> WrapLocation(STATION, "730874", 52507278, 13331992, null, "Checkpoint Charlie", null) 1 -> getLocation("Bundestag") 2 -> getLocation("Friedrichstraße") else -> throw RuntimeException() } } private fun getLocation(name: String): WrapLocation { return WrapLocation(STATION, getRandomId(), 0, 0, null, name, null) } private fun getRandomId(): String { return Random().nextInt().toString() } protected fun makeScreenshot(filename: String) { try { Screengrab.screenshot(filename) } catch (e: RuntimeException) { if (e.message != "Unable to capture screenshot.") throw e Log.w("Screengrab", "Permission to write screenshot is missing.") } } protected fun sleep(millis: Int) { try { Thread.sleep(millis.toLong()) } catch (e: InterruptedException) { e.printStackTrace() } } }
gpl-3.0
4766bbfb6124c1442014f69bf47cbeb4
37.680272
129
0.629441
3.90522
false
true
false
false
sonnytron/FitTrainerBasic
mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/adapters/ExerciseCountViewHolder.kt
1
1059
package com.sonnyrodriguez.fittrainer.fittrainerbasic.adapters import android.support.v7.widget.RecyclerView import android.view.ViewGroup import android.widget.TextView import com.sonnyrodriguez.fittrainer.fittrainerbasic.R import com.sonnyrodriguez.fittrainer.fittrainerbasic.models.ExerciseListObject import com.sonnyrodriguez.fittrainer.fittrainerbasic.models.MuscleEnum import org.jetbrains.anko.find class ExerciseCountViewHolder(itemView: ViewGroup): RecyclerView.ViewHolder(itemView) { val exerciseTitle: TextView = itemView.find(R.id.exercise_count_item_title) val exerciseMuscle: TextView = itemView.find(R.id.exercise_count_item_muscle) val exerciseCount: TextView = itemView.find(R.id.exercise_count_item_count) fun bind(exerciseListObject: ExerciseListObject) { exerciseTitle.text = exerciseListObject.title exerciseCount.text = exerciseListObject.exerciseCount.toString() MuscleEnum.fromMuscleNumber(exerciseListObject.muscleGroupNum).let { exerciseMuscle.text = it.title } } }
apache-2.0
f2fb5020a90bb7dd3b41e0c1e87de41e
45.043478
87
0.798867
4.185771
false
false
false
false
Zubnix/westmalle
compositor/src/main/kotlin/org/westford/tty/Tty.kt
3
4512
/* * Westford Wayland Compositor. * Copyright (C) 2016 Erik De Rijcke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.westford.tty import com.google.auto.factory.AutoFactory import com.google.auto.factory.Provided import org.freedesktop.jaccall.Pointer import org.westford.Signal import org.westford.nativ.glibc.Libc import org.westford.nativ.linux.Kd.KDSETMODE import org.westford.nativ.linux.Kd.KDSKBMODE import org.westford.nativ.linux.Kd.KD_TEXT import org.westford.nativ.linux.Stat.KDSKBMUTE import org.westford.nativ.linux.Vt.VT_ACKACQ import org.westford.nativ.linux.Vt.VT_ACTIVATE import org.westford.nativ.linux.Vt.VT_AUTO import org.westford.nativ.linux.Vt.VT_RELDISP import org.westford.nativ.linux.Vt.VT_SETMODE import org.westford.nativ.linux.vt_mode import java.util.logging.Logger @AutoFactory(className = "PrivateTtyFactory", allowSubclasses = true) class Tty(@param:Provided private val libc: Libc, val ttyFd: Int, private val oldKbMode: Int) : AutoCloseable { val vtEnterSignal = Signal<VtEnter>() val vtLeaveSignal = Signal<VtLeave>() private var vtActive = true fun activate(vt: Int) { LOGGER.info(String.format("Activating vt %d.", vt)) if (this.libc.ioctl(this.ttyFd, VT_ACTIVATE.toLong(), vt.toLong()) < 0) { throw RuntimeException("failed to switch to new vt.") } } fun handleVtSignal(signalNumber: Int): Int { if (this.vtActive) { LOGGER.info("Leaving our vt.") this.vtActive = false this.vtLeaveSignal.emit(VtLeave()) if (-1 == this.libc.ioctl(this.ttyFd, VT_RELDISP.toLong(), 1.toLong())) { throw Error(String.format("ioctl[VT_RELDISP, 1] failed: %d", this.libc.errno)) } } else { LOGGER.info("Entering our vt.") if (-1 == this.libc.ioctl(this.ttyFd, VT_RELDISP.toLong(), VT_ACKACQ)) { throw Error(String.format("ioctl[VT_RELDISP, VT_ACKACQ] failed: %d", this.libc.errno)) } this.vtActive = true this.vtEnterSignal.emit(VtEnter()) } return 1 } override fun close() { //restore tty if (this.libc.ioctl(this.ttyFd, KDSKBMUTE.toLong(), 0L) != 0 && this.libc.ioctl(this.ttyFd, KDSKBMODE.toLong(), this.oldKbMode.toLong()) != 0) { LOGGER.warning("failed to restore kb mode") } if (this.libc.ioctl(this.ttyFd, KDSETMODE.toLong(), KD_TEXT) != 0) { LOGGER.warning("failed to set KD_TEXT mode on tty: %m\n") } if (this.vtActive) { this.vtLeaveSignal.emit(VtLeave()) } val mode = vt_mode() mode.frsig = 0 mode.waitv = 0 mode.acqsig = 0 mode.relsig = 0 mode.mode = VT_AUTO if (this.libc.ioctl(this.ttyFd, VT_SETMODE.toLong(), Pointer.ref(mode).address) < 0) { LOGGER.warning("could not reset vt handling\n") } //TODO switch back to old tty this.libc.close(this.ttyFd) } companion object { private val LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) } }
apache-2.0
9b71ea29b1ce091017e38237c7f29649
33.707692
92
0.548537
4.039391
false
false
false
false
wiryls/HomeworkCollectionOfMYLS
2017.AndroidApplicationDevelopment/ODES/app/src/main/java/com/myls/odes/activity/MainActivity.kt
1
12361
package com.myls.odes.activity import android.os.Bundle import android.content.Intent import android.content.res.Configuration import android.support.design.widget.NavigationView import android.support.v4.app.DialogFragment import android.support.v4.app.FragmentManager import android.support.v4.view.GravityCompat import android.support.v4.widget.DrawerLayout import android.support.v7.app.AppCompatActivity import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AlertDialog import android.support.v7.widget.Toolbar import android.util.Log import android.view.MenuItem import android.view.View import android.widget.TextView import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.content_main.* import kotlinx.android.synthetic.main.content_main_drawer_header.view.* import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import com.myls.odes.R import com.myls.odes.application.AnApplication import com.myls.odes.fragment.FragmentAttribute import com.myls.odes.data.RoomInfo import com.myls.odes.data.UserList import com.myls.odes.fragment.FragmentInteraction import com.myls.odes.request.QueryUser import com.myls.odes.request.ResponseCode import com.myls.odes.service.PullJsonService import com.myls.odes.utility.Storage class MainActivity: AppCompatActivity(), FragmentInteraction, NavigationView.OnNavigationItemSelectedListener, FragmentManager.OnBackStackChangedListener { private lateinit var toggle: ActionBarDrawerToggle private lateinit var holder: ViewHolder private lateinit var saver: Storage private lateinit var users: UserList private lateinit var rooms: RoomInfo private lateinit var useri: UserList.Info override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // [Implementing Effective Navigation] // (https://developer.android.com/training/implementing-navigation/nav-drawer.html) // [Material Design with the Android Design Support Library] // (https://www.sitepoint.com/material-design-android-design-support-library/) // [Android CoordinatorLayout] // (https://www.journaldev.com/12790/android-coordinatorlayout) // [Handling Scrolls with CoordinatorLayout] // (https://guides.codepath.com/android/Handling-Scrolls-with-CoordinatorLayout) // [Cheesesquare Sample] // (https://github.com/chrisbanes/cheesesquare) // [Replace toolbar layout according to the displayed fragment] // (https://stackoverflow.com/q/26987503) // [AppBarLayout with recyclerView in nested fragment] // (https://stackoverflow.com/a/31167852) // [How change Activity AppbarLayout in Fragment] // (https://stackoverflow.com/q/33017167) // [Need to disable expand on CollapsingToolbarLayout for certain fragments] // (https://stackoverflow.com/q/30779123) // [collapsingToolbarLayout.setTitle(title) does not work after changing appbarLayout] // (https://stackoverflow.com/q/37600497) // views with(appbar) { setExpanded(false, false) // layoutParams.height = ActionBar.LayoutParams.WRAP_CONTENT } with(toolbar_layout) { // isTitleEnabled = false } with(toolbar) { [email protected](this) } with(supportActionBar!!) { setDisplayHomeAsUpEnabled(true) } with(navigation_view) { setNavigationItemSelectedListener(this@MainActivity) } with(supportFragmentManager) { addOnBackStackChangedListener(this@MainActivity) } // lateinit var toggle = MainActionBarDrawerToggle(this, drawer_layout, toolbar).also { drawer_layout.addDrawerListener(it) it.setToolbarNavigationClickListener{ onBackPressed() } // [AppCompat v7 Toolbar onOptionsItemSelected not called] // (https://stackoverflow.com/a/26590019) } (application as AnApplication).let { saver = it.saver users = it.userlist rooms = it.roominfo } useri = users.list.firstOrNull()?.info?: return onInvalidData() // update UI with(navigation_view.getHeaderView(0)) { holder = ViewHolder( name_view = this.desc_view!!, stid_view = this.stid_view!!).also { it.name_view.text = useri.name it.stid_view.text = useri.stid } } if (savedInstanceState == null) { // Home Page val default = 1 with(navigation_view.menu) { if (size() > default) { onNavigationItemSelected(getItem(default)) } } } } override fun onNavigationItemSelected(item: MenuItem) = true.also { FragmentAttribute.values().find { it.ITEM_ID == item.itemId } ?.let { item.isChecked = it.IS_ROOT onReceiveFragmentAttribute(it) } ?: run { Log.d(TAG, "Cannot find $item, with ${item.itemId}") } } override fun onBackStackChanged() { // For the "Root" fragment if (supportFragmentManager.backStackEntryCount != 0) return with(toggle) { isDrawerIndicatorEnabled = true } with(drawer_layout) { setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED) } } // [Android Sliding Menu using Navigation Drawer] // (https://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/) // [Android - Switch ActionBar Back Button to Navigation Button] // (https://stackoverflow.com/a/36677279) override fun onBackPressed() { // try close drawer with(drawer_layout) { if (isDrawerOpen(GravityCompat.START)) { closeDrawers() return } } // update title with(supportFragmentManager) { if (backStackEntryCount > 0) { getBackStackEntryAt(backStackEntryCount - 1).name.run { FragmentAttribute.values().find { it.name == this }?.TITLE } ?.let { [email protected](it) } ?:let { [email protected] = "" } toolbar_layout.title = title } } super.onBackPressed() } override fun onReceiveFragmentAttribute(item: FragmentAttribute, args: Bundle) { item.let { val fragment = it.CREATE fragment.arguments = args if (it.IS_DIALOG) { with(supportFragmentManager) { val tf = beginTransaction() .apply { findFragmentByTag(it.name)?.let { remove(it) } } .addToBackStack(null) (fragment as DialogFragment).show(tf, it.name) } return@let } with(drawer_layout) { closeDrawers() if (!it.IS_ROOT) setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED) } with(toggle) { if (!it.IS_ROOT) { isDrawerIndicatorEnabled = false } } with(this) { setTitle(it.TITLE) toolbar_layout.title = title } with(supportFragmentManager) { // clear back stack if it is a "root" fragment if (it.IS_ROOT && backStackEntryCount > 0) { val bottom = getBackStackEntryAt(0) popBackStack(bottom.id, FragmentManager.POP_BACK_STACK_INCLUSIVE) } val last = if (!it.IS_ROOT) findFragmentById(FRAGMENT_CONTAINER)?.run { FragmentAttribute.values().find { it.CLASS.isInstance(this) }?.name } else null beginTransaction() .replace(FRAGMENT_CONTAINER, fragment, it.name) .apply { if (last != null) addToBackStack(last) } .commit() // [Android - update toolbar title in activity while handle back navigation with fragment] // (https://stackoverflow.com/a/34020202) } } } override fun requireFloatingActionButton() = fab!! override fun requireFrameLayout() = frame_layout!! override fun onStart() { super.onStart() EVENT_BUS.register(this) } override fun onStop() { EVENT_BUS.unregister(this) super.onStop() } @Subscribe(threadMode = ThreadMode.MAIN) private fun onInvalidData(event: InvalidDataEvent = InvalidDataEvent("UserList is empty")) { Log.e(TAG, event.message) with(AlertDialog.Builder(this)) { setTitle(R.string.error_invalid_model) setMessage(R.string.error_invalid_model_detail) setPositiveButton(R.string.item_ok, { _, _ -> finish() startActivity(Intent(this@MainActivity, LoginActivity::class.java)) }) setCancelable(false) create() show() } } @Subscribe(threadMode = ThreadMode.MAIN) fun onServiceErrorEvent(event: PullJsonService.ErrorEvent) { when(event.request) { is QueryUser.Request -> EVENT_BUS.post(UserInfoUpdatedEvent(false, useri)) else -> return } Log.e(TAG, "Unexpected Error: ${event.code.name} - ${event.request} - ${event.message}") } @Subscribe(threadMode = ThreadMode.MAIN) fun onQueryUserEvent(event: QueryUser.Response) { val done = event.errcode == ResponseCode.SUCCESS.CODE if (done) { with(useri) { event.data.let { name = it.name gender = it.gender grade = it.grade code = it.vcode room = it.room building = it.building location = it.location }} with(holder) { useri.let { stid_view.text = it.stid name_view.text = it.name }} } else { Log.d(TAG, "Unexpected Response: ${event.errcode} - ${event.data.errmsg}") } EVENT_BUS.post(UserInfoUpdatedEvent(done, useri)) } // [Implementing Effective Navigation] // (https://developer.android.com/training/implementing-navigation/nav-drawer.html) override fun onPostCreate(savedInstanceState: Bundle?) = super.onPostCreate(savedInstanceState).also { toggle.syncState() } override fun onConfigurationChanged(newConfig: Configuration?) = super.onConfigurationChanged(newConfig).also { toggle.onConfigurationChanged(newConfig) } private class MainActionBarDrawerToggle(private val activity: MainActivity, drawerLayout: DrawerLayout, toolbar: Toolbar) : ActionBarDrawerToggle(activity, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) { override fun onDrawerOpened(drawerView: View) { super.onDrawerOpened(drawerView) activity.invalidateOptionsMenu() } override fun onDrawerClosed(drawerView: View) { super.onDrawerClosed(drawerView) activity.invalidateOptionsMenu() } } private data class ViewHolder( val name_view: TextView, val stid_view: TextView) data class InvalidDataEvent( var message: String) data class UserInfoUpdatedEvent( val done: Boolean, val user: UserList.Info) companion object { private val TAG = MainActivity::class.java.canonicalName!! private val EVENT_BUS = EventBus.getDefault() private val FRAGMENT_CONTAINER = R.id.frame_layout } }
mit
d46a5113e019d4b4f808004004e422c3
32.773224
125
0.60343
4.800388
false
false
false
false