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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/updates/UpdatesState.kt | 1 | 1951 | package eu.kanade.presentation.updates
import androidx.compose.runtime.Stable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import eu.kanade.core.util.insertSeparators
import eu.kanade.tachiyomi.ui.recent.updates.UpdatesItem
import eu.kanade.tachiyomi.ui.recent.updates.UpdatesPresenter
import eu.kanade.tachiyomi.util.lang.toDateKey
import java.util.Date
@Stable
interface UpdatesState {
val isLoading: Boolean
val items: List<UpdatesItem>
val selected: List<UpdatesItem>
val selectionMode: Boolean
val uiModels: List<UpdatesUiModel>
var dialog: UpdatesPresenter.Dialog?
}
fun UpdatesState(): UpdatesState = UpdatesStateImpl()
class UpdatesStateImpl : UpdatesState {
override var isLoading: Boolean by mutableStateOf(true)
override var items: List<UpdatesItem> by mutableStateOf(emptyList())
override val selected: List<UpdatesItem> by derivedStateOf {
items.filter { it.selected }
}
override val selectionMode: Boolean by derivedStateOf { selected.isNotEmpty() }
override val uiModels: List<UpdatesUiModel> by derivedStateOf {
items.toUpdateUiModel()
}
override var dialog: UpdatesPresenter.Dialog? by mutableStateOf(null)
}
fun List<UpdatesItem>.toUpdateUiModel(): List<UpdatesUiModel> {
return this.map {
UpdatesUiModel.Item(it)
}
.insertSeparators { before, after ->
val beforeDate = before?.item?.update?.dateFetch?.toDateKey() ?: Date(0)
val afterDate = after?.item?.update?.dateFetch?.toDateKey() ?: Date(0)
when {
beforeDate.time != afterDate.time && afterDate.time != 0L ->
UpdatesUiModel.Header(afterDate)
// Return null to avoid adding a separator between two items.
else -> null
}
}
}
| apache-2.0 | 0d370e89623c4ca84a355b0f6a42ed67 | 37.254902 | 84 | 0.71348 | 4.434091 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt | 1 | 2933 | package info.nightscout.androidaps.plugins.general.smsCommunicator
import android.os.SystemClock
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.CommandQueue
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePassword
import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePasswordValidationResult
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.interfaces.ResourceHelper
import javax.inject.Inject
class AuthRequest internal constructor(
injector: HasAndroidInjector,
var requester: Sms,
requestText: String,
var confirmCode: String,
val action: SmsAction) {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin
@Inject lateinit var rh: ResourceHelper
@Inject lateinit var otp: OneTimePassword
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var commandQueue: CommandQueue
private var date = 0L
private var processed = false
init {
injector.androidInjector().inject(this)
date = dateUtil.now()
smsCommunicatorPlugin.sendSMS(Sms(requester.phoneNumber, requestText))
}
private fun codeIsValid(toValidate: String): Boolean =
otp.checkOTP(toValidate) == OneTimePasswordValidationResult.OK
fun action(codeReceived: String) {
if (processed) {
aapsLogger.debug(LTag.SMS, "Already processed")
return
}
if (!codeIsValid(codeReceived)) {
processed = true
aapsLogger.debug(LTag.SMS, "Wrong code")
smsCommunicatorPlugin.sendSMS(Sms(requester.phoneNumber, rh.gs(R.string.sms_wrongcode)))
return
}
if (dateUtil.now() - date < Constants.SMS_CONFIRM_TIMEOUT) {
processed = true
if (action.pumpCommand) {
val start = dateUtil.now()
//wait for empty queue
while (start + T.mins(3).msecs() > dateUtil.now()) {
if (commandQueue.size() == 0) break
SystemClock.sleep(100)
}
if (commandQueue.size() != 0) {
aapsLogger.debug(LTag.SMS, "Command timed out: " + requester.text)
smsCommunicatorPlugin.sendSMS(Sms(requester.phoneNumber, rh.gs(R.string.sms_timeout_while_wating)))
return
}
}
aapsLogger.debug(LTag.SMS, "Processing confirmed SMS: " + requester.text)
action.run()
return
}
aapsLogger.debug(LTag.SMS, "Timed out SMS: " + requester.text)
}
} | agpl-3.0 | 349d21527029b040ab1790665c4c3d56 | 38.12 | 119 | 0.669962 | 4.700321 | false | false | false | false |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/entities/Bolus.kt | 1 | 2391 | package info.nightscout.androidaps.database.entities
import androidx.room.Embedded
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import info.nightscout.androidaps.database.TABLE_BOLUSES
import info.nightscout.androidaps.database.embedments.InsulinConfiguration
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.interfaces.DBEntryWithTime
import info.nightscout.androidaps.database.interfaces.TraceableDBEntry
import java.util.*
@Entity(
tableName = TABLE_BOLUSES,
foreignKeys = [
ForeignKey(
entity = Bolus::class,
parentColumns = ["id"],
childColumns = ["referenceId"]
)],
indices = [
Index("id"),
Index("isValid"),
Index("temporaryId"),
Index("pumpId"),
Index("pumpSerial"),
Index("pumpType"),
Index("referenceId"),
Index("timestamp")
]
)
data class Bolus(
@PrimaryKey(autoGenerate = true)
override var id: Long = 0,
override var version: Int = 0,
override var dateCreated: Long = -1,
override var isValid: Boolean = true,
override var referenceId: Long? = null,
@Embedded
override var interfaceIDs_backing: InterfaceIDs? = null,
override var timestamp: Long,
override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(),
var amount: Double,
var type: Type,
var isBasalInsulin: Boolean = false,
@Embedded
var insulinConfiguration: InsulinConfiguration? = null
) : TraceableDBEntry, DBEntryWithTime {
private fun contentEqualsTo(other: Bolus): Boolean =
isValid == other.isValid &&
timestamp == other.timestamp &&
utcOffset == other.utcOffset &&
amount == other.amount &&
type == other.type &&
isBasalInsulin == other.isBasalInsulin
fun onlyNsIdAdded(previous: Bolus): Boolean =
previous.id != id &&
contentEqualsTo(previous) &&
previous.interfaceIDs.nightscoutId == null &&
interfaceIDs.nightscoutId != null
enum class Type {
NORMAL,
SMB,
PRIMING;
companion object {
fun fromString(name: String?) = values().firstOrNull { it.name == name } ?: NORMAL
}
}
} | agpl-3.0 | 478a0a920bbd6a57e4f1b09b93e00e79 | 30.473684 | 94 | 0.65412 | 4.715976 | false | false | false | false |
Adventech/sabbath-school-android-2 | common/design-compose/src/main/kotlin/app/ss/design/compose/widget/icon/IconButton.kt | 1 | 4124 | /*
* Copyright (c) 2022. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package app.ss.design.compose.widget.icon
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalContentColor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import app.ss.design.compose.extensions.internal.minimumTouchTargetSize
/**
* An IconButton [IconSlot]
*/
@Immutable
data class IconButton(
val imageVector: ImageVector,
val contentDescription: String,
val onClick: () -> Unit,
val enabled: Boolean = true,
val tint: Color? = null
) : IconSlot {
@Composable
override fun Content(contentColor: Color, modifier: Modifier) {
IconButton(
onClick = onClick,
enabled = enabled,
modifier = Modifier.wrapContentSize()
) {
Icon(
imageVector = imageVector,
contentDescription = contentDescription,
tint = tint ?: contentColor,
modifier = modifier
)
}
}
}
/**
* An [androidx.compose.material3.IconButton] with a customizable [stateLayerSize].
*/
@Composable
fun IconButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
colors: SsIconButtonColors = SsIconButtonColorsDefaults.iconButtonColors(),
stateLayerSize: Dp = StateLayerSize,
content: @Composable () -> Unit
) {
Box(
modifier = modifier
.minimumTouchTargetSize()
.size(stateLayerSize)
.background(color = colors.containerColor(enabled).value)
.clickable(
onClick = onClick,
enabled = enabled,
role = Role.Button,
interactionSource = interactionSource,
indication = rememberRipple(
bounded = false,
radius = stateLayerSize / 2
)
),
contentAlignment = Alignment.Center
) {
val contentColor = colors.contentColor(enabled).value
CompositionLocalProvider(LocalContentColor provides contentColor, content = content)
}
}
private val StateLayerSize = 40.0.dp
| mit | 3ce0837aca3d2f12b98b9522d370e09a | 36.153153 | 92 | 0.709263 | 4.880473 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/base/fir/analysis-api-providers/test/org/jetbrains/kotlin/idea/fir/analysis/providers/sessions/AbstractSessionsInvalidationTest.kt | 2 | 5436 | // 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.fir.analysis.providers.sessions
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.testFramework.PsiTestUtil
import junit.framework.Assert
import org.jetbrains.kotlin.analysis.low.level.api.fir.sessions.LLFirModuleSession
import org.jetbrains.kotlin.analysis.low.level.api.fir.sessions.LLFirSession
import org.jetbrains.kotlin.analysis.low.level.api.fir.sessions.LLFirSessionProviderStorage
import org.jetbrains.kotlin.analysis.project.structure.KtSourceModule
import org.jetbrains.kotlin.idea.base.projectStructure.getMainKtSourceModule
import org.jetbrains.kotlin.idea.fir.analysis.providers.TestProjectModule
import org.jetbrains.kotlin.idea.fir.analysis.providers.TestProjectStructure
import org.jetbrains.kotlin.idea.fir.analysis.providers.TestProjectStructureReader
import org.jetbrains.kotlin.idea.fir.analysis.providers.incModificationTracker
import org.jetbrains.kotlin.idea.jsonUtils.getString
import org.jetbrains.kotlin.idea.stubs.AbstractMultiModuleTest
import org.jetbrains.kotlin.test.KotlinRoot
import java.io.File
import java.nio.file.Paths
abstract class AbstractSessionsInvalidationTest : AbstractMultiModuleTest() {
override fun getTestDataDirectory(): File =
KotlinRoot.DIR.resolve("fir-low-level-api-ide-impl").resolve("testData").resolve("sessionInvalidation")
protected fun doTest(path: String) {
val testStructure = TestProjectStructureReader.readToTestStructure(
Paths.get(path),
toTestStructure = MultiModuleTestProjectStructure.Companion::fromTestProjectStructure
)
val modulesByNames = testStructure.modules.associate { moduleData ->
moduleData.name to createEmptyModule(moduleData.name)
}
testStructure.modules.forEach { moduleData ->
val module = modulesByNames.getValue(moduleData.name)
moduleData.dependsOnModules.forEach { dependencyName ->
module.addDependency(modulesByNames.getValue(dependencyName))
}
}
val rootModule = modulesByNames[testStructure.rootModule]
?: error("${testStructure.rootModule} is not present in the list of modules")
val modulesToMakeOOBM = testStructure.modulesToMakeOOBM.map {
modulesByNames[it]
?: error("$it is not present in the list of modules")
}
val rootModuleSourceInfo = rootModule.getMainKtSourceModule()!!
val storage = LLFirSessionProviderStorage(project)
val initialSessions = storage.getFirSessions(rootModuleSourceInfo)
modulesToMakeOOBM.forEach { it.incModificationTracker() }
val sessionsAfterOOBM = storage.getFirSessions(rootModuleSourceInfo)
val intersection = com.intellij.util.containers.ContainerUtil.intersection(initialSessions, sessionsAfterOOBM)
val changedSessions = HashSet(initialSessions)
changedSessions.addAll(sessionsAfterOOBM)
changedSessions.removeAll(intersection)
val changedSessionsModulesNamesSorted = changedSessions
.map { session ->
val moduleSession = session as LLFirModuleSession
val module = moduleSession.module as KtSourceModule
module.moduleName
}
.distinct()
.sorted()
Assert.assertEquals(testStructure.expectedInvalidatedModules, changedSessionsModulesNamesSorted)
}
private fun LLFirSessionProviderStorage.getFirSessions(module: KtSourceModule): Set<LLFirSession> {
val sessionProvider = getSessionProvider(module)
return sessionProvider.allSessions.toSet()
}
private fun createEmptyModule(name: String): Module {
val tmpDir = createTempDirectory().toPath()
val module: Module = createModule("$tmpDir/$name", moduleType)
val root = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tmpDir.toFile())!!
WriteCommandAction.writeCommandAction(module.project).run<RuntimeException> {
root.refresh(false, true)
}
PsiTestUtil.addSourceContentToRoots(module, root)
return module
}
}
private data class MultiModuleTestProjectStructure(
val modules: List<TestProjectModule>,
val rootModule: String,
val modulesToMakeOOBM: List<String>,
val expectedInvalidatedModules: List<String>,
) {
companion object {
fun fromTestProjectStructure(testProjectStructure: TestProjectStructure): MultiModuleTestProjectStructure {
val json = testProjectStructure.json
return MultiModuleTestProjectStructure(
testProjectStructure.modules,
json.getString(ROOT_MODULE_FIELD),
json.getAsJsonArray(MODULES_TO_MAKE_OOBM_IN_FIELD).map { it.asString }.sorted(),
json.getAsJsonArray(EXPECTED_INVALIDATED_MODULES_FIELD).map { it.asString }.sorted(),
)
}
private const val ROOT_MODULE_FIELD = "rootModule"
private const val MODULES_TO_MAKE_OOBM_IN_FIELD = "modulesToMakeOOBM"
private const val EXPECTED_INVALIDATED_MODULES_FIELD = "expectedInvalidatedModules"
}
} | apache-2.0 | 72695945c3e3b4f73c5217f8413fc468 | 46.278261 | 158 | 0.734547 | 4.884097 | false | true | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/util/SnackbarItem.kt | 1 | 2222 | package org.wordpress.android.util
import android.view.View
import android.view.View.OnClickListener
import com.google.android.material.snackbar.Snackbar
import org.wordpress.android.ui.utils.UiString
import java.lang.ref.SoftReference
import java.lang.ref.WeakReference
// Taken from com.google.android.material.snackbar.SnackbarManager.java
// Did not find a way to get them directly from the android framework for now
private const val SHORT_DURATION_MS = 1500L
private const val LONG_DURATION_MS = 2750L
const val INDEFINITE_SNACKBAR_NOT_ALLOWED = "Snackbar.LENGTH_INDEFINITE not allowed in getSnackbarDurationMs."
class SnackbarItem @JvmOverloads constructor(
val info: Info,
val action: Action? = null,
dismissCallback: ((transientBottomBar: Snackbar?, event: Int) -> Unit)? = null,
showCallback: ((transientBottomBar: Snackbar?) -> Unit)? = null
) {
val dismissCallback = SoftReference(dismissCallback)
val showCallback = SoftReference(showCallback)
fun getSnackbarDurationMs(): Long {
return when (info.duration) {
Snackbar.LENGTH_INDEFINITE ->
throw IllegalArgumentException(INDEFINITE_SNACKBAR_NOT_ALLOWED)
Snackbar.LENGTH_LONG -> LONG_DURATION_MS
Snackbar.LENGTH_SHORT -> SHORT_DURATION_MS
else -> info.duration.toLong()
}
}
class Info @JvmOverloads constructor(
view: View,
val textRes: UiString,
val duration: Int,
val isImportant: Boolean = true
) {
val view = WeakReference(view)
}
class Action(
val textRes: UiString,
clickListener: OnClickListener
) {
val clickListener = SoftReference(clickListener)
}
val snackbarCallback = object : Snackbar.Callback() {
override fun onShown(transientBottomBar: Snackbar?) {
[email protected]()?.invoke(transientBottomBar)
super.onShown(transientBottomBar)
}
override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
[email protected]()?.invoke(transientBottomBar, event)
super.onDismissed(transientBottomBar, event)
}
}
}
| gpl-2.0 | de93e4cd1775438e92575d9b06dabad9 | 34.269841 | 110 | 0.693519 | 4.600414 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/key/KeyFormat.kt | 1 | 4322 | /*
* KeyFormat.kt
*
* Copyright 2018 Michael Farrell <[email protected]>
* Copyright 2019 Google
*
* 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 au.id.micolous.metrodroid.key
import au.id.micolous.metrodroid.multi.Log
import kotlinx.io.charsets.Charsets
import kotlinx.serialization.json.Json
/**
* Used by [au.id.micolous.metrodroid.util.Utils.detectKeyFormat] to return the format of a key contained within a
* file.
*/
enum class KeyFormat {
/** Format is unknown */
UNKNOWN,
/** Traditional raw (farebotkeys) binary format */
RAW_MFC,
/** JSON format (unspecified) */
JSON,
/** JSON format (MifareClassic, with UID) */
JSON_MFC,
/** JSON format (MifareClassic, without UID) */
JSON_MFC_NO_UID,
/** JSON format (MifareClassicStatic) */
JSON_MFC_STATIC;
val isJSON: Boolean
get() = (this == KeyFormat.JSON
|| this == KeyFormat.JSON_MFC
|| this == KeyFormat.JSON_MFC_NO_UID
|| this == KeyFormat.JSON_MFC_STATIC)
companion object {
const val TAG = "KeyFormat"
private const val MIFARE_SECTOR_COUNT_MAX = 40
private const val MIFARE_KEY_LENGTH = 6
private fun isRawMifareClassicKeyFileLength(length: Int): Boolean {
return length > 0 &&
length % MIFARE_KEY_LENGTH == 0 &&
length <= MIFARE_SECTOR_COUNT_MAX * MIFARE_KEY_LENGTH * 2
}
private fun rawFormat(length: Int) = if (isRawMifareClassicKeyFileLength(length)) KeyFormat.RAW_MFC else KeyFormat.UNKNOWN
fun detectKeyFormat(data: ByteArray): KeyFormat {
if (data[0] != '{'.toByte()) {
// This isn't a JSON file.
Log.d(TAG, "couldn't find starting {")
return rawFormat(data.size)
}
// Scan for the } at the end of the file.
for (i in (data.size - 1) downTo 0) {
val c = data[i]
if (c <= 0) {
Log.d(TAG, "unsupported encoding at byte $i")
return rawFormat(data.size)
}
if (c in listOf('\n'.toByte(), '\r'.toByte(), '\t'.toByte(),
' '.toByte())) {
continue
}
if (c == '}'.toByte()) {
break
}
// This isn't a JSON file.
Log.d(TAG, "couldn't find ending }")
return if (isRawMifareClassicKeyFileLength(data.size)) KeyFormat.RAW_MFC else KeyFormat.UNKNOWN
}
// Now see if it actually parses.
try {
val o = CardKeys.jsonParser.parseJson(kotlinx.io.core.String(bytes = data,
charset = Charsets.UTF_8)).jsonObject
val type = o.getPrimitiveOrNull(CardKeys.JSON_KEY_TYPE_KEY)?.contentOrNull
when(type) {
CardKeys.TYPE_MFC ->
return if (o.getPrimitiveOrNull(CardKeys.JSON_TAG_ID_KEY)?.contentOrNull?.isEmpty() != false) {
KeyFormat.JSON_MFC_NO_UID
} else {
KeyFormat.JSON_MFC
}
CardKeys.TYPE_MFC_STATIC -> return KeyFormat.JSON_MFC_STATIC
}
// Unhandled JSON format
return KeyFormat.JSON
} catch (e: Exception) {
Log.d(TAG, "couldn't parse JSON object in detectKeyFormat", e)
}
// Couldn't parse as JSON -- fallback
return rawFormat(data.size)
}
}
}
| gpl-3.0 | cf177da8e9fbbbdbcd97e3b62aa97bb6 | 35.319328 | 130 | 0.554836 | 4.208374 | false | false | false | false |
kiwiandroiddev/starcraft-2-build-player | app/src/main/java/com/kiwiandroiddev/sc2buildassistant/feature/brief/presentation/BriefPresenterImpl.kt | 1 | 17465 | package com.kiwiandroiddev.sc2buildassistant.feature.brief.presentation
import com.kiwiandroiddev.sc2buildassistant.R
import com.kiwiandroiddev.sc2buildassistant.domain.entity.Build
import com.kiwiandroiddev.sc2buildassistant.feature.translate.domain.CheckTranslationPossibleUseCase
import com.kiwiandroiddev.sc2buildassistant.feature.brief.domain.GetBuildUseCase
import com.kiwiandroiddev.sc2buildassistant.feature.brief.domain.GetCurrentLanguageUseCase
import com.kiwiandroiddev.sc2buildassistant.feature.brief.domain.ShouldTranslateBuildByDefaultUseCase
import com.kiwiandroiddev.sc2buildassistant.feature.brief.presentation.BriefPresenterImpl.Result.*
import com.kiwiandroiddev.sc2buildassistant.feature.translate.domain.GetTranslationUseCase
import com.kiwiandroiddev.sc2buildassistant.feature.brief.presentation.BriefView.BriefViewState
import com.kiwiandroiddev.sc2buildassistant.feature.common.presentation.StringResolver
import com.kiwiandroiddev.sc2buildassistant.feature.errorreporter.ErrorReporter
import com.kiwiandroiddev.sc2buildassistant.feature.settings.domain.GetSettingsUseCase
import com.kiwiandroiddev.sc2buildassistant.util.whenTrue
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.*
/**
* Created by Matt Clarke on 28/04/17.
*/
class BriefPresenterImpl(val getBuildUseCase: GetBuildUseCase,
val getSettingsUseCase: GetSettingsUseCase,
val getCurrentLanguageUseCase: GetCurrentLanguageUseCase,
val checkTranslationPossibleUseCase: CheckTranslationPossibleUseCase,
val shouldTranslateBuildByDefaultUseCase: ShouldTranslateBuildByDefaultUseCase,
val getTranslationUseCase: GetTranslationUseCase,
val navigator: BriefNavigator,
val errorReporter: ErrorReporter,
val stringResolver: StringResolver,
val postExecutionScheduler: Scheduler) : BriefPresenter {
companion object {
private val INITIAL_VIEW_STATE = BriefViewState(
showAds = false,
showLoadError = false,
showTranslateOption = false,
showTranslationError = false,
translationLoading = false,
showRevertTranslationOption = false,
translationStatusMessage = null,
briefText = null,
buildSource = null,
buildAuthor = null
)
}
private sealed class Result {
data class ShowAdsResult(val showAds: Boolean) : Result()
data class ShowTranslateOptionResult(val showTranslateOption: Boolean,
val currentLanguageCode: String) : Result()
data class RevertTranslationResult(val untranslatedBrief: String?,
val reshowTranslateOption: Boolean,
val currentLanguageCode: String) : Result()
sealed class LoadBuildResult : Result() {
data class Success(val build: Build) : LoadBuildResult()
data class LoadFailure(val cause: Throwable) : LoadBuildResult()
}
class SuccessfulNavigationResult : Result()
sealed class TranslationResult : Result() {
class Loading : TranslationResult()
data class Success(val translatedBrief: String,
val fromLanguageCode: String,
val toLanguageCode: String) : TranslationResult()
data class Failure(val cause: Throwable) : TranslationResult()
}
}
private var view: BriefView? = null
private var disposable: Disposable? = null
override fun attachView(view: BriefView) {
this.view = view
setupViewStateStream(view, view.getBuildId())
}
private fun setupViewStateStream(view: BriefView, buildId: Long) {
val allResults: Observable<Result> = Observable.merge(
loadBuildFollowedByTranslationOption(buildId),
showAdResults(),
getViewEventResults(view.getViewEvents())
)
disposable = allResults
.compose(this::reduceToViewState)
.subscribeOn(Schedulers.io())
.observeOn(postExecutionScheduler)
.subscribe(view::render)
}
private fun loadBuildFollowedByTranslationOption(buildId: Long): Observable<Result> =
loadBuildResult(buildId).flatMapObservable { loadResult ->
when (loadResult) {
is LoadBuildResult.Success -> Observable.concat(
Observable.just(loadResult),
getTranslatedBuildNowIfNeeded(buildId, loadResult.build)
.switchIfEmpty(
getShowTranslateOptionResult(loadResult.build).toObservable()
)
)
else -> Observable.just(loadResult)
}
}
private fun getTranslatedBuildNowIfNeeded(buildId: Long, build: Build): Observable<Result> =
isTranslationAvailableForBuild(build).toObservable()
.whenTrue()
.flatMap { shouldTranslateByDefault(buildId) }
.whenTrue()
.flatMap { getTranslateBuildResults() }
private fun shouldTranslateByDefault(buildId: Long) =
shouldTranslateBuildByDefaultUseCase.shouldTranslateByDefault(buildId).toObservable()
private fun getViewEventResults(viewEvents: Observable<BriefView.BriefViewEvent>): Observable<Result> =
viewEvents.flatMap { viewEvent ->
when (viewEvent) {
is BriefView.BriefViewEvent.PlaySelected -> navigateToPlayer(view?.getBuildId()!!)
is BriefView.BriefViewEvent.EditSelected -> navigateToEditor(view?.getBuildId()!!)
is BriefView.BriefViewEvent.SettingsSelected -> navigateToSettings()
is BriefView.BriefViewEvent.TranslateSelected -> getTranslateBuildResults()
is BriefView.BriefViewEvent.RevertTranslationSelected -> getRevertTranslationResult()
}
}
private fun navigateToPlayer(buildId: Long): Observable<Result.SuccessfulNavigationResult> =
Observable.fromCallable {
navigator.onPlayBuild(buildId)
SuccessfulNavigationResult()
}
private fun navigateToEditor(buildId: Long): Observable<Result.SuccessfulNavigationResult> =
Observable.fromCallable {
navigator.onEditBuild(buildId)
SuccessfulNavigationResult()
}
private fun navigateToSettings(): Observable<Result.SuccessfulNavigationResult> =
Observable.fromCallable {
navigator.onOpenSettings()
SuccessfulNavigationResult()
}
private fun getRevertTranslationResult(): Observable<Result> =
getBuild().toObservable().flatMap { build ->
isTranslationAvailableForBuild(build).toObservable()
.flatMap { translationAvailable ->
getCurrentLanguage().map { currentLanguageCode ->
RevertTranslationResult(
untranslatedBrief = build.notes,
reshowTranslateOption = translationAvailable,
currentLanguageCode = currentLanguageCode
)
}.toObservable()
}
.doOnNext {
shouldTranslateBuildByDefaultUseCase
.clearTranslateByDefaultPreference(view!!.getBuildId())
.subscribe()
}
}
private fun reduceToViewState(results: Observable<Result>): Observable<BriefViewState> =
results.scan(INITIAL_VIEW_STATE) { lastViewState, result ->
when (result) {
is Result.ShowAdsResult ->
lastViewState.copy(showAds = result.showAds)
is Result.LoadBuildResult.Success ->
updatedViewStateWithBuildInfo(lastViewState, result.build)
is Result.LoadBuildResult.LoadFailure ->
lastViewState.copy(showLoadError = true)
is Result.ShowTranslateOptionResult ->
lastViewState.copy(
showTranslateOption = result.showTranslateOption,
translationStatusMessage = translationPromptMessage(
result.currentLanguageCode
)
)
is Result.SuccessfulNavigationResult -> lastViewState // do nothing to view state
is Result.TranslationResult.Loading ->
lastViewState.copy(translationLoading = true)
is Result.TranslationResult.Success ->
lastViewState.copy(
briefText = result.translatedBrief,
translationLoading = false,
showTranslateOption = false,
showRevertTranslationOption = true,
translationStatusMessage = successfulTranslationMessage(
result.fromLanguageCode,
result.toLanguageCode
))
is Result.TranslationResult.Failure ->
lastViewState.copy(
showTranslationError = true,
translationLoading = false
)
is Result.RevertTranslationResult -> lastViewState.copy(
briefText = result.untranslatedBrief,
showRevertTranslationOption = false,
showTranslateOption = result.reshowTranslateOption,
translationStatusMessage = translationPromptMessage(result.currentLanguageCode)
)
}
}
private fun translationPromptMessage(currentLanguageCode: String): String {
val localisedCurrentLanguage = Locale(currentLanguageCode).getDisplayLanguage(Locale(currentLanguageCode))
return stringResolver.getString(
R.string.brief_translation_prompt_status_message,
localisedCurrentLanguage
)
}
private fun successfulTranslationMessage(fromLanguageCode: String, toLanguageCode: String): String {
val localisedOriginalLanguageName = Locale(fromLanguageCode).getDisplayLanguage(Locale(toLanguageCode))
return stringResolver.getString(
R.string.brief_translation_success_status_message,
localisedOriginalLanguageName
)
}
private fun loadBuildResult(buildId: Long): Single<LoadBuildResult> =
getBuildUseCase.getBuild(buildId)
.map { build ->
LoadBuildResult.Success(build) as LoadBuildResult
}
.onErrorReturn { error ->
error.printStackTrace()
LoadBuildResult.LoadFailure(error)
}
private fun getShowTranslateOptionResult(build: Build): Single<Result> =
isTranslationAvailableForBuild(build)
.flatMap { available ->
getCurrentLanguage().map { currentLanguageCode ->
ShowTranslateOptionResult(available, currentLanguageCode) as Result
}
}
private fun isTranslationAvailableForBuild(build: Build): Single<Boolean> =
build.hasLanguageCodeAndNotes()
.flatMap { haveBuildNotesAndLanguage ->
when (haveBuildNotesAndLanguage) {
true -> canTranslateBuildToCurrentLanguage(build)
false -> Single.just(false)
}
}
private fun Build.hasLanguageCodeAndNotes() =
Single.fromCallable { notes != null && isoLanguageCode != null }
private fun canTranslateBuildToCurrentLanguage(build: Build): Single<Boolean> =
getCurrentLanguage().flatMap { currentLanguage ->
if (currentLanguage != build.isoLanguageCode) {
translationPossibleBetweenLanguages(
from = build.isoLanguageCode!!,
to = currentLanguage
)
} else {
Single.just(false)
}
}
private fun getCurrentLanguage(): Single<String> =
getCurrentLanguageUseCase.getLanguageCode().doOnError { getCurrentLanguageError ->
errorReporter.trackNonFatalError(getCurrentLanguageError)
}
private fun translationPossibleBetweenLanguages(from: String, to: String): Single<Boolean> =
checkTranslationPossibleUseCase.canTranslateFromLanguage(
fromLanguageCode = from,
toLanguageCode = to)
.onErrorReturn { error -> error.printStackTrace(); false }
private fun getTranslateBuildResults(): Observable<Result> =
getBuild().toObservable().flatMap { build ->
isTranslationAvailableForBuild(build).toObservable()
.flatMap { translationAvailable ->
when {
translationAvailable -> {
getTranslateBuildToCurrentLanguageResults(build)
}
else -> {
val error = IllegalStateException("Translate selected when translation not available or needed")
errorReporter.trackNonFatalError(error)
Observable.just(TranslationResult.Failure(error))
}
}
}
}.doOnNext { translationResult ->
if (translationResult is TranslationResult.Success) {
shouldTranslateBuildByDefaultUseCase
.setTranslateByDefaultPreference(view!!.getBuildId())
.subscribe()
}
}.map { it as Result }
private fun getTranslateBuildToCurrentLanguageResults(build: Build): Observable<Result.TranslationResult> =
getCurrentLanguage().toObservable()
.flatMap { currentLanguageCode ->
getTranslationUseCase.getTranslation(
fromLanguageCode = build.isoLanguageCode!!, // already know this won't be null from earlier but still
toLanguageCode = currentLanguageCode,
sourceText = build.notes!!)
.toObservable()
.map { translatedBrief ->
TranslationResult.Success(
translatedBrief = translatedBrief,
fromLanguageCode = build.isoLanguageCode!!,
toLanguageCode = currentLanguageCode
) as Result.TranslationResult
}
.onErrorReturn { error ->
error.printStackTrace()
TranslationResult.Failure(error)
}
.startWith(TranslationResult.Loading())
}
private fun getBuild(): Single<Build> =
getBuildUseCase.getBuild(view?.getBuildId()!!) // TODO stub
private fun showAdResults(): Observable<Result.ShowAdsResult> =
getSettingsUseCase.showAds()
.map { showAds -> ShowAdsResult(showAds) }
.onErrorReturn { error ->
error.printStackTrace()
ShowAdsResult(showAds = false)
}
private fun updatedViewStateWithBuildInfo(oldViewState: BriefViewState, build: Build): BriefViewState =
with(build) {
oldViewState.copy(
briefText = notes,
buildSource = source,
buildAuthor = author
)
}
override fun detachView() {
view = null
disposable?.dispose()
}
} | mit | 372e664b0733b1e99b3bf997847a460c | 46.852055 | 133 | 0.562496 | 6.480519 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/quest/bucketlist/BucketListPickerDialogController.kt | 1 | 11602 | package io.ipoli.android.quest.bucketlist
import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.support.annotation.ColorRes
import android.support.v4.widget.TextViewCompat
import android.support.v7.app.AlertDialog
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import com.mikepenz.google_material_typeface_library.GoogleMaterial
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.IIcon
import com.mikepenz.ionicons_typeface_library.Ionicons
import io.ipoli.android.R
import io.ipoli.android.common.AppState
import io.ipoli.android.common.BaseViewStateReducer
import io.ipoli.android.common.DataLoadedAction
import io.ipoli.android.common.ViewUtils
import io.ipoli.android.common.redux.Action
import io.ipoli.android.common.redux.BaseViewState
import io.ipoli.android.common.text.QuestStartTimeFormatter
import io.ipoli.android.common.view.*
import io.ipoli.android.common.view.recyclerview.BaseRecyclerViewAdapter
import io.ipoli.android.common.view.recyclerview.RecyclerViewViewModel
import io.ipoli.android.common.view.recyclerview.SimpleViewHolder
import io.ipoli.android.pet.AndroidPetAvatar
import io.ipoli.android.pet.PetAvatar
import io.ipoli.android.quest.Quest
import io.ipoli.android.quest.bucketlist.BucketListPickerViewState.StateType.*
import kotlinx.android.synthetic.main.dialog_bucket_list_picker.view.*
import kotlinx.android.synthetic.main.item_bucket_list_picker_quest.view.*
import kotlinx.android.synthetic.main.view_dialog_header.view.*
sealed class BucketListPickerAction : Action {
object Load : BucketListPickerAction()
data class SelectItem(val questId: String) : BucketListPickerAction()
data class DeselectItem(val questId: String) : BucketListPickerAction()
object Done : BucketListPickerAction()
}
object BucketListPickerReducer : BaseViewStateReducer<BucketListPickerViewState>() {
override val stateKey = key<BucketListPickerViewState>()
override fun reduce(
state: AppState,
subState: BucketListPickerViewState,
action: Action
) =
when (action) {
is BucketListPickerAction.Load -> {
val newState = subState.copy(
bucketItems = state.dataState.unscheduledQuests
.filter { !it.isCompleted }
.map {
BucketListPickerViewState.BucketItem(it, false)
}
)
state.dataState.player?.let {
newState.copy(
type = DATA_LOADED,
petAvatar = it.pet.avatar
)
} ?: newState.copy(
type = LOADING
)
}
is BucketListPickerAction.SelectItem ->
subState.copy(
type = DATA_CHANGED,
bucketItems = subState.bucketItems.map {
if (it.quest.id == action.questId)
it.copy(
isSelected = true
)
else
it
}
)
is BucketListPickerAction.DeselectItem ->
subState.copy(
type = DATA_CHANGED,
bucketItems = subState.bucketItems.map {
if (it.quest.id == action.questId)
it.copy(
isSelected = false
)
else
it
}
)
is BucketListPickerAction.Done ->
subState.copy(
type = DONE
)
is DataLoadedAction.UnscheduledQuestsChanged -> {
subState.copy(
type = DATA_CHANGED,
bucketItems = action.quests
.filter { !it.isCompleted }
.map {
BucketListPickerViewState.BucketItem(it, false)
}
)
}
is DataLoadedAction.PlayerChanged -> {
subState.copy(
type = PET_AVATAR_CHANGED,
petAvatar = action.player.pet.avatar
)
}
else -> subState
}
override fun defaultState() =
BucketListPickerViewState(
type = LOADING,
petAvatar = PetAvatar.ELEPHANT,
bucketItems = emptyList()
)
}
data class BucketListPickerViewState(
val type: StateType,
val petAvatar: PetAvatar,
val bucketItems: List<BucketItem>
) : BaseViewState() {
enum class StateType {
LOADING,
DATA_LOADED,
PET_AVATAR_CHANGED,
DATA_CHANGED,
DONE
}
data class BucketItem(val quest: Quest, val isSelected: Boolean)
}
class BucketListPickerDialogController(args: Bundle? = null) :
ReduxDialogController<BucketListPickerAction, BucketListPickerViewState, BucketListPickerReducer>(
args
) {
override val reducer = BucketListPickerReducer
private var listener: (List<Quest>) -> Unit = {}
constructor(listener: (List<Quest>) -> Unit) : this() {
this.listener = listener
}
override fun onHeaderViewCreated(headerView: View) {
headerView.dialogHeaderTitle.setText(R.string.dialog_bucket_list_picker_title)
}
@SuppressLint("InflateParams")
override fun onCreateContentView(inflater: LayoutInflater, savedViewState: Bundle?): View {
val view = inflater.inflate(R.layout.dialog_bucket_list_picker, null)
view.questList.layoutManager = LinearLayoutManager(view.context)
view.questList.adapter = QuestAdapter()
return view
}
override fun onCreateLoadAction() = BucketListPickerAction.Load
override fun onCreateDialog(
dialogBuilder: AlertDialog.Builder,
contentView: View,
savedViewState: Bundle?
): AlertDialog =
dialogBuilder
.setPositiveButton(R.string.schedule, null)
.setNegativeButton(R.string.cancel, null)
.create()
override fun onDialogCreated(dialog: AlertDialog, contentView: View) {
dialog.setOnShowListener {
setPositiveButtonListener {
dispatch(BucketListPickerAction.Done)
}
}
}
override fun render(state: BucketListPickerViewState, view: View) {
when (state.type) {
DATA_LOADED -> {
changeIcon(state.petHeadImage)
(view.questList.adapter as QuestAdapter).updateAll(state.bucketItemViewModels)
}
DATA_CHANGED -> {
(view.questList.adapter as QuestAdapter).updateAll(state.bucketItemViewModels)
}
PET_AVATAR_CHANGED -> {
changeIcon(state.petHeadImage)
}
DONE -> {
listener(state.bucketItems.filter { it.isSelected }.map { it.quest })
dismiss()
}
else -> {
}
}
}
private val BucketListPickerViewState.petHeadImage
get() = AndroidPetAvatar.valueOf(petAvatar.name).headImage
data class TagViewModel(val name: String, @ColorRes val color: Int)
data class QuestItem(
override val id: String,
val name: String,
val startTime: String,
@ColorRes val color: Int,
val tags: List<TagViewModel>,
val icon: IIcon,
val isRepeating: Boolean,
val isFromChallenge: Boolean,
val isSelected: Boolean
) : RecyclerViewViewModel
inner class QuestAdapter :
BaseRecyclerViewAdapter<QuestItem>(R.layout.item_bucket_list_picker_quest) {
override fun onBindViewModel(vm: QuestItem, view: View, holder: SimpleViewHolder) {
view.questName.text = vm.name
view.questIcon.backgroundTintList =
ColorStateList.valueOf(colorRes(vm.color))
view.questIcon.setImageDrawable(smallListItemIcon(vm.icon))
view.questStartTime.text = vm.startTime
view.questStartTime.setCompoundDrawablesRelativeWithIntrinsicBounds(
IconicsDrawable(view.context)
.icon(GoogleMaterial.Icon.gmd_timer)
.sizeDp(16)
.colorRes(colorTextSecondaryResource)
.respectFontBounds(true),
null, null, null
)
if (vm.tags.isNotEmpty()) {
renderTag(view.questTagName, vm.tags.first())
} else {
view.questTagName.gone()
}
view.questRepeatIndicator.visibility =
if (vm.isRepeating) View.VISIBLE else View.GONE
view.questChallengeIndicator.visibility =
if (vm.isFromChallenge) View.VISIBLE else View.GONE
view.questSelected.setOnCheckedChangeListener(null)
view.onDebounceClick {
view.questSelected.isChecked = !vm.isSelected
}
view.questSelected.isChecked = vm.isSelected
view.questSelected.setOnCheckedChangeListener { _, isChecked ->
dispatch(
if (isChecked)
BucketListPickerAction.SelectItem(vm.id)
else
BucketListPickerAction.DeselectItem(vm.id)
)
}
}
}
private fun renderTag(tagNameView: TextView, tag: TagViewModel) {
tagNameView.visible()
tagNameView.text = tag.name
TextViewCompat.setTextAppearance(
tagNameView,
R.style.TextAppearance_AppCompat_Caption
)
val indicator = tagNameView.compoundDrawablesRelative[0] as GradientDrawable
indicator.mutate()
val size = ViewUtils.dpToPx(8f, tagNameView.context).toInt()
indicator.setSize(size, size)
indicator.setColor(colorRes(tag.color))
tagNameView.setCompoundDrawablesRelativeWithIntrinsicBounds(
indicator,
null,
null,
null
)
}
private val BucketListPickerViewState.bucketItemViewModels: List<QuestItem>
get() =
bucketItems.map {
val q = it.quest
QuestItem(
id = q.id,
name = q.name,
tags = q.tags.map { t ->
TagViewModel(
t.name,
t.color.androidColor.color500
)
},
startTime = QuestStartTimeFormatter.formatWithDuration(
q,
activity!!,
shouldUse24HourFormat
),
color = q.color.androidColor.color500,
icon = q.icon?.androidIcon?.icon
?: Ionicons.Icon.ion_checkmark,
isRepeating = q.isFromRepeatingQuest,
isFromChallenge = q.isFromChallenge,
isSelected = it.isSelected
)
}
} | gpl-3.0 | f3ab49b4eff95b4c449e40f09a2c20ce | 33.739521 | 102 | 0.579641 | 5.378767 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/pet/PetDialogViewState.kt | 1 | 2048 | package io.ipoli.android.pet
import io.ipoli.android.common.AppSideEffectHandler
import io.ipoli.android.common.AppState
import io.ipoli.android.common.BaseViewStateReducer
import io.ipoli.android.common.DataLoadedAction
import io.ipoli.android.common.redux.Action
import io.ipoli.android.common.redux.BaseViewState
import space.traversal.kapsule.required
/**
* Created by Venelin Valkov <[email protected]>
* on 12/7/17.
*/
object LoadPetDialogAction : Action
object PetDialogReducer : BaseViewStateReducer<PetDialogViewState>() {
override fun reduce(
state: AppState,
subState: PetDialogViewState,
action: Action
) =
when (action) {
LoadPetDialogAction ->
state.dataState.player?.let {
subState.copy(
type = PetDialogViewState.Type.PET_LOADED,
petAvatar = it.pet.avatar
)
} ?: subState.copy(type = PetDialogViewState.Type.LOADING)
is DataLoadedAction.PlayerChanged ->
subState.copy(
type = PetDialogViewState.Type.PET_LOADED,
petAvatar = action.player.pet.avatar
)
else -> subState
}
override fun defaultState() = PetDialogViewState(PetDialogViewState.Type.LOADING)
override val stateKey = key<PetDialogViewState>()
}
data class PetDialogViewState(
val type: Type,
val petAvatar: PetAvatar? = null
) : BaseViewState() {
enum class Type {
LOADING,
PET_LOADED
}
}
object PetDialogSideEffectHandler : AppSideEffectHandler() {
private val playerRepository by required { playerRepository }
override suspend fun doExecute(action: Action, state: AppState) {
if (action is LoadPetDialogAction && state.dataState.player == null) {
dispatch(DataLoadedAction.PlayerChanged(playerRepository.find()!!))
}
}
override fun canHandle(action: Action) = action is LoadPetDialogAction
} | gpl-3.0 | 3090ab4414a3d08039c8d2b3661ae409 | 27.859155 | 85 | 0.652344 | 4.818824 | false | false | false | false |
GunoH/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/history/FileHistoryDiffPreview.kt | 5 | 2631 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.vcs.log.history
import com.intellij.diff.chains.DiffRequestChain
import com.intellij.diff.chains.SimpleDiffRequestChain
import com.intellij.diff.impl.DiffRequestProcessor
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.changes.ChainBackedDiffPreviewProvider
import com.intellij.openapi.vcs.changes.actions.diff.ChangeDiffRequestProducer
import com.intellij.vcs.log.VcsLogBundle
import com.intellij.vcs.log.VcsLogDataKeys
import com.intellij.vcs.log.ui.actions.history.CompareRevisionsFromFileHistoryActionProvider
import com.intellij.vcs.log.ui.frame.EditorDiffPreview
import org.jetbrains.annotations.Nls
import javax.swing.JComponent
import javax.swing.event.ListSelectionListener
class FileHistoryEditorDiffPreview(project: Project, private val fileHistoryPanel: FileHistoryPanel) :
EditorDiffPreview(project, fileHistoryPanel), ChainBackedDiffPreviewProvider {
init {
init()
}
override fun getOwnerComponent(): JComponent = fileHistoryPanel.graphTable
override fun getEditorTabName(processor: DiffRequestProcessor?): @Nls String =
VcsLogBundle.message("file.history.diff.preview.editor.tab.name", fileHistoryPanel.filePath.name)
override fun addSelectionListener(listener: () -> Unit) {
val selectionListener = ListSelectionListener {
if (!fileHistoryPanel.graphTable.selectionModel.isSelectionEmpty) {
listener()
}
}
fileHistoryPanel.graphTable.selectionModel.addListSelectionListener(selectionListener)
Disposer.register(owner, Disposable { fileHistoryPanel.graphTable.selectionModel.removeListSelectionListener(selectionListener) })
}
override fun createDiffRequestProcessor(): DiffRequestProcessor {
val preview: FileHistoryDiffProcessor = fileHistoryPanel.createDiffPreview(true)
preview.updatePreview(true)
return preview
}
override fun createDiffRequestChain(): DiffRequestChain? {
val change = fileHistoryPanel.selectedChange ?: return null
val producer = ChangeDiffRequestProducer.create(project, change) ?: return null
return SimpleDiffRequestChain.fromProducer(producer)
}
override fun updateDiffAction(event: AnActionEvent) {
val selection = event.getData(VcsLogDataKeys.VCS_LOG_COMMIT_SELECTION) ?: return
CompareRevisionsFromFileHistoryActionProvider.setTextAndDescription(event, selection)
}
}
| apache-2.0 | 65d28892d5961a48e408ab2e8dec60e1 | 42.85 | 134 | 0.815279 | 4.964151 | false | false | false | false |
GunoH/intellij-community | platform/tips-of-the-day/src/com/intellij/ide/util/TipUiSettings.kt | 2 | 1377 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.util
import com.intellij.ui.JBColor
import com.intellij.util.ui.JBUI
import java.awt.Color
import javax.swing.BorderFactory
import javax.swing.border.Border
internal object TipUiSettings {
@JvmStatic
val imageMaxWidth: Int
get() = JBUI.scale(498)
@JvmStatic
val tipPanelMinHeight: Int
get() = JBUI.scale(190)
@JvmStatic
val tipPanelMaxHeight: Int
get() = JBUI.scale(540)
@JvmStatic
val tipPanelLeftIndent: Int
get() = JBUI.scale(24)
@JvmStatic
val tipPanelRightIndent: Int
get() = JBUI.scale(24)
@JvmStatic
val tipPanelTopIndent: Int
get() = JBUI.scale(16)
@JvmStatic
val tipPanelBottomIndent: Int
get() = JBUI.scale(8)
@JvmStatic
val feedbackPanelTopIndent: Int
get() = JBUI.scale(8)
@JvmStatic
val feedbackIconIndent: Int
get() = JBUI.scale(6)
@JvmStatic
val tipPanelBorder: Border
get() = BorderFactory.createEmptyBorder(tipPanelTopIndent, tipPanelLeftIndent, tipPanelBottomIndent, tipPanelRightIndent)
@JvmStatic
val imageBorderColor: Color
get() = JBColor.namedColor("TipOfTheDay.Image.borderColor", JBColor.border())
@JvmStatic
val panelBackground: Color
get() = JBColor.namedColor("TextField.background", 0xFFFFFF, 0x2B2D30)
} | apache-2.0 | 48be01895f25490b5ef32d2a78678307 | 28.319149 | 125 | 0.736383 | 3.701613 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/roots/builders/ModuleRootsIndexableIteratorHandler.kt | 2 | 3064 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.indexing.roots.builders
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PlatformUtils
import com.intellij.util.indexing.roots.IndexableEntityProvider
import com.intellij.util.indexing.roots.IndexableEntityProviderMethods
import com.intellij.util.indexing.roots.IndexableFilesIterator
import com.intellij.workspaceModel.ide.impl.virtualFile
import com.intellij.workspaceModel.ide.isEqualOrParentOf
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleId
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
class ModuleRootsIndexableIteratorHandler : IndexableIteratorBuilderHandler {
override fun accepts(builder: IndexableEntityProvider.IndexableIteratorBuilder): Boolean =
builder is ModuleRootsIteratorBuilder || builder is FullModuleContentIteratorBuilder
override fun instantiate(builders: Collection<IndexableEntityProvider.IndexableIteratorBuilder>,
project: Project,
entityStorage: EntityStorage): List<IndexableFilesIterator> {
val fullIndexedModules: Set<ModuleId> = builders.mapNotNull { (it as? FullModuleContentIteratorBuilder)?.moduleId }.toSet()
@Suppress("UNCHECKED_CAST")
val partialIterators = builders.filter {
it is ModuleRootsIteratorBuilder && !fullIndexedModules.contains(it.moduleId)
} as List<ModuleRootsIteratorBuilder>
val partialIteratorsMap = partialIterators.groupBy { builder -> builder.moduleId }
val result = mutableListOf<IndexableFilesIterator>()
fullIndexedModules.forEach { moduleId ->
entityStorage.resolve(moduleId)?.also { entity ->
result.addAll(IndexableEntityProviderMethods.createIterators(entity, entityStorage, project))
}
}
partialIteratorsMap.forEach { pair ->
entityStorage.resolve(pair.key)?.also { entity ->
result.addAll(IndexableEntityProviderMethods.createIterators(entity, resolveRoots(pair.value), entityStorage))
}
}
return result
}
private fun resolveRoots(builders: List<ModuleRootsIteratorBuilder>): List<VirtualFile> {
if (PlatformUtils.isRider() || PlatformUtils.isCLion()) {
return builders.flatMap { builder -> builder.urls }.mapNotNull { url -> url.virtualFile }
}
val roots = mutableListOf<VirtualFileUrl>()
for (builder in builders) {
for (root in builder.urls) {
var isChild = false
val it = roots.iterator()
while (it.hasNext()) {
val next = it.next()
if (next.isEqualOrParentOf(root)) {
isChild = true
break
}
if (root.isEqualOrParentOf(next)) {
it.remove()
}
}
if (!isChild) {
roots.add(root)
}
}
}
return roots.mapNotNull { url -> url.virtualFile }
}
} | apache-2.0 | 8b48c7ad24efef1f8620a3b356e8ebed | 41.569444 | 127 | 0.722911 | 4.965964 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database/src/main/kotlin/com/onyx/exception/OnyxException.kt | 1 | 1039 | package com.onyx.exception
/**
* Created by timothy.osborn on 11/3/14.
*
*
* Base exception for an entity
*/
@Suppress("LeakingThis")
open class OnyxException : Exception {
@Transient internal var rootCause: Throwable? = null
override var message:String?
/**
* Constructor with cause
*
* @param cause Root cause
*/
constructor(cause: Throwable) : this(cause.localizedMessage) {
this.rootCause = cause
}
/**
* Constructor with error message
*
* @param message Exception message
*/
@JvmOverloads
constructor(message: String? = UNKNOWN_EXCEPTION) : super(message) { this.message = message }
/**
* Constructor with message and cause
*
* @param message Exception message
* @param cause Root cause
*/
constructor(message: String? = UNKNOWN_EXCEPTION, cause: Throwable?) : super(message, cause) { this.message = message }
companion object {
const val UNKNOWN_EXCEPTION = "Unknown exception occurred"
}
}
| agpl-3.0 | d8ef5103a0565450aede6d5d681e33cb | 22.088889 | 123 | 0.640038 | 4.459227 | false | false | false | false |
jk1/intellij-community | community-guitests/testSrc/com/intellij/testGuiFramework/tests/community/CommunityProjectCreator.kt | 1 | 5001 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testGuiFramework.tests.community
import com.intellij.ide.IdeBundle
import com.intellij.openapi.diagnostic.Logger
import com.intellij.testGuiFramework.impl.*
import com.intellij.testGuiFramework.util.Key.A
import com.intellij.testGuiFramework.util.Key.V
import com.intellij.testGuiFramework.util.Modifier.CONTROL
import com.intellij.testGuiFramework.util.Modifier.META
import com.intellij.testGuiFramework.util.plus
import com.intellij.testGuiFramework.utils.TestUtilsClass
import com.intellij.testGuiFramework.utils.TestUtilsClassCompanion
import org.fest.swing.exception.ComponentLookupException
import org.fest.swing.exception.WaitTimedOutError
import org.junit.Assert
import java.io.File
val GuiTestCase.CommunityProjectCreator by CommunityProjectCreator
class CommunityProjectCreator(guiTestCase: GuiTestCase) : TestUtilsClass(guiTestCase) {
companion object : TestUtilsClassCompanion<CommunityProjectCreator>({ it -> CommunityProjectCreator(it) })
private val LOG = Logger.getInstance(this.javaClass)
private val defaultProjectName = "untitled"
fun createCommandLineProject(projectName: String = defaultProjectName, needToOpenMainJava: Boolean = true) {
with(guiTestCase) {
welcomeFrame {
actionLink("Create New Project").click()
GuiTestUtilKt.waitProgressDialogUntilGone(robot(), "Loading Templates")
dialog("New Project") {
jList("Java").clickItem("Java")
button("Next").click()
val projectFromTemplateCheckbox = checkbox("Create project from template")
projectFromTemplateCheckbox.click()
//check that "Create project from template" has been clicked. GUI-80
if (!projectFromTemplateCheckbox.isSelected) projectFromTemplateCheckbox.click()
Assert.assertTrue("Checkbox \"Create project from template\" should be selected!", projectFromTemplateCheckbox.isSelected)
jList("Command Line App").clickItem("Command Line App")
button("Next").click()
typeText(projectName)
checkFileAlreadyExistsDialog() //confirm overwriting already created project
button("Finish").click()
}
}
waitForFirstIndexing()
if (needToOpenMainJava) openMainInCommandLineProject()
}
}
private fun GuiTestCase.checkFileAlreadyExistsDialog() {
try {
val dialogFixture = dialog(IdeBundle.message("title.file.already.exists"), false, 10L)
dialogFixture.button("Yes").click()
} catch (cle: ComponentLookupException) { /*do nothing here */ }
}
private fun GuiTestCase.openMainInCommandLineProject() {
ideFrame {
projectView {
path(project.name, "src", "com.company", "Main").doubleClick()
waitForBackgroundTasksToFinish()
}
}
}
private fun GuiTestCase.openFileInCommandLineProject(fileName: String) {
ideFrame {
projectView {
path(project.name, "src", "com.company", fileName).doubleClick()
waitForBackgroundTasksToFinish()
}
}
}
private fun GuiTestCase.waitForFirstIndexing() {
ideFrame {
val secondToWaitIndexing = 10
try {
waitForStartingIndexing(secondToWaitIndexing) //let's wait for 2 minutes until indexing bar will appeared
}
catch (timedOutError: WaitTimedOutError) {
LOG.warn("Waiting for indexing has been exceeded $secondToWaitIndexing seconds")
}
waitForBackgroundTasksToFinish()
}
}
fun createJavaClass(fileContent: String, fileName: String = "Test") {
with(guiTestCase) {
ideFrame {
projectView {
path(project.name, "src", "com.company").rightClick()
}
popup("New", "Java Class")
dialog("Create New Class") {
typeText(fileName)
button("OK").click()
}
editor(fileName + ".java") {
shortcut(CONTROL + A, META + A)
copyToClipboard(fileContent)
shortcut(CONTROL + V, META + V)
}
}
}
}
/**
* @projectName of importing project should be locate in the current module testData/
*/
fun importProject(projectName: String) {
val commandLineAppDirUrl = this.javaClass.classLoader.getResource(projectName)
val commandLineAppDir = File(commandLineAppDirUrl.toURI())
guiTestCase.guiTestRule.importProject(commandLineAppDir)
}
fun importCommandLineApp() {
importProject("command-line-app")
}
/**
* @fileName - name of file with extension stored in src/com.company/
*/
fun importCommandLineAppAndOpenFile(fileName: String) {
importCommandLineApp()
guiTestCase.waitForFirstIndexing()
guiTestCase.openFileInCommandLineProject(fileName)
}
fun importCommandLineAppAndOpenMain() {
importCommandLineApp()
guiTestCase.waitForFirstIndexing()
guiTestCase.openMainInCommandLineProject()
}
}
| apache-2.0 | f24f8a7586b5ecf77671c014ed6477c7 | 34.468085 | 140 | 0.711458 | 4.82722 | false | true | false | false |
evanchooly/kobalt | src/test/kotlin/com/beust/kobalt/VariantTest.kt | 1 | 1675 | package com.beust.kobalt
import com.beust.kobalt.api.Project
import com.beust.kobalt.api.buildType
import com.beust.kobalt.api.productFlavor
import org.testng.Assert
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
import java.util.*
class VariantTest : KobaltTest() {
@DataProvider(name = "projectVariants")
fun projectVariants() = arrayOf(
arrayOf(emptySet<String>(), Project().apply {
}),
arrayOf(hashSetOf("compileDev"), Project().apply {
productFlavor("dev") {}
}),
arrayOf(hashSetOf("compileDev", "compileProd"), Project().apply {
productFlavor("dev") {}
productFlavor("prod") {}
}),
arrayOf(hashSetOf("compileDevDebug"), Project().apply {
productFlavor("dev") {}
buildType("debug") {}
}),
arrayOf(hashSetOf("compileDevRelease", "compileDevDebug", "compileProdDebug", "compileProdRelease"),
Project().apply {
productFlavor("dev") {}
productFlavor("prod") {}
buildType("debug") {}
buildType("release") {}
})
)
@Test(dataProvider = "projectVariants", description =
"Make sure we generate the correct dynamic tasks based on the product flavor and build types.")
fun taskNamesShouldWork(expected: Set<String>, project: Project) {
val variantNames = HashSet(Variant.allVariants(project).map { it.toTask("compile") })
Assert.assertEquals(variantNames, expected)
}
}
| apache-2.0 | 98e4296bff66eec809b420894f93b1b0 | 37.953488 | 112 | 0.583284 | 4.926471 | false | true | false | false |
armcha/Ribble | app/src/main/kotlin/io/armcha/ribble/presentation/screen/user_following/UserFollowingFragment.kt | 1 | 2816 | package io.armcha.ribble.presentation.screen.user_following
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.view.View
import io.armcha.ribble.R
import io.armcha.ribble.domain.entity.Shot
import io.armcha.ribble.presentation.adapter.ShotRecyclerViewAdapter
import io.armcha.ribble.presentation.adapter.listener.ShotClickListener
import io.armcha.ribble.presentation.base_mvp.base.BaseFragment
import io.armcha.ribble.presentation.screen.shot_detail.ShotDetailFragment
import io.armcha.ribble.presentation.utils.S
import io.armcha.ribble.presentation.utils.extensions.isPortrait
import io.armcha.ribble.presentation.utils.extensions.takeColor
import io.armcha.ribble.presentation.widget.navigation_view.NavigationId
import kotlinx.android.synthetic.main.fragment_user_following.*
import kotlinx.android.synthetic.main.progress_bar.*
import javax.inject.Inject
class UserFollowingFragment : BaseFragment<UserFollowingContract.View, UserFollowingContract.Presenter>(),
UserFollowingContract.View, ShotClickListener {
@Inject
protected lateinit var followingPresenter: UserFollowPresenter
private var recyclerAdapter: ShotRecyclerViewAdapter? = null
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
progressBar.backgroundCircleColor = takeColor(R.color.colorPrimary)
}
override fun injectDependencies() {
activityComponent.inject(this)
}
override val layoutResId = R.layout.fragment_user_following
override fun initPresenter() = followingPresenter
override fun onShotClicked(shot: Shot) {
val bundle = ShotDetailFragment.getBundle(shot)
goTo<ShotDetailFragment>(keepState = false, withCustomAnimation = true, arg = bundle)
}
override fun showLoading() {
progressBar.start()
}
override fun hideLoading() {
progressBar.stop()
}
override fun showError(message: String?) {
showErrorDialog(message)
}
override fun showNoShots() {
noShotsText.setAnimatedText(getString(S.no_shots))
}
override fun onShotListReceive(shotList: List<Shot>) {
updateAdapter(shotList)
}
private fun updateAdapter(shotList: List<Shot>) {
recyclerAdapter?.update(shotList) ?: setUpRecyclerView(shotList)
}
private fun setUpRecyclerView(shotList: List<Shot>) {
recyclerAdapter = ShotRecyclerViewAdapter(shotList, this)
with(shotRecyclerView) {
layoutManager = GridLayoutManager(activity, if (isPortrait()) 2 else 3)
setHasFixedSize(true)
adapter = recyclerAdapter
scheduleLayoutAnimation()
}
}
override fun getTitle() = NavigationId.FOLLOWING.name
}
| apache-2.0 | 391ed236e4d6b34359871a8e89720748 | 32.927711 | 106 | 0.746449 | 4.685524 | false | false | false | false |
rinp/task | src/main/kotlin/todo/Validate.kt | 1 | 1340 | package task
/**
* @author rinp
* @since 2016/07/15
*/
//@Constraint(validatedBy = arrayOf(IsLoopTaskValidator::class))
//@Target(AnnotationTarget.PROPERTY_GETTER)
//@Retention(AnnotationRetention.RUNTIME)
//@Suppress("unused")
//annotation class IsLoopTask(
// val message: String = "Taskがループしています。",
// val groups: Array<KClass<*>> = arrayOf(),
// val payload: Array<KClass<out Payload>> = arrayOf()
//)
//
//@Component
//open class IsLoopTaskValidator : ConstraintValidator<IsLoopTask, Pair<Long, Long>> {
//
// override fun initialize(constraintAnnotation: IsLoopTask?) {
// }
//
// @Autowired
// lateinit private var repository: TaskRepository
//
// override fun isValid(pair: Pair<Long, Long>, context: ConstraintValidatorContext?): Boolean {
// val parentId = pair.first
// val childId = pair.second
//
// val parent = repository.findOne(parentId)
// val child = repository.findOne(childId)
//
// var tasks: List<Task> = child.tasks.toList()
// while (true) {
// if (tasks.isEmpty()) {
// return true;
// }
//
// if (tasks.any { it.id == parent.id }) {
// return false;
// }
//
// tasks = tasks.flatMap { it.tasks };
//
// }
// }
//}
| apache-2.0 | d810027fd7d440f258416ca97af969b6 | 25.938776 | 99 | 0.584848 | 3.707865 | false | false | false | false |
iSoron/uhabits | uhabits-core-legacy/src/main/js/org/isoron/platform/gui/JsImage.kt | 1 | 2433 | /*
* Copyright (C) 2016-2019 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.platform.gui
import org.khronos.webgl.*
import org.w3c.dom.*
import kotlin.browser.*
import kotlin.math.*
class JsImage(val canvas: JsCanvas,
val imageData: ImageData) : Image {
override val width: Int
get() = imageData.width
override val height: Int
get() = imageData.height
val pixels = imageData.unsafeCast<Uint16Array>()
init {
console.log(width, height, imageData.data.length)
}
override suspend fun export(path: String) {
canvas.ctx.putImageData(imageData, 0.0, 0.0)
val container = document.createElement("div")
container.className = "export"
val title = document.createElement("div")
title.innerHTML = path
document.body?.appendChild(container)
container.appendChild(title)
container.appendChild(canvas.element)
}
override fun getPixel(x: Int, y: Int): Color {
val offset = 4 * (y * width + x)
return Color(imageData.data[offset + 0] / 255.0,
imageData.data[offset + 1] / 255.0,
imageData.data[offset + 2] / 255.0,
imageData.data[offset + 3] / 255.0)
}
override fun setPixel(x: Int, y: Int, color: Color) {
val offset = 4 * (y * width + x)
inline fun map(x: Double): Byte {
return (x * 255).roundToInt().unsafeCast<Byte>()
}
imageData.data.set(offset + 0, map(color.red))
imageData.data.set(offset + 1, map(color.green))
imageData.data.set(offset + 2, map(color.blue))
imageData.data.set(offset + 3, map(color.alpha))
}
} | gpl-3.0 | 7f34991aac0d69dded29ad86ed26934a | 32.791667 | 78 | 0.643503 | 3.941653 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/ide-features-trainer/src/training/featuresSuggester/listeners/PsiActionsListener.kt | 8 | 5160 | package training.featuresSuggester.listeners
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiTreeChangeAdapter
import com.intellij.psi.PsiTreeChangeEvent
import training.featuresSuggester.SuggesterSupport
import training.featuresSuggester.SuggestingUtils.handleAction
import training.featuresSuggester.actions.*
class PsiActionsListener(private val project: Project) : PsiTreeChangeAdapter() {
override fun beforePropertyChange(event: PsiTreeChangeEvent) {
if (event.parent == null || !isLoadedSourceFile(event.file)) return
handleAction(
project,
BeforePropertyChangedAction(
psiFile = event.file!!,
parent = event.parent,
timeMillis = System.currentTimeMillis()
)
)
}
override fun beforeChildAddition(event: PsiTreeChangeEvent) {
if (event.parent == null || event.child == null || !isLoadedSourceFile(event.file)) return
handleAction(
project,
BeforeChildAddedAction(
psiFile = event.file!!,
parent = event.parent,
newChild = event.child,
timeMillis = System.currentTimeMillis()
)
)
}
override fun beforeChildReplacement(event: PsiTreeChangeEvent) {
if (event.parent == null || event.newChild == null || event.oldChild == null || !isLoadedSourceFile(event.file)) return
handleAction(
project,
BeforeChildReplacedAction(
psiFile = event.file!!,
parent = event.parent,
newChild = event.newChild,
oldChild = event.oldChild,
timeMillis = System.currentTimeMillis()
)
)
}
override fun beforeChildrenChange(event: PsiTreeChangeEvent) {
if (event.parent == null || !isLoadedSourceFile(event.file)) return
handleAction(
project,
BeforeChildrenChangedAction(
psiFile = event.file!!,
parent = event.parent,
timeMillis = System.currentTimeMillis()
)
)
}
override fun beforeChildMovement(event: PsiTreeChangeEvent) {
if (event.parent == null || event.child == null || event.oldParent == null || !isLoadedSourceFile(event.file)) return
handleAction(
project,
BeforeChildMovedAction(
psiFile = event.file!!,
parent = event.parent,
child = event.child,
oldParent = event.oldParent,
timeMillis = System.currentTimeMillis()
)
)
}
override fun beforeChildRemoval(event: PsiTreeChangeEvent) {
if (event.parent == null || event.child == null || !isLoadedSourceFile(event.file)) return
handleAction(
project,
BeforeChildRemovedAction(
psiFile = event.file!!,
parent = event.parent,
child = event.child,
timeMillis = System.currentTimeMillis()
)
)
}
override fun propertyChanged(event: PsiTreeChangeEvent) {
if (event.parent == null || !isLoadedSourceFile(event.file)) return
handleAction(project, PropertyChangedAction(psiFile = event.file!!, parent = event.parent, timeMillis = System.currentTimeMillis()))
}
override fun childRemoved(event: PsiTreeChangeEvent) {
if (event.parent == null || event.child == null || !isLoadedSourceFile(event.file)) return
handleAction(
project,
ChildRemovedAction(
psiFile = event.file!!,
parent = event.parent,
child = event.child,
timeMillis = System.currentTimeMillis()
)
)
}
override fun childReplaced(event: PsiTreeChangeEvent) {
if (event.parent == null || event.newChild == null || event.oldChild == null || !isLoadedSourceFile(event.file)) return
handleAction(
project,
ChildReplacedAction(
psiFile = event.file!!,
parent = event.parent,
newChild = event.newChild,
oldChild = event.oldChild,
timeMillis = System.currentTimeMillis()
)
)
}
override fun childAdded(event: PsiTreeChangeEvent) {
if (event.parent == null || event.child == null || !isLoadedSourceFile(event.file)) return
handleAction(
project,
ChildAddedAction(
psiFile = event.file!!,
parent = event.parent,
newChild = event.child,
timeMillis = System.currentTimeMillis()
)
)
}
override fun childrenChanged(event: PsiTreeChangeEvent) {
if (event.parent == null || !isLoadedSourceFile(event.file)) return
handleAction(project, ChildrenChangedAction(psiFile = event.file!!, parent = event.parent, timeMillis = System.currentTimeMillis()))
}
override fun childMoved(event: PsiTreeChangeEvent) {
if (event.parent == null || event.child == null || event.oldParent == null || !isLoadedSourceFile(event.file)) return
handleAction(
project,
ChildMovedAction(
psiFile = event.file!!,
parent = event.parent,
child = event.child,
oldParent = event.oldParent,
timeMillis = System.currentTimeMillis()
)
)
}
private fun isLoadedSourceFile(psiFile: PsiFile?): Boolean {
val language = psiFile?.language ?: return false
return SuggesterSupport.getForLanguage(language)?.isLoadedSourceFile(psiFile) == true
}
}
| apache-2.0 | 818d51d872b5973076d6a47a57333e71 | 31.658228 | 136 | 0.667829 | 4.8 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/compiler-plugins/kotlinx-serialization/maven/src/org/jetbrains/kotlin/idea/compilerPlugin/kotlinxSerialization/maven/KotlinSerializationMavenImportHandler.kt | 4 | 1257 | // 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.compilerPlugin.kotlinxSerialization.maven
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.kotlin.idea.maven.compilerPlugin.AbstractMavenImportHandler
import org.jetbrains.kotlin.idea.compilerPlugin.CompilerPluginSetup
import org.jetbrains.kotlin.idea.compilerPlugin.kotlinxSerialization.KotlinSerializationImportHandler
import java.io.File
class KotlinSerializationMavenImportHandler : AbstractMavenImportHandler() {
override val compilerPluginId: String = "org.jetbrains.kotlinx.serialization"
override val pluginName: String = "serialization"
override val mavenPluginArtifactName: String = "kotlin-maven-serialization"
override val pluginJarFileFromIdea: String
get() = KotlinSerializationImportHandler.PLUGIN_JPS_JAR
override fun getOptions(
mavenProject: MavenProject,
enabledCompilerPlugins: List<String>,
compilerPluginOptions: List<String>
): List<CompilerPluginSetup.PluginOption>? =
if ("kotlinx-serialization" in enabledCompilerPlugins) emptyList() else null
} | apache-2.0 | 8d6105f5750f7f1dd854af1a0dad6c09 | 51.416667 | 158 | 0.802705 | 4.910156 | false | false | false | false |
DreierF/MyTargets | shared/src/main/java/de/dreier/mytargets/shared/targets/drawable/TargetImpactDrawable.kt | 1 | 5412 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets 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.
*
* MyTargets 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.
*/
package de.dreier.mytargets.shared.targets.drawable
import android.graphics.Paint
import android.graphics.RectF
import android.os.AsyncTask
import android.text.TextPaint
import de.dreier.mytargets.shared.models.Dimension
import de.dreier.mytargets.shared.models.Target
import de.dreier.mytargets.shared.models.db.Shot
import de.dreier.mytargets.shared.utils.Color.WHITE
import java.util.*
open class TargetImpactDrawable(target: Target) : TargetDrawable(target) {
protected var shots: MutableList<MutableList<Shot>> = ArrayList()
protected var transparentShots: MutableList<MutableList<Shot>> = ArrayList()
private var arrowRadius: Float = 0.toFloat()
private var shouldDrawArrows = true
private var focusedArrow: Shot? = null
private val paintText: TextPaint by lazy {
val paintText = TextPaint()
paintText.isAntiAlias = true
paintText.color = WHITE
paintText
}
private val paintFill: Paint by lazy {
val paintFill = Paint()
paintFill.isAntiAlias = true
paintFill
}
init {
setArrowDiameter(Dimension(5f, Dimension.Unit.MILLIMETER), 1f)
for (i in 0 until model.faceCount) {
shots.add(ArrayList())
transparentShots.add(ArrayList())
}
}
fun setArrowDiameter(arrowDiameter: Dimension, scale: Float) {
val (value) = model.getRealSize(target.diameter).convertTo(arrowDiameter.unit!!)
arrowRadius = arrowDiameter.value * scale / value
}
override fun onPostDraw(canvas: CanvasWrapper, faceIndex: Int) {
super.onPostDraw(canvas, faceIndex)
if (!shouldDrawArrows) {
return
}
if (transparentShots.size > faceIndex) {
for (s in transparentShots[faceIndex]) {
drawArrow(canvas, s, true)
}
}
if (shots.size > faceIndex) {
for (s in shots[faceIndex]) {
drawArrow(canvas, s, false)
}
}
if (focusedArrow != null) {
drawFocusedArrow(canvas, focusedArrow!!, faceIndex)
}
}
fun getZoneFromPoint(x: Float, y: Float): Int {
return model.getZoneFromPoint(x, y, arrowRadius)
}
private fun drawArrow(canvas: CanvasWrapper, shot: Shot, transparent: Boolean) {
var color = model.getContrastColor(shot.scoringRing)
if (transparent) {
color = 0x55000000 or (color and 0xFFFFFF)
}
paintFill.color = color
canvas.drawCircle(shot.x, shot.y, arrowRadius, paintFill)
}
fun setFocusedArrow(shot: Shot?) {
focusedArrow = shot
if (shot == null) {
setMid(0f, 0f)
} else {
setMid(shot.x, shot.y)
}
}
private fun drawFocusedArrow(canvas: CanvasWrapper, shot: Shot, drawFaceIndex: Int) {
if (shot.index % model.faceCount != drawFaceIndex) {
return
}
paintFill.color = -0xff6700
canvas.drawCircle(shot.x, shot.y, arrowRadius, paintFill)
// Draw cross
val lineLen = 2f * arrowRadius
paintFill.strokeWidth = 0.2f * arrowRadius
canvas.drawLine(shot.x - lineLen, shot.y, shot.x + lineLen, shot.y, paintFill)
canvas.drawLine(shot.x, shot.y - lineLen, shot.x, shot.y + lineLen, paintFill)
// Draw zone points
val zoneString = target.zoneToString(shot.scoringRing, shot.index)
val srcRect = RectF(shot.x - arrowRadius, shot.y - arrowRadius,
shot.x + arrowRadius, shot.y + arrowRadius)
canvas.drawText(zoneString, srcRect, paintText)
}
fun replaceShotsWith(shots: List<Shot>) {
for (i in this.shots.indices) {
this.shots[i].clear()
}
val map = shots.groupBy { (_, index) -> index % model.faceCount }
for ((key, value) in map) {
this.shots[key] = value.toMutableList()
}
notifyArrowSetChanged()
}
fun replacedTransparentShots(shots: List<Shot>) {
object : AsyncTask<Void, Void, Map<Int, List<Shot>>>() {
override fun doInBackground(vararg objects: Void): Map<Int, List<Shot>> {
return shots.groupBy { (_, index) -> index % model.faceCount }
}
override fun onPostExecute(map: Map<Int, List<Shot>>) {
super.onPostExecute(map)
for (shotList in transparentShots) {
shotList.clear()
}
for ((key, value) in map) {
transparentShots[key] = value.toMutableList()
}
notifyArrowSetChanged()
}
}.execute()
}
open fun notifyArrowSetChanged() {
invalidateSelf()
}
fun drawArrowsEnabled(enabled: Boolean) {
shouldDrawArrows = enabled
}
open fun cleanup() {
}
}
| gpl-2.0 | 714875998dd33e9227f3f70d6e8618ce | 32 | 89 | 0.616778 | 4.251375 | false | false | false | false |
DreierF/MyTargets | shared/src/main/java/de/dreier/mytargets/shared/targets/models/WA3Ring.kt | 1 | 2790 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets 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.
*
* MyTargets 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.
*/
package de.dreier.mytargets.shared.targets.models
import de.dreier.mytargets.shared.R
import de.dreier.mytargets.shared.models.Dimension
import de.dreier.mytargets.shared.models.Dimension.Unit.CENTIMETER
import de.dreier.mytargets.shared.targets.decoration.CenterMarkDecorator
import de.dreier.mytargets.shared.targets.scoringstyle.ScoringStyle
import de.dreier.mytargets.shared.targets.zone.CircularZone
import de.dreier.mytargets.shared.utils.Color.DARK_GRAY
import de.dreier.mytargets.shared.utils.Color.FLAMINGO_RED
import de.dreier.mytargets.shared.utils.Color.LEMON_YELLOW
open class WA3Ring internal constructor(id: Long, nameRes: Int, diameters: List<Dimension>) : TargetModelBase(
id = id,
nameRes = nameRes,
zones = listOf(
CircularZone(0.166f, LEMON_YELLOW, DARK_GRAY, 4),
CircularZone(0.334f, LEMON_YELLOW, DARK_GRAY, 4),
CircularZone(0.666f, LEMON_YELLOW, DARK_GRAY, 4),
CircularZone(1.0f, FLAMINGO_RED, DARK_GRAY, 4)
),
scoringStyles = listOf(
ScoringStyle(R.string.recurve_style_x_8, true, 10, 10, 9, 8),
ScoringStyle(R.string.recurve_style_10_8, false, 10, 10, 9, 8),
ScoringStyle(R.string.compound_style, false, 10, 9, 9, 8),
ScoringStyle(false, 11, 10, 9, 8),
ScoringStyle(true, 5, 5, 5, 4),
ScoringStyle(false, 9, 9, 9, 7)
),
diameters = diameters
) {
constructor() : this(
id = ID,
nameRes = R.string.wa_3_ring,
diameters = listOf(
Dimension(40f, CENTIMETER),
Dimension(60f, CENTIMETER),
Dimension(80f, CENTIMETER),
Dimension(92f, CENTIMETER),
Dimension(122f, CENTIMETER)
)
)
init {
realSizeFactor = 0.3f
decorator = CenterMarkDecorator(DARK_GRAY, 16.667f, 4, false)
}
override fun shouldDrawZone(zone: Int, scoringStyle: Int): Boolean {
// Do not draw second ring if we have a compound face
return !(scoringStyle == 1 && zone == 0) && !(scoringStyle == 2 && zone == 1)
}
companion object {
const val ID = 3L
}
}
| gpl-2.0 | ccca690e697f9b6d2bf6d14735c9192d | 37.75 | 110 | 0.636201 | 3.785617 | false | false | false | false |
xmartlabs/Android-Base-Project | mvvm/src/main/java/com/xmartlabs/bigbang/mvvm/result/ResultRxExtensions.kt | 1 | 3378 | package com.xmartlabs.bigbang.mvvm.result
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import io.reactivex.*
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import org.reactivestreams.Subscription
/** Transform a [Completable] into a [LiveData] of [Result]. */
fun Completable.toResult(): LiveData<Result<Nothing>> {
val source = MutableLiveData<Result<Nothing>>()
this
.observeOn(Schedulers.io())
.subscribe(object : CompletableObserver {
override fun onSubscribe(disposable: Disposable) {
source.value = Result.Loading
}
override fun onComplete() {
source.value = Result.Success(null)
}
override fun onError(throwable: Throwable) {
source.value = Result.Error(throwable)
}
})
return source
}
/** Transform a [Single] into a [LiveData] of [Result]. */
fun <T> Single<T>.toResult(): LiveData<Result<T>> {
val source = MutableLiveData<Result<T>>()
this
.observeOn(Schedulers.io())
.subscribe(object : SingleObserver<T> {
override fun onSubscribe(disposable: Disposable) {
source.value = Result.Loading
}
override fun onSuccess(t: T) {
source.value = Result.Success(null)
}
override fun onError(throwable: Throwable) {
source.value = Result.Error(throwable)
}
})
return source
}
/** Transform a [Observable] into a [LiveData] of [Result]. */
fun <T> Observable<T>.toResult(): LiveData<Result<T>> {
val source = MutableLiveData<Result<T>>()
this
.observeOn(Schedulers.io())
.subscribe(object : Observer<T> {
override fun onSubscribe(d: Disposable) {
source.value = Result.Loading
}
override fun onComplete() {}
override fun onNext(t: T) {
source.value = Result.Success(null)
}
override fun onError(throwable: Throwable) {
source.value = Result.Error(throwable)
}
})
return source
}
/** Transform a [Maybe] into a [LiveData] of [Result]. */
fun <T> Maybe<T>.toResult(): LiveData<Result<T>> {
val source = MutableLiveData<Result<T>>()
this
.observeOn(Schedulers.io())
.subscribe(object : MaybeObserver<T> {
override fun onComplete() {}
override fun onSubscribe(disposable: Disposable) {
source.value = Result.Loading
}
override fun onSuccess(t: T) {
source.value = Result.Success(null)
}
override fun onError(throwable: Throwable) {
source.value = Result.Error(throwable)
}
})
return source
}
/** Transform a [Flowable] into a [LiveData] of [Result]. */
fun <T> Flowable<T>.toResult(): LiveData<Result<T>> {
val source = MutableLiveData<Result<T>>()
this
.observeOn(Schedulers.io())
.subscribe(object : FlowableSubscriber<T> {
override fun onNext(t: T) {
source.value = Result.Success(null)
}
override fun onComplete() {}
override fun onSubscribe(subscription: Subscription) {
subscription.request(Long.MAX_VALUE)
source.value = Result.Loading
}
override fun onError(throwable: Throwable) {
source.value = Result.Error(throwable)
}
})
return source
}
| apache-2.0 | 300e145f87a2dfa8f2b3bc100261e054 | 27.15 | 63 | 0.623446 | 4.34749 | false | false | false | false |
georocket/georocket | src/main/kotlin/io/georocket/index/geojson/GeoJsonIdIndexerFactory.kt | 1 | 1861 | package io.georocket.index.geojson
import io.georocket.index.DatabaseIndex
import io.georocket.index.Indexer
import io.georocket.index.IndexerFactory
import io.georocket.query.Contains
import io.georocket.query.IndexQuery
import io.georocket.query.QueryCompiler
import io.georocket.query.QueryPart
import io.georocket.util.JsonStreamEvent
import io.georocket.util.StreamEvent
/**
* @author Tobias Dorra
*/
class GeoJsonIdIndexerFactory : IndexerFactory {
companion object {
const val GEOJSON_FEATURE_IDS = "geoJsonFeatureIds"
val validFieldNames = setOf("id", "geoJsonFeatureId")
}
override fun <T : StreamEvent> createIndexer(eventType: Class<T>): Indexer<T>? {
if (eventType.isAssignableFrom(JsonStreamEvent::class.java)) {
@Suppress("UNCHECKED_CAST")
return GeoJsonIdIndexer() as Indexer<T>
}
return null
}
private fun getIdFromQuery(queryPart: QueryPart): String? {
return if (queryPart.key == null) {
queryPart.value.toString()
} else if (queryPart.comparisonOperator == QueryPart.ComparisonOperator.EQ && validFieldNames.contains(queryPart.key)) {
queryPart.value.toString()
} else {
null
}
}
override fun getQueryPriority(queryPart: QueryPart): QueryCompiler.MatchPriority {
val queryFor = getIdFromQuery(queryPart)
return if (queryFor != null) {
QueryCompiler.MatchPriority.SHOULD
} else {
QueryCompiler.MatchPriority.NONE
}
}
override fun compileQuery(queryPart: QueryPart): IndexQuery? {
val queryFor = getIdFromQuery(queryPart)
return if (queryFor != null) {
Contains(GEOJSON_FEATURE_IDS, queryPart.value)
} else {
null
}
}
override fun getDatabaseIndexes(indexedFields: List<String>): List<DatabaseIndex> = listOf(
DatabaseIndex.Array(GEOJSON_FEATURE_IDS, "geo_json_feature_ids_array")
)
}
| apache-2.0 | be743eaee85212931387753df0ab0816 | 29.508197 | 124 | 0.726491 | 4.09011 | false | false | false | false |
Virtlink/aesi | paplj/src/main/kotlin/com/virtlink/paplj/parser/AstBuilder.kt | 1 | 11945 | package com.virtlink.paplj.parser
import com.google.inject.Inject
import com.virtlink.paplj.syntax.PapljAntlrLexer
import com.virtlink.paplj.syntax.PapljAntlrParser
import com.virtlink.paplj.syntax.PapljAntlrParserBaseVisitor
import com.virtlink.paplj.terms.*
import com.virtlink.terms.*
import org.antlr.v4.runtime.tree.RuleNode
import org.antlr.v4.runtime.tree.TerminalNode
class AstBuilder @Inject constructor(
private val termFactory: TermFactory)
: PapljAntlrParserBaseVisitor<ITerm>() {
override fun visitProgram(ctx: PapljAntlrParser.ProgramContext): ProgramTerm {
val id = visitQualifiedName(ctx.qualifiedName())
val imports = visitListOf(ctx.imports(), { visitImports(it) })
val types = visitListOf(ctx.type(), { visitType(it) })
val runExpr = visitMaybe(ctx.expr(), { visitExpr(it) })
return this.termFactory.createTerm(ProgramTerm.constructor, id, imports, types, runExpr)
}
override fun visitQualifiedName(ctx: PapljAntlrParser.QualifiedNameContext): StringTerm {
return this.termFactory.createString(ctx.ID().joinToString("."))
}
override fun visitQualifiedNameWithWildcard(ctx: PapljAntlrParser.QualifiedNameWithWildcardContext): Term {
// FIXME: This is a bit hacky and brittle.
val postfix = if (ctx.children.size == 2) ".*" else ""
return this.termFactory.createString(ctx.qualifiedName().ID().joinToString(".", postfix=postfix))
}
override fun visitImports(ctx: PapljAntlrParser.ImportsContext): ImportTerm {
val id = visitQualifiedNameWithWildcard(ctx.qualifiedNameWithWildcard())
return this.termFactory.createTerm(ImportTerm.constructor, id)
}
override fun visitType(ctx: PapljAntlrParser.TypeContext): TypeTerm {
val id = visitID(ctx.ID())
val extends = visitMaybe(ctx.qualifiedName(), { visitQualifiedName(it) })
val members = visitListOf(ctx.classMember(), { visitClassMember(it) })
return this.termFactory.createTerm(TypeTerm.constructor, id, extends, members)
}
override fun visitClassMember(ctx: PapljAntlrParser.ClassMemberContext): ClassMemberTerm
= object: PapljAntlrParserBaseVisitor<ClassMemberTerm>() {
override fun visitField(ctx: PapljAntlrParser.FieldContext): FieldTerm {
val type = [email protected](ctx.qualifiedName())
val name = visitID(ctx.ID())
return [email protected](FieldTerm.constructor, type, name)
}
override fun visitMethod(ctx: PapljAntlrParser.MethodContext): MethodTerm {
val type = [email protected](ctx.qualifiedName())
val name = visitID(ctx.ID())
val params = visitListOf(ctx.param(), { [email protected](it) })
val body = [email protected](ctx.block2())
return [email protected](MethodTerm.constructor, type, name, params, body)
}
}.visit(ctx)
override fun visitParam(ctx: PapljAntlrParser.ParamContext): ParamTerm {
val type = [email protected](ctx.qualifiedName())
val name = visitID(ctx.ID())
return this.termFactory.createTerm(ParamTerm.constructor, name, type)
}
override fun visitBinding(ctx: PapljAntlrParser.BindingContext): BindingTerm {
val type = [email protected](ctx.qualifiedName())
val name = visitID(ctx.ID())
val expression = visitExpr(ctx.expr())
return this.termFactory.createTerm(BindingTerm.constructor, name, type, expression)
}
override fun visitBlock2(ctx: PapljAntlrParser.Block2Context): Block2Term {
val expressions = visitListOf(ctx.expr(), { visitExpr(it) })
return this.termFactory.createTerm(Block2Term.constructor, expressions)
}
private fun visitExpr(ctx: PapljAntlrParser.ExprContext): ExprTerm
= object: PapljAntlrParserBaseVisitor<ExprTerm>() {
override fun visitParens(ctx: PapljAntlrParser.ParensContext): ExprTerm {
return visit(ctx.expr())
}
override fun visitBlock(ctx: PapljAntlrParser.BlockContext): Block2Term {
return [email protected](ctx.block2())
}
override fun visitVar(ctx: PapljAntlrParser.VarContext): VarTerm {
val id = visitID(ctx.ID())
return [email protected](VarTerm.constructor, id)
}
override fun visitCall(ctx: PapljAntlrParser.CallContext): CallTerm {
val name = visitID(ctx.ID())
val arguments = visitListOf(ctx.expr(), { [email protected](it) })
return [email protected](CallTerm.constructor, name, arguments)
}
override fun visitNew(ctx: PapljAntlrParser.NewContext): NewTerm {
val type = [email protected](ctx.qualifiedName())
return [email protected](NewTerm.constructor, type)
}
override fun visitNull(ctx: PapljAntlrParser.NullContext): NullTerm {
val type = [email protected](ctx.qualifiedName())
return [email protected](NullTerm.constructor, type)
}
override fun visitThis(ctx: PapljAntlrParser.ThisContext): ThisTerm {
return [email protected](ThisTerm.constructor)
}
override fun visitBool(ctx: PapljAntlrParser.BoolContext): BoolTerm {
return when (ctx.v.type) {
PapljAntlrLexer.TRUE -> [email protected](TrueTerm.constructor)
PapljAntlrLexer.FALSE -> [email protected](FalseTerm.constructor)
else -> throw RuntimeException("")
}
}
override fun visitNum(ctx: PapljAntlrParser.NumContext): NumTerm {
val value = visitINT(ctx.INT())
return [email protected](NumTerm.constructor, value)
}
override fun visitMember(ctx: PapljAntlrParser.MemberContext): MemberTerm {
val expr = [email protected](ctx.expr())
val name = visitID(ctx.ID())
return [email protected](MemberTerm.constructor, expr, name)
}
override fun visitMemberCall(ctx: PapljAntlrParser.MemberCallContext): MemberCallTerm {
val expr = [email protected](ctx.expr().first())
val name = visitID(ctx.ID())
val arguments = visitListOf(ctx.expr().drop(1), { [email protected](it) })
return [email protected](MemberCallTerm.constructor, expr, name, arguments)
}
override fun visitNegate(ctx: PapljAntlrParser.NegateContext): NegateTerm {
val expr = [email protected](ctx.expr())
return [email protected](NegateTerm.constructor, expr)
}
override fun visitNot(ctx: PapljAntlrParser.NotContext): NotTerm {
val expr = [email protected](ctx.expr())
return [email protected](NotTerm.constructor, expr)
}
override fun visitCast(ctx: PapljAntlrParser.CastContext): CastTerm {
val expr = [email protected](ctx.expr())
val type = [email protected](ctx.qualifiedName())
return [email protected](CastTerm.constructor, expr, type)
}
override fun visitMultiplicative(ctx: PapljAntlrParser.MultiplicativeContext): BinOpTerm {
return createBinOp(ctx.op.type, ctx.expr(0), ctx.expr(1))
}
override fun visitAdditive(ctx: PapljAntlrParser.AdditiveContext): BinOpTerm {
return createBinOp(ctx.op.type, ctx.expr(0), ctx.expr(1))
}
override fun visitCompare(ctx: PapljAntlrParser.CompareContext): BinOpTerm {
return createBinOp(ctx.op.type, ctx.expr(0), ctx.expr(1))
}
override fun visitAnd(ctx: PapljAntlrParser.AndContext): BinOpTerm {
return createBinOp(PapljAntlrLexer.AND, ctx.expr(0), ctx.expr(1))
}
override fun visitOr(ctx: PapljAntlrParser.OrContext): BinOpTerm {
return createBinOp(PapljAntlrLexer.OR, ctx.expr(0), ctx.expr(1))
}
private fun createBinOp(op: Int, lhs: PapljAntlrParser.ExprContext, rhs: PapljAntlrParser.ExprContext): BinOpTerm {
val constructor: ITermConstructor = when (op) {
PapljAntlrLexer.MUL -> MulTerm.constructor
PapljAntlrLexer.DIV -> DivTerm.constructor
PapljAntlrLexer.PLUS -> AddTerm.constructor
PapljAntlrLexer.MIN -> SubTerm.constructor
PapljAntlrLexer.EQ -> EqTerm.constructor
PapljAntlrLexer.NEQ -> NeqTerm.constructor
PapljAntlrLexer.LT -> LtTerm.constructor
PapljAntlrLexer.AND -> AndTerm.constructor
PapljAntlrLexer.OR -> OrTerm.constructor
else -> throw RuntimeException("")
}
val lhsExpr = [email protected](lhs)
val rhsExpr = [email protected](rhs)
return [email protected](constructor, lhsExpr, rhsExpr) as BinOpTerm
}
override fun visitAssignment(ctx: PapljAntlrParser.AssignmentContext): AssignTerm {
val lhsExpr = [email protected](ctx.expr(0))
val rhsExpr = [email protected](ctx.expr(1))
return [email protected](AssignTerm.constructor, lhsExpr, rhsExpr)
}
override fun visitLet(ctx: PapljAntlrParser.LetContext): LetTerm {
val bindings = visitListOf(ctx.binding(), { [email protected](it) })
val expr = [email protected](ctx.expr())
return [email protected](LetTerm.constructor, bindings, expr)
}
override fun visitIf(ctx: PapljAntlrParser.IfContext): IfTerm {
val condition = [email protected](ctx.expr(0))
val onTrue = [email protected](ctx.expr(1))
val onFalse = [email protected](ctx.expr(2))
return [email protected](IfTerm.constructor, condition, onTrue, onFalse)
}
}.visit(ctx)
/**
* Visits an ID.
*
* @param node The node.
* @return The string term.
*/
private fun visitID(node: TerminalNode): StringTerm {
assert(node.symbol.type == PapljAntlrLexer.ID)
return this.termFactory.createString(node.symbol.text)
}
/**
* Visits an integer.
*
* @param node The node.
* @return The integer term.
*/
private fun visitINT(node: TerminalNode): IntTerm {
assert(node.symbol.type == PapljAntlrLexer.ID)
val value = Integer.parseInt(node.symbol.text)
return this.termFactory.createInt(value)
}
/**
* Visits a list of nodes and constructs a list of terms.
*
* @param nodes The nodes.
* @param transform The transform function.
* @return The list term.
*/
private fun <TIn: RuleNode, TOut: ITerm> visitListOf(nodes: List<TIn>, transform: (TIn) -> TOut): ListTerm<TOut> {
return this.termFactory.createList(nodes.map { transform(it) })
}
/**
* Visits an optional node and constructs an option term.
*
* @param node The node; or null.
* @param transform The transform function.
* @return The option term.
*/
private fun <TIn: RuleNode, TOut: ITerm> visitMaybe(node: TIn?, transform: (TIn) -> TOut): OptionTerm<TOut> {
return this.termFactory.createOption(if (node != null) transform(node) else null)
}
} | apache-2.0 | 3191094812433146bea8f81cac0739c4 | 44.079245 | 123 | 0.671746 | 4.164923 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/internal/ui/uiDslTestAction/UiDslTestAction.kt | 2 | 11743 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.ui.uiDslTestAction
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.Disposer
import com.intellij.ui.CollectionComboBoxModel
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBTabbedPane
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.ui.dsl.gridLayout.VerticalAlign
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.event.ItemEvent
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.JScrollPane
import javax.swing.border.Border
internal class UiDslTestAction : DumbAwareAction("Show UI DSL Tests") {
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun actionPerformed(e: AnActionEvent) {
UiDslTestDialog(e.project).show()
}
}
@Suppress("DialogTitleCapitalization")
private class UiDslTestDialog(project: Project?) : DialogWrapper(project, null, true, IdeModalityType.IDE, false) {
init {
title = "UI DSL Tests"
init()
}
override fun createContentPaneBorder(): Border? {
return null
}
override fun createCenterPanel(): JComponent {
val result = JBTabbedPane()
result.minimumSize = Dimension(300, 200)
result.preferredSize = Dimension(800, 600)
result.addTab("Labels", JScrollPane(LabelsPanel().panel))
result.addTab("Text Fields", createTextFields())
result.addTab("Comments", JScrollPane(createCommentsPanel()))
result.addTab("Text MaxLine", createTextMaxLinePanel())
result.addTab("Groups", JScrollPane(GroupsPanel().panel))
result.addTab("Segmented Button", SegmentedButtonPanel().panel)
result.addTab("Visible/Enabled", createVisibleEnabled())
result.addTab("Cells With Sub-Panels", createCellsWithPanels())
result.addTab("Placeholder", PlaceholderPanel(myDisposable).panel)
result.addTab("Resizable Rows", createResizableRows())
result.addTab("Others", OthersPanel().panel)
result.addTab("Deprecated Api", JScrollPane(DeprecatedApiPanel().panel))
result.addTab("CheckBox/RadioButton", CheckBoxRadioButtonPanel().panel)
return result
}
fun createTextFields(): JPanel {
val result = panel {
row("Text field 1:") {
textField()
.columns(10)
.comment("columns = 10")
}
row("Text field 2:") {
textField()
.horizontalAlign(HorizontalAlign.FILL)
.comment("horizontalAlign(HorizontalAlign.FILL)")
}
row("Int text field 1:") {
intTextField()
.columns(10)
.comment("columns = 10")
}
row("Int text field 2:") {
intTextField(range = 0..1000)
.comment("range = 0..1000")
}
row("Int text field 2:") {
intTextField(range = 0..1000, keyboardStep = 100)
.comment("range = 0..1000, keyboardStep = 100")
}
}
val disposable = Disposer.newDisposable()
result.registerValidators(disposable)
Disposer.register(myDisposable, disposable)
return result
}
fun createVisibleEnabled(): JPanel {
val entities = mutableMapOf<String, Any>()
return panel {
row {
label("<html>Example test cases:<br>" +
"1. Hide Group, hide/show sub elements from Group<br>" +
" * they shouldn't be visible until Group becomes visible<br>" +
" * after Group becomes shown visible state of sub elements correspondent to checkboxes<br>" +
"2. Similar to 1 test case but with enabled state")
}
row {
panel {
entities["Row 1"] = row("Row 1") {
entities["textField1"] = textField()
.text("textField1")
}
entities["Group"] = group("Group") {
entities["Row 2"] = row("Row 2") {
entities["textField2"] = textField()
.text("textField2")
.comment("Comment with a <a>link</a>")
}
entities["Row 3"] = row("Row 3") {
entities["panel"] = panel {
row {
label("Panel inside row3")
}
entities["Row 4"] = row("Row 4") {
entities["textField3"] = textField()
.text("textField3")
}
}
}
}
}.verticalAlign(VerticalAlign.TOP)
panel {
row {
label("Visible/Enabled")
.bold()
}
for ((name, entity) in entities.toSortedMap()) {
row(name) {
checkBox("visible")
.applyToComponent {
isSelected = true
addItemListener {
when (entity) {
is Cell<*> -> entity.visible(this.isSelected)
is Row -> entity.visible(this.isSelected)
is Panel -> entity.visible(this.isSelected)
}
}
}
checkBox("enabled")
.applyToComponent {
isSelected = true
addItemListener {
when (entity) {
is Cell<*> -> entity.enabled(this.isSelected)
is Row -> entity.enabled(this.isSelected)
is Panel -> entity.enabled(this.isSelected)
}
}
}
}
}
}.horizontalAlign(HorizontalAlign.RIGHT)
}
group("Control visibility by visibleIf") {
lateinit var checkBoxText: Cell<JBCheckBox>
lateinit var checkBoxRow: Cell<JBCheckBox>
row {
checkBoxRow = checkBox("Row")
.applyToComponent { isSelected = true }
checkBoxText = checkBox("textField")
.applyToComponent { isSelected = true }
}
row("visibleIf test row") {
textField()
.text("textField")
.visibleIf(checkBoxText.selected)
label("some label")
}.visibleIf(checkBoxRow.selected)
}
}
}
fun createCellsWithPanels(): JPanel {
return panel {
row("Row") {
textField()
.columns(20)
}
row("Row 2") {
val subPanel = com.intellij.ui.dsl.builder.panel {
row {
textField()
.columns(20)
.text("Sub-Paneled Row")
}
}
cell(subPanel)
}
row("Row 3") {
textField()
.horizontalAlign(HorizontalAlign.FILL)
}
row("Row 4") {
val subPanel = com.intellij.ui.dsl.builder.panel {
row {
textField()
.horizontalAlign(HorizontalAlign.FILL)
.text("Sub-Paneled Row")
}
}
cell(subPanel)
.horizontalAlign(HorizontalAlign.FILL)
}
}
}
fun createResizableRows(): JPanel {
return panel {
for (rowLayout in RowLayout.values()) {
row(rowLayout.name) {
textArea()
.horizontalAlign(HorizontalAlign.FILL)
.verticalAlign(VerticalAlign.FILL)
}.layout(rowLayout)
.resizableRow()
}
}
}
fun createCommentsPanel(): JPanel {
var type = CommentComponentType.CHECKBOX
val placeholder = JPanel(BorderLayout())
fun applyType() {
val builder = CommentPanelBuilder(type)
placeholder.removeAll()
placeholder.add(builder.build(), BorderLayout.CENTER)
}
val result = panel {
row("Component type") {
comboBox(CollectionComboBoxModel(CommentComponentType.values().asList()))
.applyToComponent {
addItemListener {
if (it.stateChange == ItemEvent.SELECTED) {
type = it?.item as? CommentComponentType ?: CommentComponentType.CHECKBOX
applyType()
placeholder.revalidate()
}
}
}
}
row {
cell(placeholder)
}
}
applyType()
return result
}
fun createTextMaxLinePanel(): JPanel {
val longLine = (1..4).joinToString { "A very long string with a <a>link</a>" }
val string = "$longLine<br>$longLine"
return panel {
row("comment(string):") {
comment(string)
}
row("comment(string, DEFAULT_COMMENT_WIDTH):") {
comment(string, maxLineLength = DEFAULT_COMMENT_WIDTH)
}
row("comment(string, MAX_LINE_LENGTH_NO_WRAP):") {
comment(string, maxLineLength = MAX_LINE_LENGTH_NO_WRAP)
}
row("text(string):") {
text(string)
}
row("text(string, DEFAULT_COMMENT_WIDTH):") {
text(string, maxLineLength = DEFAULT_COMMENT_WIDTH)
}
row("text(string, MAX_LINE_LENGTH_NO_WRAP):") {
text(string, maxLineLength = MAX_LINE_LENGTH_NO_WRAP)
}
}
}
}
@Suppress("DialogTitleCapitalization")
private class CommentPanelBuilder(val type: CommentComponentType) {
fun build(): DialogPanel {
return panel {
for (rowLayout in RowLayout.values()) {
val labelAligned = rowLayout == RowLayout.LABEL_ALIGNED
group("rowLayout = $rowLayout") {
row("With Label:") {
customComponent("Long Component1")
.comment("Component1 comment is aligned with Component1")
customComponent("Component2")
button("button") { }
}.layout(rowLayout)
row("With Long Label:") {
customComponent("Component1")
customComponent("Long Component2")
.comment(
if (labelAligned) "LABEL_ALIGNED: Component2 comment is aligned with Component1 (cell[1]), hard to fix, rare use case"
else "Component2 comment is aligned with Component2")
button("button") { }
}.layout(rowLayout)
row("With Very Long Label:") {
customComponent("Component1")
customComponent("Long Component2")
button("button") { }
.comment(if (labelAligned) "LABEL_ALIGNED: Button comment is aligned with Component1 (cell[1]), hard to fix, rare use case"
else "Button comment is aligned with button")
}.layout(rowLayout)
if (labelAligned) {
row {
label("LABEL_ALIGNED: in the next row only two first comments are shown")
}
}
row {
customComponent("Component1 extra width")
.comment("Component1 comment")
customComponent("Component2 extra width")
.comment("Component2 comment<br>second line")
customComponent("One More Long Component3")
.comment("Component3 comment")
button("button") { }
.comment("Button comment")
}.layout(rowLayout)
}
}
}
}
private fun Row.customComponent(text: String): Cell<JComponent> {
return when (type) {
CommentComponentType.CHECKBOX -> checkBox(text)
CommentComponentType.TEXT_FIELD -> textField().text(text)
CommentComponentType.TEXT_FIELD_WITH_BROWSE_BUTTON -> textFieldWithBrowseButton().text(text)
}
}
}
private enum class CommentComponentType {
CHECKBOX,
TEXT_FIELD,
TEXT_FIELD_WITH_BROWSE_BUTTON
}
| apache-2.0 | 2fa014f261dac8245e6c546bafd48115 | 31.084699 | 137 | 0.583922 | 4.719855 | false | false | false | false |
google/intellij-community | plugins/eclipse/src/org/jetbrains/idea/eclipse/config/EmlFileSaver.kt | 5 | 8470 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.eclipse.config
import com.intellij.openapi.components.PathMacroMap
import com.intellij.openapi.roots.JavadocOrderRootType
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator
import com.intellij.workspaceModel.ide.impl.virtualFile
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.bridgeEntities.api.*
import com.intellij.workspaceModel.storage.bridgeEntities.asJavaSourceRoot
import org.jdom.Element
import org.jetbrains.annotations.NonNls
import org.jetbrains.idea.eclipse.IdeaXml.*
import org.jetbrains.idea.eclipse.conversion.EPathUtil
import org.jetbrains.idea.eclipse.conversion.IdeaSpecificSettings
import org.jetbrains.jps.model.serialization.java.JpsJavaModelSerializerExtension
import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer
/**
* Saves additional module configuration from [ModuleEntity] to *.eml file
*/
internal class EmlFileSaver(private val module: ModuleEntity,
private val entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>,
private val pathShortener: ModulePathShortener,
private val moduleReplacePathMacroMap: PathMacroMap,
private val projectReplacePathMacroMap: PathMacroMap) {
fun saveEml(): Element? {
val root = Element(COMPONENT_TAG)
saveCustomJavaSettings(root)
saveContentRoots(root)
@Suppress("UNCHECKED_CAST")
val moduleLibraries = (entities[LibraryEntity::class.java] as List<LibraryEntity>? ?: emptyList()).associateBy { it.name }
val libLevels = LinkedHashMap<String, String>()
module.dependencies.forEach { dep ->
when (dep) {
is ModuleDependencyItem.Exportable.ModuleDependency -> {
if (dep.scope != ModuleDependencyItem.DependencyScope.COMPILE) {
root.addContent(Element("module").setAttribute("name", dep.module.name).setAttribute("scope", dep.scope.name))
}
}
is ModuleDependencyItem.InheritedSdkDependency -> {
root.setAttribute(IdeaSpecificSettings.INHERIT_JDK, true.toString())
}
is ModuleDependencyItem.SdkDependency -> {
root.setAttribute("jdk", dep.sdkName)
root.setAttribute("jdk_type", dep.sdkType)
}
is ModuleDependencyItem.Exportable.LibraryDependency -> {
val libTag = Element("lib")
val library = moduleLibraries[dep.library.name]
val libName = LibraryNameGenerator.getLegacyLibraryName(dep.library) ?: generateLibName(library)
libTag.setAttribute("name", libName)
libTag.setAttribute("scope", dep.scope.name)
when (val tableId = dep.library.tableId) {
is LibraryTableId.ModuleLibraryTableId -> {
if (library != null) {
val srcRoots = library.roots.filter { it.type.name == OrderRootType.SOURCES.name() }
val eclipseUrl = srcRoots.firstOrNull()?.url?.url?.substringBefore(JarFileSystem.JAR_SEPARATOR)
srcRoots.forEach {
val url = it.url.url
val srcTag = Element(IdeaSpecificSettings.SRCROOT_ATTR).setAttribute("url", url)
if (!EPathUtil.areUrlsPointTheSame(url, eclipseUrl)) {
srcTag.setAttribute(IdeaSpecificSettings.SRCROOT_BIND_ATTR, false.toString())
}
libTag.addContent(srcTag)
}
library.roots.filter { it.type.name == "JAVADOC" }.drop(1).forEach {
libTag.addContent(Element(IdeaSpecificSettings.JAVADOCROOT_ATTR).setAttribute("url", it.url.url))
}
saveModuleRelatedRoots(libTag, library, OrderRootType.SOURCES, IdeaSpecificSettings.RELATIVE_MODULE_SRC)
saveModuleRelatedRoots(libTag, library, OrderRootType.CLASSES, IdeaSpecificSettings.RELATIVE_MODULE_CLS)
saveModuleRelatedRoots(libTag, library, JavadocOrderRootType.getInstance(), IdeaSpecificSettings.RELATIVE_MODULE_JAVADOC)
}
}
is LibraryTableId.ProjectLibraryTableId -> libLevels[dep.library.name] = LibraryTablesRegistrar.PROJECT_LEVEL
is LibraryTableId.GlobalLibraryTableId -> {
if (tableId.level != LibraryTablesRegistrar.APPLICATION_LEVEL) {
libLevels[dep.library.name] = tableId.level
}
}
}
if (libTag.children.isNotEmpty() || dep.scope != ModuleDependencyItem.DependencyScope.COMPILE) {
root.addContent(libTag)
}
}
else -> {}
}
}
if (libLevels.isNotEmpty()) {
val levelsTag = Element("levels")
for ((name, level) in libLevels) {
levelsTag.addContent(Element("level").setAttribute("name", name).setAttribute("value", level))
}
root.addContent(levelsTag)
}
moduleReplacePathMacroMap.substitute(root, SystemInfo.isFileSystemCaseSensitive)
return if (JDOMUtil.isEmpty(root)) null else root
}
private fun saveModuleRelatedRoots(libTag: Element, library: LibraryEntity, type: OrderRootType, tagName: @NonNls String) {
library.roots.filter { it.type.name == type.name() }.forEach {
val file = it.url.virtualFile
val localFile = if (file?.fileSystem is JarFileSystem) JarFileSystem.getInstance().getVirtualFileForJar(file) else file
if (localFile != null && pathShortener.isUnderContentRoots(localFile)) {
libTag.addContent(Element(tagName).setAttribute(IdeaSpecificSettings.PROJECT_RELATED, projectReplacePathMacroMap.substitute(it.url.url, SystemInfo.isFileSystemCaseSensitive)))
}
}
}
private fun generateLibName(library: LibraryEntity?): String {
val firstRoot = library?.roots?.firstOrNull { it.type.name == OrderRootType.CLASSES.name() }?.url
val file = firstRoot?.virtualFile
val fileForJar = JarFileSystem.getInstance().getVirtualFileForJar(file)
if (fileForJar != null) return fileForJar.name
return file?.name ?: "Empty Library"
}
private fun saveContentRoots(root: Element) {
module.contentRoots.forEach { contentRoot ->
val contentRootTag = Element(CONTENT_ENTRY_TAG).setAttribute(URL_ATTR, contentRoot.url.url)
contentRoot.sourceRoots.forEach { sourceRoot ->
if (sourceRoot.rootType == JpsModuleRootModelSerializer.JAVA_TEST_ROOT_TYPE_ID) {
contentRootTag.addContent(Element(TEST_FOLDER_TAG).setAttribute(URL_ATTR, sourceRoot.url.url))
}
val packagePrefix = sourceRoot.asJavaSourceRoot()?.packagePrefix
if (!packagePrefix.isNullOrEmpty()) {
contentRootTag.addContent(Element(PACKAGE_PREFIX_TAG).setAttribute(URL_ATTR, sourceRoot.url.url)
.setAttribute(PACKAGE_PREFIX_VALUE_ATTR, packagePrefix))
}
}
val rootFile = contentRoot.url.virtualFile
contentRoot.excludedUrls.forEach { excluded ->
val excludedFile = excluded.virtualFile
if (rootFile == null || excludedFile == null || VfsUtilCore.isAncestor(rootFile, excludedFile, false)) {
contentRootTag.addContent(Element(EXCLUDE_FOLDER_TAG).setAttribute(URL_ATTR, excluded.url))
}
}
if (!JDOMUtil.isEmpty(contentRootTag)) {
root.addContent(contentRootTag)
}
}
}
private fun saveCustomJavaSettings(root: Element) {
module.javaSettings?.let { javaSettings ->
javaSettings.compilerOutputForTests?.let { testOutput ->
root.addContent(Element(OUTPUT_TEST_TAG).setAttribute(URL_ATTR, testOutput.url))
}
if (javaSettings.inheritedCompilerOutput) {
root.setAttribute(JpsJavaModelSerializerExtension.INHERIT_COMPILER_OUTPUT_ATTRIBUTE, true.toString())
}
if (javaSettings.excludeOutput) {
root.addContent(Element(EXCLUDE_OUTPUT_TAG))
}
javaSettings.languageLevelId?.let {
root.setAttribute("LANGUAGE_LEVEL", it)
}
}
}
} | apache-2.0 | d6e4b7d6c0fb9e038c8fb4e223ea5165 | 49.12426 | 183 | 0.692208 | 4.777214 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/util/FileUtil.kt | 1 | 2498 | package org.jetbrains.haskell.util
import java.io.File
import java.io.BufferedReader
import java.io.Reader
import java.io.FileReader
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.InputStream
fun joinPath(first: String, vararg more: String): String {
var result = first
for (str in more) {
result += File.separator + str
}
return result
}
fun deleteRecursive(path: File) {
val files = path.listFiles()
if (files != null) {
for (file in files) {
if (file.isDirectory) {
deleteRecursive(file)
file.delete()
} else {
file.delete()
}
}
}
path.delete()
}
fun copyFile(iStream: InputStream, destination: File) {
val oStream = FileOutputStream(destination)
try {
val buffer = ByteArray(1024 * 16)
var length: Int
while (true ) {
length = iStream.read(buffer)
if (length <= 0) {
break
}
oStream.write(buffer, 0, length)
}
} finally {
iStream.close()
oStream.close()
}
}
fun getRelativePath(base: String, path: String): String {
val bpath = File(base).canonicalPath
val fpath = File(path).canonicalPath
if (fpath.startsWith(bpath)) {
return fpath.substring(bpath.length + 1)
} else {
throw RuntimeException("Base path " + base + "is wrong to " + path)
}
}
fun readLines(file: File): Iterable<String> {
return object : Iterable<String> {
override fun iterator(): Iterator<String> {
val br = BufferedReader(FileReader(file))
return object : Iterator<String> {
var reader: BufferedReader? = br
var line: String? = null
fun fetch(): String? {
if (line == null) {
line = reader?.readLine()
}
if (line == null && reader != null) {
reader?.close()
reader == null
}
return line
}
override fun next(): String {
val result = fetch()
line = null
return result!!
}
override fun hasNext(): Boolean {
return fetch() != null
}
}
}
}
} | apache-2.0 | ab153c4cba9ca702bc373fa791042ae7 | 24.762887 | 75 | 0.498799 | 4.686679 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/MoveMemberOutOfCompanionObjectIntention.kt | 1 | 5154 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.refactoring.getUsageContext
import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass
import org.jetbrains.kotlin.idea.util.hasJvmFieldAnnotation
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
import org.jetbrains.kotlin.util.findCallableMemberBySignature
class MoveMemberOutOfCompanionObjectIntention : MoveMemberOutOfObjectIntention(KotlinBundle.lazyMessage("move.out.of.companion.object")) {
override fun addConflicts(element: KtNamedDeclaration, conflicts: MultiMap<PsiElement, String>) {
val targetClass = element.containingClassOrObject?.containingClassOrObject ?: return
val targetClassDescriptor = runReadAction { targetClass.unsafeResolveToDescriptor() as ClassDescriptor }
val refsRequiringClassInstance =
element.project.runSynchronouslyWithProgress(KotlinBundle.message("searching.for.0", element.name.toString()), true) {
runReadAction {
ReferencesSearch
.search(element)
.mapNotNull { it.element }
.filter {
if (it !is KtElement) return@filter true
val resolvedCall = it.resolveToCall() ?: return@filter false
val dispatchReceiver = resolvedCall.dispatchReceiver ?: return@filter false
if (dispatchReceiver !is ImplicitClassReceiver) return@filter true
it.parents
.filterIsInstance<KtClassOrObject>()
.none {
val classDescriptor = it.resolveToDescriptorIfAny()
if (classDescriptor != null && classDescriptor.isSubclassOf(targetClassDescriptor)) return@none true
if (it.isTopLevel() || it is KtObjectDeclaration || (it is KtClass && !it.isInner())) return@filter true
false
}
}
}
} ?: return
for (refElement in refsRequiringClassInstance) {
val context = refElement.getUsageContext()
val message = KotlinBundle.message(
"0.in.1.will.require.class.instance",
refElement.text,
RefactoringUIUtil.getDescription(context, false)
)
conflicts.putValue(refElement, message)
}
runReadAction {
val callableDescriptor = element.unsafeResolveToDescriptor() as CallableMemberDescriptor
targetClassDescriptor.findCallableMemberBySignature(callableDescriptor)?.let {
DescriptorToSourceUtilsIde.getAnyDeclaration(element.project, it)
}?.let {
conflicts.putValue(
it,
KotlinBundle.message(
"class.0.already.contains.1",
targetClass.name.toString(),
RefactoringUIUtil.getDescription(it, false)
)
)
}
}
}
override fun getDestination(element: KtNamedDeclaration) = element.containingClassOrObject!!.containingClassOrObject!!
override fun applicabilityRange(element: KtNamedDeclaration): TextRange? {
if (element !is KtNamedFunction && element !is KtProperty && element !is KtClassOrObject) return null
val container = element.containingClassOrObject
if (!(container is KtObjectDeclaration && container.isCompanion())) return null
val containingClassOrObject = container.containingClassOrObject ?: return null
if (containingClassOrObject.isInterfaceClass() && element.hasJvmFieldAnnotation()) return null
return element.nameIdentifier?.textRange
}
} | apache-2.0 | 9c3858515e3a3466995135f9ac0dde52 | 52.697917 | 158 | 0.673846 | 5.930955 | false | false | false | false |
stevesea/RPGpad | adventuresmith-core/src/main/kotlin/org/stevesea/adventuresmith/core/dice_roller/Dice.kt | 2 | 7982 | /*
* Copyright (c) 2017 Steve Christensen
*
* This file is part of Adventuresmith.
*
* Adventuresmith 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.
*
* Adventuresmith 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 Adventuresmith. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.stevesea.adventuresmith.core.dice_roller
import com.github.salomonbrys.kodein.Kodein
import com.github.salomonbrys.kodein.bind
import com.github.salomonbrys.kodein.instance
import com.github.salomonbrys.kodein.provider
import com.github.salomonbrys.kodein.singleton
import org.stevesea.adventuresmith.core.Generator
import org.stevesea.adventuresmith.core.GeneratorMetaDto
import org.stevesea.adventuresmith.core.getFinalPackageName
import java.text.NumberFormat
import java.util.Locale
object DiceConstants {
val GROUP = getFinalPackageName(this.javaClass)
val regularDice =
listOf(
"1d3",
"1d4",
"1d6",
"1d8",
"1d10",
"1d12",
"1d20",
"1d30",
"1d100"
).map { "$GROUP/$it" to it }.toMap()
val fudgeDice = mapOf(
"$GROUP/NdF_1" to "Fudge Dice #1",
"$GROUP/NdF_2" to "Fudge Dice #2"
)
val explodingDice = mapOf(
"$GROUP/XdY!_1" to "Exploding Dice #1",
"$GROUP/XdY!_2" to "Exploding Dice #2",
"$GROUP/XdY!_3" to "Exploding Dice #3"
)
// if we just want to roll dice, these could just be in the 'regularDice' above. But, i like
// showing the individual rolls too
val multDice = mapOf(
"$GROUP/2d6" to Pair(2, "1d6"),
"$GROUP/3d6" to Pair(3, "1d6"),
"$GROUP/4d4" to Pair(4, "1d4")
)
val d20adv = "$GROUP/1d20 advantage"
val d20disadv = "$GROUP/1d20 disadvantage"
val customizableDice = mapOf(
"$GROUP/xdy_z_1" to "Custom Dice #1",
"$GROUP/xdy_z_2" to "Custom Dice #2",
"$GROUP/xdy_z_3" to "Custom Dice #3",
"$GROUP/xdy_z_4" to "Custom Dice #4",
"$GROUP/xdy_z_5" to "Custom Dice #5",
"$GROUP/xdy_z_6" to "Custom Dice #6"
)
val eoteDice = mapOf(
"$GROUP/eote_1" to "EotE Dice #1",
"$GROUP/eote_2" to "EotE Dice #2",
"$GROUP/eote_3" to "EotE Dice #3"
)
val myzDice = mapOf(
"$GROUP/myz_1" to "MYZ Dice #1",
"$GROUP/myz_2" to "MYZ Dice #2",
"$GROUP/myz_3" to "MYZ Dice #3"
)
val coriolisDice = mapOf(
"$GROUP/coriolis_1" to "Coriolis Dice #1",
"$GROUP/coriolis_2" to "Coriolis Dice #2",
"$GROUP/coriolis_3" to "Coriolis Dice #3"
)
val generators = listOf(
DiceConstants.regularDice.keys,
DiceConstants.multDice.keys,
listOf(
DiceConstants.d20adv,
DiceConstants.d20disadv
),
DiceConstants.customizableDice.keys,
DiceConstants.fudgeDice.keys,
DiceConstants.explodingDice.keys,
DiceConstants.eoteDice.keys,
DiceConstants.myzDice.keys,
DiceConstants.coriolisDice.keys
).flatten()
}
val diceModule = Kodein.Module {
// simple rolls
DiceConstants.regularDice.forEach {
bind<Generator>(it.key) with provider {
object : Generator {
override fun getId(): String {
return it.key
}
override fun getMetadata(locale: Locale): GeneratorMetaDto {
return GeneratorMetaDto(name = it.value)
}
val diceParser: DiceParser = instance()
override fun generate(locale: Locale, input: Map<String, String>?): String {
val nf = NumberFormat.getInstance(locale)
return "${it.value}: <strong>${nf.format(diceParser.roll(it.value))}</strong>"
}
}
}
}
// mutliple rolls
DiceConstants.multDice.forEach {
bind<Generator>(it.key) with provider {
object : Generator {
override fun getId(): String {
return it.key
}
override fun getMetadata(locale: Locale): GeneratorMetaDto {
return GeneratorMetaDto(name = it.key.split("/")[1])
}
val diceParser: DiceParser = instance()
override fun generate(locale: Locale, input: Map<String, String>?): String {
val nf = NumberFormat.getInstance(locale)
val rolls = diceParser.rollN(it.value.second, it.value.first)
val sum = rolls.sum()
return "${it.key.split("/")[1]}: <strong>${nf.format(sum)}</strong> <small>${rolls.map { nf.format(it) }}</small>"
}
}
}
}
bind<Generator>(DiceConstants.d20adv) with provider {
object : Generator {
val diceParser: DiceParser = instance()
override fun getId(): String {
return DiceConstants.d20adv
}
override fun generate(locale: Locale, input: Map<String, String>?): String {
val nf = NumberFormat.getInstance(locale)
val rolls = diceParser.rollN("1d20", 2)
val best = rolls.max()
return "2d20 Advantage: <strong>${nf.format(best)}</strong> <small>$rolls</small>"
}
override fun getMetadata(locale: Locale): GeneratorMetaDto {
return GeneratorMetaDto(name = "2d20 Advantage")
}
}
}
bind<Generator>(DiceConstants.d20disadv) with provider {
object : Generator {
val diceParser: DiceParser = instance()
override fun getId(): String {
return DiceConstants.d20disadv
}
override fun generate(locale: Locale, input: Map<String, String>?): String {
val nf = NumberFormat.getInstance(locale)
val rolls = diceParser.rollN("1d20", 2)
val worst = rolls.min()
return "2d20 Disadvantage: <strong>${nf.format(worst)}</strong> <small>$rolls</small>"
}
override fun getMetadata(locale: Locale): GeneratorMetaDto {
return GeneratorMetaDto(name = "2d20 Disadvantage")
}
}
}
DiceConstants.customizableDice.forEach {
bind<Generator>(it.key) with provider {
CustomizeableDiceGenerator(it.key, it.value, instance())
}
}
DiceConstants.explodingDice.forEach {
bind<Generator>(it.key) with provider {
ExplodingDiceGenerator(it.key, it.value, instance())
}
}
DiceConstants.fudgeDice.forEach {
bind<Generator>(it.key) with provider {
FudgeDiceGenerator(it.key, it.value, instance())
}
}
DiceConstants.eoteDice.forEach {
bind<Generator>(it.key) with provider {
EotEDiceGenerator(it.key, it.value, instance())
}
}
DiceConstants.myzDice.forEach {
bind<Generator>(it.key) with provider {
MYZDiceGenerator(it.key, it.value, instance())
}
}
DiceConstants.coriolisDice.forEach {
bind<Generator>(it.key) with provider {
CoriolisDiceGenerator(it.key, it.value, instance())
}
}
bind<DiceParser>() with singleton {
DiceParser(kodein)
}
}
| gpl-3.0 | dd5c560709223177f07018b5cdeaeee2 | 32.965957 | 134 | 0.573165 | 3.882296 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/jvm/test/exceptions/StackTraceRecoveryNestedTest.kt | 1 | 2450 | /*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("DeferredResultUnused")
package kotlinx.coroutines.exceptions
import kotlinx.coroutines.*
import org.junit.Test
import kotlin.test.*
class StackTraceRecoveryNestedTest : TestBase() {
@Test
fun testNestedAsync() = runTest {
val rootAsync = async(NonCancellable) {
expect(1)
// Just a noise for unwrapping
async {
expect(2)
delay(Long.MAX_VALUE)
}
// Do not catch, fail on cancellation
async {
expect(3)
async {
expect(4)
delay(Long.MAX_VALUE)
}
async {
expect(5)
// 1) await(), catch, verify and rethrow
try {
val nested = async {
expect(6)
throw RecoverableTestException()
}
nested.awaitNested()
} catch (e: RecoverableTestException) {
expect(7)
e.verifyException(
"await\$suspendImpl",
"awaitNested",
"\$testNestedAsync\$1\$rootAsync\$1\$2\$2.invokeSuspend"
)
// Just rethrow it
throw e
}
}
}
}
try {
rootAsync.awaitRootLevel()
} catch (e: RecoverableTestException) {
e.verifyException("awaitRootLevel")
finish(8)
}
}
private suspend fun Deferred<*>.awaitRootLevel() {
await()
assertTrue(true)
}
private suspend fun Deferred<*>.awaitNested() {
await()
assertTrue(true)
}
private fun RecoverableTestException.verifyException(vararg expectedTraceElements: String) {
// It is "recovered" only once
assertEquals(1, depth())
val stacktrace = stackTrace.map { it.methodName }.toSet()
assertTrue(expectedTraceElements.all { stacktrace.contains(it) })
}
private fun Throwable.depth(): Int {
val cause = cause ?: return 0
return 1 + cause.depth()
}
}
| apache-2.0 | 8134c07f765cdba8df2fd03b101f0a72 | 27.16092 | 102 | 0.476327 | 5.36105 | false | true | false | false |
EGF2/android-client | egf2-generator/src/main/kotlin/com/eigengraph/egf2/generator/mappers/StringMapper.kt | 1 | 1665 | package com.eigengraph.egf2.generator.mappers
import com.eigengraph.egf2.generator.Field
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.MethodSpec
import org.jetbrains.annotations.NotNull
import java.util.*
import javax.lang.model.element.Modifier
class StringMapper(targetPackage: String) : Mapper(targetPackage) {
override fun getField(field: Field, custom_schemas: LinkedHashMap<String, LinkedList<Field>>): FieldSpec {
val fs: FieldSpec.Builder
fs = FieldSpec.builder(String::class.java, field.name, Modifier.PUBLIC)
var default = field.default
if (field.enum != null) {
if (default != null) {
default = "ENUM_" + field.name.toUpperCase() + "." + field.default?.toUpperCase() + ".name().toLowerCase()"
fs.initializer("\$L", default)
}
} else {
if (field.default != null) fs.initializer("\$S", field.default)
}
if (field.required) fs.addAnnotation(NotNull::class.java)
return fs.build()
}
override fun deserialize(field: Field, supername: String, deserialize: MethodSpec.Builder, custom_schemas: LinkedHashMap<String, LinkedList<Field>>) {
if (field.required) {
deserialize.addStatement("final String \$L = jsonObject.get(\"\$L\").getAsString()", field.name, field.name)
deserialize.addStatement("\$L.\$L = \$L", supername, field.name, field.name)
} else {
deserialize.beginControlFlow("if(jsonObject.has(\"\$L\"))", field.name)
deserialize.addStatement("final String \$L = jsonObject.get(\"\$L\").getAsString()", field.name, field.name)
deserialize.addStatement("\$L.\$L = \$L", supername, field.name, field.name)
deserialize.endControlFlow()
}
deserialize.addCode("\n")
}
} | mit | a80b6840f58697de3e18ba410326cc99 | 41.717949 | 151 | 0.717117 | 3.635371 | false | false | false | false |
mtransitapps/mtransit-for-android | src/main/java/org/mtransit/android/billing/IBillingManager.kt | 1 | 3307 | package org.mtransit.android.billing
import androidx.lifecycle.LiveData
import com.android.billingclient.api.ProductDetails
import org.mtransit.android.ui.view.common.IActivity
interface IBillingManager {
@Suppress("MayBeConstant")
companion object {
@JvmField
val OFFER_DETAILS_IDX = 0 // 1 offer / subscription (for now)
@JvmField
val PRODUCT_ID_SUBSCRIPTION = "_subscription_"
@JvmField
val PRODUCT_ID_STARTS_WITH_F = "f_"
@JvmField
val DEFAULT_PRICE_CAT = "1"
@JvmField
val WEEKLY = "weekly"
@JvmField
val MONTHLY = "monthly"
@JvmField
val YEARLY = "yearly"
@JvmField
val DEFAULT_PERIOD_CAT = MONTHLY
@JvmField
val AVAILABLE_SUBSCRIPTIONS = arrayListOf(
PRODUCT_ID_STARTS_WITH_F + WEEKLY + PRODUCT_ID_SUBSCRIPTION + "1",
PRODUCT_ID_STARTS_WITH_F + WEEKLY + PRODUCT_ID_SUBSCRIPTION + "2",
PRODUCT_ID_STARTS_WITH_F + WEEKLY + PRODUCT_ID_SUBSCRIPTION + "3",
PRODUCT_ID_STARTS_WITH_F + WEEKLY + PRODUCT_ID_SUBSCRIPTION + "4",
PRODUCT_ID_STARTS_WITH_F + WEEKLY + PRODUCT_ID_SUBSCRIPTION + "5",
PRODUCT_ID_STARTS_WITH_F + WEEKLY + PRODUCT_ID_SUBSCRIPTION + "7",
PRODUCT_ID_STARTS_WITH_F + WEEKLY + PRODUCT_ID_SUBSCRIPTION + "10",
PRODUCT_ID_STARTS_WITH_F + MONTHLY + PRODUCT_ID_SUBSCRIPTION + "1",
PRODUCT_ID_STARTS_WITH_F + MONTHLY + PRODUCT_ID_SUBSCRIPTION + "2",
PRODUCT_ID_STARTS_WITH_F + MONTHLY + PRODUCT_ID_SUBSCRIPTION + "3",
PRODUCT_ID_STARTS_WITH_F + MONTHLY + PRODUCT_ID_SUBSCRIPTION + "4",
PRODUCT_ID_STARTS_WITH_F + MONTHLY + PRODUCT_ID_SUBSCRIPTION + "5",
PRODUCT_ID_STARTS_WITH_F + MONTHLY + PRODUCT_ID_SUBSCRIPTION + "7",
PRODUCT_ID_STARTS_WITH_F + MONTHLY + PRODUCT_ID_SUBSCRIPTION + "10",
PRODUCT_ID_STARTS_WITH_F + YEARLY + PRODUCT_ID_SUBSCRIPTION + "1",
PRODUCT_ID_STARTS_WITH_F + YEARLY + PRODUCT_ID_SUBSCRIPTION + "2",
PRODUCT_ID_STARTS_WITH_F + YEARLY + PRODUCT_ID_SUBSCRIPTION + "3",
PRODUCT_ID_STARTS_WITH_F + YEARLY + PRODUCT_ID_SUBSCRIPTION + "4",
PRODUCT_ID_STARTS_WITH_F + YEARLY + PRODUCT_ID_SUBSCRIPTION + "5",
PRODUCT_ID_STARTS_WITH_F + YEARLY + PRODUCT_ID_SUBSCRIPTION + "7",
PRODUCT_ID_STARTS_WITH_F + YEARLY + PRODUCT_ID_SUBSCRIPTION + "10",
)
@JvmField
val ALL_VALID_SUBSCRIPTIONS = AVAILABLE_SUBSCRIPTIONS + arrayListOf(
"weekly_subscription", // Inactive
"monthly_subscription", // Active - offered by default for months
"yearly_subscription" // Active - never offered
)
}
val productIdsWithDetails: LiveData<Map<String, ProductDetails>>
fun refreshAvailableSubscriptions()
fun refreshPurchases()
fun isHasSubscription(): Boolean?
fun getCurrentSubscription(): String?
fun launchBillingFlow(activity: IActivity, productId: String) : Boolean
fun addListener(listener: OnBillingResultListener)
fun removeListener(listener: OnBillingResultListener)
interface OnBillingResultListener {
fun onBillingResult(productId: String?)
}
} | apache-2.0 | 094803c29d4c3f017fdd616c1af26736 | 36.590909 | 80 | 0.6329 | 4.097893 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt | 1 | 7800 | package info.nightscout.androidaps.plugins.general.tidepool
import android.content.Context
import android.text.Spanned
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.events.EventNetworkChange
import info.nightscout.androidaps.events.EventNewBG
import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.tidepool.comm.TidepoolUploader
import info.nightscout.androidaps.plugins.general.tidepool.comm.TidepoolUploader.ConnectionStatus.CONNECTED
import info.nightscout.androidaps.plugins.general.tidepool.comm.TidepoolUploader.ConnectionStatus.DISCONNECTED
import info.nightscout.androidaps.plugins.general.tidepool.comm.UploadChunk
import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolDoUpload
import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolResetData
import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolStatus
import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolUpdateGUI
import info.nightscout.androidaps.plugins.general.tidepool.utils.RateLimit
import info.nightscout.androidaps.receivers.ReceiverStatusStore
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.extensions.plusAssign
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class TidepoolPlugin @Inject constructor(
injector: HasAndroidInjector,
aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper,
private val rxBus: RxBusWrapper,
private val context: Context,
private val fabricPrivacy: FabricPrivacy,
private val tidepoolUploader: TidepoolUploader,
private val uploadChunk: UploadChunk,
private val sp: SP,
private val rateLimit: RateLimit,
private val receiverStatusStore: ReceiverStatusStore
) : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL)
.pluginName(R.string.tidepool)
.shortName(R.string.tidepool_shortname)
.fragmentClass(TidepoolFragment::class.qualifiedName)
.preferencesId(R.xml.pref_tidepool)
.description(R.string.description_tidepool),
aapsLogger, resourceHelper, injector
) {
private var disposable: CompositeDisposable = CompositeDisposable()
private val listLog = ArrayList<EventTidepoolStatus>()
var textLog: Spanned = HtmlHelper.fromHtml("")
override fun onStart() {
super.onStart()
disposable += rxBus
.toObservable(EventTidepoolDoUpload::class.java)
.observeOn(Schedulers.io())
.subscribe({ doUpload() }, { fabricPrivacy.logException(it) })
disposable += rxBus
.toObservable(EventTidepoolResetData::class.java)
.observeOn(Schedulers.io())
.subscribe({
if (tidepoolUploader.connectionStatus != CONNECTED) {
aapsLogger.debug(LTag.TIDEPOOL, "Not connected for delete Dataset")
} else {
tidepoolUploader.deleteDataSet()
sp.putLong(R.string.key_tidepool_last_end, 0)
tidepoolUploader.doLogin()
}
}, {
fabricPrivacy.logException(it)
})
disposable += rxBus
.toObservable(EventTidepoolStatus::class.java)
.observeOn(Schedulers.io())
.subscribe({ event -> addToLog(event) }, {
fabricPrivacy.logException(it)
})
disposable += rxBus
.toObservable(EventNewBG::class.java)
.observeOn(Schedulers.io())
.filter { it.bgReading != null } // better would be optional in API level >24
.map { it.bgReading }
.subscribe({ bgReading ->
if (bgReading!!.date < uploadChunk.getLastEnd())
uploadChunk.setLastEnd(bgReading.date)
if (isEnabled(PluginType.GENERAL)
&& (!sp.getBoolean(R.string.key_tidepool_only_while_charging, false) || receiverStatusStore.isCharging)
&& (!sp.getBoolean(R.string.key_tidepool_only_while_unmetered, false) || receiverStatusStore.isWifiConnected)
&& rateLimit.rateLimit("tidepool-new-data-upload", T.mins(4).secs().toInt()))
doUpload()
}, {
fabricPrivacy.logException(it)
})
disposable += rxBus
.toObservable(EventPreferenceChange::class.java)
.observeOn(Schedulers.io())
.subscribe({ event ->
if (event.isChanged(resourceHelper, R.string.key_tidepool_dev_servers)
|| event.isChanged(resourceHelper, R.string.key_tidepool_username)
|| event.isChanged(resourceHelper, R.string.key_tidepool_password)
)
tidepoolUploader.resetInstance()
}, {
fabricPrivacy.logException(it)
})
disposable += rxBus
.toObservable(EventNetworkChange::class.java)
.observeOn(Schedulers.io())
.subscribe({}, {
fabricPrivacy.logException(it)
}) // TODO start upload on wifi connect
}
override fun onStop() {
disposable.clear()
super.onStop()
}
override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) {
super.preprocessPreferences(preferenceFragment)
val tidepoolTestLogin: Preference? = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_tidepool_test_login))
tidepoolTestLogin?.setOnPreferenceClickListener {
preferenceFragment.context?.let {
tidepoolUploader.testLogin(it)
}
false
}
}
private fun doUpload() =
when (tidepoolUploader.connectionStatus) {
DISCONNECTED -> tidepoolUploader.doLogin(true)
CONNECTED -> tidepoolUploader.doUpload()
else -> {
}
}
@Synchronized
private fun addToLog(ev: EventTidepoolStatus) {
synchronized(listLog) {
listLog.add(ev)
// remove the first line if log is too large
if (listLog.size >= Constants.MAX_LOG_LINES) {
listLog.removeAt(0)
}
}
rxBus.send(EventTidepoolUpdateGUI())
}
@Synchronized
fun updateLog() {
try {
val newTextLog = StringBuilder()
synchronized(listLog) {
for (log in listLog) {
newTextLog.append(log.toPreparedHtml())
}
}
textLog = HtmlHelper.fromHtml(newTextLog.toString())
} catch (e: OutOfMemoryError) {
ToastUtils.showToastInUiThread(context, rxBus, "Out of memory!\nStop using this phone !!!", R.raw.error)
}
}
} | agpl-3.0 | c7428902180edd0983a2efbf4f5feb70 | 40.94086 | 131 | 0.677179 | 4.826733 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/reactive/nodes/Label.kt | 1 | 718 | package com.cout970.reactive.nodes
import com.cout970.reactive.core.RBuilder
import com.cout970.reactive.core.RDescriptor
import org.liquidengine.legui.component.Component
import org.liquidengine.legui.component.Label
class LabelDescriptor(val text: String) : RDescriptor {
override fun mapToComponent(): Component = Label(text, 0f, 0f, 100f, 16f)
}
class LabelBuilder(var text: String) : RBuilder() {
override fun toDescriptor(): RDescriptor = LabelDescriptor(text)
}
fun RBuilder.label(text: String = "", key: String? = null, block: LabelBuilder.() -> Unit = {}) =
+LabelBuilder(text).apply(block).build(key)
fun LabelBuilder.style(func: Label.() -> Unit) {
deferred = { (it as Label).func() }
} | gpl-3.0 | e53ae9905d5f7e078aecb9ce9d2f38e8 | 33.238095 | 97 | 0.732591 | 3.554455 | false | false | false | false |
Pattonville-App-Development-Team/Android-App | app/src/main/java/org/pattonvillecs/pattonvilleapp/service/model/calendar/DataSourceMarker.kt | 1 | 2485 | /*
* Copyright (C) 2017 - 2018 Mitchell Skaggs, Keturah Gadson, Ethan Holtgrieve, Nathan Skelton, Pattonville School District
*
* 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 org.pattonvillecs.pattonvilleapp.service.model.calendar
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.os.Parcel
import android.os.Parcelable
import com.google.errorprone.annotations.Immutable
import org.pattonvillecs.pattonvilleapp.service.model.DataSource
import org.pattonvillecs.pattonvilleapp.service.model.calendar.event.CalendarEvent
/**
* Created by Mitchell on 10/9/2017.
*/
@Immutable
@Entity(tableName = "datasource_markers", primaryKeys = ["uid", "datasource"])
data class DataSourceMarker(@field:ColumnInfo(name = "uid", index = true, collate = ColumnInfo.BINARY)
val uid: String,
@field:ColumnInfo(name = "datasource", index = true, collate = ColumnInfo.BINARY)
val dataSource: DataSource) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readSerializable() as DataSource)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(uid)
parcel.writeSerializable(dataSource)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<DataSourceMarker> {
@JvmStatic
fun dataSource(calendarEvent: CalendarEvent, dataSource: DataSource): DataSourceMarker = DataSourceMarker(calendarEvent.uid, dataSource)
override fun createFromParcel(parcel: Parcel): DataSourceMarker {
return DataSourceMarker(parcel)
}
override fun newArray(size: Int): Array<DataSourceMarker?> {
return arrayOfNulls(size)
}
}
}
| gpl-3.0 | 33100ada5d16c4ba18e488805e88d423 | 38.444444 | 144 | 0.709859 | 4.733333 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/ArtifactEntityImpl.kt | 1 | 17380 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneChild
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneChildOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ArtifactEntityImpl : ArtifactEntity, WorkspaceEntityBase() {
companion object {
internal val ROOTELEMENT_CONNECTION_ID: ConnectionId = ConnectionId.create(ArtifactEntity::class.java,
CompositePackagingElementEntity::class.java,
ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true)
internal val CUSTOMPROPERTIES_CONNECTION_ID: ConnectionId = ConnectionId.create(ArtifactEntity::class.java,
ArtifactPropertiesEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
internal val ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID: ConnectionId = ConnectionId.create(ArtifactEntity::class.java,
ArtifactOutputPackagingElementEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE,
false)
val connections = listOf<ConnectionId>(
ROOTELEMENT_CONNECTION_ID,
CUSTOMPROPERTIES_CONNECTION_ID,
ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID,
)
}
@JvmField
var _name: String? = null
override val name: String
get() = _name!!
@JvmField
var _artifactType: String? = null
override val artifactType: String
get() = _artifactType!!
override var includeInProjectBuild: Boolean = false
@JvmField
var _outputUrl: VirtualFileUrl? = null
override val outputUrl: VirtualFileUrl?
get() = _outputUrl
override val rootElement: CompositePackagingElementEntity?
get() = snapshot.extractOneToAbstractOneChild(ROOTELEMENT_CONNECTION_ID, this)
override val customProperties: List<ArtifactPropertiesEntity>
get() = snapshot.extractOneToManyChildren<ArtifactPropertiesEntity>(CUSTOMPROPERTIES_CONNECTION_ID, this)!!.toList()
override val artifactOutputPackagingElement: ArtifactOutputPackagingElementEntity?
get() = snapshot.extractOneToOneChild(ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ArtifactEntityData?) : ModifiableWorkspaceEntityBase<ArtifactEntity>(), ArtifactEntity.Builder {
constructor() : this(ArtifactEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ArtifactEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
index(this, "outputUrl", this.outputUrl)
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isNameInitialized()) {
error("Field ArtifactEntity#name should be initialized")
}
if (!getEntityData().isArtifactTypeInitialized()) {
error("Field ArtifactEntity#artifactType should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CUSTOMPROPERTIES_CONNECTION_ID, this) == null) {
error("Field ArtifactEntity#customProperties should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CUSTOMPROPERTIES_CONNECTION_ID)] == null) {
error("Field ArtifactEntity#customProperties should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ArtifactEntity
this.entitySource = dataSource.entitySource
this.name = dataSource.name
this.artifactType = dataSource.artifactType
this.includeInProjectBuild = dataSource.includeInProjectBuild
this.outputUrl = dataSource.outputUrl
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData().name = value
changedProperty.add("name")
}
override var artifactType: String
get() = getEntityData().artifactType
set(value) {
checkModificationAllowed()
getEntityData().artifactType = value
changedProperty.add("artifactType")
}
override var includeInProjectBuild: Boolean
get() = getEntityData().includeInProjectBuild
set(value) {
checkModificationAllowed()
getEntityData().includeInProjectBuild = value
changedProperty.add("includeInProjectBuild")
}
override var outputUrl: VirtualFileUrl?
get() = getEntityData().outputUrl
set(value) {
checkModificationAllowed()
getEntityData().outputUrl = value
changedProperty.add("outputUrl")
val _diff = diff
if (_diff != null) index(this, "outputUrl", value)
}
override var rootElement: CompositePackagingElementEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractOneChild(ROOTELEMENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
ROOTELEMENT_CONNECTION_ID)] as? CompositePackagingElementEntity
}
else {
this.entityLinks[EntityLink(true, ROOTELEMENT_CONNECTION_ID)] as? CompositePackagingElementEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, ROOTELEMENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToAbstractOneChildOfParent(ROOTELEMENT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, ROOTELEMENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, ROOTELEMENT_CONNECTION_ID)] = value
}
changedProperty.add("rootElement")
}
// List of non-abstract referenced types
var _customProperties: List<ArtifactPropertiesEntity>? = emptyList()
override var customProperties: List<ArtifactPropertiesEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<ArtifactPropertiesEntity>(CUSTOMPROPERTIES_CONNECTION_ID,
this)!!.toList() + (this.entityLinks[EntityLink(true,
CUSTOMPROPERTIES_CONNECTION_ID)] as? List<ArtifactPropertiesEntity>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CUSTOMPROPERTIES_CONNECTION_ID)] as? List<ArtifactPropertiesEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CUSTOMPROPERTIES_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CUSTOMPROPERTIES_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CUSTOMPROPERTIES_CONNECTION_ID)] = value
}
changedProperty.add("customProperties")
}
override var artifactOutputPackagingElement: ArtifactOutputPackagingElementEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID)] as? ArtifactOutputPackagingElementEntity
}
else {
this.entityLinks[EntityLink(true, ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID)] as? ArtifactOutputPackagingElementEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID)] = value
}
changedProperty.add("artifactOutputPackagingElement")
}
override fun getEntityData(): ArtifactEntityData = result ?: super.getEntityData() as ArtifactEntityData
override fun getEntityClass(): Class<ArtifactEntity> = ArtifactEntity::class.java
}
}
class ArtifactEntityData : WorkspaceEntityData.WithCalculablePersistentId<ArtifactEntity>() {
lateinit var name: String
lateinit var artifactType: String
var includeInProjectBuild: Boolean = false
var outputUrl: VirtualFileUrl? = null
fun isNameInitialized(): Boolean = ::name.isInitialized
fun isArtifactTypeInitialized(): Boolean = ::artifactType.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ArtifactEntity> {
val modifiable = ArtifactEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ArtifactEntity {
val entity = ArtifactEntityImpl()
entity._name = name
entity._artifactType = artifactType
entity.includeInProjectBuild = includeInProjectBuild
entity._outputUrl = outputUrl
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun persistentId(): PersistentEntityId<*> {
return ArtifactId(name)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ArtifactEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ArtifactEntity(name, artifactType, includeInProjectBuild, entitySource) {
this.outputUrl = [email protected]
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ArtifactEntityData
if (this.entitySource != other.entitySource) return false
if (this.name != other.name) return false
if (this.artifactType != other.artifactType) return false
if (this.includeInProjectBuild != other.includeInProjectBuild) return false
if (this.outputUrl != other.outputUrl) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ArtifactEntityData
if (this.name != other.name) return false
if (this.artifactType != other.artifactType) return false
if (this.includeInProjectBuild != other.includeInProjectBuild) return false
if (this.outputUrl != other.outputUrl) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + artifactType.hashCode()
result = 31 * result + includeInProjectBuild.hashCode()
result = 31 * result + outputUrl.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + artifactType.hashCode()
result = 31 * result + includeInProjectBuild.hashCode()
result = 31 * result + outputUrl.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.outputUrl?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| apache-2.0 | b6ff0d4462e42bc484e1f24d94ba1c1c | 40.578947 | 207 | 0.666513 | 5.5 | false | false | false | false |
siosio/intellij-community | plugins/dependency-updater/src/com/intellij/buildsystem/model/unified/UnifiedDependencyRepository.kt | 10 | 739 | package com.intellij.buildsystem.model.unified
import com.intellij.buildsystem.model.BuildDependencyRepository
import com.intellij.openapi.util.NlsSafe
data class UnifiedDependencyRepository(
val id: String?,
val name: String?,
val url: String?
) : BuildDependencyRepository {
@get:NlsSafe
val displayName: String = buildString {
append('[')
if (!name.isNullOrBlank()) append("name='$name'")
if (!id.isNullOrBlank()) {
if (count() > 1) append(", ")
append("id='")
append(id)
append("'")
}
if (!url.isNullOrBlank()) {
if (count() > 1) append(", ")
append("url='")
append(url)
append("'")
}
if (count() == 1) append("#NO_DATA#")
append(']')
}
}
| apache-2.0 | dd3a5b5d2067fc2abd5fd06cc121d27a | 22.09375 | 63 | 0.603518 | 3.951872 | false | false | false | false |
idea4bsd/idea4bsd | platform/script-debugger/debugger-ui/src/MemberFilterWithNameMappings.kt | 14 | 1324 | /*
* Copyright 2000-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.debugger
open class MemberFilterWithNameMappings(protected val rawNameToSource: Map<String, String> = emptyMap()) : MemberFilter {
override fun hasNameMappings() = !rawNameToSource.isEmpty()
override fun rawNameToSource(variable: Variable): String {
val name = variable.name
val sourceName = rawNameToSource.get(name)
return sourceName ?: normalizeMemberName(name)
}
protected open fun normalizeMemberName(name: String) = name
override fun sourceNameToRaw(name: String): String? {
if (!hasNameMappings()) {
return null
}
for (entry in rawNameToSource.entries) {
if (entry.value == name) {
return entry.key
}
}
return null
}
}
| apache-2.0 | e8bd9f66199170ea73e3e8892850e92d | 31.292683 | 121 | 0.717523 | 4.312704 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/ProfilePageTemplate.kt | 1 | 12444 | package alraune
import alraune.Al.*
import alraune.entity.*
import vgrechka.*
import vgrechka.Jaco0.*
object ProfilePageTemplate
//class ProfilePageTemplate(val kind: Kind) {
// var pedro by notNullOnce<EntityPageTemplate.Pedro<User>>()
//
// enum class Kind {User, Admin}
//
// fun spit() {
// val product = makeFuckingTemplate()
// product.spitPage.spit()
// }
//
// fun makeFuckingTemplate(): EntityPageTemplate.Product {
// val template = EntityPageTemplate<User>()
// return template.build(Pedro().also {
// it.kind = kind
// })
// }
//
// class Pedro : EntityPageTemplate.Pedro<User>() {
// var kind by notNullOnce<Kind>()
//
// override fun identification() = when (kind) {
// Kind.User -> Identification.Implicit
// Kind.Admin -> Identification.ExplicitOrSearch
// }
//
// override fun implicitEntityPO() = when (kind) {
// Kind.User -> {
// val myID = rctx().v2.user.id
// val meUpdated = selectUserByID(myID)
// AlMaybe.Some(meUpdated)
// }
// Kind.Admin -> wtf()
// }
//
// override fun checkPermissionsForEntityAccessedViaIDIfNotAdmin(entityPO: User) =
// rctx().v2.user.id == entityPO.id
//
// override fun entityClass() = User::class.java
//
// override fun impersonationMakesSense(impersonateAs: AlUserKind): Boolean {
// val kindOfUserBeingEdited = juan.entity.kind()
// return impersonateAs == kindOfUserBeingEdited
// }
//
// override fun pageClass() = when (kind) {
// Kind.User -> SpitProfilePage::class
// Kind.Admin -> SpitAdminUserProfilePage::class
// }
//
// override fun applicableEntityAddressings() = when (kind) {
// Kind.Admin -> VList.of(EntityAddressing.writersWaitingApproval())
// else -> VList.empty()
// }
//
// override val table = User.Meta.table
//
// override val noEntityWithIDMessage = t("TOTE", "Юзера с ID <b>%s</b> не существует, такие дела...")
// override val noPermissionsForEntityWithIDMessage = t("TOTE", "Тебе на эту страницу не положено")
//
// override fun paramsModalContent() = object : EntityPageTemplate.ParamsModalContent {
// override fun composeBody(fields: BunchOfFields) = div().with {
// val f = AlCastFields_User(fields)
// oo(composeKindaWriterProfileForm(f.signUpFields))
//
// ifNotNullv(f.userFieldsForAdmin, {af ->
// af!!
// oo(Row().with {
// oo(col(12, af.adminNotes.compose()))})
//
// val state = juan.entity.state
// if (state == AlUserState.Banned)
// oo(Row().with {
// oo(col(12, af.banReason.compose()))})
// if (state == AlUserState.ProfileRejected)
// oo(Row().with {
// oo(col(12, af.profileRejectionReason.compose()))})
// })
// }
// }
//
// override fun updateEntityParams(fs: BunchOfFields) = object : Al2.UpdateEntityParams() {
// override fun shortOperationDescription() = "Edit user profile"
// override fun entity() = juan.entity
// override fun fields() = fs
// }.dance()
//
// override fun makeFields() = when {
// isAdmin() -> UserFieldsForAdmin()
// else -> UserFields()
// }
//
// override fun addTabs(xs: MutableList<EntityPageTemplate.Tab>) {
// if (isPretendingAdmin()) {
// xs.add(object : EntityPageTemplate.Tab {
// override fun id() = "History"
// override fun title() = t("TOTE", "История")
//
// override fun addTopRightControls(trb: TopRightControls) {}
//
// override fun render(rpp: RenderingParamsPile) = div().with {
// // VList<AlUser> list = new AlDB.BuildEPOQuery_History() {
//// @Override boolean count() {return false;}
//// @Override AlDB.EPOTables tables() {return AlDB.EPOTables.users;}
//// @Override Long entityID() {return juan.entity.getId();}
//// }.selectUserList();
//
// val list: VList<User> = tbd()
//
//// for (int i = 0; i < list.size(); i++) {
// // TODO:vgrechka Operations
//// AlOperation operation = list.get(i).operation;
//// Object inst = runtimize(() -> {
//// Class<?> clazz = Class.forName(operation.dataInterpreter);
//// return clazz.newInstance();
//// });
//// AlOperationDataInterpreter interp = (AlOperationDataInterpreter) inst;
//// oo(interp.render(operation.data, i == 0));
//// }
// }
// })
// }
// }
//
// override fun canEditParams() =
// juan.initialParams.impersonate.get() == AlUserKind.Admin
// || oneOf(juan.entity.state, AlUserState.Cool, AlUserState.ProfileRejected)
//
// override fun renderParamsTab(rpp: RenderingParamsPile) = div().with {
// val params = juan.entity
//
// val f = AlCastFields_User(makeFields())
//
// val immutable = ImmutableUserFields()
//
// oo(Row().with {
// oo(composeCreatedAtCol(3, params.createdAt))
// if (params.profileUpdatedAt != null)
// oo(composeTimestampCol(3, t("TOTE", "Профайл обновлен"), params.profileUpdatedAt!!))
// oo(col(3, immutable.kind.title, params.kind.title))
// oo(col(3, immutable.state.title, params.state.title))
// })
// oo(Row().with {
// oo(col(3, f.signUpFields.firstName.title, params.firstName))
// oo(col(3, f.signUpFields.lastName.title, params.lastName))
// oo(col(3, f.signUpFields.email.title, params.email))
// oo(col(3, f.signUpFields.phone.title, params.profilePhone))
// })
//
// if (params.kind == AlUserKind.Writer) {
// val subscriptions = params.writerSubscriptions!!
// oo(DetailsRow().title(f.signUpFields.writerSubscriptions.title).content(div().with {
// // params.writerSubscriptions.everything = true;
// if (subscriptions.everything) {
// oo(FA.check().style("margin-right: 0.5rem;"));
// oo(span(t("TOTE", "Подписан на все категории")));
// } else {
// oo(div().style("max-height: 10rem; overflow: auto;").with {
// for (categoryID in subscriptions.categoryIDs) {
// oo(div(AlText.endash + " " + longDocumentCategoryTitle(categoryID)))
// }
// })
// }
// }))
// }
//
// oo(DetailsRow().title(f.signUpFields.aboutMe.title).content(params.aboutMe))
//
// ifNotNullv(f.userFieldsForAdmin, {af ->
// af!!
// oo(DetailsRow().title(af.adminNotes.title).content(params.adminNotes))
// oo(DetailsRow().title(af.banReason.title).content(params.banReason))
// })
// }
//
// override fun shouldStopRenderingWithMessage() = null
//
// override fun pageTitle() = when (kind) {
// Kind.User -> t("TOTE", "Профайл")
// Kind.Admin -> t("TOTE", "Засранец №" + juan.entity.id)
// }
//
// override fun pageSubTitle() = when (kind) {
// Kind.User -> null
// Kind.Admin -> Al.userFullDisplayName(juan.entity)
// }
//
// override fun htmlHeadTitle() = Al.userFullDisplayName(juan.entity)
//
// override fun composeActionBannerBelowTitle(): Renderable {
// imf()
//// val state = juan.entity.state
//// if (AlUserState.WaitsApproval == state) {
//// return object : RenderApprovalBanner() {
//// override fun acceptButtonTitle() = t("TOTE", "Принять")
//// override fun rejectButtonTitle() = t("TOTE", "Завернуть")
//// override fun messageForUser() = t("TOTE", "Мы смотрим на твой профайл и скоро позвоним. Потом все остальное...")
//// override fun questionForAdmin() = t("TOTE", "Ну что, одобрим этого засранца?")
//// override fun frc() = juan.frc
//// override fun frc2() = juan.frc2
//// override fun wasRejectionReason() = juan.entity.wasProfileRejectionReason
//// override fun entityKindTitle() = "профайл"
////
//// override fun performRejection(fs: RejectionFields) {
//// val rejectionReason = fs.reason.value()
//// juan.changeEntityStateAndReload(
//// "Reject motherfucker's profile", rejectionReason,
//// {p ->
//// p.state = AlUserState.ProfileRejected
//// p.profileRejectionReason = rejectionReason
//// }
//// )
//// }
////
//// override fun acceptServant() = ServantHandle.Instance(Servant {
//// juan.changeEntityStateAndReload(
//// "Accept motherfucker's profile", null,
//// {p ->
//// p.state = AlUserState.Cool
//// // 1d9be9ef-24ce-4937-acff-1f3d61fd21fe
//// p.profileRejectionReason = ""
//// p.wasProfileRejectionReason = ""
//// }
//// )
//// })
//// }.dance()
//// }
//// else if (AlUserState.ProfileRejected == state) {
//// return object : RejectedBanner() {
//// override fun entityKindTitle() = "этот профайл"
//// override fun rejectionReason() = juan.entity.profileRejectionReason
////
//// override fun sendForReviewServant() = ServantHandle.Instance(Servant {
//// juan.changeEntityStateAndReload(
//// "Send user profile for review", null,
//// {p ->
//// p.state = AlUserState.WaitsApproval
//// // cfe6e13d-1034-4b68-a281-5dba80051d37
//// p.wasProfileRejectionReason = p.profileRejectionReason
//// p.profileRejectionReason = ""
//// }
//// )
//// })
//// }.dance()
//// }
//// else return div()
// }
//
// override fun shitIntoGetParams(p: AlGetParams) {}
//
// override fun renderBelowActionBanner() = null
//
// override fun shouldSkipField(fs: BunchOfFields, field: FormField<*>): Boolean {
// if (fs is UserFieldsForAdmin) {
// val state = juan.entity.state
// if (field == fs.banReason && state != AlUserState.Banned) return true
// if (field == fs.profileRejectionReason && state != AlUserState.ProfileRejected) return true
// }
// return false
// }
// }
//
//}
| apache-2.0 | 20ce72f9fd9ed44c78f801143fb5e346 | 44.248148 | 136 | 0.483834 | 4.212759 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertFunctionTypeReceiverToParameterIntention.kt | 1 | 17022 | // 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.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.builtins.getReceiverTypeFromFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.refactoring.CallableRefactoring
import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively
import org.jetbrains.kotlin.idea.refactoring.getAffectedCallables
import org.jetbrains.kotlin.idea.references.KtSimpleReference
import org.jetbrains.kotlin.idea.search.usagesSearch.searchReferencesOrMethodReferences
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.getReceiverTargetDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference
import org.jetbrains.kotlin.psi2ir.deparenthesize
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getArgumentByParameterIndex
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class ConvertFunctionTypeReceiverToParameterIntention : SelfTargetingRangeIntention<KtTypeReference>(
KtTypeReference::class.java,
KotlinBundle.lazyMessage("convert.function.type.receiver.to.parameter")
) {
class ConversionData(
val functionParameterIndex: Int?,
val lambdaReceiverType: KotlinType,
callableDeclaration: KtCallableDeclaration,
) {
private val declarationPointer = callableDeclaration.createSmartPointer()
val callableDeclaration: KtCallableDeclaration? get() = declarationPointer.element
val functionDescriptor by lazy { callableDeclaration.unsafeResolveToDescriptor() as CallableDescriptor }
fun functionType(declaration: KtCallableDeclaration? = callableDeclaration): KtFunctionType? {
val functionTypeOwner = if (functionParameterIndex != null)
declaration?.valueParameters?.getOrNull(functionParameterIndex)
else
declaration
return functionTypeOwner?.typeReference?.typeElement as? KtFunctionType
}
}
class CallableDefinitionInfo(element: KtCallableDeclaration) :
AbstractProcessableUsageInfo<KtCallableDeclaration, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val declaration = element ?: return
val functionType = data.functionType(declaration) ?: return
val functionTypeParameterList = functionType.parameterList ?: return
val functionTypeReceiver = functionType.receiverTypeReference ?: return
val parameterToAdd = KtPsiFactory(project).createFunctionTypeParameter(functionTypeReceiver)
functionTypeParameterList.addParameterBefore(parameterToAdd, functionTypeParameterList.parameters.firstOrNull())
functionType.setReceiverTypeReference(null)
}
}
class ParameterCallInfo(element: KtCallExpression) : AbstractProcessableUsageInfo<KtCallExpression, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val callExpression = element ?: return
val qualifiedExpression = callExpression.getQualifiedExpressionForSelector() ?: return
val receiverExpression = qualifiedExpression.receiverExpression
val argumentList = callExpression.getOrCreateValueArgumentList()
argumentList.addArgumentBefore(KtPsiFactory(project).createArgument(receiverExpression), argumentList.arguments.firstOrNull())
qualifiedExpression.replace(callExpression)
}
}
class LambdaInfo(element: KtLambdaExpression) : AbstractProcessableUsageInfo<KtLambdaExpression, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val lambda = element?.functionLiteral ?: return
val context = lambda.analyze()
val lambdaDescriptor = context[BindingContext.FUNCTION, lambda] ?: return
val psiFactory = KtPsiFactory(project)
val validator = CollectingNameValidator(
lambda.valueParameters.mapNotNull { it.name },
NewDeclarationNameValidator(lambda.bodyExpression!!, null, NewDeclarationNameValidator.Target.VARIABLES)
)
val lambdaExtensionReceiver = lambdaDescriptor.extensionReceiverParameter
val lambdaDispatchReceiver = lambdaDescriptor.dispatchReceiverParameter
val newParameterName = KotlinNameSuggester.suggestNamesByType(data.lambdaReceiverType, validator, "p").first()
val newParameterRefExpression = psiFactory.createExpression(newParameterName)
lambda.accept(object : KtTreeVisitorVoid() {
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
super.visitSimpleNameExpression(expression)
if (expression is KtOperationReferenceExpression) return
val resolvedCall = expression.getResolvedCall(context) ?: return
val dispatchReceiverTarget = resolvedCall.dispatchReceiver?.getReceiverTargetDescriptor(context)
val extensionReceiverTarget = resolvedCall.extensionReceiver?.getReceiverTargetDescriptor(context)
if (dispatchReceiverTarget == lambdaDescriptor || extensionReceiverTarget == lambdaDescriptor) {
val parent = expression.parent
if (parent is KtCallExpression && expression == parent.calleeExpression) {
if ((parent.parent as? KtQualifiedExpression)?.receiverExpression !is KtThisExpression) {
parent.replace(psiFactory.createExpressionByPattern("$0.$1", newParameterName, parent))
}
} else if (parent is KtQualifiedExpression && parent.receiverExpression is KtThisExpression) {
// do nothing
} else {
val referencedName = expression.getReferencedName()
expression.replace(psiFactory.createExpressionByPattern("$newParameterName.$referencedName"))
}
}
}
override fun visitThisExpression(expression: KtThisExpression) {
val resolvedCall = expression.getResolvedCall(context) ?: return
if (resolvedCall.resultingDescriptor == lambdaDispatchReceiver ||
resolvedCall.resultingDescriptor == lambdaExtensionReceiver
) {
expression.replace(newParameterRefExpression.copy())
}
}
})
val lambdaParameterList = lambda.getOrCreateParameterList()
if (lambda.valueParameters.isEmpty() && lambdaDescriptor.valueParameters.isNotEmpty()) {
val parameterToAdd = psiFactory.createLambdaParameterList("it").parameters.first()
lambdaParameterList.addParameterBefore(parameterToAdd, lambdaParameterList.parameters.firstOrNull())
}
val parameterToAdd = psiFactory.createLambdaParameterList(newParameterName).parameters.first()
lambdaParameterList.addParameterBefore(parameterToAdd, lambdaParameterList.parameters.firstOrNull())
}
}
private inner class Converter(
private val data: ConversionData,
editor: Editor?,
project: Project,
) : CallableRefactoring<CallableDescriptor>(project, editor, data.functionDescriptor, text) {
override fun performRefactoring(descriptorsForChange: Collection<CallableDescriptor>) {
val callables = getAffectedCallables(project, descriptorsForChange)
val conflicts = MultiMap<PsiElement, String>()
val usages = ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>()
project.runSynchronouslyWithProgress(KotlinBundle.message("looking.for.usages.and.conflicts"), true) {
runReadAction {
val progressStep = 1.0 / callables.size
val progressIndicator = ProgressManager.getInstance().progressIndicator
progressIndicator.isIndeterminate = false
for ((i, callable) in callables.withIndex()) {
progressIndicator.fraction = (i + 1) * progressStep
if (callable !is KtCallableDeclaration) continue
if (!checkModifiable(callable)) {
val renderedCallable = RefactoringUIUtil.getDescription(callable, true).capitalize()
conflicts.putValue(callable, KotlinBundle.message("can.t.modify.0", renderedCallable))
}
for (ref in callable.searchReferencesOrMethodReferences()) {
if (ref !is KtSimpleReference<*>) continue
processExternalUsage(ref, usages)
}
usages += CallableDefinitionInfo(callable)
processInternalUsages(callable, usages)
}
}
}
project.checkConflictsInteractively(conflicts) {
project.executeWriteCommand(text) {
val elementsToShorten = ArrayList<KtElement>()
usages.sortedByDescending { it.element?.textOffset }.forEach { it.process(data, elementsToShorten) }
ShortenReferences.DEFAULT.process(elementsToShorten)
}
}
}
private fun processExternalUsage(
ref: KtSimpleReference<*>,
usages: ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>
) {
val parameterIndex = data.functionParameterIndex ?: return
val callElement = ref.element.getParentOfTypeAndBranch<KtCallElement> { calleeExpression } ?: return
val context = callElement.analyze(BodyResolveMode.PARTIAL)
val expressionToProcess = callElement
.getArgumentByParameterIndex(parameterIndex, context)
.singleOrNull()
?.getArgumentExpression()
?.let { KtPsiUtil.safeDeparenthesize(it) }
?: return
if (expressionToProcess is KtLambdaExpression) {
usages += LambdaInfo(expressionToProcess)
}
}
private fun processInternalUsages(
callable: KtCallableDeclaration,
usages: ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>
) {
val parameterIndex = data.functionParameterIndex ?: return processLambdasInReturnExpressions(callable, usages)
val body = when (callable) {
is KtConstructor<*> -> callable.containingClassOrObject?.body
is KtDeclarationWithBody -> callable.bodyExpression
else -> null
}
if (body != null) {
val functionParameter = callable.valueParameters.getOrNull(parameterIndex) ?: return
for (ref in ReferencesSearch.search(functionParameter, LocalSearchScope(body))) {
val element = ref.element as? KtSimpleNameExpression ?: continue
val callExpression = element.getParentOfTypeAndBranch<KtCallExpression> { calleeExpression } ?: continue
usages += ParameterCallInfo(callExpression)
}
}
}
private fun processLambdasInReturnExpressions(
callable: KtCallableDeclaration,
usages: ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>,
) {
assert(data.functionParameterIndex == null)
when (callable) {
is KtNamedFunction -> processBody(callable, usages, callable.bodyExpression)
is KtProperty -> {
processBody(callable, usages, callable.initializer)
callable.getter?.let { processBody(it, usages, it.bodyExpression) }
}
else -> Unit
}
}
private fun processBody(
declaration: KtDeclaration,
usages: ArrayList<AbstractProcessableUsageInfo<*, ConversionData>>,
bodyExpression: KtExpression?,
) = when (val body = bodyExpression?.deparenthesize()) {
is KtLambdaExpression -> usages += LambdaInfo(body)
is KtBlockExpression -> {
val context by lazy { declaration.analyze(BodyResolveMode.PARTIAL_WITH_CFA) }
val target by lazy { context[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration] }
bodyExpression.forEachDescendantOfType<KtReturnExpression> { returnExpression ->
returnExpression.returnedExpression
?.deparenthesize()
?.safeAs<KtLambdaExpression>()
?.takeIf { returnExpression.getTargetFunctionDescriptor(context) == target }
?.let { usages += LambdaInfo(it) }
}
}
else -> Unit
}
}
private fun KtTypeReference.getConversionData(): ConversionData? {
val functionTypeReceiver = parent as? KtFunctionTypeReceiver ?: return null
val functionType = functionTypeReceiver.parent as? KtFunctionType ?: return null
val lambdaReceiverType = functionType
.getAbbreviatedTypeOrType(functionType.analyze(BodyResolveMode.PARTIAL))
?.getReceiverTypeFromFunctionType()
?: return null
val typeReferenceHolder = functionType.parent?.safeAs<KtTypeReference>()?.parent?.safeAs<KtCallableDeclaration>() ?: return null
val (callableDeclaration, parameterIndex) = if (typeReferenceHolder is KtParameter) {
val callableDeclaration = typeReferenceHolder.ownerFunction as? KtCallableDeclaration ?: return null
callableDeclaration to callableDeclaration.valueParameters.indexOf(typeReferenceHolder)
} else
typeReferenceHolder to null
return ConversionData(parameterIndex, lambdaReceiverType, callableDeclaration)
}
override fun startInWriteAction(): Boolean = false
override fun applicabilityRange(element: KtTypeReference): TextRange? {
val data = element.getConversionData() ?: return null
val elementBefore = data.functionType() ?: return null
val elementAfter = elementBefore.copied().apply {
parameterList?.addParameterBefore(
KtPsiFactory(element).createFunctionTypeParameter(element),
parameterList?.parameters?.firstOrNull()
)
setReceiverTypeReference(null)
}
setTextGetter(KotlinBundle.lazyMessage("convert.0.to.1", elementBefore.text, elementAfter.text))
return element.textRange
}
override fun applyTo(element: KtTypeReference, editor: Editor?) {
element.getConversionData()?.let { Converter(it, editor, element.project).run() }
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction = ConvertFunctionTypeReceiverToParameterIntention()
}
} | apache-2.0 | 8c8683f9b8763afde8b3625048167d74 | 51.540123 | 158 | 0.678651 | 6.425821 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/ConvertStringTemplateToBuildStringIntention.kt | 1 | 1864 | // 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.k2.codeinsight.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.analysis.api.utils.shortenReferences
import org.jetbrains.kotlin.idea.base.psi.isAnnotationArgument
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicable.intentions.AbstractKotlinApplicableIntention
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicabilityRange
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges
import org.jetbrains.kotlin.idea.codeinsights.impl.base.intentions.convertStringTemplateToBuildStringCall
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
internal class ConvertStringTemplateToBuildStringIntention : AbstractKotlinApplicableIntention<KtStringTemplateExpression>(
KtStringTemplateExpression::class
), LowPriorityAction {
override fun getFamilyName(): String = KotlinBundle.message("convert.string.template.to.build.string")
override fun getActionName(element: KtStringTemplateExpression): String = familyName
override fun getApplicabilityRange(): KotlinApplicabilityRange<KtStringTemplateExpression> = ApplicabilityRanges.SELF
override fun isApplicableByPsi(element: KtStringTemplateExpression): Boolean =
!element.text.startsWith("\"\"\"") && !element.isAnnotationArgument()
override fun apply(element: KtStringTemplateExpression, project: Project, editor: Editor?) {
val buildStringCall = convertStringTemplateToBuildStringCall(element)
shortenReferences(buildStringCall)
}
} | apache-2.0 | af73d0af762ff0a7cdbfc2f511bd0760 | 59.16129 | 123 | 0.834227 | 5.120879 | false | false | false | false |
tommykw/Musical | app/src/main/java/com/github/tommykw/musical/ui/video/VideoPlayerComponent.kt | 1 | 3315 | package com.github.tommykw.musical.ui.video
import android.content.Context
import android.net.Uri
import androidx.core.net.toUri
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.github.tommykw.musical.data.entity.VideoPlayerState
import com.google.android.exoplayer2.C
import com.google.android.exoplayer2.ExoPlayerFactory
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.ui.PlayerView
import com.google.android.exoplayer2.upstream.DataSource
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util
import kotlin.math.max
class VideoPlayerComponent(
private val context: Context,
private val playerView: PlayerView,
private val playerState: VideoPlayerState
) : DefaultLifecycleObserver {
private var player: SimpleExoPlayer? = null
private fun initPlayer() {
if (player == null) {
player = ExoPlayerFactory.newSimpleInstance(
context,
DefaultTrackSelector().apply {
setParameters(buildUponParameters().setMaxVideoSizeSd())
}
)
}
playerView.player = player
setPlayerParams(playerState)
}
private fun setPlayerParams(state: VideoPlayerState) {
state.videoUrl?.let { url ->
val uri = url.toUri()
val mediaSource = buildMediaSource(uri)
player?.playWhenReady = state.playWhenReady
val hasResumePosition = state.currentWindow != C.INDEX_UNSET
if (hasResumePosition) {
player?.seekTo(state.currentWindow, state.playBackPosition)
}
player?.prepare(mediaSource, false, false)
}
}
private fun releasePlayer() {
updateStartPosition()
disposePlayer()
}
fun disposePlayer() {
player?.release()
player = null
}
private fun buildMediaSource(uri: Uri): MediaSource {
val dataSourceFactory: DataSource.Factory = DefaultDataSourceFactory(
context,
Util.getUserAgent(context, "Musical")
)
return ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(uri)
}
private fun updateStartPosition() {
playerState.playWhenReady = player?.playWhenReady ?: true
playerState.currentWindow = player?.currentWindowIndex ?: C.INDEX_UNSET
playerState.playBackPosition = max(0, player?.contentPosition ?: 0)
}
override fun onStart(owner: LifecycleOwner) {
super.onStart(owner)
initPlayer()
playerView.onResume()
}
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
initPlayer()
playerView.onResume()
}
override fun onPause(owner: LifecycleOwner) {
super.onPause(owner)
playerView.onPause()
releasePlayer()
}
override fun onStop(owner: LifecycleOwner) {
super.onStop(owner)
playerView.onPause()
releasePlayer()
}
} | mit | eea801834121f53ef585420bc09cce04 | 30.884615 | 87 | 0.68537 | 5 | false | false | false | false |
androidx/androidx | core/core-graphics-integration-tests/testapp/src/main/java/androidx/core/graphics/sample/GraphicsSampleActivity.kt | 3 | 1959 | package androidx.core.graphics.sample
import android.app.Activity
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.annotation.RequiresApi
import androidx.core.graphics.BitmapCompat
class GraphicsSampleActivity : Activity() {
@RequiresApi(Build.VERSION_CODES.KITKAT)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
// decode a large natural image to use as input to different scaling algorithms
// it's too big to draw in it's current form.
val source: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.crowd_stripes)
val width = 240
val height = 160
// resize the bitmap with the builtin method.
// Bilinear with a 2x2 sample.
val scaled1: Bitmap = Bitmap.createScaledBitmap(source, width, height, true)
// resize the bitmap with the method from androidx bitmapcompat
// repeated 2x2 bilinear as if creating mipmaps but stopping at the desired size
val scaled2: Bitmap = BitmapCompat.createScaledBitmap(source, width, height, null, true)
// draw both images scaled to fill their container without filtering so as to
// make the difference obvious.
val topview: ImageView = findViewById<View>(R.id.imageView2) as ImageView
val drawable1: BitmapDrawable = BitmapDrawable(resources, scaled1)
drawable1.setFilterBitmap(false)
topview.setImageDrawable(drawable1)
val bottomview: ImageView = findViewById<View>(R.id.imageView) as ImageView
val drawable2: BitmapDrawable = BitmapDrawable(resources, scaled2)
drawable2.setFilterBitmap(false)
bottomview.setImageDrawable(drawable2)
}
} | apache-2.0 | f4d06af4e272a94248766347524b3c41 | 40.702128 | 96 | 0.734558 | 4.731884 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/input/rotary/RotaryScrollEvent.kt | 3 | 2338 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.input.rotary
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.input.focus.FocusDirectedInputEvent
/**
* This event represents a rotary input event.
*
* Some Wear OS devices contain a physical rotating side button, or a rotating bezel. When the user
* turns the button or rotates the bezel, a [RotaryScrollEvent] is sent to the item in focus.
*/
@ExperimentalComposeUiApi
class RotaryScrollEvent internal constructor(
/**
* The amount to scroll (in pixels) in response to a [RotaryScrollEvent] in a container that
* can scroll vertically.
*/
val verticalScrollPixels: Float,
/**
* The amount to scroll (in pixels) in response to a [RotaryScrollEvent] in a container that
* can scroll horizontally.
*/
val horizontalScrollPixels: Float,
/**
* The time in milliseconds at which this even occurred. The start (`0`) time is
* platform-dependent.
*/
val uptimeMillis: Long
) : FocusDirectedInputEvent {
override fun equals(other: Any?): Boolean = other is RotaryScrollEvent &&
other.verticalScrollPixels == verticalScrollPixels &&
other.horizontalScrollPixels == horizontalScrollPixels &&
other.uptimeMillis == uptimeMillis
override fun hashCode(): Int = 0
.let { 31 * it + verticalScrollPixels.hashCode() }
.let { 31 * it + horizontalScrollPixels.hashCode() }
.let { 31 * it + uptimeMillis.hashCode() }
override fun toString(): String = "RotaryScrollEvent(" +
"verticalScrollPixels=$verticalScrollPixels," +
"horizontalScrollPixels=$horizontalScrollPixels," +
"uptimeMillis=$uptimeMillis)"
}
| apache-2.0 | cb9c85bf937bf9a4edd36ca474199cf9 | 36.709677 | 99 | 0.707015 | 4.504817 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-remote-driver/src/main/kotlin/com/onyx/persistence/manager/impl/RemotePersistenceManager.kt | 1 | 18588 | package com.onyx.persistence.manager.impl
import com.onyx.network.push.PushRegistrar
import com.onyx.exception.OnyxException
import com.onyx.exception.StreamException
import com.onyx.extension.copy
import com.onyx.extension.set
import com.onyx.interactors.record.data.Reference
import com.onyx.persistence.IManagedEntity
import com.onyx.persistence.context.SchemaContext
import com.onyx.persistence.manager.PersistenceManager
import com.onyx.persistence.query.Query
import com.onyx.persistence.query.QueryCriteria
import com.onyx.persistence.query.QueryCriteriaOperator
import com.onyx.persistence.query.RemoteQueryListener
import com.onyx.persistence.stream.QueryStream
/**
* Persistence manager supplies a public API for performing database persistence and querying operations. This specifically is used for an remote database.
* Entities that are passed through these methods must be serializable
*
* This was refactored on 02/12/2017 in order to use the new RMI Server. It has been simplified to just use proxies. Also some
* of the default methods were implemented on the interface. Yay Java 1.8
*
* @author Tim Osborn
* @since 1.0.0
*
*
* PersistenceManagerFactory factory = new RemotePersistenceManagerFactory("onx://23.234.25.23:8080");
* factory.setCredentials("username", "password");
* factory.initialize();
*
* PersistenceManager manager = factory.getPersistenceManager(); // Get the Persistence manager from the persistence manager factory
*
* factory.close(); //Close the remote database
*
* or.. Kotlin
*
* val factory = RemotePersistenceManagerFactory("onx://23.234.25.23:8080")
* factory.initialize()
*
* val persistenceManager = factory.persistenceManager
* factory.close()
*
* @see com.onyx.persistence.manager.PersistenceManager
*
* Tim Osborn - 02/13/2017 This was augmented to use the new RMI Server. Also, simplified
* so that we take advantage of default methods within the PersistenceManager interface.
*/
open class RemotePersistenceManager : PersistenceManager {
override lateinit var context: SchemaContext
private lateinit var proxy: PersistenceManager
private lateinit var pushRegistrar: PushRegistrar
constructor()
/**
* Default Constructor. This should be invoked by the persistence manager factory
*
* @since 1.1.0
* @param persistenceManager Proxy Persistence manager on server
*/
constructor(persistenceManager: PersistenceManager, pushRegistrar: PushRegistrar) {
this.proxy = persistenceManager
this.pushRegistrar = pushRegistrar
}
/**
* Save entity. Persists a single entity for update or insert. This method will cascade relationships and persist indexes.
*
* @since 1.0.0
*
* @param entity Managed Entity to Save
*
* @return Saved Managed Entity
*
* @throws OnyxException Exception occurred while persisting an entity
*/
@Throws(OnyxException::class)
@Suppress("UNCHECKED_CAST")
override fun <E : IManagedEntity> saveEntity(entity: E): E {
val results = proxy.saveEntity<IManagedEntity>(entity)
entity.copy(results, context)
return entity
}
/**
* Batch saves a list of entities.
*
* The entities must all be of the same type
*
* @since 1.0.0
* @param entities List of entities
* @throws OnyxException Exception occurred while saving an entity within the list. This will not roll back preceding saves if error occurs.
*/
@Throws(OnyxException::class)
override fun saveEntities(entities: List<IManagedEntity>) {
if (entities.isNotEmpty()) {
proxy.saveEntities(entities)
}
}
/**
* Deletes a single entity
*
* The entity must exist otherwise it will throw an exception. This will cascade delete relationships and remove index references.
*
* @since 1.0.0
* @param entity Managed Entity to delete
* @return Flag indicating it was deleted
* @throws OnyxException Error occurred while deleting
*/
@Throws(OnyxException::class)
override fun deleteEntity(entity: IManagedEntity): Boolean = proxy.deleteEntity(entity)
/**
* Deletes list of entities.
*
* The entities must exist otherwise it will throw an exception. This will cascade delete relationships and remove index references.
*
* Requires all of the entities to be of the same type
*
* @since 1.0.0
* @param entities List of entities
* @throws OnyxException Error occurred while deleting. If exception is thrown, preceding entities will not be rolled back
*/
@Throws(OnyxException::class)
override fun deleteEntities(entities: List<IManagedEntity>) = proxy.deleteEntities(entities)
/**
* Execute query with criteria and optional row limitations
*
* @since 1.0.0
*
* @param query Query containing criteria
*
* @return Query Results
*
* @throws OnyxException Error while executing query
*/
@Throws(OnyxException::class)
@Suppress("UNCHECKED_CAST")
override fun <E> executeQuery(query: Query): List<E> {
// Transform the change listener to a remote change listener.
if (query.changeListener != null && query.changeListener !is RemoteQueryListener<*>) {
// Register the query listener as a push subscriber / receiver
val remoteQueryListener = RemoteQueryListener(query.changeListener)
this.pushRegistrar.register(remoteQueryListener, remoteQueryListener)
query.changeListener = remoteQueryListener
}
val result = proxy.executeQueryForResult(query)
query.resultsCount = result.query!!.resultsCount
return result.results as List<E>
}
/**
* Execute query with criteria and optional row limitations. Specify lazy instantiation of query results.
*
* @since 1.0.0
*
* @param query Query containing criteria
*
* @return LazyQueryCollection lazy loaded results
*
* @throws OnyxException Error while executing query
*/
@Throws(OnyxException::class)
@Suppress("UNCHECKED_CAST")
override fun <E : IManagedEntity> executeLazyQuery(query: Query): List<E> {
val result = proxy.executeLazyQueryForResult(query)
query.resultsCount = result.query!!.resultsCount
return result.results as List<E>
}
/**
* Updates all rows returned by a given query
*
* The query#updates list must not be null or empty
*
* @since 1.0.0
*
* @param query Query used to filter entities with criteria
*
* @throws OnyxException Exception occurred while executing update query
*
* @return Number of entities updated
*/
@Throws(OnyxException::class)
override fun executeUpdate(query: Query): Int {
val result = proxy.executeUpdateForResult(query)
query.resultsCount = result.query!!.resultsCount
return result.results as Int
}
/**
* Execute query and delete entities returned in the results
*
* @since 1.0.0
*
* @param query Query used to filter entities with criteria
*
* @throws OnyxException Exception occurred while executing delete query
*
* @return Number of entities deleted
*/
@Throws(OnyxException::class)
override fun executeDelete(query: Query): Int {
val result = proxy.executeDeleteForResult(query)
query.resultsCount = result.query!!.resultsCount
return result.results as Int
}
/**
* Hydrates an instantiated entity. The instantiated entity must have the primary key defined and partition key if the data is partitioned.
* All relationships are hydrated based on their fetch policy.
* The entity must also not be null.
*
* @since 1.0.0
*
* @param entity Entity to hydrate.
*
* @return Managed Entity
*
* @throws OnyxException Error when hydrating entity
*/
@Throws(OnyxException::class)
@Suppress("UNCHECKED_CAST")
override fun <E : IManagedEntity> find(entity: IManagedEntity): E {
val results = proxy.find<IManagedEntity>(entity)
entity.copy(results, context)
return entity as E
}
/**
* Find Entity By Class and ID.
*
* All relationships are hydrated based on their fetch policy. This does not take into account the partition.
*
* @since 1.0.0
*
* @param clazz Managed Entity Type. This must be a cast of IManagedEntity
* @param id Primary Key of entity
* @return Managed Entity
* @throws OnyxException Error when finding entity
*/
@Throws(OnyxException::class)
override fun <E : IManagedEntity> findById(clazz: Class<*>, id: Any): E? = proxy.findById(clazz, id)
/**
* Find Entity By Class and ID.
*
* All relationships are hydrated based on their fetch policy. This does not take into account the partition.
*
* @since 1.0.0
*
* @param clazz Managed Entity Type. This must be a cast of IManagedEntity
* @param id Primary Key of entity
* @param partitionId Partition key for entity
* @return Managed Entity
* @throws OnyxException Error when finding entity within partition specified
*/
@Throws(OnyxException::class)
override fun <E : IManagedEntity> findByIdInPartition(clazz: Class<*>, id: Any, partitionId: Any): E? = proxy.findByIdInPartition(clazz, id, partitionId)
/**
* Determines if the entity exists within the database.
*
* It is determined by the primary id and partition key
*
* @since 1.0.0
*
* @param entity Managed Entity to check
*
* @return Returns true if the entity primary key exists. Otherwise it returns false
*
* @throws OnyxException Error when finding entity within partition specified
*/
@Throws(OnyxException::class)
override fun exists(entity: IManagedEntity): Boolean = proxy.exists(entity)
/**
* Determines if the entity exists within the database.
*
* It is determined by the primary id and partition key
*
* @since 1.0.0
*
* @param entity Managed Entity to check
*
* @param partitionId Partition Value for entity
*
* @return Returns true if the entity primary key exists. Otherwise it returns false
*
* @throws OnyxException Error when finding entity within partition specified
*/
@Throws(OnyxException::class)
override fun exists(entity: IManagedEntity, partitionId: Any): Boolean = proxy.exists(entity, partitionId)
/**
* Provides a list of all entities with a given type
*
* @param clazz Type of managed entity to retrieve
*
* @return Unsorted List of all entities with type
*
* @throws OnyxException Exception occurred while fetching results
*/
@Throws(OnyxException::class)
override fun <E : IManagedEntity> list(clazz: Class<*>): List<E> {
val descriptor = context.getBaseDescriptorForEntity(clazz)
val criteria = QueryCriteria(descriptor!!.identifier!!.name, QueryCriteriaOperator.NOT_NULL)
return proxy.list(clazz, criteria)
}
/**
* Force Hydrate relationship based on attribute name
*
* @since 1.0.0
*
* @param entity Managed Entity to attach relationship values
*
* @param attribute String representation of relationship attribute
*
* @throws OnyxException Error when hydrating relationship. The attribute must exist and be a relationship.
*/
@Throws(OnyxException::class)
override fun initialize(entity: IManagedEntity, attribute: String) {
val relationship:Any? = proxy.getRelationship(entity, attribute)
entity.set(context = context, name = attribute, value = relationship)
}
/**
* This is a way to batch save all relationships for an entity. This does not retain any existing relationships and will
* overwrite all existing with the set you are sending in. This is useful to optimize batch saving entities with relationships.
*
* @since 1.0.0
* @param entity Parent Managed Entity
* @param relationship Relationship attribute
* @param relationshipIdentifiers Existing relationship identifiers
*
* @throws OnyxException Error occurred while saving relationship.
*/
@Throws(OnyxException::class)
override fun saveRelationshipsForEntity(entity: IManagedEntity, relationship: String, relationshipIdentifiers: Set<Any>) = proxy.saveRelationshipsForEntity(entity, relationship, relationshipIdentifiers)
/**
* Get an entity by its partition reference. This is the same as the method above but for objects that have
* a reference as part of a partition. An example usage would be in LazyQueryCollection so that it may
* hydrate objects in random partitions.
*
* @param entityType Type of managed entity
* @param reference Partition reference holding both the partition id and reference id
* @param <E> The managed entity implementation class
* @return Managed Entity
* @throws OnyxException The reference does not exist for that type
*/
@Throws(OnyxException::class)
override fun <E : IManagedEntity> getWithReference(entityType: Class<*>, reference: Reference): E? = proxy.getWithReference(entityType, reference)
/**
* Retrieves an entity using the primaryKey and partition
*
* @since 1.0.0
*
* @param clazz Entity Type
*
* @param id Entity Primary Key
*
* @param partitionId - Partition Identifier. Not to be confused with partition key. This is a unique id within the partition System table
* @return Managed Entity
*
* @throws OnyxException error occurred while attempting to retrieve entity.
*/
@Throws(OnyxException::class)
override fun <E : IManagedEntity?> findByIdWithPartitionId(clazz: Class<*>, id: Any, partitionId: Long): E = proxy.findByIdWithPartitionId<E>(clazz, id, partitionId)
/**
* This method is used for bulk streaming data entities. An example of bulk streaming is for analytics or bulk updates included but not limited to model changes.
*
* @since 1.0.0
*
* @param query Query to execute and stream
*
* @param streamer Instance of the streamer to use to stream the data
*/
@Throws(OnyxException::class)
override fun <T : Any> stream(query: Query, streamer: QueryStream<T>) = throw StreamException(StreamException.UNSUPPORTED_FUNCTION_ALTERNATIVE)
/**
* This method is used for bulk streaming. An example of bulk streaming is for analytics or bulk updates included but not limited to model changes.
*
* @since 1.0.0
*
* @param query Query to execute and stream
*
* @param queryStreamClass Class instance of the database stream
*/
@Throws(OnyxException::class)
override fun stream(query: Query, queryStreamClass: Class<*>) = proxy.stream(query, queryStreamClass)
/**
* Get Map representation of an entity with reference id.
*
* This is unsupported in the RemotePersistenceManager. The reason is because it should not apply since the stream API
* is not supported as a proxy QueryStream.
*
* @param entityType Original type of entity
*
* @param reference Reference location within a data structure
*
* @return Map of key key pair of the entity. Key being the attribute name.
*/
@Throws(OnyxException::class)
override fun getMapWithReferenceId(entityType: Class<*>, reference: Reference): Map<String, *>? = proxy.getMapWithReferenceId(entityType, reference)
/**
* Retrieve the quantity of entities that match the query criteria.
*
*
* usage:
*
*
* Query myQuery = new Query();
* myQuery.setClass(SystemEntity.class);
* long numberOfSystemEntities = persistenceManager.countForQuery(myQuery);
*
*
* or:
*
*
* Query myQuery = new Query(SystemEntity.class, new QueryCriteria("primaryKey", QueryCriteriaOperator.GREATER_THAN, 3));
* long numberOfSystemEntitiesWithIdGt3 = persistenceManager.countForQuery(myQuery);
*
* @param query The query to apply to the count operation
* @return The number of entities that meet the query criterion
* @throws OnyxException Error during query.
* @since 1.3.0 Implemented with feature request #71
*/
@Throws(OnyxException::class)
override fun countForQuery(query: Query): Long = proxy.countForQuery(query)
/**
* Un-register a query listener. This will remove the listener from observing changes for that query.
* If you do not un-register queries, they will not expire nor will they be de-registered automatically.
* This could cause performance degrading if removing the registration is neglected.
*
* These will eventually be cleared out by the server when it detects connections have been dropped but,
* it is better to be pro-active about it.
*
* @param query Query with a listener attached
*
* @throws OnyxException Un expected error when attempting to unregister listener
*
* @since 1.3.0 Added query subscribers as an enhancement.
*/
@Throws(OnyxException::class)
override fun removeChangeListener(query: Query): Boolean {
// Ensure the original change listener is attached and is a remote query listener
if (query.changeListener != null && query.changeListener is RemoteQueryListener<*>) {
// Un-register query
val retVal = proxy.removeChangeListener(query)
val remoteQueryListener = query.changeListener as RemoteQueryListener<*>
this.pushRegistrar.unregister(remoteQueryListener)
return retVal
}
return false
}
/**
* Listen to a query and register its subscriber
*
* @param query Query with query listener
* @since 1.3.1
*/
@Throws(OnyxException::class)
override fun listen(query: Query) {
query.cache = true
// Register the query listener as a push subscriber / receiver
val remoteQueryListener = RemoteQueryListener(query.changeListener)
this.pushRegistrar.register(remoteQueryListener, remoteQueryListener)
query.changeListener = remoteQueryListener
proxy.listen(query)
}
}
| agpl-3.0 | b9e5451d4a87f2540e1a005089c93ff8 | 36.551515 | 206 | 0.685173 | 4.716569 | false | false | false | false |
SimpleMobileTools/Simple-Calendar | app/src/main/kotlin/com/simplemobiletools/calendar/pro/fragments/YearFragment.kt | 1 | 5116 | package com.simplemobiletools.calendar.pro.fragments
import android.os.Bundle
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.simplemobiletools.calendar.pro.R
import com.simplemobiletools.calendar.pro.activities.MainActivity
import com.simplemobiletools.calendar.pro.extensions.config
import com.simplemobiletools.calendar.pro.extensions.getViewBitmap
import com.simplemobiletools.calendar.pro.extensions.printBitmap
import com.simplemobiletools.calendar.pro.helpers.YEAR_LABEL
import com.simplemobiletools.calendar.pro.helpers.YearlyCalendarImpl
import com.simplemobiletools.calendar.pro.interfaces.YearlyCalendar
import com.simplemobiletools.calendar.pro.models.DayYearly
import com.simplemobiletools.calendar.pro.views.SmallMonthView
import com.simplemobiletools.commons.extensions.getProperPrimaryColor
import com.simplemobiletools.commons.extensions.getProperTextColor
import com.simplemobiletools.commons.extensions.updateTextColors
import kotlinx.android.synthetic.main.fragment_year.view.*
import org.joda.time.DateTime
class YearFragment : Fragment(), YearlyCalendar {
private var mYear = 0
private var mSundayFirst = false
private var isPrintVersion = false
private var lastHash = 0
private var mCalendar: YearlyCalendarImpl? = null
lateinit var mView: View
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
mView = inflater.inflate(R.layout.fragment_year, container, false)
mYear = requireArguments().getInt(YEAR_LABEL)
requireContext().updateTextColors(mView.calendar_holder)
setupMonths()
mCalendar = YearlyCalendarImpl(this, requireContext(), mYear)
return mView
}
override fun onPause() {
super.onPause()
mSundayFirst = requireContext().config.isSundayFirst
}
override fun onResume() {
super.onResume()
val sundayFirst = requireContext().config.isSundayFirst
if (sundayFirst != mSundayFirst) {
mSundayFirst = sundayFirst
setupMonths()
}
updateCalendar()
}
fun updateCalendar() {
mCalendar?.getEvents(mYear)
}
private fun setupMonths() {
val dateTime = DateTime().withDate(mYear, 2, 1).withHourOfDay(12)
val days = dateTime.dayOfMonth().maximumValue
mView.month_2.setDays(days)
val now = DateTime()
for (i in 1..12) {
val monthView = mView.findViewById<SmallMonthView>(resources.getIdentifier("month_$i", "id", requireContext().packageName))
var dayOfWeek = dateTime.withMonthOfYear(i).dayOfWeek().get()
if (!mSundayFirst) {
dayOfWeek--
}
val monthLabel = mView.findViewById<TextView>(resources.getIdentifier("month_${i}_label", "id", requireContext().packageName))
val curTextColor = when {
isPrintVersion -> resources.getColor(R.color.theme_light_text_color)
else -> requireContext().getProperTextColor()
}
monthLabel.setTextColor(curTextColor)
monthView.firstDay = dayOfWeek
monthView.setOnClickListener {
(activity as MainActivity).openMonthFromYearly(DateTime().withDate(mYear, i, 1))
}
}
if (!isPrintVersion) {
markCurrentMonth(now)
}
}
private fun markCurrentMonth(now: DateTime) {
if (now.year == mYear) {
val monthLabel = mView.findViewById<TextView>(resources.getIdentifier("month_${now.monthOfYear}_label", "id", requireContext().packageName))
monthLabel.setTextColor(requireContext().getProperPrimaryColor())
val monthView = mView.findViewById<SmallMonthView>(resources.getIdentifier("month_${now.monthOfYear}", "id", requireContext().packageName))
monthView.todaysId = now.dayOfMonth
}
}
override fun updateYearlyCalendar(events: SparseArray<ArrayList<DayYearly>>, hashCode: Int) {
if (!isAdded)
return
if (hashCode == lastHash) {
return
}
lastHash = hashCode
for (i in 1..12) {
val monthView = mView.findViewById<SmallMonthView>(resources.getIdentifier("month_$i", "id", requireContext().packageName))
monthView.setEvents(events.get(i))
}
}
fun printCurrentView() {
isPrintVersion = true
setupMonths()
toggleSmallMonthPrintModes()
requireContext().printBitmap(mView.calendar_holder.getViewBitmap())
isPrintVersion = false
setupMonths()
toggleSmallMonthPrintModes()
}
private fun toggleSmallMonthPrintModes() {
for (i in 1..12) {
val monthView = mView.findViewById<SmallMonthView>(resources.getIdentifier("month_$i", "id", requireContext().packageName))
monthView.togglePrintMode()
}
}
}
| gpl-3.0 | ca060e3cfabfaa4a4234c5880bc81915 | 35.542857 | 152 | 0.684128 | 4.723915 | false | false | false | false |
firebase/friendlyeats-android | app/src/main/java/com/google/firebase/example/fireeats/adapter/RestaurantAdapter.kt | 1 | 2618 | package com.google.firebase.example.fireeats.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.google.firebase.example.fireeats.R
import com.google.firebase.example.fireeats.databinding.ItemRestaurantBinding
import com.google.firebase.example.fireeats.model.Restaurant
import com.google.firebase.example.fireeats.util.RestaurantUtil
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.Query
import com.google.firebase.firestore.ktx.toObject
/**
* RecyclerView adapter for a list of Restaurants.
*/
open class RestaurantAdapter(query: Query, private val listener: OnRestaurantSelectedListener) :
FirestoreAdapter<RestaurantAdapter.ViewHolder>(query) {
interface OnRestaurantSelectedListener {
fun onRestaurantSelected(restaurant: DocumentSnapshot)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(ItemRestaurantBinding.inflate(
LayoutInflater.from(parent.context), parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getSnapshot(position), listener)
}
class ViewHolder(val binding: ItemRestaurantBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(
snapshot: DocumentSnapshot,
listener: OnRestaurantSelectedListener?
) {
val restaurant = snapshot.toObject<Restaurant>()
if (restaurant == null) {
return
}
val resources = binding.root.resources
// Load image
Glide.with(binding.restaurantItemImage.context)
.load(restaurant.photo)
.into(binding.restaurantItemImage)
val numRatings: Int = restaurant.numRatings
binding.restaurantItemName.text = restaurant.name
binding.restaurantItemRating.rating = restaurant.avgRating.toFloat()
binding.restaurantItemCity.text = restaurant.city
binding.restaurantItemCategory.text = restaurant.category
binding.restaurantItemNumRatings.text = resources.getString(
R.string.fmt_num_ratings,
numRatings)
binding.restaurantItemPrice.text = RestaurantUtil.getPriceString(restaurant)
// Click listener
binding.root.setOnClickListener {
listener?.onRestaurantSelected(snapshot)
}
}
}
}
| apache-2.0 | 8a04eec1c7c300bdadd0ce663d0d4a18 | 35.873239 | 98 | 0.694423 | 5.083495 | false | false | false | false |
ianhanniballake/muzei | source-gallery/src/main/java/com/google/android/apps/muzei/gallery/GallerySettingsActivity.kt | 1 | 34239 | /*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.gallery
import android.Manifest
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.DocumentsContract
import android.provider.Settings
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.MotionEvent
import android.view.View
import android.view.ViewAnimationUtils
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.result.launch
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import androidx.core.graphics.Insets
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.paging.ExperimentalPagingApi
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.clear
import coil.load
import com.google.android.apps.muzei.gallery.databinding.GalleryActivityBinding
import com.google.android.apps.muzei.gallery.databinding.GalleryChosenPhotoItemBinding
import com.google.android.apps.muzei.util.MultiSelectionController
import com.google.android.apps.muzei.util.getString
import com.google.android.apps.muzei.util.getStringOrNull
import com.google.android.apps.muzei.util.launchWhenStartedIn
import com.google.android.apps.muzei.util.toast
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import java.util.ArrayList
import java.util.LinkedList
import kotlin.math.hypot
import kotlin.math.max
private class GetContentsFromActivityInfo : ActivityResultContract<ActivityInfo, List<Uri>>() {
private val getMultipleContents = ActivityResultContracts.GetMultipleContents()
override fun createIntent(context: Context, input: ActivityInfo): Intent =
getMultipleContents.createIntent(context, "image/*")
.setClassName(input.packageName, input.name)
override fun parseResult(resultCode: Int, intent: Intent?): List<Uri> =
getMultipleContents.parseResult(resultCode, intent)
}
private class ChoosePhotos : ActivityResultContract<Unit, List<Uri>>() {
private val openMultipleDocuments = ActivityResultContracts.OpenMultipleDocuments()
@SuppressLint("InlinedApi")
override fun createIntent(context: Context, input: Unit?) =
openMultipleDocuments.createIntent(context, arrayOf("image/*"))
.addCategory(Intent.CATEGORY_OPENABLE)
.putExtra(DocumentsContract.EXTRA_EXCLUDE_SELF, true)
override fun parseResult(resultCode: Int, intent: Intent?): List<Uri> =
openMultipleDocuments.parseResult(resultCode, intent)
}
private class ChooseFolder : ActivityResultContract<Unit, Uri?>() {
private val openDocumentTree = ActivityResultContracts.OpenDocumentTree()
@SuppressLint("InlinedApi")
override fun createIntent(context: Context, input: Unit?) =
openDocumentTree.createIntent(context, null)
.putExtra(DocumentsContract.EXTRA_EXCLUDE_SELF, true)
override fun parseResult(resultCode: Int, intent: Intent?) =
openDocumentTree.parseResult(resultCode, intent)
}
class GallerySettingsActivity : AppCompatActivity(),
GalleryImportPhotosDialogFragment.OnRequestContentListener, MultiSelectionController.Callbacks {
companion object {
private const val TAG = "GallerySettingsActivity"
private const val SHARED_PREF_NAME = "GallerySettingsActivity"
private const val SHOW_INTERNAL_STORAGE_MESSAGE = "show_internal_storage_message"
internal val CHOSEN_PHOTO_DIFF_CALLBACK: DiffUtil.ItemCallback<ChosenPhoto> = object : DiffUtil.ItemCallback<ChosenPhoto>() {
override fun areItemsTheSame(oldItem: ChosenPhoto, newItem: ChosenPhoto): Boolean {
return oldItem.uri == newItem.uri
}
override fun areContentsTheSame(oldItem: ChosenPhoto, newItem: ChosenPhoto): Boolean {
// If the items are the same (same image URI), then they are equivalent and
// no change animation is needed
return true
}
}
}
private val viewModel: GallerySettingsViewModel by viewModels()
private val requestStoragePermission = registerForActivityResult(RequestStoragePermissions()) {
onDataSetChanged()
}
/**
* Use ACTION_OPEN_DOCUMENT by default for adding photos.
* This allows us to use persistent URI permissions to access the underlying photos
* meaning we don't need to use additional storage space and will pull in edits automatically
* in addition to syncing deletions.
*
* (There's a separate 'Import photos' option which uses ACTION_GET_CONTENT to support
* legacy apps)
*/
private val choosePhotos = registerForActivityResult(ChoosePhotos()) { photos ->
processSelectedUris(photos)
}
private val chooseFolder = registerForActivityResult(ChooseFolder()) { folder ->
if (folder != null) {
getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE).edit {
putBoolean(SHOW_INTERNAL_STORAGE_MESSAGE, false)
}
}
processSelectedUris(listOfNotNull(folder))
}
private val getContents = registerForActivityResult(GetContentsFromActivityInfo()) { photos ->
processSelectedUris(photos)
}
private lateinit var binding: GalleryActivityBinding
private var itemSize = 10
private val multiSelectionController = MultiSelectionController(this)
private val placeholderDrawable: ColorDrawable by lazy {
ColorDrawable(ContextCompat.getColor(this,
R.color.gallery_chosen_photo_placeholder))
}
private var updatePosition = -1
private var lastTouchPosition: Int = 0
private var lastTouchX: Int = 0
private var lastTouchY: Int = 0
private val chosenPhotosAdapter = GalleryAdapter()
@ExperimentalPagingApi
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = GalleryActivityBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
setupMultiSelect()
val gridLayoutManager = GridLayoutManager(this, 1)
binding.photoGrid.apply {
layoutManager = gridLayoutManager
itemAnimator = DefaultItemAnimator().apply {
supportsChangeAnimations = false
}
}
val vto = binding.photoGrid.viewTreeObserver
vto.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
val width = (binding.photoGrid.width
- binding.photoGrid.paddingStart - binding.photoGrid.paddingEnd)
if (width <= 0) {
return
}
// Compute number of columns
val maxItemWidth = resources.getDimensionPixelSize(
R.dimen.gallery_chosen_photo_grid_max_item_size)
var numColumns = 1
while (true) {
if (width / numColumns > maxItemWidth) {
++numColumns
} else {
break
}
}
val spacing = resources.getDimensionPixelSize(
R.dimen.gallery_chosen_photo_grid_spacing)
itemSize = (width - spacing * (numColumns - 1)) / numColumns
// Complete setup
gridLayoutManager.spanCount = numColumns
binding.photoGrid.adapter = chosenPhotosAdapter
binding.photoGrid.viewTreeObserver.removeOnGlobalLayoutListener(this)
tryUpdateSelection(false)
}
})
ViewCompat.setOnApplyWindowInsetsListener(binding.photoGrid) { v, insets ->
val gridSpacing = resources
.getDimensionPixelSize(R.dimen.gallery_chosen_photo_grid_spacing)
ViewCompat.onApplyWindowInsets(v, WindowInsetsCompat.Builder(insets)
.setSystemWindowInsets(Insets.of(
insets.systemWindowInsetLeft + gridSpacing,
gridSpacing,
insets.systemWindowInsetRight + gridSpacing,
insets.systemWindowInsetBottom +
insets.systemWindowInsetTop + gridSpacing +
resources.getDimensionPixelSize(R.dimen.gallery_fab_space)))
.build())
insets
}
binding.enableRandom.setOnClickListener {
requestStoragePermission.launch()
}
binding.editPermissionSettings.setOnClickListener {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", packageName, null))
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
binding.addFab.apply {
setOnClickListener {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// On Lollipop and higher, we show the add toolbar to allow users to add either
// individual photos or a whole directory
showAddToolbar()
} else {
requestPhotos()
}
}
}
binding.addPhotos.setOnClickListener { requestPhotos() }
binding.addFolder.setOnClickListener {
try {
chooseFolder.launch()
val preferences = getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE)
if (preferences.getBoolean(SHOW_INTERNAL_STORAGE_MESSAGE, true)) {
toast(R.string.gallery_internal_storage_message, Toast.LENGTH_LONG)
}
} catch (e: ActivityNotFoundException) {
Snackbar.make(binding.photoGrid, R.string.gallery_add_folder_error,
Snackbar.LENGTH_LONG).show()
hideAddToolbar(true)
}
}
viewModel.chosenPhotos.onEach {
chosenPhotosAdapter.submitData(it)
}.launchWhenStartedIn(this)
chosenPhotosAdapter.loadStateFlow.onEach {
onDataSetChanged()
}.launchWhenStartedIn(this)
viewModel.getContentActivityInfoList.map {
it.size
}.distinctUntilChanged().onEach {
invalidateOptionsMenu()
}.launchWhenStartedIn(this)
GalleryScanWorker.enqueueRescan(this)
}
private fun requestPhotos() {
try {
choosePhotos.launch()
} catch (e: ActivityNotFoundException) {
Snackbar.make(binding.photoGrid, R.string.gallery_add_photos_error,
Snackbar.LENGTH_LONG).show()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
hideAddToolbar(true)
}
}
}
override fun onResume() {
super.onResume()
// Permissions might have changed in the background
onDataSetChanged()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.gallery_activity, menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
super.onPrepareOptionsMenu(menu)
// Make sure the 'Import photos' MenuItem is set up properly based on the number of
// activities that handle ACTION_GET_CONTENT
// 0 = hide the MenuItem
// 1 = show 'Import photos from APP_NAME' to go to the one app that exists
// 2 = show 'Import photos...' to have the user pick which app to import photos from
val getContentActivities = viewModel.getContentActivityInfoList.value
// Hide the 'Import photos' action if there are no activities found
val importPhotosMenuItem = menu.findItem(R.id.action_import_photos)
importPhotosMenuItem.isVisible = getContentActivities.isNotEmpty()
// If there's only one app that supports ACTION_GET_CONTENT, tell the user what that app is
if (getContentActivities.size == 1) {
importPhotosMenuItem.title = getString(R.string.gallery_action_import_photos_from,
getContentActivities.first().loadLabel(packageManager))
} else {
importPhotosMenuItem.setTitle(R.string.gallery_action_import_photos)
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_import_photos -> {
when (viewModel.getContentActivityInfoList.value.size) {
0 -> {
// Ignore
}
1 -> {
// Just start the one ACTION_GET_CONTENT app
requestGetContent(viewModel.getContentActivityInfoList.value.first())
}
else -> {
// Let the user pick which app they want to import photos from
GalleryImportPhotosDialogFragment.show(supportFragmentManager)
}
}
return true
}
R.id.action_clear_photos -> {
val context = this
lifecycleScope.launch(NonCancellable) {
GalleryDatabase.getInstance(context)
.chosenPhotoDao().deleteAll(context)
}
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
override fun requestGetContent(info: ActivityInfo) {
getContents.launch(info)
}
private fun setupMultiSelect() {
// Set up toolbar
binding.selectionToolbar.setNavigationOnClickListener {
multiSelectionController.reset(true)
}
binding.selectionToolbar.inflateMenu(R.menu.gallery_selection)
binding.selectionToolbar.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.action_remove -> {
val removePhotos = ArrayList(
multiSelectionController.selection)
lifecycleScope.launch(NonCancellable) {
// Remove chosen URIs
GalleryDatabase.getInstance(this@GallerySettingsActivity)
.chosenPhotoDao()
.delete(this@GallerySettingsActivity, removePhotos)
}
multiSelectionController.reset(true)
return@setOnMenuItemClickListener true
}
else -> return@setOnMenuItemClickListener false
}
}
// Set up controller
multiSelectionController.callbacks = this
}
override fun onSelectionChanged(restored: Boolean, fromUser: Boolean) {
tryUpdateSelection(!restored)
}
override fun onBackPressed() {
when {
multiSelectionController.selectedCount > 0 -> multiSelectionController.reset(true)
binding.addToolbar.visibility == View.VISIBLE -> hideAddToolbar(true)
else -> super.onBackPressed()
}
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private fun showAddToolbar() {
// Divide by two since we're doing two animations but we want the total time to the short animation time
val duration = resources.getInteger(android.R.integer.config_shortAnimTime) / 2
// Hide the add button
binding.addFab.animate()
.scaleX(0f)
.scaleY(0f)
.translationY(resources.getDimension(R.dimen.gallery_fab_margin))
.setDuration(duration.toLong())
.withEndAction {
if (isDestroyed) {
return@withEndAction
}
binding.addFab.visibility = View.INVISIBLE
// Then show the toolbar
binding.addToolbar.visibility = View.VISIBLE
ViewAnimationUtils.createCircularReveal(
binding.addToolbar,
binding.addToolbar.width / 2,
binding.addToolbar.height / 2,
0f,
(binding.addToolbar.width / 2).toFloat())
.setDuration(duration.toLong())
.start()
}
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private fun hideAddToolbar(showAddButton: Boolean) {
// Divide by two since we're doing two animations but we want the total time to the short animation time
val duration = resources.getInteger(android.R.integer.config_shortAnimTime) / 2
// Hide the toolbar
val hideAnimator = ViewAnimationUtils.createCircularReveal(
binding.addToolbar,
binding.addToolbar.width / 2,
binding.addToolbar.height / 2,
(binding.addToolbar.width / 2).toFloat(),
0f).setDuration((if (showAddButton) duration else duration * 2).toLong())
hideAnimator.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
binding.addToolbar.visibility = View.INVISIBLE
if (showAddButton) {
binding.addFab.visibility = View.VISIBLE
binding.addFab.animate()
.scaleX(1f)
.scaleY(1f)
.translationY(0f).duration = duration.toLong()
} else {
// Just reset the translationY
binding.addFab.translationY = 0f
}
}
})
hideAnimator.start()
}
private fun tryUpdateSelection(allowAnimate: Boolean) {
if (updatePosition >= 0) {
chosenPhotosAdapter.notifyItemChanged(updatePosition)
updatePosition = -1
} else {
chosenPhotosAdapter.notifyDataSetChanged()
}
val selectedCount = multiSelectionController.selectedCount
val toolbarVisible = selectedCount > 0
val previouslyVisible: Boolean = binding.selectionToolbarContainer.getTag(
R.id.gallery_viewtag_previously_visible) as? Boolean ?: false
if (previouslyVisible != toolbarVisible) {
binding.selectionToolbarContainer.setTag(R.id.gallery_viewtag_previously_visible, toolbarVisible)
val duration = if (allowAnimate)
resources.getInteger(android.R.integer.config_shortAnimTime)
else
0
if (toolbarVisible) {
binding.selectionToolbarContainer.visibility = View.VISIBLE
binding.selectionToolbarContainer.translationY = (-binding.selectionToolbarContainer.height).toFloat()
binding.selectionToolbarContainer.animate()
.translationY(0f)
.setDuration(duration.toLong())
.withEndAction(null)
if (binding.addToolbar.visibility == View.VISIBLE) {
hideAddToolbar(false)
} else {
binding.addFab.animate()
.scaleX(0f)
.scaleY(0f)
.setDuration(duration.toLong())
.withEndAction { binding.addFab.visibility = View.INVISIBLE }
}
} else {
binding.selectionToolbarContainer.animate()
.translationY((-binding.selectionToolbarContainer.height).toFloat())
.setDuration(duration.toLong())
.withEndAction { binding.selectionToolbarContainer.visibility = View.INVISIBLE }
binding.addFab.visibility = View.VISIBLE
binding.addFab.animate()
.scaleY(1f)
.scaleX(1f)
.setDuration(duration.toLong())
.withEndAction(null)
}
}
if (toolbarVisible) {
val title = selectedCount.toString()
if (selectedCount == 1) {
// If they've selected a tree URI, show the DISPLAY_NAME instead of just '1'
val selectedId = multiSelectionController.selection.iterator().next()
lifecycleScope.launch(Dispatchers.Main) {
val chosenPhoto = GalleryDatabase.getInstance(this@GallerySettingsActivity)
.chosenPhotoDao()
.getChosenPhoto(selectedId)
if (chosenPhoto?.isTreeUri == true && binding.selectionToolbar.isAttachedToWindow) {
getDisplayNameForTreeUri(chosenPhoto.uri)?.takeUnless { it.isEmpty() }?.run {
binding.selectionToolbar.title = this
}
}
}
}
binding.selectionToolbar.title = title
}
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private fun getDisplayNameForTreeUri(treeUri: Uri): String? {
val documentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri,
DocumentsContract.getTreeDocumentId(treeUri))
try {
contentResolver.query(documentUri,
arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME),
null, null, null)?.use { data ->
if (data.moveToNext()) {
return data.getStringOrNull(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
}
}
} catch (e: SecurityException) {
// No longer can read this URI, which means no display name for this URI
}
return null
}
private fun onDataSetChanged() {
if (chosenPhotosAdapter.itemCount != 0) {
binding.empty.visibility = View.GONE
// We have at least one image, so consider the Gallery source properly setup
setResult(RESULT_OK)
} else {
// No chosen images, show the empty View
binding.empty.visibility = View.VISIBLE
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// Permission is granted, we can show the random camera photos image
GalleryScanWorker.enqueueRescan(this)
binding.emptyAnimator.displayedChild = 0
binding.emptyDescription.setText(R.string.gallery_empty)
setResult(RESULT_OK)
} else {
// We have no images until they enable the permission
setResult(RESULT_CANCELED)
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// We should show rationale on why they should enable the storage permission and
// random camera photos
binding.emptyAnimator.displayedChild = 1
binding.emptyDescription.setText(R.string.gallery_permission_rationale)
} else {
// The user has permanently denied the storage permission. Give them a link to app settings
binding.emptyAnimator.displayedChild = 2
binding.emptyDescription.setText(R.string.gallery_denied_explanation)
}
}
}
}
internal class PhotoViewHolder(
val binding: GalleryChosenPhotoItemBinding
) : RecyclerView.ViewHolder(binding.root) {
val thumbViews = listOf(
binding.thumbnail1,
binding.thumbnail2,
binding.thumbnail3,
binding.thumbnail4)
}
private inner class GalleryAdapter : PagingDataAdapter<ChosenPhoto, PhotoViewHolder>(CHOSEN_PHOTO_DIFF_CALLBACK) {
private val handler by lazy { Handler(Looper.getMainLooper()) }
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotoViewHolder {
val binding = GalleryChosenPhotoItemBinding.inflate(
LayoutInflater.from(this@GallerySettingsActivity),
parent, false)
val vh = PhotoViewHolder(binding)
binding.root.layoutParams.height = itemSize
binding.root.setOnTouchListener { _, motionEvent ->
if (motionEvent.actionMasked != MotionEvent.ACTION_CANCEL) {
lastTouchPosition = vh.bindingAdapterPosition
lastTouchX = motionEvent.x.toInt()
lastTouchY = motionEvent.y.toInt()
}
false
}
binding.root.setOnClickListener {
updatePosition = vh.bindingAdapterPosition
if (updatePosition != RecyclerView.NO_POSITION) {
val chosenPhoto = getItem(updatePosition)
multiSelectionController.toggle(chosenPhoto?.id ?: -1, true)
}
}
return vh
}
override fun onBindViewHolder(vh: PhotoViewHolder, position: Int) {
val chosenPhoto = getItem(position) ?: return
vh.binding.folderIcon.visibility = if (chosenPhoto.isTreeUri) View.VISIBLE else View.GONE
val maxImages = vh.thumbViews.size
val images = if (chosenPhoto.isTreeUri)
getImagesFromTreeUri(chosenPhoto.uri, maxImages)
else
listOf(chosenPhoto.contentUri)
val numImages = images.size
val targetSize = if (numImages <= 1) itemSize else itemSize / 2
for (h in 0 until numImages) {
val thumbView = vh.thumbViews[h]
thumbView.visibility = View.VISIBLE
thumbView.load(images[h]) {
size(targetSize)
placeholder(placeholderDrawable)
}
}
for (h in numImages until maxImages) {
val thumbView = vh.thumbViews[h]
// Show either just the one image or all the images even if
// they are just placeholders
thumbView.visibility = if (numImages <= 1) View.GONE else View.VISIBLE
thumbView.clear()
thumbView.setImageDrawable(placeholderDrawable)
}
val checked = multiSelectionController.isSelected(chosenPhoto.id)
vh.itemView.setTag(R.id.gallery_viewtag_position, position)
if (lastTouchPosition == vh.bindingAdapterPosition && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
handler.post {
if (!vh.binding.checkedOverlay.isAttachedToWindow) {
// Can't animate detached Views
vh.binding.checkedOverlay.visibility = if (checked) View.VISIBLE else View.GONE
return@post
}
if (checked) {
vh.binding.checkedOverlay.visibility = View.VISIBLE
}
// find the smallest radius that'll cover the item
val coverRadius = maxDistanceToCorner(
lastTouchX, lastTouchY,
0, 0, vh.itemView.width, vh.itemView.height)
val revealAnim = ViewAnimationUtils.createCircularReveal(
vh.binding.checkedOverlay,
lastTouchX,
lastTouchY,
if (checked) 0f else coverRadius,
if (checked) coverRadius else 0f)
.setDuration(150)
if (!checked) {
revealAnim.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
vh.binding.checkedOverlay.visibility = View.GONE
}
})
}
revealAnim.start()
}
} else {
vh.binding.checkedOverlay.visibility = if (checked) View.VISIBLE else View.GONE
}
}
private fun maxDistanceToCorner(x: Int, y: Int, left: Int, top: Int, right: Int, bottom: Int): Float {
var maxDistance = 0f
maxDistance = max(maxDistance, hypot((x - left).toDouble(), (y - top).toDouble()).toFloat())
maxDistance = max(maxDistance, hypot((x - right).toDouble(), (y - top).toDouble()).toFloat())
maxDistance = max(maxDistance, hypot((x - left).toDouble(), (y - bottom).toDouble()).toFloat())
maxDistance = max(maxDistance, hypot((x - right).toDouble(), (y - bottom).toDouble()).toFloat())
return maxDistance
}
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
private fun getImagesFromTreeUri(treeUri: Uri, maxImages: Int): List<Uri> {
val images = ArrayList<Uri>()
val directories = LinkedList<String>()
directories.add(DocumentsContract.getTreeDocumentId(treeUri))
while (images.size < maxImages && !directories.isEmpty()) {
val parentDocumentId = directories.poll()
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri,
parentDocumentId)
try {
contentResolver.query(childrenUri,
arrayOf(DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_MIME_TYPE),
null, null, null)?.use { children ->
while (children.moveToNext()) {
val documentId = children.getString(
DocumentsContract.Document.COLUMN_DOCUMENT_ID)
val mimeType = children.getString(
DocumentsContract.Document.COLUMN_MIME_TYPE)
if (DocumentsContract.Document.MIME_TYPE_DIR == mimeType) {
directories.add(documentId)
} else if (mimeType.startsWith("image/")) {
// Add images to the list
images.add(DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId))
}
if (images.size == maxImages) {
break
}
}
}
} catch (e: SecurityException) {
// No longer can read this URI, which means no children from this URI
} catch (e: Exception) {
// Could be anything: NullPointerException, IllegalArgumentException, etc.
Log.i(TAG, "Unable to load images from $treeUri", e)
}
}
return images
}
private fun processSelectedUris(uris: List<Uri>) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (!binding.addToolbar.isAttachedToWindow) {
// Can't animate detached Views
binding.addToolbar.visibility = View.INVISIBLE
binding.addFab.visibility = View.VISIBLE
} else {
hideAddToolbar(true)
}
}
if (uris.isEmpty()) {
// Nothing to do, so we can avoid posting the runnable at all
return
}
// Update chosen URIs
lifecycleScope.launch(NonCancellable) {
GalleryDatabase.getInstance(this@GallerySettingsActivity)
.chosenPhotoDao()
.insertAll(this@GallerySettingsActivity, uris)
}
}
}
| apache-2.0 | 04077589581852fb441cccddaef2ec38 | 42.727969 | 138 | 0.601273 | 5.518859 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/fileTypes/UpdateComponentWatcher.kt | 10 | 5359 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.fileTypes
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.editor.ex.EditorEventMulticasterEx
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.FocusChangeListener
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.updateSettings.impl.PluginDownloader
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.ObjectUtils
import com.intellij.util.io.HttpRequests
import org.jdom.JDOMException
import java.io.IOException
import java.net.URLEncoder
import java.net.UnknownHostException
import java.util.*
import java.util.concurrent.TimeUnit
private val EP_NAME = ExtensionPointName<FileTypeStatisticProvider>("com.intellij.fileTypeStatisticProvider")
@Service
private class UpdateComponentWatcher : Disposable {
init {
// rely on fact that service will be initialized only once
// TODO: Use message bus once it will be provided by platform
val multicaster = EditorFactory.getInstance().eventMulticaster
if (multicaster is EditorEventMulticasterEx) {
multicaster.addFocusChangeListener(object : FocusChangeListener {
override fun focusGained(editor: Editor) {
scheduleUpdate(editor)
}
}, this)
}
}
fun scheduleUpdate(editor: Editor) {
val fileType = (editor as EditorEx).virtualFile?.fileType ?: return
// TODO: `accept` can be slow (CloudFormationFileTypeStatisticProvider), we should not call it synchronously
val ep = EP_NAME.findFirstSafe { it.accept(editor, fileType) } ?: return
// TODO: Use PluginAware EP
val plugin = EP_NAME.computeIfAbsent(ep, UpdateComponentWatcher::class.java) {
Optional.ofNullable(PluginManagerCore.getPlugin(PluginId.getId(ep.pluginId)))
}
val pluginIdString = ep.pluginId
if (!plugin.isPresent) {
LOG.error("Unknown plugin id: $pluginIdString is reported by ${ep::class.java}")
return
}
val pluginVersion = plugin.get().version
if (checkUpdateRequired(pluginIdString, pluginVersion)) {
ApplicationManager.getApplication().executeOnPooledThread {
update(pluginIdString, pluginVersion)
}
}
}
override fun dispose() {
}
}
private class UpdateComponentEditorListener : EditorFactoryListener {
override fun editorCreated(event: EditorFactoryEvent) {
if (!ApplicationManager.getApplication().isUnitTestMode) {
service<UpdateComponentWatcher>().scheduleUpdate(event.editor)
}
}
}
private val lock = ObjectUtils.sentinel("updating_monitor")
private val LOG = logger<UpdateComponentWatcher>()
private fun update(pluginIdString: String, pluginVersion: String) {
val url = getUpdateUrl(pluginIdString, pluginVersion)
sendRequest(url)
}
private fun checkUpdateRequired(pluginIdString: String, pluginVersion: String): Boolean {
synchronized(lock) {
val lastVersionKey = "$pluginIdString.LAST_VERSION"
val lastUpdateKey = "$pluginIdString.LAST_UPDATE"
val properties = PropertiesComponent.getInstance()
val lastPluginVersion = properties.getValue(lastVersionKey)
val lastUpdate = properties.getLong(lastUpdateKey, 0L)
val shouldUpdate = lastUpdate == 0L
|| System.currentTimeMillis() - lastUpdate > TimeUnit.DAYS.toMillis(1)
|| lastPluginVersion == null
|| lastPluginVersion != pluginVersion
if (!shouldUpdate) return false
properties.setValue(lastUpdateKey, System.currentTimeMillis().toString())
properties.setValue(lastVersionKey, pluginVersion)
return true
}
}
private fun sendRequest(url: String) {
try {
HttpRequests.request(url).connect {
try {
JDOMUtil.load(it.inputStream)
}
catch (e: JDOMException) {
LOG.warn(e)
}
LOG.info("updated: $url")
}
}
catch (ignored: UnknownHostException) {
// No internet connections, no need to log anything
}
catch (e: IOException) {
LOG.warn(e)
}
}
private fun getUpdateUrl(pluginIdString: String, pluginVersion: String): String {
val applicationInfo = ApplicationInfoEx.getInstanceEx()
val buildNumber = applicationInfo.build.asString()
val os = URLEncoder.encode("${SystemInfo.OS_NAME} ${SystemInfo.OS_VERSION}", Charsets.UTF_8.name())
val uid = PluginDownloader.getMarketplaceDownloadsUUID()
val baseUrl = "https://plugins.jetbrains.com/plugins/list"
return "$baseUrl?pluginId=$pluginIdString&build=$buildNumber&pluginVersion=$pluginVersion&os=$os&uuid=$uid"
} | apache-2.0 | 211c29269a1860c93f1300919654add0 | 36.482517 | 140 | 0.754059 | 4.58426 | false | false | false | false |
vnesek/nmote-jwt-issuer | src/main/kotlin/com/nmote/jwti/model/User.kt | 1 | 3704 | /*
* Copyright 2017. Vjekoslav Nesek
* 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.nmote.jwti.model
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import org.springframework.data.annotation.Id
import org.springframework.data.annotation.Transient
import org.springframework.data.mongodb.core.mapping.Field
import java.io.Serializable
import java.time.Instant
import java.util.*
import javax.validation.constraints.Email
@JsonInclude(JsonInclude.Include.NON_NULL)
data class UserData(
val id: String,
val username: String? = null,
val type: String,
val name: String? = null,
val email: String? = null,
val image: String? = null,
val roles: Set<String>? = null,
val scope: Set<String>? = null,
val accounts: List<UserData>? = null)
class User : SocialAccount<JwtiAccessToken>, Serializable {
@Id
@JsonProperty("id")
override var accountId: String = UUID.randomUUID().toString()
@Field("imageURL")
@JsonProperty("imageURL")
override var profileImageURL: String? = null
get() = field ?: firstOrNull(SocialAccount<*>::profileImageURL)
@Field("name")
@JsonProperty("name")
override var profileName: String? = null
get() = field ?: firstOrNull(SocialAccount<*>::profileName)
@Transient
@JsonIgnore
override val socialService: String = "com.nmote.jwti"
@JsonIgnore
override val accessToken: JwtiAccessToken? = null
@Field("email")
@JsonProperty("email")
@get:Email
override var profileEmail: String? = null
get() = field ?: firstOrNull(SocialAccount<*>::profileEmail)
private fun <R : Any> firstOrNull(transform: (SocialAccount<*>) -> R?): R? = accounts.mapNotNull(transform).firstOrNull()
var username: String? = null
var password: String = "not-set"
var roles: MutableMap<String, Set<String>> = mutableMapOf()
var accounts: List<BasicSocialAccount> = emptyList()
var createdAt: Instant = Instant.now()
operator fun get(id: String, service: String): BasicSocialAccount? = accounts.find { it.socialService == service && it.accountId == id }
operator fun get(account: SocialAccount<*>): BasicSocialAccount? = get(account.accountId, account.socialService)
/**
* Add new account to user
*/
operator fun plus(account: BasicSocialAccount): User {
this.minus(account)
this.accounts += account
// Update name / image / email from social account
account.profileEmail?.let { profileEmail = it }
account.profileImageURL?.let { profileImageURL = it }
account.profileName?.let { profileName = it }
return this
}
/** Remove existing account if it exists */
operator fun minus(account: BasicSocialAccount): User {
this[account]?.let { this.accounts -= it }
return this
}
fun merge(user: User) {
accounts += user.accounts
val r = roles.toMutableMap()
for ((app, roles) in user.roles) {
r.merge(app, roles) { u, v -> u + v }
}
}
} | apache-2.0 | e9c9135a39c1c3699f2fdabceb623367 | 31.787611 | 140 | 0.679806 | 4.175874 | false | false | false | false |
Jire/Charlatano | src/main/kotlin/com/charlatano/utils/collections/ListContainer.kt | 1 | 1418 | /*
* Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO
* Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.charlatano.utils.collections
@Suppress("UNCHECKED_CAST")
class ListContainer<E>(capacity: Int) {
private val lists = CacheableList<CacheableList<E>>(capacity)
fun addList(list: CacheableList<E>) = lists.add(list)
fun clear() = lists.clear()
fun empty() = lists.size() == 0
internal inline fun forEach(crossinline action: (E) -> Boolean): Boolean {
return lists.forEach {
it.forEach {
action(it)
}
}
}
fun <E> firstOrNull() = lists[0][0] as E
}
internal inline operator fun <E> ListContainer<E>.invoke(
crossinline action: (E) -> Boolean
) = forEach { action(it) } | agpl-3.0 | 40708e87b6a146460de61d0671e63da3 | 29.847826 | 78 | 0.711566 | 3.683117 | false | false | false | false |
TimePath/java-vfs | src/main/kotlin/com/timepath/vfs/server/fuse/FuseServer.kt | 1 | 2756 | package com.timepath.vfs.server.fuse
import com.timepath.vfs.VFile
import com.timepath.vfs.provider.ProviderStub
import net.fusejna.DirectoryFiller
import net.fusejna.ErrorCodes
import net.fusejna.FuseException
import net.fusejna.StructFuseFileInfo.FileInfoWrapper
import net.fusejna.StructStat.StatWrapper
import net.fusejna.types.TypeMode.NodeType
import net.fusejna.util.FuseFilesystemAdapterFull
import java.io.File
import java.io.IOException
import java.nio.ByteBuffer
import java.util.logging.Level
import java.util.logging.Logger
public class FuseServer(private val mountpoint: File) : ProviderStub(), Runnable {
private val fuse: FuseFilesystemAdapterFull
init {
fuse = object : FuseFilesystemAdapterFull() {
override fun getattr(path: String, stat: StatWrapper): Int {
val file = query(path)
if (file == null) {
return -ErrorCodes.ENOENT()
}
if (file.isDirectory) {
stat.setMode(NodeType.DIRECTORY)
} else {
stat.setMode(NodeType.FILE)
stat.size(Math.max(file.length, 0))
}
return 0
}
override fun read(path: String, buffer: ByteBuffer, size: Long, offset: Long, info: FileInfoWrapper?): Int {
query(path)?.let {
val stream = it.openStream()!!
try {
stream.skip(offset)
val buf = ByteArray(Math.max(Math.min(size, stream.available().toLong()), 0).toInt())
stream.read(buf)
buffer.put(buf)
return buf.size()
} catch (ex: IOException) {
LOG.log(Level.SEVERE, null, ex)
}
}
return -1
}
override fun readdir(path: String, filler: DirectoryFiller): Int {
val file = query(path)
if (file == null) {
return -ErrorCodes.ENOENT()
}
for (vf in file.list()) {
filler.add("$path${VFile.SEPARATOR}${vf.name}")
}
return 0
}
}
}
override fun run() {
try {
LOG.log(Level.INFO, "Mounted on ${mountpoint.getAbsolutePath()}")
fuse.mount(mountpoint)
} catch (ex: FuseException) {
LOG.log(Level.SEVERE, null, ex)
} finally {
LOG.log(Level.INFO, "Unmounted")
}
}
companion object {
private val LOG = Logger.getLogger(javaClass<FuseServer>().getName())
}
}
| artistic-2.0 | 5317881360b1131a7aeddfd3f7e389ed | 32.609756 | 120 | 0.533019 | 4.445161 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | plugins/stream-debugger/src/com/intellij/debugger/streams/trace/impl/TraceExpressionBuilderBase.kt | 4 | 6172 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.debugger.streams.trace.impl
import com.intellij.debugger.streams.lib.HandlerFactory
import com.intellij.debugger.streams.trace.IntermediateCallHandler
import com.intellij.debugger.streams.trace.TerminatorCallHandler
import com.intellij.debugger.streams.trace.TraceExpressionBuilder
import com.intellij.debugger.streams.trace.TraceHandler
import com.intellij.debugger.streams.trace.dsl.ArrayVariable
import com.intellij.debugger.streams.trace.dsl.CodeBlock
import com.intellij.debugger.streams.trace.dsl.Dsl
import com.intellij.debugger.streams.trace.dsl.Variable
import com.intellij.debugger.streams.trace.dsl.impl.TextExpression
import com.intellij.debugger.streams.trace.impl.handler.type.GenericType
import com.intellij.debugger.streams.wrapper.IntermediateStreamCall
import com.intellij.debugger.streams.wrapper.StreamChain
import com.intellij.debugger.streams.wrapper.impl.StreamChainImpl
import java.util.*
/**
* @author Vitaliy.Bibaev
*/
abstract class TraceExpressionBuilderBase(protected val dsl: Dsl, private val handlerFactory: HandlerFactory)
: TraceExpressionBuilder {
protected val resultVariableName = "myRes"
override fun createTraceExpression(chain: StreamChain): String {
val intermediateHandlers = chain.intermediateCalls.mapIndexedTo(ArrayList(), handlerFactory::getForIntermediate)
val terminatorCall = chain.terminationCall
val terminatorHandler = handlerFactory.getForTermination(terminatorCall, "evaluationResult[0]")
val traceChain = buildTraceChain(chain, intermediateHandlers, terminatorHandler)
val infoArraySize = 2 + intermediateHandlers.size
val info = dsl.array(dsl.types.ANY, "info")
val streamResult = dsl.variable(dsl.types.nullable { ANY }, "streamResult")
val declarations = buildDeclarations(intermediateHandlers, terminatorHandler)
val tracingCall = buildStreamExpression(traceChain, streamResult)
val fillingInfoArray = buildFillInfo(intermediateHandlers, terminatorHandler, info)
val result = dsl.variable(dsl.types.ANY, resultVariableName)
return dsl.code {
scope {
// TODO: avoid language dependent code
val startTime = declare(variable(types.LONG, "startTime"), "java.lang.System.nanoTime()".expr, false)
declare(info, newSizedArray(types.ANY, infoArraySize), false)
declare(timeDeclaration())
add(declarations)
add(tracingCall)
add(fillingInfoArray)
val elapsedTime = declare(array(types.LONG, "elapsedTime"),
newArray(types.LONG, "java.lang.System.nanoTime() - ${startTime.toCode()}".expr), false)
result assign newArray(types.ANY, info, streamResult, elapsedTime)
}
}
}
private fun buildTraceChain(chain: StreamChain,
intermediateCallHandlers: List<IntermediateCallHandler>,
terminatorHandler: TerminatorCallHandler): StreamChain {
val newIntermediateCalls = mutableListOf<IntermediateStreamCall>()
val qualifierExpression = chain.qualifierExpression
newIntermediateCalls.add(createTimePeekCall(qualifierExpression.typeAfter))
val intermediateCalls = chain.intermediateCalls
assert(intermediateCalls.size == intermediateCallHandlers.size)
for ((call, handler) in intermediateCalls.zip(intermediateCallHandlers)) {
newIntermediateCalls.addAll(handler.additionalCallsBefore())
newIntermediateCalls.add(handler.transformCall(call))
newIntermediateCalls.add(createTimePeekCall(call.typeAfter))
newIntermediateCalls.addAll(handler.additionalCallsAfter())
}
newIntermediateCalls.addAll(terminatorHandler.additionalCallsBefore())
val terminatorCall = terminatorHandler.transformCall(chain.terminationCall)
return StreamChainImpl(qualifierExpression, newIntermediateCalls, terminatorCall,
chain.context)
}
private fun createTimePeekCall(elementType: GenericType): IntermediateStreamCall {
val lambda = dsl.lambda("x") {
doReturn(dsl.updateTime())
}.toCode()
return dsl.createPeekCall(elementType, lambda)
}
private fun buildDeclarations(intermediateCallsHandlers: List<IntermediateCallHandler>,
terminatorHandler: TerminatorCallHandler): CodeBlock {
return dsl.block {
intermediateCallsHandlers.flatMap { it.additionalVariablesDeclaration() }.forEach({ declare(it) })
terminatorHandler.additionalVariablesDeclaration().forEach({ declare(it) })
}
}
private fun buildStreamExpression(chain: StreamChain, streamResult: Variable): CodeBlock {
val resultType = chain.terminationCall.resultType
return dsl.block {
declare(streamResult, nullExpression, true)
val evaluationResult = array(resultType, "evaluationResult")
if (resultType != types.VOID) declare(evaluationResult, newArray(resultType, TextExpression(resultType.defaultValue)), true)
tryBlock {
if (resultType == types.VOID) {
streamResult assign newSizedArray(types.ANY, 1)
statement { TextExpression(chain.text) }
}
else {
statement { evaluationResult.set(0, TextExpression(chain.text)) }
streamResult assign evaluationResult
}
}.catch(variable(types.EXCEPTION, "t")) {
// TODO: add exception variable as a property of catch code block
streamResult assign newArray(types.EXCEPTION, "t".expr)
}
}
}
private fun buildFillInfo(intermediateCallsHandlers: List<IntermediateCallHandler>,
terminatorHandler: TerminatorCallHandler,
info: ArrayVariable): CodeBlock {
val handlers = listOf<TraceHandler>(*intermediateCallsHandlers.toTypedArray(), terminatorHandler)
return dsl.block {
for ((i, handler) in handlers.withIndex()) {
scope {
add(handler.prepareResult())
statement { info.set(i, handler.resultExpression) }
}
}
}
}
}
| apache-2.0 | aefcbc006a34e714a209b756b1e5ae7a | 43.085714 | 140 | 0.733312 | 4.78079 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/variables/VariableAdapter.kt | 1 | 3373 | package ch.rmy.android.http_shortcuts.activities.variables
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import ch.rmy.android.framework.extensions.setText
import ch.rmy.android.framework.ui.BaseAdapter
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableId
import ch.rmy.android.http_shortcuts.databinding.ListEmptyItemBinding
import ch.rmy.android.http_shortcuts.databinding.ListItemVariableBinding
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.receiveAsFlow
class VariableAdapter : BaseAdapter<VariableListItem>() {
sealed interface UserEvent {
data class VariableClicked(val id: String) : UserEvent
}
private val userEventChannel = Channel<UserEvent>(capacity = Channel.UNLIMITED)
val userEvents: Flow<UserEvent> = userEventChannel.receiveAsFlow()
override fun areItemsTheSame(oldItem: VariableListItem, newItem: VariableListItem): Boolean =
when (oldItem) {
is VariableListItem.Variable -> (newItem as? VariableListItem.Variable)?.id == oldItem.id
is VariableListItem.EmptyState -> newItem is VariableListItem.EmptyState
}
override fun getItemViewType(position: Int): Int =
when (items[position]) {
is VariableListItem.Variable -> VIEW_TYPE_VARIABLE
is VariableListItem.EmptyState -> VIEW_TYPE_EMPTY_STATE
}
override fun createViewHolder(viewType: Int, parent: ViewGroup, layoutInflater: LayoutInflater): RecyclerView.ViewHolder? =
when (viewType) {
VIEW_TYPE_VARIABLE -> VariableViewHolder(ListItemVariableBinding.inflate(layoutInflater, parent, false))
VIEW_TYPE_EMPTY_STATE -> EmptyStateViewHolder(ListEmptyItemBinding.inflate(layoutInflater, parent, false))
else -> null
}
override fun bindViewHolder(holder: RecyclerView.ViewHolder, position: Int, item: VariableListItem, payloads: List<Any>) {
when (holder) {
is VariableViewHolder -> holder.setItem(item as VariableListItem.Variable)
is EmptyStateViewHolder -> holder.setItem(item as VariableListItem.EmptyState)
}
}
inner class VariableViewHolder(
private val binding: ListItemVariableBinding,
) : RecyclerView.ViewHolder(binding.root) {
lateinit var variableId: VariableId
private set
init {
binding.root.setOnClickListener {
userEventChannel.trySend(UserEvent.VariableClicked(variableId))
}
}
fun setItem(item: VariableListItem.Variable) {
variableId = item.id
binding.name.text = item.key
binding.type.setText(item.type)
binding.unused.isVisible = item.isUnused
}
}
inner class EmptyStateViewHolder(
private val binding: ListEmptyItemBinding,
) : RecyclerView.ViewHolder(binding.root) {
fun setItem(item: VariableListItem.EmptyState) {
binding.emptyMarker.setText(item.title)
binding.emptyMarkerInstructions.setText(item.instructions)
}
}
companion object {
private const val VIEW_TYPE_VARIABLE = 1
private const val VIEW_TYPE_EMPTY_STATE = 2
}
}
| mit | 2d5350f8748d1b2b0c0d05dea439d4ba | 37.770115 | 127 | 0.707086 | 4.888406 | false | false | false | false |
sksamuel/ktest | kotest-property/src/jvmTest/kotlin/com/sksamuel/kotest/property/exhaustive/CartesianTest.kt | 1 | 3495 | package com.sksamuel.kotest.property.exhaustive
import io.kotest.core.Tuple4
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.shouldBe
import io.kotest.property.Exhaustive
import io.kotest.property.exhaustive.cartesian
import io.kotest.property.exhaustive.of
class CartesianTest : FunSpec() {
init {
test("Exhaustive.cartesian arity 2") {
val e = Exhaustive.cartesian(
Exhaustive.of(1, 2, 3),
Exhaustive.of(true, false)
) { a, b -> Pair(a, b) }
e.values.shouldHaveSize(6)
e.values shouldBe listOf(
Pair(1, true),
Pair(1, false),
Pair(2, true),
Pair(2, false),
Pair(3, true),
Pair(3, false),
)
}
test("Exhaustive.cartesian arity 3") {
val e = Exhaustive.cartesian(
Exhaustive.of(1, 2, 3),
Exhaustive.of("a", "b", "c"),
Exhaustive.of(true, false)
) { a, b, c -> Triple(a, b, c) }
e.values.shouldHaveSize(18)
e.values shouldBe listOf(
Triple(1, "a", true),
Triple(1, "a", false),
Triple(1, "b", true),
Triple(1, "b", false),
Triple(1, "c", true),
Triple(1, "c", false),
Triple(2, "a", true),
Triple(2, "a", false),
Triple(2, "b", true),
Triple(2, "b", false),
Triple(2, "c", true),
Triple(2, "c", false),
Triple(3, "a", true),
Triple(3, "a", false),
Triple(3, "b", true),
Triple(3, "b", false),
Triple(3, "c", true),
Triple(3, "c", false)
)
}
test("Exhaustive.cartesian arity 4") {
val e = Exhaustive.cartesian(
Exhaustive.of(1, 2),
Exhaustive.of("a", "b", "c"),
Exhaustive.of(true, false),
Exhaustive.of('p', 'q'),
) { a, b, c, d -> Tuple4(a, b, c, d) }
e.values.shouldHaveSize(24)
e.values shouldBe listOf(
Tuple4(a = 1, b = "a", c = true, d = 'p'),
Tuple4(a = 1, b = "a", c = true, d = 'q'),
Tuple4(a = 1, b = "a", c = false, d = 'p'),
Tuple4(a = 1, b = "a", c = false, d = 'q'),
Tuple4(a = 1, b = "b", c = true, d = 'p'),
Tuple4(a = 1, b = "b", c = true, d = 'q'),
Tuple4(a = 1, b = "b", c = false, d = 'p'),
Tuple4(a = 1, b = "b", c = false, d = 'q'),
Tuple4(a = 1, b = "c", c = true, d = 'p'),
Tuple4(a = 1, b = "c", c = true, d = 'q'),
Tuple4(a = 1, b = "c", c = false, d = 'p'),
Tuple4(a = 1, b = "c", c = false, d = 'q'),
Tuple4(a = 2, b = "a", c = true, d = 'p'),
Tuple4(a = 2, b = "a", c = true, d = 'q'),
Tuple4(a = 2, b = "a", c = false, d = 'p'),
Tuple4(a = 2, b = "a", c = false, d = 'q'),
Tuple4(a = 2, b = "b", c = true, d = 'p'),
Tuple4(a = 2, b = "b", c = true, d = 'q'),
Tuple4(a = 2, b = "b", c = false, d = 'p'),
Tuple4(a = 2, b = "b", c = false, d = 'q'),
Tuple4(a = 2, b = "c", c = true, d = 'p'),
Tuple4(a = 2, b = "c", c = true, d = 'q'),
Tuple4(a = 2, b = "c", c = false, d = 'p'),
Tuple4(a = 2, b = "c", c = false, d = 'q'),
)
}
}
}
| mit | 877301b9ab9ed2eeecb4a520585b1742 | 35.789474 | 55 | 0.425465 | 3.082011 | false | true | false | false |
dreampany/framework | frame/src/main/kotlin/com/dreampany/framework/ui/fragment/BaseMenuFragment.kt | 1 | 3518 | package com.dreampany.framework.ui.fragment
import android.app.SearchManager
import android.content.Context
import android.os.Bundle
import androidx.appcompat.widget.SearchView
import android.text.InputType
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.inputmethod.EditorInfo
import com.dreampany.framework.R
/**
* Created by Hawladar Roman on 5/22/2018.
* BJIT Group
* [email protected]
*/
abstract class BaseMenuFragment : BaseFragment() {
protected var menu: Menu? = null
protected var inflater: MenuInflater? = null
open fun getMenuId(): Int {
return 0
}
open fun getSearchMenuItemId(): Int {
return 0
}
open fun onMenuCreated(menu: Menu, inflater: MenuInflater) {
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
this.menu = menu
this.inflater = inflater
val menuId = getMenuId()
if (menuId == 0) {
onMenuCreated(menu, inflater)
return
}
menu.clear()
inflater.inflate(menuId, menu)
//binding.root.post {
onMenuCreated(menu, inflater)
initSearch()
//}
}
protected fun findMenuItemById(menuItemId: Int) : MenuItem? {
if (menu == null || menuItemId == 0) {
return null
}
val item = menu?.findItem(menuItemId)
if (item == null) {
return null
}
return item
}
protected fun getSearchMenuItem(): MenuItem? {
val menuItemId = getSearchMenuItemId()
val item = findMenuItemById(menuItemId)
return item
}
protected fun getSearchView() : SearchView? {
val item = getSearchMenuItem()
if (item == null) {
return null
}
val view = item.actionView
if (view == null) {
return null
}
val searchView = item.actionView as SearchView
return searchView
}
fun initSearch() {
val searchView = getSearchView()
searchView?.let {
searchView.inputType = InputType.TYPE_TEXT_VARIATION_FILTER
searchView.imeOptions = EditorInfo.IME_ACTION_DONE or EditorInfo.IME_FLAG_NO_FULLSCREEN
searchView.queryHint = getString(R.string.search)
val searchManager = searchView.context.getSystemService(Context.SEARCH_SERVICE) as SearchManager
val activity = activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(activity?.componentName))
searchView.setOnQueryTextListener(this)
}
/* MenuItemCompat.setOnActionExpandListener(item, object : MenuItemCompat.OnActionExpandListener {
override fun onMenuItemActionExpand(menuItem: MenuItem): Boolean {
//vm.updateUiMode(UiMode.SEARCH);
return true
}
override fun onMenuItemActionCollapse(menuItem: MenuItem): Boolean {
//vm.updateUiMode(UiMode.MAIN);
return true
}
})*/
}
fun getQuery(): String? {
val searchView = getSearchView()
if (searchView != null) {
return searchView.query.toString()
}
return null
}
} | apache-2.0 | 703e474828b3ff36cd59aaa327c96839 | 26.928571 | 108 | 0.621944 | 5.054598 | false | false | false | false |
softappeal/yass | kotlin/yass-generate/main/ch/softappeal/yass/generate/py/PythonGenerator.kt | 1 | 14363 | package ch.softappeal.yass.generate.py
import ch.softappeal.yass.*
import ch.softappeal.yass.generate.*
import ch.softappeal.yass.remote.*
import ch.softappeal.yass.serialize.fast.*
import java.lang.reflect.*
import java.nio.file.*
import java.util.*
class ExternalDesc(internal val name: String, internal val typeDesc: String)
val BooleanDesc = TypeDesc(FirstTypeId, BooleanSerializer)
val DoubleDesc = TypeDesc(FirstTypeId + 1, DoubleSerializerNoSkipping)
val StringDesc = TypeDesc(FirstTypeId + 2, StringSerializer)
val BinaryDesc = TypeDesc(FirstTypeId + 3, BinarySerializer)
const val FirstDescId = FirstTypeId + 4
@SafeVarargs
fun baseTypeSerializers(vararg serializers: BaseTypeSerializer<*>): List<BaseTypeSerializer<*>> {
val s = mutableListOf(
BooleanDesc.serializer as BaseTypeSerializer<*>,
DoubleDesc.serializer as BaseTypeSerializer<*>,
StringDesc.serializer as BaseTypeSerializer<*>,
BinaryDesc.serializer as BaseTypeSerializer<*>
)
s.addAll(serializers)
return s
}
@SafeVarargs
fun baseTypeDescs(vararg descs: TypeDesc): Collection<TypeDesc> {
val d = mutableListOf(BooleanDesc, DoubleDesc, StringDesc, BinaryDesc)
d.addAll(descs)
return d
}
private const val InitPy = "__init__.py"
private const val RootModule = "contract"
private fun pyBool(value: Boolean) = if (value) "True" else "False"
/** You must use the "-parameters" option for javac to get the real method parameter names. */
class PythonGenerator(
rootPackage: String,
serializer: FastSerializer,
initiator: Services?,
acceptor: Services?,
private val includeFileForEachModule: Path?,
module2includeFile: Map<String, Path>?,
externalTypes: Map<Class<*>, ExternalDesc>,
generatedDir: Path
) : Generator(rootPackage, serializer, initiator, acceptor) {
private val module2includeFile = mutableMapOf<String, Path>()
private val externalTypes =
TreeMap<Class<*>, ExternalDesc>(Comparator.comparing<Class<*>, String> { it.canonicalName })
private val rootNamespace = Namespace(null, null, RootModule, 0)
private val type2namespace = LinkedHashMap<Class<*>, Namespace>()
private val type2id = mutableMapOf<Class<*>, Int>()
init {
if (module2includeFile != null) this.module2includeFile.putAll(module2includeFile)
this.externalTypes.putAll(externalTypes)
id2typeSerializer.forEach { (id, typeSerializer) ->
if (id >= FirstDescId) {
val type = typeSerializer.type
type2id[type] = id
if (!this.externalTypes.containsKey(type)) rootNamespace.add(type)
}
}
interfaces.forEach { rootNamespace.add(it) }
rootNamespace.generate(generatedDir.resolve(RootModule))
MetaPythonOut(generatedDir.resolve(InitPy))
}
private inner class Namespace(val parent: Namespace?, val name: String?, val moduleName: String, val depth: Int) {
val types = LinkedHashSet<Class<*>>()
val children = mutableMapOf<String, Namespace>()
fun add(qualifiedName: String, type: Class<*>) {
val dot = qualifiedName.indexOf('.')
if (dot < 0) { // leaf
checkType(type)
if (!type.isEnum && !type.isInterface) { // note: base classes must be before subclasses
val superClass = type.superclass
if (!isRootClass(superClass)) rootNamespace.add(superClass)
}
types.add(type)
type2namespace[type] = this
} else // intermediate
children.computeIfAbsent(qualifiedName.substring(0, dot)) {
Namespace(this, it, "${moduleName}_$it", depth + 1)
}
.add(qualifiedName.substring(dot + 1), type)
}
fun add(type: Class<*>) {
add(qualifiedName(type), type)
}
fun generate(path: Path) {
ContractPythonOut(path.resolve(InitPy), this)
children.forEach { (name, namespace) -> namespace.generate(path.resolve(name)) }
}
}
private fun typeSerializer(type: Class<*>): TypeSerializer = id2typeSerializer[type2id[type]]!!
private fun hasClassDesc(type: Class<*>): Boolean =
!type.isEnum && !Modifier.isAbstract(type.modifiers) && typeSerializer(type) is FastSerializer.ClassTypeSerializer
private inner class ContractPythonOut(path: Path, val namespace: Namespace) : Out(path) {
val modules = TreeSet(Comparator.comparing<Namespace, String> { it.moduleName })
init {
println("from enum import Enum")
println("from typing import List, Any, cast")
println()
println("import yass")
if (includeFileForEachModule != null) includeFile(includeFileForEachModule)
val moduleIncludeFile = module2includeFile[
if (namespace == rootNamespace)
""
else
namespace.moduleName.substring(RootModule.length + 1).replace('_', '.')
]
if (moduleIncludeFile != null) {
println2()
includeFile(moduleIncludeFile)
}
val buffer = StringBuilder()
redirect(buffer)
@Suppress("UNCHECKED_CAST") namespace.types
.filter { it.isEnum }
.forEach { generateEnum(it as Class<Enum<*>>) }
namespace.types
.filter { t ->
!t.isEnum &&
!t.isInterface &&
(Modifier.isAbstract(t.modifiers) || typeSerializer(t) is FastSerializer.ClassTypeSerializer)
}
.forEach { generateClass(it) }
namespace.types.filter { it.isInterface }.forEach { generateInterface(it) }
redirect(null)
modules.filter { it != namespace }.forEach { importModule(it) }
print(buffer)
close()
}
fun getQualifiedName(type: Class<*>): String {
val ns = type2namespace[type]!!
modules.add(ns)
return "${if (namespace != ns) ns.moduleName + '.' else ""}${type.simpleName}"
}
fun importModule(module: Namespace) {
print("from ")
for (d in namespace.depth + 2 downTo 1) print(".")
if (module == rootNamespace)
println(" import $RootModule")
else
println(
"${module.parent!!.moduleName.replace('_', '.')} " +
"import ${module.name} as ${module.moduleName}"
)
}
fun generateEnum(type: Class<out Enum<*>>) {
println2()
tabsln("class ${type.simpleName}(Enum):")
for (e in type.enumConstants) {
tab()
tabsln("${e.name} = ${e.ordinal}")
}
}
fun pythonType(type: Type): String = when {
type is ParameterizedType -> if (type.rawType === List::class.java)
"List[${pythonType(type.actualTypeArguments[0])}]"
else
error("unexpected type '$type'")
type === Void.TYPE -> "None"
type === Double::class.javaPrimitiveType || type === Double::class.javaObjectType -> "float"
type === Boolean::class.javaPrimitiveType || type === Boolean::class.javaObjectType -> "bool"
type === String::class.java -> "str"
type === ByteArray::class.java -> "bytes"
type === Any::class.java -> "Any"
Throwable::class.java.isAssignableFrom(type as Class<*>) -> "Exception"
else -> {
val externalDesc = externalTypes[primitiveWrapperType(type)]
if (externalDesc != null)
externalDesc.name
else {
checkType(type)
check(!type.isArray) { "illegal type ${type.canonicalName} (use List instead [])" }
getQualifiedName(type)
}
}
}
fun generateClass(type: Class<*>) {
println2()
val sc = type.superclass
val superClass = if (isRootClass(sc)) null else sc
if (Modifier.isAbstract(type.modifiers)) println("@yass.abstract")
tabs("class ${type.simpleName}")
var hasSuper = false
if (superClass != null) {
hasSuper = true
print("(${getQualifiedName(superClass)})")
} else if (Throwable::class.java.isAssignableFrom(sc))
print("(Exception)")
println(":")
inc()
tabsln("def __init__(self) -> None:")
inc()
if (hasSuper) tabsln("${getQualifiedName(superClass!!)}.__init__(self)")
val ownFields = type.ownFields
if (ownFields.none() && !hasSuper)
tabsln("pass")
else {
for (field in ownFields) {
val t = pythonType(field.genericType)
tabsln("self.${field.name}: $t = cast($t, None)")
}
}
dec()
dec()
}
fun generateInterface(type: Class<*>) {
SimpleMethodMapperFactory.invoke(type) // checks for overloaded methods (Python restriction)
println2()
println("class ${type.simpleName}:")
inc()
val methodMapper = methodMapper(type)
iterate(getMethods(type), { println() }, { method ->
tabs("def ${method.name}(self")
method.parameters.forEach { parameter ->
print(", ${parameter.name}: ${pythonType(parameter.parameterizedType)}")
}
println(
") -> ${if (methodMapper.map(method).oneWay) "None" else pythonType(method.genericReturnType)}:"
)
tab()
tabsln("raise NotImplementedError()")
})
dec()
}
}
private inner class MetaPythonOut(path: Path) : Out(path) {
init {
println("import yass")
if (includeFileForEachModule != null) includeFile(includeFileForEachModule)
LinkedHashSet(type2namespace.values).forEach { importModule(it) }
println()
type2namespace.keys.forEach { type ->
val qn = getQualifiedName(type)
if (type.isEnum)
println("yass.enumDesc(${type2id[type]}, $qn)")
else if (hasClassDesc(type))
println(
"yass.classDesc(${type2id[type]}, $qn, " +
"${pyBool((typeSerializer(type) as FastSerializer.ClassTypeSerializer).graph)})"
)
}
println()
type2namespace.keys.filter { hasClassDesc(it) }.forEach { type ->
tabsln("yass.fieldDescs(${getQualifiedName(type)}, [")
for (fieldDesc in (typeSerializer(type) as FastSerializer.ClassTypeSerializer).fieldDescs) {
tab()
tabsln(
"yass.FieldDesc(${fieldDesc.id}, '${fieldDesc.serializer.field.name}', " +
"${typeDesc(fieldDesc)}),"
)
}
tabsln("])")
}
println()
println("SERIALIZER = yass.FastSerializer([")
inc()
externalTypes.values.forEach { externalDesc -> tabsln("${externalDesc.typeDesc},") }
type2namespace.keys
.filter { t -> !Modifier.isAbstract(t.modifiers) }
.forEach { t -> tabsln("${getQualifiedName(t)},") }
dec()
println("])")
println()
interfaces.forEach { generateMapper(it) }
generateServices(initiator, "INITIATOR")
generateServices(acceptor, "ACCEPTOR")
close()
}
fun getQualifiedName(type: Class<*>): String {
val ns = type2namespace[type]!!
return "${ns.moduleName}.${type.simpleName}"
}
fun importModule(module: Namespace) {
print("from .")
if (module == rootNamespace)
println(" import $RootModule")
else
println(
"${module.parent!!.moduleName.replace('_', '.')} " +
"import ${module.name} as ${module.moduleName}"
)
}
fun generateServices(services: Services?, role: String) {
if (services == null) return
println2()
tabsln("class $role:")
for (sd in getServiceDescs(services)) {
val qn = getQualifiedName(sd.contractId.contract)
tab()
tabsln("${sd.name}: yass.ContractId[$qn] = yass.ContractId($qn, ${sd.contractId.id})")
}
}
fun typeDesc(fieldDesc: FieldDesc): String {
val typeSerializer = fieldDesc.serializer.typeSerializer ?: return "None"
return when {
ListTypeDesc.serializer === typeSerializer -> "yass.LIST_DESC"
BooleanDesc.serializer === typeSerializer -> "yass.BOOLEAN_DESC"
DoubleDesc.serializer === typeSerializer -> "yass.DOUBLE_DESC"
StringDesc.serializer === typeSerializer -> "yass.STRING_DESC"
BinaryDesc.serializer === typeSerializer -> "yass.BYTES_DESC"
else -> {
val externalDesc = externalTypes[primitiveWrapperType(typeSerializer.type)]
externalDesc?.typeDesc ?: getQualifiedName(typeSerializer.type)
}
}
}
fun generateMapper(type: Class<*>) {
val methodMapper = methodMapper(type)
tabsln("yass.methodMapper(${getQualifiedName(type)}, [")
for (m in getMethods(type)) {
val (method, id, oneWay) = methodMapper.map(m)
tab()
tabsln("yass.MethodMapping($id, '${method.name}', ${pyBool(oneWay)}),")
}
tabsln("])")
}
}
}
| bsd-3-clause | 83bb77592488a2842654e0cab5ee2283 | 40.154728 | 122 | 0.54905 | 4.794059 | false | false | false | false |
intrigus/jtransc | jtransc-main/test/jtransc/bug/JTranscBug12Test2Kotlin.kt | 2 | 1209 | package jtransc.bug;
import com.jtransc.experimental.kotlin.JTranscKotlinReflectStripper
import java.util.*
object JTranscBug12Test2Kotlin {
@JvmStatic fun main(args: Array<String>) {
JTranscKotlinReflectStripper.init()
println("[1]");
val field = Demo::field
var abc = "cba".reversed()
println("[2]");
println("abc".equals("abc"))
test1("a")
test1("b")
test1("c")
test1("abcdef")
test1(abc + "def")
test1("abcdefg")
test2()
test3()
Demo2().test()
Demo2.test()
}
enum class TestEnum { A, B, C; }
fun test3() {
//val set = RegularEnumSet(TestEnum::class.java, arrayOf(TestEnum.A, TestEnum.B, TestEnum.C))
}
fun test1(str:String) {
when (str) {
"a" -> println("my:a")
"b" -> println("my:b")
"abcdef" -> println("my:abcdef")
else -> println("my:else:$str")
}
}
fun test2() {
//val range = 11L until 1000
//println(range.start)
//println(range.step)
//println(range.endInclusive)
}
class Demo {
var field: String = "test"
}
class Demo2 {
companion object {
internal var test = Demo()
fun test() {
println("[1]" + test.field)
}
}
private var test = Demo()
fun test() {
println("[2]" + test.field)
}
}
}
| apache-2.0 | 8b3d67fa8343b3beb29ab0eb8213dcb7 | 16.779412 | 95 | 0.61373 | 2.772936 | false | true | false | false |
quran/quran_android | app/src/main/java/com/quran/labs/androidquran/data/QuranDisplayData.kt | 2 | 7009 | package com.quran.labs.androidquran.data
import android.content.Context
import android.text.TextUtils
import androidx.annotation.StringRes
import com.quran.data.core.QuranInfo
import com.quran.data.di.AppScope
import com.quran.data.model.SuraAyah
import com.quran.data.model.SuraAyahIterator
import com.quran.labs.androidquran.R
import com.quran.labs.androidquran.util.QuranUtils
import com.quran.page.common.data.QuranNaming
import com.squareup.anvil.annotations.ContributesBinding
import timber.log.Timber
import javax.inject.Inject
@ContributesBinding(AppScope::class)
class QuranDisplayData @Inject constructor(private val quranInfo: QuranInfo): QuranNaming {
/**
* Get localized sura name from resources
*
* @param context Application context
* @param sura Sura number (1~114)
* @param wantPrefix Whether or not to show prefix "Sura"
* @return Compiled sura name without translations
*/
override fun getSuraName(context: Context, sura: Int, wantPrefix: Boolean): String {
return getSuraName(context, sura, wantPrefix, false)
}
override fun getSuraNameWithNumber(context: Context, sura: Int, wantPrefix: Boolean): String {
val name = getSuraName(context, sura, wantPrefix)
val prefix = QuranUtils.getLocalizedNumber(context, sura)
return "$prefix. $name"
}
/**
* Get localized sura name from resources
*
* @param context Application context
* @param sura Sura number (1~114)
* @param wantPrefix Whether or not to show prefix "Sura"
* @param wantTranslation Whether or not to show sura name translations
* @return Compiled sura name based on provided arguments
*/
fun getSuraName(
context: Context, sura: Int, wantPrefix: Boolean, wantTranslation: Boolean
): String {
if (sura < Constants.SURA_FIRST || sura > Constants.SURA_LAST) return ""
val builder = StringBuilder()
val suraNames = context.resources.getStringArray(R.array.sura_names)
if (wantPrefix) {
builder.append(context.getString(R.string.quran_sura_title, suraNames[sura - 1]))
} else {
builder.append(suraNames[sura - 1])
}
if (wantTranslation) {
val translation = context.resources.getStringArray(R.array.sura_names_translation)[sura - 1]
if (!TextUtils.isEmpty(translation)) {
// Some sura names may not have translation
builder.append(" (")
builder.append(translation)
builder.append(")")
}
}
return builder.toString()
}
fun getSuraNameFromPage(context: Context, page: Int, wantTitle: Boolean): String {
val sura = quranInfo.getSuraNumberFromPage(page)
return if (sura > 0) getSuraName(context, sura, wantTitle, false) else ""
}
fun getPageSubtitle(context: Context, page: Int): String {
val description = context.getString(R.string.page_description)
return String.format(description,
QuranUtils.getLocalizedNumber(context, page),
QuranUtils.getLocalizedNumber(context, quranInfo.getJuzForDisplayFromPage(page)))
}
fun getJuzDisplayStringForPage(context: Context, page: Int): String {
val description = context.getString(R.string.juz2_description)
return String.format(description,
QuranUtils.getLocalizedNumber(context, quranInfo.getJuzForDisplayFromPage(page)))
}
fun getSuraAyahString(context: Context, sura: Int, ayah: Int): String {
return getSuraAyahString(context, sura, ayah, R.string.sura_ayah_notification_str)
}
fun getSuraAyahString(context: Context, sura: Int, ayah: Int, @StringRes resource: Int): String {
val suraName = getSuraName(context, sura, wantPrefix = false, wantTranslation = false)
return context.getString(resource, suraName, ayah)
}
fun getNotificationTitle(
context: Context, minVerse: SuraAyah, maxVerse: SuraAyah, isGapless: Boolean
): String {
val minSura = minVerse.sura
var maxSura = maxVerse.sura
val notificationTitle = getSuraName(context, minSura, wantPrefix = true, wantTranslation = false)
if (isGapless) {
// for gapless, don't show the ayah numbers since we're
// downloading the entire sura(s).
return if (minSura == maxSura) {
notificationTitle
} else {
"$notificationTitle - " + getSuraName(
context, maxSura, wantPrefix = true, wantTranslation = false
)
}
}
var maxAyah = maxVerse.ayah
if (maxAyah == 0) {
maxSura--
maxAyah = quranInfo.getNumberOfAyahs(maxSura)
}
return notificationTitle.plus(
if (minSura == maxSura) {
if (minVerse.ayah == maxAyah) {
" ($maxAyah)"
} else {
" (" + minVerse.ayah + "-" + maxAyah + ")"
}
} else {
" (" + minVerse.ayah + ") - " +
getSuraName(context, maxSura, wantPrefix = true, wantTranslation = false) +
" (" + maxAyah + ")"
}
)
}
fun getSuraListMetaString(context: Context, sura: Int): String {
val info = context.getString(if (quranInfo.isMakki(sura)) R.string.makki else R.string.madani) + " - "
val ayahs = quranInfo.getNumberOfAyahs(sura)
return info + context.resources.getQuantityString(
R.plurals.verses, ayahs,
QuranUtils.getLocalizedNumber(context, ayahs))
}
fun safelyGetSuraOnPage(page: Int): Int {
return if (page < Constants.PAGES_FIRST || page > quranInfo.numberOfPages) {
Timber.e(IllegalArgumentException("safelyGetSuraOnPage with page: $page"))
quranInfo.getSuraOnPage(1)
} else {
quranInfo.getSuraOnPage(page)
}
}
private fun getSuraNameFromPage(context: Context, page: Int): String {
val suraNumber = quranInfo.getSuraNumberFromPage(page)
return getSuraName(context, suraNumber, wantPrefix = false, wantTranslation = false)
}
fun getAyahString(sura: Int, ayah: Int, context: Context): String {
return getSuraName(context, sura, true) + " - " + context.getString(R.string.quran_ayah, ayah)
}
fun getAyahMetadata(sura: Int, ayah: Int, page: Int, context: Context): String {
val juz = quranInfo.getJuzForDisplayFromPage(page)
return context.getString(R.string.quran_ayah_details,
getSuraName(context, sura, true),
QuranUtils.getLocalizedNumber(context, ayah),
QuranUtils.getLocalizedNumber(context, quranInfo.getJuzFromSuraAyah(sura, ayah, juz)))
}
// do not remove the nullable return type
fun getSuraNameString(context: Context, page: Int): String? {
return context.getString(R.string.quran_sura_title, getSuraNameFromPage(context, page))
}
fun getAyahKeysOnPage(page: Int): Set<String> {
val ayahKeys: MutableSet<String> = LinkedHashSet()
val bounds = quranInfo.getPageBounds(page)
val start = SuraAyah(bounds[0], bounds[1])
val end = SuraAyah(bounds[2], bounds[3])
val iterator = SuraAyahIterator(quranInfo, start, end)
while (iterator.next()) {
ayahKeys.add(iterator.sura.toString() + ":" + iterator.ayah.toString())
}
return ayahKeys
}
}
| gpl-3.0 | 0d54c207bf973866144bc55c1d2ba829 | 35.316062 | 106 | 0.694393 | 3.993732 | false | false | false | false |
JakeWharton/dex-method-list | diffuse/src/main/kotlin/com/jakewharton/diffuse/diff/AarDiff.kt | 1 | 659 | package com.jakewharton.diffuse.diff
import com.jakewharton.diffuse.Aar
import com.jakewharton.diffuse.ApiMapping
import com.jakewharton.diffuse.report.DiffReport
import com.jakewharton.diffuse.report.text.AarDiffTextReport
internal class AarDiff(
val oldAar: Aar,
val oldMapping: ApiMapping,
val newAar: Aar,
val newMapping: ApiMapping
) : BinaryDiff {
val archive = ArchiveFilesDiff(oldAar.files, newAar.files, includeCompressed = false)
val jars = JarsDiff(oldAar.jars, oldMapping, newAar.jars, newMapping)
val manifest = ManifestDiff(oldAar.manifest, newAar.manifest)
override fun toTextReport(): DiffReport = AarDiffTextReport(this)
}
| apache-2.0 | 295daa1aee902fef503dc44e3c2f3dfd | 33.684211 | 87 | 0.798179 | 3.524064 | false | false | false | false |
syrop/Wiktor-Navigator | navigator/src/main/kotlin/pl/org/seva/navigator/main/data/Permissions.kt | 1 | 3377 | /*
* Copyright (C) 2017 Wiktor Nizio
*
* 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/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.navigator.main.data
import android.content.pm.PackageManager
import androidx.fragment.app.Fragment
import io.reactivex.subjects.PublishSubject
import pl.org.seva.navigator.main.extension.subscribe
import pl.org.seva.navigator.main.init.instance
fun Fragment.requestPermissions(
requestCode: Int,
requests: Array<Permissions.PermissionRequest>,
) =
permissions.request(
this,
requestCode,
requests, )
val permissions by instance<Permissions>()
class Permissions {
private val grantedSubject = PublishSubject.create<PermissionResult>()
private val deniedSubject = PublishSubject.create<PermissionResult>()
fun request(
fragment: Fragment,
requestCode: Int,
requests: Array<PermissionRequest>,
) {
val lifecycle = fragment.lifecycle
val permissionsToRequest = ArrayList<String>()
requests.forEach { request ->
permissionsToRequest.add(request.permission)
grantedSubject
.filter { it.requestCode == requestCode && it.permission == request.permission }
.subscribe(lifecycle) { request.onGranted() }
deniedSubject
.filter { it.requestCode == requestCode && it.permission == request.permission }
.subscribe(lifecycle) { request.onDenied() }
}
fragment.requestPermissions(permissionsToRequest.toTypedArray(), requestCode)
}
fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
infix fun String.onGranted(requestCode: Int) =
grantedSubject.onNext(PermissionResult(requestCode, this))
infix fun String.onDenied(requestCode: Int) =
deniedSubject.onNext(PermissionResult(requestCode, this))
if (grantResults.isEmpty()) {
permissions.forEach { it onDenied requestCode }
}
else repeat(permissions.size) {
if (grantResults[it] == PackageManager.PERMISSION_GRANTED) {
permissions[it] onGranted requestCode
}
else {
permissions[it] onDenied requestCode
}
}
}
companion object {
const val DEFAULT_PERMISSION_REQUEST_ID = 0
}
data class PermissionResult(val requestCode: Int, val permission: String)
class PermissionRequest(
val permission: String,
val onGranted: () -> Unit = {},
val onDenied: () -> Unit = {},
)
}
| gpl-3.0 | 679a0574dfb0cc8324c3ecef385653c7 | 34.925532 | 106 | 0.663607 | 4.858993 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/dynarek2/target/js/JsGenerator.kt | 1 | 4336 | package com.soywiz.dynarek2.target.js
import com.soywiz.dynarek2.*
import com.soywiz.dynarek2.tools.*
class JsGenerator(val context: D2Context, val name: String?, val debug: Boolean) {
val REGS_NAME = "regs"
val MEM_NAME = "mem"
val TEMP_NAME = "temp"
val EXTERNAL_NAME = "ext"
val ARG_NAMES = arrayOf(REGS_NAME, MEM_NAME, TEMP_NAME, EXTERNAL_NAME)
val referencedFunctions = LinkedHashMap<String, Any>()
fun generateBody(f: D2Func): MiniIndenter {
return MiniIndenter {
generateStm(f.body)
}
}
fun MiniIndenter.generateStm(s: D2Stm?): Unit {
when (s) {
null -> Unit
is D2Stm.Stms -> for (child in s.children) generateStm(child)
is D2Stm.Expr -> line("${s.expr.generateExpr()};")
is D2Stm.Return -> line("return ${s.expr.generateExpr()};")
is D2Stm.If -> {
line("if (${s.cond.generateExpr()})") {
generateStm(s.strue)
}
if (s.sfalse != null) {
line("else") {
generateStm(s.sfalse)
}
}
}
is D2Stm.While -> {
line("while (${s.cond.generateExpr()})") {
generateStm(s.body)
}
}
is D2Stm.Set<*> -> {
line("${s.ref.access} = ${s.value.generateExpr()};")
}
else -> {
TODO("$s")
}
}
Unit
}
fun D2Expr<*>.generateExpr(): String = when (this) {
is D2Expr.ILit -> "(${this.lit})"
is D2Expr.FLit -> "Math.fround(${this.lit})"
is D2Expr.IBinOp -> {
val ls = "(" + this.l.generateExpr() + ")"
val rs = "(" + this.r.generateExpr() + ")"
val os = op.symbol
when (this.op) {
D2IBinOp.MUL -> "Math.imul($ls, $rs)"
else -> "(($ls $os $rs)|0)"
}
}
is D2Expr.FBinOp -> {
val ls = "(" + this.l.generateExpr() + ")"
val rs = "(" + this.r.generateExpr() + ")"
val os = op.symbol
"(($ls $os $rs))"
}
is D2Expr.IComOp -> "(((${this.l.generateExpr()}) ${op.symbol} (${this.r.generateExpr()}))|0)"
is D2Expr.Invoke<*> -> {
val fname = "func_" + this.func.name
referencedFunctions[fname] = this.func
val argsStr = this.args.joinToString(", ") { it.generateExpr() }
"$fname($argsStr)"
}
is D2Expr.Ref -> access
is D2Expr.External -> EXTERNAL_NAME
else -> TODO("$this")
}
val D2Expr.Ref<*>.access get() = "$accessBase[${offset.generateExpr()}]"
val D2Expr.Ref<*>.accessBase get() = "${memSlot.accessName}.${size.accessName}"
val D2MemSlot.accessName: String get() = ARG_NAMES[index]
val D2Size.accessName: String
get() = when (this) {
D2Size.BYTE -> "s8"
D2Size.SHORT -> "s16"
D2Size.INT -> "s32"
D2Size.FLOAT -> "f32"
D2Size.LONG -> "s64"
}
}
class JsBody(
val context: D2Context,
val name: String?,
val debug: Boolean,
val generator: JsGenerator,
val bodyIndenter: MiniIndenter
) {
val referencedFunctions get() = generator.referencedFunctions
val body by lazy { bodyIndenter.toString() }
override fun toString(): String = body
}
fun D2Func.generateJsBody(context: D2Context, name: String? = null, debug: Boolean = false, strict: Boolean = true): JsBody {
val generator = JsGenerator(context, name, debug)
val body = generator.generateBody(this)
val rname = name ?: "generated"
val rbody = MiniIndenter {
line("(function $rname(funcs) {")
indent {
if (strict) line("\"use strict\";")
// functions
for (k in generator.referencedFunctions.keys) {
line("var $k = funcs.$k;")
}
line("return function $rname(regs, mem, temp, ext) {")
indent {
if (strict) line("\"use strict\";")
line(body)
}
line("};")
}
line("})")
}
return JsBody(context, name, debug, generator, rbody)
}
| mit | 333e95aa4c39ed16486e66f0b99d2cff | 31.601504 | 125 | 0.498386 | 3.806848 | false | false | false | false |
square/sqldelight | drivers/native-driver/src/nativeMain/kotlin/com/squareup/sqldelight/drivers/native/SqliterSqlCursor.kt | 1 | 1075 | package com.squareup.sqldelight.drivers.native
import co.touchlab.sqliter.Cursor
import co.touchlab.sqliter.getBytesOrNull
import co.touchlab.sqliter.getDoubleOrNull
import co.touchlab.sqliter.getLongOrNull
import co.touchlab.sqliter.getStringOrNull
import com.squareup.sqldelight.db.SqlCursor
/**
* Wrapper for cursor calls. Cursors point to real SQLite statements, so we need to be careful with
* them. If dev closes the outer structure, this will get closed as well, which means it could start
* throwing errors if you're trying to access it.
*/
internal class SqliterSqlCursor(
private val cursor: Cursor,
private val recycler: () -> Unit
) : SqlCursor {
override fun close() {
recycler()
}
override fun getBytes(index: Int): ByteArray? = cursor.getBytesOrNull(index)
override fun getDouble(index: Int): Double? = cursor.getDoubleOrNull(index)
override fun getLong(index: Int): Long? = cursor.getLongOrNull(index)
override fun getString(index: Int): String? = cursor.getStringOrNull(index)
override fun next(): Boolean = cursor.next()
}
| apache-2.0 | 2f84ea5f5151417a5e62c1d7b28e5a19 | 31.575758 | 100 | 0.764651 | 4.118774 | false | false | false | false |
BenoitDuffez/AndroidCupsPrint | app/src/main/java/io/github/benoitduffez/cupsprint/ssl/AdditionalKeyManager.kt | 1 | 4122 | package io.github.benoitduffez.cupsprint.ssl
import android.content.Context
import android.preference.PreferenceManager
import android.security.KeyChain
import android.security.KeyChainException
import android.text.TextUtils
import io.github.benoitduffez.cupsprint.CupsPrintApp
import timber.log.Timber
import java.net.Socket
import java.security.Principal
import java.security.PrivateKey
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.X509KeyManager
/**
* Uses the system keystore
*/
class AdditionalKeyManager private constructor(val context: Context, private val clientAlias: String, private val certificateChain: Array<X509Certificate>, private val privateKey: PrivateKey) : X509KeyManager {
override fun chooseClientAlias(keyType: Array<String>, issuers: Array<Principal>, socket: Socket): String = clientAlias
override fun getCertificateChain(alias: String): Array<X509Certificate> = certificateChain
override fun getPrivateKey(alias: String): PrivateKey = privateKey
override fun getClientAliases(keyType: String, issuers: Array<Principal>): Array<String> {
throw UnsupportedOperationException()
}
override fun chooseServerAlias(keyType: String, issuers: Array<Principal>, socket: Socket): String {
throw UnsupportedOperationException()
}
override fun getServerAliases(keyType: String, issuers: Array<Principal>): Array<String> {
throw UnsupportedOperationException()
}
companion object {
private val KEY_CERTIFICATE_ALIAS = AdditionalKeyManager::class.java.name + ".CertificateAlias"
/**
* Builds an instance of a KeyChainKeyManager using the given certificate alias. If for any reason retrieval of the credentials from the system
* KeyChain fails, a null value will be returned.
*
* @return System-wide KeyManager, or null if alias is empty
* @throws CertificateException
*/
@Throws(CertificateException::class)
fun fromAlias(context: Context): AdditionalKeyManager? {
val alias = PreferenceManager.getDefaultSharedPreferences(context).getString(KEY_CERTIFICATE_ALIAS, null)
if (TextUtils.isEmpty(alias) || alias == null) {
return null
}
val certificateChain = getCertificateChain(context, alias)
val privateKey = getPrivateKey(context, alias)
if (certificateChain == null || privateKey == null) {
throw CertificateException("Can't access certificate from keystore")
}
return AdditionalKeyManager(context, alias, certificateChain, privateKey)
}
@Throws(CertificateException::class)
private fun getCertificateChain(context: Context, alias: String): Array<X509Certificate>? {
val certificateChain: Array<X509Certificate>?
try {
certificateChain = KeyChain.getCertificateChain(context, alias)
} catch (e: KeyChainException) {
logError(alias, "certificate chain", e)
throw CertificateException(e)
} catch (e: InterruptedException) {
logError(alias, "certificate chain", e)
throw CertificateException(e)
}
return certificateChain
}
@Throws(CertificateException::class)
private fun getPrivateKey(context: Context, alias: String): PrivateKey? {
val privateKey: PrivateKey?
try {
privateKey = KeyChain.getPrivateKey(context, alias)
} catch (e: KeyChainException) {
logError(alias, "private key", e)
throw CertificateException(e)
} catch (e: InterruptedException) {
logError(alias, "private key", e)
throw CertificateException(e)
}
return privateKey
}
private fun logError(alias: String, type: String, e: Exception) =
Timber.e(e, "Unable to retrieve $type for [$alias]")
}
}
| lgpl-3.0 | 6d013caa7f8c46dc9b4a630b7012a5a5 | 40.22 | 210 | 0.672489 | 5.032967 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/lists/ListsReorderDialogFragment.kt | 1 | 3583 | package com.battlelancer.seriesguide.lists
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.loader.app.LoaderManager
import androidx.loader.content.Loader
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.databinding.DialogListsReorderBinding
import com.battlelancer.seriesguide.lists.OrderedListsLoader.OrderedList
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.uwetrottmann.seriesguide.widgets.dragsortview.DragSortController
/**
* Dialog to reorder lists using a vertical list with drag handles. Currently not accessibility or
* keyboard friendly (same as extension configuration screen).
*/
class ListsReorderDialogFragment : AppCompatDialogFragment() {
private var binding: DialogListsReorderBinding? = null
private lateinit var adapter: ListsAdapter
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val binding = DialogListsReorderBinding.inflate(layoutInflater)
this.binding = binding
val controller = DragSortController(
binding.listViewListsReorder,
R.id.dragGripViewItemList, DragSortController.ON_DOWN,
DragSortController.CLICK_REMOVE
)
controller.isRemoveEnabled = false
binding.listViewListsReorder.setFloatViewManager(controller)
binding.listViewListsReorder.setOnTouchListener(controller)
binding.listViewListsReorder.setDropListener { from: Int, to: Int -> reorderList(from, to) }
adapter = ListsAdapter(activity)
binding.listViewListsReorder.adapter = adapter
LoaderManager.getInstance(this)
.initLoader(ListsActivityImpl.LISTS_REORDER_LOADER_ID, null, listsLoaderCallbacks)
return MaterialAlertDialogBuilder(requireContext())
.setView(binding.root)
.setTitle(R.string.action_lists_reorder)
.setNegativeButton(R.string.discard, null)
.setPositiveButton(android.R.string.ok) { _: DialogInterface, _: Int ->
saveListsOrder()
dismiss()
}
.create()
}
override fun onDestroyView() {
super.onDestroyView()
this.binding = null
}
private fun reorderList(from: Int, to: Int) {
adapter.reorderList(from, to)
}
private fun saveListsOrder() {
val count = adapter.count
val listIdsInOrder: MutableList<String> = ArrayList(count)
for (position in 0 until count) {
val list = adapter.getItem(position)
if (list != null && !list.id.isNullOrEmpty()) {
listIdsInOrder.add(list.id)
}
}
ListsTools.reorderLists(requireContext(), listIdsInOrder)
}
private val listsLoaderCallbacks: LoaderManager.LoaderCallbacks<List<OrderedList>> =
object : LoaderManager.LoaderCallbacks<List<OrderedList>> {
override fun onCreateLoader(id: Int, args: Bundle?): Loader<List<OrderedList>> {
return OrderedListsLoader(activity)
}
override fun onLoadFinished(
loader: Loader<List<OrderedList>>,
data: List<OrderedList>
) {
if (!isAdded) {
return
}
adapter.setData(data)
}
override fun onLoaderReset(loader: Loader<List<OrderedList>>) {
adapter.setData(null)
}
}
} | apache-2.0 | 4a507bd09ef4b4d4ff862fbe22d4c8bf | 36.333333 | 100 | 0.66983 | 5.039381 | false | false | false | false |
VerifAPS/verifaps-lib | util/src/main/kotlin/edu/kit/iti/formal/util/tests.kt | 1 | 578 | package edu.kit.iti.formal.util
import java.io.File
val isWindows by lazy {
System.getProperty("os.name") == "WINDOWS"
}
fun findProgram(program: String): File? {
val file = File(program)
return if (file.exists())
file
else
findProgramInPath(program)
}
fun findProgramInPath(program: String): File? {
val path = System.getenv("PATH")
val folders = path.split(if (isWindows) ";" else ":")
folders.forEach {
val cand = File(it, program)
if (cand.exists()) {
return cand
}
}
return null
}
| gpl-3.0 | ef8ff2204a9a5f1db210430b7c8d3f4d | 20.407407 | 57 | 0.603806 | 3.6125 | false | false | false | false |
jamming/FrameworkBenchmarks | frameworks/Kotlin/hexagon/src/main/kotlin/Controller.kt | 1 | 3419 | package com.hexagonkt
import com.hexagonkt.core.helpers.require
import com.hexagonkt.http.server.Call
import com.hexagonkt.http.server.Router
import com.hexagonkt.serialization.json.Json
import com.hexagonkt.serialization.toFieldsMap
import com.hexagonkt.store.BenchmarkStore
import com.hexagonkt.templates.TemplatePort
import java.net.URL
import java.util.concurrent.ThreadLocalRandom
class Controller(private val settings: Settings) {
private val templates: Map<String, URL> = mapOf(
"pebble" to (urlOrNull("classpath:fortunes.pebble.html") ?: URL("file:/resin/fortunes.pebble.html"))
)
internal val router: Router by lazy {
Router {
before {
response.headers["Server"] = "Servlet/3.1"
response.headers["Transfer-Encoding"] = "chunked"
}
get("/plaintext") { ok(settings.textMessage, "text/plain") }
get("/json") { ok(Message(settings.textMessage), Json) }
benchmarkStores.forEach { (storeEngine, store) ->
benchmarkTemplateEngines.forEach { (templateEngineId, templateEngine) ->
val path = "/$storeEngine/${templateEngineId}/fortunes"
get(path) { listFortunes(store, templateEngineId, templateEngine) }
}
get("/$storeEngine/db") { dbQuery(store) }
get("/$storeEngine/query") { getWorlds(store) }
get("/$storeEngine/cached") { getCachedWorlds(store) }
get("/$storeEngine/update") { updateWorlds(store) }
}
}
}
private fun Call.listFortunes(store: BenchmarkStore, templateKind: String, templateAdapter: TemplatePort) {
val fortunes = store.findAllFortunes() + Fortune(0, "Additional fortune added at request time.")
val sortedFortunes = fortunes.sortedBy { it.message }
val context = mapOf("fortunes" to sortedFortunes)
response.contentType = "text/html;charset=utf-8"
ok(templateAdapter.render(templates.require(templateKind), context))
}
private fun Call.dbQuery(store: BenchmarkStore) {
ok(store.findWorlds(listOf(randomWorld())).first(), Json)
}
private fun Call.getWorlds(store: BenchmarkStore) {
val ids = (1..getWorldsCount(settings.queriesParam)).map { randomWorld() }
ok(store.findWorlds(ids), Json)
}
private fun Call.getCachedWorlds(store: BenchmarkStore) {
val ids = (1..getWorldsCount(settings.cachedQueriesParam)).map { randomWorld() }
ok(store.findCachedWorlds(ids).map { it.toFieldsMap() }, Json)
}
private fun Call.updateWorlds(store: BenchmarkStore) {
val worlds = (1..getWorldsCount(settings.queriesParam)).map { World(randomWorld(), randomWorld()) }
store.replaceWorlds(worlds)
ok(worlds, Json)
}
private fun Call.getWorldsCount(parameter: String): Int =
queryParametersValues[parameter]?.firstOrNull()?.toIntOrNull().let {
when {
it == null -> 1
it < 1 -> 1
it > 500 -> 500
else -> it
}
}
private fun randomWorld(): Int =
ThreadLocalRandom.current().nextInt(settings.worldRows) + 1
private fun urlOrNull(path: String): URL? =
try {
URL(path)
}
catch (e: Exception) {
null
}
}
| bsd-3-clause | fa2015658bc61f4b5dee743343edf24e | 35.37234 | 111 | 0.622404 | 4.400257 | false | false | false | false |
LarsEckart/kotlin-playground | src/main/kotlin/basics/03-returns-jumps.kt | 1 | 712 | package basics
fun main(args: Array<String>) {
loop@ for (i in 1..100) {
for (j in 1..100) {
if (j == 3) {
break@loop
}
}
}
var arr = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7)
foo(arr)
foo2(arr)
}
fun foo(ints: IntArray) {
ints.forEach {
if (it == 0) return
print(it)
}
}
fun foo2(ints: IntArray) {
ints.forEach lit@ {
if (it == 0) return@lit
print(it)
}
}
fun foo3(ints: IntArray) {
ints.forEach {
if (it == 0) return@forEach
print(it)
}
}
fun foo4(ints: IntArray) {
ints.forEach(fun(value: Int) {
if (value == 0) return
print(value)
})
}
| mit | ddf3fcb53631b101aa9d33bc7ec0995e | 15.181818 | 48 | 0.463483 | 3.042735 | false | false | false | false |
cketti/k-9 | app/core/src/main/java/com/fsck/k9/helper/CollectionExtensions.kt | 1 | 1573 | package com.fsck.k9.helper
/**
* Returns a [Set] containing the results of applying the given [transform] function to each element in the original
* collection.
*
* If you know the size of the output or can make an educated guess, specify [expectedSize] as an optimization.
* The initial capacity of the `Set` will be derived from this value.
*/
inline fun <T, R> Iterable<T>.mapToSet(expectedSize: Int? = null, transform: (T) -> R): Set<R> {
return if (expectedSize != null) {
mapTo(LinkedHashSet(setCapacity(expectedSize)), transform)
} else {
mapTo(mutableSetOf(), transform)
}
}
/**
* Returns a [Set] containing the results of applying the given [transform] function to each element in the original
* collection.
*
* The size of the output is expected to be equal to the size of the input. If that's not the case, please use
* [mapToSet] instead.
*/
inline fun <T, R> Collection<T>.mapCollectionToSet(transform: (T) -> R): Set<R> {
return mapToSet(expectedSize = size, transform)
}
// A copy of Kotlin's internal mapCapacity() for the JVM
fun setCapacity(expectedSize: Int): Int = when {
// We are not coercing the value to a valid one and not throwing an exception. It is up to the caller to
// properly handle negative values.
expectedSize < 0 -> expectedSize
expectedSize < 3 -> expectedSize + 1
expectedSize < INT_MAX_POWER_OF_TWO -> ((expectedSize / 0.75F) + 1.0F).toInt()
// any large value
else -> Int.MAX_VALUE
}
private const val INT_MAX_POWER_OF_TWO: Int = 1 shl (Int.SIZE_BITS - 2)
| apache-2.0 | b6d5c74c277600d4851bec20c9d3d8dd | 38.325 | 116 | 0.691036 | 3.763158 | false | false | false | false |
nickthecoder/tickle | tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/scene/GlassLayer.kt | 1 | 23240 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.editor.scene
import javafx.application.Platform
import javafx.scene.paint.Color
import javafx.scene.shape.StrokeLineCap
import org.joml.Vector2d
import uk.co.nickthecoder.paratask.parameters.DoubleParameter
import uk.co.nickthecoder.tickle.AttributeType
import uk.co.nickthecoder.tickle.editor.resources.DesignActorResource
import uk.co.nickthecoder.tickle.editor.resources.DesignSceneResource
import uk.co.nickthecoder.tickle.editor.resources.ModificationType
import uk.co.nickthecoder.tickle.editor.resources.SceneResourceListener
import uk.co.nickthecoder.tickle.editor.scene.history.*
import uk.co.nickthecoder.tickle.editor.util.*
import uk.co.nickthecoder.tickle.resources.ActorResource
import uk.co.nickthecoder.tickle.util.rotate
class GlassLayer(private val sceneEditor: SceneEditor)
: Layer(), SelectionListener, SceneResourceListener {
var dirty = false
set(v) {
if (field != v) {
field = v
Platform.runLater {
if (dirty) {
draw()
}
}
}
}
var newActor: ActorResource? = null
private val dragHandles = mutableListOf<DragHandle>()
init {
sceneEditor.selection.listeners.add(this)
sceneEditor.sceneResource.listeners.add(this)
}
override fun drawContent() {
val gc = canvas.graphicsContext2D
// A dashed border the size of the game window, with the bottom left at (0,0)
with(gc) {
save()
stroke = borderColor
lineWidth = borderWidth
setLineDashes(10.0 / scale, 3.0 / scale)
strokeLine(-1.0, -1.0, canvas.width + 1, -1.0)
strokeLine(canvas.width + 1, -1.0, canvas.width, canvas.height + 1)
strokeLine(canvas.width + 1, canvas.height + 1, -1.0, canvas.height + 1)
strokeLine(-1.0, canvas.height + 1, -1.0, -1.0)
setLineDashes()
restore()
}
// Dotted lines around each selected ActorResource
with(gc) {
save()
setLineDashes(3.0, 10.0)
sceneEditor.selection.selected().forEach { actorResource ->
save()
translate(actorResource.x, actorResource.y)
rotate(actorResource.direction.degrees - (actorResource.editorPose?.direction?.degrees ?: 0.0))
scale(actorResource.scale.x, actorResource.scale.y)
drawOutlined(selectionColor(actorResource === sceneEditor.selection.latest())) { drawBoundingBox(actorResource) }
restore()
}
restore()
}
// Name of the 'latest' actor
sceneEditor.selection.latest()?.let { actor ->
drawCostumeName(actor)
}
// Each drag handle
dragHandles.forEach { handle ->
handle.draw()
}
// Text for the handle the mouse is hovering over
dragHandles.firstOrNull { it.hovering }?.let { handle ->
with(canvas.graphicsContext2D) {
save()
translate(handle.x(), handle.y())
outlinedText(handle.name)
restore()
}
}
newActor?.let {
canvas.graphicsContext2D.globalAlpha = 0.5
drawActor(it)
canvas.graphicsContext2D.globalAlpha = 1.0
}
dirty = false
}
fun hover(x: Double, y: Double) {
dragHandles.forEach { handle ->
if (handle.hover(x, y)) {
dragHandles.filter { it !== handle }.forEach { it.hover(Double.MAX_VALUE, 0.0) } // Turn the others off!
return
}
}
}
override fun actorModified(sceneResource: DesignSceneResource, actorResource: DesignActorResource, type: ModificationType) {
dirty = true
}
override fun selectionChanged() {
dragHandles.clear()
val latest = sceneEditor.selection.latest()
if (latest != null) {
if (latest.costume()?.canRotate == true) {
dragHandles.add(RotateArrow("Direction", latest))
}
if (latest.isSizable()) {
dragHandles.add(SizeHandle(latest, true, true))
dragHandles.add(SizeHandle(latest, true, false))
dragHandles.add(SizeHandle(latest, false, true))
dragHandles.add(SizeHandle(latest, false, false))
} else if (latest.isScalable()) {
dragHandles.add(ScaleHandle(latest, true, true))
dragHandles.add(ScaleHandle(latest, true, false))
dragHandles.add(ScaleHandle(latest, false, true))
dragHandles.add(ScaleHandle(latest, false, false))
}
latest.attributes.map().forEach { name, data ->
data as DesignAttributeData
when (data.attributeType) {
AttributeType.DIRECTION -> {
dragHandles.add(DirectionArrow(name, latest, data, data.order))
}
AttributeType.POLAR -> {
dragHandles.add(PolarArrow(name, latest, data))
}
AttributeType.ABSOLUTE_POSITION -> {
dragHandles.add(AbsoluteHandle(name, latest, data))
}
AttributeType.RELATIVE_POSITION -> {
dragHandles.add(RelativeHandle(name, latest, data))
}
AttributeType.NORMAL -> {
}
}
}
}
dirty = true
}
fun outlinedText(text: String) {
with(canvas.graphicsContext2D) {
scale(1.0 / scale, -1.0 / scale)
lineWidth = 3.0
stroke = Color.BLACK
strokeText(text, 0.0, 0.0)
fill = latestColor
fillText(text, 0.0, 0.0)
}
}
fun drawCostumeName(actorResource: ActorResource) {
with(canvas.graphicsContext2D) {
save()
translate(actorResource.x - actorResource.offsetX(), actorResource.y - actorResource.offsetY() - 20.0)
outlinedText(actorResource.costumeName)
restore()
}
}
fun drawBoundingBox(actorResource: ActorResource) {
val margin = 2.0
if (actorResource.isSizable()) {
canvas.graphicsContext2D.strokeRect(
-actorResource.sizeAlignment.x * actorResource.size.x,
-actorResource.sizeAlignment.y * actorResource.size.y,
actorResource.size.x,
actorResource.size.y
)
} else {
actorResource.editorPose?.let { pose ->
canvas.graphicsContext2D.strokeRect(
-pose.offsetX - margin,
-pose.offsetY - margin,
pose.rect.width.toDouble() + margin * 2,
pose.rect.height.toDouble() + margin * 2)
return
}
actorResource.textStyle?.let { textStyle ->
val text = actorResource.displayText
val offsetX = textStyle.offsetX(text)
val offsetY = textStyle.offsetY(text)
val width = textStyle.width(text)
val height = textStyle.height(text)
canvas.graphicsContext2D.strokeRect(-offsetX, offsetY - height, width, height)
}
}
}
fun lineWithHandle(length: Double, handleShape: () -> Unit = { drawArrowHead() }) {
with(canvas.graphicsContext2D) {
save()
strokeLine(0.0, 0.0, length - 3 / scale, 0.0)
translate(length, 0.0)
handleShape()
restore()
}
}
fun drawArrowHead() {
with(canvas.graphicsContext2D) {
strokeLine(0.0, 0.0, -arrowSize / scale, -arrowSize / 2 / scale)
strokeLine(0.0, 0.0, -arrowSize / scale, arrowSize / 2 / scale)
}
}
fun drawRoundHandle() {
with(canvas.graphicsContext2D) {
strokeOval(-3.0 / scale, -3.0 / scale, 6.0 / scale, 6.0 / scale)
}
}
fun drawDiamondHandle() {
with(canvas.graphicsContext2D) {
save()
rotate(45.0)
drawSquareHandle()
restore()
}
}
fun drawSquareHandle() {
with(canvas.graphicsContext2D) {
strokeRect(-2.5 / scale, -2.5 / scale, 5.0 / scale, 5.0 / scale)
}
}
fun drawCornerHandle() {
with(canvas.graphicsContext2D) {
strokeRect(1.0, -3.5 / scale, 2.0 / scale, 6.0 / scale)
strokeRect(-3.5, 1.0 / scale, 6.0 / scale, 2.0 / scale)
}
}
fun drawOutlined(color: Color, shape: () -> Unit) {
with(canvas.graphicsContext2D) {
stroke = Color.BLACK
lineCap = StrokeLineCap.ROUND
lineWidth = 4.0 / scale
shape()
stroke = color
lineWidth = 2.5 / scale
shape()
}
}
companion object {
var borderColor: Color = Color.LIGHTCORAL
var borderWidth = 1.0
var selectionColor: Color = Color.web("#0000c0")
var latestColor: Color = Color.web("#8000ff")
var hightlightColor: Color = Color.web("#80ff00")
var directionLength = 40.0
var directionExtra = 15.0
var arrowSize = 10.0
fun handleColor(hovering: Boolean) = if (hovering) hightlightColor else latestColor
fun selectionColor(latest: Boolean) = if (latest) latestColor else selectionColor
}
fun findDragHandle(x: Double, y: Double): DragHandle? {
return dragHandles.firstOrNull { it.isNear(x, y) }
}
interface DragHandle {
val hovering: Boolean
val name: String
fun draw()
fun x(): Double
fun y(): Double
fun isNear(x: Double, y: Double): Boolean
fun hover(x: Double, y: Double): Boolean
fun moveTo(x: Double, y: Double, snap: Boolean)
}
abstract inner class AbstractDragHandle(override val name: String) : DragHandle {
override var hovering: Boolean = false
set(v) {
if (v != field) {
field = v
dirty = true
}
}
override fun hover(x: Double, y: Double): Boolean {
hovering = isNear(x, y)
return hovering
}
override fun isNear(x: Double, y: Double): Boolean {
val dx = x - x()
val dy = y - y()
return dx * dx + dy * dy < 36 // 6 pixels
}
}
abstract inner class Arrow(name: String, val actorResource: DesignActorResource, val distance: Int)
: AbstractDragHandle(name) {
abstract fun set(degrees: Double)
abstract fun get(): Double
override fun x() = actorResource.x + (directionLength + distance * directionExtra) * Math.cos(Math.toRadians(get()))
override fun y() = actorResource.y + (directionLength + distance * directionExtra) * Math.sin(Math.toRadians(get()))
override fun draw() {
with(canvas.graphicsContext2D) {
save()
translate(actorResource.x, actorResource.y)
val length = directionLength + distance * directionExtra
rotate(get())
drawOutlined(handleColor(hovering)) { drawArrowHandle(length) }
restore()
}
}
open fun drawArrowHandle(length: Double) {
lineWithHandle(length)
}
}
inner class RotateArrow(name: String, actorResource: DesignActorResource)
: Arrow(name, actorResource, 0) {
override fun get() = actorResource.direction.degrees
override fun set(degrees: Double) {
// I don't think this is used! ???
sceneEditor.history.makeChange(Rotate(actorResource, degrees))
}
override fun moveTo(x: Double, y: Double, snap: Boolean) {
val dx = x - actorResource.x
val dy = y - actorResource.y
val atan = Math.atan2(dy, dx)
var degrees = Math.toDegrees(if (atan < 0) atan + Math.PI * 2 else atan)
if (snap) {
degrees = sceneEditor.sceneResource.snapRotation.snapRotation(degrees)
}
val diff = degrees - actorResource.direction.degrees
sceneEditor.selection.forEach { actor ->
sceneEditor.history.makeChange(Rotate(actorResource, actor.direction.degrees + diff))
}
}
override fun drawArrowHandle(length: Double) {
lineWithHandle(length) { drawRoundHandle() }
}
}
abstract inner class SizeScaleHandle(name: String, val actorResource: DesignActorResource, val isLeft: Boolean, val isBottom: Boolean)
: AbstractDragHandle(name) {
override fun draw() {
with(canvas.graphicsContext2D) {
save()
translate(x(), y())
rotate(actorResource.direction.degrees - (actorResource.editorPose?.direction?.degrees ?: 0.0))
if (isLeft) scale(-1.0, 1.0)
if (isBottom) scale(1.0, -1.0)
drawOutlined(handleColor(hovering)) { drawCornerHandle() }
restore()
}
}
fun actorToView(actorResource: ActorResource, vector: Vector2d) {
vector.mul(actorResource.scale)
vector.rotate(actorResource.direction.radians - (actorResource.editorPose?.direction?.radians ?: 0.0))
vector.add(actorResource.x, actorResource.y)
}
fun viewToActor(actorResource: ActorResource, vector: Vector2d) {
vector.add(-actorResource.x, -actorResource.y)
vector.rotate(-actorResource.direction.radians + (actorResource.editorPose?.direction?.radians ?: 0.0))
vector.mul(1 / actorResource.scale.x, 1 / actorResource.scale.y)
}
}
inner class SizeHandle(actorResource: DesignActorResource, isLeft: Boolean, isBottom: Boolean)
: SizeScaleHandle("Resize", actorResource, isLeft, isBottom) {
override fun moveTo(x: Double, y: Double, snap: Boolean) {
val oldX = actorResource.x
val oldY = actorResource.y
val oldSizeX = actorResource.size.x
val oldSizeY = actorResource.size.y
val now = Vector2d(x, y)
viewToActor(actorResource, now)
val was = Vector2d(x(), y())
viewToActor(actorResource, was)
val dx = now.x - was.x
val dy = now.y - was.y
actorResource.size.x += if (isLeft) -dx else dx
actorResource.size.y += if (isBottom) -dy else dy
actorResource.x -= x() - x
actorResource.y -= y() - y
sceneEditor.history.makeChange(Resize(actorResource, oldX, oldY, oldSizeX, oldSizeY))
actorResource.draggedX = actorResource.x
actorResource.draggedY = actorResource.y
}
override fun x(): Double {
val vector = Vector2d(
(if (isLeft) 0.0 else actorResource.size.x) - actorResource.sizeAlignment.x * actorResource.size.x,
(if (isBottom) 0.0 else actorResource.size.y) - actorResource.sizeAlignment.y * actorResource.size.y)
actorToView(actorResource, vector)
return vector.x
}
override fun y(): Double {
val vector = Vector2d(
(if (isLeft) 0.0 else actorResource.size.x) - actorResource.sizeAlignment.x * actorResource.size.x,
(if (isBottom) 0.0 else actorResource.size.y) - actorResource.sizeAlignment.y * actorResource.size.y)
actorToView(actorResource, vector)
return vector.y
}
}
inner class ScaleHandle(actorResource: DesignActorResource, isLeft: Boolean, isBottom: Boolean)
: SizeScaleHandle("Scale", actorResource, isLeft, isBottom) {
override fun moveTo(x: Double, y: Double, snap: Boolean) {
val pose = actorResource.pose ?: return
val oldX = actorResource.x
val oldY = actorResource.y
val oldScaleX = actorResource.scale.x
val oldScaleY = actorResource.scale.y
val now = Vector2d(x, y)
viewToActor(actorResource, now)
val was = Vector2d(x(), y())
viewToActor(actorResource, was)
val factorX = (pose.rect.width + now.x - was.x) / pose.rect.width
val factorY = (pose.rect.height + now.y - was.y) / pose.rect.height
actorResource.scale.x *= if (isLeft) 1.0 / factorX else factorX
actorResource.scale.y *= if (isBottom) 1.0 / factorY else factorY
actorResource.x -= x() - x
actorResource.y -= y() - y
sceneEditor.history.makeChange(Scale(actorResource, oldX, oldY, oldScaleX, oldScaleY))
actorResource.draggedX = actorResource.x
actorResource.draggedY = actorResource.y
}
override fun x(): Double {
val pose = actorResource.pose ?: return 0.0
val vector = Vector2d(
(if (isLeft) -pose.offsetX else pose.rect.width - pose.offsetX),
(if (isBottom) -pose.offsetY else pose.rect.height - pose.offsetY))
actorToView(actorResource, vector)
return vector.x
}
override fun y(): Double {
val pose = actorResource.pose ?: return 0.0
val vector = Vector2d(
(if (isLeft) -pose.offsetX else pose.rect.width - pose.offsetX),
(if (isBottom) -pose.offsetY else pose.rect.height - pose.offsetY))
actorToView(actorResource, vector)
return vector.y
}
}
inner class DirectionArrow(name: String, actorResource: DesignActorResource, val data: DesignAttributeData, distance: Int)
: Arrow(name, actorResource, distance) {
val parameter = if (data.parameter is AngleParameter)
(data.parameter as AngleParameter).degreesP
else
data.parameter as DoubleParameter
override fun get() = parameter.value ?: 0.0
override fun set(degrees: Double) {
sceneEditor.history.makeChange(ChangeDoubleParameter(actorResource, parameter, degrees))
}
override fun moveTo(x: Double, y: Double, snap: Boolean) {
val dx = x - actorResource.x
val dy = y - actorResource.y
val atan = Math.atan2(dy, dx)
var angle = if (atan < 0) atan + Math.PI * 2 else atan
angle -= angle.rem(Math.toRadians(if (snap) 15.0 else 1.0))
set(Math.toDegrees(angle))
}
override fun drawArrowHandle(length: Double) {
lineWithHandle(length) { drawDiamondHandle() }
}
}
inner class PolarArrow(name: String, val actorResource: DesignActorResource, val data: DesignAttributeData)
: AbstractDragHandle(name) {
val parameter = data.parameter!! as PolarParameter
fun set(angleRadians: Double, magnitude: Double) {
sceneEditor.history.makeChange(ChangePolarParameter(actorResource, parameter, Math.toDegrees(angleRadians), magnitude))
}
override fun x() = actorResource.x + parameter.value.vector().x * data.scale
override fun y() = actorResource.y + parameter.value.vector().y * data.scale
override fun moveTo(x: Double, y: Double, snap: Boolean) {
val dx = x - actorResource.x
val dy = y - actorResource.y
val atan = Math.atan2(dy, dx)
var angle = if (atan < 0) atan + Math.PI * 2 else atan
angle -= angle.rem(Math.toRadians(if (snap) 15.0 else 1.0))
var mag = Math.sqrt(dx * dx + dy * dy) / data.scale
if (snap) {
mag = Math.floor(mag)
}
set(angle, mag)
}
override fun draw() {
with(canvas.graphicsContext2D) {
save()
translate(actorResource.x, actorResource.y)
val length = parameter.magnitude!! * data.scale
rotate(parameter.value.angle.degrees)
drawOutlined(handleColor(hovering)) { lineWithHandle(length) }
restore()
}
}
}
open inner class AbsoluteHandle(name: String, val actorResource: DesignActorResource, val data: DesignAttributeData)
: AbstractDragHandle(name) {
val parameter = data.parameter!! as Vector2dParameter
fun set(x: Double, y: Double) {
sceneEditor.history.makeChange(ChangeVector2dParameter(actorResource, parameter, x, y))
}
override fun x() = parameter.x!!
override fun y() = parameter.y!!
override fun moveTo(x: Double, y: Double, snap: Boolean) {
set(x, y)
}
override fun draw() {
with(canvas.graphicsContext2D) {
save()
translate(parameter.x!!, parameter.y!!)
drawOutlined(handleColor(hovering)) { drawSquareHandle() }
restore()
}
}
}
inner class RelativeHandle(name: String, actorResource: DesignActorResource, data: DesignAttributeData)
: AbsoluteHandle(name, actorResource, data) {
override fun x() = actorResource.x + super.x() * data.scale
override fun y() = actorResource.y + super.y() * data.scale
override fun moveTo(x: Double, y: Double, snap: Boolean) {
var dx = (x - actorResource.x) / data.scale
var dy = (y - actorResource.y) / data.scale
if (snap) {
dx = Math.floor(dx)
dy = Math.floor(dy)
}
set(dx, dy)
}
override fun draw() {
with(canvas.graphicsContext2D) {
save()
translate(actorResource.x + parameter.x!! * data.scale, actorResource.y + parameter.y!! * data.scale)
drawOutlined(handleColor(hovering)) { drawDiamondHandle() }
restore()
}
}
}
}
| gpl-3.0 | 2a84507fcc72b196a6714490b424a902 | 31.964539 | 138 | 0.568933 | 4.356955 | false | false | false | false |
proxer/ProxerAndroid | src/main/kotlin/me/proxer/app/ui/view/bbcode/BBTree.kt | 1 | 3573 | package me.proxer.app.ui.view.bbcode
import me.proxer.app.ui.view.bbcode.prototype.BBPrototype
import me.proxer.app.ui.view.bbcode.prototype.ConditionalTextMutatorPrototype
import me.proxer.app.ui.view.bbcode.prototype.ContentPrototype
import me.proxer.app.ui.view.bbcode.prototype.TextMutatorPrototype
import me.proxer.app.ui.view.bbcode.prototype.TextPrototype
import me.proxer.app.util.extension.unsafeLazy
/**
* @author Ruben Gees
*/
class BBTree(
val prototype: BBPrototype,
val parent: BBTree?,
val children: MutableList<BBTree> = mutableListOf(),
val args: BBArgs = BBArgs()
) {
fun endsWith(code: String) = prototype.endRegex.matches(code)
fun makeViews(parent: BBCodeView, args: BBArgs) = prototype.makeViews(parent, children, args + this.args)
fun optimize(args: BBArgs = BBArgs()) = recursiveOptimize(args).first()
fun isBlank(): Boolean {
if (prototype is ContentPrototype && !prototype.isBlank(args)) {
return false
}
return children.all { it.isBlank() }
}
private fun recursiveOptimize(args: BBArgs): List<BBTree> {
val recursiveNewChildren by unsafeLazy { getRecursiveChildren(children) }
val canOptimize = prototype !is ConditionalTextMutatorPrototype || prototype.canOptimize(recursiveNewChildren)
if (prototype is TextMutatorPrototype && canOptimize) {
recursiveNewChildren.forEach {
if (it.prototype == TextPrototype) {
val mergedArgs = args + this.args + it.args
it.args.text = prototype.mutate(it.args.safeText.toSpannableStringBuilder(), mergedArgs)
}
}
}
val newChildren = mergeChildren(children.flatMap { it.recursiveOptimize(args) })
return when {
canOptimize && prototype is TextMutatorPrototype -> newChildren.map {
BBTree(it.prototype, parent, it.children, it.args)
}
else -> {
children.clear()
children.addAll(newChildren)
listOf(this)
}
}
}
private fun mergeChildren(newChildren: List<BBTree>): List<BBTree> {
val result = mutableListOf<BBTree>()
if (newChildren.isNotEmpty()) {
var current = newChildren.first()
newChildren.drop(1).forEach { next ->
if (current.prototype == TextPrototype && next.prototype == TextPrototype) {
current.args.text = current.args.safeText.toSpannableStringBuilder().append(next.args.safeText)
} else {
result += current
current = next
}
}
result += current
}
return result
}
private fun getRecursiveChildren(current: List<BBTree>): List<BBTree> = current
.plus(current.flatMap { getRecursiveChildren(it.children) })
@Suppress("EqualsAlwaysReturnsTrueOrFalse") // False positive
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as BBTree
if (prototype != other.prototype) return false
if (children != other.children) return false
if (args != other.args) return false
return true
}
override fun hashCode(): Int {
var result = prototype.hashCode()
result = 31 * result + children.hashCode()
result = 31 * result + args.hashCode()
return result
}
}
| gpl-3.0 | e335f45c67c0ebac007cc28203a39d9e | 32.392523 | 118 | 0.623006 | 4.670588 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/utils/DictionaryExecutor.kt | 1 | 6460 | package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils
import dev.kord.common.Color
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import net.perfectdreams.discordinteraktions.common.builder.message.embed
import net.perfectdreams.discordinteraktions.common.utils.field
import net.perfectdreams.discordinteraktions.common.utils.footer
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.declarations.DictionaryCommand
import org.jsoup.Jsoup
import java.net.URLEncoder
class DictionaryExecutor(loritta: LorittaBot, val http: HttpClient) : CinnamonSlashCommandExecutor(loritta) {
inner class Options : LocalizedApplicationCommandOptions(loritta) {
val language = string("language", DictionaryCommand.I18N_PREFIX.Options.Language) {
choice(DictionaryCommand.I18N_PREFIX.Languages.PtBr, "pt-br")
}
val word = string("word", DictionaryCommand.I18N_PREFIX.Options.Word)
}
override val options = Options()
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
// TODO: More languages
val language = args[options.language]
val wordToBeSearched = args[options.word]
val httpResponse = http.get(
"https://www.dicio.com.br/pesquisa.php?q=${
URLEncoder.encode(
wordToBeSearched,
"UTF-8"
)
}"
)
if (httpResponse.status == HttpStatusCode.NotFound)
context.failEphemerally(
context.i18nContext.get(DictionaryCommand.I18N_PREFIX.WordNotFound),
Emotes.Error
)
val response = httpResponse.bodyAsText()
var jsoup = Jsoup.parse(response)
// Ao usar pesquisa.php, ele pode retornar uma página de pesquisa ou uma página com a palavra, por isto iremos primeiro descobrir se estamos na página de pesquisa
val resultadosClass = jsoup.getElementsByClass("resultados")
val resultados = resultadosClass.firstOrNull()
if (resultados != null) {
val resultadosLi = resultados.getElementsByTag("li").firstOrNull()
?: context.failEphemerally(
context.i18nContext.get(DictionaryCommand.I18N_PREFIX.WordNotFound),
Emotes.Error
)
val linkElement = resultadosLi.getElementsByClass("_sugg").first()!!
val link = linkElement.attr("href")
val httpRequest2 = http.get("https://www.dicio.com.br$link")
// This should *never* happen because we are getting it directly from the search results, but...
if (httpRequest2.status == HttpStatusCode.NotFound)
context.failEphemerally(
context.i18nContext.get(DictionaryCommand.I18N_PREFIX.WordNotFound),
Emotes.Error
)
val response2 = httpRequest2.bodyAsText()
jsoup = Jsoup.parse(response2)
}
// Se a página não possui uma descrição ou se ela possui uma descrição mas começa com "Ainda não temos o significado de", então é uma palavra inexistente!
if (jsoup.select("p[itemprop = description]").isEmpty() || jsoup.select("p[itemprop = description]")[0].text()
.startsWith("Ainda não temos o significado de")
)
context.failEphemerally(
context.i18nContext.get(DictionaryCommand.I18N_PREFIX.WordNotFound),
Emotes.Error
)
val description = jsoup.select("p[itemprop = description]")[0]
val type = description.getElementsByTag("span")[0]
val word = jsoup.select("h1[itemprop = name]")
val what = description.getElementsByTag("span").getOrNull(1)
val etim = description.getElementsByClass("etim").firstOrNull()
// *Technically* the image is always
// https://s.dicio.com.br/word_here.jpg
// Example: https://s.dicio.com.br/bunda.jpg
// However we wouldn't be sure if the image really exists, so let's check in the page
val wordImage = jsoup.getElementsByClass("imagem-palavra").firstOrNull()
val frase = if (jsoup.getElementsByClass("frase").isNotEmpty()) {
jsoup.getElementsByClass("frase")[0]
} else {
null
}
context.sendMessage {
embed {
color = Color(25, 89, 132) // TODO: Move this to a object
title = "${Emotes.BlueBook} ${context.i18nContext.get(DictionaryCommand.I18N_PREFIX.MeaningOf(word.text()))}"
this.description = buildString {
append("*${type.text()}*")
if (what != null)
append("\n\n**${what.text()}**")
}
// The first in the page will always be "synonyms"
// While the second in the page will always be "opposites"
jsoup.getElementsByClass("sinonimos").getOrNull(0)?.let {
field("\uD83D\uDE42 ${context.i18nContext.get(DictionaryCommand.I18N_PREFIX.Synonyms)}", it.text())
}
jsoup.getElementsByClass("sinonimos").getOrNull(1)?.let {
field("\uD83D\uDE41 ${context.i18nContext.get(DictionaryCommand.I18N_PREFIX.Opposite)}", it.text())
}
frase?.let {
field("\uD83D\uDD8B ${context.i18nContext.get(DictionaryCommand.I18N_PREFIX.Sentence)}", it.text())
}
if (wordImage != null)
// We need to use "data-src" because the page uses lazy loading
image = wordImage.attr("data-src")
if (etim != null)
footer(etim.text())
}
}
}
} | agpl-3.0 | 1e698f3c21b98c8e5a55cea882daf48b | 42.857143 | 170 | 0.635588 | 4.427198 | false | false | false | false |
LorittaBot/Loritta | web/dashboard/spicy-frontend/src/jsMain/kotlin/net/perfectdreams/loritta/cinnamon/dashboard/frontend/components/userdash/shipeffects/ActiveShipEffects.kt | 1 | 4839 | package net.perfectdreams.loritta.cinnamon.dashboard.frontend.components.userdash.shipeffects
import androidx.compose.runtime.Composable
import kotlinx.datetime.Clock
import net.perfectdreams.i18nhelper.core.I18nContext
import net.perfectdreams.loritta.cinnamon.dashboard.frontend.LorittaDashboardFrontend
import net.perfectdreams.loritta.cinnamon.dashboard.frontend.components.EmptySection
import net.perfectdreams.loritta.cinnamon.dashboard.frontend.components.IconWithText
import net.perfectdreams.loritta.cinnamon.dashboard.frontend.components.InlineNullableUserDisplay
import net.perfectdreams.loritta.cinnamon.dashboard.frontend.components.LoadingSection
import net.perfectdreams.loritta.cinnamon.dashboard.frontend.components.LocalizedH2
import net.perfectdreams.loritta.cinnamon.dashboard.frontend.components.RelativeTimeStamp
import net.perfectdreams.loritta.cinnamon.dashboard.frontend.screen.ShipEffectsScreen
import net.perfectdreams.loritta.cinnamon.dashboard.frontend.utils.LocalUserIdentification
import net.perfectdreams.loritta.cinnamon.dashboard.frontend.utils.SVGIconManager
import net.perfectdreams.loritta.cinnamon.dashboard.frontend.utils.State
import net.perfectdreams.loritta.i18n.I18nKeysData
import org.jetbrains.compose.web.dom.Div
import org.jetbrains.compose.web.dom.Text
@Composable
fun ActiveShipEffects(
m: LorittaDashboardFrontend,
screen: ShipEffectsScreen,
i18nContext: I18nContext
) {
LocalizedH2(i18nContext, I18nKeysData.Website.Dashboard.ShipEffects.ActiveEffects.Title)
when (val state = screen.shipEffects) {
is State.Failure -> {}
is State.Loading -> {
LoadingSection(i18nContext)
}
is State.Success -> {
Div(
attrs = {
classes("cards")
}
) {
val activeShipEffects = state.value.effects.filter { it.expiresAt > Clock.System.now() }.sortedByDescending { it.expiresAt }
if (activeShipEffects.isNotEmpty()) {
val selfUser = LocalUserIdentification.current
for (effect in activeShipEffects) {
Div(
attrs = {
classes("card")
}
) {
// We will only show the user that has the effected applied, because we know that one of them will always be the self user
// Based on the implementation, we also know that the user1 in the ship effect is always the self user, but we will check it ourselves because...
// maybe the implementation may change some day?
val user1 = state.value.resolvedUsers.firstOrNull { it.id == effect.user1 }
val user2 = state.value.resolvedUsers.firstOrNull { it.id == effect.user2 }
if (effect.user1 == effect.user2) {
// Applied to self, so let's render the first user
IconWithText(SVGIconManager.heart) {
InlineNullableUserDisplay(effect.user1, user1)
}
} else {
// Now we do individual checks for each field
// The reason we do it like this is... what if some day we let users apply effects to two different users? (Probably will never happen)
if (selfUser.id != effect.user1) {
IconWithText(SVGIconManager.heart) {
InlineNullableUserDisplay(effect.user1, user1)
}
}
if (selfUser.id != effect.user2) {
IconWithText(SVGIconManager.heart) {
InlineNullableUserDisplay(effect.user2, user2)
}
}
}
IconWithText(SVGIconManager.sparkles) {
Div {
Text("${effect.editedShipValue}%")
}
}
IconWithText(SVGIconManager.clock) {
Div {
RelativeTimeStamp(i18nContext, effect.expiresAt)
}
}
}
}
} else {
EmptySection(i18nContext)
}
}
}
}
} | agpl-3.0 | 094b5e80811a39708a8e8bb10934f1bb | 49.416667 | 173 | 0.548874 | 5.549312 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/playback/engine/preparation/PreparedPlayableFileQueue.kt | 2 | 7543 | package com.lasthopesoftware.bluewater.client.playback.engine.preparation
import com.lasthopesoftware.bluewater.client.playback.file.PositionedFile
import com.lasthopesoftware.bluewater.client.playback.file.PositionedPlayableFile
import com.lasthopesoftware.bluewater.client.playback.file.preparation.PlayableFilePreparationSource
import com.lasthopesoftware.bluewater.client.playback.file.preparation.PreparedPlayableFile
import com.lasthopesoftware.bluewater.client.playback.file.preparation.queues.IPositionedFileQueue
import com.namehillsoftware.handoff.promises.Promise
import org.joda.time.Duration
import org.slf4j.LoggerFactory
import java.io.Closeable
import java.util.*
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.locks.ReentrantReadWriteLock
class PreparedPlayableFileQueue(
private val configuration: IPreparedPlaybackQueueConfiguration,
private val playbackPreparer: PlayableFilePreparationSource,
private var positionedFileQueue: IPositionedFileQueue) : SupplyQueuedPreparedFiles, Closeable {
companion object {
private val logger = LoggerFactory.getLogger(PreparedPlayableFileQueue::class.java)
private fun <T> Queue<T>.drainQueue(): Iterable<T> {
val queue = this
return Iterable {
iterator {
do {
val next = queue.poll()
if (next != null)
yield(next)
} while (next != null)
}
}
}
}
private val queueUpdateLock = ReentrantReadWriteLock()
private val bufferingMediaPlayerPromises = ConcurrentLinkedQueue<ProvidePreparedPlaybackFile>()
private var currentPreparingPlaybackHandlerPromise: ProvidePreparedPlaybackFile? = null
fun updateQueue(newPositionedFileQueue: IPositionedFileQueue): PreparedPlayableFileQueue {
val writeLock = queueUpdateLock.writeLock()
writeLock.lock()
return try {
val newPositionedPreparingMediaPlayerPromises = LinkedList<ProvidePreparedPlaybackFile>()
for (positionedPreparingFile in bufferingMediaPlayerPromises.drainQueue()) {
if (positionedPreparingFile.positionedFile == newPositionedFileQueue.peek()) {
newPositionedPreparingMediaPlayerPromises.offer(positionedPreparingFile)
newPositionedFileQueue.poll()
continue
}
for (file in bufferingMediaPlayerPromises.drainQueue()) {
file.preparedPlaybackFilePromise.cancel()
}
}
for (positionedPreparingFile in newPositionedPreparingMediaPlayerPromises.drainQueue()) {
bufferingMediaPlayerPromises.offer(positionedPreparingFile)
}
positionedFileQueue = newPositionedFileQueue
beginQueueingPreparingPlayers()
this
} finally {
writeLock.unlock()
}
}
override fun promiseNextPreparedPlaybackFile(preparedAt: Duration): Promise<PositionedPlayableFile>? {
return bufferingMediaPlayerPromises.poll()?.let {
currentPreparingPlaybackHandlerPromise = it
Promise.whenAny(
it.promisePositionedPreparedPlaybackFile(),
Promise(PositionedPreparedPlayableFile.emptyHandler(it.positionedFile)))
.eventually(::preparePlayableFileAgainIfNecessary)
.then(::toPositionedPlayableFile)
} ?: getNextFaultingPreparingMediaPlayerPromise(preparedAt).let {
currentPreparingPlaybackHandlerPromise = it
it?.promisePositionedPreparedPlaybackFile()?.then(::toPositionedPlayableFile)
}
}
override fun close() {
currentPreparingPlaybackHandlerPromise?.preparedPlaybackFilePromise?.cancel()
val writeLock = queueUpdateLock.writeLock()
writeLock.lock()
try {
for (positionedPreparingFile in bufferingMediaPlayerPromises.drainQueue())
positionedPreparingFile.preparedPlaybackFilePromise.cancel()
} finally {
writeLock.unlock()
}
}
private fun getNextUnfaultingPreparingMediaPlayerPromise(): PositionedUnfaultingPreparingFile? {
val writeLock = queueUpdateLock.writeLock()
writeLock.lock()
return try {
positionedFileQueue.poll()
} finally {
writeLock.unlock()
}?.let {
PositionedUnfaultingPreparingFile(
it,
playbackPreparer.promisePreparedPlaybackFile(it.serviceFile, Duration.ZERO))
}
}
private fun getNextFaultingPreparingMediaPlayerPromise(preparedAt: Duration): PositionedPreparingFile? {
val writeLock = queueUpdateLock.writeLock()
writeLock.lock()
return try {
positionedFileQueue.poll()
} finally {
writeLock.unlock()
}?.let {
PositionedPreparingFile(
it,
playbackPreparer.promisePreparedPlaybackFile(it.serviceFile, preparedAt))
}
}
private fun beginQueueingPreparingPlayers() {
val writeLock = queueUpdateLock.writeLock()
writeLock.lock()
try {
if (bufferingMediaPlayerPromises.size >= configuration.maxQueueSize) return
val nextPreparingMediaPlayerPromise = getNextUnfaultingPreparingMediaPlayerPromise() ?: return
bufferingMediaPlayerPromises.offer(nextPreparingMediaPlayerPromise)
nextPreparingMediaPlayerPromise.promisePositionedPreparedPlaybackFile().then(::toPositionedPlayableFile)
} finally {
writeLock.unlock()
}
}
private fun toPositionedPlayableFile(positionedPreparedPlayableFile: PositionedPreparedPlayableFile): PositionedPlayableFile {
positionedPreparedPlayableFile.preparedPlayableFile
.bufferingPlaybackFile
.promiseBufferedPlaybackFile()
.then { beginQueueingPreparingPlayers() }
return PositionedPlayableFile(
positionedPreparedPlayableFile.preparedPlayableFile.playbackHandler,
positionedPreparedPlayableFile.preparedPlayableFile.playableFileVolumeManager,
positionedPreparedPlayableFile.positionedFile)
}
private fun preparePlayableFileAgainIfNecessary(positionedPreparedPlayableFile: PositionedPreparedPlayableFile): Promise<PositionedPreparedPlayableFile> {
if (!positionedPreparedPlayableFile.isEmpty) return Promise(positionedPreparedPlayableFile)
val positionedFile = positionedPreparedPlayableFile.positionedFile
logger.warn("$positionedFile failed to prepare in time. Cancelling and preparing again.")
currentPreparingPlaybackHandlerPromise?.preparedPlaybackFilePromise?.cancel()
return PositionedPreparingFile(
positionedFile,
playbackPreparer.promisePreparedPlaybackFile(positionedFile.serviceFile, Duration.ZERO)).also {
currentPreparingPlaybackHandlerPromise = it
}.promisePositionedPreparedPlaybackFile()
}
private class PositionedPreparingFile(
override val positionedFile: PositionedFile,
override val preparedPlaybackFilePromise: Promise<PreparedPlayableFile>)
: ProvidePreparedPlaybackFile {
override fun promisePositionedPreparedPlaybackFile(): Promise<PositionedPreparedPlayableFile> =
preparedPlaybackFilePromise.then(
{ handler -> PositionedPreparedPlayableFile(positionedFile, handler) },
{ error -> throw PreparationException(positionedFile, error) })
}
private class PositionedUnfaultingPreparingFile(
override val positionedFile: PositionedFile,
override val preparedPlaybackFilePromise: Promise<PreparedPlayableFile>) : ProvidePreparedPlaybackFile {
override fun promisePositionedPreparedPlaybackFile(): Promise<PositionedPreparedPlayableFile> =
preparedPlaybackFilePromise.then(
{ handler -> PositionedPreparedPlayableFile(positionedFile, handler) },
{ error ->
logger.warn("An error occurred during preparation, returning an empty handler to trigger re-preparation", error)
PositionedPreparedPlayableFile.emptyHandler(positionedFile)
})
}
private interface ProvidePreparedPlaybackFile {
val positionedFile: PositionedFile
val preparedPlaybackFilePromise: Promise<PreparedPlayableFile>
fun promisePositionedPreparedPlaybackFile(): Promise<PositionedPreparedPlayableFile>
}
}
| lgpl-3.0 | cb2a23cb19517557f541ffa18ec41c8a | 37.682051 | 155 | 0.811216 | 4.6533 | false | false | false | false |
SimonMarquis/FCM-toolbox | app/src/main/java/fr/smarquis/fcm/utils/Extensions.kt | 1 | 2034 | package fr.smarquis.fcm.utils
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.core.content.getSystemService
import androidx.preference.PreferenceManager
import com.google.firebase.messaging.RemoteMessage
import fr.smarquis.fcm.R
import fr.smarquis.fcm.data.model.Message
import fr.smarquis.fcm.data.model.Payload
import java.io.PrintWriter
import java.io.StringWriter
import java.util.*
val uiHandler = Handler(Looper.getMainLooper())
fun Throwable.asString(): String = StringWriter().apply { printStackTrace(PrintWriter(this)) }.toString()
fun Context.safeStartActivity(intent: Intent?) {
try {
startActivity(intent)
} catch (e: Exception) {
Toast.makeText(this, e.asString(), Toast.LENGTH_LONG).show()
}
}
fun Context.copyToClipboard(text: CharSequence?) {
val clipboard = getSystemService<ClipboardManager>() ?: return
clipboard.setPrimaryClip(ClipData.newPlainText(null, text))
uiHandler.post {
Toast.makeText(this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show()
}
}
/**
* @return UUID.randomUUID() or a previously generated UUID, stored in SharedPreferences
*/
fun uuid(context: Context): String {
val prefs = PreferenceManager.getDefaultSharedPreferences(context.applicationContext)
val value = prefs.getString("uuid", null)
if (!value.isNullOrBlank()) {
return value
}
return UUID.randomUUID().toString().apply {
prefs.edit().putString("uuid", this).apply()
}
}
fun RemoteMessage.asMessage() = Message(
from = from,
to = to,
data = data,
collapseKey = collapseKey,
messageId = messageId.toString(),
messageType = messageType,
sentTime = sentTime,
ttl = ttl,
priority = originalPriority,
originalPriority = priority,
payload = Payload.extract(this)) | apache-2.0 | 5726748b47cfc5733f6d255755cd7b57 | 30.307692 | 105 | 0.717797 | 4.35546 | false | false | false | false |
Shynixn/PetBlocks | petblocks-bukkit-plugin/petblocks-bukkit-nms-112R1/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_12_R1/NMSPetRabbit.kt | 1 | 4707 | package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_12_R1
import com.github.shynixn.petblocks.api.PetBlocksApi
import com.github.shynixn.petblocks.api.business.proxy.PathfinderProxy
import com.github.shynixn.petblocks.api.business.service.ConcurrencyService
import com.github.shynixn.petblocks.api.persistence.entity.AIMovement
import net.minecraft.server.v1_12_R1.*
import org.bukkit.Location
import org.bukkit.craftbukkit.v1_12_R1.CraftWorld
import org.bukkit.event.entity.CreatureSpawnEvent
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
class NMSPetRabbit(petDesign: NMSPetArmorstand, location: Location) : EntityRabbit((location.world as CraftWorld).handle) {
private var petDesign: NMSPetArmorstand? = null
private var pathfinderCounter = 0
init {
this.petDesign = petDesign
this.isSilent = true
clearAIGoals()
this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).value = 0.30000001192092896 * 0.75
this.P = 1.0F
val mcWorld = (location.world as CraftWorld).handle
this.setPosition(location.x, location.y - 200, location.z)
mcWorld.addEntity(this, CreatureSpawnEvent.SpawnReason.CUSTOM)
val targetLocation = location.clone()
PetBlocksApi.resolve(ConcurrencyService::class.java).runTaskSync(20L) {
// Only fix location if it is not already fixed.
if (this.bukkitEntity.location.distance(targetLocation) > 20) {
this.setPosition(targetLocation.x, targetLocation.y + 1.0, targetLocation.z)
}
}
}
/**
* Applies pathfinders to the entity.
*/
fun applyPathfinders(pathfinders: List<Any>) {
clearAIGoals()
for (pathfinder in pathfinders) {
if (pathfinder is PathfinderProxy) {
this.goalSelector.a(pathfinderCounter++, Pathfinder(pathfinder))
val aiBase = pathfinder.aiBase
if (aiBase is AIMovement) {
this.getAttributeInstance(GenericAttributes.MOVEMENT_SPEED).value = 0.30000001192092896 * aiBase.movementSpeed
this.P = aiBase.climbingHeight.toFloat()
}
} else {
this.goalSelector.a(pathfinderCounter++, pathfinder as PathfinderGoal)
}
}
}
/**
* Gets called on move to play sounds.
*/
override fun a(blockposition: BlockPosition, block: Block) {
if (petDesign == null) {
return
}
if (!this.isInWater) {
petDesign!!.proxy.playMovementEffects()
}
}
/**
* Disable health.
*/
override fun setHealth(f: Float) {
}
/**
* Gets the bukkit entity.
*/
override fun getBukkitEntity(): CraftPet {
if (this.bukkitEntity == null) {
this.bukkitEntity = CraftPet(this.world.server, this)
}
return this.bukkitEntity as CraftPet
}
/**
* Clears all entity aiGoals.
*/
private fun clearAIGoals() {
val bField = PathfinderGoalSelector::class.java.getDeclaredField("b")
bField.isAccessible = true
(bField.get(this.goalSelector) as MutableSet<*>).clear()
(bField.get(this.targetSelector) as MutableSet<*>).clear()
val cField = PathfinderGoalSelector::class.java.getDeclaredField("c")
cField.isAccessible = true
(cField.get(this.goalSelector) as MutableSet<*>).clear()
(cField.get(this.targetSelector) as MutableSet<*>).clear()
}
} | apache-2.0 | 189ea90b454bd3ccef1a84cdd1b26d2e | 35.215385 | 130 | 0.669216 | 4.322314 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/ExtraPropertiesExtensionsTest.kt | 1 | 2595 | package org.gradle.kotlin.dsl
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.inOrder
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import org.gradle.api.plugins.ExtraPropertiesExtension
import org.hamcrest.CoreMatchers.nullValue
import org.junit.Assert.assertThat
import org.junit.Test
class ExtraPropertiesExtensionsTest {
@Test
fun `can initialize extra property via delegate provider`() {
val extra = mock<ExtraPropertiesExtension> {
on { get("property") } doReturn 42
}
val property by extra(42)
// property is set eagerly
verify(extra).set("property", 42)
// And to prove the type is inferred correctly
use(property)
}
@Test
fun `can initialize extra property using lambda expression`() {
val extra = mock<ExtraPropertiesExtension> {
on { get("property") } doReturn 42
}
val property by extra { 42 }
// property is set eagerly
verify(extra).set("property", 42)
// And to prove the type is inferred correctly
use(property)
}
@Test
fun `can initialize extra property to null via delegate provider`() {
val extra = mock<ExtraPropertiesExtension> {
on { get("property") } doReturn (null as Int?)
}
run {
val property by extra<Int?>(null)
// property is set eagerly
verify(extra).set("property", null)
// And to prove the type is inferred correctly
use(property)
}
run {
val property: Int? by extra
inOrder(extra) {
verify(extra).get("property")
verifyNoMoreInteractions()
}
assertThat(property, nullValue())
}
}
@Test
fun `can initialize extra property to null using lambda expression`() {
val extra = mock<ExtraPropertiesExtension>()
run {
val property by extra { null as Int? }
// property is set eagerly
verify(extra).set("property", null)
// And to prove the type is inferred correctly
use(property)
}
run {
val property: Int? by extra
inOrder(extra) {
verify(extra).get("property")
verifyNoMoreInteractions()
}
assertThat(property, nullValue())
}
}
private
fun use(@Suppress("unused_parameter") property: Int?) = Unit
}
| apache-2.0 | 1134f8f237c4e4f2b321084517590a6e | 23.951923 | 75 | 0.584971 | 4.887006 | false | true | false | false |
halawata13/ArtichForAndroid | app/src/main/java/net/halawata/artich/model/config/ConfigList.kt | 2 | 1804 | package net.halawata.artich.model.config
import android.content.res.Resources
import net.halawata.artich.R
import net.halawata.artich.entity.ConfigListItem
import net.halawata.artich.enum.Media
class ConfigList(val resources: Resources, val type: Type) {
fun getMenuList(): ArrayList<ConfigListItem> {
val menuItems: ArrayList<ConfigListItem> = arrayListOf()
var id: Long = 0
// 共通があるのはメニュー編集のみ
if (type == Type.MENU) {
menuItems.add(ConfigListItem(
id = id++,
mediaId = Media.COMMON,
title = resources.getString(R.string.common_list_name)
))
}
menuItems.add(ConfigListItem(
id = id++,
mediaId = Media.GNEWS,
title = resources.getString(R.string.gnews_list_name)
))
menuItems.add(ConfigListItem(
id = id++,
mediaId = Media.QIITA,
title = resources.getString(R.string.qiita_list_name)
))
menuItems.add(ConfigListItem(
id = id,
mediaId = Media.HATENA,
title = resources.getString(R.string.hatena_list_name)
))
return menuItems
}
fun getMediaId(title: String): Media? =
when (title) {
resources.getString(R.string.common_list_name) -> Media.COMMON
resources.getString(R.string.hatena_list_name) -> Media.HATENA
resources.getString(R.string.qiita_list_name) -> Media.QIITA
resources.getString(R.string.gnews_list_name) -> Media.GNEWS
else -> null
}
enum class Type(val num: Int) {
MENU(0),
MUTE(1),
}
}
| mit | 3bbf6472608c3d5a42eea4eeb083f28b | 29.586207 | 78 | 0.556933 | 4.14486 | false | true | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/dev/kdrag0n/monet/theme/MaterialYouTargets.kt | 1 | 3957 | package dev.kdrag0n.monet.theme
import dev.kdrag0n.colorkt.Color
import dev.kdrag0n.colorkt.cam.Zcam
import dev.kdrag0n.colorkt.cam.Zcam.Companion.toZcam
import dev.kdrag0n.colorkt.rgb.LinearSrgb.Companion.toLinear
import dev.kdrag0n.colorkt.rgb.Srgb
import dev.kdrag0n.colorkt.tristimulus.CieXyz.Companion.toXyz
import dev.kdrag0n.colorkt.tristimulus.CieXyzAbs.Companion.toAbs
import dev.kdrag0n.colorkt.ucs.lab.CieLab
/*
* Default target colors, conforming to Material You standards.
*
* Derived from AOSP and Pixel defaults.
*/
class MaterialYouTargets(
private val chromaFactor: Double = 1.0,
useLinearLightness: Boolean,
val cond: Zcam.ViewingConditions,
) : ColorScheme() {
companion object {
// Linear ZCAM lightness
private val LINEAR_LIGHTNESS_MAP = mapOf(
0 to 100.0,
10 to 99.0,
20 to 98.0,
50 to 95.0,
100 to 90.0,
200 to 80.0,
300 to 70.0,
400 to 60.0,
500 to 50.0,
600 to 40.0,
650 to 35.0,
700 to 30.0,
800 to 20.0,
900 to 10.0,
950 to 5.0,
1000 to 0.0,
)
// CIELAB lightness from AOSP defaults
private val CIELAB_LIGHTNESS_MAP = LINEAR_LIGHTNESS_MAP
.map { it.key to if (it.value == 50.0) 49.6 else it.value }
.toMap()
// Accent colors from Pixel defaults
private val REF_ACCENT1_COLORS = listOf(
0xd3e3fd,
0xa8c7fa,
0x7cacf8,
0x4c8df6,
0x1b6ef3,
0x0b57d0,
0x0842a0,
0x062e6f,
0x041e49,
)
private const val ACCENT1_REF_CHROMA_FACTOR = 1.2
}
override val neutral1: ColorSwatch
override val neutral2: ColorSwatch
override val accent1: ColorSwatch
override val accent2: ColorSwatch
override val accent3: ColorSwatch
init {
val lightnessMap = if (useLinearLightness) {
LINEAR_LIGHTNESS_MAP
} else {
CIELAB_LIGHTNESS_MAP
.map { it.key to cielabL(it.value) }
.toMap()
}
// Accent chroma from Pixel defaults
// We use the most chromatic color as the reference
// A-1 chroma = avg(default Pixel Blue shades 100-900)
// Excluding very bright variants (10, 50) to avoid light bias
// A-1 > A-3 > A-2
val accent1Chroma = calcAccent1Chroma() * ACCENT1_REF_CHROMA_FACTOR
val accent2Chroma = accent1Chroma / 3
val accent3Chroma = accent2Chroma * 2
// Custom neutral chroma
val neutral1Chroma = accent1Chroma / 8
val neutral2Chroma = accent1Chroma / 5
neutral1 = shadesWithChroma(neutral1Chroma, lightnessMap)
neutral2 = shadesWithChroma(neutral2Chroma, lightnessMap)
accent1 = shadesWithChroma(accent1Chroma, lightnessMap)
accent2 = shadesWithChroma(accent2Chroma, lightnessMap)
accent3 = shadesWithChroma(accent3Chroma, lightnessMap)
}
private fun cielabL(l: Double) = CieLab(
L = l,
a = 0.0,
b = 0.0,
).toXyz().toAbs(cond.referenceWhite.y).toZcam(cond, include2D = false).lightness
private fun calcAccent1Chroma() = REF_ACCENT1_COLORS
.map { Srgb(it).toLinear().toXyz().toAbs(cond.referenceWhite.y).toZcam(cond, include2D = false).chroma }
.average()
private fun shadesWithChroma(
chroma: Double,
lightnessMap: Map<Int, Double>,
): Map<Int, Color> {
// Adjusted chroma
val chromaAdj = chroma * chromaFactor
return lightnessMap.map {
it.key to Zcam(
lightness = it.value,
chroma = chromaAdj,
hue = 0.0,
viewingConditions = cond,
)
}.toMap()
}
}
| gpl-3.0 | a08f92b6351b4322d00ec48fbb3b97b8 | 30.15748 | 112 | 0.589083 | 3.428943 | false | false | false | false |
SUPERCILEX/Robot-Scouter | app/server/functions/src/main/kotlin/com/supercilex/robotscouter/server/functions/Templates.kt | 1 | 8248 | package com.supercilex.robotscouter.server.functions
import com.supercilex.robotscouter.common.FIRESTORE_METRICS
import com.supercilex.robotscouter.common.FIRESTORE_NAME
import com.supercilex.robotscouter.common.FIRESTORE_TEMPLATE_ID
import com.supercilex.robotscouter.common.FIRESTORE_TIMESTAMP
import com.supercilex.robotscouter.server.utils.checkbox
import com.supercilex.robotscouter.server.utils.counter
import com.supercilex.robotscouter.server.utils.defaultTemplates
import com.supercilex.robotscouter.server.utils.header
import com.supercilex.robotscouter.server.utils.metrics
import com.supercilex.robotscouter.server.utils.selector
import com.supercilex.robotscouter.server.utils.stopwatch
import com.supercilex.robotscouter.server.utils.text
import com.supercilex.robotscouter.server.utils.types.CollectionReference
import com.supercilex.robotscouter.server.utils.types.FieldValues
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.asPromise
import kotlinx.coroutines.async
import kotlinx.coroutines.await
import kotlinx.coroutines.awaitAll
import kotlin.js.Json
import kotlin.js.Promise
import kotlin.js.json
/**
* This function and [pitTemplateMetrics] update the default templates server-side without requiring
* a full app update. To improve the templates or update them for a new game, follow these
* instructions.
*
* ## Creating a new template for a new game
*
* 1. Delete the existing metrics
* 1. Make sure to update _both_ the match and pit scouting templates (the pit template likely won't
* require much work)
* 1. Increment the letter for each new metric added (e.g. 'a' -> 'b' -> 'c')
* - Should the template exceed 26 items, start with `aa` -> 'ab' -> 'ac"
* 1. Always start with a header and space the metrics in code by grouping
* 1. In terms of punctuation, use Title Case for headers and Sentence case for all other metrics
* 1. **For examples of correct metric DSL usage**, take a look at the current template or the Git
* log for past templates
*
* ## Improving the current year's template
*
* 1. When moving metrics around, keep their letter IDs the same
* 1. When inserting a metric, don't change the IDs of surrounding metrics; just pick an unused ID
* 1. Minimize deletions at all costs since that makes data analysis harder
*/
fun matchTemplateMetrics() = metrics {
header("a", "Scout info")
text("b", "Name")
header("c", "Sandstorm")
selector("d", "Starting location") {
+Item("a", "HAB Level 1")
+Item("b", "HAB Level 2")
+Item("c", "Unknown", true)
}
checkbox("e", "Successfully crossed HAB line")
counter("f", "Panels on Cargo Ship")
counter("g", "Panels on low Rocket Hatches")
counter("h", "Panels on middle/high Rocket Hatches")
counter("i", "Cargo in Cargo Ship")
counter("j", "Cargo in low Rocket Bays")
counter("k", "Cargo in middle/high Rocket Bays")
header("l", "Teleop")
counter("m", "Panels on Cargo Ship")
counter("n", "Panels on low Rocket Hatches")
counter("o", "Panels on middle/high Rocket Hatches")
counter("p", "Cargo in Cargo Ship")
counter("q", "Cargo in low Rocket Bays")
counter("r", "Cargo in middle/high Rocket Bays")
stopwatch("s", "Panel delivery cycle time")
stopwatch("t", "Cargo delivery cycle time")
selector("u", "Endgame location") {
+Item("a", "HAB Level 1")
+Item("b", "HAB Level 2")
+Item("c", "HAB Level 3")
+Item("d", "Not on HAB", true)
}
header("v", "Post-game")
checkbox("w", "Robot broke")
text("x", "Other")
}
/** @see [matchTemplateMetrics] */
fun pitTemplateMetrics() = metrics {
header("a", "Scout info")
text("b", "Name")
header("c", "Hardware")
selector("d", "What's their drivetrain?") {
+Item("a", "Standard 6/8 wheel")
+Item("b", "Swerve")
+Item("c", "Omni/Mecanum")
+Item("d", "Other")
+Item("e", "Unknown", true)
}
text("e", "If other, please specify")
checkbox("f", "Do they have a Hatch Panel ground intake?")
checkbox("g", "Do they have a Cargo ground intake?")
header("h", "Sandstorm Strategy")
selector("i", "Where does their robot start from?") {
+Item("a", "HAB Level 1")
+Item("b", "HAB Level 2")
+Item("c", "Unknown", true)
}
selector("j", "How does their robot move during the Sandstorm?") {
+Item("a", "Autonomous code")
+Item("b", "Driver control")
+Item("c", "Hybrid")
+Item("d", "No movement")
+Item("e", "Unknown", true)
}
selector("k", "Where can they place Hatch Panels during the Sandstorm?") {
+Item("a", "Nowhere")
+Item("b", "Cargo Ship only")
+Item("c", "Cargo Ship and low Rocket Hatches")
+Item("d", "Cargo Ship and low/middle Rocket Hatches")
+Item("e", "Anywhere")
+Item("f", "Other")
+Item("g", "Unknown", true)
}
text("l", "If other, please specify")
selector("m", "Where can they place Cargo during the Sandstorm?") {
+Item("a", "Nowhere")
+Item("b", "Cargo Ship only")
+Item("c", "Cargo Ship and low Rocket Hatches")
+Item("d", "Cargo Ship and low/middle Rocket Hatches")
+Item("e", "Anywhere")
+Item("f", "Other")
+Item("g", "Unknown", true)
}
text("n", "If other, please specify")
header("o", "Teleop Strategy")
selector("p", "Where can they place Hatch Panels during Teleop?") {
+Item("a", "Nowhere")
+Item("b", "Cargo Ship only")
+Item("c", "Cargo Ship and low Rocket Hatches")
+Item("d", "Cargo Ship and low/middle Rocket Hatches")
+Item("e", "Anywhere")
+Item("f", "Other")
+Item("g", "Unknown", true)
}
text("q", "If other, please specify")
selector("r", "Where do they place Cargo during Teleop?") {
+Item("a", "Nowhere")
+Item("b", "Cargo Ship only")
+Item("c", "Cargo Ship and low Rocket Hatches")
+Item("d", "Cargo Ship and low/middle Rocket Hatches")
+Item("e", "Anywhere")
+Item("f", "Other")
+Item("g", "Unknown", true)
}
text("s", "If other, please specify")
selector("t", "Where does their robot end the game?") {
+Item("a", "Off the HAB Platform")
+Item("b", "Only HAB Level 1")
+Item("c", "Only HAB Level 2")
+Item("d", "Only HAB Level 3")
+Item("e", "HAB Level 1 or 2")
+Item("f", "HAB Level 1 or 3")
+Item("g", "Any HAB Level")
+Item("h", "Unknown", true)
}
checkbox("u", "Can they help another robot climb?")
header("v", "Other")
counter("w", "Subjective quality assessment (?/5)") {
unit = "⭐"
}
text("x", "What is something special you want us to know about your robot?")
text("y", "Other comments")
}
fun updateDefaultTemplates(): Promise<*>? {
return GlobalScope.async {
val match = async { defaultTemplates.updateMatchTemplate() }
val pit = async { defaultTemplates.updatePitTemplate() }
val empty = async { defaultTemplates.updateEmptyTemplate() }
awaitAll(match, pit, empty)
}.asPromise()
}
private suspend fun CollectionReference.updateMatchTemplate() {
doc("0").set(json(
FIRESTORE_TEMPLATE_ID to "0",
FIRESTORE_NAME to "Match Scout",
FIRESTORE_TIMESTAMP to FieldValues.serverTimestamp(),
FIRESTORE_METRICS to matchTemplateMetrics()
).log("Match")).await()
}
private suspend fun CollectionReference.updatePitTemplate() {
doc("1").set(json(
FIRESTORE_TEMPLATE_ID to "1",
FIRESTORE_NAME to "Pit Scout",
FIRESTORE_TIMESTAMP to FieldValues.serverTimestamp(),
FIRESTORE_METRICS to pitTemplateMetrics()
).log("Pit")).await()
}
private suspend fun CollectionReference.updateEmptyTemplate() {
doc("2").set(json(
FIRESTORE_TEMPLATE_ID to "2",
FIRESTORE_NAME to "Blank Scout",
FIRESTORE_TIMESTAMP to FieldValues.serverTimestamp()
).log("Blank")).await()
}
private fun Json.log(name: String) = apply { console.log("$name: ${JSON.stringify(this)}") }
| gpl-3.0 | 9256c6881bacc8abacd5806f110a1096 | 37.175926 | 100 | 0.631336 | 3.760146 | false | false | false | false |
googleapis/gax-kotlin | kgax-grpc/src/main/kotlin/com/google/longrunning/OperationsClientStub.kt | 1 | 5274 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.longrunning
import com.google.common.util.concurrent.ListenableFuture
import com.google.protobuf.Empty
import io.grpc.CallOptions
import io.grpc.Channel
import io.grpc.MethodDescriptor
import io.grpc.MethodDescriptor.generateFullMethodName
import io.grpc.protobuf.ProtoUtils
import io.grpc.stub.AbstractStub
import io.grpc.stub.ClientCalls.futureUnaryCall
import javax.annotation.Generated
/**
* A low level interface for interacting with Google Long Running Operations.
*
* Prefer to use the [com.google.api.kgax.grpc.GrpcClientStub.executeLongRunning] extension.
*/
@Generated("com.google.api.kotlin.generator.GRPCGenerator")
class OperationsClientStub(channel: Channel, callOptions: CallOptions = CallOptions.DEFAULT) :
AbstractStub<OperationsClientStub>(channel, callOptions) {
private val listOperationsDescriptor: MethodDescriptor<ListOperationsRequest, ListOperationsResponse> by lazy {
MethodDescriptor.newBuilder<ListOperationsRequest, ListOperationsResponse>()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName("google.longrunning.Operations", "ListOperations"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
ProtoUtils.marshaller(
ListOperationsRequest.getDefaultInstance()
)
)
.setResponseMarshaller(
ProtoUtils.marshaller(
ListOperationsResponse.getDefaultInstance()
)
)
.build()
}
private val getOperationDescriptor: MethodDescriptor<GetOperationRequest, Operation> by lazy {
MethodDescriptor.newBuilder<GetOperationRequest, Operation>()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName("google.longrunning.Operations", "GetOperation"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
ProtoUtils.marshaller(
GetOperationRequest.getDefaultInstance()
)
)
.setResponseMarshaller(
ProtoUtils.marshaller(
Operation.getDefaultInstance()
)
)
.build()
}
private val deleteOperationDescriptor: MethodDescriptor<DeleteOperationRequest, Empty> by lazy {
MethodDescriptor.newBuilder<DeleteOperationRequest, Empty>()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName("google.longrunning.Operations", "DeleteOperation"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
ProtoUtils.marshaller(
DeleteOperationRequest.getDefaultInstance()
)
)
.setResponseMarshaller(
ProtoUtils.marshaller(
Empty.getDefaultInstance()
)
)
.build()
}
private val cancelOperationDescriptor: MethodDescriptor<CancelOperationRequest, Empty> by lazy {
MethodDescriptor.newBuilder<CancelOperationRequest, Empty>()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName("google.longrunning.Operations", "CancelOperation"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
ProtoUtils.marshaller(
CancelOperationRequest.getDefaultInstance()
)
)
.setResponseMarshaller(
ProtoUtils.marshaller(
Empty.getDefaultInstance()
)
)
.build()
}
override fun build(channel: Channel, callOptions: CallOptions): OperationsClientStub =
OperationsClientStub(channel, callOptions)
fun listOperations(request: ListOperationsRequest): ListenableFuture<ListOperationsResponse> = futureUnaryCall(
channel.newCall(listOperationsDescriptor, callOptions),
request
)
fun getOperation(request: GetOperationRequest): ListenableFuture<Operation> = futureUnaryCall(
channel.newCall(getOperationDescriptor, callOptions),
request
)
fun deleteOperation(request: DeleteOperationRequest): ListenableFuture<Empty> = futureUnaryCall(
channel.newCall(deleteOperationDescriptor, callOptions),
request
)
fun cancelOperation(request: CancelOperationRequest): ListenableFuture<Empty> = futureUnaryCall(
channel.newCall(cancelOperationDescriptor, callOptions),
request
)
}
| apache-2.0 | 8d5499630d11eef01bb804a052be7480 | 39.259542 | 115 | 0.675958 | 5.616613 | false | false | false | false |
Maxr1998/home-assistant-Android | app/src/phoneStandard/java/io/homeassistant/android/wearable/WearableCredentialsSync.kt | 1 | 1588 | package io.homeassistant.android.wearable
import android.content.Context
import android.util.Log
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.wearable.PutDataMapRequest
import com.google.android.gms.wearable.Wearable
import io.homeassistant.android.Common
import io.homeassistant.android.Utils
object WearableCredentialsSync {
private val PREF_DATA_MAP_HASH = "data_map_hash"
@JvmStatic fun transferCredentials(c: Context) {
val oldHash = Utils.getPrefs(c).getInt(PREF_DATA_MAP_HASH, -1)
var newHash = 0
val putDataMapReq = PutDataMapRequest.create("/credentials").apply {
dataMap.apply {
putString(Common.PREF_HASS_URL_KEY, Utils.getUrl(c))
putString(Common.PREF_HASS_PASSWORD_KEY, Utils.getPassword(c))
putString(Common.PREF_BASIC_AUTH_KEY, Utils.getBasicAuth(c))
newHash = hashCode()
}
}
if (newHash != oldHash) {
val apiClient = GoogleApiClient.Builder(c)
.addApi(Wearable.API)
.build().apply { connect() }
val result = Wearable.DataApi.putDataItem(apiClient, putDataMapReq.asPutDataRequest())
result.setResultCallback {
dataItemResult ->
if (dataItemResult.status.isSuccess) {
Log.d(javaClass.simpleName, "Successfully synced Credentials!")
}
}
Utils.getPrefs(c).edit().putInt(PREF_DATA_MAP_HASH, newHash).apply()
}
}
} | gpl-3.0 | 24b8c46715e67e3462213a0f34da3f97 | 36.833333 | 98 | 0.632242 | 4.291892 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/flex/psi/FlexmarkFrontMatterBlockImpl.kt | 1 | 5243 | // Copyright (c) 2017-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.flex.psi
import com.intellij.lang.ASTNode
import com.intellij.navigation.ItemPresentation
import com.intellij.openapi.util.TextRange
import com.intellij.psi.ElementManipulators
import com.intellij.psi.LiteralTextEscaper
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiLanguageInjectionHost
import com.intellij.psi.stubs.IStubElementType
import com.intellij.psi.tree.IElementType
import com.vladsch.md.nav.flex.psi.util.FlexTextMapElementTypeProvider
import com.vladsch.md.nav.parser.MdFactoryContext
import com.vladsch.md.nav.psi.element.MdPlainTextStubElementType
import com.vladsch.md.nav.psi.element.MdStubPlainTextImpl
import com.vladsch.md.nav.psi.util.MdPsiImplUtil
import com.vladsch.md.nav.psi.util.MdTypes
import com.vladsch.md.nav.psi.util.TextMapElementType
import icons.MdIcons
import javax.swing.Icon
class FlexmarkFrontMatterBlockImpl(stub: FlexmarkFrontMatterBlockStub?, nodeType: IStubElementType<FlexmarkFrontMatterBlockStub, FlexmarkFrontMatterBlock>?, node: ASTNode?) :
MdStubPlainTextImpl<FlexmarkFrontMatterBlockStub>(stub, nodeType, node),
FlexmarkFrontMatterBlock {
constructor(stub: FlexmarkFrontMatterBlockStub, nodeType: IStubElementType<FlexmarkFrontMatterBlockStub, FlexmarkFrontMatterBlock>) : this(stub, nodeType, null)
constructor(node: ASTNode) : this(null, null, node)
override fun getTextMapType(): TextMapElementType {
return FlexTextMapElementTypeProvider.FLEXMARK_FRONT_MATTER
}
val referenceableTextType: IElementType = MdTypes.FLEXMARK_FRONT_MATTER_BLOCK
override fun getReferenceableOffsetInParent(): Int {
return MdPlainTextStubElementType.getReferenceableOffsetInParent(node, referenceableTextType)
}
override fun getReferenceableText(): String {
return content
}
override fun replaceReferenceableText(text: String, startOffset: Int, endOffset: Int): PsiElement {
val content = content
val sb = StringBuilder(content.length - (endOffset - startOffset) + text.length)
sb.append(content, 0, startOffset).append(text).append(content, endOffset, content.length)
return setContent(sb.toString())
}
val contentNode: ASTNode?
get() = node.findChildByType(referenceableTextType)
override fun getContent(): String {
val content = contentNode
return content?.text ?: ""
}
override fun setContent(blockText: String?): PsiElement {
return MdPsiImplUtil.setContent(this, blockText)
}
override fun getContentRange(): TextRange {
val startMarker = node.findChildByType(MdTypes.FLEXMARK_FRONT_MATTER_OPEN)
val content = node.findChildByType(referenceableTextType)
if (startMarker != null && content != null) {
return TextRange(startMarker.textLength + 1, startMarker.textLength + 1 + content.textLength)
}
return TextRange(0, 0)
}
override fun getPresentation(): ItemPresentation {
return object : ItemPresentation {
override fun getPresentableText(): String? {
if (!isValid) return null
return "Flexmark front matter block"
}
override fun getLocationString(): String? {
if (!isValid) return null
// create a shortened version that is still good to look at
return MdPsiImplUtil.truncateStringForDisplay(text, 50, false, true, true)
}
override fun getIcon(unused: Boolean): Icon? {
return MdIcons.getDocumentIcon()
}
}
}
override fun isValidHost(): Boolean {
return isValid
}
override fun updateText(text: String): PsiLanguageInjectionHost {
return ElementManipulators.handleContentChange(this, text)
}
override fun createLiteralTextEscaper(): LiteralTextEscaper<out PsiLanguageInjectionHost> {
return object : LiteralTextEscaper<PsiLanguageInjectionHost>(this) {
override fun decode(rangeInsideHost: TextRange, outChars: StringBuilder): Boolean {
outChars.append(rangeInsideHost.substring(myHost.text))
return true
}
override fun getOffsetInHost(offsetInDecoded: Int, rangeInsideHost: TextRange): Int {
return rangeInsideHost.startOffset + offsetInDecoded
}
override fun getRelevantTextRange(): TextRange {
return contentRange
}
override fun isOneLine(): Boolean {
return false
}
}
}
companion object {
@Suppress("UNUSED_PARAMETER")
@JvmStatic
fun getElementText(factoryContext: MdFactoryContext, content: String?): String {
val useContent = content ?: ""
if (useContent.isEmpty() || useContent[useContent.length - 1] != '\n') {
return "---\n$useContent\n...\n"
} else {
return "---\n$useContent...\n"
}
}
}
}
| apache-2.0 | 6141c416fb156599495fb6fc50756fb8 | 38.126866 | 177 | 0.688156 | 4.909176 | false | false | false | false |
NordicSemiconductor/Android-nRF-Toolbox | lib_ui/src/main/java/no/nordicsemi/android/ui/view/SectionTitle.kt | 1 | 4287 | /*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.ui.view
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun SectionTitle(
@DrawableRes resId: Int,
title: String,
menu: @Composable (() -> Unit)? = null,
modifier: Modifier = Modifier.fillMaxWidth()
) {
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start
) {
Image(
painter = painterResource(id = resId),
contentDescription = null,
colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.onSecondary),
modifier = Modifier
.background(
color = MaterialTheme.colorScheme.secondary,
shape = CircleShape
)
.padding(8.dp)
)
Spacer(modifier = Modifier.size(8.dp))
Text(
text = title,
textAlign = TextAlign.Start,
fontSize = 24.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier.weight(1f)
)
menu?.invoke()
}
}
@Composable
fun SectionTitle(
icon: ImageVector,
title: String,
modifier: Modifier = Modifier.fillMaxWidth()
) {
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start
) {
Icon(
imageVector = icon,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSecondary,
modifier = Modifier
.background(
color = MaterialTheme.colorScheme.secondary,
shape = CircleShape
)
.padding(8.dp)
)
Spacer(modifier = Modifier.size(8.dp))
Text(
text = title,
textAlign = TextAlign.Center,
fontSize = 24.sp,
fontWeight = FontWeight.Bold
)
}
}
| bsd-3-clause | 6d618d6f61cba762eb797fb996c41ceb | 35.330508 | 89 | 0.686028 | 4.871591 | false | false | false | false |
paronos/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/KitsuModels.kt | 2 | 2468 | package eu.kanade.tachiyomi.data.track.kitsu
import android.support.annotation.CallSuper
import com.github.salomonbrys.kotson.*
import com.google.gson.JsonObject
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.data.track.model.TrackSearch
open class KitsuManga(obj: JsonObject) {
val id by obj.byInt
val canonicalTitle by obj["attributes"].byString
val chapterCount = obj["attributes"].obj.get("chapterCount").nullInt
val type = obj["attributes"].obj.get("mangaType").nullString.orEmpty()
val original by obj["attributes"].obj["posterImage"].byString
val synopsis by obj["attributes"].byString
val startDate = obj["attributes"].obj.get("startDate").nullString.orEmpty()
open val status = obj["attributes"].obj.get("status").nullString.orEmpty()
@CallSuper
open fun toTrack() = TrackSearch.create(TrackManager.KITSU).apply {
remote_id = [email protected]
title = canonicalTitle
total_chapters = chapterCount ?: 0
cover_url = original
summary = synopsis
tracking_url = KitsuApi.mangaUrl(remote_id)
publishing_status = [email protected]
publishing_type = type
start_date = startDate.orEmpty()
}
}
class KitsuLibManga(obj: JsonObject, manga: JsonObject) : KitsuManga(manga) {
val remoteId by obj.byInt("id")
override val status by obj["attributes"].byString
val ratingTwenty = obj["attributes"].obj.get("ratingTwenty").nullString
val progress by obj["attributes"].byInt
override fun toTrack() = super.toTrack().apply {
remote_id = remoteId
status = toTrackStatus()
score = ratingTwenty?.let { it.toInt() / 2f } ?: 0f
last_chapter_read = progress
}
private fun toTrackStatus() = when (status) {
"current" -> Kitsu.READING
"completed" -> Kitsu.COMPLETED
"on_hold" -> Kitsu.ON_HOLD
"dropped" -> Kitsu.DROPPED
"planned" -> Kitsu.PLAN_TO_READ
else -> throw Exception("Unknown status")
}
}
fun Track.toKitsuStatus() = when (status) {
Kitsu.READING -> "current"
Kitsu.COMPLETED -> "completed"
Kitsu.ON_HOLD -> "on_hold"
Kitsu.DROPPED -> "dropped"
Kitsu.PLAN_TO_READ -> "planned"
else -> throw Exception("Unknown status")
}
fun Track.toKitsuScore(): String? {
return if (score > 0) (score * 2).toInt().toString() else null
}
| apache-2.0 | d71df39b90f7b6866e258c6dddc7049d | 34.768116 | 79 | 0.675041 | 3.739394 | false | false | false | false |
jtransc/jtransc | jtransc-rt-core-kotlin/src/com/jtransc/js/JsExt.kt | 1 | 15553 | @file:Suppress("NOTHING_TO_INLINE")
package com.jtransc.js
import com.jtransc.annotation.JTranscCallSiteBody
import com.jtransc.annotation.JTranscLiteralParam
import com.jtransc.annotation.JTranscMethodBody
import com.jtransc.annotation.JTranscUnboxParam
interface JsDynamic
class JsBoundedMethod(val obj: JsDynamic?, val methodName: String) {
operator fun invoke(vararg args: Any?): JsDynamic? = obj.call(methodName, *args)
}
val global: JsDynamic
//@JTranscMethodBody(target = "js", value = "return (typeof(window) != 'undefined') ? window : global;")
@JTranscCallSiteBody(target = "js", value = ["_global"])
get() = throw RuntimeException()
val window: JsDynamic
//@JTranscCallSiteBody(target = "js", value = "window")
@JTranscCallSiteBody(target = "js", value = ["window"])
get() = throw RuntimeException()
val console: JsDynamic get() = global["console"]!!
val document: JsDynamic get() = global["document"]!!
@JTranscCallSiteBody(target = "js", value = ["#0#.1"])
external operator fun JsDynamic?.get(@JTranscUnboxParam key: String): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["#0[#1]"])
external operator fun JsDynamic?.get(key: Int): JsDynamic?
fun JsDynamic?.getMethod(key: String): JsBoundedMethod = JsBoundedMethod(this, key)
fun JsDynamic?.method(key: String): JsBoundedMethod = JsBoundedMethod(this, key)
@JTranscCallSiteBody(target = "js", value = ["#0#.1 = #2;"])
external operator fun JsDynamic?.set(@JTranscUnboxParam key: String, @JTranscUnboxParam value: Any?): Unit
@JTranscCallSiteBody(target = "js", value = ["#0[#1] = #2;"])
external operator fun JsDynamic?.set(key: Int, @JTranscUnboxParam value: Any?): Unit
// invoke is unsafe, because it could be split in several statements and method name not bound to object
//@JTranscCallSiteBody(target = "js", value = "#0()")
//external operator fun JsDynamic?.invoke(): JsDynamic?
//
//@JTranscCallSiteBody(target = "js", value = "#0(#1)")
//external operator fun JsDynamic?.invoke(@JTranscUnboxParam p1: Any?): JsDynamic?
//
//@JTranscCallSiteBody(target = "js", value = "#0(#1, #2)")
//external operator fun JsDynamic?.invoke(@JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?): JsDynamic?
//
//@JTranscCallSiteBody(target = "js", value = "#0(#1, #2, #3)")
//external operator fun JsDynamic?.invoke(@JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?, @JTranscUnboxParam p3: Any?): JsDynamic?
//
//@JTranscCallSiteBody(target = "js", value = "#0(#1, #2, #3, #4)")
//external operator fun JsDynamic?.invoke(@JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?, @JTranscUnboxParam p3: Any?, @JTranscUnboxParam p4: Any?): JsDynamic?
//
//@JTranscCallSiteBody(target = "js", value = "#0(#1, #2, #3, #4, #5)")
//external operator fun JsDynamic?.invoke(@JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?, @JTranscUnboxParam p3: Any?, @JTranscUnboxParam p4: Any?, @JTranscUnboxParam p5: Any?): JsDynamic?
//
//@JTranscCallSiteBody(target = "js", value = "#0(#1, #2, #3, #4, #5, #6)")
//external operator fun JsDynamic?.invoke(@JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?, @JTranscUnboxParam p3: Any?, @JTranscUnboxParam p4: Any?, @JTranscUnboxParam p5: Any?, @JTranscUnboxParam p6: Any?): JsDynamic?
//
//@JTranscCallSiteBody(target = "js", value = "#0(#1, #2, #3, #4, #5, #6, #7)")
//external operator fun JsDynamic?.invoke(@JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?, @JTranscUnboxParam p3: Any?, @JTranscUnboxParam p4: Any?, @JTranscUnboxParam p5: Any?, @JTranscUnboxParam p6: Any?, @JTranscUnboxParam p7: Any?): JsDynamic?
//
//@JTranscCallSiteBody(target = "js", value = "#0(#1, #2, #3, #4, #5, #6, #7, #8)")
//external operator fun JsDynamic?.invoke(@JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?, @JTranscUnboxParam p3: Any?, @JTranscUnboxParam p4: Any?, @JTranscUnboxParam p5: Any?, @JTranscUnboxParam p6: Any?, @JTranscUnboxParam p7: Any?, @JTranscUnboxParam p8: Any?): JsDynamic?
//
//@JTranscCallSiteBody(target = "js", value = "#0(#1, #2, #3, #4, #5, #6, #7, #8, #9)")
//external operator fun JsDynamic?.invoke(@JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?, @JTranscUnboxParam p3: Any?, @JTranscUnboxParam p4: Any?, @JTranscUnboxParam p5: Any?, @JTranscUnboxParam p6: Any?, @JTranscUnboxParam p7: Any?, @JTranscUnboxParam p8: Any?, @JTranscUnboxParam p9: Any?): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["#0[#1]()"])
external fun JsDynamic?.call(@JTranscUnboxParam method: String): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["#0[#1](#2)"])
external fun JsDynamic?.call(@JTranscUnboxParam method: String, @JTranscUnboxParam p1: Any?): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["#0[#1](#2, #3)"])
external fun JsDynamic?.call(@JTranscUnboxParam method: String, @JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["#0[#1](#2, #3, #4)"])
external fun JsDynamic?.call(@JTranscUnboxParam method: String, @JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?, @JTranscUnboxParam p3: Any?): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["#0[#1](#2, #3, #4, #5)"])
external fun JsDynamic?.call(@JTranscUnboxParam method: String, @JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?, @JTranscUnboxParam p3: Any?, @JTranscUnboxParam p4: Any?): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["#0[#1](#2, #3, #4, #5, #6)"])
external fun JsDynamic?.call(@JTranscUnboxParam method: String, @JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?, @JTranscUnboxParam p3: Any?, @JTranscUnboxParam p4: Any?, @JTranscUnboxParam p5: Any?): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["#0[#1](#2, #3, #4, #5, #6, #7)"])
external fun JsDynamic?.call(@JTranscUnboxParam method: String, @JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?, @JTranscUnboxParam p3: Any?, @JTranscUnboxParam p4: Any?, @JTranscUnboxParam p5: Any?, @JTranscUnboxParam p6: Any?): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["#0[#1](#2, #3, #4, #5, #6, #7, #8)"])
external fun JsDynamic?.call(@JTranscUnboxParam method: String, @JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?, @JTranscUnboxParam p3: Any?, @JTranscUnboxParam p4: Any?, @JTranscUnboxParam p5: Any?, @JTranscUnboxParam p6: Any?, @JTranscUnboxParam p7: Any?): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["#0[#1](#2, #3, #4, #5, #6, #7, #8, #9)"])
external fun JsDynamic?.call(@JTranscUnboxParam method: String, @JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?, @JTranscUnboxParam p3: Any?, @JTranscUnboxParam p4: Any?, @JTranscUnboxParam p5: Any?, @JTranscUnboxParam p6: Any?, @JTranscUnboxParam p7: Any?, @JTranscUnboxParam p8: Any?): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["#0[#1](#2, #3, #4, #5, #6, #7, #8, #9, #10)"])
external fun JsDynamic?.call(@JTranscUnboxParam method: String, @JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?, @JTranscUnboxParam p3: Any?, @JTranscUnboxParam p4: Any?, @JTranscUnboxParam p5: Any?, @JTranscUnboxParam p6: Any?, @JTranscUnboxParam p7: Any?, @JTranscUnboxParam p8: Any?, @JTranscUnboxParam p9: Any?): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["new (#0)()"])
external fun JsDynamic?.new(): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["new (#0)(#1)"])
external fun JsDynamic?.new(@JTranscUnboxParam p1: Any?): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["new (#0)(#1, #2)"])
external fun JsDynamic?.new(@JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["new (#0)(#1, #2, #3)"])
external fun JsDynamic?.new(@JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?, @JTranscUnboxParam p3: Any?): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["new (#0)(#1, #2, #3, #4)"])
external fun JsDynamic?.new(@JTranscUnboxParam p1: Any?, @JTranscUnboxParam p2: Any?, @JTranscUnboxParam p3: Any?, @JTranscUnboxParam p4: Any?): JsDynamic?
@JTranscMethodBody(target = "js", value = ["""
var clazz = p0, rawArgs = p1;
var args = [null];
for (var n = 0; n < rawArgs.length; n++) args.push(N.unbox(rawArgs.data[n]));
return new (Function.prototype.bind.apply(clazz, args));
"""])
external fun JsDynamic?.new(vararg args: Any?): JsDynamic?
@JTranscMethodBody(target = "js", value = ["""
var obj = p0, methodName = N.istr(p1), rawArgs = p2;
var args = [];
for (var n = 0; n < rawArgs.length; n++) args.push(N.unbox(rawArgs.data[n]));
return obj[methodName].apply(obj, args)
"""])
external fun JsDynamic?.call(name: String, vararg args: Any?): JsDynamic?
inline fun jsNew(clazz: String): JsDynamic? = global[clazz].new()
inline fun jsNew(clazz: String, p1: Any?): JsDynamic? = global[clazz].new(p1)
inline fun jsNew(clazz: String, p1: Any?, p2: Any?): JsDynamic? = global[clazz].new(p1, p2)
inline fun jsNew(clazz: String, p1: Any?, p2: Any?, p3: Any?): JsDynamic? = global[clazz].new(p1, p2, p3)
inline fun jsNew(clazz: String, p1: Any?, p2: Any?, p3: Any?, p4: Any?): JsDynamic? = global[clazz].new(p1, p2, p3, p4)
inline fun jsNew(clazz: String, vararg args: Any?): JsDynamic? = global[clazz].new(*args)
@JTranscCallSiteBody(target = "js", value = ["typeof(#0)"])
external fun JsDynamic?.typeOf(): JsDynamic?
fun jsGlobal(key: String): JsDynamic? = window[key]
@JTranscCallSiteBody(target = "js", value = ["(#0)"])
external fun Any?.asJsDynamic(): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["(#0)"])
external fun <T : Any?> JsDynamic?.asJavaType(): T
@JTranscCallSiteBody(target = "js", value = ["N.unbox(#0)"])
external fun Any?.toJsDynamic(): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["N.box(#0)"])
external fun JsDynamic?.box(): Any?
@JTranscCallSiteBody(target = "js", value = ["N.str(#0)"])
external fun JsDynamic?.toJavaString(): String
@JTranscCallSiteBody(target = "js", value = ["N.str(#0)"])
external fun JsDynamic?.toJavaStringOrNull(): String?
fun <TR> jsFunction(v: Function0<TR>): JsDynamic? = v.toJsDynamic()
fun <T1, TR> jsFunction(v: Function1<T1, TR>): JsDynamic? = v.toJsDynamic()
fun <T1, T2, TR> jsFunction(v: Function2<T1, T2, TR>): JsDynamic? = v.toJsDynamic()
@JTranscMethodBody(target = "js", value = ["""
var handler = p0;
return function() {
return N.unbox(handler{% IMETHOD kotlin.jvm.functions.Function0:invoke %}());
};
"""])
external fun <TR> Function0<TR>.toJsDynamic(): JsDynamic?
@JTranscMethodBody(target = "js", value = ["""
var handler = p0;
return function(p1) {
return N.unbox(handler{% IMETHOD kotlin.jvm.functions.Function1:invoke %}(N.box(p1)));
};
"""])
external fun <T1, TR> Function1<T1, TR>.toJsDynamic(): JsDynamic?
@JTranscMethodBody(target = "js", value = ["""
var handler = p0;
return function(p1, p2) {
return N.unbox(handler{% IMETHOD kotlin.jvm.functions.Function2:invoke %}(N.box(p1), N.box(p2)));
};
"""])
external fun <T1, T2, TR> Function2<T1, T2, TR>.toJsDynamic(): JsDynamic?
@JTranscMethodBody(target = "js", value = ["""
return function() {return N.unbox(p0{% IMETHOD kotlin.jvm.functions.Function0:invoke %}());};
"""])
external fun <TR> jsFunctionRaw0(v: Function0<TR>): JsDynamic?
@JTranscMethodBody(target = "js", value = ["""
return function(p1) {return N.unbox(p0{% IMETHOD kotlin.jvm.functions.Function1:invoke %}(p1));};
"""])
external fun <TR> jsFunctionRaw1(v: Function1<JsDynamic?, TR>): JsDynamic?
@JTranscMethodBody(target = "js", value = ["""
return function(p1, p2) {return N.unbox(p0[% IMETHOD kotlin.jvm.functions.Function2:invoke %}(p1, p2));};
"""])
external fun <TR> jsFunctionRaw2(v: Function2<JsDynamic?, JsDynamic?, TR>): JsDynamic?
@JTranscMethodBody(target = "js", value = ["""
return function(p1, p2, p3) {return N.unbox(p0[% IMETHOD kotlin.jvm.functions.Function3:invoke %}(p1, p2, p3));};
"""])
external fun <TR> jsFunctionRaw3(v: Function3<JsDynamic?, JsDynamic?, JsDynamic?, TR>): JsDynamic?
@JTranscMethodBody(target = "js", value = ["""
return function(p1, p2, p3, p4) {return N.unbox(p0{% IMETHOD kotlin.jvm.functions.Function4:invoke %}(p1, p2, p3, p4));};
"""])
external fun <TR> jsFunctionRaw4(v: Function4<JsDynamic?, JsDynamic?, JsDynamic?, JsDynamic?, TR>): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["(!!(#0))"])
external fun JsDynamic?.toBool(): Boolean
@JTranscCallSiteBody(target = "js", value = ["((#0)|0)"])
external fun JsDynamic?.toInt(): Int
@JTranscCallSiteBody(target = "js", value = ["(+(#0))"])
external fun JsDynamic?.toDouble(): Double
@JTranscCallSiteBody(target = "js", value = ["((#0) == (#1))"])
external infix fun JsDynamic?.eq(that: JsDynamic?): Boolean
@JTranscCallSiteBody(target = "js", value = ["((#0) != (#1))"])
external infix fun JsDynamic?.ne(that: JsDynamic?): Boolean
@JTranscCallSiteBody(target = "js", value = ["N.istr(#0)"])
external fun String.toJavaScriptString(): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["debugger;"])
external fun jsDebugger(): Unit
class JsMethods(val obj: JsDynamic?) {
operator fun get(name: String) = JsBoundedMethod(obj, name)
}
val JsDynamic?.methods: JsMethods get() = JsMethods(this)
@JTranscMethodBody(target = "js", value = ["""
var out = [];
for (var n = 0; n < p0.length; n++) out.push(N.unbox(p0.data[n]));
return out;
"""])
external fun jsArray(vararg items: Any?): JsDynamic?
fun jsRegExp(regex: String): JsDynamic? = global["RegExp"].new(regex)
fun jsRegExp(regex: Regex): JsDynamic? = global["RegExp"].new(regex.pattern)
fun Regex.toJs() = jsRegExp(this)
data class JsAssetStat(val path: String, val size: Long)
@JTranscMethodBody(target = "js", value = ["""
var out = new JA_L({{ assetFiles|length }}, '[Lcom/jtransc/js/JsAssetStat;');
var n = 0;
{% for asset in assetFiles %}
out.data[n++] = {% CONSTRUCTOR com.jtransc.js.JsAssetStat %}(N.str({{ asset.path|quote }}), Int64.ofFloat({{ asset.size }}));
{% end %}
return out
"""])
external fun jsGetAssetStats(): Array<JsAssetStat>
@JTranscMethodBody(target = "js", value = ["""
var out = {};
for (var n = 0; n < p0.length; n++) {
var item = p0.data[n];
out[N.istr(item["{% FIELD kotlin.Pair:first %}"])] = N.unbox(item["{% FIELD kotlin.Pair:second %}"]);
}
return out
"""])
external fun jsObject(vararg items: Pair<String, Any?>): JsDynamic?
fun jsObject(map: Map<String, Any?>): JsDynamic? = jsObject(*map.map { it.key to it.value }.toTypedArray())
@JTranscCallSiteBody(target = "js", value = ["#0"])
external fun jsRaw(@JTranscLiteralParam str: String): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["require(#0)"])
external fun jsRequire(@JTranscUnboxParam name: String): JsDynamic?
@JTranscCallSiteBody(target = "js", value = ["((#0) instanceof (#1))"])
external fun JsDynamic?.jsInstanceOf(type: JsDynamic?): JsDynamic?
fun JsDynamic?.jsIsString(): Boolean = this.typeOf().toJavaString() == "string"
@JTranscMethodBody(target = "js", value = ["return JA_B.fromTypedArray(new Int8Array(p0));"])
external fun JsDynamic?.toByteArray(): ByteArray
@JTranscMethodBody(target = "js", value = ["return new Int8Array(p0.data.buffer, 0, p0.length);"])
external fun ByteArray.toJsTypedArray(): JsDynamic?
fun JsDynamic.arrayToList(): List<JsDynamic?> {
val array = this
return (0 until array["length"].toInt()).map { array[it] }
}
fun JsDynamic.getObjectKeys(): List<String> {
val keys = global["Object"].call("keys", this)
return (0 until keys["length"].toInt()).map { keys[it].toJavaStringOrNull() ?: "" }
}
fun JsDynamic.toObjectMap(): Map<String, JsDynamic?> = (getObjectKeys()).map { key -> key to this[key] }.toMap()
| apache-2.0 | cac13e7fa0768e9adeb93149daefdba8 | 48.690096 | 336 | 0.693693 | 3.046621 | false | false | false | false |
square/duktape-android | zipline-kotlin-plugin/src/main/kotlin/app/cash/zipline/kotlin/ZiplineIrGenerationExtension.kt | 1 | 3593 | /*
* Copyright (C) 2021 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 app.cash.zipline.kotlin
import org.jetbrains.kotlin.backend.common.IrElementTransformerVoidWithContext
import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.expressions.IrCall
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.ir.types.classFqName
import org.jetbrains.kotlin.ir.util.isInterface
class ZiplineIrGenerationExtension(
private val messageCollector: MessageCollector,
) : IrGenerationExtension {
override fun generate(moduleFragment: IrModuleFragment, pluginContext: IrPluginContext) {
val ziplineApis = ZiplineApis(pluginContext)
val transformer = object : IrElementTransformerVoidWithContext() {
override fun visitClassNew(declaration: IrClass): IrStatement {
val declaration = super.visitClassNew(declaration) as IrClass
try {
if (declaration.isInterface &&
declaration.superTypes.any { it.classFqName == ziplineApis.ziplineServiceFqName }
) {
AdapterGenerator(
pluginContext,
ziplineApis,
currentScope!!,
declaration
).generateAdapterIfAbsent()
}
} catch (e: ZiplineCompilationException) {
messageCollector.report(e.severity, e.message, currentFile.locationOf(e.element))
}
return declaration
}
override fun visitCall(expression: IrCall): IrExpression {
val expression = super.visitCall(expression) as IrCall
try {
val takeOrBindFunction = ziplineApis.ziplineServiceAdapterFunctions[expression.symbol]
if (takeOrBindFunction != null) {
return AddAdapterArgumentRewriter(
pluginContext,
ziplineApis,
currentScope!!,
currentDeclarationParent!!,
expression,
takeOrBindFunction,
).rewrite()
}
} catch (e: ZiplineCompilationException) {
messageCollector.report(e.severity, e.message, currentFile.locationOf(e.element))
}
try {
if (expression.symbol == ziplineApis.ziplineServiceSerializerTwoArg) {
return CallAdapterConstructorRewriter(
pluginContext,
ziplineApis,
currentScope!!,
currentDeclarationParent!!,
expression,
).rewrite()
}
} catch (e: ZiplineCompilationException) {
messageCollector.report(e.severity, e.message, currentFile.locationOf(e.element))
}
return expression
}
}
moduleFragment.transform(transformer, null)
}
}
| apache-2.0 | 191b3d5c7862485b9cfbabca6e71c6e4 | 36.041237 | 96 | 0.685221 | 5.067701 | false | false | false | false |
vilnius/tvarkau-vilniu | app/src/main/java/lt/vilnius/tvarkau/views/adapters/FilterReportTypesAdapter.kt | 1 | 1430 | package lt.vilnius.tvarkau.views.adapters
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.view_filter_report_type_row.view.*
import lt.vilnius.tvarkau.R
import lt.vilnius.tvarkau.extensions.invisible
import lt.vilnius.tvarkau.extensions.visibleIf
/**
* @author Martynas Jurkus
*/
class FilterReportTypesAdapter(
val items: List<String>,
var selected: String,
val onReportTypeClicked: (String) -> Unit
) : RecyclerView.Adapter<FilterReportTypesAdapter.TypeViewHolder>() {
override fun onBindViewHolder(vh: TypeViewHolder, position: Int) {
val item = items[position]
vh.itemView.filter_report_type.text = item
vh.itemView.setOnClickListener {
onReportTypeClicked(it.filter_report_type.text.toString())
}
vh.itemView.filter_report_type_selected.visibleIf(selected == item, { invisible() })
}
override fun getItemCount() = items.count()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TypeViewHolder {
return TypeViewHolder(
LayoutInflater
.from(parent.context)
.inflate(R.layout.view_filter_report_type_row, parent, false)
)
}
inner class TypeViewHolder(view: View) : RecyclerView.ViewHolder(view)
} | mit | 2547f0a24cfa606324dd3e0f248113a5 | 33.071429 | 92 | 0.699301 | 4.307229 | false | false | false | false |
cicada-kt/cicada-jdbc-kt | src/main/kotlin/cn/org/cicada/jdbc/kt/dao/JdbcDao.kt | 1 | 7649 | package cn.org.cicada.jdbc.kt.dao
import cn.org.cicada.jdbc.kt.api.Entity
import cn.org.cicada.jdbc.kt.query.QueryFactory
import cn.org.cicada.jdbc.kt.query.Stmt
import cn.org.cicada.jdbc.kt.query.toUnderline
import java.io.Serializable
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.jvm.javaField
open class JdbcDao private constructor(
val schemas : Map<String,Schema>,
val defaultSchema : Schema,
val queryFactory: QueryFactory,
val provider: DaoProvider) {
private constructor(builder: Builder) : this(
builder.schemas,
builder.defaultSchema ?: Schema(""),
builder.queryFactory!!,
builder.provider!!)
companion object {
fun build(f : Builder.()->Unit) : JdbcDao = Builder(f).build()
}
private val tables = mutableMapOf<KClass<*>,Table<*>>()
operator fun <T> invoke(f: JdbcDao.() -> T) : T {
(provider as? TransactionalDaoProvider).let {
try {
it?.beginTransaction()
val result = this.f()
it?.commitTransaction()
return result
} catch (ex : Exception) {
it?.rollbackTransaction()
throw ex
}
}
}
inline fun <reified T:Any> insert(entity: T) {
val stmt = queryFactory.buildInsertSql(this@JdbcDao, entity)
println(stmt.sql)
println(stmt.params)
provider.update(stmt.sql, *stmt.params.toTypedArray())
}
inline fun <reified T:Any> update(entity: T) {
val stmt = queryFactory.buildUpdateSql(this@JdbcDao, entity)
println(stmt.sql)
println(stmt.params)
provider.update(stmt.sql, *stmt.params.toTypedArray())
}
inline fun <reified T:Any> delete(entity: T) {
val stmt = queryFactory.buildDeleteSql(this@JdbcDao, entity)
println(stmt.sql)
println(stmt.params)
provider.update(stmt.sql, *stmt.params.toTypedArray())
}
inline fun <reified T:Any> delete(vararg ids : Serializable) {
val stmt = queryFactory.buildDeleteSql(this@JdbcDao, T::class, *ids)
println(stmt.sql)
println(stmt.params)
provider.update(stmt.sql, *stmt.params.toTypedArray())
}
inline fun <reified T:Any> list(noinline f: Stmt.Builder.()->Unit) : List<T> {
val stmt = Stmt.build(this, f)
println(stmt.sql)
println(stmt.params)
return provider.query(T::class.java, stmt.sql, stmt.params.toTypedArray())
}
inline fun <reified T:Any> uniqueResult(noinline f: Stmt.Builder.()->Unit) : T {
val stmt = Stmt.build(this, f)
println(stmt.sql)
println(stmt.params)
val list = provider.query(T::class.java, stmt.sql, stmt.params.toTypedArray())
when (list.size) {
1 -> return list.first()
0 -> throw EmptyResultException("Unique result not found")
else -> throw NotUniqueException("Unique result but found ${list.size} rows.")
}
}
inline fun <reified T:Any> firstResult(noinline f: Stmt.Builder.()->Unit) : T? {
val stmt = Stmt.build(this, f)
println(stmt.sql)
println(stmt.params)
val list = provider.query(T::class.java, stmt.sql, stmt.params.toTypedArray())
return if (list.isEmpty()) null else list.first()
}
class Builder(f : Builder.()->Unit) {
init {
this.f()
}
val schemas = mutableMapOf<String,Schema>()
var defaultSchema : Schema? = null
var queryFactory : QueryFactory? = null
var provider: DaoProvider? = null
fun bind(pkgName: String, schema: Schema, default: Boolean = false) {
schemas[pkgName] = schema
if (default) {
defaultSchema = schema
}
}
fun build() : JdbcDao = JdbcDao(this)
}
protected fun schemaOf(entityClass: KClass<*>) : Schema = schemaOf(entityClass.java.`package`.name)
protected fun schemaOf(pkgName: String) : Schema {
val schema = schemas[pkgName]
if (schema === null) {
val p = pkgName.lastIndexOf('.')
if (p < 0) return defaultSchema
return schemaOf(pkgName.substring(0, p))
}
return schema
}
private fun <E:Any> tableOf(entityClass: KClass<E>) : Table<E>? {
val entity = entityClass.java.getAnnotation(Entity::class.java)
if (entity === null) return null
val schema = schemaOf(entityClass)
val tablename = if (entity.name == "") {
schema.tableName(entityClass.simpleName!!)
} else {
entity.name
}
val columns = LinkedHashMap<KProperty1<E,*>,Column<E>>()
val table = Table(tablename, schema, columns)
entityClass.declaredMemberProperties.forEach {
val field = it.javaField
field ?: return@forEach
val col = field.getAnnotation(cn.org.cicada.jdbc.kt.api.Column::class.java)
col ?: return@forEach
val columnName = if (col.name == "") it.name.toUnderline(schema.lowercaseColumnName) else col.name
val id = field.getAnnotation(cn.org.cicada.jdbc.kt.api.Id::class.java)
columns[it] = Column(it, columnName, table,
col.length, col.precision, col.scale,
col.nullable, col.unique,
id !== null,
id !== null && id.autoincrement)
}
return table
}
inline fun <reified T:Any> table() : Table<T>? = table(T::class)
fun <E:Any> table(entityClass: KClass<E>) : Table<E>? {
synchronized(tables) {
val table = tables[entityClass]
@Suppress("UNCHECKED_CAST")
if (table !== null) return table as Table<E>
return tableOf(entityClass)
}
}
inline fun <reified E:Any> colomn(property: KProperty1<E,*>) : Column<E>? {
val field = property.javaField
field ?: return null
val table = table<E>()
table ?: return null
return table.columns[property]
}
data class Schema(val name: String,
val lowercaseTableName: Boolean = true,
val lowercaseColumnName: Boolean = true,
val tablePrefix: String = "",
val tableSuffix: String = "") {
fun tableName(entityClassName: String) : String {
val schemaPrefix = if (name == "") "" else "$name."
val simpleName = entityClassName.toUnderline(lowercaseTableName)
return "$schemaPrefix$tablePrefix$simpleName$tableSuffix"
}
}
data class Table<E>(val name: String,
val schema: Schema,
val columns : Map<KProperty1<E,*>,Column<E>>) {
override fun hashCode(): Int = name.hashCode() + schema.hashCode()
override fun equals(other: Any?): Boolean {
other ?: return false
other as? Table<*> ?: return false
return name == other.name && schema == other.schema
}
}
data class Column<E>(
val property: KProperty1<E,*>,
val name: String,
val table: Table<E>,
val length : Int = 0,
val precision : Int = 0,
val scale : Int = 0,
val nullable : Boolean = true,
val unique : Boolean = false,
val primaryKey: Boolean,
val autoincrement: Boolean)
}
| mit | 67664fb7c4e789b86651b5f8197976f2 | 35.080189 | 110 | 0.579553 | 4.258909 | false | false | false | false |
infinum/android_dbinspector | dbinspector/src/test/kotlin/com/infinum/dbinspector/ui/databases/DatabaseViewModelTest.kt | 1 | 10794 | package com.infinum.dbinspector.ui.databases
import android.content.Context
import app.cash.turbine.test
import com.infinum.dbinspector.domain.UseCases
import com.infinum.dbinspector.shared.BaseTest
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.awaitCancellation
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.koin.core.module.Module
import org.koin.dsl.module
import org.koin.test.get
@DisplayName("DatabaseViewModel tests")
internal class DatabaseViewModelTest : BaseTest() {
override fun modules(): List<Module> = listOf(
module {
factory { mockk<Context>() }
factory { mockk<UseCases.GetDatabases>() }
factory { mockk<UseCases.ImportDatabases>() }
factory { mockk<UseCases.RemoveDatabase>() }
factory { mockk<UseCases.CopyDatabase>() }
}
)
@Test
fun `Browse and collect all databases`() {
val useCase: UseCases.GetDatabases = get()
val viewModel = DatabaseViewModel(
useCase,
get(),
get()
)
coEvery { useCase.invoke(any()) } returns listOf(
mockk { every { name } returns "blog" },
mockk { every { name } returns "chinook" },
mockk { every { name } returns "northwind" }
)
viewModel.browse(get())
coVerify(exactly = 1) { useCase.invoke(any()) }
test {
viewModel.stateFlow.test {
val item: DatabaseState? = awaitItem()
assertTrue(item is DatabaseState.Databases)
assertTrue(item.databases.count() == 3)
assertTrue(item.databases[0].name == "blog")
assertTrue(item.databases[1].name == "chinook")
assertTrue(item.databases[2].name == "northwind")
awaitCancellation()
}
viewModel.eventFlow.test {
expectNoEvents()
}
viewModel.errorFlow.test {
expectNoEvents()
}
}
}
@Test
fun `Search database by name with result found`() {
val useCase: UseCases.GetDatabases = get()
val viewModel = DatabaseViewModel(
useCase,
get(),
get()
)
coEvery { useCase.invoke(any()) } returns listOf(
mockk { every { name } returns "blog" }
)
viewModel.browse(get(), "log")
coVerify(exactly = 1) { useCase.invoke(any()) }
test {
viewModel.stateFlow.test {
val item: DatabaseState? = awaitItem()
assertTrue(item is DatabaseState.Databases)
assertTrue(item.databases.count() == 1)
assertTrue(item.databases.first().name == "blog")
awaitCancellation()
}
viewModel.eventFlow.test {
expectNoEvents()
}
viewModel.errorFlow.test {
expectNoEvents()
}
}
}
@Test
fun `Search database by name without result found`() {
val useCase: UseCases.GetDatabases = get()
val viewModel = DatabaseViewModel(
useCase,
get(),
get()
)
coEvery { useCase.invoke(any()) } returns listOf()
viewModel.browse(get(), "south")
coVerify(exactly = 1) { useCase.invoke(any()) }
test {
viewModel.stateFlow.test {
val item: DatabaseState? = awaitItem()
assertTrue(item is DatabaseState.Databases)
assertTrue(item.databases.count() == 0)
assertTrue(item.databases.isEmpty())
awaitCancellation()
}
viewModel.eventFlow.test {
expectNoEvents()
}
viewModel.errorFlow.test {
expectNoEvents()
}
}
}
@Test
fun `Import empty list of databases`() {
val getUseCase: UseCases.GetDatabases = get()
val importUseCase: UseCases.ImportDatabases = get()
val viewModel = DatabaseViewModel(
getUseCase,
importUseCase,
get()
)
coEvery { getUseCase.invoke(any()) } returns listOf(
mockk { every { name } returns "blog" }
)
coEvery { importUseCase.invoke(any()) } returns listOf()
viewModel.import(get(), mockk())
coVerify(exactly = 1) { importUseCase.invoke(any()) }
coVerify(exactly = 1) { getUseCase.invoke(any()) }
test {
viewModel.stateFlow.test {
val item: DatabaseState? = awaitItem()
assertTrue(item is DatabaseState.Databases)
assertTrue(item.databases.count() == 1)
assertTrue(item.databases.first().name == "blog")
awaitCancellation()
}
viewModel.eventFlow.test {
expectNoEvents()
}
viewModel.errorFlow.test {
expectNoEvents()
}
}
}
@Test
fun `Import a single database`() {
val getUseCase: UseCases.GetDatabases = get()
val importUseCase: UseCases.ImportDatabases = get()
val viewModel = DatabaseViewModel(
getUseCase,
importUseCase,
get()
)
coEvery { getUseCase.invoke(any()) } returns listOf(
mockk { every { name } returns "blog" }
)
coEvery { importUseCase.invoke(any()) } returns listOf(
mockk { every { name } returns "blog" }
)
viewModel.import(get(), mockk())
coVerify(exactly = 1) { importUseCase.invoke(any()) }
coVerify(exactly = 1) { getUseCase.invoke(any()) }
test {
viewModel.stateFlow.test {
val item: DatabaseState? = awaitItem()
assertTrue(item is DatabaseState.Databases)
assertTrue(item.databases.count() == 1)
assertTrue(item.databases.first().name == "blog")
awaitCancellation()
}
viewModel.eventFlow.test {
expectNoEvents()
}
viewModel.errorFlow.test {
expectNoEvents()
}
}
}
@Test
fun `Import multiple databases`() {
val getUseCase: UseCases.GetDatabases = get()
val importUseCase: UseCases.ImportDatabases = get()
val viewModel = DatabaseViewModel(
getUseCase,
importUseCase,
get()
)
coEvery { getUseCase.invoke(any()) } returns listOf(
mockk { every { name } returns "blog" },
mockk { every { name } returns "chinook" },
mockk { every { name } returns "northwind" }
)
coEvery { importUseCase.invoke(any()) } returns listOf(
mockk { every { name } returns "chinook" },
mockk { every { name } returns "northwind" }
)
viewModel.import(get(), mockk())
coVerify(exactly = 1) { importUseCase.invoke(any()) }
coVerify(exactly = 1) { getUseCase.invoke(any()) }
test {
viewModel.stateFlow.test {
val item: DatabaseState? = awaitItem()
assertTrue(item is DatabaseState.Databases)
assertTrue(item.databases.count() == 3)
assertTrue(item.databases[0].name == "blog")
assertTrue(item.databases[1].name == "chinook")
assertTrue(item.databases[2].name == "northwind")
awaitCancellation()
}
viewModel.eventFlow.test {
expectNoEvents()
}
viewModel.errorFlow.test {
expectNoEvents()
}
}
}
// @Test
// fun `Remove database`() {
// val context: Context = get()
// val descriptor: DatabaseDescriptor = mockk()
// val useCase: UseCases.RemoveDatabase = get()
// val result: List<DatabaseDescriptor> = listOf()
// coEvery { useCase.invoke(any()) } returns result
//
// val viewModel: DatabaseViewModel = get()
//
// viewModel.remove(context, descriptor)
//
// coVerify(exactly = 1) { useCase.invoke(any()) }
// }
@Test
fun `Copy database successful`() {
val getUseCase: UseCases.GetDatabases = get()
val copyUseCase: UseCases.CopyDatabase = get()
val viewModel = DatabaseViewModel(
getUseCase,
get(),
copyUseCase
)
coEvery { getUseCase.invoke(any()) } returns listOf(
mockk { every { name } returns "blog" },
mockk { every { name } returns "blog_1" }
)
coEvery { copyUseCase.invoke(any()) } returns listOf(
mockk { every { name } returns "blog_1" }
)
viewModel.copy(get(), mockk())
coVerify(exactly = 1) { copyUseCase.invoke(any()) }
coVerify(exactly = 1) { getUseCase.invoke(any()) }
test {
viewModel.stateFlow.test {
val item: DatabaseState? = awaitItem()
assertTrue(item is DatabaseState.Databases)
assertTrue(item.databases.count() == 2)
assertTrue(item.databases[0].name == "blog")
assertTrue(item.databases[1].name == "blog_1")
awaitCancellation()
}
viewModel.eventFlow.test {
expectNoEvents()
}
viewModel.errorFlow.test {
expectNoEvents()
}
}
}
@Test
fun `Copy database failed`() {
val getUseCase: UseCases.GetDatabases = get()
val copyUseCase: UseCases.CopyDatabase = get()
val viewModel = DatabaseViewModel(
getUseCase,
get(),
copyUseCase
)
coEvery { copyUseCase.invoke(any()) } returns listOf()
viewModel.copy(get(), mockk())
coVerify(exactly = 1) { copyUseCase.invoke(any()) }
coVerify(exactly = 0) { getUseCase.invoke(any()) }
test {
viewModel.stateFlow.test {
assertNull(awaitItem())
}
viewModel.eventFlow.test {
expectNoEvents()
}
viewModel.errorFlow.test {
val item: Throwable? = awaitItem()
assertTrue(item is Throwable)
assertNull(item.message)
assertTrue(item.stackTrace.isNotEmpty())
}
}
}
}
| apache-2.0 | d8019bc668a64064f33d8b5001e0e601 | 30.934911 | 65 | 0.533908 | 4.862162 | false | true | false | false |
stardogventures/stardao | stardao-auto/src/main/java/io/stardog/stardao/auto/kotlin/DataPartialProcessor.kt | 1 | 5355 | package io.stardog.stardao.auto.kotlin
import com.google.auto.service.AutoService
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.*
import io.stardog.stardao.auto.annotations.DataPartial
import java.io.File
import javax.annotation.processing.*
import javax.lang.model.SourceVersion
import javax.lang.model.element.ElementKind
import javax.lang.model.element.TypeElement
import kotlin.reflect.jvm.internal.impl.name.FqName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import java.util.*
import kotlin.reflect.jvm.internal.impl.builtins.jvm.JavaToKotlinClassMap
@AutoService(Processor::class)
class DataPartialProcessor: AbstractProcessor() {
override fun getSupportedAnnotationTypes(): MutableSet<String> {
return mutableSetOf(DataPartial::class.java.name)
}
override fun getSupportedSourceVersion(): SourceVersion {
return SourceVersion.latest()
}
override fun process(annotations: MutableSet<out TypeElement>, env: RoundEnvironment): Boolean {
// processingEnv.messager.printMessage(Diagnostic.Kind.NOTE, "Starting processing...")
env.getElementsAnnotatedWith(DataPartial::class.java).forEach {
val className = it.simpleName.toString()
val partialClassName = "Partial$className"
val pack = processingEnv.elementUtils.getPackageOf(it).toString()
val file = generateClass(className, partialClassName, pack, it as TypeElement)
writeFile(partialClassName, file)
}
return true
}
fun generateClass(baseClassName: String, partialClassName: String, pack: String, type: TypeElement):FileSpec {
val classNameLc = baseClassName.toLowerCase()
val typeBuilder = TypeSpec.classBuilder(partialClassName)
.addModifiers(KModifier.DATA)
val primaryConBuilder = FunSpec.constructorBuilder()
val dataParams = StringJoiner(", ")
type.enclosedElements.forEach {
val propertyName = it.simpleName.toString()
val annotations = it.annotationMirrors
.map { m -> AnnotationSpec.get(m).toBuilder().useSiteTarget(AnnotationSpec.UseSiteTarget.FIELD).build() }
.filter { m -> !m.className.toString().endsWith(".NotNull") && !m.className.toString().endsWith(".Nullable") }
if (it.kind == ElementKind.FIELD && propertyName != "Companion") {
val propertyType = it.asType().asTypeName().javaToKotlinType(annotations).copy(nullable = true)
primaryConBuilder.addParameter(ParameterSpec.builder(propertyName, propertyType)
.defaultValue("null")
.addAnnotations(annotations)
.build())
typeBuilder.addProperty(PropertySpec.builder(propertyName, propertyType)
.initializer(propertyName)
.build())
dataParams.add("$propertyName = $classNameLc.$propertyName")
}
}
// copy all annotations from the base type other than @DataPartial itself and kotlin metadata
type.annotationMirrors.forEach {
if (it.annotationType.toString() != "io.stardog.stardao.auto.annotations.DataPartial"
&& it.annotationType.toString() != "kotlin.Metadata") {
typeBuilder.addAnnotation(AnnotationSpec.get(it))
}
}
typeBuilder.primaryConstructor(primaryConBuilder.build())
typeBuilder.addFunction(FunSpec.constructorBuilder()
.addParameter(ParameterSpec.builder(classNameLc, type.asType().asTypeName()).build())
.callThisConstructor(dataParams.toString())
.build())
val file = FileSpec.builder(pack, partialClassName)
.addType(typeBuilder.build())
.build()
return file
}
fun writeFile(className: String, file: FileSpec) {
val kaptKotlinGeneratedDir = processingEnv.options["kapt.kotlin.generated"]
file.writeTo(File(kaptKotlinGeneratedDir, "$className.kt"))
}
}
// asTypeName() currently returns java classes for certain classes such as String when we need the Kotlin
// version. As a workaround use the following adapted from https://github.com/square/kotlinpoet/issues/236#issuecomment-377784099
fun TypeName.javaToKotlinType(annotations: List<AnnotationSpec>): TypeName {
if (this is ParameterizedTypeName) {
val rawTypeClass = rawType.javaToKotlinType(annotations) as ClassName
val typedArgs = typeArguments.map { it.javaToKotlinType(emptyList()) }.toMutableList()
val hasNullableValues = annotations.filter { it.className.toString() == "io.stardog.stardao.auto.annotations.HasNullableValues" }.isNotEmpty()
if (hasNullableValues) {
typedArgs[typedArgs.size-1] = typedArgs[typedArgs.size-1].copy(nullable = true)
}
return rawTypeClass.parameterizedBy(*typedArgs.toTypedArray())
} else {
val className =
JavaToKotlinClassMap.INSTANCE.mapJavaToKotlin(FqName(toString()))
?.asSingleFqName()?.asString()
return if (className == null) {
this
} else {
ClassName.bestGuess(className)
}
}
}
| apache-2.0 | 69192dec8e1e5f97bad5334319e99956 | 46.8125 | 150 | 0.673763 | 5.032895 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anim/ViewAnimation.kt | 1 | 3084 | //noinspection MissingCopyrightHeader #8659
package com.ichi2.anim
import android.view.animation.AccelerateInterpolator
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.DecelerateInterpolator
import android.view.animation.TranslateAnimation
import com.ichi2.anim.ViewAnimation.Slide.*
object ViewAnimation {
enum class Slide {
SLIDE_IN_FROM_RIGHT,
SLIDE_OUT_TO_RIGHT,
SLIDE_IN_FROM_LEFT,
SLIDE_OUT_TO_LEFT,
SLIDE_IN_FROM_BOTTOM,
SLIDE_IN_FROM_TOP;
}
/**
* A TranslateAnimation, relative to self, with the given from/to x/y values.
*/
fun translateAnimation(fromXValue: Float, toXValue: Float, fromYValue: Float, toYValue: Float) =
TranslateAnimation(Animation.RELATIVE_TO_SELF, fromXValue, Animation.RELATIVE_TO_SELF, toXValue, Animation.RELATIVE_TO_SELF, fromYValue, Animation.RELATIVE_TO_SELF, toYValue)
fun slide(type: Slide, duration: Int, offset: Int): Animation {
val animation: Animation
when (type) {
SLIDE_IN_FROM_RIGHT -> {
animation = translateAnimation(
+1.0f, 0.0f, 0.0f, 0.0f
)
}
SLIDE_OUT_TO_RIGHT -> {
animation = translateAnimation(
0.0f, +1.0f, 0.0f, 0.0f
)
}
SLIDE_IN_FROM_LEFT -> {
animation = translateAnimation(
-1.0f, 0.0f, 0.0f, 0.0f
)
}
SLIDE_OUT_TO_LEFT -> {
animation = translateAnimation(
0.0f, -1.0f, 0.0f, 0.0f
)
}
SLIDE_IN_FROM_BOTTOM -> {
animation = translateAnimation(
0.0f, 0.0f, +1.0f, 0.0f
)
}
SLIDE_IN_FROM_TOP -> {
animation = translateAnimation(
0.0f, 0.0f, -1.0f, 0.0f
)
}
}
// can't factorize setInterpolator out due to some typing issue in API 21.
when (type) {
SLIDE_IN_FROM_BOTTOM,
SLIDE_IN_FROM_LEFT,
SLIDE_IN_FROM_RIGHT,
SLIDE_IN_FROM_TOP -> {
animation.setInterpolator(DecelerateInterpolator())
}
SLIDE_OUT_TO_LEFT, SLIDE_OUT_TO_RIGHT -> {
animation.setInterpolator(AccelerateInterpolator())
}
}
animation.duration = duration.toLong()
animation.startOffset = offset.toLong()
return animation
}
enum class Fade(val originalAlpha: Float) {
FADE_IN(0f),
FADE_OUT(1f);
}
fun fade(type: Fade, duration: Int, offset: Int) =
AlphaAnimation(type.originalAlpha, 1.0f - type.originalAlpha).apply {
this.duration = duration.toLong()
if (type == Fade.FADE_IN) {
zAdjustment = Animation.ZORDER_TOP
}
startOffset = offset.toLong()
}
}
| gpl-3.0 | 25162d81db3cc7567eadc8c04e4c6ab6 | 32.521739 | 182 | 0.543774 | 4 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/wildplot/android/rendering/XAxis.kt | 1 | 14129 | /****************************************************************************************
* Copyright (c) 2014 Michael Goldbach <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.wildplot.android.rendering
import com.wildplot.android.rendering.graphics.wrapper.GraphicsWrap
import com.wildplot.android.rendering.graphics.wrapper.RectangleWrap
import com.wildplot.android.rendering.interfaces.Drawable
import java.text.DecimalFormat
/**
* This Class represents a Drawable x-axis
*/
class XAxis
/**
* Constructor for an X-axis object
*
* @param plotSheet the sheet the axis will be drawn onto
* @param ticStart the start of the axis markers used for relative alignment of other markers
* @param tic the space between two markers
*/(
/**
* the PlotSheet object the x-axis is drawn onto
*/
private val plotSheet: PlotSheet,
/**
* the start of x-axis marker, used for relative alignment of further marks
*/
private val ticStart: Double,
/**
* the space between two marks
*/
private val tic: Double,
/**
* the space between two minor marks
*/
private val minorTic: Double
) : Drawable {
private var isIntegerNumbering = false
/**
* believe it or not, this axis can be placed higher or lower than y=0
*/
private var yOffset = 0.0
/**
* Name of axis
*/
private var name = "X"
private var mHasName = false
/**
* Format that is used to print numbers under markers
*/
private val df = DecimalFormat("##0.0#")
/**
* format for very big or small values
*/
private val dfScience = DecimalFormat("0.0##E0")
private val dfInteger = DecimalFormat("#.#")
/**
* is set to true if scientific format (e.g. 1E-3) should be used
*/
private var isScientific = false
/**
* the estimated size between two major tics in auto tic mode
*/
private var pixelDistance = 25f
/**
* start of drawn x-axis
*/
private var start = 0.0
/**
* end of drawn x-axis
*/
private var end = 100.0
/**
* true if the marker should be drawn into the direction above the axis
*/
private val markOnUpside = true
/**
* true if the marker should be drawn into the direction under the axis
*/
private var markOnDownside = true
/**
* length of a marker in pixel, length is only for one side
*/
private val markerLength = 5f
/**
* true if this axis is drawn onto the frame
*/
private var isOnFrame = false
private var mTickNameList: Array<String>? = null
private var mTickPositions: DoubleArray? = null
override fun paint(g: GraphicsWrap) {
val field = g.clipBounds
start = plotSheet.getxRange()[0]
end = plotSheet.getxRange()[1]
if (isOnFrame) {
yOffset = plotSheet.getyRange()[0]
}
pixelDistance = Math.abs(
plotSheet.xToGraphic(0.0, field) - plotSheet.xToGraphic(
tic, field
)
)
if (tic < 1e-2 || tic > 1e2) {
isScientific = true
}
val coordStart = plotSheet.toGraphicPoint(start, yOffset, field)
val coordEnd = plotSheet.toGraphicPoint(end, yOffset, field)
if (!isOnFrame) {
g.drawLine(coordStart[0], coordStart[1], coordEnd[0], coordEnd[1])
}
drawMarkers(g)
if (mTickPositions == null) {
drawMinorMarkers(g)
}
}
/**
* draw markers on the axis
*
* @param g graphic object used for drawing
*/
private fun drawMarkers(g: GraphicsWrap) {
val field = g.clipBounds
if (mTickPositions == null) {
drawImplicitMarker(g)
} else {
drawExplicitMarkers(g)
}
// arrow
val arrowheadPos = floatArrayOf(
plotSheet.xToGraphic(
Math.min(
plotSheet.getxRange()[1], end
),
field
),
plotSheet.yToGraphic(yOffset, field)
)
val fm = g.fontMetrics
val fontHeight = fm.height
val width = fm.stringWidth(name)
if (!isOnFrame) {
g.drawLine(
arrowheadPos[0] - 1,
arrowheadPos[1] - 1,
arrowheadPos[0] - 6,
arrowheadPos[1] - 3
)
g.drawLine(
arrowheadPos[0] - 1,
arrowheadPos[1] + 1,
arrowheadPos[0] - 6,
arrowheadPos[1] + 3
)
if (mHasName) {
g.drawString(name, arrowheadPos[0] - 14 - width, arrowheadPos[1] + 12)
}
} else {
val middlePosition =
floatArrayOf(plotSheet.xToGraphic(0.0, field), plotSheet.yToGraphic(yOffset, field))
if (mHasName) {
g.drawString(
name, field.width / 2 - width / 2,
Math.round(
middlePosition[1] + fontHeight * 2.5f
).toFloat()
)
}
}
}
private fun drawImplicitMarker(g: GraphicsWrap) {
val field = g.clipBounds
val tics = ((ticStart - start) / tic).toInt()
var currentX = ticStart - tic * tics
while (currentX <= end) {
if (!isOnFrame && plotSheet.xToGraphic(currentX, field) <= plotSheet.xToGraphic(
end,
field
) - 45 && plotSheet.xToGraphic(currentX, field) <= field.x + field.width - 45 ||
isOnFrame && currentX <= plotSheet.getxRange()[1] && currentX >= plotSheet.getxRange()[0]
) {
if (markOnDownside) {
drawDownwardsMarker(g, field, currentX)
}
if (markOnUpside) {
drawUpwardsMarker(g, field, currentX)
}
drawNumbering(g, field, currentX, -1)
}
currentX += tic
}
}
private fun drawExplicitMarkers(g: GraphicsWrap) {
val field = g.clipBounds
for (i in mTickPositions!!.indices) {
val currentX = mTickPositions!![i]
if (!isOnFrame && plotSheet.xToGraphic(currentX, field) <= plotSheet.xToGraphic(
end,
field
) - 45 && plotSheet.xToGraphic(currentX, field) <= field.x + field.width - 45 ||
isOnFrame && currentX <= plotSheet.getxRange()[1] && currentX >= plotSheet.getxRange()[0]
) {
if (markOnDownside) {
drawDownwardsMarker(g, field, currentX)
}
if (markOnUpside) {
drawUpwardsMarker(g, field, currentX)
}
drawNumbering(g, field, currentX, i)
}
}
}
/**
* draw number under a marker
*
* @param g graphic object used for drawing
* @param field bounds of plot
* @param x position of number
*/
private fun drawNumbering(g: GraphicsWrap, field: RectangleWrap, x: Double, index: Int) {
var position = x
if (tic < 1 && Math.abs(ticStart - position) < tic * tic) {
position = ticStart
}
val fm = g.fontMetrics
val fontHeight = fm.height
val coordStart = plotSheet.toGraphicPoint(position, yOffset, field)
if (Math.abs(position) - Math.abs(0) < 0.001 && !isOnFrame) {
coordStart[0] += 10f
coordStart[1] -= 10f
}
var text = if (mTickNameList == null) df.format(position) else mTickNameList!![index]
var width = fm.stringWidth(text)
if (isScientific || width > pixelDistance) {
text = if (mTickNameList == null) dfScience.format(position) else mTickNameList!![index]
width = fm.stringWidth(text)
g.drawString(
text,
coordStart[0] - width / 2,
Math.round(coordStart[1] + if (isOnFrame) Math.round(fontHeight * 1.5) else 20)
.toFloat()
)
} else if (isIntegerNumbering) {
text = if (mTickNameList == null) dfInteger.format(position) else mTickNameList!![index]
width = fm.stringWidth(text)
g.drawString(
text,
coordStart[0] - width / 2,
Math.round(coordStart[1] + if (isOnFrame) Math.round(fontHeight * 1.5) else 20)
.toFloat()
)
} else {
width = fm.stringWidth(text)
g.drawString(
text,
coordStart[0] - width / 2,
Math.round(coordStart[1] + if (isOnFrame) Math.round(fontHeight * 1.5) else 20)
.toFloat()
)
}
}
/**
* draws an upwards marker
*
* @param g graphic object used for drawing
* @param field bounds of plot
* @param x position of marker
*/
private fun drawUpwardsMarker(g: GraphicsWrap, field: RectangleWrap, x: Double) {
val coordStart = plotSheet.toGraphicPoint(x, yOffset, field)
val coordEnd = floatArrayOf(coordStart[0], coordStart[1] - markerLength)
g.drawLine(coordStart[0], coordStart[1], coordEnd[0], coordEnd[1])
}
/**
* draws an downwards marker
*
* @param g graphic object used for drawing
* @param field bounds of plot
* @param x position of marker
*/
private fun drawDownwardsMarker(g: GraphicsWrap, field: RectangleWrap, x: Double) {
val coordStart = plotSheet.toGraphicPoint(x, yOffset, field)
val coordEnd = floatArrayOf(coordStart[0], coordStart[1] + markerLength)
g.drawLine(coordStart[0], coordStart[1], coordEnd[0], coordEnd[1])
}
/**
* set the axis to draw on the border between outer frame and plot
*/
fun setOnFrame() {
isOnFrame = true
yOffset = plotSheet.getyRange()[0]
markOnDownside = false
}
override fun isOnFrame(): Boolean {
return isOnFrame
}
/**
* set name description of axis
*
* @param name of axis
*/
fun setName(name: String) {
this.name = name
mHasName = "" != name
}
/**
* draw minor markers on the axis
*
* @param g graphic object used for drawing
*/
private fun drawMinorMarkers(g: GraphicsWrap) {
val field = g.clipBounds
val tics = ((ticStart - start) / tic).toInt()
var currentX = ticStart - tic * tics
while (currentX <= end) {
if (!isOnFrame && plotSheet.xToGraphic(currentX, field) <= plotSheet.xToGraphic(
end,
field
) - 45 && plotSheet.xToGraphic(currentX, field) <= field.x + field.width - 45 ||
isOnFrame && currentX <= plotSheet.getxRange()[1] && currentX >= plotSheet.getxRange()[0]
) {
if (markOnDownside) {
drawDownwardsMinorMarker(g, field, currentX)
}
if (markOnUpside) {
drawUpwardsMinorMarker(g, field, currentX)
}
}
currentX += minorTic
}
}
/**
* draws an upwards minor marker
*
* @param g graphic object used for drawing
* @param field bounds of plot
* @param x position of marker
*/
private fun drawUpwardsMinorMarker(g: GraphicsWrap, field: RectangleWrap, x: Double) {
val coordStart = plotSheet.toGraphicPoint(x, yOffset, field)
val coordEnd =
floatArrayOf(coordStart[0], (coordStart[1] - 0.5 * markerLength).toInt().toFloat())
g.drawLine(coordStart[0], coordStart[1], coordEnd[0], coordEnd[1])
}
/**
* draws an downwards minor marker
*
* @param g graphic object used for drawing
* @param field bounds of plot
* @param x position of marker
*/
private fun drawDownwardsMinorMarker(g: GraphicsWrap, field: RectangleWrap, x: Double) {
val coordStart = plotSheet.toGraphicPoint(x, yOffset, field)
val coordEnd =
floatArrayOf(coordStart[0], (coordStart[1] + 0.5 * markerLength).toInt().toFloat())
g.drawLine(coordStart[0], coordStart[1], coordEnd[0], coordEnd[1])
}
fun setIntegerNumbering(isIntegerNumbering: Boolean) {
this.isIntegerNumbering = isIntegerNumbering
}
override fun isClusterable(): Boolean {
return true
}
override fun isCritical(): Boolean {
return true
}
fun setExplicitTicks(tickPositions: DoubleArray?, tickNameList: Array<String>?) {
mTickPositions = tickPositions
mTickNameList = tickNameList
}
}
| gpl-3.0 | ba5d99f5605c8d0cafb3c912cee70ce4 | 33.293689 | 105 | 0.534716 | 4.387888 | false | false | false | false |
shkschneider/android_Skeleton | core/src/main/kotlin/me/shkschneider/skeleton/ui/widget/AutoGridViewHeight.kt | 1 | 1008 | package me.shkschneider.skeleton.ui.widget
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.GridView
// <http://stackoverflow.com/a/8483078>
class AutoGridViewHeight : GridView {
var isExpanded = false
constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : super(context, attrs, defStyle)
public override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
if (isExpanded) {
// Calculate entire height by providing a very large height hint.
// View.MEASURED_SIZE_MASK represents the largest height possible.
val expandSpec = View.MeasureSpec.makeMeasureSpec(View.MEASURED_SIZE_MASK, View.MeasureSpec.AT_MOST)
super.onMeasure(widthMeasureSpec, expandSpec)
val params = layoutParams
params.height = measuredHeight
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
}
}
| apache-2.0 | b0b2296fa158206ce7d1ca6cecf962bd | 35 | 115 | 0.700397 | 4.60274 | false | false | false | false |
fossasia/open-event-android | app/src/main/java/org/fossasia/openevent/general/feedback/FeedbackViewModel.kt | 1 | 1919 | package org.fossasia.openevent.general.feedback
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.common.SingleLiveEvent
import org.fossasia.openevent.general.data.Resource
import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers
import timber.log.Timber
class FeedbackViewModel(
private val feedbackService: FeedbackService,
private val resource: Resource
) : ViewModel() {
private val compositeDisposable = CompositeDisposable()
private val mutableFeedback = MutableLiveData<List<Feedback>>()
val feedback: LiveData<List<Feedback>> = mutableFeedback
private val mutableMessage = SingleLiveEvent<String>()
val message: SingleLiveEvent<String> = mutableMessage
private val mutableProgress = MutableLiveData<Boolean>(false)
val progress: LiveData<Boolean> = mutableProgress
fun getAllFeedback(eventId: Long) {
if (eventId == -1L) {
mutableMessage.value = resource.getString(R.string.error_fetching_feedback_message)
return
}
compositeDisposable += feedbackService.getFeedbackUnderEventFromDb(eventId)
.withDefaultSchedulers()
.doOnSubscribe {
mutableProgress.value = true
}.doFinally {
mutableProgress.value = false
}.subscribe({
mutableFeedback.value = it
}, {
mutableMessage.value = resource.getString(R.string.error_fetching_feedback_message)
Timber.e(it, " Fail on fetching feedback for event ID: $eventId")
})
}
override fun onCleared() {
super.onCleared()
compositeDisposable.clear()
}
}
| apache-2.0 | 2d4b39d70e5ffe2d1c6c8f9bb3676784 | 37.38 | 99 | 0.70766 | 5.186486 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/sorter/CollectionDateSorter.kt | 1 | 775 | package com.boardgamegeek.sorter
import android.content.Context
import androidx.annotation.StringRes
import com.boardgamegeek.R
import com.boardgamegeek.entities.CollectionItemEntity
import java.text.SimpleDateFormat
import java.util.*
abstract class CollectionDateSorter(context: Context) : CollectionSorter(context) {
private val headerDateFormat = SimpleDateFormat("MMMM yyyy", Locale.getDefault())
@StringRes
protected open val defaultValueResId = R.string.text_unknown
override fun getHeaderText(item: CollectionItemEntity): String {
val time = getTimestamp(item)
return if (time == 0L) context.getString(defaultValueResId) else headerDateFormat.format(time)
}
override fun getDisplayInfo(item: CollectionItemEntity) = ""
}
| gpl-3.0 | e9ee9b5ecdf357d575083d9b99ebefc1 | 34.227273 | 102 | 0.780645 | 4.69697 | false | false | false | false |
android/android-studio-poet | aspoet/src/main/kotlin/com/google/androidstudiopoet/generators/android_modules/resources/StringResourcesGenerator.kt | 1 | 2153 | /*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.androidstudiopoet.generators.android_modules.resources
import com.google.androidstudiopoet.GenerationResult
import com.google.androidstudiopoet.Generator
import com.google.androidstudiopoet.models.ResourcesBlueprint
import com.google.androidstudiopoet.utils.fold
import com.google.androidstudiopoet.utils.joinPath
import com.google.androidstudiopoet.writers.FileWriter
class StringResourcesGenerator(private val fileWriter: FileWriter): Generator<ResourcesBlueprint, StringResourceGenerationResult> {
/**
* generates string resources by blueprint, returns list of string names to refer later.
* Precondition: resources package is generated
*/
override fun generate(blueprint: ResourcesBlueprint): StringResourceGenerationResult {
val valuesDirPath = blueprint.resDirPath.joinPath("values")
fileWriter.mkdir(valuesDirPath)
val stringsFileContent = getFileContent(blueprint.stringNames)
fileWriter.writeToFile(stringsFileContent, valuesDirPath.joinPath("strings.xml"))
return StringResourceGenerationResult(blueprint.stringNames)
}
private fun getFileContent(stringNames: List<String>): String {
val stringsFileContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><resources>" +
stringNames.map { "<string name=\"$it\">$it</string>\n" }.fold() +
"</resources>"
return stringsFileContent
}
}
// TODO remove the class below after refactoring the generators
data class StringResourceGenerationResult(val stringNames: List<String>): GenerationResult | apache-2.0 | 156b0a9e611b840f4878f5c844ecb898 | 41.235294 | 131 | 0.767766 | 4.904328 | false | false | false | false |
fabmax/binparse | src/main/kotlin/de/fabmax/binparse/Parser.kt | 1 | 4775 | package de.fabmax.binparse
import java.io.BufferedReader
import java.io.FileInputStream
import java.io.InputStreamReader
import java.util.*
import kotlin.text.Regex
/**
* Parses stuff.
*/
class Parser(source: String) {
val items: List<Item>
val structs = HashMap<String, StructDef>()
init {
items = parseBlock(source)
for (item in items) {
if (item.value == "struct") {
structs.put(item.identifier, StructDef(item))
}
}
//items.forEach { println(it.prettyPrint()) }
}
companion object {
fun fromFile(fileName: String): Parser {
val source = StringBuilder()
var reader: BufferedReader? = null
try {
reader = BufferedReader(InputStreamReader(FileInputStream(fileName)))
var line = reader.readLine()
while (line != null) {
if (!line.trim().startsWith('#')) {
source.append(line)
}
line = reader.readLine()
}
} finally {
reader?.close()
}
return Parser(source.toString())
}
}
private fun parseBlock(source: String): List<Item> {
val items = ArrayList<Item>();
var rest = source.trim()
while (!rest.isEmpty()) {
// discard surrounding braces
while (rest.startsWith('{') && rest.endsWith('}')) {
rest = rest.substring(1, rest.length - 1).trim();
}
var idx = getBlockEndIdx(rest)
val block = rest.substring(0, idx);
if (hasValidIdentifier(block)) {
val name = block.substring(0, block.indexOf(':')).trim()
val value = block.substring(block.indexOf(':') + 1, block.indexOfAny(";{".toCharArray())).trim()
val body = block.substring(block.indexOfAny(";{".toCharArray())).trim();
val item = Item(name, value);
if (body != ";") {
item.addChildren(parseBlock(body));
}
items.add(item)
} else {
println("invalid identifier: " + block)
}
rest = rest.substring(idx).trim();
}
return items;
}
private fun getBlockEndIdx(text: String): Int {
var idx = text.indexOfAny(";{".toCharArray());
if (idx > 0 && text[idx] == '{') {
// look for matchin '{'
var braceCnt = 1;
while (++idx < text.length) {
if (text[idx] == '{') {
braceCnt++;
} else if (text[idx] == '}' && --braceCnt == 0) {
break;
}
}
if (braceCnt > 0) {
throw IllegalStateException("Unexpected end of String, missing '}'")
}
}
if (idx < 0) {
idx = text.length;
} else {
idx++;
}
return idx;
}
private fun hasValidIdentifier(block: String): Boolean {
return block.matches(Regex("[A-Za-z0-9_]*\\s*:.*[;{].*"));
}
}
class Item(identifier: String, value: String, children : ArrayList<Item> = ArrayList<Item>())
: Iterable<Item> by children {
val identifier = identifier
val value = value
val children = children
val childrenMap = HashMap<String, Item>()
init {
for (item in children) {
if (childrenMap.containsKey(item.identifier)) {
throw IllegalArgumentException("Duplicate identifier: " + item.identifier)
}
childrenMap.put(item.identifier, item)
}
}
fun addChildren(items: List<Item>) {
for (it in items) {
addChild(it)
}
}
fun addChild(item: Item) {
if (childrenMap.containsKey(item.identifier)) {
throw IllegalArgumentException("Duplicate identifier: " + item.identifier)
}
childrenMap.put(item.identifier, item)
children.add(item)
}
fun prettyPrint(indent: Int = 0): String {
val builder = StringBuilder();
builder.append("$identifier: $value");
if (children.isEmpty()) {
builder.append(";\n")
} else {
builder.append(" {\n")
for (c in children) {
for (i in 1 .. indent + 2) {
builder.append(' ')
}
builder.append(c.prettyPrint(indent + 2))
}
for (i in 1 .. indent) {
builder.append(' ')
}
builder.append("}\n")
}
return builder.toString()
}
}
| apache-2.0 | 1d8cb0ab9b1b62a1479f3319b3c1b9cf | 27.939394 | 112 | 0.489424 | 4.622459 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.