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
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/ui/migration/MigrationPresenter.kt
1
6643
package eu.kanade.tachiyomi.ui.migration import android.os.Bundle import com.jakewharton.rxrelay.BehaviorRelay import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.database.models.MangaCategory import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.source.LocalSource import eu.kanade.tachiyomi.source.Source import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter import eu.kanade.tachiyomi.util.combineLatest import eu.kanade.tachiyomi.util.syncChaptersWithSource import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get class MigrationPresenter( private val sourceManager: SourceManager = Injekt.get(), private val db: DatabaseHelper = Injekt.get(), private val preferences: PreferencesHelper = Injekt.get() ) : BasePresenter<MigrationController>() { var state = ViewState() private set(value) { field = value stateRelay.call(value) } private val stateRelay = BehaviorRelay.create(state) override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) db.getFavoriteMangas() .asRxObservable() .observeOn(AndroidSchedulers.mainThread()) .doOnNext { state = state.copy(sourcesWithManga = findSourcesWithManga(it)) } .combineLatest(stateRelay.map { it.selectedSource } .distinctUntilChanged(), { library, source -> library to source }) .filter { (_, source) -> source != null } .observeOn(Schedulers.io()) .map { (library, source) -> libraryToMigrationItem(library, source!!.id) } .observeOn(AndroidSchedulers.mainThread()) .doOnNext { state = state.copy(mangaForSource = it) } .subscribe() stateRelay // Render the view when any field other than isReplacingManga changes .distinctUntilChanged { t1, t2 -> t1.isReplacingManga != t2.isReplacingManga } .subscribeLatestCache(MigrationController::render) stateRelay.distinctUntilChanged { state -> state.isReplacingManga } .subscribeLatestCache(MigrationController::renderIsReplacingManga) } fun setSelectedSource(source: Source) { state = state.copy(selectedSource = source, mangaForSource = emptyList()) } fun deselectSource() { state = state.copy(selectedSource = null, mangaForSource = emptyList()) } private fun findSourcesWithManga(library: List<Manga>): List<SourceItem> { val header = SelectionHeader() return library.map { it.source }.toSet() .mapNotNull { if (it != LocalSource.ID) sourceManager.getOrStub(it) else null } .map { SourceItem(it, header) } } private fun libraryToMigrationItem(library: List<Manga>, sourceId: Long): List<MangaItem> { return library.filter { it.source == sourceId }.map(::MangaItem) } fun migrateManga(prevManga: Manga, manga: Manga, replace: Boolean) { val source = sourceManager.get(manga.source) ?: return state = state.copy(isReplacingManga = true) Observable.defer { source.fetchChapterList(manga) } .onErrorReturn { emptyList() } .doOnNext { migrateMangaInternal(source, it, prevManga, manga, replace) } .onErrorReturn { emptyList() } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnUnsubscribe { state = state.copy(isReplacingManga = false) } .subscribe() } private fun migrateMangaInternal(source: Source, sourceChapters: List<SChapter>, prevManga: Manga, manga: Manga, replace: Boolean) { val flags = preferences.migrateFlags().getOrDefault() val migrateChapters = MigrationFlags.hasChapters(flags) val migrateCategories = MigrationFlags.hasCategories(flags) val migrateTracks = MigrationFlags.hasTracks(flags) db.inTransaction { // Update chapters read if (migrateChapters) { try { syncChaptersWithSource(db, sourceChapters, manga, source) } catch (e: Exception) { // Worst case, chapters won't be synced } val prevMangaChapters = db.getChapters(prevManga).executeAsBlocking() val maxChapterRead = prevMangaChapters.filter { it.read } .maxBy { it.chapter_number }?.chapter_number if (maxChapterRead != null) { val dbChapters = db.getChapters(manga).executeAsBlocking() for (chapter in dbChapters) { if (chapter.isRecognizedNumber && chapter.chapter_number <= maxChapterRead) { chapter.read = true } } db.insertChapters(dbChapters).executeAsBlocking() } } // Update categories if (migrateCategories) { val categories = db.getCategoriesForManga(prevManga).executeAsBlocking() val mangaCategories = categories.map { MangaCategory.create(manga, it) } db.setMangaCategories(mangaCategories, listOf(manga)) } // Update track if (migrateTracks) { val tracks = db.getTracks(prevManga).executeAsBlocking() for (track in tracks) { track.id = null track.manga_id = manga.id!! } db.insertTracks(tracks).executeAsBlocking() } // Update favorite status if (replace) { prevManga.favorite = false db.updateMangaFavorite(prevManga).executeAsBlocking() } manga.favorite = true db.updateMangaFavorite(manga).executeAsBlocking() // SearchPresenter#networkToLocalManga may have updated the manga title, so ensure db gets updated title db.updateMangaTitle(manga).executeAsBlocking() } } }
apache-2.0
f233dde2316d57558d2a9060dd9de31e
42.136364
116
0.619148
5.059406
false
false
false
false
xiprox/Tensuu
app/src/main/java/tr/xip/scd/tensuu/ui/login/LoginActivity.kt
1
2163
package tr.xip.scd.tensuu.ui.login import android.content.Intent import android.os.Bundle import android.support.design.widget.Snackbar import com.hannesdorfmann.mosby3.mvp.MvpActivity import kotlinx.android.synthetic.main.activity_login.* import tr.xip.scd.tensuu.R import tr.xip.scd.tensuu.ui.main.MainActivity import tr.xip.scd.tensuu.common.ext.toVisibility import tr.xip.scd.tensuu.common.ext.watchForChange class LoginActivity : MvpActivity<LoginView, LoginPresenter>(), LoginView { override fun createPresenter(): LoginPresenter = LoginPresenter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) email.watchForChange { presenter.onEmailChanged(it) } password.watchForChange { presenter.onPasswordChanged(it) } signIn.setOnClickListener { presenter.onSignInClicked(email.text.toString(), password.text.toString()) } presenter.init() } override fun setEmailError(error: String?) { emailLayout?.error = error } override fun setPasswordError(error: String?) { passwordLayout?.error = error } override fun enableEmail(enable: Boolean) { email?.isEnabled = enable } override fun enablePassword(enable: Boolean) { password?.isEnabled = enable } override fun enableSignInButton(enable: Boolean) { signIn?.isEnabled = enable } override fun showProgress(show: Boolean) { progress?.visibility = show.toVisibility() } override fun showSnackbar(text: String, actionText: String?, actionListener: (() -> Unit)?) { val snackbar = Snackbar.make(coordinatorLayout, text, Snackbar.LENGTH_LONG) if (actionText != null && actionListener != null) { snackbar.setAction(actionText, { actionListener.invoke() }) } snackbar.show() } override fun startMainActivity() { startActivity(Intent(this, MainActivity::class.java)) } override fun die() { finish() } }
gpl-3.0
193342a75c31cba3e739ef8060089df8
27.473684
97
0.666204
4.602128
false
false
false
false
square/wire
wire-library/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/ProfileParser.kt
1
3821
/* * Copyright (C) 2016 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.schema.internal import com.squareup.wire.schema.Location import com.squareup.wire.schema.internal.parser.OptionElement import com.squareup.wire.schema.internal.parser.OptionReader import com.squareup.wire.schema.internal.parser.SyntaxReader /** Parses `.wire` files. */ class ProfileParser( private val location: Location, data: String ) { private val reader = SyntaxReader(data.toCharArray(), location) private val imports = mutableListOf<String>() private val typeConfigs = mutableListOf<TypeConfigElement>() /** Output package name, or null if none yet encountered. */ private var packageName: String? = null fun read(): ProfileFileElement { val label = reader.readWord() reader.expect(label == "syntax") { "expected 'syntax'" } reader.require('=') val syntaxString = reader.readQuotedString() reader.expect(syntaxString == "wire2") { "expected 'wire2'" } reader.require(';') while (true) { val documentation = reader.readDocumentation() if (reader.exhausted()) { return ProfileFileElement( location = location, packageName = packageName, imports = imports, typeConfigs = typeConfigs ) } readDeclaration(documentation) } } private fun readDeclaration(documentation: String) { val location = reader.location() val label = reader.readWord() when (label) { "package" -> { reader.expect(packageName == null, location) { "too many package names" } packageName = reader.readName() reader.require(';') } "import" -> { val importString = reader.readString() imports.add(importString) reader.require(';') } "type" -> typeConfigs.add(readTypeConfig(location, documentation)) else -> throw reader.unexpected("unexpected label: $label", location) } } /** Reads a type config and returns it. */ private fun readTypeConfig( location: Location, documentation: String ): TypeConfigElement { val name = reader.readDataType() val withOptions = mutableListOf<OptionElement>() var target: String? = null var adapter: String? = null reader.require('{') while (!reader.peekChar('}')) { val wordLocation = reader.location() val word = reader.readWord() when (word) { "target" -> { reader.expect(target == null, wordLocation) { "too many targets" } target = reader.readWord() reader.expect(reader.readWord() == "using") { "expected 'using'" } val adapterType = reader.readWord() reader.require('#') val adapterConstant = reader.readWord() reader.require(';') adapter = "$adapterType#$adapterConstant" } "with" -> { withOptions += OptionReader(reader).readOption('=') reader.require(';') } else -> throw reader.unexpected("unexpected label: $word", wordLocation) } } return TypeConfigElement( location = location, type = name, documentation = documentation, with = withOptions, target = target, adapter = adapter ) } }
apache-2.0
18a769f44847a2efc52ffdf105ea0a4c
30.319672
81
0.646166
4.371854
false
true
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/refactoringTesting/cases/MoveRefactoringCase.kt
3
2583
// 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.cases import com.intellij.openapi.options.ConfigurationException import com.intellij.openapi.project.Project import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.actions.internal.refactoringTesting.RandomMoveRefactoringResult import org.jetbrains.kotlin.idea.actions.internal.refactoringTesting.RefactoringCase import org.jetbrains.kotlin.idea.core.util.toPsiFile import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveKotlinDeclarationsHandler import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.RefactoringConflictsFoundException import org.jetbrains.kotlin.psi.KtClass internal class MoveRefactoringCase : RefactoringCase { override fun tryCreateAndRun(project: Project): RandomMoveRefactoringResult { val projectFiles = project.files() if (projectFiles.isEmpty()) RandomMoveRefactoringResult.Failed fun getRandomKotlinClassOrNull(): KtClass? { val classes = PsiTreeUtil.collectElementsOfType(projectFiles.random().toPsiFile(project), KtClass::class.java) return if (classes.isNotEmpty()) return classes.random() else null } val targetClass: KtClass? = null val sourceClass = getRandomKotlinClassOrNull() ?: return RandomMoveRefactoringResult.Failed val sourceClassAsArray = arrayOf(sourceClass) val testDataKeeper = TestDataKeeper("no data") val handler = MoveKotlinDeclarationsHandler(MoveKotlinDeclarationsHandlerTestActions(testDataKeeper)) if (!handler.canMove(sourceClassAsArray, targetClass, /*reference = */ null)) { return RandomMoveRefactoringResult.Failed } try { handler.doMove(project, sourceClassAsArray, targetClass, null) } catch (e: Throwable) { return when (e) { is NotImplementedError, is FailedToRunCaseException, is RefactoringConflictsFoundException, is ConfigurationException -> RandomMoveRefactoringResult.Failed else -> RandomMoveRefactoringResult.ExceptionCaused( testDataKeeper.caseData, "${e.javaClass.typeName}: ${e.message ?: "No message"}" ) } } return RandomMoveRefactoringResult.Success(testDataKeeper.caseData) } }
apache-2.0
99b2fc787eb912b47789a2a0ea4fee03
43.534483
158
0.724739
5.176353
false
true
false
false
PolymerLabs/arcs
java/arcs/core/storage/StorageKeyProtocol.kt
1
1204
package arcs.core.storage /** All [StorageKey] protocols understood by Arcs. */ enum class StorageKeyProtocol( /** Full name of the protocol, e.g. "ramdisk", "reference-mode". */ private val longId: String, /** Short, single character identifier for the protocol. */ private val shortId: String ) { // Sorted alphabetically by shortProtocol. Create("create", "c"), Database("db", "d"), ReferenceMode("reference-mode", "e"), Foreign("foreign", "f"), Inline("inline", "i"), Join("join", "j"), InMemoryDatabase("memdb", "m"), RamDisk("ramdisk", "r"), Dummy("dummy", "u"), Volatile("volatile", "v"); val id = shortId val protocol = "$shortId|" override fun toString() = protocol companion object { private val SHORT_PROTOCOLS = values().associateBy { it.shortId } private val LONG_PROTOCOLS = values().associateBy { it.longId } fun parseProtocol(protocol: String): StorageKeyProtocol { // Try short protocol first. SHORT_PROTOCOLS[protocol]?.let { return it } // Fall back to long protocol. return LONG_PROTOCOLS[protocol] ?: throw IllegalArgumentException( "Unknown storage key protocol: $protocol" ) } } }
bsd-3-clause
892dfd5380c5369b0c52460730a2fdd2
28.365854
72
0.656146
4.095238
false
false
false
false
tommykw/android-optimize-resources-plugin
src/main/kotlin/ResourceOptimizeAction.kt
1
5265
import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiManager import com.intellij.psi.xml.XmlFile import utils.findChildByRelativePath import utils.findFilesRecursive import utils.isCommentOut import utils.isMatched import java.io.BufferedReader import java.io.InputStreamReader import com.intellij.openapi.ui.Messages class ResourceOptimizeAction : AnAction() { private val allowValuesXmlList = listOf("colors.xml", "dimens.xml", "strings.xml", "integers.xml") override fun actionPerformed(event: AnActionEvent) { val project = event.project ?: return optimizeValuesXmlList(project) optimizeDrawablePngList(project) Messages.showMessageDialog(project, "Optimize Resources has successfully completed", "Optimize Resource Result", Messages.getInformationIcon()) } private fun optimizeDrawablePngList(project: Project) { val appName = findAppName(project) ?: return findDrawablePngList(project).forEach { png -> val resourceName = png.name.replace(".png", "") val child = project.baseDir.findChildByRelativePath("/$appName/src/main") ?: return val files = child.findFilesRecursive() var isDeletable = true files.forEach FILES_LOOP@ { targetFile -> val reader = BufferedReader(InputStreamReader(targetFile.inputStream, "UTF-8")) var line = reader.readLine() while (line != null) { val appResName = "R.drawable.${resourceName}" val assetResName = "@drawable/${resourceName}" if (line.isMatched(appResName) || line.isMatched(assetResName)) { if (line.isCommentOut().not()) { isDeletable = false break } } line = reader.readLine() } reader.close() if (isDeletable) return@FILES_LOOP } PsiManager.getInstance(project).findFile(png)?.let { file -> WriteCommandAction.runWriteCommandAction(project, { file.delete() }) } } } private fun optimizeValuesXmlList(project: Project) { val appName = findAppName(project) ?: return findValuesXmlList(project).forEach { xml -> if (allowValuesXmlList.contains(xml.name).not()) return@forEach val resourceName = xml.name.replace("s.xml", "") (PsiManager.getInstance(project).findFile(xml) as XmlFile).rootTag?.findSubTags(resourceName)?.forEach { it.attributes.forEach { attr -> val appResName = "R.$resourceName.${attr.displayValue}" val assetResName = "@$resourceName/${attr.displayValue}" val child = project.baseDir.findChildByRelativePath("/$appName/src/main") ?: return val files = child.findFilesRecursive() var isDeletable = true files.forEach FILES_LOOP@ { targetFile -> val reader = BufferedReader(InputStreamReader(targetFile.inputStream, "UTF-8")) var line = reader.readLine() while (line != null) { if (line.isMatched(appResName) || line.isMatched(assetResName)) { if (line.isCommentOut().not()) { isDeletable = false break } } line = reader.readLine() } reader.close() if (isDeletable.not()) return@FILES_LOOP } if (isDeletable) WriteCommandAction.runWriteCommandAction(project, { attr.parent.delete() }) } } } } private fun findAppName(project: Project): String? { project.baseDir.children.forEach { if (it.isDirectory) { val child = project.baseDir.findChildByRelativePath("/${it.name}/src/main") if (child != null) return it.name } } return null } private fun findValuesXmlList(project: Project): Array<VirtualFile> { val appName = findAppName(project) ?: return arrayOf() val child = project.baseDir.findChildByRelativePath("/${appName}/src/main/res/values") ?: return arrayOf() return child.children } private fun findDrawablePngList(project: Project): List<VirtualFile> { val pngList = arrayListOf<VirtualFile>() val appName = findAppName(project) ?: return pngList.toList() val child = project.baseDir.findChildByRelativePath("/${appName}/src/main/res/drawable") ?: return pngList.toList() child.children.forEach { if (it.extension == "png") pngList.add(it) } return pngList.toList() } }
apache-2.0
7440581e2e03b7492c0dcd839895bee5
42.883333
151
0.583666
5.156709
false
false
false
false
blindpirate/gradle
build-logic/packaging/src/main/kotlin/gradlebuild/shade/ArtifactTypes.kt
3
984
/* * Copyright 2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gradlebuild.shade object ArtifactTypes { const val relocatedClassesAndAnalysisType = "relocatedClassesAndAnalysis" const val relocatedClassesType = "relocatedClasses" const val entryPointsType = "entryPoints" const val classTreesType = "classTrees" const val manifestsType = "manifests" const val buildReceiptType = "buildReceipt" }
apache-2.0
993fab5bc9743c9a1b67a834160e4415
35.444444
77
0.751016
4.296943
false
false
false
false
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/database/LogDatabase.kt
1
7544
package org.thoughtcrime.securesms.database import android.annotation.SuppressLint import android.app.Application import android.content.ContentValues import android.database.Cursor import net.zetetic.database.sqlcipher.SQLiteDatabase import net.zetetic.database.sqlcipher.SQLiteOpenHelper import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.crypto.DatabaseSecret import org.thoughtcrime.securesms.crypto.DatabaseSecretProvider import org.thoughtcrime.securesms.database.model.LogEntry import org.thoughtcrime.securesms.util.ByteUnit import org.thoughtcrime.securesms.util.CursorUtil import org.thoughtcrime.securesms.util.SqlUtil import org.thoughtcrime.securesms.util.Stopwatch import java.io.Closeable import java.util.concurrent.TimeUnit /** * Stores logs. * * Logs are very performance critical. Even though this database is written to on a low-priority background thread, we want to keep throughput high and ensure * that we aren't creating excess garbage. * * This is it's own separate physical database, so it cannot do joins or queries with any other * tables. */ class LogDatabase private constructor( application: Application, private val databaseSecret: DatabaseSecret ) : SQLiteOpenHelper( application, DATABASE_NAME, databaseSecret.asString(), null, DATABASE_VERSION, 0, SqlCipherErrorHandler(DATABASE_NAME), SqlCipherDatabaseHook() ), SignalDatabase { companion object { private val TAG = Log.tag(LogDatabase::class.java) private val MAX_FILE_SIZE = ByteUnit.MEGABYTES.toBytes(10) private val DEFAULT_LIFESPAN = TimeUnit.DAYS.toMillis(2) private val LONGER_LIFESPAN = TimeUnit.DAYS.toMillis(7) private const val DATABASE_VERSION = 2 private const val DATABASE_NAME = "signal-logs.db" private const val TABLE_NAME = "log" private const val ID = "_id" private const val CREATED_AT = "created_at" private const val KEEP_LONGER = "keep_longer" private const val BODY = "body" private const val SIZE = "size" private val CREATE_TABLE = """ CREATE TABLE $TABLE_NAME ( $ID INTEGER PRIMARY KEY, $CREATED_AT INTEGER, $KEEP_LONGER INTEGER DEFAULT 0, $BODY TEXT, $SIZE INTEGER ) """.trimIndent() private val CREATE_INDEXES = arrayOf( "CREATE INDEX keep_longer_index ON $TABLE_NAME ($KEEP_LONGER)", "CREATE INDEX log_created_at_keep_longer_index ON $TABLE_NAME ($CREATED_AT, $KEEP_LONGER)" ) @SuppressLint("StaticFieldLeak") // We hold an Application context, not a view context @Volatile private var instance: LogDatabase? = null @JvmStatic fun getInstance(context: Application): LogDatabase { if (instance == null) { synchronized(LogDatabase::class.java) { if (instance == null) { SqlCipherLibraryLoader.load(context) instance = LogDatabase(context, DatabaseSecretProvider.getOrCreateDatabaseSecret(context)) } } } return instance!! } } override fun onCreate(db: SQLiteDatabase) { Log.i(TAG, "onCreate()") db.execSQL(CREATE_TABLE) CREATE_INDEXES.forEach { db.execSQL(it) } } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { Log.i(TAG, "onUpgrade($oldVersion, $newVersion)") if (oldVersion < 2) { db.execSQL("DROP TABLE log") db.execSQL("CREATE TABLE log (_id INTEGER PRIMARY KEY, created_at INTEGER, keep_longer INTEGER DEFAULT 0, body TEXT, size INTEGER)") db.execSQL("CREATE INDEX keep_longer_index ON log (keep_longer)") db.execSQL("CREATE INDEX log_created_at_keep_longer_index ON log (created_at, keep_longer)") } } override fun onOpen(db: SQLiteDatabase) { db.enableWriteAheadLogging() db.setForeignKeyConstraintsEnabled(true) } override fun getSqlCipherDatabase(): SQLiteDatabase { return writableDatabase } fun insert(logs: List<LogEntry>, currentTime: Long) { val db = writableDatabase db.beginTransaction() try { logs.forEach { log -> db.insert(TABLE_NAME, null, buildValues(log)) } db.delete( TABLE_NAME, "($CREATED_AT < ? AND $KEEP_LONGER = ?) OR ($CREATED_AT < ? AND $KEEP_LONGER = ?)", SqlUtil.buildArgs(currentTime - DEFAULT_LIFESPAN, 0, currentTime - LONGER_LIFESPAN, 1) ) db.setTransactionSuccessful() } finally { db.endTransaction() } } fun getAllBeforeTime(time: Long): Reader { return CursorReader(readableDatabase.query(TABLE_NAME, arrayOf(BODY), "$CREATED_AT < ?", SqlUtil.buildArgs(time), null, null, null)) } fun getRangeBeforeTime(start: Int, length: Int, time: Long): List<String> { val lines = mutableListOf<String>() readableDatabase.query(TABLE_NAME, arrayOf(BODY), "$CREATED_AT < ?", SqlUtil.buildArgs(time), null, null, null, "$start,$length").use { cursor -> while (cursor.moveToNext()) { lines.add(CursorUtil.requireString(cursor, BODY)) } } return lines } fun trimToSize() { val currentTime = System.currentTimeMillis() val stopwatch = Stopwatch("trim") val sizeOfSpecialLogs: Long = getSize("$KEEP_LONGER = ?", arrayOf("1")) val remainingSize = MAX_FILE_SIZE - sizeOfSpecialLogs stopwatch.split("keepers-size") if (remainingSize <= 0) { writableDatabase.delete(TABLE_NAME, "$KEEP_LONGER = ?", arrayOf("0")) return } val sizeDiffThreshold = MAX_FILE_SIZE * 0.01 var lhs: Long = currentTime - DEFAULT_LIFESPAN var rhs: Long = currentTime var mid: Long = 0 var sizeOfChunk: Long while (lhs < rhs - 2) { mid = (lhs + rhs) / 2 sizeOfChunk = getSize("$CREATED_AT > ? AND $CREATED_AT < ? AND $KEEP_LONGER = ?", SqlUtil.buildArgs(mid, currentTime, 0)) if (sizeOfChunk > remainingSize) { lhs = mid } else if (sizeOfChunk < remainingSize) { if (remainingSize - sizeOfChunk < sizeDiffThreshold) { break } else { rhs = mid } } else { break } } stopwatch.split("binary-search") writableDatabase.delete(TABLE_NAME, "$CREATED_AT < ? AND $KEEP_LONGER = ?", SqlUtil.buildArgs(mid, 0)) stopwatch.split("delete") stopwatch.stop(TAG) } fun getLogCountBeforeTime(time: Long): Int { readableDatabase.query(TABLE_NAME, arrayOf("COUNT(*)"), "$CREATED_AT < ?", SqlUtil.buildArgs(time), null, null, null).use { cursor -> return if (cursor.moveToFirst()) { cursor.getInt(0) } else { 0 } } } private fun buildValues(log: LogEntry): ContentValues { return ContentValues().apply { put(CREATED_AT, log.createdAt) put(KEEP_LONGER, if (log.keepLonger) 1 else 0) put(BODY, log.body) put(SIZE, log.body.length) } } private fun getSize(query: String?, args: Array<String>?): Long { readableDatabase.query(TABLE_NAME, arrayOf("SUM($SIZE)"), query, args, null, null, null).use { cursor -> return if (cursor.moveToFirst()) { cursor.getLong(0) } else { 0 } } } interface Reader : Iterator<String>, Closeable class CursorReader(private val cursor: Cursor) : Reader { override fun hasNext(): Boolean { return !cursor.isLast && cursor.count > 0 } override fun next(): String { cursor.moveToNext() return CursorUtil.requireString(cursor, BODY) } override fun close() { cursor.close() } } }
gpl-3.0
41d8718dc860591c34bc37308a69b33f
29.419355
158
0.665562
4.008502
false
false
false
false
hermantai/samples
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-3/app/src/main/java/dev/mfazio/pennydrop/types/NewPlayer.kt
1
1150
package dev.mfazio.pennydrop.types import androidx.databinding.ObservableBoolean import dev.mfazio.pennydrop.game.AI data class NewPlayer( var playerName: String = "", val isHuman: ObservableBoolean = ObservableBoolean(true), val canBeRemoved: Boolean = true, val canBeToggled: Boolean = true, var isIncluded: ObservableBoolean = ObservableBoolean(!canBeRemoved), var selectedAIPosition: Int = -1 ) { fun selectedAI() = if (!isHuman.get()) { AI.basicAI.getOrNull(selectedAIPosition) } else { null } fun toPlayer() = Player( if (this.isHuman.get()) this.playerName else (this.selectedAI()?.name ?: "AI"), this.isHuman.get(), this.selectedAI() ) override fun toString() = listOf( "playerName" to this.playerName, "isIncluded" to this.isIncluded.get(), "isHuman" to this.isHuman.get(), "canBeRemoved" to this.canBeRemoved, "canBeToggled" to this.canBeToggled, "selectedAI" to (this.selectedAI()?.name ?: "N/A") ).joinToString(", ", "NewPlayer(", ")") { (property, value) -> "$property=$value" } }
apache-2.0
ebe854c16bebdc76d35d1bd0c6980995
30.944444
87
0.637391
4.151625
false
false
false
false
hzsweers/CatchUp
app/src/debug/kotlin/io/sweers/catchup/data/VariantDataModule.kt
1
2255
/* * Copyright (C) 2019. Zac Sweers * * 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 io.sweers.catchup.data import android.content.Context import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import dagger.multibindings.IntoSet import io.sweers.catchup.util.injection.qualifiers.ApplicationContext import io.sweers.catchup.util.injection.qualifiers.NetworkInterceptor import okhttp3.Interceptor import okhttp3.logging.HttpLoggingInterceptor import okhttp3.logging.HttpLoggingInterceptor.Level.BASIC import okhttp3.logging.HttpLoggingInterceptor.Logger import timber.log.Timber import javax.inject.Singleton private inline fun httpLoggingInterceptor(level: HttpLoggingInterceptor.Level = HttpLoggingInterceptor.Level.NONE, crossinline logger: (String) -> Unit): HttpLoggingInterceptor { return HttpLoggingInterceptor( object : Logger { override fun log(message: String) { logger(message) } } ).also { it.level = level } } @InstallIn(SingletonComponent::class) @Module object VariantDataModule { @Singleton @Provides @NetworkInterceptor @IntoSet internal fun provideLoggingInterceptor(): Interceptor = httpLoggingInterceptor(BASIC) { message -> Timber.tag("OkHttp") .v(message) } // @Provides // @Singleton // @NetworkInterceptor // @IntoSet // internal fun provideChuckInterceptor(@ApplicationContext context: Context): Interceptor = // ChuckInterceptor(context) @Singleton @Provides @IntoSet internal fun provideMockDataInterceptor( @ApplicationContext context: Context, debugPreferences: DebugPreferences ): Interceptor = MockDataInterceptor(context, debugPreferences) }
apache-2.0
96037d5223f95e0d8f0afa3ee2adbc42
30.760563
178
0.772062
4.537223
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/reset/GitNewResetDialog.kt
7
4588
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.reset import com.intellij.dvcs.DvcsUtil import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.dsl.builder.bind import com.intellij.ui.dsl.builder.panel import com.intellij.vcs.log.VcsFullCommitDetails import com.intellij.vcs.log.util.VcsUserUtil import com.intellij.xml.util.XmlStringUtil import git4idea.GitUtil import git4idea.i18n.GitBundle import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import javax.swing.JComponent class GitNewResetDialog(private val project: Project, private val commits: Map<GitRepository, VcsFullCommitDetails>, defaultMode: GitResetMode) : DialogWrapper(project) { var resetMode: GitResetMode = defaultMode private set init { init() title = GitBundle.message("git.reset.dialog.title") setOKButtonText(GitBundle.message("git.reset.button")) } override fun createCenterPanel(): JComponent { return panel { row { label(XmlStringUtil.wrapInHtml(prepareDescription(project, commits))) } row { label(XmlStringUtil.wrapInHtml(GitBundle.message("git.reset.dialog.description"))) } buttonsGroup { for (mode in GitResetMode.values()) { val name = mode.getName() row { radioButton(name, mode) .applyToComponent { mnemonic = name[0].code } .comment(mode.description) } } }.bind(::resetMode) } } override fun getHelpId() = DIALOG_ID companion object { private const val DIALOG_ID = "git.new.reset.dialog" //NON-NLS private fun prepareDescription(project: Project, commits: Map<GitRepository, VcsFullCommitDetails>): @Nls String { val isMultiRepo = GitRepositoryManager.getInstance(project).moreThanOneRoot() val onlyCommit = commits.entries.singleOrNull() if (onlyCommit != null && !isMultiRepo) { val (key, value) = onlyCommit return "${getSourceText(key)} -> ${getTargetText(value)}" //NON-NLS } val desc: @Nls StringBuilder = StringBuilder() for ((repository, commit) in commits) { val sourceInRepo = GitBundle.message("git.reset.dialog.description.source.in.repository", getSourceText(repository), DvcsUtil.getShortRepositoryName(repository)) desc.append("${sourceInRepo} -> ${getTargetText(commit)}<br/>") //NON-NLS } return desc.toString() //NON-NLS } private fun getTargetText(commit: VcsFullCommitDetails): @Nls String { val commitMessage = StringUtil.shortenTextWithEllipsis(commit.subject, 40, 0) val author = StringUtil.shortenTextWithEllipsis(VcsUserUtil.getShortPresentation(commit.author), 40, 0) return GitBundle.message("git.reset.dialog.description.commit.details.by.author", HtmlBuilder() .append(HtmlChunk.text(commit.id.toShortString()).bold()) .append(HtmlChunk.text(" \"$commitMessage\"")) .toString(), HtmlChunk.tag("code").addText(author)) } private fun getSourceText(repository: GitRepository): @NonNls String { val currentBranch = repository.currentBranch val currentRevision = repository.currentRevision val text = when { currentBranch != null -> currentBranch.name currentRevision != null -> "${GitUtil.HEAD} (${DvcsUtil.getShortHash(currentRevision)})" //NON-NLS else -> GitUtil.HEAD //NON-NLS } return HtmlChunk.text(text).bold().toString() } } }
apache-2.0
7b3773e5d09b105299f71ae4094dd8ba
38.560345
118
0.670227
4.606426
false
false
false
false
jk1/intellij-community
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/inference/ContractInferenceIndex.kt
3
3989
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.dataFlow.inference import com.intellij.lang.LighterAST import com.intellij.lang.LighterASTNode import com.intellij.psi.JavaTokenType import com.intellij.psi.impl.source.JavaLightStubBuilder import com.intellij.psi.impl.source.JavaLightTreeUtil import com.intellij.psi.impl.source.PsiMethodImpl import com.intellij.psi.impl.source.tree.JavaElementType.* import com.intellij.psi.impl.source.tree.LightTreeUtil import com.intellij.psi.impl.source.tree.RecursiveLighterASTNodeWalkingVisitor import com.intellij.psi.stub.JavaStubImplUtil import com.intellij.util.gist.GistManager import java.util.* /** * @author peter */ private val gist = GistManager.getInstance().newPsiFileGist("contractInference", 10, MethodDataExternalizer) { file -> indexFile(file.node.lighterAST) } private fun indexFile(tree: LighterAST): Map<Int, MethodData> { val visitor = InferenceVisitor(tree) visitor.visitNode(tree.root) return visitor.result } private class InferenceVisitor(val tree : LighterAST) : RecursiveLighterASTNodeWalkingVisitor(tree) { var methodIndex = 0 val volatileFieldNames = HashSet<String>() val result = HashMap<Int, MethodData>() override fun visitNode(element: LighterASTNode) { when(element.tokenType) { CLASS -> gatherFields(element) METHOD -> { calcData(element)?.let { data -> result[methodIndex] = data } methodIndex++ } } if (JavaLightStubBuilder.isCodeBlockWithoutStubs(element)) return super.visitNode(element) } private fun gatherFields(aClass: LighterASTNode) { val fields = LightTreeUtil.getChildrenOfType(tree, aClass, FIELD) for (field in fields) { val fieldName = JavaLightTreeUtil.getNameIdentifierText(tree, field) if (fieldName != null && JavaLightTreeUtil.hasExplicitModifier(tree, field, JavaTokenType.VOLATILE_KEYWORD)) { volatileFieldNames.add(fieldName) } } } private fun calcData(method: LighterASTNode): MethodData? { val body = LightTreeUtil.firstChildOfType(tree, method, CODE_BLOCK) ?: return null val statements = ContractInferenceInterpreter.getStatements(body, tree) val contracts = ContractInferenceInterpreter(tree, method, body).inferContracts(statements) val nullityVisitor = MethodReturnInferenceVisitor(tree, body) val purityVisitor = PurityInferenceVisitor(tree, body, volatileFieldNames) for (statement in statements) { walkMethodBody(statement) { nullityVisitor.visitNode(it); purityVisitor.visitNode(it) } } val notNullParams = inferNotNullParameters(tree, method, statements) return createData(body, contracts, nullityVisitor.result, purityVisitor.result, notNullParams) } private fun walkMethodBody(root: LighterASTNode, processor: (LighterASTNode) -> Unit) { object : RecursiveLighterASTNodeWalkingVisitor(tree) { override fun visitNode(element: LighterASTNode) { val type = element.tokenType if (type === CLASS || type === FIELD || type === METHOD || type === ANNOTATION_METHOD || type === LAMBDA_EXPRESSION) return processor(element) super.visitNode(element) } }.visitNode(root) } private fun createData(body: LighterASTNode, contracts: List<PreContract>, methodReturn: MethodReturnInferenceResult?, purity: PurityInferenceResult?, notNullParams: BitSet): MethodData? { if (methodReturn == null && purity == null && contracts.isEmpty() && notNullParams.isEmpty) return null return MethodData(methodReturn, purity, contracts, notNullParams, body.startOffset, body.endOffset) } } fun getIndexedData(method: PsiMethodImpl): MethodData? = gist.getFileData(method.containingFile)?.get(JavaStubImplUtil.getMethodStubIndex(method))
apache-2.0
c9a766484dda7d7155c9263ec0c477f2
39.714286
146
0.735773
4.692941
false
false
false
false
mvmike/min-cal-widget
app/src/main/kotlin/cat/mvmike/minimalcalendarwidget/infrastructure/resolver/GraphicResolver.kt
1
4543
// Copyright (c) 2016, Miquel Martí <[email protected]> // See LICENSE for licensing information package cat.mvmike.minimalcalendarwidget.infrastructure.resolver import android.content.Context import android.graphics.Color import android.graphics.Typeface import android.text.Spannable import android.text.SpannableString import android.text.style.ForegroundColorSpan import android.text.style.RelativeSizeSpan import android.text.style.StyleSpan import android.widget.RemoteViews import androidx.core.content.ContextCompat import cat.mvmike.minimalcalendarwidget.R object GraphicResolver { // ADD VISUAL COMPONENTS TO WIDGET fun addToWidget(widgetRemoteView: RemoteViews, remoteView: RemoteViews) = widgetRemoteView.addView(R.id.calendar_days_layout, remoteView) // MONTH YEAR HEADER fun createMonthAndYearHeader( context: Context, widgetRemoteView: RemoteViews, text: String, textColour: Int, headerRelativeYearSize: Float, textRelativeSize: Float ) { val monthAndYearSpSt = SpannableString(text) monthAndYearSpSt.setSpan(RelativeSizeSpan(textRelativeSize), 0, monthAndYearSpSt.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) monthAndYearSpSt.setSpan(RelativeSizeSpan(headerRelativeYearSize * textRelativeSize), text.length - 4, text.length, 0) monthAndYearSpSt.setSpan(ForegroundColorSpan(getColour(context, textColour)), 0, text.length, 0) widgetRemoteView.setTextViewText(R.id.month_year_label, monthAndYearSpSt) } // DAY HEADER fun createDaysHeaderRow(context: Context) = getById(context, R.layout.row_header) fun addToDaysHeaderRow( context: Context, daysHeaderRow: RemoteViews, text: String, textColour: Int, layoutId: Int, viewId: Int, dayHeaderBackgroundColour: Int?, textRelativeSize: Float ) { val dayHeaderSpSt = SpannableString(text) dayHeaderSpSt.setSpan(RelativeSizeSpan(textRelativeSize), 0, dayHeaderSpSt.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) val dayRv = getById(context, layoutId) dayRv.setTextViewText(android.R.id.text1, dayHeaderSpSt) dayRv.setTextColor(android.R.id.text1, getColour(context, textColour)) dayHeaderBackgroundColour?.let { setBackgroundColor(dayRv, viewId, it) } daysHeaderRow.addView(R.id.row_header, dayRv) } // DAY fun createDaysRow(context: Context) = getById(context, R.layout.row_week) @SuppressWarnings("LongParameterList") fun addToDaysRow( context: Context, weekRow: RemoteViews, dayLayout: Int, viewId: Int, text: String, textColour: Int, dayOfMonthInBold: Boolean, instancesColour: Int, instancesRelativeSize: Float, dayBackgroundColour: Int?, textRelativeSize: Float ) { val daySpSt = SpannableString(text) if (dayOfMonthInBold) { daySpSt.setSpan(StyleSpan(Typeface.BOLD), 0, daySpSt.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } else { daySpSt.setSpan(StyleSpan(Typeface.BOLD), daySpSt.length - 1, daySpSt.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } daySpSt.setSpan(ForegroundColorSpan(instancesColour), daySpSt.length - 1, daySpSt.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) daySpSt.setSpan(RelativeSizeSpan(textRelativeSize), 0, daySpSt.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) daySpSt.setSpan(RelativeSizeSpan(instancesRelativeSize), daySpSt.length - 1, daySpSt.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) val dayRv = getById(context, dayLayout) dayRv.setTextViewText(android.R.id.text1, daySpSt) dayRv.setTextColor(android.R.id.text1, getColour(context, textColour)) dayBackgroundColour?.let { setBackgroundColor(dayRv, viewId, it) } weekRow.addView(R.id.row_week, dayRv) } // COLOUR fun getColour(context: Context, id: Int) = ContextCompat.getColor(context, id) fun getColourAsString(context: Context, id: Int) = context.resources.getString(id) fun parseColour(colourString: String) = Color.parseColor(colourString) fun setBackgroundColor( remoteViews: RemoteViews, viewId: Int, colour: Int ) = remoteViews.setInt(viewId, "setBackgroundColor", colour) // INTERNAL UTILS private fun getById(context: Context, layoutId: Int) = RemoteViews(context.packageName, layoutId) }
bsd-3-clause
323fa9fa2fa7419dffeb57013a985939
36.53719
141
0.7107
4.163153
false
false
false
false
marius-m/wt4
components/src/main/java/lt/markmerkk/mvp/LogEditService2Impl.kt
1
2442
package lt.markmerkk.mvp import lt.markmerkk.ActiveDisplayRepository import lt.markmerkk.TicketStorage import lt.markmerkk.TimeProvider import lt.markmerkk.entities.Log import lt.markmerkk.entities.Log.Companion.clone import lt.markmerkk.entities.TicketCode import lt.markmerkk.entities.TimeGap import lt.markmerkk.entities.TimeGap.Companion.toTimeGap import lt.markmerkk.utils.LogUtils /** * Responsible for handling time change */ class LogEditService2Impl( private val timeProvider: TimeProvider, private val ticketStorage: TicketStorage, private val listener: LogEditService2.Listener, private val activeDisplayRepository: ActiveDisplayRepository, ) : LogEditService2 { override val timeGap: TimeGap get() = _timeGap private var initLog: Log = Log.createAsEmpty(timeProvider) private var _timeGap: TimeGap = TimeGap.asEmpty(timeProvider) private var codeRaw: String = "" private var comment: String = "" override fun initWithLog(log: Log) { this.initLog = log this._timeGap = log.time.toTimeGap() this.codeRaw = log.code.code this.comment = log.comment redraw() } override fun updateDateTime(timeGap: TimeGap) { this._timeGap = timeGap listener.showDateTimeChange(this._timeGap) listener.showDuration(LogUtils.formatShortDuration(timeGap.duration)) } override fun updateCode(code: String) { this.codeRaw = code } override fun updateComment(comment: String) { this.comment = comment } override fun saveEntity() { val saveLog = initLog.clone( timeProvider = timeProvider, start = _timeGap.start, end = _timeGap.end, code = TicketCode.new(codeRaw), comment = comment ) if (saveLog.hasId) { activeDisplayRepository.update(saveLog) } else { activeDisplayRepository.insertOrUpdate(saveLog) } ticketStorage.saveTicketAsUsedSync(timeProvider.preciseNow(), saveLog.code) listener.showSuccess(saveLog) } /** * Triggers according functions to show on screen */ private fun redraw() { listener.showDateTimeChange(this._timeGap) listener.showDuration(LogUtils.formatShortDuration(_timeGap.duration)) listener.showCode(TicketCode.new(codeRaw)) listener.showComment(this.comment) } }
apache-2.0
adb45ef4ab7633c2821474e73910a7df
30.307692
83
0.685913
4.392086
false
false
false
false
drakelord/wire
wire-schema/src/test/java/com/squareup/wire/schema/internal/parser/ProtoFileElementTest.kt
1
9149
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.schema.internal.parser import com.squareup.wire.schema.Location import com.squareup.wire.schema.ProtoFile.Syntax.PROTO_2 import com.squareup.wire.schema.internal.parser.OptionElement.Kind import org.assertj.core.api.Assertions.assertThat import org.junit.Test class ProtoFileElementTest { internal var location = Location.get("file.proto") @Test fun emptyToSchema() { val file = ProtoFileElement(location = location) val expected = "// file.proto\n" assertThat(file.toSchema()).isEqualTo(expected) } @Test fun emptyWithPackageToSchema() { val file = ProtoFileElement( location = location, packageName = "example.simple" ) val expected = """ |// file.proto |package example.simple; |""".trimMargin() assertThat(file.toSchema()).isEqualTo(expected) } @Test fun simpleToSchema() { val element = MessageElement( location = location, name = "Message" ) val file = ProtoFileElement( location = location, types = listOf(element) ) val expected = """ |// file.proto | |message Message {} |""".trimMargin() assertThat(file.toSchema()).isEqualTo(expected) } @Test fun simpleWithImportsToSchema() { val element = MessageElement( location = location, name = "Message" ) val file = ProtoFileElement( location = location, imports = listOf("example.other"), types = listOf(element) ) val expected = """ |// file.proto | |import "example.other"; | |message Message {} |""".trimMargin() assertThat(file.toSchema()).isEqualTo(expected) } @Test fun addMultipleDependencies() { val element = MessageElement( location = location, name = "Message" ) val file = ProtoFileElement( location = location, imports = listOf("example.other", "example.another"), types = listOf(element) ) assertThat(file.imports).hasSize(2) } @Test fun simpleWithPublicImportsToSchema() { val element = MessageElement( location = location, name = "Message" ) val file = ProtoFileElement( location = location, publicImports = listOf("example.other"), types = listOf(element) ) val expected = """ |// file.proto | |import public "example.other"; | |message Message {} |""".trimMargin() assertThat(file.toSchema()).isEqualTo(expected) } @Test fun addMultiplePublicDependencies() { val element = MessageElement( location = location, name = "Message" ) val file = ProtoFileElement(location = location, publicImports = listOf("example.other", "example.another"), types = listOf(element) ) assertThat(file.publicImports).hasSize(2) } @Test fun simpleWithBothImportsToSchema() { val element = MessageElement( location = location, name = "Message" ) val file = ProtoFileElement(location = location, imports = listOf("example.thing"), publicImports = listOf("example.other"), types = listOf(element) ) val expected = """ |// file.proto | |import "example.thing"; |import public "example.other"; | |message Message {} |""".trimMargin() assertThat(file.toSchema()).isEqualTo(expected) } @Test fun simpleWithServicesToSchema() { val element = MessageElement( location = location, name = "Message" ) val service = ServiceElement( location = location, name = "Service" ) val file = ProtoFileElement( location = location, types = listOf(element), services = listOf(service) ) val expected = """ |// file.proto | |message Message {} | |service Service {} |""".trimMargin() assertThat(file.toSchema()).isEqualTo(expected) } @Test fun addMultipleServices() { val service1 = ServiceElement( location = location, name = "Service1" ) val service2 = ServiceElement( location = location, name = "Service2" ) val file = ProtoFileElement( location = location, services = listOf(service1, service2) ) assertThat(file.services).hasSize(2) } @Test fun simpleWithOptionsToSchema() { val element = MessageElement( location = location, name = "Message" ) val option = OptionElement.create("kit", Kind.STRING, "kat") val file = ProtoFileElement( location = location, options = listOf(option), types = listOf(element) ) val expected = """ |// file.proto | |option kit = "kat"; | |message Message {} |""".trimMargin() assertThat(file.toSchema()).isEqualTo(expected) } @Test fun addMultipleOptions() { val element = MessageElement( location = location, name = "Message" ) val kitKat = OptionElement.create("kit", Kind.STRING, "kat") val fooBar = OptionElement.create("foo", Kind.STRING, "bar") val file = ProtoFileElement( location = location, options = listOf(kitKat, fooBar), types = listOf(element) ) assertThat(file.options).hasSize(2) } @Test fun simpleWithExtendsToSchema() { val file = ProtoFileElement( location = location, extendDeclarations = listOf(ExtendElement(location = location.at(5, 1), name = "Extend")), types = listOf(MessageElement(location = location, name = "Message")) ) val expected = """ |// file.proto | |message Message {} | |extend Extend {} |""".trimMargin() assertThat(file.toSchema()).isEqualTo(expected) } @Test fun addMultipleExtends() { val extend1 = ExtendElement(location = location, name = "Extend1") val extend2 = ExtendElement(location = location, name = "Extend2") val file = ProtoFileElement( location = location, extendDeclarations = listOf(extend1, extend2) ) assertThat(file.extendDeclarations).hasSize(2) } @Test fun multipleEverythingToSchema() { val element1 = MessageElement(location = location.at(10, 1), name = "Message1") val element2 = MessageElement(location = location.at(11, 1), name = "Message2") val extend1 = ExtendElement(location = location.at(13, 1), name = "Extend1") val extend2 = ExtendElement(location = location.at(14, 1), name = "Extend2") val option1 = OptionElement.create("kit", Kind.STRING, "kat") val option2 = OptionElement.create("foo", Kind.STRING, "bar") val service1 = ServiceElement( location = location.at(16, 1), name = "Service1" ) val service2 = ServiceElement( location = location.at(17, 1), name = "Service2" ) val file = ProtoFileElement( location = location, packageName = "example.simple", imports = listOf("example.thing"), publicImports = listOf("example.other"), types = listOf(element1, element2), services = listOf(service1, service2), extendDeclarations = listOf(extend1, extend2), options = listOf(option1, option2) ) val expected = """ |// file.proto |package example.simple; | |import "example.thing"; |import public "example.other"; | |option kit = "kat"; |option foo = "bar"; | |message Message1 {} |message Message2 {} | |extend Extend1 {} |extend Extend2 {} | |service Service1 {} |service Service2 {} |""".trimMargin() assertThat(file.toSchema()).isEqualTo(expected) // Re-parse the expected string into a ProtoFile and ensure they're equal. val parsed = ProtoParser.parse(location, expected) assertThat(parsed).isEqualTo(file) } @Test fun syntaxToSchema() { val element = MessageElement(location = location, name = "Message") val file = ProtoFileElement( location = location, syntax = PROTO_2, types = listOf(element) ) val expected = """ |// file.proto |syntax = "proto2"; | |message Message {} |""".trimMargin() assertThat(file.toSchema()).isEqualTo(expected) } }
apache-2.0
1c9770ffefffd366039b650cac880bfd
26.557229
98
0.603126
4.358742
false
true
false
false
dahlstrom-g/intellij-community
plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/compilation/CodeFragmentParameterAnalyzer.kt
2
19000
// 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.debugger.evaluate.compilation import com.intellij.debugger.engine.evaluation.EvaluateExceptionUtil import com.intellij.psi.PsiElement import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.codegen.AsmUtil import org.jetbrains.kotlin.codegen.getCallLabelForLambdaArgument import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor import org.jetbrains.kotlin.descriptors.impl.SyntheticFieldDescriptor import org.jetbrains.kotlin.idea.debugger.evaluate.* import org.jetbrains.kotlin.idea.debugger.evaluate.KotlinCodeFragmentFactory.Companion.FAKE_JAVA_CONTEXT_FUNCTION_NAME import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.CodeFragmentParameter.* import org.jetbrains.kotlin.idea.debugger.safeLocation import org.jetbrains.kotlin.idea.debugger.safeMethod import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.psi.psiUtil.isDotSelector import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.checkers.COROUTINE_CONTEXT_FQ_NAME import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.scopes.receivers.ExtensionReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.expressions.createFunctionType class CodeFragmentParameterInfo( val parameters: List<Smart>, val crossingBounds: Set<Dumb> ) /* The purpose of this class is to figure out what parameters the received code fragment captures. It handles both directly mentioned names such as local variables or parameters and implicit values (dispatch/extension receivers). */ class CodeFragmentParameterAnalyzer( private val context: ExecutionContext, private val codeFragment: KtCodeFragment, private val bindingContext: BindingContext, private val evaluationStatus: EvaluationStatus ) { private val parameters = LinkedHashMap<DeclarationDescriptor, Smart>() private val crossingBounds = mutableSetOf<Dumb>() private val onceUsedChecker = OnceUsedChecker(CodeFragmentParameterAnalyzer::class.java) private val containingPrimaryConstructor: ConstructorDescriptor? by lazy { context.frameProxy.safeLocation()?.safeMethod()?.takeIf { it.isConstructor } ?: return@lazy null val constructor = codeFragment.context?.getParentOfType<KtPrimaryConstructor>(false) ?: return@lazy null bindingContext[BindingContext.CONSTRUCTOR, constructor] } fun analyze(): CodeFragmentParameterInfo { onceUsedChecker.trigger() codeFragment.accept(object : KtTreeVisitor<Unit>() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression, data: Unit?): Void? { val resolvedCall = expression.getResolvedCall(bindingContext) ?: return null processResolvedCall(resolvedCall, expression) return null } private fun processResolvedCall(resolvedCall: ResolvedCall<*>, expression: KtSimpleNameExpression) { if (resolvedCall is VariableAsFunctionResolvedCall) { processResolvedCall(resolvedCall.functionCall, expression) processResolvedCall(resolvedCall.variableCall, expression) return } // Capture dispatch receiver for the extension callable run { val descriptor = resolvedCall.resultingDescriptor val containingClass = descriptor?.containingDeclaration as? ClassDescriptor val extensionParameter = descriptor?.extensionReceiverParameter if (descriptor != null && descriptor !is DebuggerFieldPropertyDescriptor && extensionParameter != null && containingClass != null ) { if (containingClass.kind != ClassKind.OBJECT) { val parameter = processDispatchReceiver(containingClass) checkBounds(descriptor, expression, parameter) } } } if (runReadAction { expression.isDotSelector() }) { val descriptor = resolvedCall.resultingDescriptor val parameter = processCoroutineContextCall(resolvedCall.resultingDescriptor) if (parameter != null) { checkBounds(descriptor, expression, parameter) } // If the receiver expression is not a coroutine context call, it is already captured for this reference return } if (isCodeFragmentDeclaration(resolvedCall.resultingDescriptor)) { // The reference is from the code fragment we analyze, no need to capture return } var processed = false val extensionReceiver = resolvedCall.extensionReceiver if (extensionReceiver is ImplicitReceiver) { val descriptor = extensionReceiver.declarationDescriptor val parameter = processReceiver(extensionReceiver) checkBounds(descriptor, expression, parameter) processed = true } val dispatchReceiver = resolvedCall.dispatchReceiver if (dispatchReceiver is ImplicitReceiver) { val descriptor = dispatchReceiver.declarationDescriptor val parameter = processReceiver(dispatchReceiver) if (parameter != null) { checkBounds(descriptor, expression, parameter) processed = true } } if (!processed && resolvedCall.resultingDescriptor is SyntheticFieldDescriptor) { val descriptor = resolvedCall.resultingDescriptor as SyntheticFieldDescriptor val parameter = processSyntheticFieldVariable(descriptor) checkBounds(descriptor, expression, parameter) processed = true } // If a reference has receivers, we can calculate its value using them, no need to capture if (!processed) { val descriptor = resolvedCall.resultingDescriptor val parameter = processDescriptor(descriptor, expression) checkBounds(descriptor, expression, parameter) } } private fun processDescriptor(descriptor: DeclarationDescriptor, expression: KtSimpleNameExpression): Smart? { return processDebugLabel(descriptor) ?: processCoroutineContextCall(descriptor) ?: processSimpleNameExpression(descriptor, expression) } override fun visitThisExpression(expression: KtThisExpression, data: Unit?): Void? { val instanceReference = runReadAction { expression.instanceReference } val target = bindingContext[BindingContext.REFERENCE_TARGET, instanceReference] if (isCodeFragmentDeclaration(target)) { // The reference is from the code fragment we analyze, no need to capture return null } val parameter = when (target) { is ClassDescriptor -> processDispatchReceiver(target) is CallableDescriptor -> { val type = bindingContext[BindingContext.EXPRESSION_TYPE_INFO, expression]?.type type?.let { processExtensionReceiver(target, type, expression.getLabelName()) } } else -> null } if (parameter != null) { checkBounds(target, expression, parameter) } return null } override fun visitSuperExpression(expression: KtSuperExpression, data: Unit?): Void? { val type = bindingContext[BindingContext.THIS_TYPE_FOR_SUPER_EXPRESSION, expression] ?: return null val descriptor = type.constructor.declarationDescriptor as? ClassDescriptor ?: return null parameters.getOrPut(descriptor) { val name = descriptor.name.asString() Smart(Dumb(Kind.DISPATCH_RECEIVER, "", "super@$name"), type, descriptor) } return null } override fun visitCallExpression(expression: KtCallExpression, data: Unit?): Void? { val resolvedCall = expression.getResolvedCall(bindingContext) if (resolvedCall != null) { val descriptor = resolvedCall.resultingDescriptor if (descriptor is ConstructorDescriptor && KotlinBuiltIns.isNothing(descriptor.returnType)) { throw EvaluateExceptionUtil.createEvaluateException( KotlinDebuggerEvaluationBundle.message("error.nothing.initialization") ) } } return super.visitCallExpression(expression, data) } }, Unit) return CodeFragmentParameterInfo(parameters.values.toList(), crossingBounds) } private fun processReceiver(receiver: ImplicitReceiver): Smart? { if (isCodeFragmentDeclaration(receiver.declarationDescriptor)) { return null } return when (receiver) { is ImplicitClassReceiver -> processDispatchReceiver(receiver.classDescriptor) is ExtensionReceiver -> processExtensionReceiver(receiver.declarationDescriptor, receiver.type, null) else -> null } } private fun processDispatchReceiver(descriptor: ClassDescriptor): Smart? { if (descriptor.kind == ClassKind.OBJECT || containingPrimaryConstructor != null) { return null } val type = descriptor.defaultType return parameters.getOrPut(descriptor) { val name = descriptor.name val debugLabel = if (name.isSpecial) "" else "@" + name.asString() Smart(Dumb(Kind.DISPATCH_RECEIVER, "", AsmUtil.THIS + debugLabel), type, descriptor) } } private fun processExtensionReceiver(descriptor: CallableDescriptor, receiverType: KotlinType, label: String?): Smart? { if (isFakeFunctionForJavaContext(descriptor)) { return processFakeJavaCodeReceiver(descriptor) } val actualLabel = label ?: getLabel(descriptor) ?: return null val receiverParameter = descriptor.extensionReceiverParameter ?: return null return parameters.getOrPut(descriptor) { Smart(Dumb(Kind.EXTENSION_RECEIVER, actualLabel, AsmUtil.THIS + "@" + actualLabel), receiverType, receiverParameter) } } private fun getLabel(callableDescriptor: CallableDescriptor): String? { val source = callableDescriptor.source.getPsi() if (source is KtFunctionLiteral) { getCallLabelForLambdaArgument(source, bindingContext)?.let { return it } } return callableDescriptor.name.takeIf { !it.isSpecial }?.asString() } private fun isFakeFunctionForJavaContext(descriptor: CallableDescriptor): Boolean { return descriptor is FunctionDescriptor && descriptor.name.asString() == FAKE_JAVA_CONTEXT_FUNCTION_NAME && codeFragment.getCopyableUserData(KtCodeFragment.FAKE_CONTEXT_FOR_JAVA_FILE) != null } private fun processFakeJavaCodeReceiver(descriptor: CallableDescriptor): Smart? { val receiverParameter = descriptor .takeIf { descriptor is FunctionDescriptor } ?.extensionReceiverParameter ?: return null val label = FAKE_JAVA_CONTEXT_FUNCTION_NAME val type = receiverParameter.type return parameters.getOrPut(descriptor) { Smart(Dumb(Kind.FAKE_JAVA_OUTER_CLASS, label, AsmUtil.THIS), type, receiverParameter) } } private fun processSyntheticFieldVariable(descriptor: SyntheticFieldDescriptor): Smart { val propertyDescriptor = descriptor.propertyDescriptor val fieldName = propertyDescriptor.name.asString() val type = propertyDescriptor.type return parameters.getOrPut(descriptor) { Smart(Dumb(Kind.FIELD_VAR, fieldName, "field"), type, descriptor) } } private fun processSimpleNameExpression(target: DeclarationDescriptor, expression: KtSimpleNameExpression): Smart? { if (target is ValueParameterDescriptor && target.isCrossinline) { evaluationStatus.error(EvaluationError.CrossInlineLambda) throw EvaluateExceptionUtil.createEvaluateException( KotlinDebuggerEvaluationBundle.message("error.crossinline.lambda.evaluation") ) } val isLocalTarget = (target as? DeclarationDescriptorWithVisibility)?.visibility == DescriptorVisibilities.LOCAL val isPrimaryConstructorParameter = !isLocalTarget && target is PropertyDescriptor && isContainingPrimaryConstructorParameter(target) if (!isLocalTarget && !isPrimaryConstructorParameter) { return null } return when (target) { is SimpleFunctionDescriptor -> { val type = target.createFunctionType(target.builtIns, target.isSuspend) ?: return null parameters.getOrPut(target) { Smart(Dumb(Kind.LOCAL_FUNCTION, target.name.asString()), type, target.original) } } is ValueDescriptor -> { val unwrappedExpression = KtPsiUtil.deparenthesize(expression) val isLValue = unwrappedExpression?.let { isAssignmentLValue(it) } ?: false parameters.getOrPut(target) { val kind = if (target is LocalVariableDescriptor && target.isDelegated) Kind.DELEGATED else Kind.ORDINARY Smart(Dumb(kind, target.name.asString()), target.type, target, isLValue) } } else -> null } } private fun isAssignmentLValue(expression: PsiElement): Boolean { val assignmentExpression = (expression.parent as? KtBinaryExpression)?.takeIf { KtPsiUtil.isAssignment(it) } ?: return false return assignmentExpression.left == expression } private fun isContainingPrimaryConstructorParameter(target: PropertyDescriptor): Boolean { val primaryConstructor = containingPrimaryConstructor ?: return false for (parameter in primaryConstructor.valueParameters) { val property = bindingContext[BindingContext.VALUE_PARAMETER_AS_PROPERTY, parameter] if (target == property) { return true } } return false } private fun processCoroutineContextCall(target: DeclarationDescriptor): Smart? { if (target is PropertyDescriptor && target.fqNameSafe == COROUTINE_CONTEXT_FQ_NAME) { return parameters.getOrPut(target) { Smart(Dumb(Kind.COROUTINE_CONTEXT, ""), target.type, target) } } return null } private fun processDebugLabel(target: DeclarationDescriptor): Smart? { val debugLabelPropertyDescriptor = target as? DebugLabelPropertyDescriptor ?: return null val labelName = debugLabelPropertyDescriptor.labelName val debugString = debugLabelPropertyDescriptor.name.asString() return parameters.getOrPut(target) { val type = debugLabelPropertyDescriptor.type Smart(Dumb(Kind.DEBUG_LABEL, labelName, debugString), type, debugLabelPropertyDescriptor) } } fun checkBounds(descriptor: DeclarationDescriptor?, expression: KtExpression, parameter: Smart?) { if (parameter == null || descriptor !is DeclarationDescriptorWithSource) { return } val targetPsi = descriptor.source.getPsi() if (targetPsi != null && doesCrossInlineBounds(expression, targetPsi)) { crossingBounds += parameter.dumb } } private fun doesCrossInlineBounds(expression: PsiElement, declaration: PsiElement): Boolean { val declarationParent = declaration.parent ?: return false var currentParent: PsiElement? = expression.parent?.takeIf { it.isInside(declarationParent) } ?: return false while (currentParent != null && currentParent != declarationParent) { if (currentParent is KtFunction) { val functionDescriptor = bindingContext[BindingContext.FUNCTION, currentParent] if (functionDescriptor != null && !functionDescriptor.isInline) { return true } } currentParent = when (currentParent) { is KtCodeFragment -> currentParent.context else -> currentParent.parent } } return false } private fun isCodeFragmentDeclaration(descriptor: DeclarationDescriptor?): Boolean { if (descriptor is ValueParameterDescriptor && isCodeFragmentDeclaration(descriptor.containingDeclaration)) { return true } if (descriptor !is DeclarationDescriptorWithSource) { return false } return descriptor.source.getPsi()?.containingFile is KtCodeFragment } private tailrec fun PsiElement.isInside(parent: PsiElement): Boolean { if (parent.isAncestor(this)) { return true } val context = (this.containingFile as? KtCodeFragment)?.context ?: return false return context.isInside(parent) } } private class OnceUsedChecker(private val clazz: Class<*>) { private var used = false fun trigger() { if (used) { error(clazz.name + " may be only used once") } used = true } }
apache-2.0
b033fe7e42d941130ef90763c4d64f8c
43.917258
134
0.652263
5.997475
false
false
false
false
JiaweiWu/GiphyApp
app/src/main/java/com/jwu5/giphyapp/viewholder/GiphyViewHolder.kt
1
2831
package com.jwu5.giphyapp.viewholder import android.content.Context import android.graphics.Color import android.support.v7.widget.RecyclerView import android.view.View import android.widget.ImageButton import android.widget.ImageView import android.widget.ProgressBar import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.resource.drawable.GlideDrawable import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import com.jwu5.giphyapp.adapters.GiphyRecyclerViewAdapter import com.jwu5.giphyapp.R import com.jwu5.giphyapp.network.model.GiphyModel /** * Created by Jiawei on 8/16/2017. */ class GiphyViewHolder(itemView: View, private val mContext: Context, private val mAdapter: GiphyRecyclerViewAdapter, override val tag: String) : RecyclerView.ViewHolder(itemView), ViewHolderView { private val mItemImageView: ImageView private val mFavoriteButton: ImageButton private val mProgressBar: ProgressBar private val WHITE = Color.WHITE private val PINK = Color.argb(255, 255, 102, 153) protected var mViewHolderPresenter: ViewHolderPresenter init { mItemImageView = itemView.findViewById(R.id.Giphy_image_view) as ImageView mProgressBar = itemView.findViewById(R.id.progress_bar) as ProgressBar mFavoriteButton = itemView.findViewById(R.id.Giphy_image_button) as ImageButton mViewHolderPresenter = ViewHolderPresenter(this, mContext) } fun bindGiphyItem(item: GiphyModel) { Glide.with(mContext).load(item.url).listener(object : RequestListener<String, GlideDrawable> { override fun onException(e: Exception, model: String, target: Target<GlideDrawable>, isFirstResource: Boolean): Boolean { mProgressBar.visibility = View.GONE return false } override fun onResourceReady(resource: GlideDrawable, model: String, target: Target<GlideDrawable>, isFromMemoryCache: Boolean, isFirstResource: Boolean): Boolean { mProgressBar.visibility = View.GONE return false } }).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(mItemImageView) mViewHolderPresenter.setFavoriteIcon(item) mFavoriteButton.setOnClickListener { mViewHolderPresenter.saveToFavorites(item) } } override fun getInFavoritesColor(): Int { return PINK; } override fun getNotInFavoritesColor(): Int { return WHITE; } override fun setButtonColor(color: Int) { mFavoriteButton.setColorFilter(color) } override fun removeItemFromView(item: GiphyModel) { mAdapter.removeItem(item) } override fun updateAdapter() { mAdapter.notifyItemChanged(adapterPosition) } }
mit
276cfda6d5a1b7f226d7f9fc9c7a1761
35.294872
196
0.737195
4.671617
false
false
false
false
dahlstrom-g/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/fileActions/export/MarkdownExportProvider.kt
6
1312
// 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 org.intellij.plugins.markdown.fileActions.export import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import org.intellij.plugins.markdown.fileActions.MarkdownFileActionFormat import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import java.io.File import javax.swing.JComponent @ApiStatus.Experimental interface MarkdownExportProvider { val formatDescription: MarkdownFileActionFormat fun exportFile(project: Project, mdFile: VirtualFile, outputFile: String) fun validate(project: Project, file: VirtualFile): @Nls String? fun createSettingsComponent(project: Project, suggestedTargetFile: File): JComponent? = null companion object { private val EP_NAME: ExtensionPointName<MarkdownExportProvider> = ExtensionPointName.create("org.intellij.markdown.markdownExportProvider") val allProviders: List<MarkdownExportProvider> = EP_NAME.extensionList internal object NotificationIds { const val exportSuccess = "markdown.export.success" const val exportFailed = "markdown.export.failed" } } }
apache-2.0
d2a1d7f87f75f17fb07481238c389fb1
37.588235
140
0.803354
4.619718
false
false
false
false
spotify/heroic
aggregation/simple/src/main/java/com/spotify/heroic/aggregation/simple/DeltaInstance.kt
1
4109
/* * Copyright (c) 2019 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.spotify.heroic.aggregation.simple import com.spotify.heroic.ObjectHasher import com.spotify.heroic.aggregation.* import com.spotify.heroic.common.DateRange import com.spotify.heroic.common.Series import com.spotify.heroic.metric.* import com.spotify.heroic.metric.Spread import java.util.* object DeltaInstance : AggregationInstance { private val INNER = EmptyInstance.INSTANCE override fun estimate(range: DateRange): Long { return INNER.estimate(range) } override fun cadence(): Long { return -1 } override fun distributed(): AggregationInstance { return this } override fun reducer(): AggregationInstance { return INNER } override fun distributable(): Boolean { return false } override fun hashTo(hasher: ObjectHasher) { hasher.putObject(javaClass) } fun computeDiff(points: List<Point>): List<Point> { val it = points.iterator() val result = ArrayList<Point>() if (!it.hasNext()) { return emptyList() } var previous = it.next() while (it.hasNext()) { val current = it.next() val diff = current.value - previous.value result.add(Point(current.timestamp, diff)) previous = current } return result } override fun session( range: DateRange, quotaWatcher: RetainQuotaWatcher, bucketStrategy: BucketStrategy ): AggregationSession { return Session(INNER.session(range, quotaWatcher, bucketStrategy)) } private class Session(private val childSession: AggregationSession) : AggregationSession { override fun updatePoints( key: Map<String, String>, series: Set<Series>, values: List<Point> ) { this.childSession.updatePoints(key, series, values) } override fun updatePayload( key: Map<String, String>, series: Set<Series>, values: List<Payload> ) { } override fun updateGroup( key: Map<String, String>, series: Set<Series>, values: List<MetricGroup> ) { } override fun updateSpreads( key: Map<String, String>, series: Set<Series>, values: List<Spread> ) { } override fun updateDistributionPoints( key: Map<String, String>, series: Set<Series>, values: List<DistributionPoint> ) { } override fun updateTDigestPoints( key: Map<String, String>, series: Set<Series>, values: List<TdigestPoint> ) { } override fun result(): AggregationResult { val (result, statistics) = this.childSession.result() val outputs: List<AggregationOutput> = result .map { (key, series, metrics) -> AggregationOutput( key, series, MetricCollection.build( MetricType.POINT, computeDiff(metrics.getDataAs(Point::class.java)) ) ) } return AggregationResult(outputs, statistics) } } }
apache-2.0
fa1761bfab18c8ddf0436c692fabb4ee
29.437037
94
0.614748
4.679954
false
false
false
false
kdwink/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt
1
24388
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.updateSettings.impl import com.intellij.diagnostic.IdeErrorsDialog import com.intellij.externalDependencies.DependencyOnPlugin import com.intellij.externalDependencies.ExternalDependenciesManager import com.intellij.ide.IdeBundle import com.intellij.ide.plugins.* import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.NotificationDisplayType import com.intellij.notification.NotificationGroup import com.intellij.notification.NotificationListener import com.intellij.notification.NotificationType import com.intellij.openapi.application.* import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.diagnostic.IdeaLoggingEvent import com.intellij.openapi.diagnostic.LogUtil import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.EmptyProgressIndicator 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.project.ProjectManager import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.updateSettings.UpdateStrategyCustomization import com.intellij.openapi.util.ActionCallback import com.intellij.openapi.util.BuildNumber import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.util.PlatformUtils import com.intellij.util.containers.ContainerUtil import com.intellij.util.io.HttpRequests import com.intellij.util.io.URLUtil import com.intellij.util.ui.UIUtil import com.intellij.xml.util.XmlStringUtil import org.apache.http.client.utils.URIBuilder import org.jdom.JDOMException import org.jetbrains.annotations.Contract import java.io.File import java.io.IOException import java.net.URISyntaxException import java.net.URL import java.util.* /** * See XML file by [ApplicationInfoEx.getUpdateUrls] for reference. * * @author mike * @since Oct 31, 2002 */ object UpdateChecker { private val LOG = Logger.getInstance("#com.intellij.openapi.updateSettings.impl.UpdateChecker") val NO_PLATFORM_UPDATE = "ide.no.platform.update" @JvmField val NOTIFICATIONS = NotificationGroup(IdeBundle.message("update.notifications.group"), NotificationDisplayType.STICKY_BALLOON, true) private val INSTALLATION_UID = "installation.uid" private val DISABLED_UPDATE = "disabled_update.txt" private var ourDisabledToUpdatePlugins: MutableSet<String>? = null private val ourAdditionalRequestOptions = hashMapOf<String, String>() private val ourUpdatedPlugins = hashMapOf<String, PluginDownloader>() private val ourShownNotificationTypes = Collections.synchronizedSet(EnumSet.noneOf(NotificationUniqueType::class.java)) private val UPDATE_URL by lazy { ApplicationInfoEx.getInstanceEx().updateUrls.checkingUrl } private val PATCHES_URL by lazy { ApplicationInfoEx.getInstanceEx().updateUrls.patchesUrl } val excludedFromUpdateCheckPlugins = hashSetOf<String>() private val updateUrl: String get() = System.getProperty("idea.updates.url") ?: UPDATE_URL private val patchesUrl: String get() = System.getProperty("idea.patches.url") ?: PATCHES_URL /** * For scheduled update checks. */ @JvmStatic fun updateAndShowResult(): ActionCallback { val callback = ActionCallback() ApplicationManager.getApplication().executeOnPooledThread { doUpdateAndShowResult(null, true, false, UpdateSettings.getInstance(), null, callback) } return callback } /** * For manual update checks (Help | Check for Updates, Settings | Updates | Check Now) * (the latter action may pass customised update settings). */ @JvmStatic fun updateAndShowResult(project: Project?, customSettings: UpdateSettings?) { val settings = customSettings ?: UpdateSettings.getInstance() val fromSettings = customSettings != null ProgressManager.getInstance().run(object : Task.Backgroundable(project, IdeBundle.message("updates.checking.progress"), true) { override fun run(indicator: ProgressIndicator) { doUpdateAndShowResult(getProject(), fromSettings, true, settings, indicator, null) } override fun isConditionalModal(): Boolean = fromSettings override fun shouldStartInBackground(): Boolean = !fromSettings }) } private fun doUpdateAndShowResult(project: Project?, fromSettings: Boolean, manualCheck: Boolean, updateSettings: UpdateSettings, indicator: ProgressIndicator?, callback: ActionCallback?) { // check platform update indicator?.text = IdeBundle.message("updates.checking.platform") val result = checkPlatformUpdate(updateSettings) if (manualCheck && result.state == UpdateStrategy.State.LOADED) { val settings = UpdateSettings.getInstance() settings.saveLastCheckedInfo() settings.setKnownChannelIds(result.allChannelsIds) } else if (result.state == UpdateStrategy.State.CONNECTION_ERROR) { val e = result.error if (e != null) LOG.debug(e) val cause = e?.message ?: "internal error" showErrorMessage(manualCheck, IdeBundle.message("updates.error.connection.failed", cause)) return } // check plugins update (with regard to potential platform update) indicator?.text = IdeBundle.message("updates.checking.plugins") val updatedPlugins: Collection<PluginDownloader>? val incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>? if (newChannelReady(result.channelToPropose)) { updatedPlugins = null incompatiblePlugins = null } else { val buildNumber: BuildNumber? = result.newBuildInSelectedChannel?.apiVersion incompatiblePlugins = if (buildNumber != null) HashSet<IdeaPluginDescriptor>() else null try { updatedPlugins = checkPluginsUpdate(updateSettings, indicator, incompatiblePlugins, buildNumber) } catch (e: IOException) { showErrorMessage(manualCheck, IdeBundle.message("updates.error.connection.failed", e.message)) return } } // show result ApplicationManager.getApplication().invokeLater({ showUpdateResult(project, result, updateSettings, updatedPlugins, incompatiblePlugins, !fromSettings, manualCheck) callback?.setDone() }, if (fromSettings) ModalityState.any() else ModalityState.NON_MODAL) } private fun checkPlatformUpdate(settings: UpdateSettings): CheckForUpdateResult { if (System.getProperty(NO_PLATFORM_UPDATE, "false").toBoolean()) { return CheckForUpdateResult(UpdateStrategy.State.NOTHING_LOADED, null) } val updateInfo: UpdatesInfo? try { val uriBuilder = URIBuilder(updateUrl) if (URLUtil.FILE_PROTOCOL != uriBuilder.scheme) { prepareUpdateCheckArgs(uriBuilder) } val updateUrl = uriBuilder.build().toString() LogUtil.debug(LOG, "load update xml (UPDATE_URL='%s')", updateUrl) updateInfo = HttpRequests.request(updateUrl) .forceHttps(settings.canUseSecureConnection()) .connect { request -> try { UpdatesInfo(JDOMUtil.load(request.reader)) } catch (e: JDOMException) { // corrupted content, don't bother telling user LOG.info(e) null } } } catch (e: URISyntaxException) { return CheckForUpdateResult(UpdateStrategy.State.CONNECTION_ERROR, e) } catch (e: IOException) { return CheckForUpdateResult(UpdateStrategy.State.CONNECTION_ERROR, e) } if (updateInfo == null) { return CheckForUpdateResult(UpdateStrategy.State.NOTHING_LOADED, null) } val appInfo = ApplicationInfo.getInstance() val majorVersion = Integer.parseInt(appInfo.majorVersion) val customization = UpdateStrategyCustomization.getInstance() val strategy = UpdateStrategy(majorVersion, appInfo.build, updateInfo, settings, customization) return strategy.checkForUpdates() } private fun checkPluginsUpdate(updateSettings: UpdateSettings, indicator: ProgressIndicator?, incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>?, buildNumber: BuildNumber?): Collection<PluginDownloader>? { val updateable = collectUpdateablePlugins() if (updateable.isEmpty()) return null // check custom repositories and the main one for updates val toUpdate = ContainerUtil.newTroveMap<PluginId, PluginDownloader>() val hosts = RepositoryHelper.getPluginHosts() val state = InstalledPluginsState.getInstance() outer@ for (host in hosts) { try { val forceHttps = host == null && updateSettings.canUseSecureConnection() val list = RepositoryHelper.loadPlugins(host, buildNumber, forceHttps, indicator) for (descriptor in list) { val id = descriptor.pluginId if (updateable.containsKey(id)) { updateable.remove(id) state.onDescriptorDownload(descriptor) val downloader = PluginDownloader.createDownloader(descriptor, host, buildNumber) downloader.setForceHttps(forceHttps) checkAndPrepareToInstall(downloader, state, toUpdate, incompatiblePlugins, indicator) if (updateable.isEmpty()) { break@outer } } } } catch (e: IOException) { LOG.debug(e) if (host != null) { LOG.info("failed to load plugin descriptions from " + host + ": " + e.message) } else { throw e } } } return if (toUpdate.isEmpty) null else toUpdate.values } /** * Returns a list of plugins which are currently installed or were installed in the previous installation from which * we're importing the settings. */ private fun collectUpdateablePlugins(): MutableMap<PluginId, IdeaPluginDescriptor> { val updateable = ContainerUtil.newTroveMap<PluginId, IdeaPluginDescriptor>() updateable += PluginManagerCore.getPlugins().filter { !it.isBundled }.toMapBy { it.pluginId } val onceInstalled = PluginManager.getOnceInstalledIfExists() if (onceInstalled != null) { try { for (line in FileUtil.loadLines(onceInstalled)) { val id = PluginId.getId(line.trim { it <= ' ' }) if (id !in updateable) { updateable.put(id, null) } } } catch (e: IOException) { LOG.error(onceInstalled.path, e) } //noinspection SSBasedInspection onceInstalled.deleteOnExit() } for (excludedPluginId in excludedFromUpdateCheckPlugins) { if (!isRequiredForAnyOpenProject(excludedPluginId)) { updateable.remove(PluginId.getId(excludedPluginId)) } } return updateable } private fun isRequiredForAnyOpenProject(pluginId: String) = ProjectManager.getInstance().openProjects.any { isRequiredForProject(it, pluginId) } private fun isRequiredForProject(project: Project, pluginId: String) = ExternalDependenciesManager.getInstance(project).getDependencies(DependencyOnPlugin::class.java).any { it.pluginId == pluginId } @Throws(IOException::class) @JvmStatic fun checkAndPrepareToInstall(downloader: PluginDownloader, state: InstalledPluginsState, toUpdate: MutableMap<PluginId, PluginDownloader>, incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>?, indicator: ProgressIndicator?) { @Suppress("NAME_SHADOWING") var downloader = downloader val pluginId = downloader.pluginId if (PluginManagerCore.getDisabledPlugins().contains(pluginId)) return val pluginVersion = downloader.pluginVersion val installedPlugin = PluginManager.getPlugin(PluginId.getId(pluginId)) if (installedPlugin == null || pluginVersion == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(installedPlugin, pluginVersion) > 0) { var descriptor: IdeaPluginDescriptor? val oldDownloader = ourUpdatedPlugins[pluginId] if (oldDownloader == null || StringUtil.compareVersionNumbers(pluginVersion, oldDownloader.pluginVersion) > 0) { descriptor = downloader.descriptor if (descriptor is PluginNode && descriptor.isIncomplete) { if (downloader.prepareToInstall(indicator ?: EmptyProgressIndicator())) { descriptor = downloader.descriptor } ourUpdatedPlugins.put(pluginId, downloader) } } else { downloader = oldDownloader descriptor = oldDownloader.descriptor } if (descriptor != null && PluginManagerCore.isCompatible(descriptor, downloader.buildNumber) && !state.wasUpdated(descriptor.pluginId)) { toUpdate.put(PluginId.getId(pluginId), downloader) } } //collect plugins which were not updated and would be incompatible with new version if (incompatiblePlugins != null && installedPlugin != null && installedPlugin.isEnabled && !toUpdate.containsKey(installedPlugin.pluginId) && PluginManagerCore.isIncompatible(installedPlugin, downloader.buildNumber)) { incompatiblePlugins.add(installedPlugin) } } private fun showErrorMessage(showDialog: Boolean, message: String) { LOG.info(message) if (showDialog) { UIUtil.invokeLaterIfNeeded { Messages.showErrorDialog(message, IdeBundle.message("updates.error.connection.title")) } } } @Contract("null -> false") private fun newChannelReady(channelToPropose: UpdateChannel?): Boolean { return channelToPropose?.getLatestBuild() != null } private fun showUpdateResult(project: Project?, checkForUpdateResult: CheckForUpdateResult, updateSettings: UpdateSettings, updatedPlugins: Collection<PluginDownloader>?, incompatiblePlugins: Collection<IdeaPluginDescriptor>?, enableLink: Boolean, alwaysShowResults: Boolean) { val channelToPropose = checkForUpdateResult.channelToPropose val updatedChannel = checkForUpdateResult.updatedChannel val latestBuild = checkForUpdateResult.newBuildInSelectedChannel if (updatedChannel != null && latestBuild != null) { val runnable = { val forceHttps = updateSettings.canUseSecureConnection() UpdateInfoDialog(updatedChannel, latestBuild, enableLink, forceHttps, updatedPlugins, incompatiblePlugins).show() } if (alwaysShowResults) { runnable.invoke() } else { val message = IdeBundle.message("updates.ready.message", ApplicationNamesInfo.getInstance().fullProductName) showNotification(project, message, runnable, NotificationUniqueType.UPDATE_IN_CHANNEL) } } else if (newChannelReady(channelToPropose)) { val runnable = { val dialog = NewChannelDialog(channelToPropose!!) dialog.show() // once we informed that new product is available (when new channel was detected), remember the fact if (dialog.exitCode == DialogWrapper.CANCEL_EXIT_CODE && checkForUpdateResult.state == UpdateStrategy.State.LOADED && !updateSettings.knownChannelsIds.contains(channelToPropose.id)) { val newIds = ArrayList(updateSettings.knownChannelsIds) newIds.add(channelToPropose.id) updateSettings.setKnownChannelIds(newIds) } } if (alwaysShowResults) { runnable.invoke() } else { val message = IdeBundle.message("updates.new.version.available", ApplicationNamesInfo.getInstance().fullProductName) showNotification(project, message, runnable, NotificationUniqueType.NEW_CHANNEL) } } else if (updatedPlugins != null && !updatedPlugins.isEmpty()) { val runnable = { PluginUpdateInfoDialog(updatedPlugins, enableLink).show() } if (alwaysShowResults) { runnable.invoke() } else { val plugins = updatedPlugins.joinToString { downloader -> downloader.pluginName } val message = IdeBundle.message("updates.plugins.ready.message", updatedPlugins.size, plugins) showNotification(project, message, runnable, NotificationUniqueType.PLUGINS_UPDATE) } } else if (alwaysShowResults) { NoUpdatesDialog(enableLink).show() } } private fun showNotification(project: Project?, message: String, runnable: (() -> Unit)?, notificationType: NotificationUniqueType?) { if (notificationType != null) { if (!ourShownNotificationTypes.add(notificationType)) { return } } var listener: NotificationListener? = null if (runnable != null) { listener = NotificationListener { notification, event -> notification.expire() runnable.invoke() } } val title = IdeBundle.message("update.notifications.title") NOTIFICATIONS.createNotification(title, XmlStringUtil.wrapInHtml(message), NotificationType.INFORMATION, listener) .whenExpired { ourShownNotificationTypes.remove(notificationType) } .notify(project) } @JvmStatic fun addUpdateRequestParameter(name: String, value: String) { ourAdditionalRequestOptions.put(name, value) } private fun prepareUpdateCheckArgs(uriBuilder: URIBuilder) { addUpdateRequestParameter("build", ApplicationInfo.getInstance().build.asString()) addUpdateRequestParameter("uid", getInstallationUID(PropertiesComponent.getInstance())) addUpdateRequestParameter("os", SystemInfo.OS_NAME + ' ' + SystemInfo.OS_VERSION) if (ApplicationInfoEx.getInstanceEx().isEAP) { addUpdateRequestParameter("eap", "") } for ((name, value) in ourAdditionalRequestOptions) { uriBuilder.addParameter(name, if (StringUtil.isEmpty(value)) null else value) } } @JvmStatic fun getInstallationUID(propertiesComponent: PropertiesComponent): String { if (SystemInfo.isWindows) { val uid = getInstallationUIDOnWindows(propertiesComponent) if (uid != null) { return uid } } var uid = propertiesComponent.getValue(INSTALLATION_UID) if (uid == null) { uid = generateUUID() propertiesComponent.setValue(INSTALLATION_UID, uid) } return uid } private fun getInstallationUIDOnWindows(propertiesComponent: PropertiesComponent): String? { val appdata = System.getenv("APPDATA") if (appdata != null) { val jetBrainsDir = File(appdata, "JetBrains") if (jetBrainsDir.exists() || jetBrainsDir.mkdirs()) { val permanentIdFile = File(jetBrainsDir, "PermanentUserId") try { if (permanentIdFile.exists()) { return FileUtil.loadFile(permanentIdFile).trim { it <= ' ' } } var uuid = propertiesComponent.getValue(INSTALLATION_UID) if (uuid == null) { uuid = generateUUID() } FileUtil.writeToFile(permanentIdFile, uuid) return uuid } catch (ignored: IOException) { } } } return null } private fun generateUUID(): String = try { UUID.randomUUID().toString() } catch (ignored: Exception) { "" } catch (ignored: InternalError) { "" } @JvmStatic @Throws(IOException::class) fun installPlatformUpdate(patch: PatchInfo, toBuild: BuildNumber, forceHttps: Boolean) { ProgressManager.getInstance().runProcessWithProgressSynchronously( { val indicator = ProgressManager.getInstance().progressIndicator downloadAndInstallPatch(patch, toBuild, forceHttps, indicator) }, IdeBundle.message("update.downloading.patch.progress.title"), true, null) } private fun downloadAndInstallPatch(patch: PatchInfo, toBuild: BuildNumber, forceHttps: Boolean, indicator: ProgressIndicator) { val productCode = ApplicationInfo.getInstance().build.productCode val fromBuildNumber = patch.fromBuild.asStringWithoutProductCode() val toBuildNumber = toBuild.asStringWithoutProductCode() var bundledJdk = "" val jdkRedist = System.getProperty("idea.java.redist") if (jdkRedist != null && jdkRedist.lastIndexOf("NoJavaDistribution") >= 0) { bundledJdk = "-no-jdk" } val osSuffix = "-" + patch.osSuffix val fileName = "$productCode-$fromBuildNumber-$toBuildNumber-patch$bundledJdk$osSuffix.jar" val url = URL(URL(patchesUrl), fileName).toString() val tempFile = HttpRequests.request(url) .gzip(false) .forceHttps(forceHttps) .connect { request -> request.saveToFile(FileUtil.createTempFile("ij.platform.", ".patch", true), indicator) } val patchFileName = ("jetbrains.patch.jar." + PlatformUtils.getPlatformPrefix()).toLowerCase(Locale.ENGLISH) val patchFile = File(FileUtil.getTempDirectory(), patchFileName) FileUtil.copy(tempFile, patchFile) FileUtil.delete(tempFile) } @JvmStatic fun installPluginUpdates(downloaders: Collection<PluginDownloader>, indicator: ProgressIndicator): Boolean { var installed = false val disabledToUpdate = disabledToUpdatePlugins for (downloader in downloaders) { if (downloader.pluginId in disabledToUpdate) { continue } try { if (downloader.prepareToInstall(indicator)) { val descriptor = downloader.descriptor if (descriptor != null) { downloader.install() installed = true } } } catch (e: IOException) { LOG.info(e) } } return installed } @JvmStatic val disabledToUpdatePlugins: Set<String> get() { if (ourDisabledToUpdatePlugins == null) { ourDisabledToUpdatePlugins = TreeSet<String>() if (!ApplicationManager.getApplication().isUnitTestMode) { try { val file = File(PathManager.getConfigPath(), DISABLED_UPDATE) if (file.isFile) { FileUtil.loadFile(file) .split("[\\s]".toRegex()) .map { it.trim() } .filterTo(ourDisabledToUpdatePlugins!!) { it.isNotEmpty() } } } catch (e: IOException) { LOG.error(e) } } } return ourDisabledToUpdatePlugins!! } @JvmStatic fun saveDisabledToUpdatePlugins() { val plugins = File(PathManager.getConfigPath(), DISABLED_UPDATE) try { PluginManagerCore.savePluginsList(disabledToUpdatePlugins, false, plugins) } catch (e: IOException) { LOG.error(e) } } private var ourHasFailedPlugins = false @JvmStatic fun checkForUpdate(event: IdeaLoggingEvent) { if (!ourHasFailedPlugins && UpdateSettings.getInstance().isCheckNeeded) { val throwable = event.throwable val pluginDescriptor = PluginManager.getPlugin(IdeErrorsDialog.findPluginId(throwable)) if (pluginDescriptor != null && !pluginDescriptor.isBundled) { ourHasFailedPlugins = true updateAndShowResult() } } } private enum class NotificationUniqueType { NEW_CHANNEL, UPDATE_IN_CHANNEL, PLUGINS_UPDATE } }
apache-2.0
1f643b05c421b80d82081c6a75a238fc
36.871118
156
0.689314
5.194462
false
false
false
false
elpassion/el-space-android
el-space-app/src/main/java/pl/elpassion/elspace/hub/project/choose/ProjectChooseActivity.kt
1
3995
package pl.elpassion.elspace.hub.project.choose import android.app.Activity import android.content.Intent import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v4.view.MenuItemCompat.getActionView import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.SearchView import android.view.Menu import android.view.MenuItem import com.crashlytics.android.Crashlytics import com.elpassion.android.commons.recycler.adapters.basicAdapterWithLayoutAndBinder import com.jakewharton.rxbinding2.support.v7.widget.queryTextChanges import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.project_choose_activity.* import kotlinx.android.synthetic.main.project_item.view.* import pl.elpassion.elspace.R import pl.elpassion.elspace.common.SchedulersSupplier import pl.elpassion.elspace.common.extensions.handleClickOnBackArrowItem import pl.elpassion.elspace.common.extensions.showBackArrowOnActionBar import pl.elpassion.elspace.common.hideLoader import pl.elpassion.elspace.common.showLoader import pl.elpassion.elspace.hub.project.Project class ProjectChooseActivity : AppCompatActivity(), ProjectChoose.View { private val controller by lazy { ProjectChooseController(this, ProjectRepositoryProvider.get(), SchedulersSupplier(Schedulers.io(), AndroidSchedulers.mainThread())) } private var projects = mutableListOf<Project>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.project_choose_activity) setSupportActionBar(toolbar) showBackArrowOnActionBar() initRecyclerView() } private fun initRecyclerView() { projectsContainer.layoutManager = LinearLayoutManager(this) projectsContainer.adapter = basicAdapterWithLayoutAndBinder(projects, R.layout.project_item) { holder, item -> holder.itemView.projectName.text = item.name holder.itemView.setOnClickListener { controller.onProjectClicked(item) } } } override fun showProjects(projects: List<Project>) { this.projects.clear() this.projects.addAll(projects) projectsContainer.adapter.notifyDataSetChanged() } override fun selectProject(project: Project) { setResult(Activity.RESULT_OK, Intent().putExtra(SELECTED_PROJECT, project)) finish() } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.action_search) { return true } else { return handleClickOnBackArrowItem(item) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.project_choose_menu, menu) val searchView = menu.getSearchView() controller.onCreate(searchView.queryTextChanges()) return true } private fun Menu.getSearchView(): SearchView { val searchItem = findItem(R.id.action_search) return getActionView(searchItem) as SearchView } override fun showError(ex: Throwable) { Crashlytics.logException(ex) Snackbar.make(projectsCoordinator, R.string.internet_connection_error, Snackbar.LENGTH_INDEFINITE).show() } override fun hideLoader() = hideLoader(projectsCoordinator) override fun showLoader() = showLoader(projectsCoordinator) override fun onDestroy() { super.onDestroy() controller.onDestroy() } companion object { private val SELECTED_PROJECT = "selected_project" fun startForResult(activity: Activity, requestCode: Int) { activity.startActivityForResult(Intent(activity, ProjectChooseActivity::class.java), requestCode) } fun getProject(data: Intent): Project = data.getSerializableExtra(ProjectChooseActivity.SELECTED_PROJECT) as Project } }
gpl-3.0
f53971b5ff836c2a9f2e32d24c4dc585
37.786408
170
0.748686
4.7
false
false
false
false
zeapo/Android-Password-Store
app/src/main/java/com/zeapo/pwdstore/autofill/AutofillActivity.kt
1
3958
package com.zeapo.pwdstore.autofill import android.app.PendingIntent import android.content.Context import android.content.Intent import android.content.IntentSender import android.content.SharedPreferences import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import com.zeapo.pwdstore.PasswordStore import com.zeapo.pwdstore.utils.splitLines import org.eclipse.jgit.util.StringUtils import java.util.ArrayList import java.util.Arrays // blank activity started by service for calling startIntentSenderForResult class AutofillActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val extras = intent.extras if (extras != null && extras.containsKey("pending_intent")) { try { val pi = extras.getParcelable<PendingIntent>("pending_intent") ?: return startIntentSenderForResult(pi.intentSender, REQUEST_CODE_DECRYPT_AND_VERIFY, null, 0, 0, 0) } catch (e: IntentSender.SendIntentException) { Log.e(AutofillService.Constants.TAG, "SendIntentException", e) } } else if (extras != null && extras.containsKey("pick")) { val intent = Intent(applicationContext, PasswordStore::class.java) intent.putExtra("matchWith", true) startActivityForResult(intent, REQUEST_CODE_PICK) } else if (extras != null && extras.containsKey("pickMatchWith")) { val intent = Intent(applicationContext, PasswordStore::class.java) intent.putExtra("matchWith", true) startActivityForResult(intent, REQUEST_CODE_PICK_MATCH_WITH) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { finish() // go back to the password field app when (requestCode) { REQUEST_CODE_DECRYPT_AND_VERIFY -> if (resultCode == RESULT_OK) { AutofillService.instance?.setResultData(data!!) // report the result to service } REQUEST_CODE_PICK -> if (resultCode == RESULT_OK) { AutofillService.instance?.setPickedPassword(data!!.getStringExtra("path")) } REQUEST_CODE_PICK_MATCH_WITH -> if (resultCode == RESULT_OK) { // need to not only decrypt the picked password, but also // update the "match with" preference val extras = intent.extras ?: return val packageName = extras.getString("packageName") val isWeb = extras.getBoolean("isWeb") val path = data!!.getStringExtra("path") AutofillService.instance?.setPickedPassword(data.getStringExtra("path")) val prefs: SharedPreferences prefs = if (!isWeb) { applicationContext.getSharedPreferences("autofill", Context.MODE_PRIVATE) } else { applicationContext.getSharedPreferences("autofill_web", Context.MODE_PRIVATE) } val editor = prefs.edit() when (val preference = prefs.getString(packageName, "")) { "", "/first", "/never" -> editor.putString(packageName, path) else -> { val matches = ArrayList(Arrays.asList(*preference!!.trim { it <= ' ' }.splitLines())) matches.add(path) val paths = StringUtils.join(matches, "\n") editor.putString(packageName, paths) } } editor.apply() } } super.onActivityResult(requestCode, resultCode, data) } companion object { const val REQUEST_CODE_DECRYPT_AND_VERIFY = 9913 const val REQUEST_CODE_PICK = 777 const val REQUEST_CODE_PICK_MATCH_WITH = 778 } }
gpl-3.0
ceea7bb74c7958ff0beaa05bbaae15da
43.47191
109
0.612178
4.978616
false
false
false
false
TheMrMilchmann/lwjgl3
modules/lwjgl/core/src/templates/kotlin/core/linux/liburing/templates/liburing.kt
1
36766
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package core.linux.liburing.templates import org.lwjgl.generator.* import core.linux.* import core.linux.liburing.* val LibURing = "LibURing".nativeClass(Module.CORE_LINUX_LIBURING, nativeSubPath = "linux", prefixConstant = "", prefixMethod = "io_uring_") { nativeImport("liburing.h") javaImport("org.lwjgl.system.linux.*") documentation = """ Native bindings to ${url("https://github.com/axboe/liburing", "liburing")}. """ LongConstant("", "LIBURING_UDATA_TIMEOUT".."-1L") io_uring_probe.p( "get_probe_ring", """ Return an allocated {@code io_uring_probe} structure, or #NULL if probe fails (for example, if it is not available). The caller is responsible for freeing it. """, io_uring.p("ring", "") ) io_uring_probe.p( "get_probe", """ Returns an allocated {@code io_uring_probe} structure to the caller. The caller is responsible for freeing the structure with the function #free_probe(). Note: Earlier versions of the Linux kernel (&le; 5.5) do not support probe. If the kernel doesn't support probe, this function will return #NULL. """, void() ) void( "free_probe", "Frees the {@code probe} instance allocated with the #get_probe() function.", io_uring_probe.p("probe", "") ) int( "opcode_supported", """ Allows the caller to determine if the passed in {@code opcode} belonging to the {@code probe} param is supported. An instance of the {@code io_uring_probe} instance can be obtained by calling the function #get_probe(). """, io_uring_probe.const.p("p", ""), int("op", "") ) int( "queue_init_params", "", unsigned("entries", ""), io_uring.p("ring", ""), io_uring_params.p("p", "") ) int( "queue_init", """ Executes the #setup() syscall to initialize the submission and completion queues in the kernel with at least {@code entries} entries and then maps the resulting file descriptor to memory shared between the application and the kernel. On success, the resources held by {@code ring} should be released via a corresponding call to #queue_exit(). """, unsigned("entries", ""), io_uring.p("ring", ""), unsigned("flags", "will be passed through to the #setup() syscall"), returnDoc = "0 on success and {@code ring} will point to the shared memory containing the {@code io_uring} queues. On failure {@code -errno} is returned." ) int( "queue_mmap", "For users that want to specify {@code sq_thread_cpu} or {@code sq_thread_idle}, this interface is a convenient helper for {@code mmap()}ing the rings.", int("fd", "a file descriptor returned by #setup()"), io_uring_params.p("p", ""), io_uring.p("ring", "on success, contains the necessary information to read/write to the rings"), returnDoc = "{@code -errno} on error, or zero on success" ) int( "ring_dontfork", """ Ensure that the {@code mmap}'ed rings aren't available to a child after a {@code fork(2)}. This uses {@code madvise(..., MADV_DONTFORK)} on the {@code mmap}'ed ranges. """, io_uring.p("ring", "") ) void( "queue_exit", """ Will release all resources acquired and initialized by #queue_init(). It first unmaps the memory shared between the application and the kernel and then closes the {@code io_uring} file descriptor. """, io_uring.p("ring", "") ) unsigned( "peek_batch_cqe", "Fill in an array of IO completions up to count, if any are available.", io_uring.p("ring", ""), io_uring_cqe.p.p("cqes", ""), AutoSize("cqes")..unsigned("count", ""), returnDoc = "the amount of IO completions filled" ) int( "wait_cqes", """ Returns {@code wait_nr} IO completions from the queue belonging to the {@code ring} param, waiting for it if necessary or until the timeout {@code ts} expires. If {@code ts} is specified, the application does not need to call #submit() before calling {@code io_uring_wait_cqes()}. """, io_uring.p("ring", ""), io_uring_cqe.p.p("cqe_ptr", "filled in on success"), AutoSize("cqe_ptr")..unsigned("wait_nr", ""), nullable..__kernel_timespec.p("ts", ""), nullable..sigset_t.p("sigmask", "the set of signals to block. The prevailing signal mask is restored before returning."), returnDoc = "0 on success and the {@code cqe_ptr} param is filled in. On failure it returns {@code -errno}." ) int( "wait_cqe_timeout", """ Returns one IO completion from the queue belonging to the {@code ring} param, waiting for it if necessary or until the timeout {@code ts} expires. If {@code ts} is specified, the application does not need to call #submit() before calling {@code io_uring_wait_cqe_timeout()}. """, io_uring.p("ring", ""), Check(1)..io_uring_cqe.p.p("cqe_ptr", "filled in on success"), nullable..__kernel_timespec.p("ts", ""), returnDoc = "0 on success and the {@code cqe_ptr} param is filled in. On failure it returns {@code -errno}." ) int( "submit", """ Submits the next events to the submission queue belonging to the {@code ring}. After the caller retrieves a submission queue entry (SQE) with #get_sqe(), prepares the SQE, it can be submitted with {@code io_uring_submit()}. """, io_uring.p("ring", ""), returnDoc = "the number of submitted submission queue entries on success. On failure it returns {@code -errno}." ) int( "submit_and_wait", """ Submits the next events to the submission queue belonging to the {@code ring} and waits for {@code wait_nr} completion events. After the caller retrieves a submission queue entry (SQE) with #get_sqe(), prepares the SQE, it can be submitted with {@code io_uring_submit_and_wait()}. """, io_uring.p("ring", ""), unsigned("wait_nr", ""), returnDoc = "the number of submitted submission queue entries on success. On failure it returns {@code -errno}." ) int( "submit_and_wait_timeout", """ Submits the next events to the submission queue belonging to the {@code ring} and waits for {@code wait_nr} completion events or until the timeout {@code ts} expires.The completion events are stored in the {@code cqe_ptr} array. After the caller retrieves a submission queue entry (SQE) with #get_sqe(), prepares the SQE, it can be submitted with {@code io_uring_submit_and_wait_timeout()}. """, io_uring.p("ring", ""), io_uring_cqe.p.p("cqe_ptr", ""), AutoSize("cqe_ptr")..unsigned("wait_nr", ""), nullable..__kernel_timespec.p("ts", ""), nullable..sigset_t.p("sigmask", "the set of signals to block. The prevailing signal mask is restored before returning."), returnDoc = "the number of submitted submission queue entries on success. On failure it returns {@code -errno}." ) io_uring_sqe.p( "get_sqe", """ Gets the next available submission queue entry from the submission queue belonging to the {@code ring} param. If a submission queue event is returned, it should be filled out via one of the prep functions such as #prep_read() and submitted via #submit(). """, io_uring.p("ring", ""), returnDoc = "a pointer to the next submission queue event on success and #NULL on failure" ) int( "register_buffers", """ Registers {@code nr_iovecs} number of buffers defined by the array {@code iovecs} belonging to the {@code ring}. After the caller has registered the buffers, they can be used with one of the fixed buffers functions. Registered buffers is an optimization that is useful in conjunction with {@code O_DIRECT} reads and writes, where maps the specified range into the kernel once when the buffer is registered, rather than doing a map and unmap for each IO every time IO is performed to that region. Additionally, it also avoids manipulating the page reference counts for each IO. """, io_uring.p("ring", ""), iovec.const.p("iovecs", ""), AutoSize("iovecs")..unsigned("nr_iovecs", ""), returnDoc = "0 on success. On failure it returns {@code -errno}." ) int( "register_buffers_tags", "", io_uring.p("ring", ""), iovec.const.p("iovecs", ""), __u64.const.p("tags", ""), AutoSize("iovecs", "tags")..unsigned("nr", "") ) int( "register_buffers_update_tag", "", io_uring.p("ring", ""), unsigned("off", ""), iovec.const.p("iovecs", ""), __u64.const.p("tags", ""), AutoSize("iovecs", "tags")..unsigned("nr", "") ) int( "unregister_buffers", "Unregisters the fixed buffers previously registered to the {@code ring}.", io_uring.p("ring", ""), returnDoc = "0 on success. On failure it returns {@code -errno}." ) int( "register_files", """ Registers {@code nr_files} number of file descriptors defined by the array {@code files} belonging to the {@code ring} for subsequent operations. After the caller has registered the buffers, they can be used with the submission queue polling operations. """, io_uring.p("ring", ""), int.const.p("files", ""), AutoSize("files")..unsigned("nr_files", ""), returnDoc = "0 on success. On failure it returns {@code -errno}." ) int( "register_files_tags", "", io_uring.p("ring", ""), int.const.p("files", ""), __u64.const.p("tags", ""), AutoSize("files", "tags")..unsigned("nr", "") ) int( "register_files_update_tag", "", io_uring.p("ring", ""), unsigned("off", ""), int.const.p("files", ""), __u64.const.p("tags", ""), AutoSize("files", "tags")..unsigned("nr_files", "") ) int( "unregister_files", "", io_uring.p("ring", "") ) int( "register_files_update", "", io_uring.p("ring", ""), unsigned("off", ""), int.p("files", ""), AutoSize("files")..unsigned("nr_files", "") ) int( "register_eventfd", "", io_uring.p("ring", ""), int("fd", "") ) int( "register_eventfd_async", "", io_uring.p("ring", ""), int("fd", "") ) int( "unregister_eventfd", "", io_uring.p("ring", "") ) int( "register_probe", "", io_uring.p("ring", ""), io_uring_probe.p("p", ""), unsigned("nr", "") ) int( "register_personality", "", io_uring.p("ring", "") ) int( "unregister_personality", "", io_uring.p("ring", ""), int("id", "") ) int( "register_restrictions", "", io_uring.p("ring", ""), io_uring_restriction.p("res", ""), AutoSize("res")..unsigned("nr_res", "") ) int( "enable_rings", "", io_uring.p("ring", "") ) int( "__io_uring_sqring_wait", "", io_uring.p("ring", ""), noPrefix = true ) int( "register_iowq_aff", "", io_uring.p("ring", ""), size_t("cpusz", ""), cpu_set_t.const.p("mask", "") ) int( "unregister_iowq_aff", "", io_uring.p("ring", "") ) int( "register_iowq_max_workers", "", io_uring.p("ring", ""), Check(2)..unsigned_int.p("values", "") ) void( "cqe_seen", """ Marks the IO completion {@code cqe} belonging to the {@code ring} param as processed. After the caller has submitted a request with #submit(), they can retrieve the completion with #wait_cqe() and mark it then as processed with {@code io_uring_cqe_seen()}. Completions must be marked as completed, so their slot can get reused. """, io_uring.p("ring", ""), io_uring_cqe.p("cqe", "") ) void( "sqe_set_data", """ Stores a {@code user_data} pointer with the submission queue entry {@code sqe}. After the caller has requested an submission queue entry (SQE) with #get_sqe(), they can associate a data pointer with the SQE. Once the completion arrives, the function #cqe_get_data() can be called to identify the user request. """, io_uring_sqe.p("sqe", ""), opaque_p("data", "") ) opaque_p( "cqe_get_data", """ Returns the {@code user_data} with the completion queue entry {@code cqe}. After the caller has received a completion queue entry (CQE) with #wait_cqe(), they can call the {@code io_uring_cqe_get_data()} function to retrieve the {@code user_data} value. This requires that {@code user_data} has been set earlier with the function #sqe_set_data(). """, io_uring_cqe.const.p("cqe", "") ) void( "sqe_set_data64", """ Assign a 64-bit value to this {@code sqe}, which can get retrieved at completion time with #cqe_get_data64(). Just like the non-64 variants, except these store a 64-bit type rather than a data pointer. """, io_uring_sqe.p("sqe", ""), __u64("data", "") ) __u64( "cqe_get_data64", "See #sqe_set_data64().", io_uring_cqe.const.p("cqe", "") ) void( "sqe_set_flags", """ Allows the caller to change the behavior of the submission queue entry by specifying flags. It enables the {@code flags} belonging to the {@code sqe} submission queue entry param. """, io_uring_sqe.p("sqe", ""), unsigned_int("flags", "") ) void( "prep_splice", """ Precondition: Either {@code fd_in} or {@code fd_out} must be a pipe. This splice operation can be used to implement {@code sendfile} by splicing to an intermediate pipe first, then splice to the final destination. In fact, the implementation of {@code sendfile} in kernel uses {@code splice} internally. NOTE that even if {@code fd_in} or {@code fd_out} refers to a pipe, the splice operation can still failed with {@code EINVAL} if one of the fd doesn't explicitly support splice operation, e.g. reading from terminal is unsupported from kernel 5.7 to 5.11. Check issue \#291 for more information. """, io_uring_sqe.p("sqe", ""), int("fd_in", ""), int64_t( "off_in", """ if {@code fd_in} refers to a pipe, {@code off_in} must be {@code (int64_t) -1}; If {@code fd_in} does not refer to a pipe and {@code off_in} is {@code (int64_t) -1}, then bytes are read from {@code fd_in} starting from the file offset and it is adjust appropriately; If {@code fd_in} does not refer to a pipe and {@code off_in} is not {@code (int64_t) -1}, then the starting {@code offset} of {@code fd_in} will be {@code off_in}. """ ), int("fd_out", ""), int64_t("off_out", "the description of {@code off_in} also applied to {@code off_out}"), unsigned_int("nbytes", ""), unsigned_int("splice_flags", "see man {@code splice(2)} for description of flags") ) void( "prep_tee", "", io_uring_sqe.p("sqe", ""), int("fd_in", ""), int("fd_out", ""), unsigned_int("nbytes", ""), unsigned_int("splice_flags", "") ) void( "prep_readv", """ Prepares a vectored IO read request. The submission queue entry {@code sqe} is setup to use the file descriptor {@code fd} to start reading {@code nr_vecs} into the {@code iovecs} array at the specified {@code offset}. On files that support seeking, if the {@code offset} is set to -1, the read operation commences at the file offset, and the file offset is incremented by the number of bytes read. See {@code read(2)} for more details. On files that are not capable of seeking, the offset is ignored. After the write has been prepared it can be submitted with one of the submit functions. """, io_uring_sqe.p("sqe", ""), int("fd", ""), iovec.const.p("iovecs", ""), AutoSize("iovecs")..unsigned_int("nr_vecs", ""), int("offset", "") ) void( "prep_readv2", """ Prepares a vectored IO read request. The submission queue entry {@code sqe} is setup to use the file descriptor {@code fd} to start reading {@code nr_vecs} into the {@code iovecs} array at the specified {@code offset}. The behavior of the function can be controlled with the {@code flags} parameter. Supported values for flags are: ${ul( "{@code RWF_HIPRI} - High priority request, poll if possible", "{@code RWF_DSYNC} - per-IO {@code O_DSYNC}", "{@code RWF_SYNC} - per-IO {@code O_SYNC}", "{@code RWF_NOWAIT} - per-IO, return {@code -EAGAIN} if operation would block", "{@code RWF_APPEND} - per-IO {@code O_APPEND}" )} On files that support seeking, if the {@code offset} is set to -1, the read operation commences at the file offset, and the file offset is incremented by the number of bytes read. See {@code read(2)} for more details. On files that are not capable of seeking, the offset is ignored. After the write has been prepared, it can be submitted with one of the submit functions. """, io_uring_sqe.p("sqe", ""), int("fd", ""), iovec.const.p("iovecs", ""), AutoSize("iovecs")..unsigned_int("nr_vecs", ""), int("offset", ""), int("flags", "") ) void( "prep_read_fixed", """ Prepares an IO read request with a previously registered IO buffer. The submission queue entry {@code sqe} is setup to use the file descriptor {@code fd} to start reading {@code nbytes} into the buffer {@code buf} at the specified {@code offset}, and with the buffer matching the registered index of {@code buf_index}. This work just like #prep_read() except it requires the user of buffers that have been registered with #register_buffers(). The {@code buf} and {@code nbytes} arguments must fall within a region specificed by {@code buf_index} in the previously registered buffer. The buffer need not be aligned with the start of the registered buffer. After the read has been prepared it can be submitted with one of the submit functions. """, io_uring_sqe.p("sqe", ""), int("fd", ""), void.p("buf", ""), AutoSize("buf")..unsigned_int("nbytes", ""), int("offset", ""), int("buf_index", "") ) void( "prep_writev", """ Prepares a vectored IO write request. The submission queue entry {@code sqe} is setup to use the file descriptor {@code fd} to start writing {@code nr_vecs} from the {@code iovecs} array at the specified {@code offset}. On files that support seeking, if the {@code offset} is set to -1, the write operation commences at the file offset, and the file offset is incremented by the number of bytes written. See {@code write(2)} for more details. On files that are not capable of seeking, the offset is ignored. After the write has been prepared it can be submitted with one of the submit functions. """, io_uring_sqe.p("sqe", ""), int("fd", ""), iovec.const.p("iovecs", ""), AutoSize("iovecs")..unsigned_int("nr_vecs", ""), int("offset", "") ) void( "prep_writev2", """ Prepares a vectored IO write request. The submission queue entry {@code sqe} is setup to use the file descriptor {@code fd} to start writing {@code nr_vecs} from the {@code iovecs} array at the specified {@code offset}. The behavior of the function can be controlled with the {@code flags} parameter. Supported values for flags are: ${ul( "{@code RWF_HIPRI} - High priority request, poll if possible", "{@code RWF_DSYNC} - per-IO {@code O_DSYNC}", "{@code RWF_SYNC} - per-IO {@code O_SYNC}", "{@code RWF_NOWAIT} - per-IO, return {@code -EAGAIN} if operation would block", "{@code RWF_APPEND} - per-IO {@code O_APPEND}" )} On files that support seeking, if the {@code offset} is set to -1, the write operation commences at the file offset, and the file offset is incremented by the number of bytes written. See {@code write(2)} for more details. On files that are not capable of seeking, the offset is ignored. After the write has been prepared, it can be submitted with one of the submit functions. """, io_uring_sqe.p("sqe", ""), int("fd", ""), iovec.const.p("iovecs", ""), AutoSize("iovecs")..unsigned_int("nr_vecs", ""), int("offset", ""), int("flags", "") ) void( "prep_write_fixed", """ Prepares an IO write request with a previously registered IO buffer. The submission queue entry {@code sqe} is setup to use the file descriptor {@code fd} to start writing {@code nbytes} from the buffer {@code buf} at the specified {@code offset}, and with the buffer matching the registered index of {@code buf_index}. This work just like #prep_write() except it requires the user of buffers that have been registered with #register_buffers(). The {@code buf} and {@code nbytes} arguments must fall within a region specificed by {@code buf_index} in the previously registered buffer. The buffer need not be aligned with the start of the registered buffer. After the read has been prepared it can be submitted with one of the submit functions. """, io_uring_sqe.p("sqe", ""), int("fd", ""), void.const.p("buf", ""), AutoSize("buf")..unsigned_int("nbytes", ""), int("offset", ""), int("buf_index", "") ) void( "prep_recvmsg", "", io_uring_sqe.p("sqe", ""), int("fd", ""), msghdr.p("msg", ""), unsigned_int("flags", "") ) void( "prep_sendmsg", "", io_uring_sqe.p("sqe", ""), int("fd", ""), msghdr.const.p("msg", ""), unsigned_int("flags", "") ) void( "prep_poll_add", "", io_uring_sqe.p("sqe", ""), int("fd", ""), unsigned_int("poll_mask", "") ) void( "prep_poll_multishot", "", io_uring_sqe.p("sqe", ""), int("fd", ""), unsigned_int("poll_mask", "") ) void( "prep_poll_remove", "", io_uring_sqe.p("sqe", ""), __u64("user_data", "") ) void( "prep_poll_update", "", io_uring_sqe.p("sqe", ""), __u64("old_user_data", ""), __u64("new_user_data", ""), unsigned_int("poll_mask", ""), unsigned_int("flags", "") ) void( "prep_fsync", "", io_uring_sqe.p("sqe", ""), int("fd", ""), unsigned_int("fsync_flags", "") // TODO: ) void( "prep_nop", "", io_uring_sqe.p("sqe", "") ) void( "prep_timeout", "", io_uring_sqe.p("sqe", ""), __kernel_timespec.p("ts", ""), unsigned_int("count", ""), unsigned_int("flags", "") ) void( "prep_timeout_remove", "", io_uring_sqe.p("sqe", ""), __u64("user_data", ""), unsigned_int("flags", "") ) void( "prep_timeout_update", "", io_uring_sqe.p("sqe", ""), __kernel_timespec.p("ts", ""), __u64("user_data", ""), unsigned_int("flags", "") ) void( "prep_accept", "", io_uring_sqe.p("sqe", ""), int("fd", ""), sockaddr.p("addr", ""), Check(1)..socklen_t.p("addrlen", ""), int("flags", "") ) void( "prep_accept_direct", "", io_uring_sqe.p("sqe", ""), int("fd", ""), sockaddr.p("addr", ""), Check(1)..socklen_t.p("addrlen", ""), int("flags", ""), unsigned_int("file_index", "") ) void( "prep_cancel", "", io_uring_sqe.p("sqe", ""), __u64("user_data", ""), int("flags", "") // TODO: ) void( "prep_link_timeout", "", io_uring_sqe.p("sqe", ""), __kernel_timespec.p("ts", ""), unsigned_int("flags", "") ) void( "prep_connect", "", io_uring_sqe.p("sqe", ""), int("fd", ""), sockaddr.const.p("addr", ""), socklen_t("addrlen", "") ) void( "prep_files_update", "", io_uring_sqe.p("sqe", ""), int.p("fds", ""), AutoSize("fds")..unsigned_int("nr_fds", ""), int("offset", "") ) void( "prep_fallocate", "", io_uring_sqe.p("sqe", ""), int("fd", ""), int("mode", ""), // TODO: off_t("offset", ""), off_t("len", "") ) void( "prep_openat", "", io_uring_sqe.p("sqe", ""), int("dfd", ""), charUTF8.const.p("path", ""), int("flags", ""), // TODO: int("mode", "") // TODO: ) void( "prep_openat_direct", "", io_uring_sqe.p("sqe", ""), int("dfd", ""), charUTF8.const.p("path", ""), int("flags", ""), // TODO: int("mode", ""), // TODO: unsigned_int("file_index", "") ) void( "prep_close", "", io_uring_sqe.p("sqe", ""), int("fd", "") ) void( "prep_close_direct", "", io_uring_sqe.p("sqe", ""), unsigned_int("file_index", "") ) void( "prep_read", """ Prepares an IO read request. The submission queue entry {@code sqe} is setup to use the file descriptor {@code fd} to start reading {@code nbytes} into the buffer {@code buf} at the specified {@code offset}. On files that support seeking, if the {@code offset} is set to -1, the read operation commences at the file offset, and the file offset is incremented by the number of bytes read. See {@code read(2)} for more details. On files that are not capable of seeking, the {@code offset} is ignored. After the read has been prepared it can be submitted with one of the submit functions. """, io_uring_sqe.p("sqe", ""), int("fd", ""), void.p("buf", ""), AutoSize("buf")..unsigned_int("nbytes", ""), int("offset", "") ) void( "prep_write", """ Prepares an IO write request. The submission queue entry {@code sqe} is setup to use the file descriptor {@code fd} to start writing {@code nbytes} from the buffer {@code buf} at the specified {@code offset}. On files that support seeking, if the {@code offset} is set to -1, the write operation commences at the file offset, and the file offset is incremented by the number of bytes written. See {@code write(2)} for more details. On files that are not capable of seeking, the offset is ignored. After the write has been prepared, it can be submitted with one of the submit functions. """, io_uring_sqe.p("sqe", ""), int("fd", ""), void.const.p("buf", ""), AutoSize("buf")..unsigned_int("nbytes", ""), int("offset", "") ) void( "prep_statx", "", io_uring_sqe.p("sqe", ""), int("dfd", ""), charUTF8.const.p("path", ""), int("flags", ""), unsigned_int("mask", ""), statx.p("statxbuf", "") ) void( "prep_fadvise", "", io_uring_sqe.p("sqe", ""), int("fd", ""), int("offset", ""), off_t("len", ""), int("advice", "") // TODO: ) void( "prep_madvise", "", io_uring_sqe.p("sqe", ""), void.p("addr", ""), AutoSize("addr")..off_t("length", ""), int("advice", "") // TODO: ) void( "prep_send", "", io_uring_sqe.p("sqe", ""), int("sockfd", ""), void.const.p("buf", ""), AutoSize("buf")..size_t("len", ""), int("flags", "") ) void( "prep_recv", "", io_uring_sqe.p("sqe", ""), int("sockfd", ""), void.p("buf", ""), AutoSize("buf")..size_t("len", ""), int("flags", "") ) void( "prep_openat2", "", io_uring_sqe.p("sqe", ""), int("dfd", ""), charUTF8.const.p("path", ""), open_how.p("how", "") ) void( "prep_openat2_direct", "open directly into the fixed file table", io_uring_sqe.p("sqe", ""), int("dfd", ""), charUTF8.const.p("path", ""), open_how.p("how", ""), unsigned_int("file_index", "") ) void( "prep_epoll_ctl", "", io_uring_sqe.p("sqe", ""), int("epfd", ""), int("fd", ""), int("op", ""), epoll_event.p("ev", "") ) void( "prep_provide_buffers", "", io_uring_sqe.p("sqe", ""), void.p("addr", ""), AutoSize("addr")..int("len", ""), int("nr", ""), int("bgid", ""), int("bid", "") ) void( "prep_remove_buffers", "", io_uring_sqe.p("sqe", ""), int("nr", ""), int("bgid", "") ) void( "prep_shutdown", "", io_uring_sqe.p("sqe", ""), int("fd", ""), int("how", "") // TODO: ) void( "prep_unlinkat", "", io_uring_sqe.p("sqe", ""), int("dfd", ""), charUTF8.const.p("path", ""), int("flags", "") // TODO: ) void( "prep_renameat", "", io_uring_sqe.p("sqe", ""), int("olddfd", ""), charUTF8.const.p("oldpath", ""), int("newdfd", ""), charUTF8.const.p("newpath", ""), int("flags", "") // TODO: ) void( "prep_sync_file_range", "", io_uring_sqe.p("sqe", ""), int("fd", ""), unsigned_int("len", ""), int("offset", ""), int("flags", "") // TODO: ) void( "prep_mkdirat", "", io_uring_sqe.p("sqe", ""), int("dfd", ""), charUTF8.const.p("path", ""), int("mode", "") // TODO: ) void( "prep_symlinkat", "", io_uring_sqe.p("sqe", ""), charUTF8.const.p("target", ""), int("newdirfd", ""), charUTF8.const.p("linkpath", "") ) void( "prep_linkat", "", io_uring_sqe.p("sqe", ""), int("olddfd", ""), charUTF8.const.p("oldpath", ""), int("newdfd", ""), charUTF8.const.p("newpath", ""), int("flags", "") // TODO: ) // TODO: add readdir(3) /*void( "prep_getdents", """ Prepares a {@code getdents64} request. The submission queue entry {@code sqe} is setup to use the file descriptor {@code fd} to start writing up to {@code count} bytes into the buffer {@code buf} starting at {@code offset}. After the {@code getdents} call has been prepared it can be submitted with one of the submit functions. """, io_uring_sqe.p("sqe", ""), int("fd", ""), void.p("buf", ""), AutoSize("buf")..unsigned_int("count", ""), uint64_t("offset", "") )*/ unsigned_int( "sq_ready", "Returns the number of unconsumed (if {@code SQPOLL}) or unsubmitted entries that exist in the SQ ring belonging to the {@code ring} param.", io_uring.const.p("ring", "") ) unsigned_int( "sq_space_left", "Returns how much space is left in the SQ ring belonging to the {@code ring} param.", io_uring.const.p("ring", "") ) int( "sqring_wait", """ Allows the caller to wait for space to free up in the SQ ring belonging to the {@code ring} param, which happens when the kernel side thread has consumed one or more entries. If the SQ ring is currently non-full, no action is taken. This feature can only be used when {@code SQPOLL} is enabled. """, io_uring.p("ring", "") ) unsigned_int( "cq_ready", "Retuns the number of unconsumed entries that are ready belonging to the {@code ring} param.", io_uring.const.p("ring", "") ) bool( "cq_eventfd_enabled", "Returns true if the {@code eventfd} notification is currently enabled.", io_uring.const.p("ring", "") ) int( "cq_eventfd_toggle", "Toggle {@code eventfd} notification on or off, if an {@code eventfd} is registered with the ring.", io_uring.p("ring", ""), bool("enabled", "") ) int( "wait_cqe_nr", """ Returns {@code wait_nr} IO completion events from the queue belonging to the {@code ring} param, waiting for it if necessary. The {@code cqe_ptr} param is filled in on success. After the caller has submitted a request with #submit(), they can retrieve the completion with {@code io_uring_wait_cqe_nr()}. """, io_uring.p("ring", ""), io_uring_cqe.p.p("cqe_ptr", ""), AutoSize("cqe_ptr")..unsigned_int("wait_nr", ""), returnDoc = "0 on success and the {@code cqe_ptr} param is filled in. On failure it returns {@code -errno}." ) int( "peek_cqe", "Returns an IO completion, if one is readily available.", io_uring.p("ring", ""), Check(1)..io_uring_cqe.p.p("cqe_ptr", ""), returnDoc = "0 with {@code cqe_ptr} filled in on success, {@code -errno} on failure" ) int( "wait_cqe", """ Returns an IO completion from the queue belonging to the {@code ring} param, waiting for it if necessary. The {@code cqe_ptr} param is filled in on success. After the caller has submitted a request with #submit(), they can retrieve the completion with {@code io_uring_wait_cqe()}. """, io_uring.p("ring", ""), Check(1)..io_uring_cqe.p.p("cqe_ptr", ""), returnDoc = "0 on success and the {@code cqe_ptr} param is filled in. On failure it returns {@code -errno}." ) int( "mlock_size", "Return required {@code ulimit -l} memory space for a given ring setup. See #mlock_size_params().", unsigned("entries", ""), unsigned("flags", "{@code io_uring_params} flags") ) int( "mlock_size_params", """ Returns the required {@code ulimit -l memlock} memory required for a given ring setup, in bytes. May return {@code -errno} on error. On newer (5.12+) kernels, {@code io_uring} no longer requires any {@code memlock} memory, and hence this function will return 0 for that case. On older (5.11 and prior) kernels, this will return the required memory so that the caller can ensure that enough space is available before setting up a ring with the specified parameters. """, unsigned("entries", ""), io_uring_params.p("p", "") ) }
bsd-3-clause
8d746c992ccda2742484f107f475ce90
28.041864
161
0.534108
3.880317
false
false
false
false
MGaetan89/ShowsRage
app/src/main/kotlin/com/mgaetan89/showsrage/presenter/EpisodePresenter.kt
1
841
package com.mgaetan89.showsrage.presenter import android.support.annotation.ColorRes import android.text.format.DateUtils import com.mgaetan89.showsrage.extension.toRelativeDate import com.mgaetan89.showsrage.model.Episode class EpisodePresenter(val episode: Episode?) { fun getAirDate(): CharSequence? { val airDate = this._getEpisode()?.airDate ?: return null if (airDate.isEmpty()) { return null } return airDate.toRelativeDate("yyyy-MM-dd", DateUtils.DAY_IN_MILLIS) } fun getQuality(): String { val quality = this._getEpisode()?.quality ?: return "" return if ("N/A".equals(quality, true)) "" else quality } @ColorRes fun getStatusColor() = this._getEpisode()?.getStatusBackgroundColor() ?: android.R.color.transparent private fun _getEpisode() = if (this.episode?.isValid == true) this.episode else null }
apache-2.0
e0c99281ea61b45b61386d69d50be15a
28
101
0.743163
3.721239
false
false
false
false
BreakOutEvent/breakout-backend
src/main/java/backend/model/event/TeamServiceImpl.kt
1
7782
package backend.model.event import backend.controller.exceptions.NotFoundException import backend.model.media.Media import backend.model.media.MediaService import backend.model.misc.Email import backend.model.misc.EmailAddress import backend.model.user.Participant import backend.model.user.User import backend.model.user.UserService import backend.services.ConfigurationService import backend.services.mail.MailService import backend.util.data.DonateSums import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.data.domain.PageRequest import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.math.BigDecimal import kotlin.math.sqrt @Service class TeamServiceImpl(private val repository: TeamRepository, private val userService: UserService, private val mailService: MailService, private val mediaService: MediaService, private val configurationService: ConfigurationService) : TeamService { private val logger: Logger = LoggerFactory.getLogger(TeamServiceImpl::class.java) @Transactional override fun create(creator: Participant, name: String, description: String, event: Event, profilePic: Media?, postaddress: String?): Team { val team = Team(creator, name, description, event, profilePic, postaddress) // TODO: Maybe use sensible cascading? if (team.profilePic != null) { team.profilePic = mediaService.save(team.profilePic as Media) } val savedTeam = this.repository.save(team) savedTeam.invoice?.generatePurposeOfTransfer() userService.save(creator) return savedTeam } override fun invite(emailAddress: EmailAddress, team: Team) { team.invite(emailAddress) mailService.sendInvitationEmail(emailAddress, team) this.save(team) } private fun getInvitationUrl(token: String): String { val baseUrl = configurationService.getRequired("org.breakout.team.invitationurl") return "${baseUrl.replace("CUSTOMTOKEN", token)}?utm_source=backend&utm_medium=email&utm_campaign=invite" } override fun save(team: Team): Team { if (team.profilePic != null) { team.profilePic = mediaService.save(team.profilePic as Media) } return repository.save(team) } override fun findOne(id: Long) = repository.findById(id) override fun findPostingsById(teamId: Long, page: Int, size: Int) = repository.findPostingsByTeamId(teamId, PageRequest(page, size)) override fun findLocationPostingsById(id: Long) = repository.findLocationByTeamId(id) override fun findInvitationsForUser(user: User): List<Invitation> { return repository.findInvitationsWithEmail(user.email) } override fun findInvitationsForUserAndEvent(user: User, eventId: Long): List<Invitation> { return repository.findInvitationsWithEmailAndEventId(user.email, eventId) } override fun getDistanceForTeam(teamId: Long): Double { return this.findOne(teamId)?.getCurrentDistance() ?: 0.0 } override fun findInvitationsByInviteCode(code: String): Invitation? { return repository.findInvitationsByInviteCode(code) } override fun findInvitationsByTeamId(teamId: Long): List<Invitation> { return repository.findInvitationsByTeamId(teamId) } @Transactional override fun leave(team: Team, participant: Participant) { team.leave(participant) } @Transactional override fun join(participant: Participant, team: Team) { val members = team.join(participant) if (team.isFull()) { mailService.sendTeamIsCompleteEmail(team.members.toList()) } } override fun getDistance(teamId: Long): Double { return this.findOne(teamId)?.getCurrentDistance() ?: 0.0 } override fun findByEventId(eventId: Long): List<Team> { return repository.findByEventId(eventId) } fun getSponsoringSum(team: Team): BigDecimal { return team.raisedAmountFromSponsorings().numberStripped } fun getChallengeSum(team: Team): BigDecimal { return team.raisedAmountFromChallenges().numberStripped } override fun getDonateSum(team: Team): DonateSums { val sponsorSum = getSponsoringSum(team) val challengesSum = getChallengeSum(team) return DonateSums(sponsorSum, challengesSum, sponsorSum + challengesSum) } @Transactional override fun getDonateSum(teamId: Long): DonateSums { val team: Team = this.findOne(teamId) ?: throw NotFoundException("Team with id $teamId not found") return getDonateSum(team) } override fun getScore(team: Team): Double { val donateSum = getDonateSum(team) val distance = getDistance(team.id!!) var totalScore = 0.0 if (team.event.city == "Anywhere") { totalScore = donateSum.fullSum.toDouble() + distance }else{ totalScore = sqrt(donateSum.fullSum.toDouble() * distance) } return totalScore } @Transactional override fun getScore(teamId: Long): Double { val team: Team = this.findOne(teamId) ?: throw NotFoundException("Team with id $teamId not found") return getScore(team) } override fun searchByString(search: String): List<Team> { return repository.searchByString(search) } override fun sendEmailsToTeamsWhenEventHasEnded() { repository.findAll().filter { it.hasStarted } .apply { logger.info("Sending emails that event has ended to ${this.count()} teams") } .forEach { val mail = Email( to = it.members.map { EmailAddress(it.email) }, subject = "BreakOut 2016 - War ein voller Erfolg!", body = getEmailBodyToTeamsWhenEventHasEnded(it), buttonText = "ZUM LIVEBLOG", buttonUrl = "https://event.break-out.org/?utm_source=backend&utm_medium=email&utm_content=intial&utm_campaign=event_ended_team") mailService.sendAsync(mail) } } private fun getEmailBodyToTeamsWhenEventHasEnded(team: Team): String { return "Liebes Team ${team.name}," + "Ihr habt es geschafft und habt erfolgreich bei BreakOut 2016 teilgenommen. Wir feiern Euch hart ab. Mega, dass Ihr mitgemacht und so gemeinsam Spenden für das DAFI-Programm der UNO Flüchtlingshilfe gesammelt habt.<br><br>" + "Damit wir Eure überragende Leistung gebührend zusammen feiern können, seid Ihr alle herzlich zur BreakOut- Siegerehrung eingeladen.<br>" + "Diese findet am 15. Juni um 18:00 Uhr in der 089-Bar in München statt.<br><br>" + "Weitere Informationen zur Siegerehrung und Eurer Reise folgen bald.<br><br>" + "Genießt den Abend. Wir wünschen Euch eine schöne und sichere Heimreise.<br>" + "Ihr BreakOut-Team" } override fun findAll(): Iterable<Team> { return repository.findAll() } override fun findAllTeamSummaryProjections(): Iterable<TeamSummaryProjection> { return repository.findAllByEventIsCurrentTrueOrderByName() } override fun sendEmailsToTeamsWithDonationOverview(event: Event): Int { val teams = this.findByEventId(event.id!!).filter { it.hasStarted } teams.forEach { mailService.sendTeamWithDonationOverviewEmail(it) Thread.sleep(1000) // Needed in order not to kill our mailserver } return teams.size } }
agpl-3.0
a7d14b343e3458bb76aafaa5fdf8b707
36.375
241
0.677473
4.354622
false
false
false
false
imageprocessor/cv4j
app/src/main/java/com/cv4j/app/activity/DslActivity.kt
1
1476
package com.cv4j.app.activity import android.graphics.BitmapFactory import android.os.Bundle import com.cv4j.app.R import com.cv4j.app.app.BaseActivity import com.cv4j.core.filters.NatureFilter import com.cv4j.rxjava.cv4j import kotlinx.android.synthetic.main.activity_dsl.* import thereisnospon.codeview.CodeViewTheme class DslActivity : BaseActivity() { var title: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_dsl) initData() } private fun initData() { title = intent.extras?.getString("Title") toolbar?.title = "< " + title cv4j { bitmap = BitmapFactory.decodeResource(resources, R.drawable.test_io) filter = NatureFilter() imageView = image } codeview?.setTheme(CodeViewTheme.ANDROIDSTUDIO)?.fillColor() val code = StringBuilder() code.append("cv4j {") .append("\r\n") .append(" bitmap = BitmapFactory.decodeResource(resources, R.drawable.test_io)") .append("\r\n") .append(" filter = NatureFilter()") .append("\r\n") .append(" imageView = image") .append("\r\n") .append("}") codeview?.showCode(code.toString()) toolbar?.setOnClickListener { finish() } } }
apache-2.0
5217cfcef2a31c4dd3e78558a950ff8f
25.836364
99
0.595528
4.278261
false
false
false
false
google/intellij-community
plugins/kotlin/gradle/gradle-tooling/tests/test/org/jetbrains/kotlin/gradle/createKotlinMPPGradleModel.kt
2
5581
// 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.gradle import org.gradle.internal.impldep.org.apache.commons.lang.math.RandomUtils import org.jetbrains.kotlin.idea.gradleTooling.* import org.jetbrains.kotlin.idea.gradleTooling.arguments.* import org.jetbrains.kotlin.idea.projectModel.* internal fun createKotlinMPPGradleModel( dependencyMap: Map<KotlinDependencyId, KotlinDependency> = emptyMap(), sourceSets: Set<KotlinSourceSet> = emptySet(), targets: Iterable<KotlinTarget> = emptyList(), extraFeatures: ExtraFeatures = createExtraFeatures(), kotlinNativeHome: String = "" ): KotlinMPPGradleModelImpl { return KotlinMPPGradleModelImpl( dependencyMap = dependencyMap, sourceSetsByName = sourceSets.associateBy { it.name }, targets = targets.toList(), extraFeatures = extraFeatures, kotlinNativeHome = kotlinNativeHome, cacheAware = CompilerArgumentsCacheAwareImpl() ) } internal fun createExtraFeatures( coroutinesState: String? = null, isHmppEnabled: Boolean = false, ): ExtraFeaturesImpl { return ExtraFeaturesImpl( coroutinesState = coroutinesState, isHMPPEnabled = isHmppEnabled, ) } internal fun createKotlinSourceSet( name: String, declaredDependsOnSourceSets: Set<String> = emptySet(), allDependsOnSourceSets: Set<String> = declaredDependsOnSourceSets, platforms: Set<KotlinPlatform> = emptySet(), ): KotlinSourceSetImpl = KotlinSourceSetImpl( name = name, languageSettings = KotlinLanguageSettingsImpl( languageVersion = null, apiVersion = null, isProgressiveMode = false, enabledLanguageFeatures = emptySet(), optInAnnotationsInUse = emptySet(), compilerPluginArguments = emptyArray(), compilerPluginClasspath = emptySet(), freeCompilerArgs = emptyArray() ), sourceDirs = emptySet(), resourceDirs = emptySet(), regularDependencies = emptyArray(), intransitiveDependencies = emptyArray(), declaredDependsOnSourceSets = declaredDependsOnSourceSets, allDependsOnSourceSets = allDependsOnSourceSets, additionalVisibleSourceSets = emptySet(), actualPlatforms = KotlinPlatformContainerImpl().apply { pushPlatforms(platforms) }, ) @Suppress("DEPRECATION_ERROR") internal fun createKotlinCompilation( name: String = "main", defaultSourceSets: Set<KotlinSourceSet> = emptySet(), allSourceSets: Set<KotlinSourceSet> = emptySet(), dependencies: Iterable<KotlinDependencyId> = emptyList(), output: KotlinCompilationOutput = createKotlinCompilationOutput(), arguments: KotlinCompilationArguments = createKotlinCompilationArguments(), dependencyClasspath: Iterable<String> = emptyList(), cachedArgsInfo: CachedArgsInfo<*> = createCachedArgsInfo(), kotlinTaskProperties: KotlinTaskProperties = createKotlinTaskProperties(), nativeExtensions: KotlinNativeCompilationExtensions? = null, associateCompilations: Set<KotlinCompilationCoordinates> = emptySet() ): KotlinCompilationImpl { return KotlinCompilationImpl( name = name, declaredSourceSets = defaultSourceSets, allSourceSets = allSourceSets, dependencies = dependencies.toList().toTypedArray(), output = output, arguments = arguments, dependencyClasspath = dependencyClasspath.toList().toTypedArray(), cachedArgsInfo = cachedArgsInfo, kotlinTaskProperties = kotlinTaskProperties, nativeExtensions = nativeExtensions, associateCompilations = associateCompilations ) } internal fun createKotlinCompilationOutput(): KotlinCompilationOutputImpl { return KotlinCompilationOutputImpl( classesDirs = emptySet(), effectiveClassesDir = null, resourcesDir = null ) } @Suppress("DEPRECATION_ERROR") internal fun createKotlinCompilationArguments(): KotlinCompilationArgumentsImpl { return KotlinCompilationArgumentsImpl( defaultArguments = emptyArray(), currentArguments = emptyArray() ) } internal fun createCachedArgsBucket(): CachedCompilerArgumentsBucket = CachedCompilerArgumentsBucket( compilerArgumentsClassName = KotlinCachedRegularCompilerArgument(0), singleArguments = emptyMap(), classpathParts = KotlinCachedMultipleCompilerArgument(emptyList()), multipleArguments = emptyMap(), flagArguments = emptyMap(), internalArguments = emptyList(), freeArgs = emptyList() ) internal fun createCachedArgsInfo(): CachedArgsInfo<*> = CachedExtractedArgsInfo( cacheOriginIdentifier = RandomUtils.nextLong(), currentCompilerArguments = createCachedArgsBucket(), defaultCompilerArguments = createCachedArgsBucket(), dependencyClasspath = emptyList() ) internal fun createKotlinTaskProperties(): KotlinTaskPropertiesImpl { return KotlinTaskPropertiesImpl( null, null, null, null ) } internal fun createKotlinTarget( name: String, platform: KotlinPlatform = KotlinPlatform.COMMON, compilations: Iterable<KotlinCompilation> = emptyList() ): KotlinTargetImpl { return KotlinTargetImpl( name = name, presetName = null, disambiguationClassifier = null, platform = platform, compilations = compilations.toList(), testRunTasks = emptyList(), nativeMainRunTasks = emptyList(), jar = null, konanArtifacts = emptyList() ) }
apache-2.0
aa0657fd6d273ff719d1ff5496e50897
36.709459
158
0.734456
5.918346
false
false
false
false
allotria/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/ProjectModule.kt
1
986
package com.jetbrains.packagesearch.intellij.plugin.extensibility import com.intellij.openapi.module.Module import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vfs.VirtualFile import com.intellij.pom.Navigatable enum class BuildSystemType(val statisticsKey: String) { MAVEN(statisticsKey = "maven"), GRADLE_GROOVY(statisticsKey = "gradle-groovy"), GRADLE_KOTLIN(statisticsKey = "gradle-kts") } data class ProjectModule( @NlsSafe val name: String, val nativeModule: Module, val parent: ProjectModule?, val buildFile: VirtualFile, val buildSystemType: BuildSystemType, val moduleType: ProjectModuleType ) { var getNavigatableDependency: (groupId: String, artifactId: String, version: String) -> Navigatable? = { _: String, _: String, _: String -> null } @NlsSafe fun getFullName(): String { if (parent != null) { return parent.getFullName() + ":$name" } return name } }
apache-2.0
9d096e55b7aa892c92e5c18f8f587f17
28.878788
106
0.697769
4.401786
false
false
false
false
leafclick/intellij-community
python/src/com/jetbrains/python/codeInsight/intentions/PyAbsoluteToRelativeImportIntention.kt
13
1645
// 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.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.jetbrains.python.codeInsight.imports.PyRelativeImportData import com.jetbrains.python.psi.PyFile import com.jetbrains.python.psi.resolve.QualifiedNameFinder /** * Converts location of 'from one.two.three import foo' to the one relative to the current file, e.g. 'from .three import foo'. * * @see PyRelativeToAbsoluteImportIntention * @author Aleksei.Kniazev */ class PyAbsoluteToRelativeImportIntention : PyConvertImportIntentionAction("INTN.convert.absolute.to.relative") { override fun doInvoke(project: Project, editor: Editor, file: PsiFile) { val statement = findStatement(file, editor) ?: return val targetPath = statement.importSourceQName ?: return val importData = PyRelativeImportData.fromString(targetPath.toString(), file as PyFile) ?: return replaceImportStatement(statement, file, importData.locationWithDots) } override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { if (file !is PyFile) return false val statement = findStatement(file, editor) ?: return false if (statement.relativeLevel != 0) return false val targetPath = statement.importSourceQName ?: return false val filePath = QualifiedNameFinder.findCanonicalImportPath(file, null) ?: return false return targetPath.firstComponent == filePath.firstComponent } }
apache-2.0
2769298e8a60796357f1b91ef0dfd122
44.722222
140
0.779939
4.272727
false
false
false
false
leafclick/intellij-community
platform/vcs-tests/testSrc/com/intellij/openapi/vcs/BaseChangeListsTest.kt
1
10792
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs import com.intellij.openapi.application.AccessToken import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.undo.DocumentReferenceManager import com.intellij.openapi.command.undo.DocumentReferenceProvider import com.intellij.openapi.editor.Document import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.BaseLineStatusTrackerTestCase.Companion.parseInput import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.changes.committed.MockAbstractVcs import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl import com.intellij.openapi.vcs.impl.projectlevelman.AllVcses import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.LightPlatformTestCase import com.intellij.testFramework.RunAll import com.intellij.util.ThrowableRunnable import com.intellij.util.ui.UIUtil import com.intellij.vcsUtil.VcsUtil import org.mockito.Mockito import java.util.concurrent.Semaphore import java.util.concurrent.TimeUnit abstract class BaseChangeListsTest : LightPlatformTestCase() { companion object { val DEFAULT = LocalChangeList.getDefaultName() fun createMockFileEditor(document: Document): FileEditor { val editor = Mockito.mock(FileEditor::class.java, Mockito.withSettings().extraInterfaces(DocumentReferenceProvider::class.java)) val references = listOf(DocumentReferenceManager.getInstance().create(document)) Mockito.`when`((editor as DocumentReferenceProvider).documentReferences).thenReturn(references) return editor } } protected lateinit var vcs: MyMockVcs protected lateinit var changeProvider: MyMockChangeProvider protected lateinit var clm: ChangeListManagerImpl protected lateinit var dirtyScopeManager: VcsDirtyScopeManagerImpl protected lateinit var testRoot: VirtualFile protected lateinit var vcsManager: ProjectLevelVcsManagerImpl protected var arePartialChangelistsSupported: Boolean = true override fun setUp() { super.setUp() testRoot = runWriteAction { VfsUtil.markDirtyAndRefresh(false, false, true, this.project.baseDir) VfsUtil.createDirectoryIfMissing(this.project.baseDir, getTestName(true)) } vcs = MyMockVcs(this.project) changeProvider = MyMockChangeProvider() vcs.changeProvider = changeProvider clm = ChangeListManagerImpl.getInstanceImpl(this.project) dirtyScopeManager = VcsDirtyScopeManager.getInstance(this.project) as VcsDirtyScopeManagerImpl vcsManager = ProjectLevelVcsManager.getInstance(this.project) as ProjectLevelVcsManagerImpl vcsManager.registerVcs(vcs) vcsManager.directoryMappings = listOf(VcsDirectoryMapping(testRoot.path, vcs.name)) vcsManager.waitForInitialized() assertTrue(vcsManager.hasActiveVcss()) try { resetTestState() } catch (e: Throwable) { super.tearDown() throw e } } override fun tearDown() { RunAll() .append(ThrowableRunnable { resetSettings() }) .append(ThrowableRunnable { resetChanges() }) .append(ThrowableRunnable { resetChangelists() }) .append(ThrowableRunnable { vcsManager.directoryMappings = emptyList() }) .append(ThrowableRunnable { AllVcses.getInstance(getProject()).unregisterManually(vcs) }) .append(ThrowableRunnable { runWriteAction { testRoot.delete(this) } }) .append(ThrowableRunnable { super.tearDown() }) .run() } protected open fun resetSettings() { arePartialChangelistsSupported = false } protected open fun resetTestState() { resetSettings() resetChanges() resetChangelists() resetTestRootContent() } private fun resetTestRootContent() { VfsUtil.markDirtyAndRefresh(false, true, true, testRoot) runWriteAction { testRoot.children.forEach { child -> child.delete(this) } } } private fun resetChanges() { changeProvider.changes.clear() changeProvider.files.clear() clm.waitUntilRefreshed() } private fun resetChangelists() { clm.addChangeList(LocalChangeList.getDefaultName(), null) clm.setDefaultChangeList(LocalChangeList.getDefaultName()) for (changeListName in clm.changeLists.map { it.name }) { if (changeListName != LocalChangeList.getDefaultName()) clm.removeChangeList(changeListName) } clm.waitUntilRefreshed() } protected fun addLocalFile(name: String, content: String): VirtualFile { val file = runWriteAction { val file = testRoot.createChildData(this, name) VfsUtil.saveText(file, parseInput(content)) file } assertFalse(changeProvider.files.contains(file)) changeProvider.files.add(file) return file } protected fun removeLocalFile(name: String) { val file = runWriteAction { val file = VfsUtil.findRelativeFile(testRoot, name) file!!.delete(this) file } assertTrue(changeProvider.files.contains(file)) changeProvider.files.remove(file) } protected fun setBaseVersion(name: String, baseContent: String?) { setBaseVersion(name, baseContent, name) } protected fun setBaseVersion(name: String, baseContent: String?, oldName: String) { val contentRevision: ContentRevision? = when (baseContent) { null -> null else -> SimpleContentRevision(parseInput(baseContent), oldName.toFilePath, baseContent) } changeProvider.changes[name.toFilePath] = contentRevision } protected fun removeBaseVersion(name: String) { changeProvider.changes.remove(name.toFilePath) } protected fun refreshCLM() { dirtyScopeManager.markEverythingDirty() clm.waitUntilRefreshed() UIUtil.dispatchAllInvocationEvents() // ensure `fileStatusesChanged` events are fired } protected val String.toFilePath: FilePath get() = VcsUtil.getFilePath(testRoot, this) protected fun Array<out String>.toFilePaths() = this.asList().toFilePaths() protected fun List<String>.toFilePaths() = this.map { it.toFilePath } protected val VirtualFile.change: Change? get() = clm.getChange(this) protected val VirtualFile.document: Document get() = FileDocumentManager.getInstance().getDocument(this)!! protected fun VirtualFile.assertAffectedChangeLists(vararg expectedNames: String) { assertSameElements(clm.getChangeLists(this).map { it.name }, *expectedNames) } protected fun FilePath.assertAffectedChangeLists(vararg expectedNames: String) { val change = clm.getChange(this)!! assertSameElements(clm.getChangeLists(change).map { it.name }, *expectedNames) } protected fun String.asListNameToList(): LocalChangeList = clm.changeLists.find { it.name == this }!! protected fun String.asListIdToList(): LocalChangeList = clm.changeLists.find { it.id == this }!! protected fun String.asListNameToId(): String = asListNameToList().id protected fun String.asListIdToName(): String = asListIdToList().name protected fun Iterable<String>.asListNamesToIds() = this.map { it.asListNameToId() } protected fun Iterable<String>.asListIdsToNames() = this.map { it.asListIdToName() } private fun changeListsNames() = clm.changeLists.map { it.name } fun runBatchFileChangeOperation(task: () -> Unit) { BackgroundTaskUtil.syncPublisher(project, VcsFreezingProcess.Listener.TOPIC).onFreeze() try { task() } finally { BackgroundTaskUtil.syncPublisher(project, VcsFreezingProcess.Listener.TOPIC).onUnfreeze() } } protected fun createChangelist(listName: String) { assertDoesntContain(changeListsNames(), listName) clm.addChangeList(listName, null) } protected fun removeChangeList(listName: String) { assertContainsElements(changeListsNames(), listName) clm.removeChangeList(listName) } protected fun setDefaultChangeList(listName: String) { assertContainsElements(changeListsNames(), listName) clm.setDefaultChangeList(listName) } protected fun VirtualFile.moveChanges(fromListName: String, toListName: String) { assertContainsElements(changeListsNames(), fromListName) assertContainsElements(changeListsNames(), toListName) val listChange = fromListName.asListNameToList().changes.find { it == this.change!! }!! clm.moveChangesTo(toListName.asListNameToList(), listChange) } protected fun VirtualFile.moveAllChangesTo(toListName: String) { assertContainsElements(changeListsNames(), toListName) clm.moveChangesTo(toListName.asListNameToList(), this.change!!) } protected inner class MyMockChangeProvider : ChangeProvider { private val semaphore = Semaphore(1) private val markerSemaphore = Semaphore(0) val changes = mutableMapOf<FilePath, ContentRevision?>() val files = mutableSetOf<VirtualFile>() override fun getChanges(dirtyScope: VcsDirtyScope, builder: ChangelistBuilder, progress: ProgressIndicator, addGate: ChangeListManagerGate) { markerSemaphore.release() semaphore.acquireOrThrow() try { for ((filePath, beforeRevision) in changes) { val file = files.find { VcsUtil.getFilePath(it) == filePath } val afterContent: ContentRevision? = when (file) { null -> null else -> CurrentContentRevision(filePath) } val change = Change(beforeRevision, afterContent) builder.processChange(change, MockAbstractVcs.getKey()) } } finally { semaphore.release() markerSemaphore.acquireOrThrow() } } override fun isModifiedDocumentTrackingRequired(): Boolean { return false } override fun doCleanup(files: List<VirtualFile>) { } fun awaitAndBlockRefresh(): AccessToken { semaphore.acquireOrThrow() dirtyScopeManager.markEverythingDirty() clm.scheduleUpdate() markerSemaphore.acquireOrThrow() markerSemaphore.release() return object : AccessToken() { override fun finish() { semaphore.release() } } } private fun Semaphore.acquireOrThrow() { val success = this.tryAcquire(10000, TimeUnit.MILLISECONDS) if (!success) throw IllegalStateException() } } protected inner class MyMockVcs(project: Project) : MockAbstractVcs(project) { override fun arePartialChangelistsSupported(): Boolean = arePartialChangelistsSupported } }
apache-2.0
2f9aad56ab478d1fdfc0b0accdde24c1
34.857143
140
0.739437
4.987061
false
true
false
false
leafclick/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionReference.kt
1
4865
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions import com.intellij.lang.java.beans.PropertyKind import com.intellij.psi.PsiElement import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.GrSuperReferenceResolver.resolveSuperExpression import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.GrThisReferenceResolver.resolveThisExpression import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil import org.jetbrains.plugins.groovy.lang.psi.util.getRValue import org.jetbrains.plugins.groovy.lang.psi.util.isPropertyName import org.jetbrains.plugins.groovy.lang.resolve.GrReferenceResolveRunner import org.jetbrains.plugins.groovy.lang.resolve.GrResolverProcessor import org.jetbrains.plugins.groovy.lang.resolve.api.Argument import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyCachingReference import org.jetbrains.plugins.groovy.lang.resolve.processors.AccessorAwareProcessor import org.jetbrains.plugins.groovy.lang.resolve.processors.AccessorProcessor import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolveKind import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolveKind.* import java.util.* abstract class GrReferenceExpressionReference(ref: GrReferenceExpressionImpl) : GroovyCachingReference<GrReferenceExpressionImpl>(ref) { override fun doResolve(incomplete: Boolean): Collection<GroovyResolveResult> { require(!incomplete) val staticResults = element.staticReference.resolve(incomplete) if (staticResults.isNotEmpty()) { return staticResults } return doResolveNonStatic() } protected open fun doResolveNonStatic(): Collection<GroovyResolveResult> { val expression = element val name = expression.referenceName ?: return emptyList() val kinds = expression.resolveKinds() val processor = buildProcessor(name, expression, kinds) GrReferenceResolveRunner(expression, processor).resolveReferenceExpression() return processor.results } protected abstract fun buildProcessor(name: String, place: PsiElement, kinds: Set<GroovyResolveKind>): GrResolverProcessor<*> } class GrRValueExpressionReference(ref: GrReferenceExpressionImpl) : GrReferenceExpressionReference(ref) { override fun doResolveNonStatic(): Collection<GroovyResolveResult> { return element.handleSpecialCases() ?: super.doResolveNonStatic() } override fun buildProcessor(name: String, place: PsiElement, kinds: Set<GroovyResolveKind>): GrResolverProcessor<*> { return rValueProcessor(name, place, kinds) } } class GrLValueExpressionReference(ref: GrReferenceExpressionImpl) : GrReferenceExpressionReference(ref) { override fun buildProcessor(name: String, place: PsiElement, kinds: Set<GroovyResolveKind>): GrResolverProcessor<*> { val rValue = requireNotNull(element.getRValue()) return lValueProcessor(name, place, kinds, rValue) } } private fun GrReferenceExpression.handleSpecialCases(): Collection<GroovyResolveResult>? { when (referenceNameElement?.node?.elementType) { GroovyElementTypes.KW_THIS -> return resolveThisExpression(this) GroovyElementTypes.KW_SUPER -> return resolveSuperExpression(this) GroovyElementTypes.KW_CLASS -> { if (!PsiUtil.isCompileStatic(this) && qualifier?.type == null) { return emptyList() } } } return null } fun GrReferenceExpression.resolveKinds(): Set<GroovyResolveKind> { return resolveKinds(isQualified) } fun resolveKinds(qualified: Boolean): Set<GroovyResolveKind> { return if (qualified) { EnumSet.of(FIELD, PROPERTY, VARIABLE) } else { EnumSet.of(FIELD, PROPERTY, VARIABLE, BINDING) } } fun rValueProcessor(name: String, place: PsiElement, kinds: Set<GroovyResolveKind>): GrResolverProcessor<*> { val accessorProcessors = if (name.isPropertyName()) listOf( AccessorProcessor(name, PropertyKind.GETTER, emptyList(), place), AccessorProcessor(name, PropertyKind.BOOLEAN_GETTER, emptyList(), place) ) else { emptyList() } return AccessorAwareProcessor(name, place, kinds, accessorProcessors) } fun lValueProcessor(name: String, place: PsiElement, kinds: Set<GroovyResolveKind>, argument: Argument?): GrResolverProcessor<*> { val accessorProcessors = if (name.isPropertyName()) { listOf(AccessorProcessor(name, PropertyKind.SETTER, argument?.let(::listOf), place)) } else { emptyList() } return AccessorAwareProcessor(name, place, kinds, accessorProcessors) }
apache-2.0
cfbf56934f3cc4b9e3e7424978a6ad1e
42.053097
140
0.788078
4.568075
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/operatorConventions/compareTo/longInt.kt
5
301
fun checkLess(x: Long, y: Int) = when { x >= y -> "Fail $x >= $y" !(x < y) -> "Fail !($x < $y)" !(x <= y) -> "Fail !($x <= $y)" x > y -> "Fail $x > $y" x.compareTo(y) >= 0 -> "Fail $x.compareTo($y) >= 0" else -> "OK" } fun box() = checkLess(-123456789123.toLong(), 0)
apache-2.0
65319b917d753eeba2107756419271ff
29.1
55
0.415282
2.447154
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/enclosing/lambdaInLambda.kt
2
687
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT fun box(): String { val l = { {} } val javaClass = l().javaClass val enclosingMethod = javaClass.getEnclosingMethod() if (enclosingMethod?.getName() != "invoke") return "method: $enclosingMethod" val enclosingClass = javaClass.getEnclosingClass()!!.getName() if (enclosingClass != "LambdaInLambdaKt\$box\$l\$1") return "enclosing class: $enclosingClass" val declaringClass = javaClass.getDeclaringClass() if (declaringClass != null) return "anonymous function has a declaring class: $declaringClass" return "OK" }
apache-2.0
ed5b91af4e756d53048fa58716d24275
30.227273
98
0.691412
4.549669
false
false
false
false
smmribeiro/intellij-community
python/python-terminal/src/com/jetbrains/python/sdk/PyVirtualEnvTerminalCustomizer.kt
1
4265
// 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.jetbrains.python.sdk import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.options.UnnamedConfigurable import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.util.SystemInfo import com.jetbrains.python.run.findActivateScript import org.jetbrains.plugins.terminal.LocalTerminalCustomizer import org.jetbrains.plugins.terminal.TerminalOptionsProvider import java.io.File import javax.swing.JCheckBox class PyVirtualEnvTerminalCustomizer : LocalTerminalCustomizer() { override fun customizeCommandAndEnvironment(project: Project, command: Array<out String>, envs: MutableMap<String, String>): Array<out String> { val sdk: Sdk? = findSdk(project) if (sdk != null && (PythonSdkUtil.isVirtualEnv(sdk) || PythonSdkUtil.isConda(sdk)) && PyVirtualEnvTerminalSettings.getInstance(project).virtualEnvActivate) { // in case of virtualenv sdk on unix we activate virtualenv val path = sdk.homePath if (path != null && command.isNotEmpty()) { val shellPath = command[0] if (isShellIntegrationAvailable(shellPath)) { //fish shell works only for virtualenv and not for conda //for bash we pass activate script to jediterm shell integration (see jediterm-bash.in) to source it there //TODO: fix conda for fish findActivateScript(path, shellPath)?.let { activate -> envs.put("JEDITERM_SOURCE", activate.first) envs.put("JEDITERM_SOURCE_ARGS", activate.second?:"") } } else { //for other shells we read envs from activate script by the default shell and pass them to the process envs.putAll(PySdkUtil.activateVirtualEnv(sdk)) } } } return command } private fun isShellIntegrationAvailable(shellPath: String) : Boolean { if (TerminalOptionsProvider.instance.shellIntegration) { val shellName = File(shellPath).name return shellName == "bash" || (SystemInfo.isMac && shellName == "sh") || shellName == "zsh" || shellName == "fish" } return false } private fun findSdk(project: Project): Sdk? { for (m in ModuleManager.getInstance(project).modules) { val sdk: Sdk? = PythonSdkUtil.findPythonSdk(m) if (sdk != null && !PythonSdkUtil.isRemote(sdk)) { return sdk } } return null } override fun getDefaultFolder(project: Project): String? { return null } override fun getConfigurable(project: Project): UnnamedConfigurable = object : UnnamedConfigurable { val settings = PyVirtualEnvTerminalSettings.getInstance(project) var myCheckbox: JCheckBox = JCheckBox(PyTerminalBundle.message("activate.virtualenv.checkbox.text")) override fun createComponent() = myCheckbox override fun isModified() = myCheckbox.isSelected != settings.virtualEnvActivate override fun apply() { settings.virtualEnvActivate = myCheckbox.isSelected } override fun reset() { myCheckbox.isSelected = settings.virtualEnvActivate } } } class SettingsState { var virtualEnvActivate: Boolean = true } @State(name = "PyVirtualEnvTerminalCustomizer", storages = [(Storage("python-terminal.xml"))]) class PyVirtualEnvTerminalSettings : PersistentStateComponent<SettingsState> { var myState: SettingsState = SettingsState() var virtualEnvActivate: Boolean get() = myState.virtualEnvActivate set(value) { myState.virtualEnvActivate = value } override fun getState(): SettingsState = myState override fun loadState(state: SettingsState) { myState.virtualEnvActivate = state.virtualEnvActivate } companion object { fun getInstance(project: Project): PyVirtualEnvTerminalSettings { return project.getService(PyVirtualEnvTerminalSettings::class.java) } } }
apache-2.0
2bd1d486b05b15a28cc088826cc3e3e9
33.674797
140
0.709027
4.84109
false
false
false
false
PhilippHeuer/twitch4j
kotlin/src/test/kotlin/com/github/twitch4j/kotlin/mock/MockChat.kt
1
1266
package com.github.twitch4j.kotlin.mock import com.github.philippheuer.events4j.core.EventManager import com.github.twitch4j.chat.TwitchChat import com.github.twitch4j.chat.util.TwitchChatLimitHelper import com.github.twitch4j.common.util.ThreadUtils /** * The bare minimum we need to test the TwitchChat extensions */ class MockChat : TwitchChat( null, EventManager().apply { autoDiscovery() }, null, null, FDGT_TEST_SOCKET_SERVER, false, emptyList(), 1, null, null, null, null, ThreadUtils.getDefaultScheduledThreadPoolExecutor("MOCK", 1), 1, null, false, false, null, false, 100, 1, 0, null, TwitchChatLimitHelper.MOD_MESSAGE_LIMIT ) { @Volatile var isConnected = false override fun connect() { isConnected = true } override fun disconnect() { isConnected = false } override fun joinChannel(channelName: String) { val lowerChannelName = channelName.lowercase() currentChannels.add(lowerChannelName) } override fun leaveChannel(channelName: String): Boolean { val lowerChannelName = channelName.lowercase() currentChannels.remove(lowerChannelName) return true } }
mit
68364860a6f41b6b7c9874706f51ab58
20.827586
65
0.669036
4.097087
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/gui/canvas/GridLines.kt
1
796
package com.cout970.modeler.gui.canvas import com.cout970.modeler.gui.Gui import com.cout970.vector.api.IVector3 import com.cout970.vector.extensions.Vector3 import com.cout970.vector.extensions.vec3Of class GridLines { lateinit var gui: Gui var gridOffset: IVector3 = Vector3.ZERO set(value) { field = value; onChange() } var gridSize: IVector3 = vec3Of(16 * 5) set(value) { field = value; onChange() } var enableXPlane = false set(value) { field = value; onChange() } var enableYPlane = true set(value) { field = value; onChange() } var enableZPlane = false set(value) { field = value; onChange() } private fun onChange() { gui.state.gridLinesHash = (System.currentTimeMillis() and 0xFFFFFFFF).toInt() } }
gpl-3.0
1b1d72d2fda6fe00c93e990d503a2b1b
25.566667
85
0.668342
3.634703
false
false
false
false
Flank/flank
test_runner/src/main/kotlin/ftl/args/yml/errors/ConfigurationErrorMessageBuilder.kt
1
2607
@file:Suppress("DEPRECATION") package ftl.args.yml.errors import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.dataformat.yaml.snakeyaml.error.MarkedYAMLException import java.lang.Exception object ConfigurationErrorMessageBuilder { private val parseMessage = ConfigurationErrorParser private val resolveErrorNode = ErrorNodeResolver //region error message elements private const val messageHeader = "Error on parse config: " private const val missingElementMessage = "Missing element or value for: '%s'" private const val atMessage = "At line: %s, column: %s" private const val errorNodeMessage = "Error node: %s" //endregion private const val exceptionTemplate = "Parse message error: %s" operator fun invoke(errorMessage: String, yamlTreeNode: JsonNode? = null) = try { val errorModel = parseMessage(errorMessage) val errorMessageBuilder = StringBuilder(messageHeader) errorMessageBuilder.appendLine(createReferenceChain(errorModel.referenceChain)) if (errorModel.propertyName != "") { errorMessageBuilder.appendLine(missingElementMessage.format(errorModel.propertyName)) } errorMessageBuilder.appendLine(atMessage.format(errorModel.line, errorModel.column)) yamlTreeNode?.let { errorMessageBuilder.appendLine(errorNodeMessage.format(resolveErrorNode(yamlTreeNode, errorModel))) } errorMessageBuilder.toString().trim() } catch (error: Exception) { exceptionTemplate.format(errorMessage) } operator fun invoke(yamlException: MarkedYAMLException): String { val problemMark = yamlException.problemMark return StringBuilder(messageHeader + yamlException.problem).apply { appendLine() appendLine(atMessage.format(problemMark.line, problemMark.column)) appendLine(errorNodeMessage.format(System.lineSeparator() + problemMark._snippet)) }.toString().trim() } private fun createReferenceChain(referenceChain: List<String>): String { val chainBuilder = StringBuilder() referenceChain.forEachIndexed { index, chainPart -> chainBuilder.append(appendChainElement(chainPart, index > 0)) } return chainBuilder.toString() } private fun appendChainElement(chainPart: String, withSeparator: Boolean): String = when { chainPart.toIntOrNull() != null -> "[$chainPart]" withSeparator -> "->$chainPart" else -> chainPart } }
apache-2.0
e36e6b6080a1643a82bf3c82686e70ee
41.048387
115
0.694668
4.872897
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertCollectionConstructorToFunction.kt
1
2329
// 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.intentions import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe class ConvertCollectionConstructorToFunction : SelfTargetingIntention<KtCallExpression>( KtCallExpression::class.java, KotlinBundle.lazyMessage("convert.collection.constructor.to.function") ) { @SafeFieldForPreview private val functionMap = hashMapOf( "java.util.ArrayList.<init>" to "arrayListOf", "kotlin.collections.ArrayList.<init>" to "arrayListOf", "java.util.HashMap.<init>" to "hashMapOf", "kotlin.collections.HashMap.<init>" to "hashMapOf", "java.util.HashSet.<init>" to "hashSetOf", "kotlin.collections.HashSet.<init>" to "hashSetOf", "java.util.LinkedHashMap.<init>" to "linkedMapOf", "kotlin.collections.LinkedHashMap.<init>" to "linkedMapOf", "java.util.LinkedHashSet.<init>" to "linkedSetOf", "kotlin.collections.LinkedHashSet.<init>" to "linkedSetOf" ) override fun isApplicableTo(element: KtCallExpression, caretOffset: Int): Boolean { val fq = element.resolveToCall()?.resultingDescriptor?.fqNameSafe?.asString() ?: return false return functionMap.containsKey(fq) && element.valueArguments.size == 0 } override fun applyTo(element: KtCallExpression, editor: Editor?) { val fq = element.resolveToCall()?.resultingDescriptor?.fqNameSafe?.asString() ?: return val toCall = functionMap[fq] ?: return val callee = element.calleeExpression ?: return callee.replace(KtPsiFactory(element).createExpression(toCall)) element.getQualifiedExpressionForSelector()?.replace(element) } }
apache-2.0
bc6f364ce0cfec027a68c2746d6e13e2
50.755556
158
0.752254
4.73374
false
false
false
false
550609334/Twobbble
app/src/main/java/com/twobbble/view/fragment/BaseFragment.kt
1
1437
package com.twobbble.view.fragment import android.app.Activity import android.app.ActivityOptions import android.app.Fragment import android.content.Intent import android.os.Bundle import android.speech.RecognizerIntent import android.view.KeyEvent import com.twobbble.tools.Constant import com.twobbble.tools.QuickSimpleIO import com.twobbble.view.activity.DetailsActivity import kotlinx.android.synthetic.main.item_shots.* import kotlinx.android.synthetic.main.search_layout.* /** * Created by liuzipeng on 2017/2/22. */ abstract class BaseFragment : Fragment() { var isShowSearchBar: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } open fun onBackPressed() {} open fun onKeyDown(keyCode: Int, event: KeyEvent?) { } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == Constant.VOICE_CODE && resultCode == Activity.RESULT_OK) { val keywords = data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS) keywords?.forEach { mSearchEdit.setText(it) } } super.onActivityResult(requestCode, resultCode, data) } fun startDetailsActivity() { startActivity(Intent(activity, DetailsActivity::class.java), ActivityOptions.makeSceneTransitionAnimation(activity).toBundle()) } }
apache-2.0
7c7a3162d466644d1306d70d5c943b3e
28.958333
88
0.720251
4.605769
false
false
false
false
siosio/intellij-community
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/NewProjectWizardModuleBuilder.kt
1
12668
// 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.tools.projectWizard.wizard import com.intellij.ide.RecentProjectsManager import com.intellij.ide.actions.NewProjectAction import com.intellij.ide.util.projectWizard.* import com.intellij.ide.wizard.AbstractWizard import com.intellij.openapi.Disposable import com.intellij.openapi.module.ModifiableModuleModel import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.ModuleType import com.intellij.openapi.options.ConfigurationException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.ex.JavaSdkUtil import com.intellij.openapi.roots.ui.configuration.ModulesProvider import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Disposer import com.intellij.util.SystemProperties import org.jetbrains.kotlin.idea.framework.KotlinTemplatesFactory import org.jetbrains.kotlin.idea.projectWizard.WizardStatsService import org.jetbrains.kotlin.idea.projectWizard.WizardStatsService.ProjectCreationStats import org.jetbrains.kotlin.idea.projectWizard.WizardStatsService.UiEditorUsageStats import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.tools.projectWizard.core.buildList import org.jetbrains.kotlin.tools.projectWizard.core.div import org.jetbrains.kotlin.tools.projectWizard.core.entity.StringValidators import org.jetbrains.kotlin.tools.projectWizard.core.entity.ValidationResult import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference import org.jetbrains.kotlin.tools.projectWizard.core.isSuccess import org.jetbrains.kotlin.tools.projectWizard.core.onFailure import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase import org.jetbrains.kotlin.tools.projectWizard.plugins.Plugins import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin import org.jetbrains.kotlin.tools.projectWizard.projectTemplates.ProjectTemplate import org.jetbrains.kotlin.tools.projectWizard.wizard.service.IdeaJpsWizardService import org.jetbrains.kotlin.tools.projectWizard.wizard.service.IdeaServices import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.asHtml import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.firstStep.FirstWizardStepComponent import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.runWithProgressBar import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.secondStep.SecondStepWizardComponent import java.io.File import javax.swing.JButton import javax.swing.JComponent import com.intellij.openapi.module.Module as IdeaModule /* Have to override EmptyModuleBuilder here instead of just ModuleBuilder As EmptyModuleBuilder has not expert panel option which are redundant */ class NewProjectWizardModuleBuilder : EmptyModuleBuilder() { val wizard = IdeWizard(Plugins.allPlugins, IdeaServices.PROJECT_INDEPENDENT, isUnitTestMode = false) private val uiEditorUsagesStats = UiEditorUsageStats() override fun isOpenProjectSettingsAfter(): Boolean = false override fun canCreateModule(): Boolean = false override fun getPresentableName(): String = moduleType.name override fun getDescription(): String? = moduleType.description override fun getGroupName(): String? = moduleType.name override fun isTemplateBased(): Boolean = false companion object { const val MODULE_BUILDER_ID = "kotlin.newProjectWizard.builder" private val projectNameValidator = StringValidators.shouldBeValidIdentifier("Project name", setOf('-', '_')) private const val INVALID_PROJECT_NAME_MESSAGE = "Invalid project name" } override fun isAvailable(): Boolean = isCreatingNewProject() private var wizardContext: WizardContext? = null private var finishButtonClicked: Boolean = false override fun getModuleType(): ModuleType<*> = NewProjectWizardModuleType() override fun getParentGroup(): String = KotlinTemplatesFactory.KOTLIN_PARENT_GROUP_NAME override fun createWizardSteps( wizardContext: WizardContext, modulesProvider: ModulesProvider ): Array<ModuleWizardStep> { this.wizardContext = wizardContext val disposable = wizardContext.disposable return arrayOf(ModuleNewWizardSecondStep(wizard, uiEditorUsagesStats, wizardContext, disposable)) } override fun commit( project: Project, model: ModifiableModuleModel?, modulesProvider: ModulesProvider? ): List<IdeaModule>? { runWriteAction { wizard.jdk?.let { jdk -> JavaSdkUtil.applyJdkToProject(project, jdk) } } val modulesModel = model ?: ModuleManager.getInstance(project).modifiableModel val success = wizard.apply( services = buildList { +IdeaServices.createScopeDependent(project) +IdeaServices.PROJECT_INDEPENDENT +IdeaJpsWizardService(project, modulesModel, this@NewProjectWizardModuleBuilder, wizard) }, phases = GenerationPhase.startingFrom(GenerationPhase.FIRST_STEP) ).onFailure { errors -> val errorMessages = errors.joinToString(separator = "\n") { it.message } Messages.showErrorDialog(project, errorMessages, KotlinNewProjectWizardUIBundle.message("error.generation")) }.isSuccess if (success) { logToFUS(project) } return when { !success -> null wizard.buildSystemType == BuildSystemType.Jps -> runWriteAction { modulesModel.modules.toList().onEach { setupModule(it) } } else -> emptyList() } } private fun logToFUS(project: Project?) { val modules = wizard.context.read { KotlinPlugin.modules.reference.settingValue } val projectCreationStats = ProjectCreationStats( KotlinTemplatesFactory.KOTLIN_GROUP_NAME, wizard.projectTemplate!!.id, wizard.buildSystemType!!.id, modules.map { it.configurator.id }, ) WizardStatsService.logDataOnProjectGenerated( wizard.context.contextComponents.get(), project, projectCreationStats, uiEditorUsagesStats ) val moduleTemplates = modules.map { module -> module.template?.id ?: "none" } WizardStatsService.logUsedModuleTemplatesOnNewWizardProjectCreated( wizard.context.contextComponents.get(), project, wizard.projectTemplate!!.id, moduleTemplates, ) } private fun clickFinishButton() { if (finishButtonClicked) return finishButtonClicked = true wizardContext?.getNextButton()?.doClick() } override fun modifySettingsStep(settingsStep: SettingsStep): ModuleWizardStep? { settingsStep.moduleNameLocationSettings?.apply { moduleName = wizard.projectName!! moduleContentRoot = wizard.projectPath!!.toString() } clickFinishButton() return null } override fun validateModuleName(moduleName: String): Boolean { when (val validationResult = wizard.context.read { projectNameValidator.validate(this, moduleName) }) { ValidationResult.OK -> return true is ValidationResult.ValidationError -> { val message = validationResult.messages.firstOrNull() ?: INVALID_PROJECT_NAME_MESSAGE throw ConfigurationException(message, INVALID_PROJECT_NAME_MESSAGE) } } } internal fun selectProjectTemplate(template: ProjectTemplate) { wizard.buildSystemType = BuildSystemType.GradleKotlinDsl wizard.projectTemplate = template } override fun getCustomOptionsStep(context: WizardContext?, parentDisposable: Disposable) = ModuleNewWizardFirstStep(wizard, parentDisposable) } abstract class WizardStep(protected val wizard: IdeWizard, private val phase: GenerationPhase) : ModuleWizardStep() { override fun getHelpId(): String = HELP_ID override fun updateDataModel() = Unit // model is updated on every UI action override fun validate(): Boolean = when (val result = wizard.context.read { with(wizard) { validate(setOf(phase)) } }) { ValidationResult.OK -> true is ValidationResult.ValidationError -> { handleErrors(result) false } } protected open fun handleErrors(error: ValidationResult.ValidationError) { throw ConfigurationException(error.asHtml(), "Validation Error") } companion object { private const val HELP_ID = "new_project_wizard_kotlin" } } class ModuleNewWizardFirstStep(wizard: IdeWizard, disposable: Disposable) : WizardStep(wizard, GenerationPhase.FIRST_STEP) { private val component = FirstWizardStepComponent(wizard) override fun getComponent(): JComponent = component.component init { runPreparePhase() initDefaultValues() component.onInit() Disposer.register(disposable, component) } private fun runPreparePhase() = runWithProgressBar(title = "") { wizard.apply(emptyList(), setOf(GenerationPhase.PREPARE)) { task -> ProgressManager.getInstance().progressIndicator.text = task.title ?: "" } } override fun handleErrors(error: ValidationResult.ValidationError) { component.navigateTo(error) } private fun initDefaultValues() { val suggestedProjectParentLocation = RecentProjectsManager.getInstance().suggestNewProjectLocation() val suggestedProjectName = ProjectWizardUtil.findNonExistingFileName(suggestedProjectParentLocation, "untitled", "") wizard.context.writeSettings { StructurePlugin.name.reference.setValue(suggestedProjectName) StructurePlugin.projectPath.reference.setValue(suggestedProjectParentLocation / suggestedProjectName) StructurePlugin.artifactId.reference.setValue(suggestedProjectName) if (StructurePlugin.groupId.notRequiredSettingValue == null) { StructurePlugin.groupId.reference.setValue(suggestGroupId()) } } } private fun suggestGroupId(): String { val username = SystemProperties.getUserName() ?: return DEFAULT_GROUP_ID if (!username.matches("[\\w\\s]+".toRegex())) return DEFAULT_GROUP_ID val usernameAsGroupId = username.trim().toLowerCase().split("\\s+".toRegex()).joinToString(separator = ".") return "me.$usernameAsGroupId" } companion object { private const val DEFAULT_GROUP_ID = "me.user" } } class ModuleNewWizardSecondStep( wizard: IdeWizard, uiEditorUsagesStats: UiEditorUsageStats, private val wizardContext: WizardContext, disposable: Disposable ) : WizardStep(wizard, GenerationPhase.SECOND_STEP) { private val component = SecondStepWizardComponent(wizard, uiEditorUsagesStats) override fun getComponent(): JComponent = component.component init { Disposer.register(disposable, component) } override fun _init() { component.onInit() WizardStatsService.logDataOnNextClicked(wizard.context.contextComponents.get()) } override fun onStepLeaving() { if (isNavigatingBack()) { WizardStatsService.logDataOnPrevClicked(wizard.context.contextComponents.get()) } super.onStepLeaving() } override fun getPreferredFocusedComponent(): JComponent? { wizardContext.getNextButton()?.text = "Finish" return super.getPreferredFocusedComponent() } override fun handleErrors(error: ValidationResult.ValidationError) { component.navigateTo(error) } } private fun isCreatingNewProject() = Thread.currentThread().stackTrace.any { element -> element.className == NewProjectAction::class.java.name } private fun isNavigatingBack() = Thread.currentThread().stackTrace.any { element -> element.methodName == "doPreviousAction" } private fun WizardContext.getNextButton() = try { AbstractWizard::class.java.getDeclaredMethod("getNextButton") .also { it.isAccessible = true } .invoke(wizard) as? JButton } catch (_: Throwable) { null }
apache-2.0
f388b2900376b0038966d1df4ac3f30a
41.086379
158
0.723555
5.061127
false
false
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/service/FloatingNoteService.kt
1
5208
package com.maubis.scarlet.base.service import android.app.Activity import android.content.Intent import android.content.Intent.FLAG_ACTIVITY_NEW_TASK import android.view.Gravity import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.core.content.ContextCompat import com.bsk.floatingbubblelib.FloatingBubbleConfig import com.bsk.floatingbubblelib.FloatingBubblePermissions import com.bsk.floatingbubblelib.FloatingBubbleService import com.maubis.markdown.Markdown import com.maubis.scarlet.base.R import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTheme import com.maubis.scarlet.base.config.CoreConfig.Companion.notesDb import com.maubis.scarlet.base.core.note.NoteBuilder import com.maubis.scarlet.base.database.room.note.Note import com.maubis.scarlet.base.note.copy import com.maubis.scarlet.base.note.creation.activity.CreateNoteActivity import com.maubis.scarlet.base.note.creation.activity.INTENT_KEY_NOTE_ID import com.maubis.scarlet.base.note.getDisplayTime import com.maubis.scarlet.base.note.getFullTextForDirectMarkdownRender import com.maubis.scarlet.base.note.getTextForSharing import com.maubis.scarlet.base.note.getTitleForSharing import com.maubis.scarlet.base.support.ui.ThemeColorType import com.maubis.scarlet.base.support.utils.maybeThrow /** * The floating not service * Created by bijoy on 3/29/17. */ class FloatingNoteService : FloatingBubbleService() { private var note: Note? = null private lateinit var description: TextView private lateinit var timestamp: TextView private lateinit var panel: View override fun getConfig(): FloatingBubbleConfig { return FloatingBubbleConfig.Builder() .bubbleIcon(ContextCompat.getDrawable(context, R.drawable.app_icon)) .removeBubbleIcon( ContextCompat.getDrawable( context, com.bsk.floatingbubblelib.R.drawable.close_default_icon)) .bubbleIconDp(72) .removeBubbleIconDp(72) .paddingDp(8) .borderRadiusDp(4) .physicsEnabled(true) .expandableColor(sAppTheme.get(ThemeColorType.BACKGROUND)) .triangleColor(sAppTheme.get(ThemeColorType.BACKGROUND)) .gravity(Gravity.END) .expandableView(loadView()) .removeBubbleAlpha(0.7f) .build() } override fun onGetIntent(intent: Intent): Boolean { note = null if (intent.hasExtra(INTENT_KEY_NOTE_ID)) { note = notesDb.getByID(intent.getIntExtra(INTENT_KEY_NOTE_ID, 0)) } return note != null } private fun loadView(): View { if (note == null) { note = NoteBuilder().emptyNote() stopSelf() } val rootView = getInflater().inflate(R.layout.layout_add_note_overlay, null) description = rootView.findViewById<View>(R.id.description) as TextView timestamp = rootView.findViewById<View>(R.id.timestamp) as TextView description.setTextColor(sAppTheme.get(ThemeColorType.SECONDARY_TEXT)) val noteItem = note!! val editButton = rootView.findViewById<View>(R.id.panel_edit_button) as ImageView editButton.setImageResource(R.drawable.ic_edit_white_48dp) editButton.setOnClickListener { try { val intent = Intent(context, CreateNoteActivity::class.java) intent.putExtra(INTENT_KEY_NOTE_ID, noteItem.uid) intent.addFlags(FLAG_ACTIVITY_NEW_TASK) context.startActivity(intent) } catch (exception: Exception) { maybeThrow(exception) } stopSelf() } val shareButton = rootView.findViewById<View>(R.id.panel_share_button) as ImageView shareButton.setImageResource(R.drawable.ic_share_white_48dp) shareButton.setOnClickListener { getShareIntent(noteItem) stopSelf() } val copyButton = rootView.findViewById<View>(R.id.panel_copy_button) as ImageView copyButton.visibility = View.VISIBLE copyButton.setOnClickListener { noteItem.copy(context) setState(false) } panel = rootView.findViewById(R.id.panel_layout) panel.setBackgroundColor(sAppTheme.get(ThemeColorType.BACKGROUND)) setNote(noteItem) return rootView } fun getShareIntent(note: Note) { val sharingIntent = Intent(Intent.ACTION_SEND) sharingIntent.type = "text/plain" sharingIntent.putExtra(Intent.EXTRA_SUBJECT, note.getTitleForSharing()) sharingIntent.putExtra(Intent.EXTRA_TEXT, note.getTextForSharing()) sharingIntent.addFlags(FLAG_ACTIVITY_NEW_TASK) context.startActivity(sharingIntent) } fun setNote(note: Note) { val noteDescription = Markdown.render(note.getFullTextForDirectMarkdownRender(), true) description.text = noteDescription timestamp.text = note.getDisplayTime() } companion object { fun openNote(activity: Activity, note: Note?, finishOnOpen: Boolean) { if (FloatingBubblePermissions.requiresPermission(activity)) { FloatingBubblePermissions.startPermissionRequest(activity) } else { val intent = Intent(activity, FloatingNoteService::class.java) if (note != null) { intent.putExtra(INTENT_KEY_NOTE_ID, note.uid) } activity.startService(intent) if (finishOnOpen) activity.finish() } } } }
gpl-3.0
b95576cb9404ffe986677b92ca55f59b
33.95302
90
0.740783
3.990805
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinParameterProcessor.kt
4
3047
// 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.rename import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.search.SearchScope import com.intellij.refactoring.listeners.RefactoringElementListener import com.intellij.usageView.UsageInfo import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import org.jetbrains.kotlin.idea.search.or import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.utils.SmartList class RenameKotlinParameterProcessor : RenameKotlinPsiProcessor() { override fun canProcessElement(element: PsiElement) = element is KtParameter && element.ownerFunction is KtFunction override fun isToSearchInComments(psiElement: PsiElement) = KotlinRefactoringSettings.instance.RENAME_SEARCH_IN_COMMENTS_FOR_VARIABLE override fun setToSearchInComments(element: PsiElement, enabled: Boolean) { KotlinRefactoringSettings.instance.RENAME_SEARCH_IN_COMMENTS_FOR_VARIABLE = enabled } override fun findCollisions( element: PsiElement, newName: String, allRenames: MutableMap<out PsiElement, String>, result: MutableList<UsageInfo> ) { val declaration = element.namedUnwrappedElement as? KtNamedDeclaration ?: return val collisions = SmartList<UsageInfo>() checkRedeclarations(declaration, newName, collisions) checkOriginalUsagesRetargeting(declaration, newName, result, collisions) checkNewNameUsagesRetargeting(declaration, newName, collisions) result += collisions } override fun findReferences( element: PsiElement, searchScope: SearchScope, searchInCommentsAndStrings: Boolean ): Collection<PsiReference> { if (element !is KtParameter) return super.findReferences(element, searchScope, searchInCommentsAndStrings) val ownerFunction = element.ownerFunction ?: return super.findReferences(element, searchScope, searchInCommentsAndStrings) val newScope = searchScope or ownerFunction.useScope return super.findReferences(element, newScope, searchInCommentsAndStrings) } override fun renameElement(element: PsiElement, newName: String, usages: Array<UsageInfo>, listener: RefactoringElementListener?) { super.renameElement(element, newName, usages, listener) usages.forEach { (it as? KtResolvableCollisionUsageInfo)?.apply() } } override fun prepareRenaming(element: PsiElement, newName: String, allRenames: MutableMap<PsiElement, String>, scope: SearchScope) { super.prepareRenaming(element, newName, allRenames, scope) ForeignUsagesRenameProcessor.prepareRenaming(element, newName, allRenames, scope) } }
apache-2.0
e56f5efe6759c79367a33fcc0d139a2d
46.609375
158
0.770594
5.208547
false
false
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/ir/interop/cenum/CEnumByValueFunctionGenerator.kt
1
5282
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin.backend.konan.ir.interop.cenum import org.jetbrains.kotlin.backend.konan.ir.KonanSymbols import org.jetbrains.kotlin.backend.konan.ir.interop.DescriptorToIrTranslationMixin import org.jetbrains.kotlin.backend.konan.ir.interop.findDeclarationByName import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.ir.builders.* import org.jetbrains.kotlin.ir.declarations.IrClass import org.jetbrains.kotlin.ir.declarations.IrFunction import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns import org.jetbrains.kotlin.ir.expressions.impl.IrCallImpl import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol import org.jetbrains.kotlin.ir.types.classOrNull import org.jetbrains.kotlin.ir.types.getClass import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.ir.util.irCall import org.jetbrains.kotlin.psi2ir.generators.GeneratorContext import org.jetbrains.kotlin.util.OperatorNameConventions /** * Generate IR for function that returns appropriate enum entry for the provided integral value. */ internal class CEnumByValueFunctionGenerator( context: GeneratorContext, private val symbols: KonanSymbols ) : DescriptorToIrTranslationMixin { override val irBuiltIns: IrBuiltIns = context.irBuiltIns override val symbolTable: SymbolTable = context.symbolTable override val typeTranslator: TypeTranslator = context.typeTranslator override val postLinkageSteps: MutableList<() -> Unit> = mutableListOf() fun generateByValueFunction( companionIrClass: IrClass, valuesIrFunctionSymbol: IrSimpleFunctionSymbol ): IrFunction { val byValueFunctionDescriptor = companionIrClass.descriptor.findDeclarationByName<FunctionDescriptor>("byValue")!! val byValueIrFunction = createFunction(byValueFunctionDescriptor) val irValueParameter = byValueIrFunction.valueParameters.first() // val values: Array<E> = values() // var i: Int = 0 // val size: Int = values.size // while (i < size) { // val entry: E = values[i] // if (entry.value == arg) { // return entry // } // i++ // } // throw NPE postLinkageSteps.add { byValueIrFunction.body = irBuilder(irBuiltIns, byValueIrFunction.symbol, SYNTHETIC_OFFSET, SYNTHETIC_OFFSET).irBlockBody { +irReturn(irBlock { val values = irTemporary(irCall(valuesIrFunctionSymbol), isMutable = true) val inductionVariable = irTemporary(irInt(0), isMutable = true) val arrayClass = values.type.classOrNull!! val valuesSize = irCall(symbols.arraySize.getValue(arrayClass), irBuiltIns.intType).also { irCall -> irCall.dispatchReceiver = irGet(values) } val getElementFn = symbols.arrayGet.getValue(arrayClass) val plusFun = symbols.getBinaryOperator(OperatorNameConventions.PLUS, irBuiltIns.intType, irBuiltIns.intType) val lessFunctionSymbol = irBuiltIns.lessFunByOperandType.getValue(irBuiltIns.intClass) +irWhile().also { loop -> loop.condition = irCall(lessFunctionSymbol, irBuiltIns.booleanType).also { irCall -> irCall.putValueArgument(0, irGet(inductionVariable)) irCall.putValueArgument(1, valuesSize) } loop.body = irBlock { val entry = irTemporary(irCall(getElementFn, byValueIrFunction.returnType).also { irCall -> irCall.dispatchReceiver = irGet(values) irCall.putValueArgument(0, irGet(inductionVariable)) }, isMutable = true) val valueGetter = entry.type.getClass()!!.getPropertyGetter("value")!! val entryValue = irGet(irValueParameter.type, irGet(entry), valueGetter) +irIfThenElse( type = irBuiltIns.unitType, condition = irEquals(entryValue, irGet(irValueParameter)), thenPart = irReturn(irGet(entry)), elsePart = irSetVar( inductionVariable, irCallOp(plusFun, irBuiltIns.intType, irGet(inductionVariable), irInt(1) ) ) ) } } +IrCallImpl.fromSymbolOwner(startOffset, endOffset, irBuiltIns.nothingType, symbols.throwNullPointerException) }) } } return byValueIrFunction } }
apache-2.0
af34554723514751f611be5fbc61558c
51.83
134
0.600719
5.209073
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/subscription/donate/card/CreditCardTextWatcher.kt
1
2543
package org.thoughtcrime.securesms.components.settings.app.subscription.donate.card import android.text.Editable import android.text.TextWatcher /** * Formats a credit card by type as the user modifies it. */ class CreditCardTextWatcher : TextWatcher { private var isBackspace: Boolean = false override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { isBackspace = count == 0 } override fun afterTextChanged(s: Editable) { val userInput = s.toString() val normalizedNumber = userInput.filter { it != ' ' } val formattedNumber = when (CreditCardType.fromCardNumber(normalizedNumber)) { CreditCardType.AMERICAN_EXPRESS -> applyAmexFormatting(normalizedNumber) CreditCardType.UNIONPAY -> applyUnionPayFormatting(normalizedNumber) CreditCardType.OTHER -> applyOtherFormatting(normalizedNumber) } val backspaceHandled = if (isBackspace && formattedNumber.endsWith(' ') && formattedNumber.length > userInput.length) { formattedNumber.dropLast(2) } else { formattedNumber } if (userInput != backspaceHandled) { s.replace(0, s.length, backspaceHandled) } } private fun applyAmexFormatting(normalizedNumber: String): String { return applyGrouping(normalizedNumber, listOf(4, 6, 5)) } private fun applyUnionPayFormatting(normalizedNumber: String): String { return when { normalizedNumber.length <= 13 -> applyGrouping(normalizedNumber, listOf(4, 4, 5)) normalizedNumber.length <= 16 -> applyGrouping(normalizedNumber, listOf(4, 4, 4, 4)) else -> applyGrouping(normalizedNumber, listOf(5, 5, 5, 4)) } } private fun applyOtherFormatting(normalizedNumber: String): String { return if (normalizedNumber.length <= 16) { applyGrouping(normalizedNumber, listOf(4, 4, 4, 4)) } else { applyGrouping(normalizedNumber, listOf(5, 5, 5, 4)) } } private fun applyGrouping(normalizedNumber: String, groups: List<Int>): String { val maxCardLength = groups.sum() return groups.fold(0 to emptyList<String>()) { acc, limit -> val offset = acc.first val section = normalizedNumber.drop(offset).take(limit) val segment = if (limit == section.length && offset + limit != maxCardLength) { "$section " } else { section } (offset + limit) to acc.second + segment }.second.filter { it.isNotEmpty() }.joinToString("") } }
gpl-3.0
971e86e72ff89fcfaab81499f4de9f57
32.906667
123
0.692882
4.259631
false
false
false
false
androidx/androidx
compose/foundation/foundation/samples/src/main/java/androidx/compose/foundation/samples/ScrollerSamples.kt
3
4826
/* * Copyright 2019 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.samples import androidx.annotation.Sampled import androidx.compose.foundation.gestures.scrollBy import androidx.compose.foundation.gestures.animateScrollBy import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.TileMode import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch private val colors = listOf( Color(0xFFffd7d7.toInt()), Color(0xFFffe9d6.toInt()), Color(0xFFfffbd0.toInt()), Color(0xFFe3ffd9.toInt()), Color(0xFFd0fff8.toInt()) ) @Sampled @Composable fun HorizontalScrollSample() { val scrollState = rememberScrollState() val gradient = Brush.horizontalGradient( listOf(Color.Red, Color.Blue, Color.Green), 0.0f, 10000.0f, TileMode.Repeated ) Box( Modifier .horizontalScroll(scrollState) .size(width = 10000.dp, height = 200.dp) .background(brush = gradient) ) } @Sampled @Composable fun VerticalScrollExample() { val scrollState = rememberScrollState() val gradient = Brush.verticalGradient( listOf(Color.Red, Color.Blue, Color.Green), 0.0f, 10000.0f, TileMode.Repeated ) Box( Modifier .verticalScroll(scrollState) .fillMaxWidth() .requiredHeight(10000.dp) .background(brush = gradient) ) } @Sampled @Composable fun ControlledScrollableRowSample() { // Create ScrollState to own it and be able to control scroll behaviour of scrollable Row below val scrollState = rememberScrollState() val scope = rememberCoroutineScope() Column { Row(Modifier.horizontalScroll(scrollState)) { repeat(1000) { index -> Square(index) } } // Controls for scrolling Row(verticalAlignment = Alignment.CenterVertically) { Text("Scroll") Button( onClick = { scope.launch { scrollState.scrollTo(scrollState.value - 1000) } } ) { Text("< -") } Button( onClick = { scope.launch { scrollState.scrollBy(10000f) } } ) { Text("--- >") } } Row(verticalAlignment = Alignment.CenterVertically) { Text("Smooth Scroll") Button( onClick = { scope.launch { scrollState.animateScrollTo(scrollState.value - 1000) } } ) { Text("< -") } Button( onClick = { scope.launch { scrollState.animateScrollBy(10000f) } } ) { Text("--- >") } } } } @Composable private fun Square(index: Int) { Box( Modifier.size(75.dp, 200.dp).background(colors[index % colors.size]), contentAlignment = Alignment.Center ) { Text(index.toString()) } } @Composable private fun Button(onClick: () -> Unit, content: @Composable () -> Unit) { Box( Modifier.padding(5.dp) .size(120.dp, 60.dp) .clickable(onClick = onClick) .background(color = Color.LightGray), contentAlignment = Alignment.Center ) { content() } }
apache-2.0
caf6a7693f0afb75b425c87393b2e4db
30.542484
99
0.645255
4.574408
false
false
false
false
pokk/SSFM
app/src/main/kotlin/taiwan/no1/app/ssfm/features/chart/ChartRankChartDetailFragment.kt
1
5145
package taiwan.no1.app.ssfm.features.chart import android.os.Bundle import com.devrapid.kotlinknifer.recyclerview.WrapContentLinearLayoutManager import com.devrapid.kotlinknifer.recyclerview.itemdecorator.VerticalItemDecorator import com.hwangjr.rxbus.RxBus import com.hwangjr.rxbus.annotation.Subscribe import com.hwangjr.rxbus.annotation.Tag import org.jetbrains.anko.bundleOf import taiwan.no1.app.ssfm.R import taiwan.no1.app.ssfm.databinding.FragmentRankChartDetailBinding import taiwan.no1.app.ssfm.features.base.AdvancedFragment import taiwan.no1.app.ssfm.misc.constants.Constant import taiwan.no1.app.ssfm.misc.constants.RxBusTag.HELPER_ADD_TO_PLAYLIST import taiwan.no1.app.ssfm.misc.extension.recyclerview.DataInfo import taiwan.no1.app.ssfm.misc.extension.recyclerview.RankChartDetailAdapter import taiwan.no1.app.ssfm.misc.extension.recyclerview.firstFetch import taiwan.no1.app.ssfm.misc.extension.recyclerview.refreshAndChangeList import taiwan.no1.app.ssfm.misc.utilies.devices.helper.music.playerHelper import taiwan.no1.app.ssfm.misc.widgets.recyclerviews.adapters.BaseDataBindingAdapter import taiwan.no1.app.ssfm.models.entities.PlaylistItemEntity import taiwan.no1.app.ssfm.models.entities.v2.RankChartEntity import taiwan.no1.app.ssfm.models.usecases.AddPlaylistItemCase import javax.inject.Inject import javax.inject.Named /** * @author jieyi * @since 11/24/17 */ class ChartRankChartDetailFragment : AdvancedFragment<ChartRankChartDetailFragmentViewModel, FragmentRankChartDetailBinding>() { //region Static initialization companion object Factory { // The key name of the fragment initialization parameters. private const val ARG_PARAM_RANK_CODE: String = "param_music_rank_code" private const val ARG_PARAM_CHART_ENTITY: String = "param_music_chart_entity" /** * Use this factory method to create a new instance of this fragment using the provided parameters. * * @return A new instance of [android.app.Fragment] ChartArtistDetailFragment. */ fun newInstance(code: Int = Constant.SPECIAL_NUMBER, chartEntity: RankChartEntity? = null) = ChartRankChartDetailFragment().apply { arguments = bundleOf(ARG_PARAM_RANK_CODE to code, ARG_PARAM_CHART_ENTITY to (chartEntity ?: RankChartEntity())).apply { } } } //endregion @Inject override lateinit var viewModel: ChartRankChartDetailFragmentViewModel @field:[Inject Named("add_playlist_item")] lateinit var addPlaylistItemCase: AddPlaylistItemCase private val trackInfo by lazy { DataInfo() } private var trackRes = mutableListOf<PlaylistItemEntity>() // Get the arguments from the bundle here. private val rankCode by lazy { arguments.getInt(ARG_PARAM_RANK_CODE) } private val chartEntity: RankChartEntity? by lazy { arguments.getParcelable<RankChartEntity>(ARG_PARAM_CHART_ENTITY) } //region Fragment lifecycle override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) RxBus.get().register(this) } override fun onDestroyView() { (binding?.trackAdapter as BaseDataBindingAdapter<*, *>).detachAll() super.onDestroyView() } override fun onDestroy() { RxBus.get().unregister(this) super.onDestroy() } //endregion //region Base fragment implement override fun rendered(savedInstanceState: Bundle?) { binding?.apply { trackLayoutManager = WrapContentLinearLayoutManager(activity) trackAdapter = RankChartDetailAdapter(this@ChartRankChartDetailFragment, R.layout.item_music_type_6, trackRes) { holder, item, index -> if (null == holder.binding.avm) holder.binding.avm = RecyclerViewRankChartDetailViewModel(addPlaylistItemCase, item, index + 1) else holder.binding.avm?.setMusicItem(item, index + 1) } trackDecoration = VerticalItemDecorator(20) } // First time showing this fragment. trackInfo.firstFetch { viewModel.fetchRankChartDetail(rankCode, chartEntity) { trackRes.refreshAndChangeList(it, 0, binding?.trackAdapter as RankChartDetailAdapter, trackInfo) } } playerHelper.currentObject = this.javaClass.name } override fun provideInflateView(): Int = R.layout.fragment_rank_chart_detail //endregion /** * @param playlistItem * * @event_from [taiwan.no1.app.ssfm.features.chart.RecyclerViewRankChartDetailViewModel.trackOnClick] */ @Subscribe(tags = [Tag(HELPER_ADD_TO_PLAYLIST)]) fun addToPlaylist(playlistItem: PlaylistItemEntity) { playerHelper.addToPlaylist(playlistItem, trackRes, this.javaClass.name) } }
apache-2.0
0c4ef35699d6956eb933524b320a6a0f
43.362069
128
0.68552
4.677273
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/toc/OutdatedTableOfContentsInspection.kt
4
2433
package org.intellij.plugins.markdown.editor.toc import com.intellij.codeInspection.* import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiFile import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.lang.psi.MarkdownElementVisitor import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile internal class OutdatedTableOfContentsInspection: LocalInspectionTool() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return object: MarkdownElementVisitor() { override fun visitMarkdownFile(file: MarkdownFile) { super.visitMarkdownFile(file) checkFile(file, holder) } } } private fun checkFile(file: MarkdownFile, holder: ProblemsHolder) { val existingRanges = GenerateTableOfContentsAction.findExistingTocs(file).toList() if (existingRanges.isEmpty()) { return } val document = PsiDocumentManager.getInstance(file.project).getDocument(file) ?: return val expectedToc = GenerateTableOfContentsAction.obtainToc(file) for (range in existingRanges.asReversed()) { val text = document.getText(range) if (text != expectedToc) { holder.registerProblem( file, MarkdownBundle.message("markdown.outdated.table.of.contents.inspection.description"), ProblemHighlightType.WARNING, range, UpdateTocSectionQuickFix(expectedToc) ) } } } private class UpdateTocSectionQuickFix(private val expectedToc: String): LocalQuickFix { override fun getName(): String { return MarkdownBundle.message("markdown.outdated.table.of.contents.quick.fix.name") } override fun getFamilyName(): String { return MarkdownBundle.message("markdown.inspection.group.ruby.name") } override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val file = descriptor.psiElement as? PsiFile checkNotNull(file) val document = file.viewProvider.document if (document == null) { thisLogger().error("Failed to find document for the quick fix") return } val range = descriptor.textRangeInElement document.replaceString(range.startOffset, range.endOffset, expectedToc) } } }
apache-2.0
15159ffcceda4b867766a6245a5db795
36.430769
95
0.73284
4.678846
false
false
false
false
ReplayMod/ReplayMod
src/main/kotlin/com/replaymod/core/gui/common/scrollbar/UITexturedScrollBar.kt
1
1027
package com.replaymod.core.gui.common.scrollbar import com.replaymod.core.gui.common.UI9Slice import com.replaymod.core.gui.common.timeline.UITimeline.Companion.TEXTURE import gg.essential.elementa.components.UIContainer import gg.essential.elementa.constraints.CenterConstraint import gg.essential.elementa.dsl.* class UITexturedScrollBar : UIContainer() { val background by UI9Slice(TEXTURE, UI9Slice.TextureData.ofSize(64, 9, 2).offset(0, 7)).constrain { width = 100.percent height = 100.percent } childOf this val inner by UIContainer().constrain { x = CenterConstraint() y = CenterConstraint() width = 100.percent - 2.pixels height = 100.percent - 2.pixels } childOf background val grip by UI9Slice(TEXTURE, UI9Slice.TextureData.ofSize(62, 7, 2)).constrain { width = 100.percent height = 100.percent } childOf inner init { constrain { width = 100.percent height = 100.percent } } }
gpl-3.0
0ed361d50aefa3f3dea62c79f217a141
30.151515
103
0.680623
4.011719
false
false
false
false
vovagrechka/fucking-everything
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/translate/general/ModuleWrapperTranslation.kt
1
7941
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.js.translate.general import org.jetbrains.kotlin.js.backend.ast.* import org.jetbrains.kotlin.js.translate.context.Namer import org.jetbrains.kotlin.js.translate.context.StaticContext import org.jetbrains.kotlin.js.translate.utils.JsAstUtils import org.jetbrains.kotlin.serialization.js.ModuleKind object ModuleWrapperTranslation { @JvmStatic fun wrapIfNecessary( moduleId: String, function: JsExpression, importedModules: List<StaticContext.ImportedModule>, program: JsProgram, kind: ModuleKind ): List<JsStatement> { return when (kind) { ModuleKind.AMD -> wrapAmd(moduleId, function, importedModules, program) ModuleKind.COMMON_JS -> wrapCommonJs(function, importedModules, program) ModuleKind.UMD -> wrapUmd(moduleId, function, importedModules, program) ModuleKind.PLAIN -> wrapPlain(moduleId, function, importedModules, program) } } private fun wrapUmd( moduleId: String, function: JsExpression, importedModules: List<StaticContext.ImportedModule>, program: JsProgram ): List<JsStatement> { val scope = program.scope val defineName = scope.declareName("define") val exportsName = scope.declareName("exports") val adapterBody = JsBlock() val adapter = JsFunction(program.scope, adapterBody, "Adapter") val rootName = adapter.scope.declareName("root") val factoryName = adapter.scope.declareName("factory") adapter.parameters += JsParameter(rootName) adapter.parameters += JsParameter(factoryName) val amdTest = JsAstUtils.and(JsAstUtils.typeOfIs(defineName.makeRef(), program.getStringLiteral("function")), JsNameRef("amd", defineName.makeRef())) val commonJsTest = JsAstUtils.typeOfIs(exportsName.makeRef(), program.getStringLiteral("object")) val amdBody = JsBlock(wrapAmd(moduleId, factoryName.makeRef(), importedModules, program)) val commonJsBody = JsBlock(wrapCommonJs(factoryName.makeRef(), importedModules, program)) val plainInvocation = makePlainInvocation(moduleId, factoryName.makeRef(), importedModules, program) val lhs: JsExpression = if (Namer.requiresEscaping(moduleId)) { JsArrayAccess(rootName.makeRef(), program.getStringLiteral(moduleId)) } else { JsNameRef(scope.declareName(moduleId), rootName.makeRef()) } val plainBlock = JsBlock() for (importedModule in importedModules) { plainBlock.statements += addModuleValidation(moduleId, program, importedModule) } plainBlock.statements += JsAstUtils.assignment(lhs, plainInvocation).makeStmt() val selector = JsAstUtils.newJsIf(amdTest, amdBody, JsAstUtils.newJsIf(commonJsTest, commonJsBody, plainBlock)) adapterBody.statements += selector return listOf(JsInvocation(adapter, JsLiteral.THIS, function).makeStmt()) } private fun wrapAmd( moduleId: String, function: JsExpression, importedModules: List<StaticContext.ImportedModule>, program: JsProgram ): List<JsStatement> { val scope = program.scope val defineName = scope.declareName("define") val invocationArgs = listOf( program.getStringLiteral(moduleId), JsArrayLiteral(listOf(program.getStringLiteral("exports")) + importedModules.map { program.getStringLiteral(it.externalName) }), function ) val invocation = JsInvocation(defineName.makeRef(), invocationArgs) return listOf(invocation.makeStmt()) } private fun wrapCommonJs( function: JsExpression, importedModules: List<StaticContext.ImportedModule>, program: JsProgram ): List<JsStatement> { val scope = program.scope val moduleName = scope.declareName("module") val requireName = scope.declareName("require") val invocationArgs = importedModules.map { JsInvocation(requireName.makeRef(), program.getStringLiteral(it.externalName)) } val invocation = JsInvocation(function, listOf(JsNameRef("exports", moduleName.makeRef())) + invocationArgs) return listOf(invocation.makeStmt()) } private fun wrapPlain( moduleId: String, function: JsExpression, importedModules: List<StaticContext.ImportedModule>, program: JsProgram ): List<JsStatement> { val invocation = makePlainInvocation(moduleId, function, importedModules, program) val statements = mutableListOf<JsStatement>() for (importedModule in importedModules) { statements += addModuleValidation(moduleId, program, importedModule) } statements += if (Namer.requiresEscaping(moduleId)) { JsAstUtils.assignment(makePlainModuleRef(moduleId, program), invocation).makeStmt() } else { JsAstUtils.newVar(program.rootScope.declareName(moduleId), invocation) } return statements } private fun addModuleValidation( currentModuleId: String, program: JsProgram, module: StaticContext.ImportedModule ): JsStatement { val moduleRef = makePlainModuleRef(module, program) val moduleExistsCond = JsAstUtils.typeOfIs(moduleRef, program.getStringLiteral("undefined")) val moduleNotFoundMessage = program.getStringLiteral( "Error loading module '" + currentModuleId + "'. Its dependency '" + module.externalName + "' was not found. " + "Please, check whether '" + module.externalName + "' is loaded prior to '" + currentModuleId + "'.") val moduleNotFoundThrow = JsThrow(JsNew(JsNameRef("Error"), listOf<JsExpression>(moduleNotFoundMessage))) return JsIf(moduleExistsCond, JsBlock(moduleNotFoundThrow)) } private fun makePlainInvocation( moduleId: String, function: JsExpression, importedModules: List<StaticContext.ImportedModule>, program: JsProgram ): JsInvocation { val invocationArgs = importedModules.map { makePlainModuleRef(it, program) } val moduleRef = makePlainModuleRef(moduleId, program) val testModuleDefined = JsAstUtils.typeOfIs(moduleRef, program.getStringLiteral("undefined")) val selfArg = JsConditional(testModuleDefined, JsObjectLiteral(false), moduleRef.deepCopy()) return JsInvocation(function, listOf(selfArg) + invocationArgs) } private fun makePlainModuleRef(module: StaticContext.ImportedModule, program: JsProgram): JsExpression { return module.plainReference ?: makePlainModuleRef(module.externalName, program) } private fun makePlainModuleRef(moduleId: String, program: JsProgram): JsExpression { // TODO: we could use `this.moduleName` syntax. However, this does not work for `kotlin` module in Rhino, since // we run kotlin.js in a parent scope. Consider better solution return if (Namer.requiresEscaping(moduleId)) { JsArrayAccess(JsLiteral.THIS, program.getStringLiteral(moduleId)) } else { program.scope.declareName(moduleId).makeRef() } } }
apache-2.0
f4e216abb66f66707214ae466af34eba
44.901734
144
0.687571
4.786618
false
false
false
false
dkrivoruchko/ScreenStream
app/src/main/kotlin/info/dvkr/screenstream/ui/fragment/StreamFragment.kt
1
14650
package info.dvkr.screenstream.ui.fragment import android.content.ActivityNotFoundException import android.content.ClipData import android.content.ClipboardManager import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Build import android.os.Bundle import android.text.Spannable import android.text.SpannableString import android.text.style.ForegroundColorSpan import android.text.style.UnderlineSpan import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.appcompat.widget.AppCompatImageView import androidx.core.content.ContextCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.customview.customView import com.afollestad.materialdialogs.lifecycle.lifecycleOwner import com.elvishew.xlog.XLog import info.dvkr.screenstream.R import info.dvkr.screenstream.common.AppError import info.dvkr.screenstream.common.asString import info.dvkr.screenstream.common.getLog import info.dvkr.screenstream.databinding.FragmentStreamBinding import info.dvkr.screenstream.databinding.ItemClientBinding import info.dvkr.screenstream.databinding.ItemDeviceAddressBinding import info.dvkr.screenstream.mjpeg.* import info.dvkr.screenstream.mjpeg.settings.MjpegSettings import info.dvkr.screenstream.service.ServiceMessage import info.dvkr.screenstream.service.helper.IntentAction import info.dvkr.screenstream.ui.activity.ServiceActivity import info.dvkr.screenstream.ui.viewBinding import io.nayuki.qrcodegen.QrCode import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import org.koin.android.ext.android.inject class StreamFragment : AdFragment(R.layout.fragment_stream) { private val colorAccent by lazy(LazyThreadSafetyMode.NONE) { ContextCompat.getColor(requireContext(), R.color.colorAccent) } private val clipboard: ClipboardManager? by lazy(LazyThreadSafetyMode.NONE) { ContextCompat.getSystemService(requireContext(), ClipboardManager::class.java) } private val mjpegSettings: MjpegSettings by inject() private var httpClientAdapter: HttpClientAdapter? = null private var errorPrevious: AppError? = null private val binding by viewBinding { fragment -> FragmentStreamBinding.bind(fragment.requireView()) } private fun String.setColorSpan(color: Int, start: Int = 0, end: Int = this.length) = SpannableString(this).apply { setSpan(ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } private fun String.setUnderlineSpan(start: Int = 0, end: Int = this.length) = SpannableString(this).apply { setSpan(UnderlineSpan(), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) loadAdOnViewCreated(binding.flFragmentStreamAdViewContainer) binding.tvFragmentStreamTrafficHeader.text = getString(R.string.stream_fragment_current_traffic).run { format(0.0).setColorSpan(colorAccent, indexOf('%')) } binding.tvFragmentStreamClientsHeader.text = getString(R.string.stream_fragment_connected_clients).run { format(0).setColorSpan(colorAccent, indexOf('%')) } with(binding.rvFragmentStreamClients) { itemAnimator = DefaultItemAnimator() httpClientAdapter = HttpClientAdapter().apply { setHasStableIds(true) } adapter = httpClientAdapter } (requireActivity() as ServiceActivity).serviceMessageFlow .flowWithLifecycle(viewLifecycleOwner.lifecycle, Lifecycle.State.STARTED) .onEach { serviceMessage -> when (serviceMessage) { is ServiceMessage.ServiceState -> onServiceStateMessage(serviceMessage) is ServiceMessage.Clients -> onClientsMessage(serviceMessage) is ServiceMessage.TrafficHistory -> onTrafficHistoryMessage(serviceMessage) is ServiceMessage.FinishActivity -> Unit } } .launchIn(viewLifecycleOwner.lifecycleScope) } override fun onStart() { super.onStart() XLog.d(getLog("onStart")) IntentAction.GetServiceState.sendToAppService(requireContext()) } override fun onDestroyView() { super.onDestroyView() httpClientAdapter = null } private suspend fun onServiceStateMessage(serviceMessage: ServiceMessage.ServiceState) { // Interfaces binding.llFragmentStreamAddresses.removeAllViews() if (serviceMessage.netInterfaces.isEmpty()) { with(ItemDeviceAddressBinding.inflate(layoutInflater, binding.llFragmentStreamAddresses, false)) { tvItemDeviceAddressName.text = "" tvItemDeviceAddress.setText(R.string.stream_fragment_no_address) tvItemDeviceAddress.setTextColor(ContextCompat.getColor(requireContext(), R.color.textColorPrimary)) binding.llFragmentStreamAddresses.addView(this.root) } } else { serviceMessage.netInterfaces.sortedBy { it.address.asString() }.forEach { netInterface -> with(ItemDeviceAddressBinding.inflate(layoutInflater, binding.llFragmentStreamAddresses, false)) { tvItemDeviceAddressName.text = getString(R.string.stream_fragment_interface, netInterface.name) val fullAddress = "http://${netInterface.address.asString()}:${mjpegSettings.serverPortFlow.first()}" tvItemDeviceAddress.text = fullAddress.setUnderlineSpan() tvItemDeviceAddress.setOnClickListener { openInBrowser(fullAddress) } ivItemDeviceAddressOpenExternal.setOnClickListener { openInBrowser(fullAddress) } ivItemDeviceAddressCopy.setOnClickListener { clipboard?.setPrimaryClip( ClipData.newPlainText(tvItemDeviceAddress.text, tvItemDeviceAddress.text) ) if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2) Toast.makeText(requireContext(), R.string.stream_fragment_copied, Toast.LENGTH_LONG).show() } ivItemDeviceAddressShare.setOnClickListener { shareAddress(fullAddress) } ivItemDeviceAddressQr.setOnClickListener { showQrCode(fullAddress) } binding.llFragmentStreamAddresses.addView(this.root) } } } // Hide pin on Start if (mjpegSettings.enablePinFlow.first()) { if (serviceMessage.isStreaming && mjpegSettings.hidePinOnStartFlow.first()) { val pinText = getString(R.string.stream_fragment_pin, "*") binding.tvFragmentStreamPin.text = pinText.setColorSpan(colorAccent, pinText.length - 1) } else { val pinText = getString(R.string.stream_fragment_pin, mjpegSettings.pinFlow.first()) binding.tvFragmentStreamPin.text = pinText.setColorSpan(colorAccent, pinText.length - mjpegSettings.pinFlow.first().length) } } else { binding.tvFragmentStreamPin.setText(R.string.stream_fragment_pin_disabled) } showError(serviceMessage.appError) } private fun onClientsMessage(serviceMessage: ServiceMessage.Clients) { val clientsCount = serviceMessage.clients.count { (it as MjpegClient).isDisconnected.not() } binding.tvFragmentStreamClientsHeader.text = getString(R.string.stream_fragment_connected_clients).run { format(clientsCount).setColorSpan(colorAccent, indexOf('%')) } httpClientAdapter?.submitList(serviceMessage.clients.map { it as MjpegClient }) } private fun Long.bytesToMbit() = (this * 8).toFloat() / 1024 / 1024 private fun onTrafficHistoryMessage(serviceMessage: ServiceMessage.TrafficHistory) { binding.tvFragmentStreamTrafficHeader.text = getString(R.string.stream_fragment_current_traffic).run { val lastTrafficPoint = serviceMessage.trafficHistory.lastOrNull() as? MjpegTrafficPoint ?: return@run "0" format(lastTrafficPoint.bytes.bytesToMbit()).setColorSpan(colorAccent, indexOf('%')) } binding.trafficGraphFragmentStream.setDataPoints( serviceMessage.trafficHistory.map { it as MjpegTrafficPoint }.map { Pair(it.time, it.bytes.bytesToMbit()) } ) } private fun openInBrowser(fullAddress: String) { try { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(fullAddress)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } catch (ex: ActivityNotFoundException) { Toast.makeText( requireContext().applicationContext, R.string.stream_fragment_no_web_browser_found, Toast.LENGTH_LONG ).show() XLog.w(getLog("openInBrowser", ex.toString())) } catch (ex: SecurityException) { Toast.makeText( requireContext().applicationContext, R.string.stream_fragment_external_app_error, Toast.LENGTH_LONG ).show() XLog.w(getLog("openInBrowser", ex.toString())) } } private fun shareAddress(fullAddress: String) { val sharingIntent = Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra(Intent.EXTRA_TEXT, fullAddress) } startActivity(Intent.createChooser(sharingIntent, getString(R.string.stream_fragment_share_address))) } private fun showQrCode(fullAddress: String) { fullAddress.getQRBitmap(resources.getDimensionPixelSize(R.dimen.fragment_stream_qrcode_size))?.let { qrBitmap -> if (viewLifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) { val imageView = AppCompatImageView(requireContext()).apply { setImageBitmap(qrBitmap) } MaterialDialog(requireActivity()) .lifecycleOwner(viewLifecycleOwner) .customView(view = imageView, noVerticalPadding = true) .maxWidth(R.dimen.fragment_stream_qrcode_size) .show() } } } private fun showError(appError: AppError?) { errorPrevious != appError || return if (appError == null) { binding.tvFragmentStreamError.visibility = View.GONE } else { XLog.d(getLog("showError", appError.toString())) binding.tvFragmentStreamError.text = when (appError) { is AddressInUseException -> getString(R.string.error_port_in_use) is CastSecurityException -> getString(R.string.error_invalid_media_projection) is AddressNotFoundException -> getString(R.string.error_ip_address_not_found) is BitmapFormatException -> getString(R.string.error_wrong_image_format) else -> appError.toString() } binding.tvFragmentStreamError.visibility = View.VISIBLE } errorPrevious = appError } private class HttpClientAdapter : ListAdapter<MjpegClient, HttpClientViewHolder>( object : DiffUtil.ItemCallback<MjpegClient>() { override fun areItemsTheSame(oldItem: MjpegClient, newItem: MjpegClient): Boolean = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: MjpegClient, newItem: MjpegClient): Boolean = oldItem == newItem } ) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = HttpClientViewHolder(ItemClientBinding.inflate(LayoutInflater.from(parent.context), parent, false)) override fun getItemId(position: Int): Long = getItem(position).id override fun onBindViewHolder(holder: HttpClientViewHolder, position: Int) = holder.bind(getItem(position)) } private class HttpClientViewHolder(private val binding: ItemClientBinding) : RecyclerView.ViewHolder(binding.root) { private val textColorPrimary by lazy { ContextCompat.getColor(binding.root.context, R.color.textColorPrimary) } private val colorError by lazy { ContextCompat.getColor(binding.root.context, R.color.colorError) } private val colorAccent by lazy { ContextCompat.getColor(binding.root.context, R.color.colorAccent) } fun bind(product: MjpegClient) = with(product) { binding.tvClientItemAddress.text = clientAddress with(binding.tvClientItemStatus) { when { isBlocked -> { setText(R.string.stream_fragment_client_blocked) setTextColor(colorError) } isDisconnected -> { setText(R.string.stream_fragment_client_disconnected) setTextColor(textColorPrimary) } isSlowConnection -> { setText(R.string.stream_fragment_client_slow_network) setTextColor(colorError) } else -> { setText(R.string.stream_fragment_client_connected) setTextColor(colorAccent) } } } } } private fun String.getQRBitmap(size: Int): Bitmap? = try { val qrCode = QrCode.encodeText(this, QrCode.Ecc.MEDIUM) val scale = size / qrCode.size val pixels = IntArray(size * size).apply { fill(0xFFFFFFFF.toInt()) } for (y in 0 until size) for (x in 0 until size) if (qrCode.getModule(x / scale, y / scale)) pixels[y * size + x] = 0xFF000000.toInt() val border = 16 Bitmap.createBitmap(size + border, size + border, Bitmap.Config.ARGB_8888).apply { setPixels(pixels, 0, size, border, border, size, size) } } catch (ex: Exception) { XLog.e(getLog("String.getQRBitmap", ex.toString())) null } }
mit
135a8c5e4d1a50a1ca5bba889c57816e
46.723127
128
0.671672
4.942645
false
false
false
false
jwren/intellij-community
platform/diff-impl/src/com/intellij/openapi/vcs/ex/DocumentTracker.kt
4
35082
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.ex import com.intellij.diff.comparison.iterables.DiffIterable import com.intellij.diff.comparison.iterables.FairDiffIterable import com.intellij.diff.comparison.trimStart import com.intellij.diff.tools.util.text.LineOffsets import com.intellij.diff.util.DiffRangeUtil import com.intellij.diff.util.DiffUtil import com.intellij.diff.util.Range import com.intellij.diff.util.Side import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationListener import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.ex.DocumentTracker.Block import com.intellij.openapi.vcs.ex.DocumentTracker.Handler import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.containers.PeekableIteratorWrapper import org.jetbrains.annotations.ApiStatus import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock import kotlin.math.max /** * Any external calls (ex: Document modifications) must be avoided under [LOCK], * to avoid deadlocks with application Read/Write action and ChangeListManager. * * Tracker assumes that both documents are modified on EDT only. * * Blocks are modified on EDT and under [LOCK]. */ class DocumentTracker( document1: Document, document2: Document, private val LOCK: Lock ) : Disposable { private val handlers: MutableList<Handler> = mutableListOf() var document1: Document = document1 private set var document2: Document = document2 private set private val tracker: LineTracker private val freezeHelper: FreezeHelper = FreezeHelper() private var isDisposed: Boolean = false private val documentListener1 = MyDocumentListener(Side.LEFT, document1) private val documentListener2 = MyDocumentListener(Side.RIGHT, document2) init { assert(document1 != document2) val changes = when { document1.immutableCharSequence === document2.immutableCharSequence -> emptyList() else -> compareLines(document1.immutableCharSequence, document2.immutableCharSequence, document1.lineOffsets, document2.lineOffsets).iterateChanges().toList() } tracker = LineTracker(handlers, changes) val application = ApplicationManager.getApplication() application.addApplicationListener(MyApplicationListener(), this) } @RequiresEdt override fun dispose() { ApplicationManager.getApplication().assertIsDispatchThread() if (isDisposed) return isDisposed = true LOCK.write { tracker.destroy() } } @RequiresEdt fun addHandler(newHandler: Handler) { handlers.add(newHandler) } val blocks: List<Block> get() = tracker.blocks fun <T> readLock(task: () -> T): T = LOCK.read(task) fun <T> writeLock(task: () -> T): T = LOCK.write(task) val isLockHeldByCurrentThread: Boolean get() = LOCK.isHeldByCurrentThread fun isFrozen(): Boolean { LOCK.read { return freezeHelper.isFrozen() } } fun freeze(side: Side) { LOCK.write { freezeHelper.freeze(side) } } @RequiresEdt fun unfreeze(side: Side) { LOCK.write { freezeHelper.unfreeze(side) } } @RequiresEdt inline fun doFrozen(task: () -> Unit) { doFrozen(Side.LEFT) { doFrozen(Side.RIGHT) { task() } } } @RequiresEdt inline fun doFrozen(side: Side, task: () -> Unit) { freeze(side) try { task() } finally { unfreeze(side) } } fun getContent(side: Side): CharSequence { LOCK.read { val frozenContent = freezeHelper.getFrozenContent(side) if (frozenContent != null) return frozenContent return side[document1, document2].immutableCharSequence } } @RequiresEdt fun replaceDocument(side: Side, newDocument: Document) { assert(!LOCK.isHeldByCurrentThread) doFrozen { if (side.isLeft) { documentListener1.switchDocument(newDocument) document1 = newDocument } else { documentListener2.switchDocument(newDocument) document2 = newDocument } } } @RequiresEdt fun refreshDirty(fastRefresh: Boolean, forceInFrozen: Boolean = false) { if (isDisposed) return if (!forceInFrozen && freezeHelper.isFrozen()) return LOCK.write { if (tracker.isDirty && blocks.isNotEmpty() && StringUtil.equals(document1.immutableCharSequence, document2.immutableCharSequence)) { tracker.setRanges(emptyList(), false) return } tracker.refreshDirty(document1.immutableCharSequence, document2.immutableCharSequence, document1.lineOffsets, document2.lineOffsets, fastRefresh) } } private fun unfreeze(side: Side, oldText: CharSequence) { assert(LOCK.isHeldByCurrentThread) if (isDisposed) return val newText = side[document1, document2] val iterable = compareLines(oldText, newText.immutableCharSequence, oldText.lineOffsets, newText.lineOffsets) if (iterable.changes().hasNext()) { tracker.rangesChanged(side, iterable) } } @RequiresEdt fun updateFrozenContentIfNeeded() { // ensure blocks are up to date updateFrozenContentIfNeeded(Side.LEFT) updateFrozenContentIfNeeded(Side.RIGHT) refreshDirty(fastRefresh = false, forceInFrozen = true) } private fun updateFrozenContentIfNeeded(side: Side) { assert(LOCK.isHeldByCurrentThread) if (!freezeHelper.isFrozen(side)) return unfreeze(side, freezeHelper.getFrozenContent(side)!!) freezeHelper.setFrozenContent(side, side[document1, document2].immutableCharSequence) } @RequiresEdt fun partiallyApplyBlocks(side: Side, condition: (Block) -> Boolean) { partiallyApplyBlocks(side, condition, { _, _ -> }) } @RequiresEdt fun partiallyApplyBlocks(side: Side, condition: (Block) -> Boolean, consumer: (Block, shift: Int) -> Unit) { if (isDisposed) return val otherSide = side.other() val document = side[document1, document2] val otherDocument = otherSide[document1, document2] doFrozen(side) { val appliedBlocks = LOCK.write { updateFrozenContentIfNeeded() tracker.partiallyApplyBlocks(side, condition) } // We use already filtered blocks here, because conditions might have been changed from other thread. // The documents/blocks themselves did not change though. var shift = 0 for (block in appliedBlocks) { DiffUtil.applyModification(document, block.range.start(side) + shift, block.range.end(side) + shift, otherDocument, block.range.start(otherSide), block.range.end(otherSide)) consumer(block, shift) shift += getRangeDelta(block.range, side) } LOCK.write { freezeHelper.setFrozenContent(side, document.immutableCharSequence) } } } @RequiresEdt fun getContentWithPartiallyAppliedBlocks(side: Side, condition: (Block) -> Boolean): String { val otherSide = side.other() val affectedBlocks = LOCK.write { updateFrozenContentIfNeeded() tracker.blocks.filter(condition) } val content = getContent(side) val otherContent = getContent(otherSide) val lineOffsets = content.lineOffsets val otherLineOffsets = otherContent.lineOffsets val ranges = affectedBlocks.map { Range(it.range.start(side), it.range.end(side), it.range.start(otherSide), it.range.end(otherSide)) } return DiffUtil.applyModification(content, lineOffsets, otherContent, otherLineOffsets, ranges) } fun setFrozenState(content1: CharSequence, content2: CharSequence, lineRanges: List<Range>): Boolean { assert(freezeHelper.isFrozen(Side.LEFT) && freezeHelper.isFrozen(Side.RIGHT)) if (isDisposed) return false LOCK.write { if (!isValidRanges(content1, content2, content1.lineOffsets, content2.lineOffsets, lineRanges)) return false freezeHelper.setFrozenContent(Side.LEFT, content1) freezeHelper.setFrozenContent(Side.RIGHT, content2) tracker.setRanges(lineRanges, true) return true } } @RequiresEdt fun setFrozenState(lineRanges: List<Range>): Boolean { if (isDisposed) return false assert(freezeHelper.isFrozen(Side.LEFT) && freezeHelper.isFrozen(Side.RIGHT)) LOCK.write { val content1 = getContent(Side.LEFT) val content2 = getContent(Side.RIGHT) if (!isValidRanges(content1, content2, content1.lineOffsets, content2.lineOffsets, lineRanges)) return false tracker.setRanges(lineRanges, true) return true } } private inner class MyApplicationListener : ApplicationListener { override fun afterWriteActionFinished(action: Any) { refreshDirty(fastRefresh = true) } } private inner class MyDocumentListener(val side: Side, private var document: Document) : DocumentListener { private var line1: Int = 0 private var line2: Int = 0 init { document.addDocumentListener(this, this@DocumentTracker) if (document.isInBulkUpdate) freeze(side) } fun switchDocument(newDocument: Document) { document.removeDocumentListener(this) if (document.isInBulkUpdate == true) unfreeze(side) document = newDocument newDocument.addDocumentListener(this, this@DocumentTracker) if (newDocument.isInBulkUpdate) freeze(side) } override fun beforeDocumentChange(e: DocumentEvent) { if (isDisposed || freezeHelper.isFrozen(side)) return line1 = document.getLineNumber(e.offset) if (e.oldLength == 0) { line2 = line1 + 1 } else { line2 = document.getLineNumber(e.offset + e.oldLength) + 1 } } override fun documentChanged(e: DocumentEvent) { if (isDisposed || freezeHelper.isFrozen(side)) return val newLine2: Int if (e.newLength == 0) { newLine2 = line1 + 1 } else { newLine2 = document.getLineNumber(e.offset + e.newLength) + 1 } val (startLine, afterLength, beforeLength) = getAffectedRange(line1, line2, newLine2, e) LOCK.write { tracker.rangeChanged(side, startLine, beforeLength, afterLength) } } override fun bulkUpdateStarting(document: Document) { freeze(side) } override fun bulkUpdateFinished(document: Document) { unfreeze(side) } private fun getAffectedRange(line1: Int, oldLine2: Int, newLine2: Int, e: DocumentEvent): Triple<Int, Int, Int> { val afterLength = newLine2 - line1 val beforeLength = oldLine2 - line1 // Whole line insertion / deletion if (e.oldLength == 0 && e.newLength != 0) { if (StringUtil.endsWithChar(e.newFragment, '\n') && isNewlineBefore(e)) { return Triple(line1, afterLength - 1, beforeLength - 1) } if (StringUtil.startsWithChar(e.newFragment, '\n') && isNewlineAfter(e)) { return Triple(line1 + 1, afterLength - 1, beforeLength - 1) } } if (e.oldLength != 0 && e.newLength == 0) { if (StringUtil.endsWithChar(e.oldFragment, '\n') && isNewlineBefore(e)) { return Triple(line1, afterLength - 1, beforeLength - 1) } if (StringUtil.startsWithChar(e.oldFragment, '\n') && isNewlineAfter(e)) { return Triple(line1 + 1, afterLength - 1, beforeLength - 1) } } return Triple(line1, afterLength, beforeLength) } private fun isNewlineBefore(e: DocumentEvent): Boolean { if (e.offset == 0) return true return e.document.immutableCharSequence[e.offset - 1] == '\n' } private fun isNewlineAfter(e: DocumentEvent): Boolean { if (e.offset + e.newLength == e.document.immutableCharSequence.length) return true return e.document.immutableCharSequence[e.offset + e.newLength] == '\n' } } private inner class FreezeHelper { private var data1: FreezeData? = null private var data2: FreezeData? = null fun isFrozen(side: Side) = getData(side) != null fun isFrozen() = isFrozen(Side.LEFT) || isFrozen(Side.RIGHT) fun freeze(side: Side) { val wasFrozen = isFrozen() var data = getData(side) if (data == null) { data = FreezeData(side[document1, document2]) setData(side, data) data.counter++ if (wasFrozen) onFreeze() onFreeze(side) } else { data.counter++ } } fun unfreeze(side: Side) { val data = getData(side) if (data == null || data.counter == 0) { LOG.error("DocumentTracker is not freezed: $side, ${data1?.counter ?: -1}, ${data2?.counter ?: -1}") return } data.counter-- if (data.counter == 0) { unfreeze(side, data.textBeforeFreeze) setData(side, null) refreshDirty(fastRefresh = false) onUnfreeze(side) if (!isFrozen()) onUnfreeze() } } private fun getData(side: Side) = side[data1, data2] private fun setData(side: Side, data: FreezeData?) { if (side.isLeft) { data1 = data } else { data2 = data } } fun getFrozenContent(side: Side): CharSequence? = getData(side)?.textBeforeFreeze fun setFrozenContent(side: Side, newContent: CharSequence) { setData(side, FreezeData(getData(side)!!, newContent)) } private fun onFreeze(side: Side) { handlers.forEach { it.onFreeze(side) } } private fun onUnfreeze(side: Side) { handlers.forEach { it.onUnfreeze(side) } } private fun onFreeze() { handlers.forEach { it.onFreeze() } } private fun onUnfreeze() { handlers.forEach { it.onUnfreeze() } } } private class FreezeData(val textBeforeFreeze: CharSequence, var counter: Int) { constructor(document: Document) : this(document.immutableCharSequence, 0) constructor(data: FreezeData, textBeforeFreeze: CharSequence) : this(textBeforeFreeze, data.counter) } @ApiStatus.Internal class Lock { val myLock = ReentrantLock() inline fun <T> read(task: () -> T): T { return myLock.withLock(task) } inline fun <T> write(task: () -> T): T { return myLock.withLock(task) } val isHeldByCurrentThread: Boolean get() = myLock.isHeldByCurrentThread } /** * All methods are invoked under [LOCK]. */ interface Handler { fun onRangeRefreshed(before: Block, after: List<Block>) {} fun onRangesChanged(before: List<Block>, after: Block) {} fun onRangeShifted(before: Block, after: Block) {} /** * In some cases, we might want to refresh multiple adjustent blocks together. * This method allows to veto such merging (ex: if blocks share conflicting sets of flags). * * @return true if blocks are allowed to be merged */ fun mergeRanges(block1: Block, block2: Block, merged: Block): Boolean = true fun afterBulkRangeChange(isDirty: Boolean) {} fun onFreeze(side: Side) {} fun onUnfreeze(side: Side) {} fun onFreeze() {} fun onUnfreeze() {} } class Block(val range: Range, internal val isDirty: Boolean, internal val isTooBig: Boolean) : BlockI { var data: Any? = null override val start: Int get() = range.start2 override val end: Int get() = range.end2 override val vcsStart: Int get() = range.start1 override val vcsEnd: Int get() = range.end1 } companion object { private val LOG = Logger.getInstance(DocumentTracker::class.java) } } private class LineTracker(private val handlers: List<Handler>, originalChanges: List<Range>) { var blocks: List<Block> = originalChanges.map { Block(it, false, false) } private set var isDirty: Boolean = false private set private var forceMergeNearbyBlocks: Boolean = false fun setRanges(ranges: List<Range>, dirty: Boolean) { val newBlocks = ranges.map { Block(it, dirty, false) } for (block in newBlocks) { onRangesChanged(emptyList(), block) } blocks = newBlocks isDirty = dirty forceMergeNearbyBlocks = false afterBulkRangeChange(isDirty) } fun destroy() { blocks = emptyList() } fun refreshDirty(text1: CharSequence, text2: CharSequence, lineOffsets1: LineOffsets, lineOffsets2: LineOffsets, fastRefresh: Boolean) { if (!isDirty) return val result = BlocksRefresher(handlers, text1, text2, lineOffsets1, lineOffsets2, forceMergeNearbyBlocks).refresh(blocks, fastRefresh) blocks = result.newBlocks isDirty = false forceMergeNearbyBlocks = false afterBulkRangeChange(isDirty) } fun rangeChanged(side: Side, startLine: Int, beforeLength: Int, afterLength: Int) { val data = RangeChangeHandler().run(blocks, side, startLine, beforeLength, afterLength) onRangesChanged(data.affectedBlocks, data.newAffectedBlock) for (i in data.afterBlocks.indices) { onRangeShifted(data.afterBlocks[i], data.newAfterBlocks[i]) } blocks = data.newBlocks isDirty = data.newBlocks.isNotEmpty() afterBulkRangeChange(isDirty) } fun rangesChanged(side: Side, iterable: DiffIterable) { val newBlocks = BulkRangeChangeHandler(handlers, blocks, side).run(iterable) blocks = newBlocks isDirty = newBlocks.isNotEmpty() forceMergeNearbyBlocks = isDirty afterBulkRangeChange(isDirty) } fun partiallyApplyBlocks(side: Side, condition: (Block) -> Boolean): List<Block> { val newBlocks = mutableListOf<Block>() val appliedBlocks = mutableListOf<Block>() var shift = 0 for (block in blocks) { if (condition(block)) { appliedBlocks.add(block) shift += getRangeDelta(block.range, side) } else { val newBlock = block.shift(side, shift) onRangeShifted(block, newBlock) newBlocks.add(newBlock) } } blocks = newBlocks afterBulkRangeChange(isDirty) return appliedBlocks } private fun onRangesChanged(before: List<Block>, after: Block) { handlers.forEach { it.onRangesChanged(before, after) } } private fun onRangeShifted(before: Block, after: Block) { handlers.forEach { it.onRangeShifted(before, after) } } private fun afterBulkRangeChange(isDirty: Boolean) { handlers.forEach { it.afterBulkRangeChange(isDirty) } } } private class RangeChangeHandler { fun run(blocks: List<Block>, side: Side, startLine: Int, beforeLength: Int, afterLength: Int): Result { val endLine = startLine + beforeLength val rangeSizeDelta = afterLength - beforeLength val (beforeBlocks, affectedBlocks, afterBlocks) = sortRanges(blocks, side, startLine, endLine) val ourToOtherShift: Int = getOurToOtherShift(side, beforeBlocks) val newAffectedBlock = getNewAffectedBlock(side, startLine, endLine, rangeSizeDelta, ourToOtherShift, affectedBlocks) val newAfterBlocks = afterBlocks.map { it.shift(side, rangeSizeDelta) } val newBlocks = ArrayList<Block>(beforeBlocks.size + newAfterBlocks.size + 1) newBlocks.addAll(beforeBlocks) newBlocks.add(newAffectedBlock) newBlocks.addAll(newAfterBlocks) return Result(beforeBlocks, newBlocks, affectedBlocks, afterBlocks, newAffectedBlock, newAfterBlocks) } private fun sortRanges(blocks: List<Block>, side: Side, line1: Int, line2: Int): Triple<List<Block>, List<Block>, List<Block>> { val beforeChange = ArrayList<Block>() val affected = ArrayList<Block>() val afterChange = ArrayList<Block>() for (block in blocks) { if (block.range.end(side) < line1) { beforeChange.add(block) } else if (block.range.start(side) > line2) { afterChange.add(block) } else { affected.add(block) } } return Triple(beforeChange, affected, afterChange) } private fun getOurToOtherShift(side: Side, beforeBlocks: List<Block>): Int { val lastBefore = beforeBlocks.lastOrNull()?.range val otherShift: Int if (lastBefore == null) { otherShift = 0 } else { otherShift = lastBefore.end(side.other()) - lastBefore.end(side) } return otherShift } private fun getNewAffectedBlock(side: Side, startLine: Int, endLine: Int, rangeSizeDelta: Int, ourToOtherShift: Int, affectedBlocks: List<Block>): Block { val rangeStart: Int val rangeEnd: Int val rangeStartOther: Int val rangeEndOther: Int if (affectedBlocks.isEmpty()) { rangeStart = startLine rangeEnd = endLine + rangeSizeDelta rangeStartOther = startLine + ourToOtherShift rangeEndOther = endLine + ourToOtherShift } else { val firstAffected = affectedBlocks.first().range val lastAffected = affectedBlocks.last().range val affectedStart = firstAffected.start(side) val affectedStartOther = firstAffected.start(side.other()) val affectedEnd = lastAffected.end(side) val affectedEndOther = lastAffected.end(side.other()) if (affectedStart <= startLine) { rangeStart = affectedStart rangeStartOther = affectedStartOther } else { rangeStart = startLine rangeStartOther = startLine + (affectedStartOther - affectedStart) } if (affectedEnd >= endLine) { rangeEnd = affectedEnd + rangeSizeDelta rangeEndOther = affectedEndOther } else { rangeEnd = endLine + rangeSizeDelta rangeEndOther = endLine + (affectedEndOther - affectedEnd) } } val isTooBig = affectedBlocks.any { it.isTooBig } val range = createRange(side, rangeStart, rangeEnd, rangeStartOther, rangeEndOther) return Block(range, true, isTooBig) } data class Result(val beforeBlocks: List<Block>, val newBlocks: List<Block>, val affectedBlocks: List<Block>, val afterBlocks: List<Block>, val newAffectedBlock: Block, val newAfterBlocks: List<Block>) } /** * We use line numbers in 3 documents: * A: Line number in unchanged document * B: Line number in changed document <before> the change * C: Line number in changed document <after> the change * * Algorithm is similar to building ranges for a merge conflict, * see [com.intellij.diff.comparison.ComparisonMergeUtil.FairMergeBuilder]. * ie: B is the "Base" and A/C are "Left"/"Right". Old blocks hold the differences "A -> B", * changes from iterable hold the differences "B -> C". We want to construct new blocks with differences "A -> C. * * We iterate all differences in 'B' order, collecting interleaving groups of differences. Each group becomes a single newBlock. * [blockShift]/[changeShift] indicate how 'B' line is mapped to the 'A'/'C' lines at the start of current group. * [dirtyBlockShift]/[dirtyChangeShift] accumulate differences from the current group. * * block(otherSide -> side): A -> B * newBlock(otherSide -> side): A -> C * iterable: B -> C * dirtyStart, dirtyEnd: B * blockShift: delta B -> A * changeShift: delta B -> C */ private class BulkRangeChangeHandler(private val handlers: List<Handler>, private val blocks: List<Block>, private val side: Side) { private val newBlocks: MutableList<Block> = mutableListOf() private var dirtyStart = -1 private var dirtyEnd = -1 private val dirtyBlocks: MutableList<Block> = mutableListOf() private var dirtyBlocksModified = false private var blockShift: Int = 0 private var changeShift: Int = 0 private var dirtyBlockShift: Int = 0 private var dirtyChangeShift: Int = 0 fun run(iterable: DiffIterable): List<Block> { val it1 = PeekableIteratorWrapper(blocks.iterator()) val it2 = PeekableIteratorWrapper(iterable.changes()) while (it1.hasNext() || it2.hasNext()) { if (!it2.hasNext()) { handleBlock(it1.next()) continue } if (!it1.hasNext()) { handleChange(it2.next()) continue } val block = it1.peek() val range1 = block.range val range2 = it2.peek() if (range1.start(side) <= range2.start1) { handleBlock(it1.next()) } else { handleChange(it2.next()) } } flush(Int.MAX_VALUE) return newBlocks } private fun handleBlock(block: Block) { val range = block.range flush(range.start(side)) dirtyBlockShift += getRangeDelta(range, side) markDirtyRange(range.start(side), range.end(side)) dirtyBlocks.add(block) } private fun handleChange(range: Range) { flush(range.start1) dirtyChangeShift += getRangeDelta(range, Side.LEFT) markDirtyRange(range.start1, range.end1) dirtyBlocksModified = true } private fun markDirtyRange(start: Int, end: Int) { if (dirtyEnd == -1) { dirtyStart = start dirtyEnd = end } else { dirtyEnd = max(dirtyEnd, end) } } private fun flush(nextLine: Int) { if (dirtyEnd != -1 && dirtyEnd < nextLine) { if (dirtyBlocksModified) { val isTooBig = dirtyBlocks.any { it.isTooBig } val isDirty = true val range = createRange(side, dirtyStart + changeShift, dirtyEnd + changeShift + dirtyChangeShift, dirtyStart + blockShift, dirtyEnd + blockShift + dirtyBlockShift) val newBlock = Block(range, isDirty, isTooBig) onRangesChanged(dirtyBlocks, newBlock) newBlocks.add(newBlock) } else { assert(dirtyBlocks.size == 1) if (changeShift != 0) { for (oldBlock in dirtyBlocks) { val newBlock = oldBlock.shift(side, changeShift) onRangeShifted(oldBlock, newBlock) newBlocks.add(newBlock) } } else { newBlocks.addAll(dirtyBlocks) } } dirtyStart = -1 dirtyEnd = -1 dirtyBlocks.clear() dirtyBlocksModified = false blockShift += dirtyBlockShift changeShift += dirtyChangeShift dirtyBlockShift = 0 dirtyChangeShift = 0 } } private fun onRangesChanged(before: List<Block>, after: Block) { handlers.forEach { it.onRangesChanged(before, after) } } private fun onRangeShifted(before: Block, after: Block) { handlers.forEach { it.onRangeShifted(before, after) } } } private class BlocksRefresher(val handlers: List<Handler>, val text1: CharSequence, val text2: CharSequence, val lineOffsets1: LineOffsets, val lineOffsets2: LineOffsets, val forceMergeNearbyBlocks: Boolean) { fun refresh(blocks: List<Block>, fastRefresh: Boolean): Result { val newBlocks = ArrayList<Block>() processMergeableGroups(blocks) { group -> if (group.any { it.isDirty }) { processMergedBlocks(group) { mergedBlock -> val freshBlocks = refreshMergedBlock(mergedBlock, fastRefresh) onRangeRefreshed(mergedBlock.merged, freshBlocks) newBlocks.addAll(freshBlocks) } } else { newBlocks.addAll(group) } } return Result(newBlocks) } private fun processMergeableGroups(blocks: List<Block>, processGroup: (group: List<Block>) -> Unit) { if (blocks.isEmpty()) return var i = 0 var blockStart = 0 while (i < blocks.size - 1) { if (!shouldMergeBlocks(blocks[i], blocks[i + 1])) { processGroup(blocks.subList(blockStart, i + 1)) blockStart = i + 1 } i += 1 } processGroup(blocks.subList(blockStart, i + 1)) } private fun shouldMergeBlocks(block1: Block, block2: Block): Boolean { if (forceMergeNearbyBlocks && block2.range.start2 - block1.range.end2 < NEARBY_BLOCKS_LINES) { return true } if (isWhitespaceOnlySeparated(block1, block2)) return true return false } private fun isWhitespaceOnlySeparated(block1: Block, block2: Block): Boolean { val range1 = DiffRangeUtil.getLinesRange(lineOffsets1, block1.range.start1, block1.range.end1, false) val range2 = DiffRangeUtil.getLinesRange(lineOffsets1, block2.range.start1, block2.range.end1, false) val start = range1.endOffset val end = range2.startOffset return trimStart(text1, start, end) == end } private fun processMergedBlocks(group: List<Block>, processBlock: (merged: MergedBlock) -> Unit) { assert(!group.isEmpty()) var merged: Block? = null val original: MutableList<Block> = mutableListOf() for (block in group) { if (merged == null) { merged = block original += block } else { val newMerged = mergeBlocks(merged, block) if (newMerged != null) { merged = newMerged original += block } else { processBlock(MergedBlock(merged, original.toList())) original.clear() merged = block original += merged } } } processBlock(MergedBlock(merged!!, original.toList())) } private fun mergeBlocks(block1: Block, block2: Block): Block? { val isDirty = block1.isDirty || block2.isDirty val isTooBig = block1.isTooBig || block2.isTooBig val range = Range(block1.range.start1, block2.range.end1, block1.range.start2, block2.range.end2) val merged = Block(range, isDirty, isTooBig) for (handler in handlers) { val success = handler.mergeRanges(block1, block2, merged) if (!success) return null // merging vetoed } return merged } private fun refreshMergedBlock(mergedBlock: MergedBlock, fastRefresh: Boolean): List<Block> { val freshBlocks = refreshBlock(mergedBlock.merged, fastRefresh) if (mergedBlock.original.size == 1) return freshBlocks if (!forceMergeNearbyBlocks) return freshBlocks // try reuse original blocks to prevent occasional 'insertion' moves val nonMergedFreshBlocks = mergedBlock.original.flatMap { block -> if (block.isDirty) { refreshBlock(block, fastRefresh) } else { listOf(block) } } val oldSize = calcNonWhitespaceSize(text1, text2, lineOffsets1, lineOffsets2, nonMergedFreshBlocks) val newSize = calcNonWhitespaceSize(text1, text2, lineOffsets1, lineOffsets2, freshBlocks) if (oldSize < newSize) return nonMergedFreshBlocks if (oldSize > newSize) return freshBlocks val oldTotalSize = calcSize(nonMergedFreshBlocks) val newTotalSize = calcSize(freshBlocks) if (oldTotalSize <= newTotalSize) return nonMergedFreshBlocks return freshBlocks } private fun refreshBlock(block: Block, fastRefresh: Boolean): List<Block> { if (block.range.isEmpty) return emptyList() val iterable: FairDiffIterable val isTooBig: Boolean if (block.isTooBig && fastRefresh) { iterable = fastCompareLines(block.range, text1, text2, lineOffsets1, lineOffsets2) isTooBig = true } else { val realIterable = tryCompareLines(block.range, text1, text2, lineOffsets1, lineOffsets2) if (realIterable != null) { iterable = realIterable isTooBig = false } else { iterable = fastCompareLines(block.range, text1, text2, lineOffsets1, lineOffsets2) isTooBig = true } } return iterable.iterateChanges().map { Block(shiftRange(it, block.range.start1, block.range.start2), false, isTooBig) } } private fun calcSize(blocks: List<Block>): Int { var result = 0 for (block in blocks) { result += block.range.end1 - block.range.start1 result += block.range.end2 - block.range.start2 } return result } private fun calcNonWhitespaceSize(text1: CharSequence, text2: CharSequence, lineOffsets1: LineOffsets, lineOffsets2: LineOffsets, blocks: List<Block>): Int { var result = 0 for (block in blocks) { for (line in block.range.start1 until block.range.end1) { if (!isWhitespaceLine(text1, lineOffsets1, line)) result++ } for (line in block.range.start2 until block.range.end2) { if (!isWhitespaceLine(text2, lineOffsets2, line)) result++ } } return result } private fun isWhitespaceLine(text: CharSequence, lineOffsets: LineOffsets, line: Int): Boolean { val start = lineOffsets.getLineStart(line) val end = lineOffsets.getLineEnd(line) return trimStart(text, start, end) == end } private fun onRangeRefreshed(before: Block, after: List<Block>) { handlers.forEach { it.onRangeRefreshed(before, after) } } data class Result(val newBlocks: List<Block>) data class MergedBlock(val merged: Block, val original: List<Block>) companion object { private const val NEARBY_BLOCKS_LINES = 30 } } private fun getRangeDelta(range: Range, side: Side): Int { val otherSide = side.other() val deleted = range.end(side) - range.start(side) val inserted = range.end(otherSide) - range.start(otherSide) return inserted - deleted } private fun Block.shift(side: Side, delta: Int) = Block( shiftRange(this.range, side, delta), this.isDirty, this.isTooBig) private fun shiftRange(range: Range, side: Side, shift: Int) = when { side.isLeft -> shiftRange(range, shift, 0) else -> shiftRange(range, 0, shift) } private fun shiftRange(range: Range, shift1: Int, shift2: Int) = Range(range.start1 + shift1, range.end1 + shift1, range.start2 + shift2, range.end2 + shift2) private fun createRange(side: Side, start: Int, end: Int, otherStart: Int, otherEnd: Int): Range = when { side.isLeft -> Range(start, end, otherStart, otherEnd) else -> Range(otherStart, otherEnd, start, end) }
apache-2.0
a5461499f7ed649efdb75e9f5698f81f
29.964695
140
0.651303
4.380322
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/CategoryMemberContributor.kt
5
3258
// 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 org.jetbrains.plugins.groovy.lang.resolve import com.intellij.openapi.util.NlsSafe import com.intellij.psi.* import com.intellij.psi.scope.ElementClassHint import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.psi.util.PsiTypesUtil.getPsiClass import com.intellij.psi.util.PsiUtil.substituteTypeParameter import com.intellij.psi.util.parents import org.jetbrains.plugins.groovy.dgm.GdkMethodHolder.getHolderForClass import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember import org.jetbrains.plugins.groovy.lang.psi.impl.GrTupleType import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil.shouldProcessMethods import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint fun processCategoriesInScope(qualifierType: PsiType, processor: PsiScopeProcessor, place: PsiElement, state: ResolveState): Boolean { if (!shouldProcessMethods(processor.getHint(ElementClassHint.KEY))) return true for (parent in place.parents(true)) { if (parent is GrMember) break if (parent !is GrFunctionalExpression) continue val call = checkMethodCall(parent) ?: continue val categories = getCategoryClasses(call, parent) ?: continue val holders = categories.map { getHolderForClass(it, false) } val stateWithContext = state.put(ClassHint.RESOLVE_CONTEXT, call) for (category in holders) { if (!category.processMethods(processor, stateWithContext, qualifierType, place.project)) return false } } return true } private fun getCategoryClasses(call: GrMethodCall, closure: GrFunctionalExpression): List<PsiClass>? { val closures = call.closureArguments val args = call.expressionArguments if (args.isEmpty()) return null val lastArg = closure == args.last() if (!lastArg && closure != closures.singleOrNull()) return null if (call.resolveMethod() !is GrGdkMethod) return null if (args.size == 1 || args.size == 2 && lastArg) { val tupleType = args.first().type as? GrTupleType tupleType?.let { return it.componentTypes.mapNotNull { getPsiClass(substituteTypeParameter(it, CommonClassNames.JAVA_LANG_CLASS, 0, false)) } } } return args.mapNotNull { (it as? GrReferenceExpression)?.resolve() as? PsiClass } } @NlsSafe private const val USE = "use" private fun checkMethodCall(place: PsiElement): GrMethodCall? { val context = place.context val call = when (context) { is GrMethodCall -> context is GrArgumentList -> context.context as? GrMethodCall else -> null } if (call == null) return null val invoked = call.invokedExpression as? GrReferenceExpression if (invoked?.referenceName != USE) return null return call }
apache-2.0
b029b5da1ec37024be66f96b2d7a3acf
41.324675
140
0.774401
4.275591
false
false
false
false
smmribeiro/intellij-community
python/python-grazie/src/com/intellij/grazie/ide/language/python/PythonTextExtractor.kt
8
1826
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.grazie.ide.language.python import com.intellij.grazie.text.TextContent import com.intellij.grazie.text.TextContentBuilder import com.intellij.grazie.text.TextExtractor import com.intellij.grazie.utils.getNotSoDistantSimilarSiblings import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.impl.source.tree.PsiCommentImpl import com.intellij.psi.util.PsiUtilCore import com.jetbrains.python.PyTokenTypes import com.jetbrains.python.PyTokenTypes.FSTRING_TEXT import com.jetbrains.python.psi.PyFormattedStringElement internal class PythonTextExtractor : TextExtractor() { override fun buildTextContent(root: PsiElement, allowedDomains: MutableSet<TextContent.TextDomain>): TextContent? { val elementType = PsiUtilCore.getElementType(root) if (elementType in PyTokenTypes.STRING_NODES) { val domain = if (elementType == PyTokenTypes.DOCSTRING) TextContent.TextDomain.DOCUMENTATION else TextContent.TextDomain.LITERALS return TextContentBuilder.FromPsi.removingIndents(" \t").removingLineSuffixes(" \t").withUnknown(this::isUnknownFragment).build(root.parent, domain) } if (root is PsiCommentImpl) { val siblings = getNotSoDistantSimilarSiblings(root) { it is PsiCommentImpl } return TextContent.joinWithWhitespace('\n', siblings.mapNotNull { TextContent.builder().build(it, TextContent.TextDomain.COMMENTS) }) } return null } private fun isUnknownFragment(element: PsiElement): Boolean { if (element.parent is PyFormattedStringElement) { return element !is LeafPsiElement || element.elementType != FSTRING_TEXT } return false } }
apache-2.0
ca50bc3366529eff3032c0bb4f583a26
45.820513
154
0.790252
4.316785
false
false
false
false
mcilloni/kt-uplink
src/main/kotlin/Types.kt
1
2264
/* * uplink, a simple daemon to implement a simple chat protocol * Copyright (C) Marco Cilloni <[email protected]> 2016 * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * Exhibit B is not attached; this software is compatible with the * licenses expressed under Section 1.12 of the MPL v2. * */ package com.github.mcilloni.uplink import com.github.mcilloni.uplink.nano.UplinkProto import java.util.* class Message internal constructor (val tag: Long, val sender: String, val convID: Long, val body: String, val time : Date = Date()) { internal constructor(convID: Long, netMsg: UplinkProto.Message) : this( tag = netMsg.tag, sender = netMsg.senderName, convID = convID, body = netMsg.body, time = Date(netMsg.timestamp * 1000L) ) val svcMessage = sender == "uplink" override fun toString(): String{ return "Message(tag=$tag, sender='$sender', convID=$convID, body='$body', time=$time, svcMessage=$svcMessage)" } override fun equals(other: Any?): Boolean{ if (this === other) return true if (other?.javaClass != javaClass) return false other as Message if (tag != other.tag) return false if (sender != other.sender) return false if (convID != other.convID) return false if (body != other.body) return false if (time != other.time) return false if (svcMessage != other.svcMessage) return false return true } override fun hashCode(): Int{ var result = tag.hashCode() result = 31 * result + sender.hashCode() result = 31 * result + convID.hashCode() result = 31 * result + body.hashCode() result = 31 * result + time.hashCode() result = 31 * result + svcMessage.hashCode() return result } } data class Invite internal constructor (val fromUser: String, val toConv: String, val convID: Long) data class ConversationInvite internal constructor (val sender: String, val conv: Conversation)
mpl-2.0
4c8258ec43fb55d00519cdb41fe2dfe9
33.30303
118
0.632951
3.992945
false
false
false
false
TachiWeb/TachiWeb-Server
TachiServer/src/main/java/xyz/nulldev/ts/api/v2/java/impl/chapters/ChapterCollectionImpl.kt
1
1545
package xyz.nulldev.ts.api.v2.java.impl.chapters import eu.kanade.tachiyomi.data.database.DatabaseHelper import xyz.nulldev.ts.api.v2.java.impl.util.DbMapper import xyz.nulldev.ts.api.v2.java.impl.util.ProxyList import xyz.nulldev.ts.api.v2.java.model.chapters.ChapterCollection import xyz.nulldev.ts.api.v2.java.model.chapters.ChapterModel import xyz.nulldev.ts.api.v2.java.model.chapters.ReadingStatus import xyz.nulldev.ts.ext.kInstanceLazy class ChapterCollectionImpl(override val id: List<Long>): ChapterCollection, List<ChapterModel> by ProxyList(id, { ChapterCollectionProxy(it) }) { private val db: DatabaseHelper by kInstanceLazy() private val dbMapper = DbMapper( id, dbGetter = { db.getChapter(it).executeAsBlocking() }, dbSetter = { db.insertChapter(it).executeAsBlocking() } ) override var readingStatus: List<ReadingStatus?> get() = dbMapper.mapGet { ReadingStatus(it.last_page_read, it.read) } set(value) = dbMapper.mapSet(value) { chapter, status -> status.lastPageRead?.let { chapter.last_page_read = it } status.read?.let { chapter.read = it } } } class ChapterCollectionProxy(override val id: Long) : ChapterModel { private val collection = ChapterCollectionImpl(listOf(id)) override var readingStatus: ReadingStatus? get() = collection.readingStatus[0] set(value) { collection.readingStatus = listOf(value) } }
apache-2.0
bee4f0605ede4fb90da9c7a5e303dc41
35.809524
77
0.678964
3.843284
false
false
false
false
MaTriXy/gradle-play-publisher-1
play/android-publisher/src/main/kotlin/com/github/triplet/gradle/androidpublisher/internal/AndroidPublisher.kt
1
3713
package com.github.triplet.gradle.androidpublisher.internal import com.github.triplet.gradle.common.utils.PLUGIN_NAME import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport import com.google.api.client.googleapis.json.GoogleJsonResponseException import com.google.api.client.http.HttpRequest import com.google.api.client.http.HttpTransport import com.google.api.client.http.apache.v2.ApacheHttpTransport import com.google.api.client.http.javanet.NetHttpTransport import com.google.api.client.json.jackson2.JacksonFactory import com.google.api.services.androidpublisher.AndroidPublisher import com.google.api.services.androidpublisher.AndroidPublisherScopes import com.google.auth.http.HttpCredentialsAdapter import com.google.auth.oauth2.GoogleCredentials import org.apache.http.auth.AuthScope import org.apache.http.auth.UsernamePasswordCredentials import org.apache.http.impl.client.BasicCredentialsProvider import org.apache.http.impl.client.ProxyAuthenticationStrategy import java.io.FileInputStream import java.io.InputStream import java.security.KeyStore internal fun createPublisher(credentials: InputStream): AndroidPublisher { val transport = buildTransport() val credential = GoogleCredentials.fromStream(credentials) { transport } .createScoped(listOf(AndroidPublisherScopes.ANDROIDPUBLISHER)) return AndroidPublisher.Builder( transport, JacksonFactory.getDefaultInstance(), AndroidPublisherAdapter(credential) ).setApplicationName(PLUGIN_NAME).build() } internal infix fun GoogleJsonResponseException.has(error: String) = details?.errors.orEmpty().any { it.reason == error } private fun buildTransport(): HttpTransport { val trustStore: String? = System.getProperty("javax.net.ssl.trustStore", null) val trustStorePassword: String? = System.getProperty("javax.net.ssl.trustStorePassword", null) return if (trustStore == null) { createHttpTransport() } else { val ks = KeyStore.getInstance(KeyStore.getDefaultType()) FileInputStream(trustStore).use { fis -> ks.load(fis, trustStorePassword?.toCharArray()) } NetHttpTransport.Builder().trustCertificates(ks).build() } } private fun createHttpTransport() : HttpTransport { val protocols = arrayOf("http", "https") for (protocol in protocols) { val proxyHost = System.getProperty("$protocol.proxyHost") val proxyUser = System.getProperty("$protocol.proxyUser") val proxyPassword = System.getProperty("$protocol.proxyPassword"); if (proxyHost != null && proxyUser != null && proxyPassword != null) { val defaultProxyPort = if (protocol == "http") "80" else "443" val proxyPort = Integer.parseInt(System.getProperty("$protocol.proxyPort", defaultProxyPort)) val credentials = BasicCredentialsProvider() credentials.setCredentials( AuthScope(proxyHost, proxyPort), UsernamePasswordCredentials(proxyUser, proxyPassword) ) val httpClient = ApacheHttpTransport.newDefaultHttpClientBuilder() .setProxyAuthenticationStrategy(ProxyAuthenticationStrategy.INSTANCE) .setDefaultCredentialsProvider(credentials) .build() return ApacheHttpTransport(httpClient) } } return GoogleNetHttpTransport.newTrustedTransport() } private class AndroidPublisherAdapter( credential: GoogleCredentials ) : HttpCredentialsAdapter(credential) { override fun initialize(request: HttpRequest) { super.initialize(request.setReadTimeout(0)) } }
mit
413433e4923b0be5e843ed269d0c0823
43.202381
105
0.732831
4.705957
false
false
false
false
intrigus/jtransc
jtransc-core/src/com/jtransc/ast/ast_type.kt
1
21189
package com.jtransc.ast import com.jtransc.error.InvalidOperationException import com.jtransc.error.invalidArgument import com.jtransc.error.invalidOp import com.jtransc.error.noImpl import com.jtransc.injector.Singleton import com.jtransc.lang.toBool import com.jtransc.lang.toInt import com.jtransc.text.StrReader import com.jtransc.text.readUntil import java.io.Serializable import java.util.* open class AstType { abstract class Primitive( underlyingClassStr: String, val ch: Char, val shortName: String, val byteSize: Int, val priority: Int, val subsets: Set<Primitive> = setOf() ) : AstType() { //val underlyingClass: FqName = underlyingClassStr.fqname val CLASSTYPE = REF(underlyingClassStr) val chstring = "$ch" override fun hashCode() = ch.toInt() override fun equals(other: Any?): Boolean { if (other == null) return false; if (other !is Primitive) return false return Objects.equals(this.ch, (other as Primitive?)?.ch) } override fun toString() = shortName fun canHold(other: Primitive) = other in subsets } open class Reference : AstType() data class UNKNOWN(val reason: String) : Reference() object NULL : Reference() object VOID : Primitive("java.lang.Void", 'V', "void", 0, priority = 8, subsets = setOf()) object BOOL : Primitive("java.lang.Boolean", 'Z', "bool", 1, priority = 7, subsets = setOf()) object BYTE : Primitive("java.lang.Byte", 'B', "byte", 1, priority = 6, subsets = setOf(BOOL)) object CHAR : Primitive("java.lang.Character", 'C', "char", 2, priority = 5, subsets = setOf(BOOL)) object SHORT : Primitive("java.lang.Short", 'S', "short", 2, priority = 4, subsets = setOf(BOOL, BYTE)) object INT : Primitive("java.lang.Integer", 'I', "int", 4, priority = 3, subsets = setOf(BOOL, BYTE, CHAR, SHORT)) object LONG : Primitive("java.lang.Long", 'J', "long", 8, priority = 2, subsets = setOf(BOOL, BYTE, CHAR, SHORT, INT)) object FLOAT : Primitive("java.lang.Float", 'F', "float", 4, priority = 1, subsets = setOf(BOOL, BYTE, CHAR, SHORT)) object DOUBLE : Primitive("java.lang.Double", 'D', "double", 8, priority = 0, subsets = setOf(BOOL, BYTE, CHAR, SHORT, INT)) data class REF(val name: FqName) : Reference(), AstRef { constructor(name: String) : this(FqName(name)) init { if (fqname.contains(';') || fqname.contains(']')) { invalidOp("AstType.REF containing ; or ] :: $fqname") } } val fqname: String get() = name.fqname override fun hashCode(): Int = name.hashCode() override fun equals(other: Any?): Boolean { if (other == null || other !is REF) return false return Objects.equals(this.name, other.name) } override fun toString() = name.fqname } //object OBJECT : REF("java.lang.Object") //object NULL : REF("java.lang.Object") data class ARRAY(val element: AstType) : Reference() { override fun toString() = "$element[]" } data class COMMON(val elements: HashSet<AstType>) : AstType() { constructor(first: AstType) : this(HashSet()) { add(first) } val single: AstType? get() = if (elements.size == 1) elements.first() else null val singleOrInvalid: AstType get() = single ?: invalidArgument("Common type not resolved $elements") fun add(type: AstType) { if (type != this) { if (type is AstType.COMMON) { for (e in type.elements) add(e) } else { elements += type } } } override fun toString() = "COMMON($elements)" } data class MUTABLE(var ref: AstType) : AstType() { override fun toString() = "MUTABLE($ref)" } data class GENERIC(val type: AstType.REF, val suffixes: List<GENERIC_SUFFIX>, val dummy: Boolean) : Reference() { constructor(type: AstType.REF, params: List<AstType>) : this(type, listOf(GENERIC_SUFFIX(null, params)), true) val params0: List<AstType> get() = suffixes[0].params!! } data class GENERIC_SUFFIX(val id: String?, val params: List<AstType>?) data class TYPE_PARAMETER(val id: String) : AstType() object GENERIC_STAR : AstType() object GENERIC_ITEM : AstType() data class GENERIC_DESCRIPTOR(val element: AstType, val types: List<Pair<String, AstType>>) : AstType() data class GENERIC_LOWER_BOUND(val element: AstType) : AstType() data class GENERIC_UPPER_BOUND(val element: AstType) : AstType() data class METHOD(val ret: AstType, val args: List<AstArgument>, val dummy: Boolean, val paramTypes: List<Pair<String, AstType>> = listOf()) : AstType() { val argCount: Int get() = argTypes.size constructor(ret: AstType, argTypes: List<AstType>, paramTypes: List<Pair<String, AstType>> = listOf()) : this(ret, argTypes.toArguments(), true, paramTypes) constructor(args: List<AstArgument>, ret: AstType, paramTypes: List<Pair<String, AstType>> = listOf()) : this(ret, args, true, paramTypes) constructor(ret: AstType, vararg args: AstArgument, paramTypes: List<Pair<String, AstType>> = listOf()) : this(ret, args.toList(), true, paramTypes) constructor(ret: AstType, vararg args: AstType, paramTypes: List<Pair<String, AstType>> = listOf()) : this(args.withIndex().map { AstArgument(it.index, it.value) }, ret, paramTypes) val argNames by lazy { args.map { it.name } } val argTypes by lazy { args.map { it.type } } val desc by lazy { this.mangle(true) } val desc2 by lazy { this.mangle(false) } val retVoid by lazy { ret == AstType.VOID } val argsPlusReturn by lazy { argTypes + listOf(ret) } val argsPlusReturnVoidIsEmpty by lazy { if (argTypes.isEmpty()) { listOf(AstType.VOID, ret) } else { argTypes + listOf(ret) } } val withoutRetval: AstType.METHOD get() = AstType.METHOD(AstType.UNKNOWN("No retval"), argTypes, paramTypes) override fun hashCode() = desc.hashCode(); override fun equals(other: Any?) = Objects.equals(this.desc, (other as METHOD?)?.desc) override fun toString() = ret.toString() + " (" + args.joinToString(", ") + ")" } companion object { val THROWABLE = AstType.REF("java.lang.Throwable") val STRING = AstType.REF("java.lang.String") val STRINGBUILDER = AstType.REF("java.lang.StringBuilder") val OBJECT = AstType.REF("java.lang.Object") val CLASS = AstType.REF("java.lang.Class") fun fromConstant(value: Any?): AstType = when (value) { null -> AstType.NULL is Boolean -> AstType.BOOL is Byte -> AstType.BYTE is Char -> AstType.CHAR is Short -> AstType.SHORT is Int -> AstType.INT is Long -> AstType.LONG is Float -> AstType.FLOAT is Double -> AstType.DOUBLE is String -> AstType.STRING is AstType.ARRAY -> AstType.CLASS is AstType.REF -> AstType.CLASS is AstType.METHOD -> AstType.CLASS // @TODO: Probably java.lang...MethodHandle or something like this! is AstMethodHandle -> AstType.CLASS // @TODO: Probably java.lang...MethodHandle or something like this! else -> invalidOp("Literal type: ${value.javaClass} : $value") } } } fun AstType.asArray(): AstType.ARRAY { if (this !is AstType.ARRAY) invalidOp("$this is not AstType.ARRAY") return this } fun AstType.asReference(): AstType.Reference { if (this !is AstType.Reference) invalidOp("$this is not AstType.Reference") return this } fun AstType.asREF(): AstType.REF { if (this !is AstType.REF) invalidOp("$this is not AstType.REF") return this } fun ARRAY(type: AstType) = AstType.ARRAY(type) @Singleton class AstTypes { private val AstTypeDemangleCache = hashMapOf<String, AstType>() fun fromConstant(value: Any?): AstType = AstType.fromConstant(value) fun ARRAY(element: AstType, count: Int): AstType.ARRAY = if (count <= 1) AstType.ARRAY(element) else ARRAY(AstType.ARRAY(element), count - 1) fun REF_INT(internalName: String): AstType = if (internalName.startsWith("[")) demangle(internalName) else REF_INT2(internalName) fun REF_INT2(internalName: String): AstType.REF = AstType.REF(internalName.replace('/', '.')) fun REF_INT3(internalName: String?): AstType.REF? = if (internalName != null) REF_INT2(internalName) else null fun demangle(desc: String): AstType = AstTypeDemangleCache.getOrPut(desc) { this.readOne(StrReader(desc)) } fun demangleMethod(text: String): AstType.METHOD = demangle(text) as AstType.METHOD fun <T : AstType> build(init: AstTypeBuilder.() -> T): T = AstTypeBuilder.init() // @TODO: implement unification fun unify(a: AstType, b: AstType): AstType = a // http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-TypeVariableSignature fun readOne(reader: StrReader): AstType { if (reader.eof) return AstType.UNKNOWN("demangling eof") val typech = reader.readch() return when (typech) { 'V' -> AstType.VOID 'Z' -> AstType.BOOL 'B' -> AstType.BYTE 'C' -> AstType.CHAR 'S' -> AstType.SHORT 'D' -> AstType.DOUBLE 'F' -> AstType.FLOAT 'I' -> AstType.INT 'J' -> AstType.LONG '[' -> AstType.ARRAY(readOne(reader)) '*' -> AstType.GENERIC_STAR '-' -> AstType.GENERIC_LOWER_BOUND(readOne(reader)) '+' -> AstType.GENERIC_UPPER_BOUND(readOne(reader)) 'T' -> { val id = reader.readUntil(T_DELIMITER, including = false, readDelimiter = true) AstType.TYPE_PARAMETER(id) } 'L' -> { val base = reader.readUntil(REF_DELIMITER, including = false, readDelimiter = false) val delim = reader.readch() val ref = AstType.REF(base.replace('/', '.')) when (delim) { ';' -> ref '<' -> { var index = 0 val suffixes = arrayListOf<AstType.GENERIC_SUFFIX>(); mainGenerics@ while (reader.hasMore) { val id = if (reader.peekch() == '.') { reader.readch() val id = reader.readUntil(REF_DELIMITER, including = false, readDelimiter = false) val ch = reader.readch() when (ch) { '<' -> id ';' -> { suffixes += AstType.GENERIC_SUFFIX(id, null) break@mainGenerics } else -> invalidOp("Expected > or ; but found $ch on reader $reader") } } else { null } val generic = arrayListOf<AstType>() mainGeneric@ while (reader.hasMore) { val ch = reader.peekch() if (ch == '>') { reader.expect(">") when (reader.peekch()) { '.' -> break@mainGeneric ';' -> break@mainGeneric } break } else { generic.add(readOne(reader)) } } index++ suffixes += AstType.GENERIC_SUFFIX(id, generic) if (reader.peekch() == ';') { reader.expect(";") break } } AstType.GENERIC(ref, suffixes, true) } else -> throw InvalidOperationException() } } // PARAMETRIZED TYPE '<' -> { val types = arrayListOf<Pair<String, AstType>>() while (reader.peekch() != '>') { val id = reader.readUntil(TYPE_DELIMITER, including = false, readDelimiter = false) reader.expect(":") if (reader.peekch() == ':') { reader.readch() } types += Pair(id, this.readOne(reader)) } reader.expect(">") val item = this.readOne(reader) if (item is AstType.METHOD) { AstType.METHOD(item.ret, item.argTypes, types) } else { AstType.GENERIC_DESCRIPTOR(item, types) } } '(' -> { val args = arrayListOf<AstType>() while (reader.peekch() != ')') { args.add(readOne(reader)) } assert(reader.readch() == ')') val ret = readOne(reader) AstType.METHOD(ret, args) } else -> { throw NotImplementedError("Not implemented type '$typech' @ $reader") } } } } fun _castLiteral(value: Int, to: AstType): Any = when (to) { AstType.BOOL -> value.toBool() AstType.BYTE -> value.toByte() AstType.CHAR -> value.toChar() AstType.SHORT -> value.toShort() AstType.INT -> value.toInt() AstType.LONG -> value.toLong() AstType.FLOAT -> value.toFloat() AstType.DOUBLE -> value.toDouble() //is AstType.Reference -> null else -> invalidOp("Can't cast $value to $to") } fun <T> Class<T>.ref() = AstType.REF(this.name) fun _castLiteral(value: Long, to: AstType): Any = when (to) { AstType.BOOL -> value.toBool() AstType.BYTE -> value.toByte() AstType.CHAR -> value.toChar() AstType.SHORT -> value.toShort() AstType.INT -> value.toInt() AstType.LONG -> value.toLong() AstType.FLOAT -> value.toFloat() AstType.DOUBLE -> value.toDouble() else -> invalidOp("Can't cast $value to $to") } fun _castLiteral(value: Float, to: AstType): Any = when (to) { AstType.BOOL -> value.toBool() AstType.BYTE -> value.toByte() AstType.CHAR -> value.toChar() AstType.SHORT -> value.toShort() AstType.INT -> value.toInt() AstType.LONG -> value.toLong() AstType.FLOAT -> value.toFloat() AstType.DOUBLE -> value.toDouble() else -> invalidOp("Can't cast $value to $to") } fun _castLiteral(value: Double, to: AstType): Any = when (to) { AstType.BOOL -> value.toBool() AstType.BYTE -> value.toByte() AstType.CHAR -> value.toChar() AstType.SHORT -> value.toShort() AstType.INT -> value.toInt() AstType.LONG -> value.toLong() AstType.FLOAT -> value.toFloat() AstType.DOUBLE -> value.toDouble() else -> invalidOp("Can't cast $value to $to") } fun Boolean.castTo(to: AstType) = _castLiteral(this.toInt(), to) fun Byte.castTo(to: AstType) = _castLiteral(this.toInt(), to) fun Char.castTo(to: AstType) = _castLiteral(this.toInt(), to) fun Short.castTo(to: AstType) = _castLiteral(this.toInt(), to) fun Int.castTo(to: AstType) = _castLiteral(this, to) fun Long.castTo(to: AstType) = _castLiteral(this, to) fun Float.castTo(to: AstType) = _castLiteral(this, to) fun Double.castTo(to: AstType) = _castLiteral(this, to) fun Iterable<AstType>.toArguments(): List<AstArgument> = this.mapIndexed { i, v -> AstArgument(i, v) } fun AstType.getNull(): Any? = when (this) { is AstType.VOID -> null is AstType.BOOL -> false is AstType.INT -> 0.toInt() is AstType.SHORT -> 0.toShort() is AstType.CHAR -> 0.toChar() is AstType.BYTE -> 0.toByte() is AstType.LONG -> 0.toLong() is AstType.FLOAT -> 0f.toFloat() is AstType.DOUBLE -> 0.0.toDouble() is AstType.UNKNOWN -> { println("Referenced UNKNOWN") null } is AstType.REF, is AstType.ARRAY, is AstType.NULL -> null is AstType.COMMON -> this.elements.firstOrNull()?.getNull() else -> noImpl("Not supported type $this") } //fun AstType.getNullCompact(): Any? = when(this) { // is AstType.BOOL -> false // is AstType.INT, is AstType.SHORT, is AstType.CHAR, is AstType.BYTE -> 0 // is AstType.LONG -> 0L // is AstType.FLOAT, is AstType.DOUBLE -> 0.0 // is AstType.REF, is AstType.ARRAY, is AstType.NULL -> null // else -> noImpl("Not supported type $this") //} data class AstArgument(val index: Int, val type: AstType, override val name: String = "p$index", val optional: Boolean = false) : ArgumentRef { override fun toString() = "$type $name" } data class FqName(val fqname: String) : Serializable { constructor(packagePath: String, simpleName: String) : this("$packagePath.$simpleName".trim('.')) constructor(packageParts: List<String>, simpleName: String) : this("${packageParts.joinToString(".")}.$simpleName".trim('.')) constructor(parts: List<String>) : this(parts.joinToString(".").trim('.')) companion object { fun fromInternal(internalName: String): FqName { return FqName(internalName.replace('/', '.')) } } init { //if (fqname.isNullOrBlank()) invalidOp("Fqname is empty!") if (!fqname.isEmpty()) { val f = fqname.first() //if (!f.isLetterOrUnderscore()) { if ((f == '(') || (f == '[') || ('/' in fqname)) { invalidOp("Invalid classname '$fqname'") } } } val parts: List<String> get() = fqname.split('.') val packageParts: List<String> get() = packagePath.split('.') val packagePath by lazy { fqname.substringBeforeLast('.', "") } val simpleName by lazy { fqname.substringAfterLast('.') } val internalFqname by lazy { fqname.replace('.', '/') } val pathToClass by lazy { "$internalFqname.class" } fun withPackagePath(packagePath: String) = FqName(packagePath, simpleName) fun withPackageParts(packageParts: List<String>) = FqName(packageParts, simpleName) fun withSimpleName(simpleName: String) = FqName(packagePath, simpleName) override fun toString() = fqname override fun hashCode(): Int = fqname.hashCode() override fun equals(other: Any?): Boolean = this.fqname == (other as? FqName)?.fqname fun append(s: String): FqName = FqName(this.fqname + s) } val Class<*>.fqname: FqName get() = FqName(this.name) val String.fqname: FqName get() = FqName(this) val FqName.ref: AstType.REF get() = AstType.REF(this) fun AstType.isPrimitive() = (this is AstType.Primitive) fun AstType.isNotPrimitive() = (this !is AstType.Primitive) fun AstType.isReference() = (this is AstType.Reference) fun AstType.isREF() = (this is AstType.REF) fun AstType.isArray() = (this is AstType.ARRAY) fun AstType.isFloating() = (this == AstType.FLOAT) || (this == AstType.DOUBLE) fun AstType.isLongOrDouble() = (this == AstType.LONG) || (this == AstType.DOUBLE) object AstTypeBuilder { val STRING = AstType.STRING val OBJECT = AstType.OBJECT val CLASS = AstType.CLASS val METHOD = AstType.REF("java.lang.reflect.Method") val NULL = AstType.NULL val VOID = AstType.VOID val BOOL = AstType.BOOL val BYTE = AstType.BYTE val CHAR = AstType.CHAR val SHORT = AstType.SHORT val INT = AstType.INT val LONG = AstType.LONG val FLOAT = AstType.FLOAT val DOUBLE = AstType.DOUBLE fun REF(name: FqName) = AstType.REF(name) fun ARRAY(element: AstType) = AstType.ARRAY(element) fun ARRAY(element: AstClass) = AstType.ARRAY(element.ref) //fun ARRAY(element: AstType, dimensions: Int = 1) = AstType.ARRAY(element, dimensions) //fun GENERIC(type: AstType.REF, params: List<AstType>) = AstType.GENERIC(type, params) fun METHOD(args: List<AstArgument>, ret: AstType) = AstType.METHOD(args, ret) fun METHOD(ret: AstType, vararg args: AstType) = AstType.METHOD(ret, args.toList()) } fun <T : AstType> AstTypeBuild(init: AstTypeBuilder.() -> T): T = AstTypeBuilder.init() val REF_DELIMITER = setOf(';', '<') val REF_DELIMITER2 = setOf(';', '<', '.') val T_DELIMITER = setOf(';') val TYPE_DELIMITER = setOf(':', '>') val AstType.elementType: AstType get() = when (this) { is AstType.ARRAY -> this.element is AstType.GENERIC -> this.suffixes[0].params!![0] is AstType.COMMON -> this.singleOrInvalid.elementType else -> invalidArgument("Type is not an array: $this") } fun AstType.mangleExt(retval: Boolean = true): String = when (this) { is AstType.COMMON -> { if (this.elements.size == 1) { this.elements.first().mangleExt(retval) } else { "COMMON(" + this.elements.map { it.mangleExt(retval) } + ")" } } is AstType.MUTABLE -> this.ref.mangleExt(retval) else -> mangle(retval) } fun AstType.mangle(retval: Boolean = true): String = when (this) { is AstType.Primitive -> this.chstring is AstType.GENERIC -> "L" + type.name.internalFqname + this.suffixes.map { (it.id ?: "") + (if (it.params != null) "<" + it.params.map { it.mangle(retval) }.joinToString("") + ">" else "") }.joinToString(".") + ";" is AstType.REF -> "L" + name.internalFqname + ";" is AstType.ARRAY -> "[" + element.mangle(retval) is AstType.GENERIC_STAR -> "*" is AstType.GENERIC_LOWER_BOUND -> "-" + this.element.mangle(retval) is AstType.GENERIC_UPPER_BOUND -> "+" + this.element.mangle(retval) is AstType.TYPE_PARAMETER -> "T" + this.id + ";" is AstType.GENERIC_DESCRIPTOR -> { "<" + this.types.map { it.first + ":" + it.second.mangle(retval) }.joinToString("") + ">" + this.element.mangle(retval) } is AstType.METHOD -> { val param = if (this.paramTypes.isNotEmpty()) { "<" + this.paramTypes.map { it.first + ":" + it.second.mangle(retval) }.joinToString("") + ">" } else { "" } val args = "(" + argTypes.map { it.mangle(retval) }.joinToString("") + ")" if (retval) { param + args + ret.mangle(retval) } else { param + args } } is AstType.COMMON -> { if (this.elements.size == 1) { this.elements.first().mangle(retval) } else { throw RuntimeException("Can't mangle common with several types: ${this.elements}. Resolve COMMONS first.") } } is AstType.UNKNOWN -> { //throw RuntimeException("Can't mangle unknown") "!!UNKNOWN!!" } else -> throw RuntimeException("Don't know how to mangle $this") } fun AstType.getRefTypes(): List<AstType.REF> = this.getRefTypesFqName().map { AstType.REF(it) } fun AstType.getRefTypesFqName(): List<FqName> = when (this) { is AstType.REF -> listOf(this.name) is AstType.ARRAY -> this.element.getRefTypesFqName() is AstType.METHOD -> { //if (this.paramTypes.isNotEmpty()) println(":::::::: " + this.paramTypes) this.argTypes.flatMap { it.getRefTypesFqName() } + this.ret.getRefTypesFqName() + this.paramTypes.flatMap { it.second.getRefTypesFqName() } } is AstType.GENERIC -> { this.type.getRefTypesFqName() + this.suffixes.flatMap { it.params ?: listOf() }.flatMap { it.getRefTypesFqName() } } is AstType.Primitive, is AstType.UNKNOWN, is AstType.NULL -> listOf() is AstType.TYPE_PARAMETER -> listOf() is AstType.GENERIC_STAR -> listOf() is AstType.GENERIC_LOWER_BOUND -> this.element.getRefTypesFqName() is AstType.GENERIC_UPPER_BOUND -> this.element.getRefTypesFqName() is AstType.COMMON -> this.elements.flatMap { it.getRefTypesFqName() } is AstType.MUTABLE -> this.ref.getRefTypesFqName() else -> noImpl("AstType.getRefTypesFqName: $this") }
apache-2.0
d7e44586426aca5459b684bc7ab4cb92
34.25624
183
0.668743
3.345808
false
false
false
false
JakeWharton/dex-method-list
diffuse/src/main/kotlin/com/jakewharton/diffuse/Manifest.kt
1
8670
package com.jakewharton.diffuse import com.android.aapt.Resources.XmlNode import com.android.tools.build.bundletool.model.utils.xmlproto.XmlProtoNode import com.android.tools.build.bundletool.xml.XmlProtoToXmlConverter import com.google.devrel.gmscore.tools.apk.arsc.BinaryResourceFile import com.google.devrel.gmscore.tools.apk.arsc.BinaryResourceValue.Type.INT_BOOLEAN import com.google.devrel.gmscore.tools.apk.arsc.BinaryResourceValue.Type.INT_COLOR_ARGB4 import com.google.devrel.gmscore.tools.apk.arsc.BinaryResourceValue.Type.INT_COLOR_ARGB8 import com.google.devrel.gmscore.tools.apk.arsc.BinaryResourceValue.Type.INT_COLOR_RGB4 import com.google.devrel.gmscore.tools.apk.arsc.BinaryResourceValue.Type.INT_COLOR_RGB8 import com.google.devrel.gmscore.tools.apk.arsc.BinaryResourceValue.Type.INT_DEC import com.google.devrel.gmscore.tools.apk.arsc.BinaryResourceValue.Type.INT_HEX import com.google.devrel.gmscore.tools.apk.arsc.BinaryResourceValue.Type.NULL import com.google.devrel.gmscore.tools.apk.arsc.BinaryResourceValue.Type.REFERENCE import com.google.devrel.gmscore.tools.apk.arsc.BinaryResourceValue.Type.STRING import com.google.devrel.gmscore.tools.apk.arsc.XmlChunk import com.google.devrel.gmscore.tools.apk.arsc.XmlEndElementChunk import com.google.devrel.gmscore.tools.apk.arsc.XmlNamespaceStartChunk import com.google.devrel.gmscore.tools.apk.arsc.XmlStartElementChunk import com.jakewharton.diffuse.io.Input import java.io.StringReader import java.util.ArrayDeque import javax.xml.parsers.DocumentBuilderFactory import javax.xml.xpath.XPathConstants import javax.xml.xpath.XPathFactory import org.w3c.dom.Document import org.w3c.dom.Element import org.w3c.dom.NamedNodeMap import org.w3c.dom.Node import org.w3c.dom.NodeList import org.xml.sax.InputSource class Manifest private constructor( val xml: String, val packageName: String, val versionName: String?, val versionCode: Long? ) { companion object { private val documentBuilderFactory = DocumentBuilderFactory.newInstance()!! .apply { isNamespaceAware = true } internal fun BinaryResourceFile.toManifest(arsc: Arsc? = null): Manifest { return toDocument(arsc).toManifest() } @JvmStatic @JvmName("parse") fun String.toManifest(): Manifest = toDocument().toManifest() @JvmStatic @JvmName("parse") fun Input.toManifest(): Manifest = toUtf8().toManifest() internal fun XmlNode.toManifest(): Manifest { return XmlProtoToXmlConverter.convert(XmlProtoNode(this)) .apply { normalizeWhitespace() } .toManifest() } private fun BinaryResourceFile.toDocument(arsc: Arsc?): Document { val rootChunk = requireNotNull(chunks.singleOrNull() as XmlChunk?) { "Unable to parse manifest from binary XML" } val document = documentBuilderFactory .newDocumentBuilder() .newDocument() val nodeStack = ArrayDeque<Node>().apply { add(document) } val namespacesToAdd = mutableMapOf<String, String>() val namespacesInScope = mutableMapOf<String?, String>(null to "") rootChunk.chunks.values.forEach { chunk -> when (chunk) { is XmlNamespaceStartChunk -> { check(namespacesToAdd.put(chunk.prefix, chunk.uri) == null) check(namespacesInScope.put(chunk.uri, "${chunk.prefix}:") == null) } is XmlStartElementChunk -> { val canonicalNamespace = chunk.namespace.takeIf(String::isNotEmpty) val canonicalName = namespacesInScope[canonicalNamespace] + chunk.name val element = document.createElementNS(canonicalNamespace, canonicalName) if (namespacesToAdd.isNotEmpty()) { namespacesToAdd.forEach { (prefix, uri) -> element.setAttribute("xmlns:$prefix", uri) } namespacesToAdd.clear() } for (attribute in chunk.attributes) { val attributeNamespace = attribute.namespace().takeIf(String::isNotEmpty) val attributeName = namespacesInScope[attributeNamespace] + attribute.name() val typedValue = attribute.typedValue() val attributeValue = when (typedValue.type()) { INT_BOOLEAN -> if (typedValue.data() == 0) "false" else "true" INT_COLOR_ARGB4 -> String.format("#%04x", typedValue.data()) INT_COLOR_ARGB8 -> String.format("#%08x", typedValue.data()) INT_COLOR_RGB4 -> String.format("#%03x", typedValue.data()) INT_COLOR_RGB8 -> String.format("#%06x", typedValue.data()) INT_DEC -> typedValue.data().toString() INT_HEX -> "0x${typedValue.data()}" REFERENCE -> { if (arsc != null) "@${arsc.entries[typedValue.data()]}" else typedValue.data().toString() } NULL -> "null" STRING -> attribute.rawValue() // TODO handle other formats appropriately... else -> typedValue.data().toString() } element.setAttributeNS(attributeNamespace, attributeName, attributeValue) } nodeStack.peekFirst()!!.appendChild(element) nodeStack.addFirst(element) } is XmlEndElementChunk -> { nodeStack.removeFirst() } } } return document } private fun String.toDocument(): Document { return documentBuilderFactory.newDocumentBuilder() .parse(InputSource(StringReader(this))) .apply { normalizeWhitespace() } } private fun Document.normalizeWhitespace() { normalize() val emptyNodes = XPathFactory.newInstance().newXPath().evaluate( "//text()[normalize-space()='']", this, XPathConstants.NODESET ) as NodeList for (emptyNode in emptyNodes) { emptyNode.parentNode.removeChild(emptyNode) } } private fun Document.toManifest(): Manifest { val manifestElement = documentElement require(manifestElement.tagName == "manifest") { "Unable to find root <manifest> tag" } val packageName = manifestElement.getAttribute("package") val versionName = manifestElement.getAttributeOrNull(ANDROID_NS, "versionName") val versionCodeMinor = manifestElement.getAttributeOrNull(ANDROID_NS, "versionCode")?.toInt() val versionCodeMajor = manifestElement.getAttributeOrNull(ANDROID_NS, "versionCodeMajor")?.toInt() ?: 0 val versionCode = if (versionCodeMinor != null) { (versionCodeMajor.toLong() shl 32) + versionCodeMinor } else { null } return Manifest(toFormattedXml(), packageName, versionName, versionCode) } private fun Document.toFormattedXml() = buildString { fun appendIndent(indent: Int) { repeat(indent) { append(" ") } } fun appendNode(node: Node, indent: Int) { appendIndent(indent) append('<') append(node.nodeName) if (node.hasAttributes()) { // TODO sort attributes // xmlns: should be first // otherwise alphabetical for (attribute in node.attributes) { appendln() appendIndent(indent + 2) append(attribute.nodeName) append("=\"") append(attribute.nodeValue) append('"') } appendln() appendIndent(indent + 2) } if (!node.hasChildNodes()) { append('/') } appendln('>') if (node.hasChildNodes()) { for (child in node.childNodes) { appendNode(child, indent + 1) } appendIndent(indent) append("</") append(node.nodeName) appendln('>') } } appendNode(documentElement, 0) } private operator fun NodeList.iterator() = object : Iterator<Node> { private var index = 0 override fun hasNext() = index < length override fun next() = item(index++) } private operator fun NamedNodeMap.iterator() = object : Iterator<Node> { private var index = 0 override fun hasNext() = index < length override fun next() = item(index++) } private fun Element.getAttributeOrNull(namespace: String?, name: String): String? { return if (hasAttributeNS(namespace, name)) { getAttributeNS(namespace, name) } else { null } } private const val ANDROID_NS = "http://schemas.android.com/apk/res/android" } }
apache-2.0
506e296dc07ee3d88e1ce19215d8b224
36.37069
109
0.64579
4.423469
false
false
false
false
quran/quran_android
feature/downloadmanager/src/main/kotlin/com/quran/mobile/feature/downloadmanager/ui/sheikhdownload/SheikhDownloadToolbar.kt
2
2024
package com.quran.mobile.feature.downloadmanager.ui.sheikhdownload import androidx.compose.foundation.layout.RowScope import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import com.quran.mobile.feature.downloadmanager.R import com.quran.mobile.feature.downloadmanager.ui.DownloadManagerToolbar @Composable fun SheikhDownloadToolbar( titleResource: Int, isContextual: Boolean, downloadIcon: Boolean, removeIcon: Boolean, downloadAction: (() -> Unit), eraseAction: (() -> Unit), onBackAction: (() -> Unit) ) { val backgroundColor = if (isContextual) MaterialTheme.colorScheme.secondary else MaterialTheme.colorScheme.primary val tintColor = if (isContextual) MaterialTheme.colorScheme.onSecondary else MaterialTheme.colorScheme.onPrimary val actions: @Composable() (RowScope.() -> Unit) = { if (downloadIcon) { IconButton(onClick = downloadAction) { val contentDescription = if (isContextual) R.string.audio_manager_download_selection else R.string.audio_manager_download_all Icon( painterResource(id = R.drawable.ic_download), contentDescription = stringResource(id = contentDescription), tint = tintColor ) } } if (removeIcon) { IconButton(onClick = eraseAction) { Icon( imageVector = Icons.Filled.Close, contentDescription = stringResource(id = R.string.audio_manager_delete_selection), tint = tintColor ) } } } DownloadManagerToolbar( title = if (isContextual) "" else stringResource(titleResource), backgroundColor = backgroundColor, tintColor = tintColor, onBackPressed = onBackAction, actions = actions ) }
gpl-3.0
4e63921c70eddb98582c460daffb87ab
32.733333
133
0.732708
4.527964
false
false
false
false
fossasia/rp15
app/src/main/java/org/fossasia/openevent/general/event/EventService.kt
1
6743
package org.fossasia.openevent.general.event import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.Single import org.fossasia.openevent.general.event.faq.EventFAQ import org.fossasia.openevent.general.event.faq.EventFAQApi import org.fossasia.openevent.general.event.location.EventLocation import org.fossasia.openevent.general.event.location.EventLocationApi import org.fossasia.openevent.general.event.topic.EventTopic import org.fossasia.openevent.general.event.topic.EventTopicApi import org.fossasia.openevent.general.event.topic.EventTopicsDao import org.fossasia.openevent.general.event.types.EventType import org.fossasia.openevent.general.event.types.EventTypesApi import org.fossasia.openevent.general.favorite.FavoriteEvent import org.fossasia.openevent.general.favorite.FavoriteEventApi import org.fossasia.openevent.general.sessions.track.Track import org.fossasia.openevent.general.speakercall.SpeakersCall import org.fossasia.openevent.general.speakercall.SpeakersCallDao import org.jetbrains.anko.collections.forEachWithIndex import java.util.Date class EventService( private val eventApi: EventApi, private val eventDao: EventDao, private val eventTopicApi: EventTopicApi, private val eventTopicsDao: EventTopicsDao, private val eventTypesApi: EventTypesApi, private val eventLocationApi: EventLocationApi, private val eventFAQApi: EventFAQApi, private val speakersCallDao: SpeakersCallDao, private val favoriteEventApi: FavoriteEventApi ) { fun getEventLocations(): Single<List<EventLocation>> { return eventLocationApi.getEventLocation() } fun getEventFAQs(id: Long): Single<List<EventFAQ>> { return eventFAQApi.getEventFAQ(id) } private fun getEventTopicList(eventsList: List<Event>): List<EventTopic?> { return eventsList .filter { it.eventTopic != null } .map { it.eventTopic } .toList() } fun getEventTypes(): Single<List<EventType>> { return eventTypesApi.getEventTypes() } fun getSearchEventsPaged(filter: String, sortBy: String, page: Int): Flowable<List<Event>> { return eventApi.searchEventsPaged(sortBy, filter, page).flatMapPublisher { eventsList -> eventsList.forEach { it.speakersCall?.let { sc -> speakersCallDao.insertSpeakerCall(sc) } } updateFavorites(eventsList) } } fun getFavoriteEvents(): Flowable<List<Event>> { return eventDao.getFavoriteEvents() } fun getEventsByLocationPaged(locationName: String?, page: Int, pageSize: Int = 5): Flowable<List<Event>> { val query = "[{\"name\":\"location-name\",\"op\":\"ilike\",\"val\":\"%$locationName%\"}," + "{\"name\":\"ends-at\",\"op\":\"ge\",\"val\":\"%${EventUtils.getTimeInISO8601(Date())}%\"}]" return eventApi.searchEventsPaged("name", query, page, pageSize).flatMapPublisher { apiList -> updateFavorites(apiList) } } private fun updateFavorites(apiList: List<Event>): Flowable<List<Event>> { val ids = apiList.map { it.id }.toList() eventTopicsDao.insertEventTopics(getEventTopicList(apiList)) return eventDao.getFavoriteEventWithinIds(ids) .flatMapPublisher { favEvents -> val favEventIdsList = favEvents.map { it.id } val favEventFavIdsList = favEvents.map { it.favoriteEventId } apiList.map { val index = favEventIdsList.indexOf(it.id) if (index != -1) { it.favorite = true it.favoriteEventId = favEventFavIdsList[index] } } eventDao.insertEvents(apiList) val eventIds = apiList.map { it.id }.toList() eventDao.getEventWithIds(eventIds) } } fun getEvent(id: Long): Flowable<Event> { return eventDao.getEvent(id) } fun getEventByIdentifier(identifier: String): Single<Event> { return eventApi.getEventFromApi(identifier) } fun getEventById(eventId: Long): Single<Event> { return eventDao.getEventById(eventId) .onErrorResumeNext { eventApi.getEventFromApi(eventId.toString()).map { eventDao.insertEvent(it) it } } } fun getEventsWithQuery(query: String): Single<List<Event>> { return eventApi.eventsByQuery(query).map { eventDao.insertEvents(it) it } } fun loadFavoriteEvent(): Single<List<FavoriteEvent>> = favoriteEventApi.getFavorites() fun saveFavoritesEventFromApi(favIdsList: List<FavoriteEvent>): Single<List<Event>> { val idsList = favIdsList.filter { it.event != null }.map { it.event!!.id } val query = """[{ | 'and':[{ | 'name':'id', | 'op':'in', | 'val': $idsList | }] |}]""".trimMargin().replace("'", "\"") return eventApi.eventsWithQuery(query).map { it.forEachWithIndex { index, event -> event.favoriteEventId = favIdsList[index].id event.favorite = true eventDao.insertEvent(event) } it } } fun addFavorite(favoriteEvent: FavoriteEvent, event: Event) = favoriteEventApi.addFavorite(favoriteEvent).map { event.favoriteEventId = it.id event.favorite = true eventDao.insertEvent(event) it } fun removeFavorite(favoriteEvent: FavoriteEvent, event: Event): Completable = favoriteEventApi.removeFavorite(favoriteEvent.id).andThen { event.favorite = false event.favoriteEventId = null eventDao.insertEvent(event) } fun getSimilarEventsPaged(id: Long, page: Int, pageSize: Int = 5): Flowable<List<Event>> { val filter = "[{\"name\":\"ends-at\",\"op\":\"ge\",\"val\":\"%${EventUtils.getTimeInISO8601(Date())}%\"}]" return eventTopicApi.getEventsUnderTopicIdPaged(id, filter, page, pageSize) .flatMapPublisher { updateFavorites(it) } } fun getSpeakerCall(id: Long): Single<SpeakersCall> = speakersCallDao.getSpeakerCall(id).onErrorResumeNext { eventApi.getSpeakerCallForEvent(id).doAfterSuccess { speakersCallDao.insertSpeakerCall(it) } } fun fetchTracksUnderEvent(eventId: Long): Single<List<Track>> = eventApi.fetchTracksUnderEvent(eventId) }
apache-2.0
7174abe08cce8904c08736a12b436e10
37.976879
114
0.636067
4.471485
false
false
false
false
cmcpasserby/MayaCharm
src/main/kotlin/debugattach/MayaAttachToProcessDebugRunner.kt
1
2794
package debugattach import MayaBundle as Loc import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.IconLoader import com.intellij.xdebugger.XDebugProcess import com.intellij.xdebugger.XDebugProcessStarter import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.XDebuggerManager import com.jetbrains.python.debugger.PyDebugRunner import com.jetbrains.python.debugger.PyLocalPositionConverter import com.jetbrains.python.debugger.attach.PyAttachToProcessDebugRunner import run.MayaCharmDebugProcess import settings.ApplicationSettings import java.io.IOException import java.net.ServerSocket class MayaAttachToProcessDebugRunner( private val project: Project, private val pid: Int, private val sdkPath: String?, private val mayaSdk: ApplicationSettings.SdkInfo ) : PyAttachToProcessDebugRunner(project, pid, sdkPath) { override fun launch(): XDebugSession? { FileDocumentManager.getInstance().saveAllDocuments() return launchRemoteDebugServer() } private fun getDebuggerSocket(): ServerSocket? { var portSocket: ServerSocket? = null try { portSocket = ServerSocket(0) } catch (e: IOException) { e.printStackTrace() Messages.showErrorDialog( Loc.message("mayacharm.debugattachproc.FailedFindPort"), Loc.message("mayacharm.debugattachproc.FailedFindPortTitle") ) } return portSocket } private fun launchRemoteDebugServer(): XDebugSession? { val serverSocket = getDebuggerSocket() ?: return null val state = MayaAttachToProcessCliState.create(project, sdkPath!!, serverSocket.localPort, pid, mayaSdk) val result = state.execute(state.environment.executor, this) val icon = IconLoader.getIcon("/icons/MayaCharm_ToolWindow.png", this::class.java) return XDebuggerManager.getInstance(project) .startSessionAndShowTab(pid.toString(), icon, null, false, object : XDebugProcessStarter() { override fun start(dSession: XDebugSession): XDebugProcess { val process = MayaCharmDebugProcess( dSession, serverSocket, result.executionConsole, result.processHandler, null, pid ) process.positionConverter = PyLocalPositionConverter() PyDebugRunner.createConsoleCommunicationAndSetupActions(project, result, process, dSession) return process } }) } }
mit
c683963f783b60eb2ed9ed8bc20225c3
38.352113
112
0.678597
5.23221
false
false
false
false
seventhroot/elysium
bukkit/rpk-moderation-bukkit/src/main/kotlin/com/rpkit/moderation/bukkit/command/vanish/UnvanishCommand.kt
1
2102
/* * Copyright 2018 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.moderation.bukkit.command.vanish import com.rpkit.moderation.bukkit.RPKModerationBukkit import com.rpkit.moderation.bukkit.vanish.RPKVanishProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class UnvanishCommand(private val plugin: RPKModerationBukkit): CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (!sender.hasPermission("rpkit.moderation.command.unvanish")) { sender.sendMessage(plugin.messages["no-permission-unvanish"]) return true } if (sender !is Player) { sender.sendMessage(plugin.messages["not-from-console"]) return true } val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender) if (minecraftProfile == null) { sender.sendMessage(plugin.messages["no-minecraft-profile"]) return true } val vanishProvider = plugin.core.serviceManager.getServiceProvider(RPKVanishProvider::class) vanishProvider.setVanished(minecraftProfile, false) sender.sendMessage(plugin.messages["unvanish-valid"]) return true } }
apache-2.0
fe5cf5441438bdeb89b799f19f447418
40.235294
120
0.735966
4.58952
false
false
false
false
Adven27/Exam
exam-core/src/main/java/io/github/adven27/concordion/extensions/exam/core/PlaceholdersResolver.kt
1
1555
@file:JvmName("PlaceholdersResolver") package io.github.adven27.concordion.extensions.exam.core import io.github.adven27.concordion.extensions.exam.core.handlebars.HANDLEBARS import io.github.adven27.concordion.extensions.exam.core.handlebars.matchers.PLACEHOLDER_TYPE import io.github.adven27.concordion.extensions.exam.core.handlebars.resolveObj import org.concordion.api.Evaluator fun Evaluator.resolveForContentType(body: String, type: String): String = if (type.contains("xml", true)) resolveXml(body) else resolveJson(body) fun Evaluator.resolveNoType(body: String): String = resolveTxt(body, "text", this) fun Evaluator.resolveJson(body: String): String = resolveTxt(body, "json", this) fun Evaluator.resolveXml(body: String): String = resolveTxt(body, "xml", this) private fun resolveTxt(body: String, type: String, eval: Evaluator): String = eval.apply { setVariable("#$PLACEHOLDER_TYPE", type) }.resolveToObj(body).toString() fun Evaluator.resolveToObj(placeholder: String?): Any? = HANDLEBARS.resolveObj(this, placeholder) fun String?.vars(eval: Evaluator, setVar: Boolean = false, separator: String = ","): Map<String, Any?> = pairs(separator) .mapValues { (k, v) -> k to eval.resolveToObj(v).apply { if (setVar) eval.setVariable("#$k", this) } } fun String?.headers(separator: String = ","): Map<String, String> = pairs(separator) private fun String?.pairs(separator: String) = this?.split(separator) ?.map { it.split('=', limit = 2) } ?.associate { (k, v) -> k.trim() to v.trim() } ?: emptyMap()
mit
d27765a14291a3420f18ad679877a81e
47.59375
110
0.732476
3.607889
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/problem/rest/seeding/postman/PostmanParser.kt
1
7922
package org.evomaster.core.problem.rest.seeding.postman import com.google.gson.Gson import io.swagger.v3.oas.models.OpenAPI import org.evomaster.core.problem.api.service.param.Param import org.evomaster.core.problem.rest.RestCallAction import org.evomaster.core.problem.rest.param.* import org.evomaster.core.problem.rest.seeding.AbstractParser import org.evomaster.core.problem.rest.seeding.postman.pojos.PostmanCollectionObject import org.evomaster.core.problem.rest.seeding.postman.pojos.Request import org.evomaster.core.search.gene.ObjectGene import org.evomaster.core.search.gene.optional.OptionalGene import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.File import java.lang.IllegalStateException import java.net.URLDecoder import java.nio.charset.StandardCharsets class PostmanParser( defaultRestCallActions: List<RestCallAction>, swagger: OpenAPI ) : AbstractParser(defaultRestCallActions, swagger) { companion object { private val log: Logger = LoggerFactory.getLogger(PostmanParser::class.java) private const val TMP_PATH_STR = "_TEMP_REPLACE_1234_ABCD_" } override fun parseTestCases(path: String): MutableList<MutableList<RestCallAction>> { log.info("Parsing seed test cases from Postman collection located at {}", path) val testCases = mutableListOf<MutableList<RestCallAction>>() val postmanContent = File(path).inputStream().readBytes().toString(StandardCharsets.UTF_8) val postmanObject = Gson().fromJson(postmanContent, PostmanCollectionObject::class.java) postmanObject.item.forEach { postmanItem -> val postmanRequest = postmanItem.request // Copy action corresponding to Postman request val restAction = getRestAction(defaultRestCallActions, postmanRequest) if (restAction != null) { // Update action parameters according to Postman request restAction.parameters.forEach { parameter -> updateParameterGenesWithRequest(parameter, postmanRequest, restAction) } testCases.add(mutableListOf(restAction)) } } return testCases } private fun getRestAction(defaultRestActions: List<RestCallAction>, postmanRequest: Request): RestCallAction? { val verb = postmanRequest.method val path = getPath(postmanRequest.url.path) val originalRestAction = defaultRestActions.firstOrNull { it.verb.toString() == verb && it.path.matches(path) } if (originalRestAction == null) log.warn("Endpoint {} not found in the Swagger", "$verb:$path") return originalRestAction?.copy() as RestCallAction? } private fun updateParameterGenesWithRequest(parameter: Param, postmanRequest: Request, restAction: RestCallAction) { if (!isFormBody(parameter)) { // Form bodies in Postman are not a single string but an array of key-value val paramValue = getParamValueFromRequest(parameter, postmanRequest, restAction) updateGenesRecursivelyWithParameterValue(parameter.gene, parameter.name, paramValue) } else updateFormBodyGenesWithRequest(parameter as BodyParam, postmanRequest) } /** * In a Postman collection file, all parameter values are represented as strings, * except for form bodies. * * @param parameter Parameter extracted from an action * @param postmanRequest Postman representation of a request * @param restAction Action where the parameter is contained. Needed to find * path parameters, since Postman doesn't use keys for them, only values * @return Value of the parameter in the Postman request, null if not found */ private fun getParamValueFromRequest(parameter: Param, postmanRequest: Request, restAction: RestCallAction): String? { var value: String? = null when (parameter) { is HeaderParam -> value = postmanRequest.header?.find { it.key == parameter.name }?.value is QueryParam -> { value = postmanRequest.url.query?.find { it.key == parameter.name }?.value if (value != null) value = URLDecoder.decode(value, StandardCharsets.UTF_8.toString()) // Query params must be encoded } is BodyParam -> value = postmanRequest.body?.raw // Will return null for form bodies is PathParam -> { val path = getPath(postmanRequest.url.path) val pathParamValue = restAction.path.getKeyValues(path)?.get(parameter.name) if (pathParamValue == null) log.warn("Ignoring path parameter value... RestAction path and Postman path do not match: {} vs {}", restAction.path.toString(), path) else value = getDecodedPathElement(pathParamValue) } } return value } /** * Form bodies in Postman are not a single raw string, but rather a list of * key-value pairs. This function takes a form body parameter containing an * object gene and updates its first-level subgenes according to the key-value * pairs present in the Postman request. */ private fun updateFormBodyGenesWithRequest(formBody: BodyParam, postmanRequest: Request) { /* TODO: Support nested objects according to different serialization schemes [1]. The payload format is similar to that of query parameters, therefore it would be possible to parse a Postman-formatted form body according to the serialization scheme defined in the Swagger [2]. [1] https://swagger.io/docs/specification/describing-request-body/ (section "Form Data") [2] https://swagger.io/docs/specification/describing-parameters/#query-parameters */ // Optional form body not present in request if (postmanRequest.body?.urlencoded?.isEmpty() != false) { if (formBody.gene is OptionalGene) formBody.gene.isActive = false else log.warn("Required form body was not found in a seeded request. Ignoring and keeping the body...") return } when (val rootGene = if (formBody.gene is OptionalGene) formBody.gene.gene else formBody.gene) { is ObjectGene -> { rootGene.fields.forEach { formBodyField -> val paramValue = postmanRequest.body.urlencoded.find { it.key == formBodyField.name }?.value updateGenesRecursivelyWithParameterValue(formBodyField, formBodyField.name, paramValue) } } else -> throw IllegalStateException("Only objects are supported for form bodies when parsing Postman requests") } } private fun getPath(pathElements: List<String>): String { return "/" + pathElements.joinToString("/") } /** * Path elements are encoded/decoded differently that query elements in a URL. * Actually, the only problem when decoding path elements are white spaces, * which could be encoded as "+" in the query. When decoding a "+" in the path, * it should remain as "+" and not be changed for " ". * * This method decodes path elements using the standard URLDecoder class from * the Java API, but replaces "+" chars with a temporary string before and * after, so that those do not get transformed to " ". */ private fun getDecodedPathElement(pathElement: String): String { return URLDecoder.decode( pathElement.replace("+", TMP_PATH_STR), StandardCharsets.UTF_8.toString() ).replace(TMP_PATH_STR, "+") } private fun isFormBody(parameter: Param): Boolean { return parameter is BodyParam && parameter.isForm() } }
lgpl-3.0
d0fe19e1762c93ed2f811082a8bda724
45.605882
154
0.6718
4.72673
false
false
false
false
square/sqldelight
sqldelight-gradle-plugin/src/main/kotlin/com/squareup/sqldelight/gradle/GenerateMigrationOutputTask.kt
1
3573
package com.squareup.sqldelight.gradle import com.squareup.sqldelight.VERSION import com.squareup.sqldelight.core.SqlDelightCompilationUnit import com.squareup.sqldelight.core.SqlDelightDatabaseProperties import com.squareup.sqldelight.core.SqlDelightEnvironment import com.squareup.sqldelight.core.lang.util.rawSqlText import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.FileTree import org.gradle.api.provider.Property import org.gradle.api.tasks.CacheableTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFiles import org.gradle.api.tasks.Nested import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.SkipWhenEmpty import org.gradle.api.tasks.TaskAction import org.gradle.workers.WorkAction import org.gradle.workers.WorkParameters import java.io.File @Suppress("UnstableApiUsage") // Worker API. @CacheableTask abstract class GenerateMigrationOutputTask : SqlDelightWorkerTask() { @Suppress("unused") // Required to invalidate the task on version updates. @Input val pluginVersion = VERSION @get:OutputDirectory var outputDirectory: File? = null @Input val projectName: Property<String> = project.objects.property(String::class.java) @Nested lateinit var properties: SqlDelightDatabasePropertiesImpl @Nested lateinit var compilationUnit: SqlDelightCompilationUnitImpl @Input lateinit var migrationOutputExtension: String @TaskAction fun generateSchemaFile() { workQueue().submit(GenerateMigration::class.java) { it.outputDirectory.set(outputDirectory) it.moduleName.set(projectName) it.properties.set(properties) it.migrationExtension.set(migrationOutputExtension) it.compilationUnit.set(compilationUnit) } } @InputFiles @SkipWhenEmpty @PathSensitive(PathSensitivity.RELATIVE) override fun getSource(): FileTree { return super.getSource() } interface GenerateSchemaWorkParameters : WorkParameters { val outputDirectory: DirectoryProperty val moduleName: Property<String> val properties: Property<SqlDelightDatabaseProperties> val compilationUnit: Property<SqlDelightCompilationUnit> val migrationExtension: Property<String> } abstract class GenerateMigration : WorkAction<GenerateSchemaWorkParameters> { private val sourceFolders: List<File> get() = parameters.compilationUnit.get().sourceFolders.map { it.folder } override fun execute() { val properties = parameters.properties.get() val environment = SqlDelightEnvironment( sourceFolders = sourceFolders.filter { it.exists() }, dependencyFolders = emptyList(), moduleName = parameters.moduleName.get(), properties = properties, verifyMigrations = false, compilationUnit = parameters.compilationUnit.get(), ) val outputDirectory = parameters.outputDirectory.get().asFile val migrationExtension = parameters.migrationExtension.get() // Clear out the output directory. outputDirectory.listFiles()?.forEach { it.delete() } // Generate the new files. environment.forMigrationFiles { migrationFile -> val output = File( outputDirectory, "${migrationFile.virtualFile!!.nameWithoutExtension}$migrationExtension" ) output.writeText( migrationFile.sqlStmtList?.stmtList.orEmpty() .filterNotNull().joinToString(separator = "\n\n") { "${it.rawSqlText()};" } ) } } } }
apache-2.0
0528bc959d9754533d4390c869c2c753
34.73
89
0.753149
4.71372
false
false
false
false
grote/Transportr
app/src/main/java/de/grobox/transportr/networks/TransportNetwork.kt
1
2877
/* * 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.networks import android.content.Context import androidx.annotation.DrawableRes import androidx.annotation.StringRes import com.google.common.base.Preconditions.checkArgument import de.grobox.transportr.R import de.schildbach.pte.NetworkId import de.schildbach.pte.NetworkProvider import java.lang.ref.SoftReference import javax.annotation.concurrent.Immutable @Immutable data class TransportNetwork internal constructor( val id: NetworkId, @field:StringRes private val name: Int = 0, @field:StringRes private val description: Int, @field:StringRes private val agencies: Int = 0, val status: Status = Status.STABLE, @field:DrawableRes @get:DrawableRes val logo: Int = R.drawable.network_placeholder, private val goodLineNames: Boolean = false, private val itemIdExtra: Int = 0, private val factory: () -> NetworkProvider ) : Region { enum class Status { ALPHA, BETA, STABLE } val networkProvider: NetworkProvider by lazy { networkProviderRef.get() ?: getNetworkProviderReference().get()!! } private val networkProviderRef by lazy { getNetworkProviderReference() } private fun getNetworkProviderReference() = SoftReference<NetworkProvider>(factory.invoke()) init { checkArgument(description != 0 || agencies != 0) } override fun getName(context: Context): String { return if (name == 0) { id.name } else { context.getString(name) } } fun getDescription(context: Context): String? { return if (description != 0 && agencies != 0) { context.getString(description) + " (" + context.getString(agencies) + ")" } else if (description != 0) { context.getString(description) } else if (agencies != 0) { context.getString(agencies) } else { throw IllegalArgumentException() } } fun hasGoodLineNames(): Boolean { return goodLineNames } internal fun getItem(): TransportNetworkItem { return TransportNetworkItem(this, itemIdExtra) } }
gpl-3.0
c709a8be6d94263703883892191f8554
32.847059
118
0.683698
4.385671
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/inspections/global/DesignedForTabletsInspection.kt
1
8571
package com.gmail.blueboxware.libgdxplugin.inspections.global import com.gmail.blueboxware.libgdxplugin.message import com.gmail.blueboxware.libgdxplugin.utils.androidManifest.ManifestModel import com.gmail.blueboxware.libgdxplugin.utils.androidManifest.SdkVersionType import com.gmail.blueboxware.libgdxplugin.utils.firstParent import com.gmail.blueboxware.libgdxplugin.utils.isLibGDXProject import com.gmail.blueboxware.libgdxplugin.utils.toPsiFile import com.intellij.analysis.AnalysisScope import com.intellij.codeInspection.* import com.intellij.psi.PsiElement import com.intellij.psi.search.FilenameIndex import com.intellij.psi.xml.XmlFile import com.intellij.psi.xml.XmlTag import org.jetbrains.kotlin.idea.search.projectScope import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementVisitor import org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrApplicationStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression /* * Copyright 2016 Blue Box Ware * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ class DesignedForTabletsInspection : GlobalInspectionTool() { override fun getDisplayName() = message("designed.for.tablets.inspection") @Suppress("DialogTitleCapitalization") override fun getGroupDisplayName() = "libGDX" override fun getStaticDescription() = message("designed.for.tablets.html.description") override fun isEnabledByDefault() = true override fun getShortName() = "LibGDXDesignedForTablets" override fun runInspection( scope: AnalysisScope, manager: InspectionManager, globalContext: GlobalInspectionContext, problemDescriptionsProcessor: ProblemDescriptionsProcessor ) { val project = globalContext.project if (!project.isLibGDXProject()) { return } val problems = mutableListOf<Pair<PsiElement, String>>() val versionsMap = mutableMapOf<SdkVersionType, Int>() val gradleFiles = FilenameIndex.getVirtualFilesByName("build.gradle", project.projectScope()).toTypedArray() gradleFiles.sortBy { it.path } for (gradleFile in gradleFiles) { gradleFile.toPsiFile(project) ?.accept(GroovyPsiElementVisitor(DesignedForTabletsGradleVisitor(problems, versionsMap))) } val manifests = FilenameIndex.getVirtualFilesByName( "AndroidManifest.xml", project.projectScope() ) for (manifest in manifests) { (manifest.toPsiFile(project) as? XmlFile)?.let { processManifest(problems, it, versionsMap) } } for ((element, msg) in problems) { if (!isSuppressedFor(element)) { problemDescriptionsProcessor.addProblemElement( globalContext.refManager.getReference(element.containingFile), manager.createProblemDescriptor( element, msg, false, null, ProblemHighlightType.WEAK_WARNING ) ) } } } private fun processManifest( problems: MutableList<Pair<PsiElement, String>>, manifest: XmlFile, versionsMap: Map<SdkVersionType, Int> ) { val model = ManifestModel.fromFile(manifest) model.applyExternalVersions(versionsMap) val versionTag = (model.targetSDK?.element ?: model.minSDK.element ?: model.maxSDK?.element)?.let { attribute -> attribute.firstParent { it is XmlTag } } ?: manifest if (model.resolveTargetSDK() < 11 && model.minSDK.value < 11) { problems.add(versionTag to message("designed.for.tablets.problem.descriptor.target.or.min")) } else if ((model.maxSDK?.value ?: 11) < 11) { problems.add(versionTag to message("designed.for.tablets.problem.descriptor.max")) } if (model.supportScreens == null && model.minSDK.value < 13) { problems.add(manifest to message("designed.for.tablets.problem.descriptor.missing.support.screens")) } else { val supportScreens = model.resolveSupportsScreens() val supportScreensElement = model.supportScreens?.element ?: manifest if ( (model.hasLargeScreensSupportAttribute && supportScreens.largeScreens != true) || (model.hasXLargeScreenSupportAttribute && supportScreens.xlargeScreens != true) ) { problems.add(supportScreensElement to message("designed.for.tablets.problem.descriptor.large.false")) } if (model.minSDK.value < 13 && (!model.hasLargeScreensSupportAttribute || !model.hasXLargeScreenSupportAttribute)) { problems.add(supportScreensElement to message("designed.for.tablets.problem.descriptor.large.missing")) } } } } private class DesignedForTabletsGradleVisitor( val problems: MutableList<Pair<PsiElement, String>>, val versionsMap: MutableMap<SdkVersionType, Int> ) : GroovyRecursiveElementVisitor() { private var foundElementMap: MutableMap<SdkVersionType, GrMethodCall> = mutableMapOf() private fun updateVersionMap(call: GrMethodCall) { val invokedText = call.invokedExpression.text if (invokedText != "minSdkVersion" && invokedText != "maxSdkVersion" && invokedText != "targetSdkVersion") return if (call.argumentList.allArguments.isEmpty()) return val argument = call.argumentList.allArguments[0] val version = ((argument as? GrLiteral)?.value as? Int) ?: return var type: SdkVersionType? = null when (invokedText) { "maxSdkVersion" -> type = SdkVersionType.MAX "minSdkVersion" -> type = SdkVersionType.MIN "targetSdkVersion" -> type = SdkVersionType.TARGET } type?.let { typeNotNull -> if (version > (versionsMap[typeNotNull] ?: 0)) { versionsMap[typeNotNull] = version } foundElementMap[typeNotNull] = call } if (invokedText == "maxSdkVersion" && (versionsMap[SdkVersionType.MAX] ?: 11) < 11) { if (problems.none { it.first == call }) { problems.add(call to message("designed.for.tablets.problem.descriptor.max")) } } } override fun visitFile(file: GroovyFileBase) { super.visitFile(file) if (foundElementMap[SdkVersionType.TARGET] != null || foundElementMap[SdkVersionType.MIN] != null) { if ((versionsMap[SdkVersionType.TARGET] ?: 11) < 11 && (versionsMap[SdkVersionType.MIN] ?: 11) < 11) { foundElementMap[SdkVersionType.TARGET]?.let { problems.add( it to message("designed.for.tablets.problem.descriptor.target.or.min") ) } foundElementMap[SdkVersionType.MIN]?.let { problems.add( it to message("designed.for.tablets.problem.descriptor.target.or.min") ) } } } } override fun visitCallExpression(callExpression: GrCallExpression) { super.visitCallExpression(callExpression) if (callExpression is GrMethodCall) { updateVersionMap(callExpression) } } override fun visitApplicationStatement(applicationStatement: GrApplicationStatement) { super.visitApplicationStatement(applicationStatement) updateVersionMap(applicationStatement) } }
apache-2.0
cbed37661acfb3f315dc8eda9b8a3dfc
37.434978
128
0.662233
4.790945
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/firstball/RightChopOffsStatistic.kt
1
1240
package ca.josephroque.bowlingcompanion.statistics.impl.firstball import android.os.Parcel import android.os.Parcelable import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator import ca.josephroque.bowlingcompanion.games.lane.Deck import ca.josephroque.bowlingcompanion.games.lane.isRightChopOff /** * Copyright (C) 2018 Joseph Roque * * Percentage of shots which are right chop offs. */ class RightChopOffsStatistic(numerator: Int = 0, denominator: Int = 0) : FirstBallStatistic(numerator, denominator) { // MARK: Modifiers /** @Override */ override fun isModifiedBy(deck: Deck) = deck.isRightChopOff // MARK: Overrides override val titleId = Id override val id = Id.toLong() // MARK: Parcelable companion object { /** Creator, required by [Parcelable]. */ @Suppress("unused") @JvmField val CREATOR = parcelableCreator(::RightChopOffsStatistic) /** Unique ID for the statistic. */ const val Id = R.string.statistic_right_chops } /** * Construct this statistic from a [Parcel]. */ private constructor(p: Parcel): this(numerator = p.readInt(), denominator = p.readInt()) }
mit
6d5c572d3e5f9f9061f8c062ad8c640a
28.52381
117
0.708871
4.412811
false
false
false
false
BracketCove/PosTrainer
app/src/main/java/com/bracketcove/postrainer/settings/SettingsFragment.kt
1
1927
package com.bracketcove.postrainer.settings import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.navigation.ui.setupWithNavController import com.bracketcove.postrainer.R import kotlinx.android.synthetic.main.fragment_settings.* /** * Created by Ryan on 05/03/2017. */ class SettingsFragment : Fragment(), SettingsContract.View { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_settings, container, false) } override fun onStart() { super.onStart() bottomNavSettings.selectedItemId = R.id.settings setUpBottomNav() } override fun startAlarmListActivity() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } private fun setUpBottomNav() { bottomNavSettings.setupWithNavController(findNavController()) bottomNavSettings.setOnNavigationItemSelectedListener { when (it.itemId) { R.id.reminders -> if (findNavController().currentDestination?.id == R.id.settingsFragment) { findNavController().navigate( SettingsFragmentDirections.actionSettingsFragmentToReminderListFragment() ) } R.id.movements -> if (findNavController().currentDestination?.id == R.id.settingsFragment) { findNavController().navigate( SettingsFragmentDirections.actionSettingsFragmentToMovementListFragment() ) } } true } } }
apache-2.0
7bdaf409c7952b09f35ff775b702394c
32.807018
116
0.644525
5.537356
false
false
false
false
luiqn2007/miaowo
app/src/main/java/org/miaowo/miaowo/data/bean/SearchResult.kt
1
652
package org.miaowo.miaowo.data.bean data class SearchResult( val matchCount: Int = 0, val pageCount: Int = 1, val timing: Float = 0.00f, val users: List<User> = emptyList(), val posts: List<Post> = emptyList(), val time: Float = 0.00f, val pagination: Pagination? = null, val showAsPosts: Boolean = false, val showAsTopics: Boolean = false, val expandSearch: Boolean = false, val searchDefaultSortBy: String = "", val search_query: String = "", val term: String = "", val loggedIn: Boolean = false, val relative_path: String = "" )
apache-2.0
a8a0b9367563e2231f830ce6658304aa
33.368421
45
0.582822
4.100629
false
false
false
false
christophpickl/kpotpourri
boot-data-jpa4k/src/main/kotlin/com/github/christophpickl/kpotpourri/bootdatajpa/pagination.kt
1
970
package com.github.christophpickl.kpotpourri.bootdatajpa import org.springframework.data.domain.Page import org.springframework.data.domain.PageImpl import org.springframework.data.domain.PageRequest import javax.persistence.TypedQuery const val DEFAULT_PAGE_SIZE = 5 val defaultPageable = pageOf(0, DEFAULT_PAGE_SIZE) fun pageOf(pageNumber: Int?, pageSize: Int?): PageRequest = PageRequest.of( pageNumber ?: 0, pageSize ?: DEFAULT_PAGE_SIZE) fun <T> TypedQuery<T>.resultPage(pagination: PaginationRequest): Page<T> { val totalRows = resultList.size firstResult = pagination.pageNumber * pagination.pageSize maxResults = pagination.pageSize return PageImpl(resultList, pagination.toPageable(), totalRows.toLong()) } data class PaginationRequest( val pageNumber: Int, val pageSize: Int ) { companion object { val all get() = PaginationRequest(0, Int.MAX_VALUE) } fun toPageable() = pageOf(pageNumber, pageSize) }
apache-2.0
5f7d4252333b5fefab7ee7373bbc9c40
27.529412
76
0.750515
3.959184
false
false
false
false
halawata13/ArtichForAndroid
app/src/main/java/net/halawata/artich/MenuAdditionFragment.kt
2
2182
package net.halawata.artich import android.app.AlertDialog import android.app.Dialog import android.app.DialogFragment import android.content.Context import android.view.LayoutInflater import android.os.Bundle import android.widget.EditText import net.halawata.artich.enum.Media import net.halawata.artich.model.DatabaseHelper import net.halawata.artich.model.Log import net.halawata.artich.model.menu.MediaMenuFactory class MenuAdditionFragment : DialogFragment() { var mediaType: Media? = null override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = AlertDialog.Builder(activity) val inflater = activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val content = inflater.inflate(R.layout.fragment_menu_addition, null) builder.setView(content) builder.setTitle(getString(R.string.add_item)) .setPositiveButton(getString(R.string.add), { dialogInterface, i -> val editText = content.findViewById(R.id.menu_addition_text) as EditText mediaType?.let { val text = editText.text.toString() val helper = DatabaseHelper(activity) val mediaMenu = MediaMenuFactory.create(it, helper, activity.resources) val activity = activity as MenuManagementActivity try { // activity.listView.insert() で最後尾に追加しようとすると落ちるので普通に突っ込む activity.mediaList.add(text) mediaMenu.save(activity.mediaList) activity.adapter.notifyDataSetChanged() activity.listView.invalidateViews() } catch (ex: Exception) { Log.e(ex.message) activity.showError(getString(R.string.loading_fail_data)) } } }) .setNegativeButton(getString(R.string.cancel), null) return builder.create() } }
mit
e068420d53ff727596ee96f9d0e2bd70
39.188679
99
0.610329
5.059382
false
false
false
false
owncloud/android
owncloudData/src/test/java/com/owncloud/android/data/sharees/repository/OCShareeRepositoryTest.kt
2
2002
/** * ownCloud Android client application * * @author David González Verdugo * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.data.sharees.repository import com.owncloud.android.data.sharing.sharees.datasources.RemoteShareeDataSource import com.owncloud.android.data.sharing.sharees.repository.OCShareeRepository import com.owncloud.android.domain.exceptions.NoConnectionWithServerException import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.junit.Test class OCShareeRepositoryTest { private val remoteShareeDataSource = mockk<RemoteShareeDataSource>(relaxed = true) private val oCShareeRepository: OCShareeRepository = OCShareeRepository((remoteShareeDataSource)) @Test fun readShareesFromNetworkOk() { every { remoteShareeDataSource.getSharees(any(), any(), any()) } returns arrayListOf() oCShareeRepository.getSharees("user", 1, 5) verify(exactly = 1) { remoteShareeDataSource.getSharees("user", 1, 5) } } @Test(expected = NoConnectionWithServerException::class) fun readShareesFromNetworkNoConnection() { every { remoteShareeDataSource.getSharees(any(), any(), any()) } throws NoConnectionWithServerException() oCShareeRepository.getSharees("user", 1, 5) verify(exactly = 1) { remoteShareeDataSource.getSharees("user", 1, 5) } } }
gpl-2.0
070c9093d0a102ef8db465dd8166ebd7
34.732143
113
0.737631
4.117284
false
true
false
false
android/trackr
app/src/main/java/com/example/android/trackr/ui/tasks/DragAndDropActionsHelper.kt
1
3888
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.trackr.ui.tasks import com.example.android.trackr.R class DragAndDropActionsHelper(private val items: List<ListItem>) { private var headerPositions: List<Int> = mutableListOf() private var previousHeaderPosition = NO_POSITION private var nextHeaderPosition = NO_POSITION init { items.forEachIndexed { index, item -> if (item is ListItem.TypeHeader) { (headerPositions as MutableList).add(index) } } } fun execute(position: Int): List<DragAndDropActionInfo> { try { previousHeaderPosition = headerPositions.first() headerPositions.forEach { if (it < position) { previousHeaderPosition = it } } nextHeaderPosition = headerPositions.last() if (nextHeaderPosition < position) { // there is no next header nextHeaderPosition = items.size } else { headerPositions.asReversed().forEach { if (it > position) { nextHeaderPosition = it } } } return obtainDragAndDropActionInfo(position) } catch (e: NoSuchElementException) { e.printStackTrace() // We get here if there are no headers. In that case, there are no actions associated // with drag and drop. return emptyList() } } private fun obtainDragAndDropActionInfo(position: Int): List<DragAndDropActionInfo> { val actionParams = mutableListOf<DragAndDropActionInfo>() if (nextHeaderPosition != NO_POSITION && previousHeaderPosition != NO_POSITION && nextHeaderPosition - previousHeaderPosition > 2 // Only one item between two headers. ) { if (position - previousHeaderPosition > 1) { actionParams.add( DragAndDropActionInfo( position, previousHeaderPosition + 1, R.string.move_to_top ) ) if (position - previousHeaderPosition > 2) { actionParams.add( DragAndDropActionInfo(position, position - 1, R.string.move_up_one) ) } } if (nextHeaderPosition - position > 1) { actionParams.add( DragAndDropActionInfo(position, nextHeaderPosition - 1, R.string.move_to_bottom) ) if (nextHeaderPosition - position > 2) { actionParams.add( DragAndDropActionInfo(position, position + 1, R.string.move_down_one) ) } } } return actionParams } /** * Contains data for building a custom accessibility action to enable the dragging and dropping * of items. */ data class DragAndDropActionInfo( val fromPosition: Int, val toPosition: Int, val label: Int ) companion object { private const val NO_POSITION = -1 } }
apache-2.0
995866d5340494a8278bb0d690a21a4f
33.415929
100
0.568158
5.149669
false
false
false
false
Motsai/neblina-android
NebCtrlPanel/app/src/main/java/com/motsai/nebctrlpanel/MainActivity.kt
1
41161
package com.motsai.nebctrlpanel import android.Manifest import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothManager import android.bluetooth.le.BluetoothLeScanner import android.bluetooth.le.ScanCallback import android.bluetooth.le.ScanResult import android.content.Context import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import android.renderscript.* import android.service.autofill.Dataset import com.github.mikephil.charting.charts.LineChart import com.github.mikephil.charting.data.LineData import com.jjoe64.graphview.GraphView import com.jjoe64.graphview.Viewport import com.jjoe64.graphview.series.DataPoint import com.jjoe64.graphview.series.LineGraphSeries import com.motsai.neblina.* import java.nio.ByteBuffer import java.nio.ByteOrder import java.util.HashMap import android.opengl.* import android.opengl.GLSurfaceView import fr.arnaudguyon.smartgl.math.Vector3D import fr.arnaudguyon.smartgl.opengl.LightParallel //import fr.arnaudguyon.smartgl.opengl.Object3D; import fr.arnaudguyon.smartgl.opengl.RenderObject //import fr.arnaudguyon.smartgl.opengl.RenderPassObject3D; import fr.arnaudguyon.smartgl.opengl.RenderPassSprite import fr.arnaudguyon.smartgl.opengl.SmartColor import fr.arnaudguyon.smartgl.opengl.SmartGLRenderer import fr.arnaudguyon.smartgl.opengl.SmartGLView import fr.arnaudguyon.smartgl.opengl.SmartGLViewController import fr.arnaudguyon.smartgl.opengl.Sprite import fr.arnaudguyon.smartgl.opengl.Texture //import fr.arnaudguyon.smartgl.tools.WavefrontModel; import fr.arnaudguyon.smartgl.touch.TouchHelperEvent import kotlinx.android.synthetic.main.activity_main.* import kotlin.experimental.or import java.util.Scanner import javax.microedition.khronos.opengles.GL10 class MainActivity : AppCompatActivity(), NeblinaDelegate, SmartGLViewController { private var mBluetoothAdapter: BluetoothAdapter? = null private val mHandler: Handler? = null private var mLEScanner: BluetoothLeScanner? = null private var mAdapter: DeviceListAdapter? = null private var mDev: Neblina? = null private var mCmdListView: ListView? = null private var mTextLine1: TextView? = null private var mTextLine2: TextView? = null private var mTextLine3: TextView? = null private var mQuatRate: Int = 0 private var mQuatPeriod: Int = 0 private var mQuatTimeStamp: Long = 0 private var mQuatDropCnt = 0 private var mQuatCnt = 0 private var mQuatBdCnt = 0 private var mFlashEraseProgress = false private var mRenderer : SmartGLRenderer? = null private var modelview = 0 private var mShip: Object3D? = null private var mCube: Object3D?= null private var mCur3DObj : Object3D? = null private var mSpaceFrigateTexture: Texture? = null private var mRenderPassShip: RenderPassObject3D? = null private var mRenderPassCube: RenderPassObject3D? = null private var mGraphView: LineChart? = null //private var mSeries: LineGraphSeries<DataPoint>? = null private var mLineData: LineData? = null val cmdList = arrayOf( NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_GENERAL, Neblina.NEBLINA_COMMAND_GENERAL_INTERFACE_STATE, Neblina.NEBLINA_INTERFACE_STATUS_BLE.toInt(), "BLE Data Port", NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_GENERAL, Neblina.NEBLINA_COMMAND_GENERAL_INTERFACE_STATE, Neblina.NEBLINA_INTERFACE_STATUS_UART.toInt(), "UART Data Port", NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_GENERAL, Neblina.NEBLINA_COMMAND_GENERAL_DEVICE_NAME_SET, 0, "Change Device Name", NebCmdItem.ACTUATOR_TYPE_TEXT_FIELD_BUTTON.toInt(), "Change"), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_FUSION, Neblina.NEBLINA_COMMAND_FUSION_CALIBRATE_FORWARD_POSITION, 0, "Calibrate Forward Pos", NebCmdItem.ACTUATOR_TYPE_BUTTON.toInt(), "Calib Fwrd"), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_FUSION, Neblina.NEBLINA_COMMAND_FUSION_CALIBRATE_DOWN_POSITION, 0, "Calibrate Down Pos", NebCmdItem.ACTUATOR_TYPE_BUTTON.toInt(), "Calib Dwn"), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_GENERAL, Neblina.NEBLINA_COMMAND_GENERAL_RESET_TIMESTAMP, 0, "Reset timestamp", NebCmdItem.ACTUATOR_TYPE_BUTTON.toInt(), "Reset"), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_FUSION, Neblina.NEBLINA_COMMAND_FUSION_FUSION_TYPE, 0, "Fusion 9 axis", NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_FUSION, Neblina.NEBLINA_COMMAND_FUSION_QUATERNION_STREAM, Neblina.NEBLINA_FUSION_STATUS_QUATERNION.toInt(), "Quaternion Stream", NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_FUSION, Neblina.NEBLINA_COMMAND_FUSION_PEDOMETER_STREAM, Neblina.NEBLINA_FUSION_STATUS_PEDOMETER.toInt(), "Pedometer Stream", NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_FUSION, Neblina.NEBLINA_COMMAND_FUSION_ROTATION_INFO_STREAM, Neblina.NEBLINA_FUSION_STATUS_ROTATION_INFO.toInt(), "Rotation info Stream", NebCmdItem.ACTUATOR_TYPE_TEXT_FIELD_SWITCH.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_SENSOR, Neblina.NEBLINA_COMMAND_SENSOR_ACCELEROMETER_STREAM, Neblina.NEBLINA_SENSOR_STATUS_ACCELEROMETER.toInt(), "Accelerometer Sensor Stream", NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_SENSOR, Neblina.NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM, Neblina.NEBLINA_SENSOR_STATUS_GYROSCOPE.toInt(), "Gyro Sensor Stream", NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_SENSOR, Neblina.NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM, Neblina.NEBLINA_SENSOR_STATUS_MAGNETOMETER.toInt(), "Mag Sensor Stream", NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_SENSOR, Neblina.NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM, Neblina.NEBLINA_SENSOR_STATUS_ACCELEROMETER_GYROSCOPE.toInt(), "Accel & Gyro Stream", NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_SENSOR, Neblina.NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM, Neblina.NEBLINA_SENSOR_STATUS_HUMIDITY.toInt(), "Humidity Sensor Stream", NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_FUSION, Neblina.NEBLINA_COMMAND_FUSION_LOCK_HEADING_REFERENCE, 0, "Lock Heading Ref.", NebCmdItem.ACTUATOR_TYPE_BUTTON.toInt(), "Lock"), NebCmdItem(0xf.toByte(), 2.toByte(), 0, "Luggage data logging", NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_RECORDER, Neblina.NEBLINA_COMMAND_RECORDER_RECORD, Neblina.NEBLINA_RECORDER_STATUS_RECORD.toInt(), "Stream/Record", NebCmdItem.ACTUATOR_TYPE_BUTTON.toInt(), "Start"), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_RECORDER, Neblina.NEBLINA_COMMAND_RECORDER_RECORD, 0, "Stream/Record", NebCmdItem.ACTUATOR_TYPE_BUTTON.toInt(), "Stop"), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_RECORDER, Neblina.NEBLINA_COMMAND_RECORDER_RECORD, 0, "Flash Record", NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_RECORDER, Neblina.NEBLINA_COMMAND_RECORDER_PLAYBACK, 0, "Flash Playback", NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_LED, Neblina.NEBLINA_COMMAND_LED_STATE, 0, "Set LED0 level", NebCmdItem.ACTUATOR_TYPE_TEXT_FIELD.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_LED, Neblina.NEBLINA_COMMAND_LED_STATE, 0, "Set LED1 level", NebCmdItem.ACTUATOR_TYPE_TEXT_FIELD.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_LED, Neblina.NEBLINA_COMMAND_LED_STATE, 0, "Set LED2", NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_EEPROM, Neblina.NEBLINA_COMMAND_EEPROM_READ, 0, "EEPROM Read", NebCmdItem.ACTUATOR_TYPE_BUTTON.toInt(), "Read"), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_POWER, Neblina.NEBLINA_COMMAND_POWER_CHARGE_CURRENT, 0, "Charge Current in mA", NebCmdItem.ACTUATOR_TYPE_TEXT_FIELD.toInt(), ""), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_RECORDER, Neblina.NEBLINA_COMMAND_RECORDER_ERASE_ALL, 0, "Flash Erase All", NebCmdItem.ACTUATOR_TYPE_BUTTON.toInt(), "Erase"), NebCmdItem(Neblina.NEBLINA_SUBSYSTEM_GENERAL, Neblina.NEBLINA_COMMAND_GENERAL_FIRMWARE_UPDATE, 0, "Firmware Update", NebCmdItem.ACTUATOR_TYPE_BUTTON.toInt(), "Enter DFU"), NebCmdItem(0xf.toByte(), 0.toByte(), 0, "Motion data stream", NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt(), ""), NebCmdItem(0xf.toByte(), 1.toByte(), 0, "Heading", NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt(), "")) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) requestPermissions(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION), 1) val glview = findViewById(R.id.surfaceView) as SmartGLView glview.setDefaultRenderer(this) glview.setController(this) val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager mBluetoothAdapter = bluetoothManager.adapter mLEScanner = mBluetoothAdapter!!.getBluetoothLeScanner() mAdapter = DeviceListAdapter(this, R.layout.nebdevice_list_content)//android.R.layout.simple_list_item_1); mTextLine1 = findViewById<View>(R.id.textView1) as TextView mTextLine2 = findViewById<View>(R.id.textView2) as TextView mTextLine3 = findViewById<View>(R.id.textView3) as TextView mGraphView = findViewById(R.id.graph) as LineChart /* mSeries = LineGraphSeries<DataPoint>() mGraphView!!.addSeries(mSeries); mGraphView!!.getViewport().setYAxisBoundsManual(true) mGraphView!!.getViewport().setMinY(-2.0) mGraphView!!.getViewport().setMaxY(2.0) mGraphView!!.getViewport().setScrollable(true) */ //val inputStream = context.getResources().openRawResource(rawResId) //val scanner = Scanner(glview.context.getAssets().open("res/raw/space_frigate_obj.txt")) val scanner = Scanner(glview.context.getResources().openRawResource(R.raw.space_frigate_obj)) var vertices : ArrayList<Float> = ArrayList<Float>() var faces : ArrayList<Short> = ArrayList<Short>() var idx : Int = 0 while (scanner.hasNextLine()) { val line = scanner.nextLine() if (line.startsWith("v ")) { // Add vertex line to list of vertices //vertices.add(line) val coords = line.split(" ") // Split by space val x :Float = java.lang.Float.parseFloat(coords[1]) val y = java.lang.Float.parseFloat(coords[2]) val z = java.lang.Float.parseFloat(coords[3]) vertices.add (x)//[idx++] = x vertices.add (y) vertices.add (z) } else if (line.startsWith("f ")) { // Add face line to faces list //facesList.add(line) val vertexIndices = line.split(" ", "/"); for (i in 1..vertexIndices.size - 1 ) { val vertex = java.lang.Short.parseShort(vertexIndices[i]); faces.add((vertex - 1).toShort()) } } } // Close the scanner scanner.close() mSpaceFrigateTexture = Texture(glview.context, R.drawable.space_frigate_6_color) var model = WavefrontModel.Builder(glview.context, R.raw.space_frigate_obj) .addTexture("", mSpaceFrigateTexture) .create(); mShip = model.toObject3D() mShip?.setPos(0f, 0f, -10f); mRenderPassShip?.addObject(mShip); model = WavefrontModel.Builder(glview.context, R.raw.calibration_cube_obj) .create(); mCube = model.toObject3D() mCube?.setPos(0f, 0f, -10f) mRenderPassCube?.addObject(mCube) mCur3DObj = mShip; val sw3dv = findViewById<Switch>(R.id.switch_3dview) as Switch sw3dv.isChecked = false sw3dv.setOnCheckedChangeListener(object : CompoundButton.OnCheckedChangeListener { override fun onCheckedChanged(vi: CompoundButton, isChecked: Boolean) { if (isChecked) { modelview = 1 mCur3DObj = mCube mRenderer?.addRenderPass(mRenderPassCube) mRenderer?.removeRenderPass(mRenderPassShip) } else { modelview = 0 mCur3DObj = mShip mRenderer?.addRenderPass(mRenderPassShip) mRenderer?.removeRenderPass(mRenderPassCube) } } }) val listView = findViewById<View>(R.id.founddevice_listView) as ListView listView.adapter = mAdapter listView.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id -> val adapter = parent.adapter as DeviceListAdapter mLEScanner!!.stopScan(mScanCallback) if (mDev != null) { mDev!!.Disconnect() } mDev = adapter.getItem(position) as Neblina mDev!!.SetDelegate(this@MainActivity) mDev!!.Connect(baseContext) } mCmdListView = findViewById<View>(R.id.cmd_listView) as ListView val adapter = CmdListAdapter(this, R.layout.nebcmd_item, cmdList) mCmdListView!!.setAdapter(adapter) mCmdListView!!.setTag(this) mCmdListView!!.setOnScrollListener(object : AbsListView.OnScrollListener { override fun onScrollStateChanged(view: AbsListView, scrollState: Int) { if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) { if (mDev != null) { mDev!!.getSystemStatus() } } } override fun onScroll(view: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) { } } ) mLEScanner!!.startScan(mScanCallback) } private val mScanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult) { val device = result.device val scanRecord = result.scanRecord val scanData = scanRecord!!.bytes var name = scanRecord.deviceName var deviceID: Long = 0 val manuf = scanRecord.getManufacturerSpecificData(0x0274) if (name == null) name = device.name if (name == null || manuf == null || manuf.size < 8) return val x = ByteBuffer.wrap(manuf) x.order(ByteOrder.LITTLE_ENDIAN) deviceID = x.long val listView = findViewById<View>(R.id.founddevice_listView) as ListView val r = listView.adapter as DeviceListAdapter mAdapter!!.addItem(Neblina(name, deviceID, device)) mAdapter!!.notifyDataSetChanged() } override fun onBatchScanResults(results: List<ScanResult>) { for (sr in results) { Log.i("ScanResult - Results", sr.toString()) } } override fun onScanFailed(errorCode: Int) { Log.e("Scan Failed", "Error Code: " + errorCode) } } inner class DeviceListAdapter(private val mContext: Context, textViewResourceId: Int)//}, ArrayList<Neblina> devices) { //super(context, textViewResourceId); : BaseAdapter() { private val mNebDevices = HashMap<String, Neblina>() fun addItem(dev: Neblina) { if (mNebDevices.containsKey(dev.toString()) == false) { mNebDevices.put(dev.toString(), dev) Log.w("BLUETOOTH DEBUG", "Item added " + dev.toString()) } } override fun getCount(): Int { return mNebDevices.size } override fun getItem(position: Int): Any { return mNebDevices.values.toTypedArray()[position] } override fun getItemId(position: Int): Long { return 0 } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var convertView = convertView if (convertView == null) { val inflater = LayoutInflater.from(mContext) convertView = inflater.inflate(R.layout.nebdevice_list_content, parent, false) } val textView = convertView!!.findViewById<View>(R.id.id) as TextView //ImageView imageView = (ImageView) rowView.findViewById(R.id.icon); if (mNebDevices.size > position) { textView.text = mNebDevices.values.toTypedArray()[position].toString() } return convertView } } fun onSwitchButtonChanged(button: CompoundButton, isChecked: Boolean) { val idx = button.tag as Int if (idx < 0 || idx > cmdList.size) return Log.d("onSwitchButtonChanged", "idx " + idx.toString()) when (cmdList[idx].mSubSysId) { Neblina.NEBLINA_SUBSYSTEM_GENERAL -> when (cmdList[idx].mCmdId) { Neblina.NEBLINA_COMMAND_GENERAL_INTERFACE_STATE -> if (isChecked) mDev!!.setDataPort(idx, 1.toByte().toInt()) else mDev!!.setDataPort(idx, 0.toByte().toInt()) else -> { } } Neblina.NEBLINA_SUBSYSTEM_FUSION -> when (cmdList[idx].mCmdId) { Neblina.NEBLINA_COMMAND_FUSION_RATE -> { } Neblina.NEBLINA_COMMAND_FUSION_DOWNSAMPLE -> { } Neblina.NEBLINA_COMMAND_FUSION_MOTION_STATE_STREAM -> mDev!!.streamMotionState(isChecked) Neblina.NEBLINA_COMMAND_FUSION_QUATERNION_STREAM -> { mDev!!.streamEulerAngle(false) mDev!!.streamQuaternion(isChecked) } Neblina.NEBLINA_COMMAND_FUSION_EULER_ANGLE_STREAM -> { mDev!!.streamQuaternion(false) mDev!!.streamEulerAngle(isChecked) } Neblina.NEBLINA_COMMAND_FUSION_EXTERNAL_FORCE_STREAM -> mDev!!.streamExternalForce(isChecked) Neblina.NEBLINA_COMMAND_FUSION_FUSION_TYPE -> if (isChecked) mDev!!.setFusionType(1.toByte()) else mDev!!.setFusionType(0.toByte()) Neblina.NEBLINA_COMMAND_FUSION_TRAJECTORY_RECORD -> { } Neblina.NEBLINA_COMMAND_FUSION_TRAJECTORY_INFO_STREAM -> { } Neblina.NEBLINA_COMMAND_FUSION_PEDOMETER_STREAM -> mDev!!.streamPedometer(isChecked) Neblina.NEBLINA_COMMAND_FUSION_SITTING_STANDING_STREAM -> { } Neblina.NEBLINA_COMMAND_FUSION_LOCK_HEADING_REFERENCE -> { } Neblina.NEBLINA_COMMAND_FUSION_FINGER_GESTURE_STREAM -> { } Neblina.NEBLINA_COMMAND_FUSION_ROTATION_INFO_STREAM -> mDev!!.streamRotationInfo(isChecked) Neblina.NEBLINA_COMMAND_FUSION_EXTERNAL_HEADING_CORRECTION -> { } } Neblina.NEBLINA_SUBSYSTEM_SENSOR -> when (cmdList[idx].mCmdId) { Neblina.NEBLINA_COMMAND_SENSOR_ACCELEROMETER_STREAM -> mDev!!.sensorStreamAccelData(isChecked) Neblina.NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM -> mDev!!.sensorStreamGyroData(isChecked) Neblina.NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM -> mDev!!.sensorStreamHumidityData(isChecked) Neblina.NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM -> mDev!!.sensorStreamMagData(isChecked) Neblina.NEBLINA_COMMAND_SENSOR_PRESSURE_STREAM -> mDev!!.sensorStreamPressureData(isChecked) Neblina.NEBLINA_COMMAND_SENSOR_TEMPERATURE_STREAM -> mDev!!.sensorStreamTemperatureData(isChecked) Neblina.NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM -> mDev!!.sensorStreamAccelGyroData(isChecked) Neblina.NEBLINA_COMMAND_SENSOR_ACCELEROMETER_MAGNETOMETER_STREAM -> mDev!!.sensorStreamAccelMagData(isChecked) else -> { } } Neblina.NEBLINA_SUBSYSTEM_RECORDER -> when (cmdList[idx].mCmdId) { Neblina.NEBLINA_COMMAND_RECORDER_PLAYBACK -> mDev!!.sessionPlayback(isChecked, 0.toShort()) } 0xf.toByte() -> when (cmdList[idx].mCmdId) { 2.toByte() -> { // if (isChecked) { mDev!!.sessionRecord(isChecked) mDev!!.sensorStreamAccelGyroData(isChecked) mDev!!.sensorStreamMagData(isChecked) mDev!!.sensorStreamPressureData(isChecked) mDev!!.sensorStreamTemperatureData(isChecked) } }// } // else { // mDev.sessionRecord(isChecked); // } } } fun onButtonClick(button: View) { val idx = button.tag as Int if (idx < 0 || idx > cmdList.size) return when (cmdList[idx].mSubSysId) { Neblina.NEBLINA_SUBSYSTEM_EEPROM -> when (cmdList[idx].mCmdId) { Neblina.NEBLINA_COMMAND_EEPROM_READ -> mDev!!.eepromRead(0.toShort()) Neblina.NEBLINA_COMMAND_EEPROM_WRITE -> { } } Neblina.NEBLINA_SUBSYSTEM_FUSION -> when (cmdList[idx].mCmdId) { Neblina.NEBLINA_COMMAND_FUSION_CALIBRATE_FORWARD_POSITION -> mDev!!.calibrateForwardPosition() Neblina.NEBLINA_COMMAND_FUSION_CALIBRATE_DOWN_POSITION -> mDev!!.calibrateDownPosition() } Neblina.NEBLINA_SUBSYSTEM_RECORDER -> when (cmdList[idx].mCmdId) { Neblina.NEBLINA_COMMAND_RECORDER_ERASE_ALL -> if (mFlashEraseProgress == false) { mFlashEraseProgress = true mTextLine3!!.setText("Erasing...") mTextLine3!!.getRootView().postInvalidate() mDev!!.eraseStorage(false) } Neblina.NEBLINA_COMMAND_RECORDER_RECORD -> if (cmdList[idx].mActiveStatus == 0) { mDev!!.sessionRecord(false) } else { mDev!!.sessionRecord(true) } Neblina.NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD -> { } Neblina.NEBLINA_COMMAND_RECORDER_PLAYBACK -> { } } 0xFF.toByte() -> if (cmdList[idx].mCmdId.toInt() == 1) //start stream/record { mDev!!.streamQuaternion(true) //mNedDev.streamIMU(true); mDev!!.sessionRecord(true) } else //stop stream/record { mDev!!.disableStreaming() mDev!!.sessionRecord(false) } } } fun updateUI(data: ByteArray?) { for (i in cmdList.indices) { var status = 0 when (cmdList[i].mSubSysId) { Neblina.NEBLINA_SUBSYSTEM_GENERAL -> status = data!![8].toInt() and 0xFF Neblina.NEBLINA_SUBSYSTEM_FUSION -> { status = (data!![0].toInt() and 0xFF) or ((data[1]?.toInt() and 0xFF) shl 8) or ((data[2]?.toInt() and 0xFF) shl 16) or ((data[3]?.toInt() and 0xFF) shl 24) Log.w("BLUETOOTH DEBUG", "NEBLINA_SUBSYSTEM_FUSION STATUS " + status.toString() ) } Neblina.NEBLINA_SUBSYSTEM_SENSOR -> status = (data!![4].toInt() and 0xFF) or ((data[5]?.toInt() and 0xFF) shl 8) Neblina.NEBLINA_SUBSYSTEM_RECORDER -> status = data!![7].toInt() and 0xFF } // val rowView = mCmdListView?.getChildAt(i) //if (rowView != null) { Log.d("***** updateUI", "status *****" + cmdList[i].mActuator.toString() + "i=" + i.toString()) when (cmdList[i].mActuator) { NebCmdItem.ACTUATOR_TYPE_TEXT_FIELD_SWITCH.toInt(), NebCmdItem.ACTUATOR_TYPE_SWITCH.toInt() -> { Log.d("***** updateUI", "ACTUATOR_TYPE_SWITCH *****" + i.toString() + " "+ cmdList[i].mActiveStatus.toString()) //val x = cmdAdapter.findViewWithTag<View>(cmdList[i].mActuator) // val v = rowView!!.findViewById(R.id.switch1) as Switch? //<View>(i) as Switch val v = mCmdListView?.findViewWithTag<View>(i) as Switch? if (v != null) { val visi = v.visibility v.visibility = View.INVISIBLE; if ((cmdList[i].mActiveStatus and status) == 0) { v.isChecked = false } else { Log.d("***** updateUI", "v.visibility *****" + visi.toString()) v.isChecked = true } v.visibility = visi v.rootView.postInvalidate() } } NebCmdItem.ACTUATOR_TYPE_BUTTON.toInt() -> { } } //rowView.postInvalidate() //} } } override fun didConnectNeblina(sender: Neblina?) { Log.w("BLUETOOTH DEBUG", "Connected " + sender.toString()) sender?.getSystemStatus() sender?.getFirmwareVersion() } override fun didReceiveResponsePacket(sender: Neblina?, subsystem: Int, cmdRspId: Int, data: ByteArray?, dataLen: Int) { when (subsystem) { Neblina.NEBLINA_SUBSYSTEM_GENERAL.toInt() -> { when (cmdRspId) { Neblina.NEBLINA_COMMAND_GENERAL_SYSTEM_STATUS.toInt() -> { runOnUiThread { updateUI(data) } //updateUI(data); } Neblina.NEBLINA_COMMAND_GENERAL_FIRMWARE_VERSION.toInt() -> { runOnUiThread { val b = (data!![4].toInt() and 0xFF) or ((data!![5].toInt() and 0xFF) shl 8) or ((data!![6].toInt() and 0xFF) shl 16) as Int val s = String.format("API:%d, FW:%d.%d.%d-%d", data!![0], data[1], data[2], data[3], b) val tv = findViewById<View>(R.id.version_TextView) as TextView tv.text = s tv.rootView.postInvalidate() } } } when (cmdRspId) { Neblina.NEBLINA_COMMAND_FUSION_QUATERNION_STREAM.toInt() -> { mQuatRate = data!![2].toInt() or (data[3].toInt() shl 8) mQuatPeriod = 1000000 / mQuatRate } } } Neblina.NEBLINA_SUBSYSTEM_FUSION.toInt() -> when (cmdRspId) { Neblina.NEBLINA_COMMAND_FUSION_QUATERNION_STREAM.toInt() -> { mQuatRate = data!![2].toInt() or (data[3].toInt() shl 8) mQuatPeriod = 1000000 / mQuatRate } } Neblina.NEBLINA_SUBSYSTEM_SENSOR.toInt() -> { } Neblina.NEBLINA_SUBSYSTEM_RECORDER.toInt() -> when (cmdRspId) { Neblina.NEBLINA_COMMAND_RECORDER_ERASE_ALL.toInt() -> { runOnUiThread { mTextLine3!!.setText("Flash erased") mTextLine3!!.getRootView().postInvalidate() } mFlashEraseProgress = false } } } } override fun didReceiveRSSI(sender: Neblina?, rssi: Int) { // TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun didReceiveGeneralData(sender: Neblina?, respType: Int, cmdRspId: Int, data: ByteArray?, dataLen: Int, errFlag: Boolean) { when (cmdRspId) { Neblina.NEBLINA_COMMAND_GENERAL_SYSTEM_STATUS.toInt() -> { runOnUiThread { updateUI(data) } //updateUI(data); } } } override fun didReceiveFusionData(sender: Neblina?, respType: Int, cmdRspId: Int, data: ByteArray?, dataLen: Int, errFlag: Boolean) { val timeStamp = data!![0].toLong() and 0xFF or (data[1].toLong() and 0xFF shl 8) or (data[2].toLong() and 0xFF shl 16) or (data[3].toLong() and 0xFF shl 24) when (cmdRspId) { Neblina.NEBLINA_COMMAND_FUSION_EULER_ANGLE_STREAM.toInt() -> { val rotx = ((data[4].toInt() and 0xFF) or ((data[5].toInt() and 0xFF) shl 8)).toDouble() / 10.0 val roty = ((data[6].toInt() and 0xFF) or ((data[7].toInt() and 0xFF) shl 8)).toDouble() / 10.0 val rotz = ((data[8].toInt() and 0xFF) or ((data[9].toInt() and 0xFF) shl 8)).toDouble() / 10.0 runOnUiThread { val s = String.format("Euler : T : %d - (Yaw : %f, Ptich : %f, Roll : %f)", timeStamp, rotx, roty, rotz) //Log.w("BLUETOOTH DEBUG", s); mTextLine1!!.setText(s) mTextLine1!!.getRootView().postInvalidate() } //val controler = mActivityGLView!!.controller as GLViewController //controler.setQuaternion(0.0.toFloat(), rotx.toFloat(), roty.toFloat(), rotz.toFloat()) } Neblina.NEBLINA_COMMAND_FUSION_QUATERNION_STREAM.toInt() -> { val q1 = (((data[4].toInt() and 0xFF) or ((data[5].toInt() and 0xFF) shl 8)).toShort()).toDouble() / 32768.0 val q2 = (((data[6].toInt() and 0x00FF) or ((data[7].toInt() and 0x00FF) shl 8)).toShort()).toDouble() / 32768.0 val q3 = (((data[8].toInt() and 0x00FF) or ((data[9].toInt() and 0x00FF) shl 8)).toShort()).toDouble() / 32768.0 val q4 = (((data[10].toInt() and 0x00FF) or ((data[11].toInt() and 0x00FF) shl 8)).toShort()).toDouble() / 32768.0 //val q1 = (data[4] as Short and 0xFF as Short) or (data[5] as Short and 0xFF shl 8)) / 32768.0 runOnUiThread { val s = String.format("Quat: T : %d - (%.2f, %.2f, %.2f, %.2f)", timeStamp, q1, q2, -q4, q3) mTextLine1!!.setText(s) mTextLine1!!.getRootView().postInvalidate() mCur3DObj?.setQuaternion(q1.toFloat(), q2.toFloat(), -q4.toFloat(), q3.toFloat()) //mSeries!!.appendData(DataPoint(timeStamp.toDouble(), q2), true, 20) // mGraphView!!.postInvalidate() //mShip?.setQuaternion(q1.toFloat(), q2.toFloat(), q3.toFloat(), q4.toFloat()) //mCube?.setQuaternion(q1.toFloat(), q2.toFloat(), q3.toFloat(), q4.toFloat()) } //ByteBuffer ar = ByteBuffer.wrap(data); //int ts = (data[0] & 0xFF) | ((data[1] & 0xFF) << 8) | ((data[2] & 0xFF) << 16) | ((data[3] & 0xFF) << 24); var dt: Long if (timeStamp == mQuatTimeStamp) { mQuatBdCnt++ } if (timeStamp > mQuatTimeStamp) { dt = timeStamp - mQuatTimeStamp } else { dt = -0x1.toLong() - mQuatTimeStamp + timeStamp } if (dt < 0) { dt = -dt } if (dt > mQuatPeriod + (mQuatPeriod shr 1) || dt < mQuatPeriod - (mQuatPeriod shr 1)) { mQuatDropCnt++ } mQuatCnt++ val finalDt = dt runOnUiThread { val s = String.format("%d, %d %d %d", finalDt, mQuatCnt, mQuatDropCnt, mQuatBdCnt) mTextLine2!!.setText(s) mTextLine2!!.getRootView().postInvalidate() } mQuatTimeStamp = timeStamp } } } override fun didReceivePmgntData(sender: Neblina?, respType: Int, cmdRspId: Int, data: ByteArray?, dataLen: Int, errFlag: Boolean) { // TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun didReceiveLedData(sender: Neblina?, respType: Int, cmdRspId: Int, data: ByteArray?, dataLen: Int, errFlag: Boolean) { // TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun didReceiveDebugData(sender: Neblina?, respType: Int, cmdRspId: Int, data: ByteArray?, dataLen: Int, errFlag: Boolean) { /// TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun didReceiveRecorderData(sender: Neblina?, respType: Int, cmdRspId: Int, data: ByteArray?, dataLen: Int, errFlag: Boolean) { // TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun didReceiveEepromData(sender: Neblina?, respType: Int, cmdRspId: Int, data: ByteArray?, dataLen: Int, errFlag: Boolean) { // TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun didReceiveSensorData(sender: Neblina?, respType: Int, cmdRspId: Int, data: ByteArray?, dataLen: Int, errFlag: Boolean) { val timeStamp = data!![0].toLong() and 0xFF or (data[1].toLong() and 0xFF shl 8) or (data[2].toLong() and 0xFF shl 16) or (data[3].toLong() and 0xFF shl 24) when (cmdRspId) { Neblina.NEBLINA_COMMAND_SENSOR_ACCELEROMETER_STREAM.toInt() -> { val x = data[4].toInt() and 0xff or (data[5].toInt() shl 8) val y = data[6].toInt() and 0xff or (data[7].toInt() shl 8) val z = data[8].toInt() and 0xff or (data[9].toInt() shl 8) runOnUiThread { val s = String.format("Accel : %d - (%d, %d, %d)", timeStamp, x, y, z) //Log.w("BLUETOOTH DEBUG", s); mTextLine1!!.setText(s) mTextLine1!!.getRootView().postInvalidate() } } Neblina.NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM.toInt() -> { val x = data[4].toInt() and 0xff or (data[5].toInt() shl 8) val y = data[6].toInt() and 0xff or (data[7].toInt() shl 8) val z = data[8].toInt() and 0xff or (data[9].toInt() shl 8) runOnUiThread { val s = String.format("Gyro : %d - (%d, %d, %d)", timeStamp, x, y, z) //Log.w("BLUETOOTH DEBUG", s); mTextLine1!!.setText(s) mTextLine1!!.getRootView().postInvalidate() } } Neblina.NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM.toInt() -> { val x = data[4].toInt() and 0xff or (data[5].toInt() shl 8) or (data[6].toInt() shl 16) or (data[7].toInt() shl 24) val xf = x.toFloat() / 100.0.toFloat() runOnUiThread { val s = String.format("Humidity : %f %", xf) //Log.w("BLUETOOTH DEBUG", s); mTextLine1!!.setText(s) mTextLine1!!.getRootView().postInvalidate() } } Neblina.NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM.toInt() -> { val x = (data[4].toInt() and 0xff) or ((data[5].toInt() and 0xFF) shl 8) val y = (data[6].toInt() and 0xff) or ((data[7].toInt() and 0xFF) shl 8) val z = (data[8].toInt() and 0xff) or ((data[9].toInt() and 0xFF) shl 8) runOnUiThread { val s = String.format("Mag : %d - (%d, %d, %d)", timeStamp, x, y, z) //Log.w("BLUETOOTH DEBUG", s); mTextLine1!!.setText(s) mTextLine1!!.getRootView().postInvalidate() } } Neblina.NEBLINA_COMMAND_SENSOR_PRESSURE_STREAM.toInt() -> { } Neblina.NEBLINA_COMMAND_SENSOR_TEMPERATURE_STREAM.toInt() -> { val x = data[4].toInt() and 0xff or (data[5].toInt() shl 8) or (data[6].toInt() shl 16) or (data[7].toInt() shl 24) val xf = x.toFloat() / 100.0.toFloat() runOnUiThread { val s = String.format("Temp : %f %", xf) //Log.w("BLUETOOTH DEBUG", s); mTextLine2!!.setText(s) mTextLine2!!.getRootView().postInvalidate() } } Neblina.NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM.toInt() -> { } Neblina.NEBLINA_COMMAND_SENSOR_ACCELEROMETER_MAGNETOMETER_STREAM.toInt() -> { } } } // 3D View public override fun onPrepareView(smartGLView: SmartGLView) { val context = smartGLView.context // Add RenderPass for Sprites & Object3D mRenderer = smartGLView.smartGLRenderer mRenderPassShip = RenderPassObject3D(RenderPassObject3D.ShaderType.SHADER_TEXTURE_LIGHTS, true, true) mRenderPassCube = RenderPassObject3D(RenderPassObject3D.ShaderType.SHADER_COLOR, true, false) mRenderer?.addRenderPass(mRenderPassShip) mRenderer?.setDoubleSided(false) val lightColor = SmartColor(1f, 1f, 1f) val lightDirection = Vector3D(0f, 1f, -1f) lightDirection.normalize() val lightParallel = LightParallel(lightColor, lightDirection) mRenderer?.setLightParallel(lightParallel) mSpaceFrigateTexture = Texture(context, R.drawable.space_frigate_6_color) var model = WavefrontModel.Builder(context, R.raw.space_frigate_obj) .addTexture("", mSpaceFrigateTexture) .create(); mShip = model.toObject3D() mShip?.setPos(0f, 0f, -10f); mRenderPassShip?.addObject(mShip); model = WavefrontModel.Builder(context, R.raw.calibration_cube_obj) .create(); mCube = model.toObject3D() mCube?.setPos(0f, 0f, -10f) mRenderPassCube?.addObject(mCube) mCur3DObj = mShip; } override fun onReleaseView(smartGLView: SmartGLView) { if (mSpaceFrigateTexture != null) { mSpaceFrigateTexture?.release() } } override fun onResizeView(smartGLView: SmartGLView) { // onReleaseView(smartGLView); // onPrepareView(smartGLView); } override fun onTick(smartGLView: SmartGLView) { // val renderer = smartGLView.smartGLRenderer // val frameDuration = renderer.frameDuration } public override fun onTouchEvent(smartGLView:SmartGLView, event:TouchHelperEvent) {} /* class MyGLSurfaceView(context: Context) : GLSurfaceView(context) { private val mRenderer: MyGLRenderer init { // Create an OpenGL ES 2.0 context setEGLContextClientVersion(2) mRenderer = MyGLRenderer() // Set the Renderer for drawing on the GLSurfaceView setRenderer(mRenderer) } } class MyGLRenderer : GLSurfaceView.Renderer { override fun onSurfaceCreated(GL10 gl, EGLConfig config) { // Set the background frame color GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f) } override fun onDrawFrame(unused: GL10) { // Redraw background color GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT) } override fun onSurfaceChanged(unused: GL10, width: Int, height: Int) { GLES20.glViewport(0, 0, width, height) } }*/ }
mit
d857666beef67de2d5455eb4b4e0f094
47.424706
176
0.585409
3.809088
false
false
false
false
google/horologist
media-ui/src/androidTest/java/com/google/android/horologist/test/toolbox/testdoubles/FakePlayerRepository.kt
1
4963
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalHorologistMediaApi::class) package com.google.android.horologist.test.toolbox.testdoubles import com.google.android.horologist.media.ExperimentalHorologistMediaApi import com.google.android.horologist.media.model.Command import com.google.android.horologist.media.model.Media import com.google.android.horologist.media.model.MediaPosition import com.google.android.horologist.media.model.PlayerState import com.google.android.horologist.media.repository.PlayerRepository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlin.time.Duration import kotlin.time.Duration.Companion.seconds class FakePlayerRepository : PlayerRepository { private val _connected = MutableStateFlow(true) override val connected: StateFlow<Boolean> = _connected private var _availableCommandsList = MutableStateFlow(emptySet<Command>()) override val availableCommands: StateFlow<Set<Command>> = _availableCommandsList private var _currentState = MutableStateFlow(PlayerState.Idle) override val currentState: StateFlow<PlayerState> = _currentState private var _currentMedia: MutableStateFlow<Media?> = MutableStateFlow(null) override val currentMedia: StateFlow<Media?> = _currentMedia private var _mediaPosition: MutableStateFlow<MediaPosition?> = MutableStateFlow(null) override val mediaPosition: StateFlow<MediaPosition?> = _mediaPosition private var _shuffleModeEnabled = MutableStateFlow(false) override val shuffleModeEnabled: StateFlow<Boolean> = _shuffleModeEnabled private var _seekBackIncrement = MutableStateFlow<Duration?>(null) override val seekBackIncrement: StateFlow<Duration?> = _seekBackIncrement private var _seekForwardIncrement = MutableStateFlow<Duration?>(null) override val seekForwardIncrement: StateFlow<Duration?> = _seekForwardIncrement private var _mediaList: List<Media>? = null private var currentItemIndex = -1 override fun prepare() { // do nothing } override fun play() { _currentState.value = PlayerState.Playing } override fun seekToDefaultPosition(mediaIndex: Int) { currentItemIndex = mediaIndex } override fun pause() { _currentState.value = PlayerState.Ready } override fun hasPreviousMedia(): Boolean = currentItemIndex > 0 override fun skipToPreviousMedia() { currentItemIndex-- _currentMedia.value = _mediaList!![currentItemIndex] } override fun hasNextMedia(): Boolean = _mediaList?.let { currentItemIndex < it.size - 2 } ?: false override fun skipToNextMedia() { currentItemIndex++ _currentMedia.value = _mediaList!![currentItemIndex] } override fun seekBack() { // do nothing } override fun seekForward() { // do nothing } override fun setShuffleModeEnabled(shuffleModeEnabled: Boolean) { // do nothing } override fun setMedia(media: Media) { _currentMedia.value = media currentItemIndex = 0 } override fun setMediaList(mediaList: List<Media>) { _mediaList = mediaList currentItemIndex = 0 _currentMedia.value = mediaList[currentItemIndex] } override fun setMediaListAndPlay(mediaList: List<Media>, index: Int) { // do nothing } override fun addMedia(media: Media) { // do nothing } override fun addMedia(index: Int, media: Media) { // do nothing } override fun removeMedia(index: Int) { // do nothing } override fun clearMediaList() { // do nothing } override fun getMediaCount(): Int = _mediaList?.size ?: 0 override fun getMediaAt(index: Int): Media? = null // not implemented override fun getCurrentMediaIndex(): Int = 0 // not implemented override fun release() { _connected.value = false } fun updatePosition() { _mediaPosition.value = _mediaPosition.value?.let { val newCurrent = (it as MediaPosition.KnownDuration).current + 1.seconds MediaPosition.create(newCurrent, it.duration) } ?: MediaPosition.create(1.seconds, 10.seconds) } fun addCommand(command: Command) { _availableCommandsList.value += command } }
apache-2.0
7ee5b0c52c6c874acdf117d087f95c96
30.611465
89
0.706025
4.717681
false
false
false
false
tmarsteel/compiler-fiddle
src/compiler/binding/BoundAssignmentStatement.kt
1
4415
/* * Copyright 2018 Tobias Marstaller * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package compiler.binding import compiler.InternalCompilerError import compiler.ast.AssignmentStatement import compiler.ast.Executable import compiler.binding.context.CTContext import compiler.binding.expression.BoundExpression import compiler.binding.expression.BoundIdentifierExpression import compiler.binding.expression.BoundMemberAccessExpression import compiler.nullableOr import compiler.reportings.Reporting class BoundAssignmentStatement( override val context: CTContext, override val declaration: AssignmentStatement, val targetExpression: BoundExpression<*>, val valueExpression: BoundExpression<*> ) : BoundExecutable<AssignmentStatement> { /** * What this statement assigns to. Must not be null after semantic analysis has been completed. */ var assignmentTargetType: AssignmentTargetType? = null private set /** * The variable this statement assigns to, if it does assign to a variable (see [assignmentTargetType]) */ var targetVariable: BoundVariable? = null private set override val isGuaranteedToThrow: Boolean? get() = targetExpression.isGuaranteedToThrow nullableOr valueExpression.isGuaranteedToThrow override fun semanticAnalysisPhase1() = targetExpression.semanticAnalysisPhase1() + valueExpression.semanticAnalysisPhase1() override fun semanticAnalysisPhase2() = targetExpression.semanticAnalysisPhase2() + valueExpression.semanticAnalysisPhase2() override fun semanticAnalysisPhase3(): Collection<Reporting> { val reportings = mutableSetOf<Reporting>() // TODO // reject if the targetExpression does not point to something that // can or should be written to if (targetExpression is BoundIdentifierExpression) { reportings.addAll(targetExpression.semanticAnalysisPhase3()) if (targetExpression.referredType == BoundIdentifierExpression.ReferredType.VARIABLE) { assignmentTargetType = AssignmentTargetType.VARIABLE targetVariable = targetExpression.referredVariable!! if (!targetVariable!!.isAssignable) { reportings.add(Reporting.illegalAssignment("Cannot assign to value / final variable ${targetVariable!!.name}", this)) } } else { reportings += Reporting.illegalAssignment("Cannot assign a value to a type", this) } } else if (targetExpression is BoundMemberAccessExpression) { } else { reportings += Reporting.illegalAssignment("Cannot assign to this target", this) } return reportings } override fun findReadsBeyond(boundary: CTContext): Collection<BoundExecutable<Executable<*>>> { return valueExpression.findReadsBeyond(boundary) } override fun findWritesBeyond(boundary: CTContext): Collection<BoundExecutable<Executable<*>>> { val writesByValueExpression = valueExpression.findWritesBeyond(boundary) if (assignmentTargetType == AssignmentTargetType.VARIABLE) { // check whether the target variable is beyond the boundary if (context.containsWithinBoundary(targetVariable!!, boundary)) { return writesByValueExpression } else { return writesByValueExpression + this } } else { throw InternalCompilerError("Write boundary check for $assignmentTargetType not implemented yet") } } enum class AssignmentTargetType { VARIABLE, OBJECT_MEMBER } }
lgpl-3.0
2ed9353dfd6378b129ea4cd2ce9fc896
38.783784
137
0.70872
5.268496
false
false
false
false
exteso/alf.io-PI
backend/src/main/kotlin/alfio/pi/repository/UserRepository.kt
1
3492
/* * This file is part of alf.io. * * alf.io 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. * * alf.io 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 alf.io. If not, see <http://www.gnu.org/licenses/>. */ package alfio.pi.repository import alfio.pi.model.Event import alfio.pi.model.Role import alfio.pi.model.User import ch.digitalfondue.npjt.* import java.util.* @QueryRepository interface UserRepository { @Query("insert into user(username, password) values(:username, :password)") fun insert(@Bind("username") username: String, @Bind("password") password: String): AffectedRowCountAndKey<Int> @Query("select id, username from user where username = :username") fun findByUsername(@Bind("username") username: String): Optional<User> @Query("select id, username from user where id = :userId") fun findById(@Bind("userId") id: Int): Optional<User> @Query("select user.id, user.username from user, authority where user.username = authority.username and authority.role <> 'ADMIN'") fun findAllOperators(): List<User> @Query("update user set password = :password where id = :userId") fun updatePassword(@Bind("userId") id: Int, @Bind("password") password: String) } @QueryRepository interface AuthorityRepository { @Query("insert into authority(username, role) values(:username, :role)") fun insert(@Bind("username") username: String, @Bind("role") role: Role): Int } @QueryRepository interface EventRepository { @Query("select * from event") fun loadAll(): List<Event> @Query("select * from event where key = :key") fun loadSingle(@Bind("key") eventName: String): Optional<Event> @Query(type = QueryType.TEMPLATE, value = "insert into event(key, name, image_url, begin_ts, end_ts, location, api_version, one_day, active, timezone) values(:key, :name, :imageUrl, :begin, :end, :location, :apiVersion, :oneDay, :active, :timezone)") fun bulkInsert(): String @Query(type = QueryType.TEMPLATE, value = "update event set name = :name, image_url = :imageUrl, begin_ts = :begin, end_ts = :end, location = :location, api_version = :apiVersion, one_day = :oneDay, timezone = :timezone where key = :key") fun bulkUpdate(): String @Query("update event set active = :state where key = :key") fun toggleActivation(@Bind("key") id: String, @Bind("state") state: Boolean): Int } @QueryRepository interface ConfigurationRepository { companion object { const val PRINTER_REMAINING_LABEL_DEFAULT_COUNTER = "PRINTER_REMAINING_LABEL_DEFAULT_COUNTER" } @Query("""merge into configuration using (values (:key, :value)) as vals(key, value) on configuration.key = vals.key when matched then update set configuration.value = vals.value when not matched then insert values vals.key, vals.value""") fun insertOrUpdate(@Bind("key") key : String, @Bind("value") value: String) : Int @Query("select value from configuration where key = :key") fun getData(@Bind("key") key : String) : Optional<String> }
gpl-3.0
4c45d014237f27f4db62edb3130007d7
39.616279
254
0.706472
3.86711
false
true
false
false
AllanWang/Frost-for-Facebook
app/src/main/kotlin/com/pitchedapps/frost/facebook/parsers/BadgeParser.kt
1
2010
/* * Copyright 2020 Allan Wang * * 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.pitchedapps.frost.facebook.parsers import com.pitchedapps.frost.R import com.pitchedapps.frost.facebook.FB_URL_BASE import org.jsoup.nodes.Document object BadgeParser : FrostParser<FrostBadges> by BadgeParserImpl() data class FrostBadges( val feed: String?, val friends: String?, val messages: String?, val notifications: String? ) : ParseData { override val isEmpty: Boolean get() = feed.isNullOrEmpty() && friends.isNullOrEmpty() && messages.isNullOrEmpty() && notifications.isNullOrEmpty() } private class BadgeParserImpl : FrostParserBase<FrostBadges>(false) { // Not actually displayed override var nameRes: Int = R.string.frost_name override val url: String = FB_URL_BASE override fun parseImpl(doc: Document): FrostBadges? { val header = doc.getElementById("header") ?: return null if (header.select("[data-sigil=count]").isEmpty()) return null val (feed, requests, messages, notifications) = listOf("feed", "requests", "messages", "notifications") .map { "[data-sigil*=$it] [data-sigil=count]" } .map { doc.select(it) } .map { e -> e?.getOrNull(0)?.ownText() } return FrostBadges( feed = feed, friends = requests, messages = messages, notifications = notifications ) } }
gpl-3.0
d863bc73d73c9af675f6c42e1f6cc3dd
32.5
72
0.69801
3.996024
false
false
false
false
wuseal/JsonToKotlinClass
src/main/kotlin/wu/seal/jsontokotlin/utils/KotlinClassFileGenerator.kt
1
4346
package wu.seal.jsontokotlin.utils import com.intellij.openapi.project.Project import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiFileFactory import wu.seal.jsontokotlin.model.classscodestruct.KotlinClass import wu.seal.jsontokotlin.filetype.KotlinFileType class KotlinClassFileGenerator { fun generateSingleKotlinClassFile( packageDeclare: String, kotlinClass: KotlinClass, project: Project?, psiFileFactory: PsiFileFactory, directory: PsiDirectory ) { val fileNamesWithoutSuffix = currentDirExistsFileNamesWithoutKTSuffix(directory) var kotlinClassForGenerateFile = kotlinClass while (fileNamesWithoutSuffix.contains(kotlinClass.name)) { kotlinClassForGenerateFile = kotlinClassForGenerateFile.rename(newName = kotlinClassForGenerateFile.name + "X") } generateKotlinClassFile( kotlinClassForGenerateFile.name, packageDeclare, kotlinClassForGenerateFile.getCode(), project, psiFileFactory, directory ) val notifyMessage = "Kotlin Data Class file generated successful" showNotify(notifyMessage, project) } fun generateMultipleKotlinClassFiles( kotlinClass: KotlinClass, packageDeclare: String, project: Project?, psiFileFactory: PsiFileFactory, directory: PsiDirectory, generatedFromJSONSchema: Boolean ) { val fileNamesWithoutSuffix = currentDirExistsFileNamesWithoutKTSuffix(directory) val existsKotlinFileNames = IgnoreCaseStringSet().also { it.addAll(fileNamesWithoutSuffix) } val splitClasses = kotlinClass.resolveNameConflicts(existsKotlinFileNames).getAllModifiableClassesRecursivelyIncludeSelf().run { if (!generatedFromJSONSchema) distinctByPropertiesAndSimilarClassName() else this } splitClasses.forEach { splitDataClass -> generateKotlinClassFile( splitDataClass.name, packageDeclare, splitDataClass.getOnlyCurrentCode(), project, psiFileFactory, directory ) } val notifyMessage = buildString { append("${splitClasses.size} Kotlin Data Class files generated successful") } showNotify(notifyMessage, project) } private fun currentDirExistsFileNamesWithoutKTSuffix(directory: PsiDirectory): List<String> { val kotlinFileSuffix = ".kt" return directory.files.filter { it.name.endsWith(kotlinFileSuffix) } .map { it.name.dropLast(kotlinFileSuffix.length) } } private fun getRenameClassMap(originNames: List<String>, currentNames: List<String>): List<Pair<String, String>> { if (originNames.size != currentNames.size) { throw IllegalArgumentException("two names list must have the same size!") } val renameMap = mutableListOf<Pair<String, String>>() originNames.forEachIndexed { index, originName -> if (originName != currentNames[index]) { renameMap.add(Pair(originName, currentNames[index])) } } return renameMap } private fun generateKotlinClassFile( fileName: String, packageDeclare: String, classCodeContent: String, project: Project?, psiFileFactory: PsiFileFactory, directory: PsiDirectory ) { val kotlinFileContent = buildString { if (packageDeclare.isNotEmpty()) { append(packageDeclare) append("\n\n") } val importClassDeclaration = ClassImportDeclaration.getImportClassDeclaration() if (importClassDeclaration.isNotBlank()) { append(importClassDeclaration) append("\n\n") } append(classCodeContent) } executeCouldRollBackAction(project) { val file = psiFileFactory.createFileFromText("${fileName.trim('`')}.kt", KotlinFileType(), kotlinFileContent) directory.add(file) } } }
gpl-3.0
4122926e9dd2a755be9d54794387ea1b
38.153153
136
0.629084
5.600515
false
false
false
false
uber/RIBs
android/libraries/rib-router-navigator/src/main/kotlin/com/uber/rib/core/RouterNavigator.kt
1
11792
/* * Copyright (C) 2017. Uber Technologies * * 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.uber.rib.core import androidx.annotation.IntRange import org.checkerframework.checker.guieffect.qual.PolyUIEffect import org.checkerframework.checker.guieffect.qual.PolyUIType import org.checkerframework.checker.guieffect.qual.UIEffect /** * Simple utility for switching a child router based on a state. * * @param <StateT> type of state to switch on. */ interface RouterNavigator<StateT : RouterNavigatorState> { /** Determine how pushes will affect the stack */ enum class Flag { /** Push a new state to the top of the stack. */ DEFAULT, /** Push a state that will not be retained when the next state is pushed. */ TRANSIENT, /** * Start looking at the stack from the top until we see the state that is being pushed. If it is * found, remove all states that we traversed and transition the app to the found state. If the * state is not found in the stack, create a new instance and transition to it pushing it on top * of the stack. */ CLEAR_TOP, /** * First create a new instance of the state and push it to the top of the stack. Then traverse * down the stack and and delete any instances of the state being pushed. */ SINGLE_TOP, /** * Search through the stack for the state and if found, move the state to the top but don’t * change the stack otherwise. If the state doesn’t exist in the stack, create a new instance * and push to the top. */ REORDER_TO_TOP, /** Clears the previous stack (no back stack) and pushes the state on to the top of the stack */ NEW_TASK, /** * Clears the previous stack (no back stack) and pushes the state on to the top of the stack. * If the state is already on the top of the stack, it is detached and replaced. */ NEW_TASK_REPLACE, /** * Remove the top state in the stack if it is not empty and then push a new state to the top of * the stack. */ REPLACE_TOP, } /** Pop the current state and rewind to the previous state (if there is a previous state). */ fun popState() /** * Switch to a new state - this will switch out children if the state is not the current active * state already. * * * NOTE: This will retain the Riblet in memory until it is popped or detached by a push with * certain flags. * * @param newState to switch to. * @param attachTransition method to attach child router. * @param detachTransition method to clean up child router when removed. * @param <R> router type to detach. </R> */ fun <R : Router<*>> pushState( newState: StateT, attachTransition: AttachTransition<R, StateT>, detachTransition: DetachTransition<R, StateT>? ) /** * Switch to a new state - this will switch out children if the state is not the current active * state already. The transition will be controlled by the [StackRouterNavigator.Flag] * provided. * * * NOTE: This will retain the Riblet in memory until it is popped or detached by a push with * certain flags. * * @param newState to switch to. * @param attachTransition method to attach child router. * @param detachTransition method to clean up child router when removed. * @param <R> router type to detach. </R> */ fun <R : Router<*>> pushState( newState: StateT, flag: Flag, attachTransition: AttachTransition<R, StateT>, detachTransition: DetachTransition<R, StateT>? ) /** * Switch to a new state - this will switch out children if the state is not the current active * state already. * * * NOTE: This will retain the Riblet in memory until it is popped. To push transient, riblets, * use [RouterNavigator.pushTransientState] * * * Deprecated: Use pushState(newState, attachTransition, detachTransition) * * @param newState to switch to. * @param attachTransition method to attach child router. * @param detachTransition method to clean up child router when removed. * @param <R> router type to detach. </R> */ @Deprecated("") fun <R : Router<*>> pushRetainedState( newState: StateT, attachTransition: AttachTransition<R, StateT>, detachTransition: DetachTransition<R, StateT>? ) /** * Switch to a new state - this will switch out children if the state is not the current active * state already. * * * NOTE: This will retain the Riblet in memory until it is popped. To push transient, riblets, * use [RouterNavigator.pushTransientState] * * * Deprecated: Use pushState(newState, attachTransition, null) * * @param newState to switch to. * @param attachTransition method to attach child router. * @param <R> [Router] type. </R> */ @Deprecated("") fun <R : Router<*>> pushRetainedState( newState: StateT, attachTransition: AttachTransition<R, StateT> ) /** * Switch to a new transient state - this will switch out children if the state is not the current * active state already. * * * NOTE: Transient states do not live in the back navigation stack. * * * Deprecated: Use pushState(newState, Flag.TRANSIENT, attachTransition, detachTransition) * * @param newState to switch to. * @param attachTransition method to attach child router. * @param detachTransition method to clean up child router when removed. * @param <R> router type to detach. </R> */ @Deprecated("") fun <R : Router<*>> pushTransientState( newState: StateT, attachTransition: AttachTransition<R, StateT>, detachTransition: DetachTransition<R, StateT>? ) /** * Switch to a new transient state - this will switch out children if the state is not the current * active state already. * * * NOTE: Transient states do not live in the back navigation stack. * * * Deprecated: Use pushState(newState, Flag.TRANSIENT, attachTransition, null) * * @param newState to switch to. * @param attachTransition method to attach child router. * @param <R> [Router] type. </R> */ @Deprecated("") fun <R : Router<*>> pushTransientState( newState: StateT, attachTransition: AttachTransition<R, StateT> ) /** * Peek the top [Router] on the stack. * * @return the top [Router] on the stack. */ fun peekRouter(): Router<*>? /** * Peek the top [StateT] on the stack. * * @return the top [StateT] on the stack. */ fun peekState(): StateT? /** * Gets the size of the navigation stack. * * @return Size of the navigation stack. */ @IntRange(from = 0) fun size(): Int /** * Must be called when host interactor is going to detach. This will pop the current active router * and clear the entire stack. */ fun hostWillDetach() /** * Allows consumers to write custom attachment logic when switching states. * * @param <StateT> state type. </StateT> */ interface AttachTransition<RouterT : Router<*>, StateT : RouterNavigatorState> { /** * Constructs a new [RouterT] instance. This will only be called once. * * @return the newly attached child router. */ fun buildRouter(): RouterT /** * Prepares the router for a state transition. [StackRouterNavigator] will handling * attaching the router, but consumers of this should handle adding any views. * * @param router [RouterT] that is being attached. * @param previousState state the navigator is transition from (if any). * @param newState state the navigator is transitioning to. */ @UIEffect fun willAttachToHost( router: RouterT, previousState: StateT?, newState: StateT, isPush: Boolean ) } /** * Allows consumers to write custom detachment logic when the state is changing. This allows for * custom state prior to and immediately post detach. * * @param <RouterT> [RouterT] * @param <StateT> [StateT] </StateT></RouterT> */ abstract class DetachCallback<RouterT : Router<*>, StateT : RouterNavigatorState> : DetachTransition<RouterT, StateT> { override fun willDetachFromHost( router: RouterT, previousState: StateT, newState: StateT?, isPush: Boolean ) { } /** * Notifies the consumer that the [StackRouterNavigator] has detached the supplied [ ]. Consumers can complete any post detachment behavior here. * * @param router [Router] * @param newState [StateT] */ open fun onPostDetachFromHost(router: RouterT, newState: StateT?, isPush: Boolean) {} } /** * Allows consumers to write custom detachment logic wen switching states. * * @param <RouterT> router type to detach. * @param <StateT> state type. </StateT></RouterT> */ @PolyUIType interface DetachTransition<RouterT : Router<*>, StateT : RouterNavigatorState> { /** * Notifies consumer that [StackRouterNavigator] is going to detach this router. Consumers * should remove any views and perform any required cleanup. * * @param router being removed. * @param previousState state the navigator is transitioning out of. * @param newState state the navigator is transition in to (if any). */ @PolyUIEffect fun willDetachFromHost( router: RouterT, previousState: StateT, newState: StateT?, isPush: Boolean ) } /** Internal class for keeping track of a navigation stack. */ class RouterAndState<StateT : RouterNavigatorState?> internal constructor( /** * Gets the [Router] associated with this state. * * @return [Router] */ open val router: Router<*>, /** * Gets the state. * * @return [StateT] */ open val state: StateT, /** * Gets the [AttachTransition] associated with this state. * * @return [AttachTransition] */ internal open val attachTransition: AttachTransition<*, *>, detachTransition: DetachTransition<*, *>? ) { /** * Gets the [DetachCallback] associated with this state. * * @return [DetachCallback] */ internal open var detachCallback: DetachCallback<*, *>? = null init { detachCallback = if (detachTransition != null) { if (detachTransition is DetachCallback<*, *>) { detachTransition } else { DetachCallbackWrapper(detachTransition) } } else { null } } } /** * Wrapper class to wrap [DetachTransition] calls into the new [DetachCallback] * format. * * @param <RouterT> [RouterT] * @param <StateT> [StateT] </StateT></RouterT> */ class DetachCallbackWrapper<RouterT : Router<*>, StateT : RouterNavigatorState> internal constructor( transitionCallback: DetachTransition<RouterT, StateT> ) : DetachCallback<RouterT, StateT>() { private val transitionCallback: DetachTransition<RouterT, StateT> = transitionCallback override fun willDetachFromHost( router: RouterT, previousState: StateT, newState: StateT?, isPush: Boolean ) { transitionCallback.willDetachFromHost(router, previousState, newState, isPush) } } }
apache-2.0
07d649b911ad101809280bbe9489da25
30.434667
149
0.666695
4.169791
false
false
false
false
italoag/qksms
domain/src/main/java/com/moez/QKSMS/model/Contact.kt
3
1205
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS 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. * * QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.model import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class Contact( @PrimaryKey var lookupKey: String = "", var numbers: RealmList<PhoneNumber> = RealmList(), var name: String = "", var photoUri: String? = null, var starred: Boolean = false, var lastUpdate: Long = 0 ) : RealmObject() { fun getDefaultNumber(): PhoneNumber? = numbers.find { number -> number.isDefault } }
gpl-3.0
434f63f11606737af91168b538e2bd84
32.472222
86
0.717842
4.016667
false
false
false
false
dataloom/conductor-client
src/main/kotlin/com/openlattice/data/storage/PostgresEntityDataQueryService.kt
1
50887
package com.openlattice.data.storage import com.codahale.metrics.annotation.Timed import com.openlattice.IdConstants import com.openlattice.analysis.SqlBindInfo import com.openlattice.analysis.requests.Filter import com.openlattice.data.DeleteType import com.openlattice.data.WriteEvent import com.openlattice.data.storage.PostgresEntitySetSizesInitializationTask.Companion.ENTITY_SET_SIZES_VIEW import com.openlattice.data.storage.partitions.PartitionManager import com.openlattice.data.storage.partitions.getPartition import com.openlattice.data.util.PostgresDataHasher import com.openlattice.edm.type.PropertyType import com.openlattice.postgres.* import com.openlattice.postgres.PostgresColumn.* import com.openlattice.postgres.PostgresTable.DATA import com.openlattice.postgres.PostgresTable.IDS import com.openlattice.postgres.streams.BasePostgresIterable import com.openlattice.postgres.streams.PreparedStatementHolderSupplier import com.openlattice.postgres.streams.StatementHolderSupplier import com.zaxxer.hikari.HikariDataSource import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind import org.apache.olingo.commons.api.edm.FullQualifiedName import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import java.lang.Exception import java.nio.ByteBuffer import java.security.InvalidParameterException import java.sql.Connection import java.sql.PreparedStatement import java.sql.ResultSet import java.util.* import java.util.concurrent.atomic.AtomicLong import kotlin.streams.asStream const val S3_DELETE_BATCH_SIZE = 10_000 /** * * @author Matthew Tamayo-Rios &lt;[email protected]&gt; */ @Service class PostgresEntityDataQueryService( private val hds: HikariDataSource, private val reader: HikariDataSource, private val byteBlobDataManager: ByteBlobDataManager, protected val partitionManager: PartitionManager ) { companion object { private val logger = LoggerFactory.getLogger(PostgresEntityDataQueryService::class.java) } fun getEntitySetCounts(): Map<UUID, Long> { return BasePostgresIterable(StatementHolderSupplier(reader, "SELECT * FROM $ENTITY_SET_SIZES_VIEW")) { ResultSetAdapters.entitySetId(it) to ResultSetAdapters.count(it) }.toMap() } @JvmOverloads fun getEntitiesWithPropertyTypeIds( entityKeyIds: Map<UUID, Optional<Set<UUID>>>, authorizedPropertyTypes: Map<UUID, Map<UUID, PropertyType>>, propertyTypeFilters: Map<UUID, Set<Filter>> = mapOf(), metadataOptions: Set<MetadataOption> = EnumSet.noneOf(MetadataOption::class.java), version: Optional<Long> = Optional.empty() ): BasePostgresIterable<Pair<UUID, Map<UUID, Set<Any>>>> { return getEntitySetIterable( entityKeyIds, authorizedPropertyTypes, propertyTypeFilters, metadataOptions, version ) { rs -> getEntityPropertiesByPropertyTypeId(rs, authorizedPropertyTypes, metadataOptions, byteBlobDataManager) } } @JvmOverloads fun getLinkedEntitiesWithPropertyTypeIds( entityKeyIds: Map<UUID, Optional<Set<UUID>>>, authorizedPropertyTypes: Map<UUID, Map<UUID, PropertyType>>, propertyTypeFilters: Map<UUID, Set<Filter>> = mapOf(), metadataOptions: Set<MetadataOption> = EnumSet.noneOf(MetadataOption::class.java), version: Optional<Long> = Optional.empty() ): BasePostgresIterable<Pair<UUID, Map<UUID, Set<Any>>>> { return getEntitySetIterable( entityKeyIds, authorizedPropertyTypes, propertyTypeFilters, metadataOptions, version, linking = true ) { rs -> getEntityPropertiesByPropertyTypeId(rs, authorizedPropertyTypes, metadataOptions, byteBlobDataManager) } } fun getEntitySetWithPropertyTypeIdsIterable( entityKeyIds: Map<UUID, Optional<Set<UUID>>>, authorizedPropertyTypes: Map<UUID, Map<UUID, PropertyType>>, metadataOptions: Set<MetadataOption> = EnumSet.noneOf(MetadataOption::class.java) ): BasePostgresIterable<Pair<UUID, Map<UUID, Set<Any>>>> { return getEntitiesWithPropertyTypeIds(entityKeyIds, authorizedPropertyTypes, mapOf(), metadataOptions) } /** * Returns linked entity set data detailed in a Map mapped by linking id, (normal) entity set id, origin id, * property type id and values respectively. */ @JvmOverloads fun getLinkedEntitiesByEntitySetIdWithOriginIds( entityKeyIds: Map<UUID, Optional<Set<UUID>>>, authorizedPropertyTypes: Map<UUID, Map<UUID, PropertyType>>, metadataOptions: EnumSet<MetadataOption> = EnumSet.noneOf(MetadataOption::class.java), propertyTypeFilters: Map<UUID, Set<Filter>> = mapOf(), version: Optional<Long> = Optional.empty() ): BasePostgresIterable<Pair<UUID, Pair<UUID, Map<UUID, MutableMap<UUID, MutableSet<Any>>>>>> { return getEntitySetIterable( entityKeyIds, authorizedPropertyTypes, propertyTypeFilters, metadataOptions, version, linking = true, detailed = true ) { rs -> getEntityPropertiesByEntitySetIdOriginIdAndPropertyTypeId( rs, authorizedPropertyTypes, metadataOptions, byteBlobDataManager ) } } /** * Returns linked entity set data detailed in a Map mapped by linking id, (normal) entity set id, origin id, * property type full qualified name and values respectively. */ @JvmOverloads fun getLinkedEntitySetBreakDown( entityKeyIds: Map<UUID, Optional<Set<UUID>>>, authorizedPropertyTypes: Map<UUID, Map<UUID, PropertyType>>, propertyTypeFilters: Map<UUID, Set<Filter>> = mapOf(), version: Optional<Long> = Optional.empty() ): BasePostgresIterable<Pair<UUID, Pair<UUID, Map<UUID, MutableMap<FullQualifiedName, MutableSet<Any>>>>>> { return getEntitySetIterable( entityKeyIds, authorizedPropertyTypes, propertyTypeFilters, EnumSet.noneOf(MetadataOption::class.java), version, linking = true, detailed = true ) { rs -> getEntityPropertiesByEntitySetIdOriginIdAndPropertyTypeFqn( rs, authorizedPropertyTypes, EnumSet.noneOf(MetadataOption::class.java), byteBlobDataManager ) } } @JvmOverloads fun getEntitiesWithPropertyTypeFqns( entityKeyIds: Map<UUID, Optional<Set<UUID>>>, authorizedPropertyTypes: Map<UUID, Map<UUID, PropertyType>>, propertyTypeFilters: Map<UUID, Set<Filter>> = mapOf(), metadataOptions: Set<MetadataOption> = EnumSet.noneOf(MetadataOption::class.java), version: Optional<Long> = Optional.empty(), linking: Boolean = false ): Map<UUID, MutableMap<FullQualifiedName, MutableSet<Any>>> { return getEntitySetIterable( entityKeyIds, authorizedPropertyTypes, propertyTypeFilters, metadataOptions, version, linking ) { rs -> getEntityPropertiesByFullQualifiedName( rs, authorizedPropertyTypes, metadataOptions, byteBlobDataManager ) }.toMap() } /** * Note: for linking queries, linking id and entity set id will be returned, thus data won't be merged by linking id */ private fun <T> getEntitySetIterable( entityKeyIds: Map<UUID, Optional<Set<UUID>>>, authorizedPropertyTypes: Map<UUID, Map<UUID, PropertyType>>, propertyTypeFilters: Map<UUID, Set<Filter>> = mapOf(), metadataOptions: Set<MetadataOption> = EnumSet.noneOf(MetadataOption::class.java), version: Optional<Long> = Optional.empty(), linking: Boolean = false, detailed: Boolean = false, adapter: (ResultSet) -> T ): BasePostgresIterable<T> { val propertyTypes = authorizedPropertyTypes.values.flatMap { it.values }.associateBy { it.id } val entitySetIds = entityKeyIds.keys val ids = entityKeyIds.values.flatMap { it.orElse(emptySet()) }.toSet() // For linking queries we use all the partitions of participating entity sets, since cannot narrow down the // partitions due to the lack of origin ids val partitions = entityKeyIds.flatMap { (entitySetId, maybeEntityKeyIds) -> val entitySetPartitions = partitionManager.getEntitySetPartitions(entitySetId).toList() if (!linking) { maybeEntityKeyIds.map { getPartitionsInfo(it, entitySetPartitions) }.orElse(entitySetPartitions) } else { entitySetPartitions } }.toSet() var startIndex = 2 if (ids.isNotEmpty()) { startIndex++ } if (partitions.isNotEmpty()) { startIndex++ } val (sql, binders) = buildPreparableFiltersSql( startIndex, propertyTypes, propertyTypeFilters, metadataOptions, linking, ids.isNotEmpty(), partitions.isNotEmpty(), detailed ) return BasePostgresIterable(PreparedStatementHolderSupplier(reader, sql, FETCH_SIZE) { ps -> val metaBinders = linkedSetOf<SqlBinder>() var bindIndex = 1 metaBinders.add( SqlBinder( SqlBindInfo(bindIndex++, PostgresArrays.createUuidArray(ps.connection, entitySetIds)), ::doBind ) ) if (ids.isNotEmpty()) { metaBinders.add( SqlBinder( SqlBindInfo(bindIndex++, PostgresArrays.createUuidArray(ps.connection, ids)), ::doBind ) ) } if (partitions.isNotEmpty()) { metaBinders.add( SqlBinder( SqlBindInfo(bindIndex, PostgresArrays.createIntArray(ps.connection, partitions)), ::doBind ) ) } (metaBinders + binders).forEach { it.bind(ps) } }, adapter) } /** * Updates or insert entities. * @param entitySetId The entity set id for which to insert entities for. * @param entities The entites to update or insert. * @param authorizedPropertyTypes The authorized property types for the insertion. * @param awsPassthrough True if the data will be stored directly in AWS via another means and all that is being * provided is the s3 prefix and key. * @param partitions Contains the partition information for the requested entity set. * * @return A write event summarizing the results of performing this operation. */ @Timed fun upsertEntities( entitySetId: UUID, entities: Map<UUID, Map<UUID, Set<Any>>>, authorizedPropertyTypes: Map<UUID, PropertyType>, awsPassthrough: Boolean = false, partitions: List<Int> = partitionManager.getEntitySetPartitions(entitySetId).toList() ): WriteEvent { val version = System.currentTimeMillis() val tombstoneFn = { _: Long, _: Map<UUID, Map<UUID, Set<Any>>> -> } return upsertEntities( entitySetId, tombstoneFn, entities, authorizedPropertyTypes, version, partitions, awsPassthrough ) } /** * Updates or insert entities. * @param entitySetId The entity set id for which to insert entities. * @param tombstoneFn A function that may tombstone values before performing the upsert. * @param entities The entities to update or insert. * @param authorizedPropertyTypes The authorized property types for the insertion. * @param version The version to use for upserting. * @param partitions Contains the partition information for the requested entity set. * @param awsPassthrough True if the data will be stored directly in AWS via another means and all that is being * provided is the s3 prefix and key. * * @return A write event summarizing the results of performing this operation. */ private fun upsertEntities( entitySetId: UUID, tombstoneFn: (version: Long, entityBatch: Map<UUID, Map<UUID, Set<Any>>>) -> Unit, entities: Map<UUID, Map<UUID, Set<Any>>>, // ekids -> authorizedPropertyTypes: Map<UUID, PropertyType>, version: Long, partitions: List<Int> = partitionManager.getEntitySetPartitions(entitySetId).toList(), awsPassthrough: Boolean = false ): WriteEvent { var updatedEntityCount = 0 var updatedPropertyCounts = 0 entities.entries .groupBy { getPartition(it.key, partitions) } .toSortedMap() .forEach { (partition, batch) -> var entityBatch = batch.associate { it.key to it.value } if (!awsPassthrough) { entityBatch = entityBatch.mapValues { JsonDeserializer.validateFormatAndNormalize( it.value, authorizedPropertyTypes ) { "Entity set $entitySetId with entity key id ${it.key}" } } } tombstoneFn(version, entityBatch) val upc = upsertEntities( entitySetId, entityBatch, authorizedPropertyTypes, version + 1, partition, awsPassthrough ) //For now we can't track how many entities were updated in a call transactionally. //If we want to check how many entities were written at a specific version that is possible but //expensive. updatedEntityCount += batch.size updatedPropertyCounts += upc } logger.debug("Updated $updatedEntityCount entities and $updatedPropertyCounts properties") return WriteEvent(version, updatedEntityCount) } private fun upsertEntities( entitySetId: UUID, entities: Map<UUID, Map<UUID, Set<Any>>>, authorizedPropertyTypes: Map<UUID, PropertyType>, version: Long, partition: Int, awsPassthrough: Boolean ): Int { val entitiesWithHashAndInsertData = entities.mapValues { entityKeyIdToEntity -> entityKeyIdToEntity.value.mapValues { propertyTypeIdToPropertyValues -> propertyTypeIdToPropertyValues.value.map { propertyValue -> getPropertyHash( entitySetId, entityKeyIdToEntity.key, propertyTypeIdToPropertyValues.key, propertyValue, authorizedPropertyTypes.getValue(propertyTypeIdToPropertyValues.key).datatype, awsPassthrough ) } } } return hds.connection.use { connection -> //Update the versions of all entities. val versionsArrays = PostgresArrays.createLongArray(connection, version) /* * We do not need entity level locking as the version in the ids table ensures that data is consistent even * if the follow property upserts fails halfway through. * * Previous me said deletes had to be handled specially, but it makes sense that clear is fine. * */ //Update property values. We use multiple prepared statements in batch while re-using ARRAY[version]. val upsertPropertyValues = mutableMapOf<UUID, PreparedStatement>() val updatedPropertyCounts = entitiesWithHashAndInsertData.entries.map { (entityKeyId, entityData) -> entityData.map { (propertyTypeId, hashAndInsertValue) -> val upsertPropertyValue = upsertPropertyValues.getOrPut(propertyTypeId) { val pt = authorizedPropertyTypes[propertyTypeId] ?: abortInsert(entitySetId, entityKeyId) connection.prepareStatement(upsertPropertyValueSql(pt)) } hashAndInsertValue.map { (propertyHash, insertValue) -> upsertPropertyValue.setObject(1, entitySetId) upsertPropertyValue.setObject(2, entityKeyId) upsertPropertyValue.setInt(3, partition) upsertPropertyValue.setObject(4, propertyTypeId) upsertPropertyValue.setBytes(5, propertyHash) upsertPropertyValue.setObject(6, version) upsertPropertyValue.setArray(7, versionsArrays) upsertPropertyValue.setObject(8, insertValue) upsertPropertyValue.addBatch() } } upsertPropertyValues.values.map { it.executeBatch().sum() }.sum() }.sum() /** * At this point, we either need to either commit all versions by updating the version in the ids table our * fail out. Dead locks should be impossible due to explicit locking within the transaction. * */ //Make data visible by marking new version in ids table. val ps = connection.prepareStatement(updateEntitySql) entities.keys.sorted().forEach { entityKeyId -> ps.setArray(1, versionsArrays) ps.setObject(2, version) ps.setObject(3, version) ps.setObject(4, entitySetId) ps.setObject(5, entityKeyId) ps.setInt(6, partition) ps.addBatch() } val updatedEntities = ps.executeBatch().sum() logger.debug("Updated $updatedEntities entities as part of insert.") return updatedPropertyCounts } } private fun getPropertyHash( entitySetId: UUID, entityKeyId: UUID, propertyTypeId: UUID, value: Any, dataType: EdmPrimitiveTypeKind, awsPassthrough: Boolean ): Pair<ByteArray, Any> { if (dataType != EdmPrimitiveTypeKind.Binary) { return PostgresDataHasher.hashObject(value, dataType) to value } //Binary data types get stored in S3 bucket: if (awsPassthrough) { //Data is being stored in AWS directly the value will be the url fragment //of where the data will be stored in AWS. return PostgresDataHasher.hashObject(value, EdmPrimitiveTypeKind.String) to value } //Data is expected to be of a specific type so that it can be stored in s3 bucket val binaryData = value as BinaryDataWithContentType val digest = PostgresDataHasher.hashObjectToHex(binaryData.data, EdmPrimitiveTypeKind.Binary) //store entity set id/entity key id/property type id/property hash as key in S3 val s3Key = "$entitySetId/$entityKeyId/$propertyTypeId/$digest" byteBlobDataManager.putObject(s3Key, binaryData.data, binaryData.contentType) return PostgresDataHasher.hashObject(s3Key, EdmPrimitiveTypeKind.String) to s3Key } @Timed fun replaceEntities( entitySetId: UUID, entities: Map<UUID, Map<UUID, Set<Any>>>, authorizedPropertyTypes: Map<UUID, PropertyType>, partitions: List<Int> = partitionManager.getEntitySetPartitions(entitySetId).toList() ): WriteEvent { val propertyTypes = authorizedPropertyTypes.values val tombstoneFn: (Long, Map<UUID, Map<UUID, Set<Any>>>) -> Unit = { version: Long, entityBatch: Map<UUID, Map<UUID, Set<Any>>> -> tombstone( entitySetId, entityBatch.keys, propertyTypes, version, partitions ) } return upsertEntities( entitySetId, tombstoneFn, entities, authorizedPropertyTypes, System.currentTimeMillis(), partitions ) } @Timed fun partialReplaceEntities( entitySetId: UUID, entities: Map<UUID, Map<UUID, Set<Any>>>, authorizedPropertyTypes: Map<UUID, PropertyType>, partitions: List<Int> = partitionManager.getEntitySetPartitions(entitySetId).toList() ): WriteEvent { // Is the overhead from including irrelevant property types in a bulk delete really worse than performing individual queries? :thinking-face: val tombstoneFn = { version: Long, entityBatch: Map<UUID, Map<UUID, Set<Any>>> -> entityBatch.forEach { (entityKeyId, entity) -> //Implied access enforcement as it will raise exception if lacking permission tombstone( entitySetId, setOf(entityKeyId), entity.keys.map { authorizedPropertyTypes.getValue(it) }.toSet(), version, partitions ) } } return upsertEntities( entitySetId, tombstoneFn, entities, authorizedPropertyTypes, System.currentTimeMillis(), partitions ) } @Timed fun replacePropertiesInEntities( entitySetId: UUID, replacementProperties: Map<UUID, Map<UUID, Set<Map<ByteBuffer, Any>>>>, // ekid -> ptid -> hashes -> shit authorizedPropertyTypes: Map<UUID, PropertyType> ): WriteEvent { //We expect controller to have performed access control checks upstream. val partitions = partitionManager.getEntitySetPartitions(entitySetId).toList() val tombstoneFn: (Long, Map<UUID, Map<UUID, Set<Any>>>) -> Unit = { version: Long, entityBatch: Map<UUID, Map<UUID, Set<Any>>> -> val ids = entityBatch.keys tombstone( entitySetId, replacementProperties.filter { ids.contains(it.key) }, version, partitions ) } //This performs unnecessary copies and we should fix at some point val replacementValues = replacementProperties.asSequence().map { it.key to extractValues( it.value ) }.toMap() return upsertEntities( entitySetId, tombstoneFn, replacementValues, authorizedPropertyTypes, System.currentTimeMillis(), partitions ) } private fun extractValues(propertyValues: Map<UUID, Set<Map<ByteBuffer, Any>>>): Map<UUID, Set<Any>> { return propertyValues.mapValues { (_, replacements) -> replacements.flatMap { it.values }.toSet() } } /** * This is fail safe as all id tombstones should commit at once. * Tombstones all entities in an entity set in both [IDS] and [DATA] table. */ private fun tombstone(conn: Connection, entitySetId: UUID, version: Long): WriteEvent { val partitions = partitionManager.getEntitySetPartitions(entitySetId) val idTombstones = conn.prepareStatement(updateVersionsForEntitySet) val dataTombstones = conn.prepareStatement(updateVersionsForPropertiesInEntitySet) partitions.sorted().map { partition -> idTombstones.setLong(1, -version) idTombstones.setLong(2, -version) idTombstones.setLong(3, -version) idTombstones.setObject(4, entitySetId) idTombstones.setInt(5, partition) idTombstones.addBatch() } val numUpdates = idTombstones.executeBatch().sum() //We don't count the number of property types that were updated //TODO: Someday if we encounter deadlocks when deleting entity sets, we will probably have to implement locking //Only likely to happen if someone is actively writing to an entity set that is being cleared. dataTombstones.setLong(1, -version) dataTombstones.setLong(2, -version) dataTombstones.setLong(3, -version) dataTombstones.setObject(4, entitySetId) dataTombstones.setArray(5, PostgresArrays.createIntArray(conn, partitions)) dataTombstones.executeUpdate() return WriteEvent(version, numUpdates) } /** * Tombstones all data from authorizedPropertyTypes for an entity set in both [IDS] and [DATA] table. * * NOTE: this function commits the tombstone transactions. */ @Timed fun clearEntitySet(entitySetId: UUID, authorizedPropertyTypes: Map<UUID, PropertyType>): WriteEvent { return hds.connection.use { conn -> val version = System.currentTimeMillis() tombstone(conn, entitySetId, authorizedPropertyTypes.values, version) val event = tombstone(conn, entitySetId, version) event } } /** * Tombstones (writes a negative version) for the provided entities. * @param entitySetId The entity set to operate on. * @param entityKeyIds The entity key ids to tombstone. * @param authorizedPropertyTypes The property types the user is allowed to tombstone. We assume that authorization * checks are enforced at a higher level and that this just streamlines issuing the necessary queries. * @param partitions Contains the partition information for the requested entity set. */ fun clearEntities( entitySetId: UUID, entityKeyIds: Set<UUID>, authorizedPropertyTypes: Map<UUID, PropertyType>, partitions: List<Int> = partitionManager.getEntitySetPartitions(entitySetId).toList() ): WriteEvent { val version = System.currentTimeMillis() tombstone( entitySetId, entityKeyIds, authorizedPropertyTypes.values, version, partitions ) return tombstoneIdsTable(entitySetId, entityKeyIds, version, partitions) } /** * Tombstones (writes a negative version) for the provided entity properties. * @param entitySetId The entity set to operate on. * @param entityKeyIds The entity key ids to tombstone. * @param authorizedPropertyTypes The property types the user is requested and is allowed to tombstone. We assume * that authorization checks are enforced at a higher level and that this just streamlines issuing the necessary * queries. * @param partitions Contains the partition information for the requested entity set. */ fun clearEntityData( entitySetId: UUID, entityKeyIds: Set<UUID>, authorizedPropertyTypes: Map<UUID, PropertyType>, partitions: Set<Int> = partitionManager.getEntitySetPartitions(entitySetId) ): WriteEvent { val version = System.currentTimeMillis() return hds.connection.use { conn -> val writeEvent = tombstone( entitySetId, entityKeyIds, authorizedPropertyTypes.values, version, partitions.toList() ) return@use writeEvent } } /** * Deletes properties of entities in entity set from [DATA] table. */ fun deleteEntityData( entitySetId: UUID, entityKeyIds: Set<UUID>, authorizedPropertyTypes: Map<UUID, PropertyType>, partitions: List<Int> = partitionManager.getEntitySetPartitions(entitySetId).toList() ): WriteEvent { // TODO same as deleteEntityDataAndEntities? // Delete properties from S3 authorizedPropertyTypes.map { property -> if (property.value.datatype == EdmPrimitiveTypeKind.Binary) { deletePropertyOfEntityFromS3(entitySetId, entityKeyIds, property.key) } } val numUpdates = entityKeyIds .groupBy { getPartition(it, partitions) } .map { (partition, entities) -> deletePropertiesFromEntities( entitySetId, entities, authorizedPropertyTypes, partition ) }.sum() return WriteEvent(System.currentTimeMillis(), numUpdates) } /** * Deletes properties of entities in entity set from [DATA] table. */ private fun deletePropertiesFromEntities( entitySetId: UUID, entities: Collection<UUID>, authorizedPropertyTypes: Map<UUID, PropertyType>, partition: Int ): Int { return hds.connection.use { connection -> val propertyTypesArr = PostgresArrays.createUuidArray(connection, authorizedPropertyTypes.keys) val idsArr = PostgresArrays.createUuidArray(connection, entities) // Delete entity and linked entity properties from data table connection .prepareStatement(deletePropertiesOfEntitiesInEntitySet) .use { ps -> ps.setObject(1, entitySetId) ps.setArray(2, idsArr) ps.setArray(3, idsArr) ps.setInt(4, partition) ps.setArray(5, propertyTypesArr) ps.executeUpdate() } } } /** * Deletes properties of entities in entity set from [DATA] table. */ fun deleteEntityDataAndEntities( entitySetId: UUID, entityKeyIds: Set<UUID>, authorizedPropertyTypes: Map<UUID, PropertyType>, partitions: List<Int> = partitionManager.getEntitySetPartitions(entitySetId).toList() ): WriteEvent { // Delete properties from S3 authorizedPropertyTypes.map { property -> if (property.value.datatype == EdmPrimitiveTypeKind.Binary) { deletePropertyOfEntityFromS3(entitySetId, entityKeyIds, property.key) } } val numUpdates = entityKeyIds .groupBy { getPartition(it, partitions) } .map { (partition, entities) -> deleteEntities(entitySetId, entities, partition) }.sum() return WriteEvent(System.currentTimeMillis(), numUpdates) } /** * Deletes entities from [DATA] table. */ private fun deleteEntities( entitySetId: UUID, entities: Collection<UUID>, partition: Int ): Int { return hds.connection.use { connection -> val idsArr = PostgresArrays.createUuidArray(connection, entities) // Delete entity and linking entity properties from data table connection.prepareStatement(deleteEntitiesInEntitySet) .use { deleteEntities -> deleteEntities.setObject(1, entitySetId) deleteEntities.setArray(2, idsArr) deleteEntities.setArray(3, idsArr) deleteEntities.setInt(4, partition) deleteEntities.executeUpdate() } } } /** * Deletes property types of entity set from [DATA] table. */ fun deleteEntitySetData(entitySetId: UUID, propertyTypes: Map<UUID, PropertyType>): WriteEvent { val numUpdates = hds.connection.use { connection -> val ps = connection.prepareStatement(deletePropertyInEntitySet) propertyTypes .map { propertyType -> if (propertyType.value.datatype == EdmPrimitiveTypeKind.Binary) { deletePropertiesInEntitySetFromS3(entitySetId, propertyType.key) } ps.setObject(1, entitySetId) ps.setObject(2, propertyType.key) ps.addBatch() } ps.executeBatch().sum() } return WriteEvent(System.currentTimeMillis(), numUpdates) } private fun deletePropertyOfEntityFromS3( entitySetId: UUID, entityKeyIds: Set<UUID>, propertyTypeId: UUID ) { val count = AtomicLong() BasePostgresIterable<String>( PreparedStatementHolderSupplier(hds, selectEntitiesTextProperties, FETCH_SIZE) { ps -> val connection = ps.connection val entitySetIdsArr = PostgresArrays.createUuidArray(connection, setOf(entitySetId)) val propertyTypeIdsArr = PostgresArrays.createUuidArray(connection, setOf(propertyTypeId)) val entityKeyIdsArr = PostgresArrays.createUuidArray(connection, entityKeyIds) ps.setArray(1, entitySetIdsArr) ps.setArray(2, propertyTypeIdsArr) ps.setArray(3, entityKeyIdsArr) } ) { rs -> rs.getString(getMergedDataColumnName(PostgresDatatype.TEXT)) }.asSequence().chunked(S3_DELETE_BATCH_SIZE).asStream().parallel().forEach { s3Keys -> byteBlobDataManager.deleteObjects(s3Keys) count.addAndGet(s3Keys.size.toLong()) } } private fun deletePropertiesInEntitySetFromS3(entitySetId: UUID, propertyTypeId: UUID): Long { val count = AtomicLong() BasePostgresIterable<String>( PreparedStatementHolderSupplier(hds, selectEntitySetTextProperties, FETCH_SIZE) { ps -> val entitySetIdsArr = PostgresArrays.createUuidArray(ps.connection, setOf(entitySetId)) val propertyTypeIdsArr = PostgresArrays.createUuidArray(ps.connection, setOf(propertyTypeId)) ps.setArray(1, entitySetIdsArr) ps.setArray(2, propertyTypeIdsArr) } ) { rs -> rs.getString(getMergedDataColumnName(PostgresDatatype.TEXT)) }.asSequence().chunked(S3_DELETE_BATCH_SIZE).asStream().parallel().forEach { s3Keys -> byteBlobDataManager.deleteObjects(s3Keys) count.addAndGet(s3Keys.size.toLong()) } return count.get() } /** * Tombstones (to version = 0) entity key ids belonging to the requested entity set in [IDS] table. */ fun tombstoneDeletedEntitySet(entitySetId: UUID): WriteEvent { val partitions = partitionManager.getEntitySetPartitions(entitySetId) val numUpdates = hds.connection.use { connection -> try { lockIdsAndExecute( connection, zeroVersionsForEntitySet, entitySetId, partitions.associateWith { listOf<UUID>() }, batch = true, shouldLockEntireEntitySet = true ) { ps, partition, _ -> ps.setObject(1, entitySetId) ps.setInt(2, partition) } } catch (ex: Exception) { logger.error("Unable to mark entity set $entitySetId for deletion.") throw ex } } return WriteEvent(System.currentTimeMillis(), numUpdates) } /** * Deletes entities from [IDS] table. */ fun deleteEntities(entitySetId: UUID, entityKeyIds: Set<UUID>): WriteEvent { val partitions = partitionManager.getEntitySetPartitions(entitySetId).toList() val entitiesByPartition = getIdsByPartition(entityKeyIds, partitions) val numUpdates = hds.connection.use { connection -> try { lockIdsAndExecute( connection, deleteEntityKeys, entitySetId, entitiesByPartition, batch = true ) { ps, partition, entityKeyIds -> val entityArr = PostgresArrays.createUuidArray(ps.connection, entityKeyIds) ps.setObject(1, entitySetId) ps.setArray(2, entityArr) ps.setInt(3, partition) } } catch (ex: Exception) { logger.error("Unable to delete entities ($entityKeyIds) in $entitySetId.") throw ex } } return WriteEvent(System.currentTimeMillis(), numUpdates) } /** * Tombstones (to version = 0) entities in [IDS] table. */ fun tombstoneDeletedEntities(entitySetId: UUID, entityKeyIds: Set<UUID>): WriteEvent { val partitions = partitionManager.getEntitySetPartitions(entitySetId).toList() val entitiesByPartition = getIdsByPartition(entityKeyIds, partitions) val numUpdates = hds.connection.use { connection -> try { lockIdsAndExecute( connection, zeroVersionsForEntitiesInEntitySet, entitySetId, entitiesByPartition, shouldLockEntireEntitySet = false, batch = true ) { ps, partition, entityKeyIds -> val idsArr = PostgresArrays.createUuidArray(ps.connection, entityKeyIds) ps.setObject(1, entitySetId) ps.setInt(2, partition) ps.setArray(3, idsArr) } } catch (ex: Exception) { logger.error("Unable to market entities for deletion ($entityKeyIds) in $entitySetId.") throw ex } } return WriteEvent(System.currentTimeMillis(), numUpdates) } /** * Tombstones the provided set of property types for each provided entity key. * * This version of tombstone only operates on the [DATA] table and does not change the version of * entities in the [IDS] table * * @param conn A valid JDBC connection, ideally with autocommit disabled. * @param entitySetId The entity set id for which to tombstone entries * @param propertyTypesToTombstone A collection of property types to tombstone * * @return A write event object containing a summary of the operation useful for auditing purposes. * */ private fun tombstone( conn: Connection, entitySetId: UUID, propertyTypesToTombstone: Collection<PropertyType>, version: Long ): WriteEvent { val propertyTypeIdsArr = PostgresArrays.createUuidArray(conn, propertyTypesToTombstone.map { it.id }) val partitions = PostgresArrays.createIntArray(conn, partitionManager.getEntitySetPartitions(entitySetId)) val numUpdated = conn.prepareStatement(updateVersionsForPropertyTypesInEntitySet).use { ps -> ps.setLong(1, -version) ps.setLong(2, -version) ps.setLong(3, -version) ps.setObject(4, entitySetId) ps.setArray(5, partitions) ps.setArray(6, propertyTypeIdsArr) ps.executeUpdate() } return WriteEvent(version, numUpdated) } /** * Tombstones entities in the [PostgresTable.IDS] table. * * @param conn A valid JDBC connection, ideally with autocommit disabled. * @param entitySetId The entity set id for which to tombstone entries. * @param entityKeyIds The entity key ids for which to tombstone entries. * @param version Version to be used for tombstoning. * @param partitions Contains the partition information for the requested entity set. */ private fun tombstoneIdsTable( entitySetId: UUID, entityKeyIds: Set<UUID>, version: Long, partitions: List<Int> = partitionManager.getEntitySetPartitions(entitySetId).toList() ): WriteEvent { val idsByPartition = getIdsByPartition(entityKeyIds, partitions) val numUpdated = hds.connection.use { connection -> lockIdsAndExecute( connection, updateVersionsForEntitiesInEntitySet, entitySetId, idsByPartition, batch = true ) { ps, partition, ids -> val entityKeyIdsArr = PostgresArrays.createUuidArray(ps.connection, ids) ps.setLong(1, -version) ps.setLong(2, -version) ps.setLong(3, -version) ps.setObject(4, entitySetId) ps.setInt(5, partition) ps.setArray(6, entityKeyIdsArr) } } return WriteEvent(version, numUpdated) } /** * Tombstones the provided set of property types for each provided entity key. * * This version of tombstone only operates on the [DATA] table and does not change the version of * entities in the [IDS] table * * @param entitySetId The entity set id for which to tombstone entries * @param entityKeyIds The entity key ids for which to tombstone entries. * @param propertyTypesToTombstone A collection of property types to tombstone * @param version Version to be used for tombstoning. * @param partitions Contains the partition info for the requested entity set. * * @return A write event object containing a summary of the operation useful for auditing purposes. */ private fun tombstone( entitySetId: UUID, entityKeyIds: Set<UUID>, propertyTypesToTombstone: Collection<PropertyType>, version: Long, partitions: List<Int> = partitionManager.getEntitySetPartitions(entitySetId).toList() ): WriteEvent { return hds.connection.use { conn -> val propertyTypeIdsArr = PostgresArrays.createUuidArray(conn, propertyTypesToTombstone.map { it.id }) val entityKeyIdsArr = PostgresArrays.createUuidArray(conn, entityKeyIds) val partitionsArr = PostgresArrays.createIntArray(conn, entityKeyIds.map { getPartition( it, partitions ) }) val numUpdated = conn.prepareStatement( updateVersionsForPropertyTypesInEntitiesInEntitySet() ).use { ps -> ps.setLong(1, -version) ps.setLong(2, -version) ps.setLong(3, -version) ps.setObject(4, entitySetId) ps.setArray(5, partitionsArr) ps.setArray(6, propertyTypeIdsArr) ps.setArray(7, entityKeyIdsArr) ps.executeUpdate() } val linksTombstoned = conn.prepareStatement( updateVersionsForPropertyTypesInEntitiesInEntitySet(linking = true) ).use { ps -> ps.setLong(1, -version) ps.setLong(2, -version) ps.setLong(3, -version) ps.setObject(4, entitySetId) ps.setArray(5, partitionsArr) ps.setArray(6, propertyTypeIdsArr) ps.setArray(7, entityKeyIdsArr) ps.executeUpdate() } WriteEvent(version, numUpdated + linksTombstoned) } } /** * * Tombstones the provided set of property type hash values for each provided entity key. * * This version of tombstone only operates on the [DATA] table and does not change the version of * entities in the [IDS] table * * @param entitySetId The entity set id for which to tombstone entries * @param entities The entities with their properties for which to tombstone entries. * @param version The version to use to tombstone. * @param partitions Contains the partition info for the entity set of the entities. * * @return A write event object containing a summary of the operation useful for auditing purposes. * */ private fun tombstone( entitySetId: UUID, entities: Map<UUID, Map<UUID, Set<Map<ByteBuffer, Any>>>>, version: Long, partitions: List<Int> = partitionManager.getEntitySetPartitions(entitySetId).toList() ): WriteEvent { return hds.connection.use { conn -> val entityKeyIds = entities.keys val entityKeyIdsArr = PostgresArrays.createUuidArray(conn, entityKeyIds) val partitionsArr = PostgresArrays.createIntArray( conn, entities.keys.map { getPartition(it, partitions) }) val updatePropertyValueVersion = conn.prepareStatement( updateVersionsForPropertyValuesInEntitiesInEntitySet() ) val tombstoneLinks = conn.prepareStatement( updateVersionsForPropertyValuesInEntitiesInEntitySet(linking = true) ) entities.forEach { (_, entity) -> entity.forEach { (propertyTypeId, updates) -> val propertyTypeIdsArr = PostgresArrays.createUuidArray(conn, propertyTypeId) //TODO: https://github.com/pgjdbc/pgjdbc/issues/936 //TODO: https://github.com/pgjdbc/pgjdbc/pull/1194 //TODO: https://github.com/pgjdbc/pgjdbc/pull/1044 //Once above issues are resolved this can be done as a single query WHERE HASH = ANY(?) updates .flatMap { it.keys } .forEach { update -> updatePropertyValueVersion.setLong(1, -version) updatePropertyValueVersion.setLong(2, -version) updatePropertyValueVersion.setLong(3, -version) updatePropertyValueVersion.setObject(4, entitySetId) updatePropertyValueVersion.setArray(5, partitionsArr) updatePropertyValueVersion.setArray(6, propertyTypeIdsArr) updatePropertyValueVersion.setArray(7, entityKeyIdsArr) updatePropertyValueVersion.setBytes(8, update.array()) updatePropertyValueVersion.addBatch() tombstoneLinks.setLong(1, -version) tombstoneLinks.setLong(2, -version) tombstoneLinks.setLong(3, -version) tombstoneLinks.setObject(4, entitySetId) tombstoneLinks.setArray(5, partitionsArr) tombstoneLinks.setArray(6, propertyTypeIdsArr) tombstoneLinks.setArray(7, entityKeyIdsArr) tombstoneLinks.setBytes(8, update.array()) tombstoneLinks.addBatch() } } } val numUpdated = updatePropertyValueVersion.executeUpdate() val linksUpdated = tombstoneLinks.executeUpdate() WriteEvent(version, numUpdated + linksUpdated) } } fun getExpiringEntitiesFromEntitySet( entitySetId: UUID, expirationBaseColumn: String, formattedDateMinusTTE: Any, sqlFormat: Int, deleteType: DeleteType ): BasePostgresIterable<UUID> { val partitions = PostgresArrays.createIntArray( hds.connection, partitionManager.getEntitySetPartitions(entitySetId) ) return BasePostgresIterable( PreparedStatementHolderSupplier( hds, getExpiringEntitiesQuery(expirationBaseColumn, deleteType), FETCH_SIZE, false ) { stmt -> stmt.setObject(1, entitySetId) stmt.setArray(2, partitions) stmt.setObject(3, IdConstants.ID_ID.id) stmt.setObject(4, formattedDateMinusTTE, sqlFormat) } ) { rs -> ResultSetAdapters.id(rs) } } private fun getExpiringEntitiesQuery(expirationBaseColumn: String, deleteType: DeleteType): String { var ignoredClearedEntitiesClause = "" if (deleteType == DeleteType.Soft) { ignoredClearedEntitiesClause = "AND ${VERSION.name} >= 0 " } return "SELECT ${ID.name} FROM ${DATA.name} " + "WHERE ${ENTITY_SET_ID.name} = ? " + "AND ${PARTITION.name} = ANY(?) " + "AND ${PROPERTY_TYPE_ID.name} != ? " + "AND $expirationBaseColumn <= ? " + ignoredClearedEntitiesClause // this clause ignores entities that have already been cleared } } private fun abortInsert(entitySetId: UUID, entityKeyId: UUID): Nothing { throw InvalidParameterException( "Cannot insert property type not in authorized property types for entity $entityKeyId from entity set $entitySetId." ) }
gpl-3.0
aa32f1ea1fb443d2b2decdb85e59fd0e
41.090157
149
0.591801
5.4782
false
false
false
false
goAV/NettyAndroid
app/src/main/java/com/goav/app/NettyTest.kt
1
2837
import com.goav.netty.Handler.ClientHelper import com.goav.netty.Handler.ReConnect import com.goav.netty.Impl.ChannelConnectImpl import io.netty.channel.ChannelHandlerContext import io.netty.channel.ChannelOutboundHandlerAdapter import io.netty.channel.ChannelPipeline import io.netty.channel.ChannelPromise import io.netty.channel.socket.SocketChannel import java.util.concurrent.TimeUnit fun main(args: Array<String>) { val client = ClientHelper.init() .reConnect(ReConnect(true, 2)) .address("0", 7373) .addCallBack(object : ChannelConnectImpl { override fun onConnectCallBack(sc: SocketChannel?) { System.out.println((sc == null).toString()) } override fun addChannelHandler(pipeline: ChannelPipeline): ChannelPipeline = pipeline.addLast(TestHandler()).addLast(OutChannel()) }) .build() .connect(); } class TestHandler : io.netty.channel.ChannelDuplexHandler() { override fun channelRead(ctx: ChannelHandlerContext?, msg: Any?) { val value = String(msg as ByteArray) System.out.println(value) // super.channelRead(ctx, msg) } override fun write(ctx: ChannelHandlerContext?, msg: Any?, promise: ChannelPromise?) { System.out.println("write") super.write(ctx, msg, promise) } override fun channelActive(ctx: ChannelHandlerContext?) { System.out.println("channelActive") ctx?.writeAndFlush("connectByKotlin") ctx?.executor()?.scheduleAtFixedRate( { ctx.writeAndFlush(SocketPong()) }, 0, 10, TimeUnit.SECONDS) // super.channelActive(ctx) } override fun channelRegistered(ctx: ChannelHandlerContext?) { System.out.println("channelRegistered") super.channelRegistered(ctx) } override fun channelUnregistered(ctx: ChannelHandlerContext?) { System.out.println("channelUnregistered") ctx?.close() // super.channelUnregistered(ctx) } override fun channelInactive(ctx: ChannelHandlerContext?) { System.out.println("channelInactive") super.channelInactive(ctx) } override fun close(ctx: ChannelHandlerContext?, promise: ChannelPromise?) { System.out.println("close") super.close(ctx, promise) } override fun exceptionCaught(ctx: ChannelHandlerContext?, cause: Throwable?) { System.out.println(cause?.message) super.exceptionCaught(ctx, cause) } } class OutChannel : ChannelOutboundHandlerAdapter() { override fun write(ctx: ChannelHandlerContext?, msg: Any?, promise: ChannelPromise?) { System.out.print("write out") super.write(ctx, msg, promise) } }
mit
8287dbbff1a67a56fd76778ed50b8cf2
31.62069
146
0.65386
4.605519
false
false
false
false
laurencegw/jenjin
jenjin-demo/src/com/binarymonks/jj/demo/demos/D04_components.kt
1
5303
package com.binarymonks.jj.demo.demos import com.badlogic.gdx.physics.box2d.BodyDef import com.binarymonks.jj.core.JJ import com.binarymonks.jj.core.JJConfig import com.binarymonks.jj.core.JJGame import com.binarymonks.jj.core.components.Component import com.binarymonks.jj.core.properties.PropOverride import com.binarymonks.jj.core.specs.Circle import com.binarymonks.jj.core.specs.SceneSpec import com.binarymonks.jj.core.specs.params /** * Building [com.binarymonks.jj.core.components.Component]s is what lets you build the behaviour of your game. Along with * [com.binarymonks.jj.core.physics.CollisionHandler]s. But this is to demonstrate the former. * * Components are the primary building blocks of any special mechanics of your game which make it more than * just a 2d physics simulator. * * Here we build a simple back and forth movement component [BackForwardMovement] for some platforms as an example. * * We build it in a way which makes it configurable and reusable across different objects. */ class D04_components : JJGame(JJConfig { b2d.debugRender = true gameView.worldBoxWidth = 30f gameView.cameraPosX = 0f gameView.cameraPosY = 15f }) { public override fun gameOn() { JJ.scenes.addSceneSpec("platform", platform()) JJ.scenes.addSceneSpec("orb", orb()) JJ.scenes.loadAssetsNow() val initialSceneSpec = SceneSpec { node("platform") { x = -10f y = 15f scaleX = 3f prop("direction", Direction.VERTICAL) prop("movementRange", 5f) prop("metersPerSecond", 1f) } node("platform") { x = 0f y = 4f scaleX = 6f prop("direction", Direction.HORIZONTAL) prop("movementRange", 10f) prop("metersPerSecond", 3f) } node("orb") { x = 6f y = 20f scaleX = 2f prop("direction", Direction.VERTICAL) prop("movementRange", 10f) prop("metersPerSecond", 5f) } //This instance does not set the localProperties, and so the defaults of the component will be used. node("orb") { x = 0f y = 20f scaleX = 3f } } JJ.scenes.instantiate(initialSceneSpec) } private fun orb(): SceneSpec { return SceneSpec { physics { // Kinematic is suited for direct movement of physics objects bodyType = BodyDef.BodyType.KinematicBody fixture { shape = Circle(0.5f) } } //Add our component to our me and bind fields to localProperties component(BackForwardMovement()) { direction.setOverride("direction") movementRange.setOverride("movementRange") metersPerSecond.setOverride("metersPerSecond") } } } private fun platform(): SceneSpec { return SceneSpec { physics { // Kinematic is suited for direct movement of physics objects bodyType = BodyDef.BodyType.KinematicBody fixture { } } //Add our component to our me and bind fields to localProperties component(BackForwardMovement()) { direction.setOverride("direction") movementRange.setOverride("movementRange") metersPerSecond.setOverride("metersPerSecond") } } } } enum class Direction { HORIZONTAL, VERTICAL } //A reusable and configurable component that can be attache to any Scene class BackForwardMovement : Component() { //We want our component to have the option of delegating its values to localProperties. // These are our configurable fields. var direction: PropOverride<Direction> = PropOverride(Direction.HORIZONTAL) var movementRange: PropOverride<Float> = PropOverride(0f) var metersPerSecond: PropOverride<Float> = PropOverride(0f) //These are our private fields for the running state. private var startLocation: com.badlogic.gdx.math.Vector2 = com.binarymonks.jj.core.pools.vec2() private var velocity: com.badlogic.gdx.math.Vector2 = com.binarymonks.jj.core.pools.vec2() //For our platform we want to know where we start in the world so we can control movement // relative to that override fun onAddToWorld() { startLocation.set(me().physicsRoot.position()) when (direction.get()) { com.binarymonks.jj.demo.demos.Direction.VERTICAL -> velocity.set(0f, metersPerSecond.get()) com.binarymonks.jj.demo.demos.Direction.HORIZONTAL -> velocity.set(metersPerSecond.get(), 0F) } me().physicsRoot.b2DBody.linearVelocity = velocity } override fun update() { val distanceFromStart = me().physicsRoot.position().sub(startLocation).len() if (distanceFromStart > movementRange.get()) { velocity.scl(-1f) me().physicsRoot.b2DBody.linearVelocity = velocity } } }
apache-2.0
b0261908727bc8e1db2c429aaac63ee6
35.07483
121
0.614369
4.532479
false
false
false
false
alashow/music-android
modules/ui-search/src/main/java/tm/alashow/datmusic/ui/search/SearchViewModel.kt
1
8399
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.ui.search import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.PagingConfig import androidx.paging.cachedIn import com.google.firebase.analytics.FirebaseAnalytics import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.launch import timber.log.Timber import tm.alashow.base.ui.SnackbarManager import tm.alashow.base.util.event import tm.alashow.base.util.extensions.getStateFlow import tm.alashow.datmusic.data.observers.ObservePagedDatmusicSearch import tm.alashow.datmusic.data.repos.CaptchaSolution import tm.alashow.datmusic.data.repos.search.DatmusicSearchParams import tm.alashow.datmusic.data.repos.search.DatmusicSearchParams.BackendType import tm.alashow.datmusic.data.repos.search.DatmusicSearchParams.Companion.withTypes import tm.alashow.datmusic.domain.entities.Album import tm.alashow.datmusic.domain.entities.Artist import tm.alashow.datmusic.domain.entities.Audio import tm.alashow.datmusic.playback.PlaybackConnection import tm.alashow.domain.models.errors.ApiCaptchaError import tm.alashow.navigation.QUERY_KEY import tm.alashow.navigation.SEARCH_BACKENDS_KEY const val SEARCH_DEBOUNCE_MILLIS = 400L @OptIn(FlowPreview::class) @HiltViewModel internal class SearchViewModel @Inject constructor( handle: SavedStateHandle, private val audiosPager: ObservePagedDatmusicSearch<Audio>, private val minervaPager: ObservePagedDatmusicSearch<Audio>, private val flacsPager: ObservePagedDatmusicSearch<Audio>, private val artistsPager: ObservePagedDatmusicSearch<Artist>, private val albumsPager: ObservePagedDatmusicSearch<Album>, private val snackbarManager: SnackbarManager, private val analytics: FirebaseAnalytics, private val playbackConnection: PlaybackConnection, ) : ViewModel() { private val initialQuery = handle.get(QUERY_KEY) ?: "" private val searchQuery = MutableStateFlow(initialQuery) private val searchFilter = handle.getStateFlow("search_filter", viewModelScope, SearchFilter.from(handle.get(SEARCH_BACKENDS_KEY))) private val searchTrigger = handle.getStateFlow("search_trigger", viewModelScope, SearchTrigger(initialQuery)) private val captchaError = MutableStateFlow<ApiCaptchaError?>(null) private val pendingActions = MutableSharedFlow<SearchAction>() val pagedAudioList get() = audiosPager.flow.cachedIn(viewModelScope) val pagedMinervaList get() = minervaPager.flow.cachedIn(viewModelScope) val pagedFlacsList get() = flacsPager.flow.cachedIn(viewModelScope) val pagedArtistsList get() = artistsPager.flow.cachedIn(viewModelScope) val pagedAlbumsList get() = albumsPager.flow.cachedIn(viewModelScope) val state = combine(searchFilter.filterNotNull(), snackbarManager.errors, captchaError, ::SearchViewState) init { viewModelScope.launch { pendingActions.collect { action -> when (action) { is SearchAction.QueryChange -> { searchQuery.value = action.query // trigger search while typing if minerva is the only backend selected if (searchFilter.value?.hasMinervaOnly == true) { searchTrigger.value = SearchTrigger(searchQuery.value) } } is SearchAction.Search -> searchTrigger.value = SearchTrigger(searchQuery.value) is SearchAction.SelectBackendType -> selectBackendType(action) is SearchAction.SubmitCaptcha -> submitCaptcha(action) is SearchAction.AddError -> snackbarManager.addError(action.error) is SearchAction.ClearError -> snackbarManager.removeCurrentError() is SearchAction.PlayAudio -> playAudio(action.audio) } } } viewModelScope.launch { combine(searchTrigger.filterNotNull(), searchFilter.filterNotNull(), ::Pair) .debounce(SEARCH_DEBOUNCE_MILLIS) .collectLatest { (trigger, filter) -> search(trigger, filter) } } listOf(audiosPager, minervaPager, flacsPager, artistsPager, albumsPager).forEach { pager -> pager.errors().watchForErrors(pager) } } fun search(trigger: SearchTrigger, filter: SearchFilter) { val query = trigger.query val searchParams = DatmusicSearchParams(query, trigger.captchaSolution) val backends = filter.backends.joinToString { it.type } Timber.d("Searching with query=$query, backends=$backends") analytics.event("search", mapOf("query" to query, "backends" to backends)) if (filter.hasAudios) audiosPager(ObservePagedDatmusicSearch.Params(searchParams)) if (filter.hasMinerva) minervaPager(ObservePagedDatmusicSearch.Params(searchParams.withTypes(BackendType.MINERVA), MINERVA_PAGING)) if (filter.hasFlacs) flacsPager(ObservePagedDatmusicSearch.Params(searchParams.withTypes(BackendType.FLACS), MINERVA_PAGING)) // don't send queries if backend can't handle empty queries if (query.isNotBlank()) { if (filter.hasArtists) artistsPager(ObservePagedDatmusicSearch.Params(searchParams.withTypes(BackendType.ARTISTS))) if (filter.hasAlbums) albumsPager(ObservePagedDatmusicSearch.Params(searchParams.withTypes(BackendType.ALBUMS))) } } fun submitAction(action: SearchAction) { viewModelScope.launch { pendingActions.emit(action) } } /** * Queue given audio to play with current query as the queue. */ private fun playAudio(audio: Audio) { val query = searchTrigger.value?.query ?: searchQuery.value when { searchFilter.value?.hasMinerva == true -> playbackConnection.playWithMinervaQuery(query, audio.id) searchFilter.value?.hasFlacs == true -> playbackConnection.playWithFlacsQuery(query, audio.id) else -> playbackConnection.playWithQuery(query, audio.id) } } /** * Sets search filter to only given backend if [action.selected] otherwise resets to [SearchFilter.DefaultBackends]. */ private fun selectBackendType(action: SearchAction.SelectBackendType) { analytics.event("search.selectBackend", mapOf("type" to action.backendType)) searchFilter.value = searchFilter.value?.copy( backends = when (action.selected) { true -> setOf(action.backendType) else -> SearchFilter.DefaultBackends } ) } /** * Resets captcha error and triggers search with given captcha solution. */ private fun submitCaptcha(action: SearchAction.SubmitCaptcha) { captchaError.value = null searchTrigger.value = SearchTrigger( query = searchQuery.value, captchaSolution = CaptchaSolution( action.captchaError.error.captchaId, action.captchaError.error.captchaIndex, action.solution ) ) } private fun Flow<Throwable>.watchForErrors(pager: ObservePagedDatmusicSearch<*>) = viewModelScope.launch { collectErrors(pager) } private suspend fun Flow<Throwable>.collectErrors(pager: ObservePagedDatmusicSearch<*>) = collect { error -> Timber.e(error, "Collected error from a pager") when (error) { is ApiCaptchaError -> captchaError.value = error } } companion object { val MINERVA_PAGING = PagingConfig( pageSize = 50, initialLoadSize = 50, prefetchDistance = 5, enablePlaceholders = true ) } }
apache-2.0
839691006b56883254780caeb41d34fa
41.20603
135
0.698297
4.705322
false
false
false
false
Gu3pardo/PasswordSafe-AndroidClient
mobile/src/main/java/guepardoapps/passwordsafe/views/fragments/FragmentPreferences.kt
1
26031
package guepardoapps.passwordsafe.views.fragments import android.Manifest import android.annotation.SuppressLint import android.app.Activity.RESULT_OK import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.os.Build import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.SeekBar import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.afollestad.materialdialogs.MaterialDialog import com.innovattic.rangeseekbar.RangeSeekBar import com.jaiselrahman.filepicker.activity.FilePickerActivity import com.jaiselrahman.filepicker.config.Configurations import com.jaiselrahman.filepicker.model.MediaFile import es.dmoral.toasty.Toasty import guepardoapps.password.checkPasswordQuality import guepardoapps.passwordsafe.R import guepardoapps.passwordsafe.common.Constants import guepardoapps.passwordsafe.controller.ISystemInfoController import guepardoapps.passwordsafe.enums.InputSource import guepardoapps.passwordsafe.services.accountgroups.IAccountGroupService import guepardoapps.passwordsafe.services.accounts.IAccountService import guepardoapps.passwordsafe.services.client.IClientService import guepardoapps.passwordsafe.services.preferences.IPreferencesService import guepardoapps.passwordsafe.services.securityquestions.ISecurityQuestionService import guepardoapps.usbkeyboard.enums.Language import guepardoapps.usbkeyboard.services.IUsbKeyboardService import kotlinx.android.synthetic.main.fragment_preferences.* @ExperimentalUnsignedTypes internal class FragmentPreferences : BaseFragment() { private var saveButtonEnabled: Boolean = false private var clipboardTimeout: UInt = Constants.SharedPref.ClipboardTimeoutDefaultSec private var bubbleEnabled: Boolean = Constants.SharedPref.BubbleEnabledDefault private var loginTimeout: UInt = Constants.SharedPref.LoginTimeoutDefaultSec private var minSignsInPw: UInt = Constants.SharedPref.MinSignsInPwDefault private var pwLengthRange: Pair<UInt, UInt> = Pair(Constants.SharedPref.PwLengthRangeMinDefault, Constants.SharedPref.PwLengthRangeMaxDefault) private var language: Language = Language.en_US private var originalPassphrase: String = Constants.String.Empty private var passphrase: String = Constants.String.Empty private var passphrase2: String = Constants.String.Empty private var passphraseValidationCheck: Pair<Boolean, String> = Pair(false, Constants.String.Empty) private var passphraseMatch = false private lateinit var accountService: IAccountService private lateinit var accountGroupService: IAccountGroupService private lateinit var preferencesService: IPreferencesService private lateinit var securityQuestionService: ISecurityQuestionService private lateinit var systemInfoController: ISystemInfoController private lateinit var usbKeyboardService: IUsbKeyboardService override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_preferences, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupClipboard() setupBubble() setupPromptForLogin() setupMinSignsInPw() setupPwLength() setupUsbKeyboardLanguage() setupSaveButton() setupChangePassword() setupExportButton() setupImportButton() } fun setup(accountService: IAccountService, accountGroupService: IAccountGroupService, securityQuestionService: ISecurityQuestionService, clientService: IClientService, preferencesService: IPreferencesService, usbKeyboardService: IUsbKeyboardService, systemInfoController: ISystemInfoController) { this.accountService = accountService this.accountGroupService = accountGroupService this.securityQuestionService = securityQuestionService this.clientService = clientService this.preferencesService = preferencesService this.usbKeyboardService = usbKeyboardService this.systemInfoController = systemInfoController } fun hasChanges(): Boolean { return saveButtonEnabled } fun saveChanges() { if (saveButtonEnabled) { preferencesService.saveClipboardTimeout(clipboardTimeout) preferencesService.saveBubbleEnabled(bubbleEnabled) preferencesService.saveLoginTimeout(loginTimeout) preferencesService.saveMinSignsInPw(minSignsInPw) preferencesService.savePwLengthRange(pwLengthRange) preferencesService.saveUsbKeyboardLanguage(language) usbKeyboardService.language = language Toasty.success(context!!, "Successfully saved", Toast.LENGTH_LONG).show() validateSaveButtonEnabled() } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { when (requestCode) { Constants.Permission.ReadStorageRequestId -> { if (grantResults.any() && grantResults.first() == PackageManager.PERMISSION_GRANTED) { promptForImport() } else { Toasty.error(context!!, "Read permission denied. Cannot import data", Toast.LENGTH_LONG).show() } } Constants.Permission.WriteStorageRequestId -> { if (grantResults.any() && grantResults.first() == PackageManager.PERMISSION_GRANTED) { promptForExport() } else { Toasty.error(context!!, "Write permission denied. Cannot export data", Toast.LENGTH_LONG).show() } } else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == Constants.RequestCode.FilePicker && resultCode == RESULT_OK && data != null) { clientService.import(data.getParcelableArrayListExtra<MediaFile>(FilePickerActivity.MEDIA_FILES).first()) } } private fun setupClipboard() { clipboardTimeout = preferencesService.loadClipboardTimeout() fragment_preferences_edit_clipboard_timeout.setText(clipboardTimeout.toString()) fragment_preferences_edit_clipboard_timeout.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(editable: Editable?) { try { val string = editable.toString() if (!string.isEmpty()) { validateClipboardTimeout(Integer.parseInt(string).toUInt(), InputSource.TextField) } else { validateClipboardTimeout(Constants.SharedPref.ClipboardTimeoutDefaultSec, InputSource.TextField) } } catch (exception: Exception) { Log.e(tag, exception.message) } } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} }) fragment_preferences_seekbar_clipboard_timeout.max = (Constants.SharedPref.ClipboardTimeoutMaxSec - Constants.SharedPref.ClipboardTimeoutMinSec).toInt() fragment_preferences_seekbar_clipboard_timeout.progress = (clipboardTimeout - Constants.SharedPref.ClipboardTimeoutMinSec).toInt() fragment_preferences_seekbar_clipboard_timeout.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { if (fromUser) { validateClipboardTimeout(progress.toUInt() + Constants.SharedPref.ClipboardTimeoutMinSec, InputSource.SeekBar) } } override fun onStartTrackingTouch(seekBar: SeekBar?) {} override fun onStopTrackingTouch(seekBar: SeekBar?) {} }) } private fun setupBubble() { if (systemInfoController.currentAndroidApi() > Build.VERSION_CODES.M) { floating_account_expansionHeader.visibility = View.VISIBLE bubbleEnabled = preferencesService.loadBubbleEnabled() floating_account_checkbox.isChecked = bubbleEnabled floating_account_checkbox.setOnCheckedChangeListener { _, isChecked -> bubbleEnabled = isChecked if (bubbleEnabled) { systemInfoController.checkAPI23SystemPermission(Constants.Permission.DrawOverlayRequestId) } } } else { floating_account_expansionHeader.visibility = View.GONE } } private fun setupPromptForLogin() { loginTimeout = preferencesService.loadLoginTimeout() fragment_preferences_edit_prompt_for_login.setText(loginTimeout.toString()) fragment_preferences_edit_prompt_for_login.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(editable: Editable?) { try { val string = editable.toString() if (!string.isEmpty()) { validateLoginTimeout(Integer.parseInt(string).toUInt(), InputSource.TextField) } else { validateLoginTimeout(Constants.SharedPref.LoginTimeoutDefaultSec, InputSource.TextField) } } catch (exception: Exception) { Log.e(tag, exception.message) } } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} }) fragment_preferences_seekbar_prompt_for_login.max = (Constants.SharedPref.LoginTimeoutMaxSec - Constants.SharedPref.LoginTimeoutMinSec).toInt() fragment_preferences_seekbar_prompt_for_login.progress = (loginTimeout - Constants.SharedPref.LoginTimeoutMinSec).toInt() fragment_preferences_seekbar_prompt_for_login.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { if (fromUser) { validateLoginTimeout(progress.toUInt() + Constants.SharedPref.LoginTimeoutMinSec, InputSource.SeekBar) } } override fun onStartTrackingTouch(seekBar: SeekBar?) {} override fun onStopTrackingTouch(seekBar: SeekBar?) {} }) } private fun setupMinSignsInPw() { minSignsInPw = preferencesService.loadMinSignsInPw() fragment_preferences_edit_min_signs_in_pws.setText(minSignsInPw.toString()) fragment_preferences_edit_min_signs_in_pws.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(editable: Editable?) { try { val string = editable.toString() if (!string.isEmpty()) { validateMinSignsInPw(Integer.parseInt(string).toUInt(), InputSource.TextField) } else { validateMinSignsInPw(Constants.SharedPref.MinSignsInPwDefault, InputSource.TextField) } } catch (exception: Exception) { Log.e(tag, exception.message) } } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} }) fragment_preferences_seekbar_min_signs_in_pws.max = (Constants.SharedPref.MinSignsInPwMax - Constants.SharedPref.MinSignsInPwMin).toInt() fragment_preferences_seekbar_min_signs_in_pws.progress = (minSignsInPw - Constants.SharedPref.MinSignsInPwMin).toInt() fragment_preferences_seekbar_min_signs_in_pws.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { if (fromUser) { validateMinSignsInPw(progress.toUInt() + Constants.SharedPref.MinSignsInPwMin, InputSource.SeekBar) } } override fun onStartTrackingTouch(seekBar: SeekBar?) {} override fun onStopTrackingTouch(seekBar: SeekBar?) {} }) } private fun setupChangePassword() { input_change_passphrase_original.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(editable: Editable?) { originalPassphrase = editable.toString() } override fun beforeTextChanged(charSequence: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) {} }) input_change_passphrase.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(editable: Editable?) { passphrase = editable.toString() passphraseValidationCheck = passphrase.checkPasswordQuality() passphraseMatch = passphrase == passphrase2 && passphrase.isNotBlank() && passphrase2.isNotBlank() if (!passphraseValidationCheck.first) { input_change_passphrase_strength_indicator.setTextColor(Color.RED) input_change_passphrase_strength_indicator.text = passphraseValidationCheck.second } else { input_change_passphrase_strength_indicator.setTextColor(Color.GREEN) input_change_passphrase_strength_indicator.text = getString(R.string.valid) } if (!passphraseMatch) { input_change_passphrase_match_indicator.setTextColor(Color.RED) input_change_passphrase_match_indicator.text = getString(R.string.noMatch) } else { input_change_passphrase_match_indicator.setTextColor(Color.GREEN) input_change_passphrase_match_indicator.text = getString(R.string.match) } input_change_passphrase_save.isEnabled = originalPassphrase.isNotEmpty() && passphraseValidationCheck.first && passphraseMatch } override fun beforeTextChanged(charSequence: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) {} }) input_change_passphrase_2.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(editable: Editable?) { passphrase2 = editable.toString() passphraseMatch = passphrase == passphrase2 if (!passphraseMatch) { input_change_passphrase_match_indicator.setTextColor(Color.RED) input_change_passphrase_match_indicator.text = getString(R.string.noMatch) } else { input_change_passphrase_match_indicator.setTextColor(Color.GREEN) input_change_passphrase_match_indicator.text = getString(R.string.match) } input_change_passphrase_save.isEnabled = originalPassphrase.isNotEmpty() && passphraseValidationCheck.first && passphraseMatch } override fun beforeTextChanged(charSequence: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) {} }) input_change_passphrase_save.setOnClickListener { val originalPassphrase = input_change_passphrase_original.text.toString() if (!clientService.applicationLogin(originalPassphrase).successful) { input_change_passphrase_original_match.visibility = View.VISIBLE return@setOnClickListener } else { input_change_passphrase_original_match.visibility = View.GONE } val passphrase = input_change_passphrase.text.toString() val passphraseValidationCheck = passphrase.checkPasswordQuality() if (!passphraseValidationCheck.first) { input_change_passphrase_strength_indicator.visibility = View.VISIBLE return@setOnClickListener } else { input_change_passphrase_strength_indicator.visibility = View.GONE } val passphrase2 = input_change_passphrase_2.text.toString() val passphraseMatch = passphrase == passphrase2 && passphrase.isNotBlank() && passphrase2.isNotBlank() if (!passphraseMatch) { input_change_passphrase_match_indicator.visibility = View.VISIBLE return@setOnClickListener } else { input_change_passphrase_match_indicator.visibility = View.GONE } val accountList = accountService.get() val accountGroupList = accountGroupService.get() accountService.eraseData() accountGroupService.eraseData() clientService.eraseData() clientService.applicationSignUp(passphrase) accountService.updatePasswordData(context!!, clientService.getArgumentOne(), clientService.getArgumentTwo(), passphrase) accountGroupService.updatePasswordData(context!!, clientService.getArgumentOne(), clientService.getArgumentTwo(), passphrase) accountList.forEach { account -> accountService.create(account) } accountGroupList.forEach { accountGroup -> accountGroupService.create(accountGroup) } input_change_passphrase_original.setText(Constants.String.Empty) input_change_passphrase.setText(Constants.String.Empty) input_change_passphrase_2.setText(Constants.String.Empty) Toasty.success(context!!, "Successfully changed password", Toast.LENGTH_LONG).show() } } @SuppressLint("SetTextI18n") private fun setupPwLength() { pwLengthRange = preferencesService.loadPwLengthRange() pw_length_rangeseekbar_value.text = "${pwLengthRange.first} - ${pwLengthRange.second}" pw_length_rangeseekbar.seekBarChangeListener = object : RangeSeekBar.SeekBarChangeListener { override fun onStartedSeeking() {} override fun onStoppedSeeking() {} override fun onValueChanged(minThumbValue: Int, maxThumbValue: Int) { pwLengthRange = Pair(minThumbValue.toUInt(), maxThumbValue.toUInt()) pw_length_rangeseekbar_value.text = "$minThumbValue - $maxThumbValue" } } } private fun setupUsbKeyboardLanguage() { val languageList = Language.values().map { x -> x.text } val languageAdapter = ArrayAdapter<String>(context!!, android.R.layout.simple_spinner_item, languageList) languageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) usbkeyboard_language_spinner.adapter = languageAdapter usbkeyboard_language_spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) {} override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { language = Language.values().find { x -> x.text == languageList[position] }!! } } } private fun setupSaveButton() { fragment_preferences_save_button.isEnabled = saveButtonEnabled fragment_preferences_save_button.setOnClickListener { saveChanges() } } private fun setupExportButton() { fragment_preferences_export_button.setOnClickListener { if (ContextCompat.checkSelfPermission(context!!, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { promptForExport() } else { ActivityCompat.requestPermissions(activity!!, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), Constants.Permission.WriteStorageRequestId) } } } private fun setupImportButton() { fragment_preferences_import_button.setOnClickListener { if (ContextCompat.checkSelfPermission(context!!, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { promptForImport() } else { ActivityCompat.requestPermissions(activity!!, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), Constants.Permission.ReadStorageRequestId) } } } private fun validateClipboardTimeout(newClipboardTimeout: UInt, inputSource: InputSource) { clipboardTimeout = newClipboardTimeout if (clipboardTimeout < Constants.SharedPref.ClipboardTimeoutMinSec) { clipboardTimeout = Constants.SharedPref.ClipboardTimeoutMinSec } else if (clipboardTimeout > Constants.SharedPref.ClipboardTimeoutMaxSec) { clipboardTimeout = Constants.SharedPref.ClipboardTimeoutMaxSec } when (inputSource) { InputSource.SeekBar -> fragment_preferences_edit_clipboard_timeout.setText(clipboardTimeout.toString()) InputSource.TextField -> fragment_preferences_seekbar_clipboard_timeout.progress = (clipboardTimeout - Constants.SharedPref.ClipboardTimeoutMinSec).toInt() else -> Log.w(tag, "Invalid source $inputSource") } validateSaveButtonEnabled() } private fun validateLoginTimeout(newLoginTimeout: UInt, inputSource: InputSource) { loginTimeout = newLoginTimeout if (loginTimeout < Constants.SharedPref.LoginTimeoutMinSec) { loginTimeout = Constants.SharedPref.LoginTimeoutMinSec } else if (loginTimeout > Constants.SharedPref.LoginTimeoutMaxSec) { loginTimeout = Constants.SharedPref.LoginTimeoutMaxSec } when (inputSource) { InputSource.SeekBar -> fragment_preferences_edit_prompt_for_login.setText(loginTimeout.toString()) InputSource.TextField -> fragment_preferences_seekbar_prompt_for_login.progress = (loginTimeout - Constants.SharedPref.LoginTimeoutMinSec).toInt() else -> Log.w(tag, "Invalid source $inputSource") } validateSaveButtonEnabled() } private fun validateMinSignsInPw(newMinSignsInPw: UInt, inputSource: InputSource) { minSignsInPw = newMinSignsInPw if (minSignsInPw < Constants.SharedPref.MinSignsInPwMin) { minSignsInPw = Constants.SharedPref.MinSignsInPwMin } else if (minSignsInPw > Constants.SharedPref.MinSignsInPwMax) { minSignsInPw = Constants.SharedPref.MinSignsInPwMax } when (inputSource) { InputSource.SeekBar -> fragment_preferences_edit_min_signs_in_pws.setText(minSignsInPw.toString()) InputSource.TextField -> fragment_preferences_seekbar_min_signs_in_pws.progress = (minSignsInPw - Constants.SharedPref.MinSignsInPwMin).toInt() else -> Log.w(tag, "Invalid source $inputSource") } validateSaveButtonEnabled() } private fun validateSaveButtonEnabled() { saveButtonEnabled = clipboardTimeout != preferencesService.loadClipboardTimeout() || bubbleEnabled != preferencesService.loadBubbleEnabled() || loginTimeout != preferencesService.loadLoginTimeout() || minSignsInPw != preferencesService.loadMinSignsInPw() || language != preferencesService.loadUsbKeyboardLanguage() fragment_preferences_save_button.isEnabled = saveButtonEnabled fragment_preferences_save_button.setTextColor(if (saveButtonEnabled) Color.BLACK else Color.LTGRAY) } private fun promptForExport() { MaterialDialog.Builder(context!!) .title(R.string.exportDialogTitle) .content(R.string.exportDialogPrompt) .positiveText(R.string.backupEncrypted) .onPositive { _, _ -> exportData(false) } .negativeText(R.string.backupDecrypted) .onNegative { _, _ -> exportData(true) } .show() } private fun exportData(decrypt: Boolean) { fragment_preferences_export_button.isEnabled = false try { clientService.export(decrypt) } catch (exception: Exception) { Log.e(tag, exception.message) } finally { fragment_preferences_export_button.isEnabled = true } } private fun promptForImport() { val intent = Intent(context, FilePickerActivity::class.java) intent.putExtra(FilePickerActivity.CONFIGS, Configurations.Builder() .setShowFiles(true) .setShowImages(false) .setShowVideos(false) .setSingleChoiceMode(true) .setSuffixes("csv") .build()) startActivityForResult(intent, Constants.RequestCode.FilePicker) } }
mit
37c67e0126dd272637b06018cbc0e1a7
46.590494
167
0.673005
5.196846
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/preferences/SeekBarPreferenceCompat.kt
1
9803
/* * Copyright (c) 2021 David Allison <[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/>. * * * The following code was written by Matthew Wiggins * and is released under the APACHE 2.0 license * * http://www.apache.org/licenses/LICENSE-2.0 * * adjusted by Norbert Nagold 2011 <[email protected]> * adjusted by David Allison 2021 <[email protected]> * * Converted to androidx.preference.DialogPreference * * Split into SeekBarPreferenceCompat and SeekBarDialogFragmentCompat */ package com.ichi2.preferences import android.content.Context import android.util.AttributeSet import android.view.Gravity import android.view.View import android.widget.LinearLayout import android.widget.SeekBar import android.widget.SeekBar.OnSeekBarChangeListener import android.widget.TextView import androidx.annotation.StringRes import androidx.appcompat.app.AlertDialog import androidx.core.content.withStyledAttributes import androidx.preference.DialogPreference import androidx.preference.PreferenceDialogFragmentCompat import com.ichi2.anki.AnkiDroidApp import com.ichi2.anki.R import com.ichi2.ui.FixedTextView class SeekBarPreferenceCompat @JvmOverloads // required to inflate the preference from a XML constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.dialogPreferenceStyle, defStyleRes: Int = R.style.Preference_DialogPreference ) : DialogPreference(context, attrs, defStyleAttr, defStyleRes), DialogFragmentProvider { private var suffix: String private var default: Int private var max: Int private var min: Int private var interval: Int private var mValue = 0 @StringRes private var xLabel: Int @StringRes private var yLabel: Int init { suffix = attrs?.getAttributeValue(AnkiDroidApp.ANDROID_NAMESPACE, "text") ?: "" default = attrs?.getAttributeIntValue(AnkiDroidApp.ANDROID_NAMESPACE, "defaultValue", 0) ?: 0 max = attrs?.getAttributeIntValue(AnkiDroidApp.ANDROID_NAMESPACE, "max", 100) ?: 100 min = attrs?.getAttributeIntValue(AnkiDroidApp.XML_CUSTOM_NAMESPACE, "min", 0) ?: 0 interval = attrs?.getAttributeIntValue(AnkiDroidApp.XML_CUSTOM_NAMESPACE, "interval", 1) ?: 1 xLabel = attrs?.getAttributeResourceValue(AnkiDroidApp.XML_CUSTOM_NAMESPACE, "xlabel", 0) ?: 0 yLabel = attrs?.getAttributeResourceValue(AnkiDroidApp.XML_CUSTOM_NAMESPACE, "ylabel", 0) ?: 0 context.withStyledAttributes(attrs, R.styleable.CustomPreference) { val useSimpleSummaryProvider = getBoolean(R.styleable.CustomPreference_useSimpleSummaryProvider, false) if (useSimpleSummaryProvider) { setSummaryProvider { value.toString() } } val summaryFormat = getString(R.styleable.CustomPreference_summaryFormat) if (summaryFormat != null) { setSummaryProvider { String.format(summaryFormat, value) } } } } @Suppress("DEPRECATION") @Deprecated("Deprecated in Java") override fun onSetInitialValue(restore: Boolean, defaultValue: Any?) { super.onSetInitialValue(restore, defaultValue) mValue = getPersistedInt(default) mValue = if (restore) { if (shouldPersist()) getPersistedInt(default) else 0 } else { defaultValue as Int } } var value: Int get() = if (mValue == 0) { getPersistedInt(default) } else { mValue } set(value) { mValue = value persistInt(value) } private fun onValueUpdated() { if (shouldPersist()) { persistInt(mValue) } callChangeListener(mValue) } private val valueText: String get() = mValue.toString() + suffix // TODO: These could do with some thought as to either documentation, or defining the coupling between here and // SeekBarDialogFragmentCompat private fun setRelativeValue(value: Int) { mValue = value * interval + min } private val relativeMax: Int get() = (max - min) / interval private val relativeProgress: Int get() = (mValue - min) / interval private fun setupTempValue() { if (!shouldPersist()) { return } mValue = getPersistedInt(default) } class SeekBarDialogFragmentCompat : PreferenceDialogFragmentCompat(), OnSeekBarChangeListener { private lateinit var seekLine: LinearLayout private lateinit var seekBar: SeekBar private lateinit var valueText: TextView override fun getPreference(): SeekBarPreferenceCompat { return super.getPreference() as SeekBarPreferenceCompat } override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) { if (fromUser) { preference.setRelativeValue(value) preference.onValueUpdated() onValueUpdated() } } private fun onValueUpdated() { valueText.text = preference.valueText } override fun onStartTrackingTouch(seekBar: SeekBar) { // intentionally left blank } override fun onStopTrackingTouch(seekBar: SeekBar) { preference.notifyChanged() // to reload the summary with summaryProvider this.dialog!!.dismiss() } override fun onDialogClosed(positiveResult: Boolean) { // nothing needed - see onStopTrackingTouch } override fun onBindDialogView(v: View) { super.onBindDialogView(v) seekBar.max = preference.relativeMax seekBar.progress = preference.relativeProgress } override fun onPrepareDialogBuilder(builder: AlertDialog.Builder) { super.onPrepareDialogBuilder(builder) builder.setNegativeButton(null, null) builder.setPositiveButton(null, null) builder.setTitle(null) } override fun onCreateDialogView(context: Context): View { val layout = LinearLayout(context) layout.orientation = LinearLayout.VERTICAL layout.setPadding(6, 6, 6, 6) valueText = FixedTextView(context).apply { gravity = Gravity.CENTER_HORIZONTAL textSize = 32f } val params = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) layout.addView(valueText, params) if (preference.xLabel != 0 && preference.yLabel != 0) { val paramsSeekbar = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) paramsSeekbar.setMargins(0, 12, 0, 0) seekLine = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL setPadding(6, 6, 6, 6) } addLabelsBelowSeekBar(context) layout.addView(seekLine, paramsSeekbar) } preference.setupTempValue() seekBar = SeekBar(context).apply { setOnSeekBarChangeListener(this@SeekBarDialogFragmentCompat) max = preference.relativeMax progress = preference.relativeProgress } layout.addView( seekBar, LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) ) onValueUpdated() return layout } private fun addLabelsBelowSeekBar(context: Context) { val labels = intArrayOf(preference.xLabel, preference.yLabel) for (count in 0..1) { val textView = FixedTextView(context).apply { text = context.getString(labels[count]) gravity = Gravity.START } seekLine.addView(textView) textView.layoutParams = if (context.resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_LTR) { if (count == 1) { getLayoutParams(0.0f) } else { getLayoutParams(1.0f) } } else { if (count == 0) { getLayoutParams(0.0f) } else { getLayoutParams(1.0f) } } } } fun getLayoutParams(weight: Float): LinearLayout.LayoutParams { return LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, weight ) } } override fun makeDialogFragment() = SeekBarDialogFragmentCompat() }
gpl-3.0
b42ddc679f008b9fe1ab1113f9816a8b
35.715356
123
0.623687
5.145932
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/view/activity/webView/ProgressResponseBody.kt
1
2179
/* * Copyright (c) 2017. Toshi Inc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.toshi.view.activity.webView import okhttp3.MediaType import okhttp3.ResponseBody import okio.BufferedSource import okio.Okio import okio.Source import okio.ForwardingSource import okio.Buffer class ProgressResponseBody( private val responseBody: ResponseBody, private val progressListener: (Int) -> Unit ) : ResponseBody() { private var bufferedSource: BufferedSource? = null override fun contentLength(): Long = responseBody.contentLength() override fun contentType(): MediaType? = responseBody.contentType() override fun source(): BufferedSource? { if (bufferedSource == null) bufferedSource = Okio.buffer(source(responseBody.source())) return bufferedSource } private fun source(source: Source): Source { return object : ForwardingSource(source) { private var totalBytesRead = 0L override fun read(sink: Buffer?, byteCount: Long): Long { if (sink == null) return totalBytesRead val bytesRead = super.read(sink, byteCount) totalBytesRead += if (bytesRead != -1L) bytesRead else 0L val contentLength = responseBody.contentLength() or Math.max(bytesRead, 5000L) val progress = if (bytesRead == -1L) 0L else (100 * bytesRead) / contentLength progressListener.invoke(progress.toInt()) return bytesRead } } } }
gpl-3.0
c495307fcc06650f7f2c45137c2f4f7f
35.949153
95
0.673704
4.757642
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/viewmodel/MechanicViewModel.kt
1
1538
package com.boardgamegeek.ui.viewmodel import android.app.Application import androidx.lifecycle.* import com.boardgamegeek.db.CollectionDao import com.boardgamegeek.provider.BggContract import com.boardgamegeek.repository.MechanicRepository class MechanicViewModel(application: Application) : AndroidViewModel(application) { enum class CollectionSort { NAME, RATING } private val repository = MechanicRepository(getApplication()) private val _mechanic = MutableLiveData<Pair<Int, CollectionSort>>() fun setId(id: Int) { if (_mechanic.value?.first != id) _mechanic.value = id to CollectionSort.RATING } fun setSort(sortType: CollectionSort) { if (_mechanic.value?.second != sortType) _mechanic.value = (_mechanic.value?.first ?: BggContract.INVALID_ID) to sortType } fun refresh() { _mechanic.value?.let { _mechanic.value = it } } val sort = _mechanic.map { it.second } val collection = _mechanic.switchMap { m -> liveData { emit( when (m.first) { BggContract.INVALID_ID -> emptyList() else -> when (m.second) { CollectionSort.NAME -> repository.loadCollection(m.first, CollectionDao.SortType.NAME) CollectionSort.RATING -> repository.loadCollection(m.first, CollectionDao.SortType.RATING) } } ) } } }
gpl-3.0
d9f5591c96b0e6812680efdbe59b0ca8
30.387755
118
0.604681
4.445087
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/command/LanternCommandCauseFactory.kt
1
2750
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.command import org.lanternpowered.api.Lantern import org.lanternpowered.api.audience.Audience import org.lanternpowered.api.cause.CauseContextKeys import org.lanternpowered.api.cause.CauseStack import org.lanternpowered.api.cause.first import org.lanternpowered.api.cause.get import org.lanternpowered.api.entity.Entity import org.lanternpowered.api.text.Text import org.lanternpowered.api.util.optional.asOptional import org.lanternpowered.api.util.optional.orNull import org.lanternpowered.api.world.Locatable import org.spongepowered.api.block.BlockSnapshot import org.spongepowered.api.command.CommandCause import org.lanternpowered.api.cause.Cause import org.lanternpowered.api.world.Location import org.spongepowered.api.service.permission.Subject import org.spongepowered.math.vector.Vector3d import java.util.Optional object LanternCommandCauseFactory : CommandCause.Factory { override fun create(): CommandCause = LanternCommandCause(CauseStack.currentCause) } private class LanternCommandCause(private val cause: Cause) : CommandCause { override fun getSubject(): Subject = this.cause[CauseContextKeys.SUBJECT] ?: this.cause.first() ?: Lantern.systemSubject override fun getAudience(): Audience = this.cause[CauseContextKeys.AUDIENCE] ?: this.cause.first() ?: Lantern.systemSubject override fun getLocation(): Optional<Location> { var location = this.cause[CauseContextKeys.LOCATION] if (location != null) return location.asOptional() location = this.targetBlock.orNull()?.location?.orNull() if (location != null) return location.asOptional() return this.cause.first<Locatable>()?.serverLocation.asOptional() } override fun getRotation(): Optional<Vector3d> { val rotation = this.cause[CauseContextKeys.ROTATION] if (rotation != null) return rotation.asOptional() return this.cause.first<Entity>()?.rotation.asOptional() } override fun getTargetBlock(): Optional<BlockSnapshot> { val target = this.cause[CauseContextKeys.BLOCK_TARGET] if (target != null) return target.asOptional() return this.cause.first<BlockSnapshot>().asOptional() } override fun sendMessage(message: Text) { this.audience.sendMessage(message) } override fun getCause() = this.cause }
mit
09aced19711fa49fa711ba389e5a2dea
36.671233
96
0.736364
4.276827
false
false
false
false
ursjoss/scipamato
core/core-sync/src/test/kotlin/ch/difty/scipamato/core/sync/jobs/newsletter/NewStudySyncConfigTest.kt
1
4803
package ch.difty.scipamato.core.sync.jobs.newsletter import ch.difty.scipamato.common.FrozenDateTimeService import io.mockk.every import io.mockk.mockk import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeInstanceOf import org.jooq.DSLContext import org.jooq.SQLDialect import org.jooq.impl.DSL import org.jooq.tools.jdbc.MockConnection import org.jooq.tools.jdbc.MockDataProvider import org.junit.jupiter.api.Test import org.springframework.batch.core.configuration.annotation.JobBuilderFactory import org.springframework.batch.core.configuration.annotation.StepBuilderFactory import java.sql.ResultSet import java.sql.Timestamp import javax.sql.DataSource internal class NewStudySyncConfigTest { private val provider = mockk<MockDataProvider>() private val connection = MockConnection(provider) private val jooqCore: DSLContext = DSL.using(connection, SQLDialect.POSTGRES) private val jooqPublic: DSLContext = DSL.using(connection, SQLDialect.POSTGRES) private val coreDataSource = mockk<DataSource>() private val jobBuilderFactory = mockk<JobBuilderFactory>() private val stepBuilderFactory = mockk<StepBuilderFactory>() private val dateTimeService = FrozenDateTimeService() private val config = NewStudySyncConfig( jooqCore, jooqPublic, coreDataSource, jobBuilderFactory, stepBuilderFactory, dateTimeService ) @Test fun jobName() { config.jobName shouldBeEqualTo "syncNewStudyJob" } @Test fun publicWriter() { config.publicWriter() shouldBeInstanceOf NewStudyItemWriter::class } @Test fun lastSynchedField() { config.lastSynchedField().toString() shouldBeEqualTo """"public"."new_study"."last_synched"""" } @Test fun makingEntity() { val resultSet = mockk<ResultSet> { every { getInt("newsletter_id") } returns 10 every { getInt("newsletter_topic_id") } returns 11 every { getLong("number") } returns 12 every { getInt("publication_year") } returns 13 every { getString("first_author") } returns "myfirstauthor" every { getString("authors") } returns "a2,a3" every { getString("goals") } returns "mygoals" every { getString("headline") } returns "myheadline" every { getInt("version") } returns 14 every { getTimestamp("created") } returns Timestamp.valueOf("2020-04-04 12:13:14") every { getTimestamp("last_modified") } returns Timestamp.valueOf("2020-04-04 13:14:15") every { wasNull() } returns false } val newStudy = config.makeEntity(resultSet) newStudy.newsletterId shouldBeEqualTo 10 newStudy.newsletterTopicId shouldBeEqualTo 11 newStudy.sort shouldBeEqualTo 1 newStudy.paperNumber shouldBeEqualTo 12 newStudy.year shouldBeEqualTo 13 newStudy.authors shouldBeEqualTo "myfirstauthor et al." newStudy.headline shouldBeEqualTo "myheadline" newStudy.description shouldBeEqualTo "mygoals" newStudy.version shouldBeEqualTo 14 newStudy.created.toString() shouldBeEqualTo "2020-04-04 12:13:14.0" newStudy.lastModified.toString() shouldBeEqualTo "2020-04-04 13:14:15.0" newStudy.lastSynched.toString() shouldBeEqualTo "2016-12-09 06:02:13.0" } @Suppress("MaxLineLength") @Test fun selectSql() { /* ktlint-disable max-line-length */ config.selectSql() shouldBeEqualTo """select "public"."paper_newsletter"."newsletter_id", "public"."paper_newsletter"."paper_id", "public"."paper_newsletter"."newsletter_topic_id", "public"."paper"."publication_year", "public"."paper"."number", "public"."paper"."first_author", "public"."paper"."authors", "public"."paper_newsletter"."headline", "public"."paper"."goals", "public"."paper_newsletter"."version", "public"."paper_newsletter"."created", "public"."paper_newsletter"."last_modified" from "public"."paper_newsletter" join "public"."paper" on "public"."paper_newsletter"."paper_id" = "public"."paper"."id" join "public"."paper_code" on "public"."paper"."id" = "public"."paper_code"."paper_id" join "public"."newsletter" on "public"."paper_newsletter"."newsletter_id" = "public"."newsletter"."id" where "public"."newsletter"."publication_status" = 1""" /* ktlint-enable max-line-length */ } @Test fun pseudoFkDcs() { config.pseudoFkDcs.toString() shouldBeEqualTo """delete from "public"."new_study" |where "public"."new_study"."newsletter_topic_id" not in ( | select distinct "public"."newsletter_topic"."id" | from "public"."newsletter_topic" |)""".trimMargin() } }
bsd-3-clause
80755fd50077ccef959d4e24cb389693
44.311321
837
0.685197
4.354488
false
true
false
false
googlecodelabs/watchnext-for-movie-tv-episodes
step_4_completed/src/test/java/com/android/tv/reference/shared/watchprogress/WatchProgressTest.kt
9
3818
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tv.reference.shared.watchprogress import android.content.Context import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.room.Room import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.tv.reference.lifecycle.ext.getOrAwaitValue import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Tests the WatchProgress database interaction */ @RunWith(AndroidJUnit4::class) class WatchProgressTest { @get:Rule var instantTaskExecutorRule: InstantTaskExecutorRule = InstantTaskExecutorRule() private lateinit var watchProgressDatabase: WatchProgressDatabase private lateinit var watchProgressDao: WatchProgressDao @Before fun setUp() { val context = ApplicationProvider.getApplicationContext<Context>() watchProgressDatabase = Room.inMemoryDatabaseBuilder(context, WatchProgressDatabase::class.java) .allowMainThreadQueries() .build() watchProgressDao = watchProgressDatabase.watchProgressDao() } @After fun tearDown() { watchProgressDatabase.close() } @Test fun basicWriteAndRead() = runBlocking { // Create and insert two WatchProgress instances val watchProgress1 = WatchProgress("test1", 123) val watchProgress2 = WatchProgress("test2", 0) watchProgressDao.insert(watchProgress1) watchProgressDao.insert(watchProgress2) // Read the WatchProgress data back out of the database val watchProgressRead1 = watchProgressDao.getWatchProgressByVideoId(watchProgress1.videoId).getOrAwaitValue() val watchProgressRead2 = watchProgressDao.getWatchProgressByVideoId(watchProgress2.videoId).getOrAwaitValue() // Verify the data matches what was supposed to be inserted assertThat(watchProgressRead1).isEqualTo(watchProgress1) assertThat(watchProgressRead2).isEqualTo(watchProgress2) } @Test fun writeOverwriteAndRead() = runBlocking { // Insert a WatchProgress val watchProgress = WatchProgress("test1", 0) watchProgressDao.insert(watchProgress) // Insert an update watchProgress.startPosition = 500 watchProgressDao.insert(watchProgress) // Verify the update was stored val watchProgressRead = watchProgressDao.getWatchProgressByVideoId(watchProgress.videoId).getOrAwaitValue() assertThat(watchProgressRead).isEqualTo(watchProgress) } @Test fun writeAndClear() = runBlocking { // Insert a WatchProgress val watchProgress = WatchProgress("test1", 0) watchProgressDao.insert(watchProgress) // Delete all entries watchProgressDao.deleteAll() // Verify the inserted entry is no longer present val watchProgressRead = watchProgressDao.getWatchProgressByVideoId(watchProgress.videoId).value assertThat(watchProgressRead).isNull() } }
apache-2.0
adc22b15c7b2c57f23b19696b5c44281
34.351852
96
0.727082
4.784461
false
true
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/util/ErrorFormatting.kt
1
10148
package com.pr0gramm.app.util import android.content.Context import androidx.annotation.StringRes import com.pr0gramm.app.Logger import com.pr0gramm.app.R import com.pr0gramm.app.api.pr0gramm.LoginCookieJar import com.pr0gramm.app.ui.PermissionHelperDelegate import com.squareup.moshi.JsonDataException import com.squareup.moshi.JsonEncodingException import retrofit2.HttpException import java.io.EOFException import java.io.FileNotFoundException import java.io.IOException import java.net.* import java.util.concurrent.TimeoutException import javax.net.ssl.SSLException /** * This provides utilities for formatting of exceptions.. */ object ErrorFormatting { fun getFormatter(error: Throwable): Formatter { return formatters.firstOrNull { it.handles(error) } ?: throw IllegalStateException("There should always be a default formatter", error) } class Formatter internal constructor(private val errorCheck: (Throwable) -> Boolean, private val message: (Throwable, Context) -> String, private val report: Boolean = true) { /** * Tests if this formatter handles the given exception. */ fun handles(thr: Throwable): Boolean = errorCheck(thr) /** * Gets the message for the given exception. You must only call this, * if [.handles] returned true before. */ fun getMessage(context: Context, thr: Throwable): String { Logger("ErrorFormatting").warn("Formatting error:", thr) return message(thr, context) } /** * Returns true, if this exception should be logged */ fun shouldSendToCrashlytics(): Boolean { return report } } private fun guessMessage(err: Throwable, context: Context): String { var message = err.localizedMessage if (message.isNullOrBlank()) message = err.message if (message.isNullOrBlank()) message = context.getString(R.string.error_exception_of_type, err.javaClass.directName) return message } private class Builder<out T : Throwable>(private val errorType: Class<in T>) { private val _errorCheck = mutableListOf<(T) -> Boolean>() private var _report: Boolean = true // by default just print the message of the exception. private var _message = { thr: T, ctx: Context -> guessMessage(thr, ctx) } fun silence() { _report = false } fun string(@StringRes id: Int) { _message = { _, ctx -> ctx.getString(id) } } fun format(fn: Context.(T) -> String) { _message = { thr, ctx -> ctx.fn(thr) } } fun check(fn: T.() -> Boolean) { _errorCheck += { it.fn() } } @Suppress("UNCHECKED_CAST") fun build(): Formatter { return Formatter( errorCheck = { err -> errorType.isInstance(err) && _errorCheck.all { it(err as T) } }, message = { err, ctx -> _message(err as T, ctx) }, report = _report) } } private class FormatterList { val formatters = mutableListOf<Formatter>() inline fun <reified T : Throwable> add(configure: Builder<T>.() -> Unit) { formatters.add(Builder(T::class.java).apply(configure).build()) } inline fun <reified T : Throwable> addCaused(configure: Builder<T>.() -> Unit) { val actual = Builder(T::class.java).apply(configure).build() formatters.add(Formatter( errorCheck = { it.hasCauseOfType<T>() && actual.handles(it.getCauseOfType<T>()!!) }, message = { err, ctx -> actual.getMessage(ctx, err.getCauseOfType<T>()!!) }, report = actual.shouldSendToCrashlytics() )) } } /** * Returns a list containing multiple error formatters in the order they should * be applied. * @return The error formatters. */ private fun makeErrorFormatters(): List<Formatter> { val formatters = FormatterList() formatters.add<HttpException> { silence() check { code() == 403 && "cloudflare" in bodyContent } string(R.string.error_cloudflare) } formatters.add<HttpException> { silence() check { code() == 403 && "<html>" in bodyContent } string(R.string.error_blocked) } formatters.add<HttpException> { silence() check { code() in listOf(401, 403) } string(R.string.error_not_authorized) } formatters.add<HttpException> { silence() check { code() == 429 } string(R.string.error_rate_limited) } formatters.add<HttpException> { silence() check { code() == 404 } string(R.string.error_not_found) } formatters.add<HttpException> { silence() check { code() == 504 } string(R.string.error_proxy_timeout) } formatters.add<HttpException> { silence() check { code() == 522 } string(R.string.error_origin_timeout_ddos) } formatters.add<HttpException> { silence() check { code() / 100 == 5 } string(R.string.error_service_unavailable) } formatters.add<JsonEncodingException> { string(R.string.error_json) } formatters.addCaused<FileNotFoundException> { silence() string(R.string.error_post_not_found) } formatters.addCaused<TimeoutException> { silence() string(R.string.error_timeout) } formatters.addCaused<SocketTimeoutException> { silence() string(R.string.error_timeout) } formatters.addCaused<JsonDataException> { silence() string(R.string.error_conversion) } formatters.addCaused<UnknownHostException> { silence() string(R.string.error_host_not_found) } formatters.addCaused<SSLException> { silence() string(R.string.error_ssl_error) } formatters.addCaused<ProtocolException> { string(R.string.error_protocol_exception) } formatters.addCaused<ConnectException> { silence() format { err -> if (":443" in err.toString()) { getString(R.string.error_connect_exception_https, err.localizedMessage) } else { getString(R.string.error_connect_exception, err.localizedMessage) } } } formatters.addCaused<SocketException> { silence() string(R.string.error_socket) } formatters.addCaused<EOFException> { silence() string(R.string.error_socket) } formatters.add<LoginCookieJar.LoginRequiredException> { string(R.string.error_login_required_exception) } formatters.add<IllegalStateException> { silence() check { "onSaveInstanceState" in toString() } string(R.string.error_generic) } formatters.add<IllegalStateException> { silence() check { ": Expected " in toString() } format { getString(R.string.error_json_mapping, it.message) } } formatters.add<StringException> { silence() format { it.messageProvider(this) } } formatters.add<PermissionHelperDelegate.PermissionNotGranted> { format { var permissionName: CharSequence = it.permission try { val permissionInfo = packageManager.getPermissionInfo(it.permission, 0) permissionName = permissionInfo.loadLabel(packageManager) } catch (err: Throwable) { } getString(R.string.error_permission_not_granted, permissionName) } } formatters.add<IOException> { silence() } formatters.addCaused<NullPointerException> { string(R.string.error_nullpointer) } formatters.addCaused<OutOfMemoryError> { string(R.string.error_oom) } formatters.add<Throwable> {} return formatters.formatters } inline fun <reified T : Throwable> Throwable.getCauseOfType(): T? { var current: Throwable? = this while (current != null) { if (current is T) { return current } current = current.cause } return null } /** * Checks if the given throwable or any of it's causes is of the given type. */ inline fun <reified T : Throwable> Throwable.hasCauseOfType(): Boolean { return getCauseOfType<T>() != null } fun format(context: Context, error: Throwable): String { return getFormatter(error).getMessage(context, error) } private val formatters = makeErrorFormatters() } private val HttpException.bodyContent: String get() { val body = this.response()?.errorBody() ?: return "" return runCatching { body.string() }.getOrDefault("") } class StringException : RuntimeException { val messageProvider: (Context) -> String constructor(cause: Throwable, @StringRes stringId: Int) : super(cause) { messageProvider = { ctx -> ctx.getString(stringId) } } constructor(internalMessage: String, @StringRes stringId: Int) : super(internalMessage) { messageProvider = { ctx -> ctx.getString(stringId) } } constructor(internalMessage: String, provider: (Context) -> String) : super(internalMessage) { messageProvider = provider } }
mit
806575c95f3f6583e8656d7ed490cb15
29.65861
106
0.57233
4.742056
false
false
false
false
pjq/rpi
android/app/src/main/java/me/pjq/rpicar/TemperatureChartTimeActivity.kt
1
16416
package me.pjq.rpicar import android.graphics.Color import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.widget.SeekBar import android.widget.SeekBar.OnSeekBarChangeListener import android.widget.TextView import android.widget.Toast import com.github.mikephil.charting.charts.LineChart import com.github.mikephil.charting.components.AxisBase import com.github.mikephil.charting.components.XAxis import com.github.mikephil.charting.components.YAxis import com.github.mikephil.charting.components.YAxis.AxisDependency import com.github.mikephil.charting.data.Entry import com.github.mikephil.charting.data.LineData import com.github.mikephil.charting.data.LineDataSet import com.github.mikephil.charting.formatter.IAxisValueFormatter import com.github.mikephil.charting.utils.ColorTemplate import com.google.gson.Gson import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.text.SimpleDateFormat import java.util.ArrayList import java.util.Arrays import java.util.Collections import java.util.Date import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import io.reactivex.Observable import io.reactivex.ObservableSource import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.functions.Function import io.reactivex.schedulers.Schedulers import me.pjq.rpicar.chart.ChartDemoBaseActivity import me.pjq.rpicar.models.WeatherItem import me.pjq.rpicar.realm.Settings import me.pjq.rpicar.utils.Logger class TemperatureChartTimeActivity : ChartDemoBaseActivity(), OnSeekBarChangeListener { private var mChart: LineChart? = null private var mSeekBarX: SeekBar? = null private var tvX: TextView? = null private var colorPM25: TextView? = null private var colorTemp: TextView? = null private var colorHumidity: TextView? = null internal var disposable: Disposable? = null internal var weatherItems: List<WeatherItem>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_temperature_chart) supportActionBar!!.setHomeButtonEnabled(true) setTitle(R.string.pm25title) colorPM25 = findViewById(R.id.colorPM25) as TextView colorTemp = findViewById(R.id.colorTemp) as TextView colorHumidity = findViewById(R.id.colorHumidity) as TextView tvX = findViewById(R.id.tvXMax) as TextView mSeekBarX = findViewById(R.id.seekBar1) as SeekBar mSeekBarX!!.progress = 100 tvX!!.text = "100" mSeekBarX!!.setOnSeekBarChangeListener(this) mChart = findViewById(R.id.chart1) as LineChart // no description text mChart!!.description.isEnabled = false // enable touch gestures mChart!!.setTouchEnabled(true) mChart!!.dragDecelerationFrictionCoef = 0.9f // enable scaling and dragging mChart!!.isDragEnabled = true mChart!!.setScaleEnabled(true) mChart!!.setDrawGridBackground(false) mChart!!.isHighlightPerDragEnabled = true // set an alternative background color mChart!!.setBackgroundColor(Color.WHITE) mChart!!.setViewPortOffsets(0f, 0f, 0f, 0f) mChart!!.invalidate() // get the legend (only possible after setting data) val l = mChart!!.legend l.isEnabled = false val xAxis = mChart!!.xAxis xAxis.position = XAxis.XAxisPosition.TOP_INSIDE xAxis.typeface = mTfLight xAxis.textSize = 10f xAxis.textColor = Color.GREEN xAxis.setDrawAxisLine(false) xAxis.setDrawGridLines(true) // xAxis.setTextColor(Color.rgb(255, 192, 56)); xAxis.textColor = Color.DKGRAY xAxis.setCenterAxisLabels(true) xAxis.granularity = 1f // one hour // xAxis.valueFormatter = object : IAxisValueFormatter { // // private val mFormat = SimpleDateFormat(" MM/dd HH:mm") // // override fun getFormattedValue(value: Float, axis: AxisBase): String { // if (value < 0 || value >= weatherItems!!.size) { // return "" // } // // val item = weatherItems!![value.toInt()] // return mFormat.format(Date(item.timestamp)) // } // } val leftAxis = mChart!!.axisLeft leftAxis.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART) leftAxis.typeface = mTfLight leftAxis.textColor = ColorTemplate.getHoloBlue() leftAxis.setDrawGridLines(true) leftAxis.isGranularityEnabled = true leftAxis.axisMinimum = 0f leftAxis.axisMaximum = 500f leftAxis.yOffset = -9f // leftAxis.setTextColor(Color.rgb(255, 192, 56)); leftAxis.textColor = Color.DKGRAY val rightAxis = mChart!!.axisRight rightAxis.isEnabled = false initWeatherStatus() readDemoJson() } private fun readDemoJson() { val settings = DataManager.realm.where(Settings::class.java).findFirst() if (settings != null) { val weatherJson = settings.getWeatherJson() if (null != weatherJson) { val weatherItems = Arrays.asList(*Gson().fromJson(weatherJson, Array<WeatherItem>::class.java)) val item = weatherItems[0] as WeatherItem val value = item.date + " PM2.5 " + item.pm25 + " " + item.temperature + "°C " + item.humidity + "%" Logger.log(TAG, value) setData(weatherItems) mChart!!.invalidate() } return } try { val inputStream = assets.open("demo.json") val bufferedReader = BufferedReader(InputStreamReader(inputStream)) var line: String? = bufferedReader.readLine() val stringBuffer = StringBuffer() while (line != null) { stringBuffer.append(line + '\n') line = bufferedReader.readLine() } val gson = Gson() val weatherItems = gson.fromJson(stringBuffer.toString(), Array<WeatherItem>::class.java) val list = ArrayList<WeatherItem>() for (weatherItem in weatherItems) { list.add(weatherItem) } setData(list) mChart!!.invalidate() } catch (e: IOException) { e.printStackTrace() } } private fun initWeatherStatus() { if (null != disposable) { disposable!!.dispose() } val apiService = CarControllerApiService.instance val scheduler = Schedulers.from(Executors.newSingleThreadExecutor()) disposable = Observable.interval(0, 2, TimeUnit.SECONDS) .flatMap(object : Function<Long, ObservableSource<List<WeatherItem>>> { @Throws(Exception::class) override fun apply(t: Long): ObservableSource<List<WeatherItem>>? { return apiService.api.getWeatherItems(0, mSeekBarX!!.progress) } }) .doOnError { throwable -> log(throwable.toString()) } .retryWhen { throwablObservable -> throwablObservable.flatMap<Any> { Observable.timer(2, TimeUnit.SECONDS) } } .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(scheduler) .subscribe({ weatherItems -> val item = weatherItems[0] val value = item.date + "\nPM2.5 " + item.pm25 + " " + item.temperature + "°C " + item.humidity + "%" log(value) setData(weatherItems) mChart!!.invalidate() DataManager.realm.executeTransaction { realm -> realm.where(Settings::class.java).findFirst()!!.setWeatherJson(Gson().toJson(weatherItems)) } }) { throwable -> log(throwable.toString()) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.line, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.actionToggleValues -> { val sets = mChart!!.data .dataSets for (iSet in sets) { val set = iSet as LineDataSet set.setDrawValues(!set.isDrawValuesEnabled) } mChart!!.invalidate() } R.id.actionToggleHighlight -> { if (mChart!!.data != null) { mChart!!.data.isHighlightEnabled = !mChart!!.data.isHighlightEnabled mChart!!.invalidate() } } R.id.actionToggleFilled -> { val sets = mChart!!.data .dataSets for (iSet in sets) { val set = iSet as LineDataSet if (set.isDrawFilledEnabled) set.setDrawFilled(false) else set.setDrawFilled(true) } mChart!!.invalidate() } R.id.actionToggleCircles -> { val sets = mChart!!.data .dataSets for (iSet in sets) { val set = iSet as LineDataSet if (set.isDrawCirclesEnabled) set.setDrawCircles(false) else set.setDrawCircles(true) } mChart!!.invalidate() } R.id.actionToggleCubic -> { val sets = mChart!!.data .dataSets for (iSet in sets) { val set = iSet as LineDataSet if (set.mode == LineDataSet.Mode.CUBIC_BEZIER) set.mode = LineDataSet.Mode.LINEAR else set.mode = LineDataSet.Mode.CUBIC_BEZIER } mChart!!.invalidate() } R.id.actionToggleStepped -> { val sets = mChart!!.data .dataSets for (iSet in sets) { val set = iSet as LineDataSet if (set.mode == LineDataSet.Mode.STEPPED) set.mode = LineDataSet.Mode.LINEAR else set.mode = LineDataSet.Mode.STEPPED } mChart!!.invalidate() } R.id.actionTogglePinch -> { if (mChart!!.isPinchZoomEnabled) mChart!!.setPinchZoom(false) else mChart!!.setPinchZoom(true) mChart!!.invalidate() } R.id.actionToggleAutoScaleMinMax -> { mChart!!.isAutoScaleMinMaxEnabled = !mChart!!.isAutoScaleMinMaxEnabled mChart!!.notifyDataSetChanged() } R.id.animateX -> { mChart!!.animateX(3000) } R.id.animateY -> { mChart!!.animateY(3000) } R.id.animateXY -> { mChart!!.animateXY(3000, 3000) } R.id.actionSave -> { if (mChart!!.saveToPath("title" + System.currentTimeMillis(), "")) { Toast.makeText(applicationContext, "Saving SUCCESSFUL!", Toast.LENGTH_SHORT).show() } else Toast.makeText(applicationContext, "Saving FAILED!", Toast.LENGTH_SHORT) .show() }// mChart.saveToGallery("title"+System.currentTimeMillis()) } return true } override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { tvX!!.text = "" + mSeekBarX!!.progress initWeatherStatus() // redraw // mChart.invalidate(); } internal fun log(log: String) { Log.i(TAG, log) } private fun setData(weatherItemList: List<WeatherItem>) { // weatherItemList.sort(new Comparator<WeatherItem>() { // @Override // public int compare(WeatherItem o1, WeatherItem o2) { // return (int) (o1.getTimestamp()-o2.getTimestamp()); // } // }); Collections.sort(weatherItemList) { o1, o2 -> (o1.timestamp - o2.timestamp).toInt() } weatherItems = weatherItemList // now in hours val now = TimeUnit.MILLISECONDS.toHours(System.currentTimeMillis()) val values = ArrayList<Entry>() val values2 = ArrayList<Entry>() val values3 = ArrayList<Entry>() val from = now.toFloat() val count = weatherItemList.size val range = 30 // count = hours val to = (now + count).toFloat() // increment by 1 hour // for (float x = from; x < to; x++) { // // float y = getRandom(range, 50); // values.add(new Entry(x, y)); // add one entry per hour // } var i = 0 for (item in weatherItemList) { // values.add(new Entry(TimeUnit.MILLISECONDS.toMinutes(item.getTimestamp() / 1000), item.getPm25())); values.add(Entry(i.toFloat(), item.pm25.toFloat())) values2.add(Entry(i.toFloat(), item.temperature.toFloat())) values3.add(Entry(i.toFloat(), item.humidity.toFloat())) i++ } // create a dataset and give it a type val set1 = LineDataSet(values, "PM 2.5") set1.axisDependency = AxisDependency.LEFT set1.color = ColorTemplate.getHoloBlue() set1.valueTextColor = ColorTemplate.getHoloBlue() set1.lineWidth = 1.5f set1.setDrawCircles(false) set1.setDrawValues(false) set1.fillAlpha = 65 set1.fillColor = ColorTemplate.getHoloBlue() set1.highLightColor = Color.rgb(244, 117, 117) set1.setDrawCircleHole(false) colorPM25!!.setTextColor(ColorTemplate.getHoloBlue()) val set2 = LineDataSet(values2, "Temperature") set2.axisDependency = AxisDependency.LEFT set2.color = ColorTemplate.JOYFUL_COLORS[0] set2.valueTextColor = ColorTemplate.JOYFUL_COLORS[0] set2.lineWidth = 1.5f set2.setDrawCircles(false) set2.setDrawValues(false) set2.fillAlpha = 65 set2.fillColor = ColorTemplate.JOYFUL_COLORS[0] set2.highLightColor = Color.rgb(244, 117, 117) set2.setDrawCircleHole(false) colorTemp!!.setTextColor(ColorTemplate.JOYFUL_COLORS[0]) val set3 = LineDataSet(values3, "Humidity") set3.axisDependency = AxisDependency.LEFT set3.color = ColorTemplate.JOYFUL_COLORS[1] set3.valueTextColor = ColorTemplate.JOYFUL_COLORS[1] set3.lineWidth = 1.5f set3.setDrawCircles(false) set3.setDrawValues(false) set3.fillAlpha = 65 set3.fillColor = ColorTemplate.JOYFUL_COLORS[1] set3.highLightColor = Color.rgb(244, 117, 117) set3.setDrawCircleHole(false) colorHumidity!!.setTextColor(ColorTemplate.JOYFUL_COLORS[1]) // create a data object with the datasets val data = LineData(set1, set2, set3) data.setValueTextColor(ColorTemplate.JOYFUL_COLORS[2]) data.setValueTextSize(9f) // set data mChart!!.data = data } override fun onStartTrackingTouch(seekBar: SeekBar) { // TODO Auto-generated method stub } override fun onStopTrackingTouch(seekBar: SeekBar) { // TODO Auto-generated method stub } override fun onDestroy() { super.onDestroy() disposable!!.dispose() } companion object { private val TAG = "TemperatureChart" } }
apache-2.0
7c0d7e1685b83c63ae715f9736d78da9
34.530303
161
0.580785
4.591329
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/helpers/BottomNavigationBehavior.kt
1
6450
/* * ************************************************************************ * BottomNavigationBehavior.kt * ************************************************************************* * Copyright © 2020 VLC authors and VideoLAN * Author: Nicolas POMEPUY * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * ************************************************************************** * * */ package org.videolan.vlc.gui.helpers import android.animation.ValueAnimator import android.content.Context import android.util.AttributeSet import android.view.Gravity import android.view.View import android.view.animation.DecelerateInterpolator import android.widget.FrameLayout import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.view.ViewCompat import com.google.android.material.snackbar.Snackbar import org.videolan.vlc.R import kotlin.math.max import kotlin.math.min class BottomNavigationBehavior<V : View>(context: Context, attrs: AttributeSet) : CoordinatorLayout.Behavior<V>(context, attrs) { private val listeners = ArrayList<(translation: Float) -> Unit>() @ViewCompat.NestedScrollType private var lastStartedType: Int = 0 private var offsetAnimator: ValueAnimator? = null private var isSnappingEnabled = true var isPlayerHidden = false private var player: FrameLayout? = null override fun onNestedPreScroll(coordinatorLayout: CoordinatorLayout, child: V, target: View, dx: Int, dy: Int, consumed: IntArray, type: Int) { super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type) child.translationY = max(0f, min(child.height.toFloat(), child.translationY + dy)) listeners.forEach { it(child.translationY) } player?.let { updatePlayer(child, it) } } override fun layoutDependsOn(parent: CoordinatorLayout, child: V, dependency: View): Boolean { if (dependency is Snackbar.SnackbarLayout) { updateSnackbar(child, dependency) } if (dependency is FrameLayout && dependency.id == R.id.audio_player_container) { player = dependency updatePlayer(child, dependency) } return super.layoutDependsOn(parent, child, dependency) } override fun onStartNestedScroll( coordinatorLayout: CoordinatorLayout, child: V, directTargetChild: View, target: View, axes: Int, type: Int ): Boolean { if (isPlayerHidden) return false if (axes != ViewCompat.SCROLL_AXIS_VERTICAL) return false lastStartedType = type offsetAnimator?.cancel() return true } override fun onStopNestedScroll(coordinatorLayout: CoordinatorLayout, child: V, target: View, type: Int) { if (!isSnappingEnabled) return // add snap behaviour // Logic here borrowed from AppBarLayout onStopNestedScroll code if (lastStartedType == ViewCompat.TYPE_TOUCH || type == ViewCompat.TYPE_NON_TOUCH) { // find nearest seam val currTranslation = child.translationY val childHalfHeight = child.height * 0.5f // translate down if (currTranslation >= childHalfHeight) { animateBarVisibility(child, isVisible = false) } // translate up else { animateBarVisibility(child, isVisible = true) } } } fun addScrollListener(listener: (translation: Float) -> Unit) { listeners.add(listener) } private fun updateSnackbar(child: View, snackbarLayout: Snackbar.SnackbarLayout) { if (snackbarLayout.layoutParams is CoordinatorLayout.LayoutParams) { val params = snackbarLayout.layoutParams as CoordinatorLayout.LayoutParams params.anchorId = child.id params.anchorGravity = Gravity.TOP params.gravity = Gravity.TOP snackbarLayout.layoutParams = params } } private fun updatePlayer(child: View, player: FrameLayout) { if (player.layoutParams is CoordinatorLayout.LayoutParams) { val params = player.layoutParams as CoordinatorLayout.LayoutParams val playerBehavior = params.behavior as PlayerBehavior<*> playerBehavior.peekHeight = child.context.resources.getDimensionPixelSize(R.dimen.player_peek_height) + child.height - child.translationY.toInt() } } fun animateBarVisibility(child: View, isVisible: Boolean) { val targetTranslation = if (isVisible) 0f else child.height.toFloat() if (child.translationY == targetTranslation) return if (offsetAnimator == null) { offsetAnimator = ValueAnimator().apply { interpolator = DecelerateInterpolator() duration = 150L } offsetAnimator?.addUpdateListener { child.translationY = it.animatedValue as Float listeners.forEach { listener -> listener(it.animatedValue as Float) } player?.let { updatePlayer(child, it) } } } else { offsetAnimator?.cancel() } offsetAnimator?.setFloatValues(child.translationY, targetTranslation) offsetAnimator?.start() } companion object { fun <V : View> from(view: V): BottomNavigationBehavior<V>? { val params = view.layoutParams require(params is CoordinatorLayout.LayoutParams) { "The view is not a child of CoordinatorLayout" } val behavior = params.behavior require(behavior is BottomNavigationBehavior<*>) { "The view is not associated with BottomNavigationBehavior" } return behavior as BottomNavigationBehavior<V>? } } }
gpl-2.0
01f6b462ff5c79e4e120bfd72b8d7363
39.566038
157
0.651419
5.085962
false
false
false
false
natanieljr/droidmate
project/pcComponents/core/src/test/kotlin/org/droidmate/test_tools/ApkFixtures.kt
1
2473
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2018. Saarland University // // 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/>. // // Current Maintainers: // Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland> // Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland> // // Former Maintainers: // Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de> // // web: www.droidmate.org /*package org.droidmate.test_tools import org.droidmate.device.android_sdk.AaptWrapper import org.droidmate.device.android_sdk.Apk import org.droidmate.device.android_sdk.IAaptWrapper import org.droidmate.configuration.ConfigurationWrapper import org.droidmate.legacy.Resource import org.droidmate.misc.EnvironmentConstants import org.droidmate.misc.SysCmdExecutor import org.droidmate.misc.text import java.nio.file.Path import java.nio.file.Paths class ApkFixtures(aapt: IAaptWrapper) { companion object { @JvmStatic val apkFixture_simple_packageName = "org.droidmate.fixtures.apks.simple" @JvmStatic fun build(): ApkFixtures = ApkFixtures(AaptWrapper(ConfigurationWrapper.getDefault(), SysCmdExecutor())) } val gui: Apk val monitoredInlined_api23: Apk val Resource.extractedPath: Path get() { val resDir = Paths.get("out",EnvironmentConstants.dir_name_temp_extracted_resources) return this.extractTo(resDir).toAbsolutePath() } val Resource.extractedPathString: String get() { return this.extractedPath.toString() } val Resource.extractedText: String get() { return extractedPath.text } initialize { gui = Apk.fromFile(Resource("${EnvironmentConstants.apk_fixtures}/GuiApkFixture-debug.apk").extractedPath) monitoredInlined_api23 = Apk.fromFile(Resource("${EnvironmentConstants.apk_fixtures}/${EnvironmentConstants.monitored_inlined_apk_fixture_api23_name}").extractedPath) } }*/
gpl-3.0
3e247c05946dab5566ba4caa63062d2c
33.361111
168
0.770724
3.852025
false
false
false
false
gpolitis/jitsi-videobridge
jvb/src/main/kotlin/org/jitsi/videobridge/transport/octo/BridgeOctoTransport.kt
1
13156
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge.transport.octo import org.jitsi.nlj.PacketHandler import org.jitsi.rtp.Packet import org.jitsi.rtp.UnparsedPacket import org.jitsi.rtp.rtp.RtpPacket import org.jitsi.utils.MediaType import org.jitsi.utils.OrderedJsonObject import org.jitsi.utils.logging2.Logger import org.jitsi.utils.logging2.cdebug import org.jitsi.utils.logging2.createChildLogger import org.jitsi.videobridge.octo.OctoPacket import org.jitsi.videobridge.octo.OctoPacket.OCTO_HEADER_LENGTH import org.jitsi.videobridge.octo.OctoPacketInfo import org.jitsi.videobridge.transport.octo.OctoUtils.Companion.JVB_EP_ID import org.jitsi.videobridge.util.ByteBufferPool import java.net.SocketAddress import java.nio.charset.StandardCharsets import java.time.Instant import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicLong import java.util.concurrent.atomic.LongAdder import kotlin.math.floor import kotlin.math.log10 /** * [BridgeOctoTransport] handles *all* incoming and outgoing Octo traffic for a * given bridge. * * [relayId] is the Octo relay ID which will be advertised by this JVB. * Other bridges can use this ID in order to discover the socket address that * this bridge is accessible on. With the current implementation the ID just * encodes a pre-configured IP address and port, e.g. "10.0.0.1:20000" */ class BridgeOctoTransport( val relayId: String, parentLogger: Logger ) { private val logger = createChildLogger(parentLogger, mapOf("relayId" to relayId)) private val stats = Stats(logger) /** * Handlers for incoming Octo packets. Packets will be routed to a handler based on the conference * ID in the Octo packet. */ private val incomingPacketHandlers: MutableMap<Long, IncomingOctoPacketHandler> = ConcurrentHashMap() /** * Maps how many Octo packets have been received for unknown conference IDs, to avoid * spamming the error logs */ private val unknownConferences: MutableMap<Long, AtomicLong> = ConcurrentHashMap() /** * The handler which will be invoked when this [BridgeOctoTransport] wants to * send data. */ var outgoingDataHandler: OutgoingOctoPacketHandler? = null init { logger.info("Created OctoTransport") } /** * Registers a [PacketHandler] for the given [conferenceId] */ fun addHandler(conferenceId: Long, handler: IncomingOctoPacketHandler) { if (conferenceId < 0 || conferenceId > 0xffff_ffff) { throw IllegalArgumentException("Invalid conference ID: $conferenceId") } logger.info("Adding handler for conference $conferenceId") synchronized(incomingPacketHandlers) { incomingPacketHandlers.put(conferenceId, handler)?.let { logger.warn("Replacing an existing packet handler for gid=$conferenceId") } unknownConferences.remove(conferenceId) } } /** * Removes the [PacketHandler] for the given [conferenceId] IFF the one * in the map is the same as [handler]. */ fun removeHandler(conferenceId: Long, handler: IncomingOctoPacketHandler) = synchronized(incomingPacketHandlers) { // If the Colibri conference for this GID was re-created, and the // original Conference object is expired after a new packet handler // was registered, the new packet handler should not be removed (as // this would break the new conference). incomingPacketHandlers[conferenceId]?.let { if (it == handler) { logger.info("Removing handler for conference $conferenceId") incomingPacketHandlers.remove(conferenceId) } else { logger.info( "Tried to remove handler for conference $conferenceId but it wasn't the currently " + "active one" ) } } } fun stop() { } @Suppress("DEPRECATION") fun dataReceived(buf: ByteArray, off: Int, len: Int, receivedTime: Instant) { var conferenceId: Long var mediaType: MediaType var sourceEpId: String try { conferenceId = OctoPacket.readConferenceId(buf, off, len) mediaType = OctoPacket.readMediaType(buf, off, len) sourceEpId = OctoPacket.readEndpointId(buf, off, len) } catch (iae: IllegalArgumentException) { logger.warn("Invalid Octo packet, len=$len", iae) stats.invalidPacketReceived() return } val handler = incomingPacketHandlers[conferenceId] ?: run { stats.noHandlerFound() unknownConferences[conferenceId]?.let { unknownConfEventAdder -> val value = unknownConfEventAdder.incrementAndGet() // Only print log on exact powers of 10 packets received val logValue = log10(value.toFloat()) if (logValue > 0 && logValue == floor(logValue)) { logger.warn("Received $value Octo packets for unknown conference $conferenceId") } } ?: run { /* Potentially a race here if more than one packet arrives at once * for the same unknown conference? This will just result in a few * duplicate logs, though, so not a big deal. */ unknownConferences[conferenceId] = AtomicLong(1) logger.warn("Received an Octo packet for an unknown conference: $conferenceId") } return } when (mediaType) { MediaType.AUDIO, MediaType.VIDEO -> { handler.handleMediaPacket(createPacketInfo(sourceEpId, buf, off, len, receivedTime)) } MediaType.DATA -> { handler.handleMessagePacket(createMessageString(buf, off, len), sourceEpId) } else -> { logger.warn("Unsupported media type $mediaType") stats.invalidPacketReceived() } } } fun sendMediaData( buf: ByteArray, off: Int, len: Int, targets: Collection<SocketAddress>, confId: Long, sourceEpId: String? = null ) { sendData(buf, off, len, targets, confId, MediaType.VIDEO, sourceEpId) } @Suppress("DEPRECATION") fun sendString(msg: String, targets: Collection<SocketAddress>, confId: Long) { val msgData = msg.toByteArray(StandardCharsets.UTF_8) sendData(msgData, 0, msgData.size, targets, confId, MediaType.DATA, null) } private fun sendData( buf: ByteArray, off: Int, len: Int, targets: Collection<SocketAddress>, confId: Long, mediaType: MediaType, sourceEpId: String? = null ) { val octoPacketLength = len + OCTO_HEADER_LENGTH // Not all packets originate from an endpoint (e.g. some come from the bridge) val epId = sourceEpId ?: JVB_EP_ID val (newBuf, newOff) = when { off >= OCTO_HEADER_LENGTH -> { // We can fit the Octo header into the room left at the beginning of the packet Pair(buf, off - OCTO_HEADER_LENGTH) } buf.size >= octoPacketLength -> { // The buffer is big enough to hold the Octo header as well, but we // need to shift it System.arraycopy(buf, off, buf, OCTO_HEADER_LENGTH, len) Pair(buf, 0) } else -> { // The buffer isn't big enough, we need a new one val newBuf = ByteBufferPool.getBuffer(octoPacketLength).apply { System.arraycopy(buf, off, this, OCTO_HEADER_LENGTH, len) } Pair(newBuf, 0) } } OctoPacket.writeHeaders( newBuf, newOff, mediaType, confId, epId ) if (octoPacketLength > 1500) { stats.largePacketSent(mediaType) } outgoingDataHandler?.sendData(newBuf, newOff, octoPacketLength, targets) ?: stats.noOutgoingHandler() } fun getStatsJson(): OrderedJsonObject = OrderedJsonObject().apply { put("relay_id", relayId) putAll(getStats().toJson()) } fun getStats(): StatsSnapshot = stats.toSnapshot() private fun createPacketInfo( sourceEpId: String, buf: ByteArray, off: Int, len: Int, receivedTime: Instant ): OctoPacketInfo { val rtpLen = len - OCTO_HEADER_LENGTH val bufCopy = ByteBufferPool.getBuffer( rtpLen + RtpPacket.BYTES_TO_LEAVE_AT_START_OF_PACKET + Packet.BYTES_TO_LEAVE_AT_END_OF_PACKET ).apply { System.arraycopy( buf, off + OCTO_HEADER_LENGTH, this, RtpPacket.BYTES_TO_LEAVE_AT_START_OF_PACKET, rtpLen ) } return OctoPacketInfo(UnparsedPacket(bufCopy, RtpPacket.BYTES_TO_LEAVE_AT_START_OF_PACKET, rtpLen)).apply { this.endpointId = sourceEpId this.receivedTime = receivedTime.toEpochMilli() } } private fun createMessageString(buf: ByteArray, off: Int, len: Int): String { return String( buf, off + OCTO_HEADER_LENGTH, len - OCTO_HEADER_LENGTH ).also { logger.cdebug { "Received a message in an Octo data packet: $it" } } } private class Stats(val logger: Logger) { private val numInvalidPackets = LongAdder() private val numIncomingDroppedNoHandler = LongAdder() private val numOutgoingDroppedNoHandler = LongAdder() private val largePacketsSent = HashMap<MediaType, AtomicLong>() fun invalidPacketReceived() { numInvalidPackets.increment() } fun noHandlerFound() { numIncomingDroppedNoHandler.increment() } fun noOutgoingHandler() { numOutgoingDroppedNoHandler.increment() } fun largePacketSent(mediaType: MediaType) { val value = largePacketsSent.computeIfAbsent(mediaType) { AtomicLong() }.incrementAndGet() if (value == 1L || value % 1000 == 0L) { logger.warn("Sent $value large (>1500B) packets with type $mediaType") } } fun toSnapshot(): StatsSnapshot = StatsSnapshot( numInvalidPackets = numInvalidPackets.sum(), numIncomingDroppedNoHandler = numIncomingDroppedNoHandler.sum(), numOutgoingDroppedNoHandler = numOutgoingDroppedNoHandler.sum(), numLargeAudioPacketsSent = largePacketsSent[MediaType.AUDIO]?.get() ?: 0, numLargeVideoPacketsSent = largePacketsSent[MediaType.VIDEO]?.get() ?: 0, numLargeDataPacketsSent = largePacketsSent[MediaType.DATA]?.get() ?: 0 ) } class StatsSnapshot( val numInvalidPackets: Long, val numIncomingDroppedNoHandler: Long, val numOutgoingDroppedNoHandler: Long, val numLargeAudioPacketsSent: Long, val numLargeVideoPacketsSent: Long, val numLargeDataPacketsSent: Long ) { fun toJson(): OrderedJsonObject = OrderedJsonObject().apply { put("num_invalid_packets_rx", numInvalidPackets) put("num_incoming_packets_dropped_no_handler", numIncomingDroppedNoHandler) put("num_outgoing_packets_dropped_no_handler", numOutgoingDroppedNoHandler) put("num_large_audio_packets_sent", numLargeAudioPacketsSent) put("num_large_video_packets_sent", numLargeVideoPacketsSent) put("num_large_data_packets_sent", numLargeDataPacketsSent) } } /** * Handler for when Octo packets are received */ interface IncomingOctoPacketHandler { /** * Notify that an Octo media packet has been received. The handler * *does* own the packet buffer inside the [OctoPacketInfo] */ fun handleMediaPacket(packetInfo: OctoPacketInfo) /** * Notify that a message packet has been received from remote endpoint * [sourceEpId] */ fun handleMessagePacket(message: String, sourceEpId: String) } interface OutgoingOctoPacketHandler { fun sendData(data: ByteArray, off: Int, length: Int, remoteAddresses: Collection<SocketAddress>) } }
apache-2.0
41a5fb228c96d35a7482b4f3817073ad
36.913545
118
0.631271
4.58078
false
false
false
false
d3xter/bo-android
app/src/main/java/org/blitzortung/android/app/view/LegendView.kt
1
7522
/* Copyright 2015 Andreas Würl 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.blitzortung.android.app.view import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.util.AttributeSet import android.view.View import org.blitzortung.android.app.R import org.blitzortung.android.map.overlay.StrikesOverlay import org.blitzortung.android.util.TabletAwareView class LegendView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : TabletAwareView(context, attrs, defStyle) { private val colorFieldSize: Float private val textPaint: Paint private val rasterTextPaint: Paint private val regionTextPaint: Paint private val countThresholdTextPaint: Paint private val backgroundPaint: Paint private val foregroundPaint: Paint private val backgroundRect: RectF private val legendColorRect: RectF var strikesOverlay: StrikesOverlay? = null init { colorFieldSize = textSize foregroundPaint = Paint(Paint.ANTI_ALIAS_FLAG) backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = context.resources.getColor(R.color.translucent_background) } backgroundRect = RectF() legendColorRect = RectF() textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = -1 textSize = [email protected] } rasterTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = -1 textSize = [email protected] * RASTER_HEIGHT textAlign = Paint.Align.CENTER } regionTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = -1 textSize = [email protected] * REGION_HEIGHT textAlign = Paint.Align.CENTER } countThresholdTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = -1 textSize = [email protected] * COUNT_THRESHOLD_HEIGHT textAlign = Paint.Align.CENTER } setBackgroundColor(Color.TRANSPARENT) } private fun determineWidth(intervalDuration: Int): Float { var innerWidth = colorFieldSize + padding + textPaint.measureText(if (intervalDuration > 100) "< 100min" else "< 10min").toFloat() if (hasRegion()) { innerWidth = Math.max(innerWidth, regionTextPaint.measureText(regionName).toFloat()) } return padding + innerWidth + padding } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val getSize = fun (spec: Int) = View.MeasureSpec.getSize(spec) val parentWidth = getSize(widthMeasureSpec) val parentHeight = getSize(heightMeasureSpec) val width = Math.min(determineWidth(strikesOverlay?.parameters?.intervalDuration ?: 0), parentWidth.toFloat()) val colorHandler = strikesOverlay?.getColorHandler() var height = 0.0f; if (colorHandler != null) { height = Math.min((colorFieldSize + padding) * colorHandler.colors.size + padding, parentHeight.toFloat()) if (hasRegion()) { height += colorFieldSize * REGION_HEIGHT + padding } if (hasRaster()) { height += colorFieldSize * RASTER_HEIGHT + padding if (hasCountThreshold()) { height += colorFieldSize * COUNT_THRESHOLD_HEIGHT + padding } } } super.onMeasure(View.MeasureSpec.makeMeasureSpec(width.toInt(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(height.toInt(), View.MeasureSpec.EXACTLY)) } override fun onDraw(canvas: Canvas) { strikesOverlay?.let { strikesOverlay -> val colorHandler = strikesOverlay.getColorHandler() val minutesPerColor = strikesOverlay.parameters.intervalDuration / colorHandler.numberOfColors backgroundRect.set(0f, 0f, width.toFloat(), height.toFloat()) canvas.drawRect(backgroundRect, backgroundPaint) val numberOfColors = colorHandler.numberOfColors var topCoordinate = padding for (index in 0..numberOfColors - 1) { foregroundPaint.color = colorHandler.getColor(index) legendColorRect.set(padding, topCoordinate, padding + colorFieldSize, topCoordinate + colorFieldSize) canvas.drawRect(legendColorRect, foregroundPaint) val isLastValue = index == numberOfColors - 1 val text = "%c %dmin".format(if (isLastValue) '>' else '<', (index + (if (isLastValue) 0 else 1)) * minutesPerColor) canvas.drawText(text, 2 * padding + colorFieldSize, topCoordinate + colorFieldSize / 1.1f, textPaint) topCoordinate += colorFieldSize + padding } if (hasRegion()) { canvas.drawText(regionName, width / 2.0f, topCoordinate + colorFieldSize * REGION_HEIGHT / 1.1f, regionTextPaint) topCoordinate += colorFieldSize * REGION_HEIGHT + padding } if (hasRaster()) { canvas.drawText("Raster: " + rasterString, width / 2.0f, topCoordinate + colorFieldSize * RASTER_HEIGHT / 1.1f, rasterTextPaint) topCoordinate += colorFieldSize * RASTER_HEIGHT + padding if (hasCountThreshold()) { val countThreshold = strikesOverlay.parameters.countThreshold canvas.drawText("# > " + countThreshold, width / 2.0f, topCoordinate + colorFieldSize * COUNT_THRESHOLD_HEIGHT / 1.1f, countThresholdTextPaint) topCoordinate += colorFieldSize * COUNT_THRESHOLD_HEIGHT + padding } } } } private val regionName: String get() { val regionNumber = strikesOverlay!!.parameters.region var index = 0 for (region_number in resources.getStringArray(R.array.regions_values)) { if (regionNumber == Integer.parseInt(region_number)) { return resources.getStringArray(R.array.regions)[index] } index++ } return "n/a" } fun setAlpha(alpha: Int) { foregroundPaint.alpha = alpha } private fun hasRaster(): Boolean { return strikesOverlay?.hasRasterParameters() ?: false } private fun hasRegion(): Boolean { return strikesOverlay?.parameters?.region ?: 0 != 0 } val rasterString: String get() = strikesOverlay?.rasterParameters?.info ?: "n/a" private fun hasCountThreshold(): Boolean { return strikesOverlay?.parameters?.countThreshold ?: 0 > 0 } companion object { val REGION_HEIGHT = 1.1f val RASTER_HEIGHT = 0.8f val COUNT_THRESHOLD_HEIGHT = 0.8f } }
apache-2.0
656425bc19596463cec515c7b6633339
35.158654
174
0.63941
4.727216
false
false
false
false
olonho/carkot
car_fmw/src/include/DebugInfo.kt
1
1021
external fun dynamic_heap_tail(): Int external fun static_heap_tail(): Int external fun dynamic_heap_max_bytes(): Int external fun dynamic_heap_total(): Int object DebugInfo { fun getDynamicHeapTail(): Int = dynamic_heap_tail() fun getStaticHeapTail(): Int = static_heap_tail() fun getDynamicHeapMaxSize(): Int = dynamic_heap_max_bytes() fun getDynamicHeapTotalBytes(): Int = dynamic_heap_total() } external fun car_sonar_get_measurement_total(): Int external fun car_sonar_get_measurement_failed_checksum(): Int external fun car_sonar_get_measurement_failed_distance(): Int external fun car_sonar_get_measurement_failed_command(): Int object DebugSonarInfo { fun getMeasurementCount(): Int = car_sonar_get_measurement_total() fun getMeasurementFailedChecksum(): Int = car_sonar_get_measurement_failed_checksum() fun getMeasurementFailedDistance(): Int = car_sonar_get_measurement_failed_distance() fun getMeasurementFailedCommand(): Int = car_sonar_get_measurement_failed_command() }
mit
42de264cac9e1858ce6cd8c51df7d26d
41.541667
89
0.757101
3.838346
false
false
false
false