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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
failex234/FastHub | app/src/main/java/com/fastaccess/ui/widgets/markdown/MarkdownEditText.kt | 1 | 3879 | package com.fastaccess.ui.widgets.markdown
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.ArrayAdapter
import android.widget.ListView
import com.fastaccess.ui.widgets.FontEditText
import java.util.*
/**
* Created by kosh on 14/08/2017.
*/
class MarkdownEditText : FontEditText {
var savedText: CharSequence? = ""
private var mention: ListView? = null
private var listDivider: View? = null
private var inMentionMode = -1
private var participants: ArrayList<String>? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
fun initListView(mention: ListView?, listDivider: View?, participants: ArrayList<String>?) {
this.mention = mention
this.listDivider = listDivider
this.participants = participants
this.participants?.let {
mention?.setOnItemClickListener { _, _, position, _ ->
try {
if (inMentionMode != -1) {
val complete = mention.adapter.getItem(position).toString() + " "
val end = selectionEnd
text.replace(inMentionMode, end, complete, 0, complete.length)
inMentionMode = -1
}
} catch (ignored: Exception) {
}
mention.visibility = GONE
listDivider?.visibility = GONE
}
}
}
override fun onTextChanged(text: CharSequence?, start: Int, lengthBefore: Int, lengthAfter: Int) {
super.onTextChanged(text, start, lengthBefore, lengthAfter)
if (isEnabled) {
savedText = text
text?.let {
mention(it)
}
}
}
fun mention(charSequence: CharSequence) {
try {
var lastChar: Char = 0.toChar()
if (charSequence.isNotEmpty()) lastChar = charSequence[charSequence.length - 1]
if (lastChar.toInt() != 0) {
if (lastChar == '@') {
inMentionMode = selectionEnd
mention?.visibility = GONE
listDivider?.visibility = GONE
return
} else if (lastChar == ' ')
inMentionMode = -1
else if (inMentionMode > -1)
updateMentionList(charSequence.toString().substring(inMentionMode, selectionEnd))
else {
val copy = text.toString().substring(0, selectionEnd)
val list = copy.split("\\s+".toRegex())
val last = list[list.size - 1]
if (last.startsWith("@")) {
inMentionMode = copy.lastIndexOf("@") + 1
updateMentionList(charSequence.toString().substring(inMentionMode, selectionEnd))
}
}
} else {
inMentionMode = -1
}
if (inMentionMode > -1) mention?.let {
it.visibility = if (inMentionMode > 0) View.VISIBLE else GONE
listDivider!!.visibility = it.visibility
}
} catch (ignored: Exception) {
}
}
private fun updateMentionList(mentioning: String) {
participants?.let {
val mentions = it.filter { it.toLowerCase().startsWith(mentioning.replace("@", "").toLowerCase()) }
val adapter = ArrayAdapter<String>(context, android.R.layout.simple_list_item_1,
android.R.id.text1, mentions.subList(0, Math.min(mentions.size, 3)))
mention?.setAdapter(adapter)
}
}
}
| gpl-3.0 | 261f1ba99cd6a8d576c42d719303716e | 37.405941 | 112 | 0.555556 | 4.922589 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/clipper/ClipperData.kt | 1 | 2906 | /*
* ClipperData.kt
*
* Copyright 2011 "an anonymous contributor"
* Copyright 2011-2014 Eric Butler <[email protected]>
* Copyright 2018 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.transit.clipper
import au.id.micolous.metrodroid.util.NumberUtils
import au.id.micolous.metrodroid.multi.FormattedString
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.transit.Station
import au.id.micolous.metrodroid.transit.Trip
import au.id.micolous.metrodroid.util.StationTableReader
internal object ClipperData {
const val AGENCY_CALTRAIN = 0x06
private const val AGENCY_GGT = 0x0b
const val AGENCY_SMART = 0x0c
const val AGENCY_MUNI = 0x12
const val AGENCY_GG_FERRY = 0x19
const val AGENCY_BAY_FERRY = 0x1b
const val CLIPPER_STR = "clipper"
fun getMode(agency: Int): Trip.Mode {
return StationTableReader.getOperatorDefaultMode(CLIPPER_STR, agency)
}
fun getAgencyName(agency: Int, isShort: Boolean) =
StationTableReader.getOperatorName(CLIPPER_STR, agency, isShort)
fun getRouteName(agency: Int, routeId: Int) =
StationTableReader.getLineNameNoFallback(CLIPPER_STR, agency shl 16 or routeId)
fun getStation(agency: Int, stationId: Int, isEnd: Boolean): Station? {
val humanReadableId = NumberUtils.intToHex(agency) + "/" + NumberUtils.intToHex(stationId)
val s = StationTableReader.getStationNoFallback(CLIPPER_STR, agency shl 16 or stationId,
humanReadableId)
if (s != null)
return s
if (agency == ClipperData.AGENCY_GGT
|| agency == ClipperData.AGENCY_CALTRAIN
|| agency == ClipperData.AGENCY_GG_FERRY
|| agency == ClipperData.AGENCY_SMART) {
if (stationId == 0xffff)
return Station.nameOnly(Localizer.localizeString(R.string.clipper_end_of_line))
if (agency != ClipperData.AGENCY_GG_FERRY)
return Station.nameOnly(Localizer.localizeString(R.string.clipper_zone_number, stationId.toString()))
}
// Placeholders
return if (stationId == (if (isEnd) 0xffff else 0)) null else Station.unknown(humanReadableId)
}
}
| gpl-3.0 | fbc14f734dbc383391be34598ae16d74 | 39.361111 | 117 | 0.706813 | 3.85923 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/challenge/preset/sideeffect/PresetChallengeSideEffectHandler.kt | 1 | 5097 | package io.ipoli.android.challenge.preset.sideeffect
import com.google.firebase.auth.FirebaseAuth
import io.ipoli.android.challenge.preset.PresetChallengeAction
import io.ipoli.android.challenge.preset.add.AddPresetChallengeAction
import io.ipoli.android.challenge.preset.category.list.ChallengeListForCategoryAction
import io.ipoli.android.challenge.preset.usecase.UnlockPresetChallengeUseCase
import io.ipoli.android.challenge.usecase.CreateChallengeFromPresetUseCase
import io.ipoli.android.challenge.usecase.CreatePresetChallengeUseCase
import io.ipoli.android.common.AppSideEffectHandler
import io.ipoli.android.common.AppState
import io.ipoli.android.common.DataLoadedAction
import io.ipoli.android.common.ErrorLogger
import io.ipoli.android.common.redux.Action
import org.threeten.bp.LocalDate
import space.traversal.kapsule.required
import timber.log.Timber
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 9/28/18.
*/
object PresetChallengeSideEffectHandler : AppSideEffectHandler() {
private val challengeRepository by required { challengeRepository }
private val presetChallengeRepository by required { presetChallengeRepository }
private val createChallengeFromPresetUseCase by required { createChallengeFromPresetUseCase }
private val unlockPresetChallengeUseCase by required { unlockPresetChallengeUseCase }
private val createPresetChallengeUseCase by required { createPresetChallengeUseCase }
override suspend fun doExecute(action: Action, state: AppState) {
when (action) {
is ChallengeListForCategoryAction.Load -> {
try {
dispatch(
DataLoadedAction.PresetChallengeListForCategoryChanged(
category = action.category,
challenges = presetChallengeRepository.findForCategory(action.category)
)
)
} catch (e: Throwable) {
Timber.e(e)
dispatch(ChallengeListForCategoryAction.ErrorLoadingChallenges)
}
}
is PresetChallengeAction.Accept -> {
if (challengeRepository.hasActivePresetChallenge(action.challenge.id)) {
dispatch(PresetChallengeAction.ChallengeAlreadyAccepted)
return
}
val c = createChallengeFromPresetUseCase.execute(
CreateChallengeFromPresetUseCase.Params(
preset = action.challenge,
schedule = action.schedule,
tags = action.tags,
startDate = LocalDate.now(),
questsStartTime = action.startTime,
playerPhysicalCharacteristics = action.physicalCharacteristics
)
)
presetChallengeRepository.join(action.challenge.id)
dispatch(PresetChallengeAction.Accepted(c.id))
}
is PresetChallengeAction.Unlock -> {
val result = unlockPresetChallengeUseCase.execute(
UnlockPresetChallengeUseCase.Params(action.challenge)
)
when (result) {
is UnlockPresetChallengeUseCase.Result.Unlocked -> {
dispatch(PresetChallengeAction.Unlocked)
}
UnlockPresetChallengeUseCase.Result.TooExpensive -> {
dispatch(
PresetChallengeAction.ChallengeTooExpensive
)
}
}
}
is AddPresetChallengeAction.Save -> {
try {
savePresetChallenge(action)
dispatch(AddPresetChallengeAction.Saved)
} catch (e: Throwable) {
ErrorLogger.log(e)
dispatch(AddPresetChallengeAction.SaveError)
}
}
}
}
private fun savePresetChallenge(action: AddPresetChallengeAction.Save) {
createPresetChallengeUseCase.execute(
CreatePresetChallengeUseCase.Params(
playerId = FirebaseAuth.getInstance().currentUser!!.uid,
name = action.name,
shortDescription = action.shortDescription,
description = action.description,
icon = action.icon,
color = action.color,
duration = action.duration,
category = action.category,
expectedResults = action.expectedResults,
requirements = action.requirements,
difficulty = action.difficulty,
quests = action.quests,
habits = action.habits
)
)
}
override fun canHandle(action: Action) =
action is ChallengeListForCategoryAction
|| action is PresetChallengeAction
|| action is AddPresetChallengeAction
} | gpl-3.0 | d95a240d7460108a5fff06da664fc8eb | 40.447154 | 99 | 0.610359 | 6.09689 | false | false | false | false |
Turbo87/intellij-emberjs | src/main/kotlin/com/emberjs/configuration/EmberConfigurationBase.kt | 1 | 2139 | package com.emberjs.configuration
import com.emberjs.configuration.utils.ElementUtils
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.RunConfigurationBase
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import org.jdom.Element
abstract class EmberConfigurationBase(project: Project, factory: ConfigurationFactory, name: String) :
RunConfigurationBase<Any>(project, factory, name),
EmberConfiguration {
override var module: Module? = null
override var nodeInterpreter: String? = null
override var env: Map<String, String>? = null
override fun writeExternal(element: Element) {
super.writeExternal(element)
element.let {
options.fields().forEach { optionsField -> optionsField.writeTo(element) }
}
val moduleName = module?.name
when (moduleName) {
is String -> ElementUtils.writeString(element, "module", moduleName, "NAME")
else -> ElementUtils.removeField(element, "module", "NAME")
}
when (nodeInterpreter) {
is String -> ElementUtils.writeString(element, "node-interpreter", nodeInterpreter!!)
else -> ElementUtils.removeField(element, "node-interpreter")
}
when (env) {
is Map -> ElementUtils.writeEnv(element, env!!)
else -> ElementUtils.removeEnv(element)
}
}
override fun readExternal(element: Element) {
super.readExternal(element)
element.let {
options.fields().forEach { optionsField -> optionsField.readFrom(element) }
}
ElementUtils.readString(element, "module", "NAME")?.let { moduleString ->
module = ModuleManager.getInstance(project).modules.find { it.name == moduleString }
}
ElementUtils.readString(element, "node-interpreter")?.let { elementNodeInterpreter ->
nodeInterpreter = elementNodeInterpreter
}
ElementUtils.readEnv(element)?.let { env = it }
}
} | apache-2.0 | 421b4cc39e43d420fae25b908a38d466 | 37.214286 | 102 | 0.675082 | 4.774554 | false | true | false | false |
square/picasso | picasso/src/main/java/com/squareup/picasso3/Utils.kt | 1 | 8467 | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.picasso3
import android.app.ActivityManager
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.content.pm.PackageManager.NameNotFoundException
import android.content.res.Resources
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.os.StatFs
import android.provider.Settings.Global
import android.util.Log
import androidx.core.content.ContextCompat
import okio.BufferedSource
import okio.ByteString
import okio.ByteString.Companion.encodeUtf8
import java.io.File
import java.io.FileNotFoundException
import kotlin.math.max
import kotlin.math.min
internal object Utils {
const val THREAD_PREFIX = "Picasso-"
const val THREAD_IDLE_NAME = THREAD_PREFIX + "Idle"
private const val PICASSO_CACHE = "picasso-cache"
private const val MIN_DISK_CACHE_SIZE = 5 * 1024 * 1024 // 5MB
private const val MAX_DISK_CACHE_SIZE = 50 * 1024 * 1024 // 50MB
const val THREAD_LEAK_CLEANING_MS = 1000
/** Thread confined to main thread for key creation. */
val MAIN_THREAD_KEY_BUILDER = StringBuilder()
/** Logging */
const val OWNER_MAIN = "Main"
const val OWNER_DISPATCHER = "Dispatcher"
const val OWNER_HUNTER = "Hunter"
const val VERB_CREATED = "created"
const val VERB_CHANGED = "changed"
const val VERB_IGNORED = "ignored"
const val VERB_ENQUEUED = "enqueued"
const val VERB_CANCELED = "canceled"
const val VERB_RETRYING = "retrying"
const val VERB_EXECUTING = "executing"
const val VERB_DECODED = "decoded"
const val VERB_TRANSFORMED = "transformed"
const val VERB_JOINED = "joined"
const val VERB_REMOVED = "removed"
const val VERB_DELIVERED = "delivered"
const val VERB_REPLAYING = "replaying"
const val VERB_COMPLETED = "completed"
const val VERB_ERRORED = "errored"
const val VERB_PAUSED = "paused"
const val VERB_RESUMED = "resumed"
/* WebP file header
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 'R' | 'I' | 'F' | 'F' |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| File Size |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 'W' | 'E' | 'B' | 'P' |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
private val WEBP_FILE_HEADER_RIFF: ByteString = "RIFF".encodeUtf8()
private val WEBP_FILE_HEADER_WEBP: ByteString = "WEBP".encodeUtf8()
fun <T> checkNotNull(value: T?, message: String?): T {
if (value == null) {
throw NullPointerException(message)
}
return value
}
fun checkNotMain() {
check(!isMain) { "Method call should not happen from the main thread." }
}
fun checkMain() {
check(isMain) { "Method call should happen from the main thread." }
}
private val isMain: Boolean
get() = Looper.getMainLooper().thread === Thread.currentThread()
fun getLogIdsForHunter(hunter: BitmapHunter, prefix: String = ""): String {
return buildString {
append(prefix)
val action = hunter.action
if (action != null) {
append(action.request.logId())
}
val actions = hunter.actions
if (actions != null) {
for (i in actions.indices) {
if (i > 0 || action != null) append(", ")
append(actions[i].request.logId())
}
}
}
}
fun log(owner: String, verb: String, logId: String, extras: String? = "") {
Log.d(TAG, String.format("%1$-11s %2$-12s %3\$s %4\$s", owner, verb, logId, extras ?: ""))
}
fun createDefaultCacheDir(context: Context): File {
val cache = File(context.applicationContext.cacheDir, PICASSO_CACHE)
if (!cache.exists()) {
cache.mkdirs()
}
return cache
}
fun calculateDiskCacheSize(dir: File): Long {
var size = MIN_DISK_CACHE_SIZE.toLong()
try {
val statFs = StatFs(dir.absolutePath)
val blockCount = statFs.blockCountLong
val blockSize = statFs.blockSizeLong
val available = blockCount * blockSize
// Target 2% of the total space.
size = available / 50
} catch (ignored: IllegalArgumentException) {
}
// Bound inside min/max size for disk cache.
return max(min(size, MAX_DISK_CACHE_SIZE.toLong()), MIN_DISK_CACHE_SIZE.toLong())
}
fun calculateMemoryCacheSize(context: Context): Int {
val am = ContextCompat.getSystemService(context, ActivityManager::class.java)
val largeHeap = context.applicationInfo.flags and ApplicationInfo.FLAG_LARGE_HEAP != 0
val memoryClass = if (largeHeap) am!!.largeMemoryClass else am!!.memoryClass
// Target ~15% of the available heap.
return (1024L * 1024L * memoryClass / 7).toInt()
}
fun isAirplaneModeOn(context: Context): Boolean {
return try {
val contentResolver = context.contentResolver
Global.getInt(contentResolver, Global.AIRPLANE_MODE_ON, 0) != 0
} catch (e: NullPointerException) {
// https://github.com/square/picasso/issues/761, some devices might crash here, assume that
// airplane mode is off.
false
} catch (e: SecurityException) {
// https://github.com/square/picasso/issues/1197
false
}
}
fun hasPermission(context: Context, permission: String): Boolean {
return context.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
}
fun isWebPFile(source: BufferedSource): Boolean {
return source.rangeEquals(0, WEBP_FILE_HEADER_RIFF) &&
source.rangeEquals(8, WEBP_FILE_HEADER_WEBP)
}
fun getResourceId(resources: Resources, data: Request): Int {
if (data.resourceId != 0 || data.uri == null) {
return data.resourceId
}
val pkg = data.uri.authority ?: throw FileNotFoundException("No package provided: " + data.uri)
val segments = data.uri.pathSegments
return when (segments?.size ?: 0) {
0 -> throw FileNotFoundException("No path segments: " + data.uri)
1 -> {
try {
segments[0].toInt()
} catch (e: NumberFormatException) {
throw FileNotFoundException("Last path segment is not a resource ID: " + data.uri)
}
}
2 -> {
val type = segments[0]
val name = segments[1]
resources.getIdentifier(name, type, pkg)
}
else -> throw FileNotFoundException("More than two path segments: " + data.uri)
}
}
fun getResources(
context: Context,
data: Request
): Resources {
if (data.resourceId != 0 || data.uri == null) {
return context.resources
}
return try {
val pkg =
data.uri.authority ?: throw FileNotFoundException("No package provided: " + data.uri)
context.packageManager.getResourcesForApplication(pkg)
} catch (e: NameNotFoundException) {
throw FileNotFoundException("Unable to obtain resources for package: " + data.uri)
}
}
/**
* Prior to Android 12, HandlerThread always keeps a stack local reference to the last message
* that was sent to it. This method makes sure that stack local reference never stays there
* for too long by sending new messages to it every second.
*
* https://github.com/square/leakcanary/blob/main/plumber-android-core/src/main/java/leakcanary/AndroidLeakFixes.kt#L153
*/
fun flushStackLocalLeaks(looper: Looper) {
val handler: Handler = object : Handler(looper) {
override fun handleMessage(msg: Message) {
sendMessageDelayed(obtainMessage(), THREAD_LEAK_CLEANING_MS.toLong())
}
}
handler.sendMessageDelayed(handler.obtainMessage(), THREAD_LEAK_CLEANING_MS.toLong())
}
}
| apache-2.0 | 11bc774a6c89e6471bc1b2ba0f77e741 | 34.426778 | 122 | 0.64155 | 4.080482 | false | false | false | false |
GunoH/intellij-community | platform/lang-api/src/com/intellij/psi/util/PartiallyKnownString.kt | 2 | 13455 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.util
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.TextRange
import com.intellij.psi.ContributedReferenceHost
import com.intellij.psi.ElementManipulators
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiLanguageInjectionHost
import com.intellij.refactoring.suggested.startOffset
import com.intellij.util.SmartList
import com.intellij.util.containers.headTailOrNull
import org.jetbrains.annotations.ApiStatus
/**
* Represents string which value is only partially known because of some variables concatenated with or interpolated into the string.
*
* For UAST languages it could be obtained from `UStringConcatenationsFacade.asPartiallyKnownString`.
*
* The common use case is a search for a place in partially known content to inject a reference.
*/
@ApiStatus.Experimental
class PartiallyKnownString(val segments: List<StringEntry>) {
val valueIfKnown: String?
get() {
(segments.singleOrNull() as? StringEntry.Known)?.let { return it.value }
val stringBuffer = StringBuffer()
for (segment in segments) {
when (segment) {
is StringEntry.Known -> stringBuffer.append(segment.value)
is StringEntry.Unknown -> return null
}
}
return stringBuffer.toString()
}
val concatenationOfKnown: String
get() {
(segments.singleOrNull() as? StringEntry.Known)?.let { return it.value }
val stringBuffer = StringBuffer()
for (segment in segments) {
if (segment is StringEntry.Known) stringBuffer.append(segment.value)
}
return stringBuffer.toString()
}
override fun toString(): String = segments.joinToString { segment ->
when (segment) {
is StringEntry.Known -> segment.value
is StringEntry.Unknown -> "<???>"
}
}
constructor(single: StringEntry) : this(listOf(single))
constructor(string: String, sourcePsi: PsiElement?, textRange: TextRange) : this(
StringEntry.Known(string, sourcePsi, textRange))
constructor(string: String) : this(string, null, TextRange.EMPTY_RANGE)
@JvmOverloads
fun findIndexOfInKnown(pattern: String, startFrom: Int = 0): Int {
var accumulated = 0
for (segment in segments) {
when (segment) {
is StringEntry.Known -> {
val i = segment.value.indexOf(pattern, startFrom - accumulated)
if (i >= 0) return accumulated + i
accumulated += segment.value.length
}
is StringEntry.Unknown -> {
}
}
}
return -1
}
private fun rangeForSubElement(parent: StringEntry, partRange: TextRange): TextRange =
parent.rangeAlignedToHost
?.let { (host, hostRange) ->
mapRangeToHostRange(host, hostRange, partRange)?.shiftLeft(parent.sourcePsi!!.startOffset - host.startOffset)
}
?: partRange.shiftRight(parent.range.startOffset)
private fun buildSegmentWithMappedRange(parent: StringEntry, value: String, rangeInPks: TextRange): StringEntry.Known =
StringEntry.Known(value, parent.sourcePsi, rangeForSubElement(parent, rangeInPks))
fun splitAtInKnown(splitAt: Int): Pair<PartiallyKnownString, PartiallyKnownString> {
var accumulated = 0
val left = SmartList<StringEntry>()
for ((i, segment) in segments.withIndex()) {
when (segment) {
is StringEntry.Known -> {
if (accumulated + segment.value.length < splitAt) {
accumulated += segment.value.length
left.add(segment)
}
else {
val leftPart = segment.value.substring(0, splitAt - accumulated)
val rightPart = segment.value.substring(splitAt - accumulated)
left.add(buildSegmentWithMappedRange(segment, leftPart, TextRange.from(0, leftPart.length)))
return PartiallyKnownString(left) to PartiallyKnownString(
ArrayList<StringEntry>(segments.lastIndex - i + 1).apply {
if (rightPart.isNotEmpty())
add(buildSegmentWithMappedRange(segment, rightPart, TextRange.from(leftPart.length, rightPart.length)))
addAll(segments.subList(i + 1, segments.size))
}
)
}
}
is StringEntry.Unknown -> {
left.add(segment)
}
}
}
return this to empty
}
fun split(pattern: String, escaperFactory: (CharSequence, String) -> SplitEscaper = { _, _ -> SplitEscaper.AcceptAll })
: List<PartiallyKnownString> {
tailrec fun collectPaths(result: MutableList<PartiallyKnownString>,
pending: MutableList<StringEntry>,
segments: List<StringEntry>): MutableList<PartiallyKnownString> {
val (head, tail) = segments.headTailOrNull() ?: return result.apply {
add(PartiallyKnownString(pending))
}
when (head) {
is StringEntry.Unknown -> return collectPaths(result, pending.apply { add(head) }, tail)
is StringEntry.Known -> {
val value = head.value
val stringParts = splitToTextRanges(value, pattern, escaperFactory).toList()
if (stringParts.size == 1) {
return collectPaths(result, pending.apply { add(head) }, tail)
}
else {
return collectPaths(
result.apply {
add(PartiallyKnownString(
pending.apply {
add(StringEntry.Known(stringParts.first().substring(value), head.sourcePsi,
rangeForSubElement(head, stringParts.first())))
}))
addAll(stringParts.subList(1, stringParts.size - 1).map {
PartiallyKnownString(it.substring(value), head.sourcePsi, rangeForSubElement(head, it))
})
},
mutableListOf(StringEntry.Known(stringParts.last().substring(value), head.sourcePsi,
rangeForSubElement(head, stringParts.last()))),
tail
)
}
}
}
}
return collectPaths(SmartList(), mutableListOf(), segments)
}
fun mapRangeToHostRange(host: PsiElement, rangeInPks: TextRange): TextRange? =
mapRangeToHostRange(host, ElementManipulators.getValueTextRange(host), rangeInPks)
/**
* @return the range in the given [host] (encoder-aware) that corresponds to the [rangeInPks] in the [valueIfKnown]
* @param rangeInHost - range in the [host] if the only the part of the [host] should be considered.
* useful if [host] corresponds to multiple [PartiallyKnownString]
*
* NOTE: currently supports only single-segment [rangeInPks]
*/
private fun mapRangeToHostRange(host: PsiElement, rangeInHost: TextRange, rangeInPks: TextRange): TextRange? {
fun getHostRangeEscapeAware(segmentRange: TextRange, inSegmentStart: Int, inSegmentEnd: Int): TextRange {
if (host is PsiLanguageInjectionHost) {
fun mkAttachments(): Array<Attachment> = arrayOf(
Attachment("host.txt", kotlin.runCatching { host.text ?: "<null>" }.getOrElse { it.stackTraceToString() }),
Attachment(kotlin.runCatching { host.containingFile?.virtualFile?.name }.getOrNull() ?: "file.txt",
kotlin.runCatching { host.containingFile?.text ?: "<null>" }.getOrElse { it.stackTraceToString() })
)
try {
val escaper = host.createLiteralTextEscaper()
val decode = escaper.decode(segmentRange, StringBuilder())
if (decode) {
val start = escaper.getOffsetInHost(inSegmentStart, segmentRange)
val end = escaper.getOffsetInHost(inSegmentEnd, segmentRange)
if (start != -1 && end != -1 && start <= end)
return TextRange(start, end)
else {
logger<PartiallyKnownString>().error(
"decoding of ${segmentRange} failed for $host : [$start, $end] inSegment = [$inSegmentStart, $inSegmentEnd]",
*mkAttachments()
)
return TextRange(segmentRange.startOffset + inSegmentStart, segmentRange.startOffset + inSegmentEnd)
}
}
}
catch (e: Exception) {
if (e is ControlFlowException) throw e
logger<PartiallyKnownString>().error(
"decoding of ${segmentRange} failed for $host inSegment = [$inSegmentStart, $inSegmentEnd]", e, *mkAttachments()
)
}
}
return TextRange(segmentRange.startOffset + inSegmentStart, segmentRange.startOffset + inSegmentEnd)
}
var accumulated = 0
for (segment in segments) {
if (segment !is StringEntry.Known) continue
val (segmentHost, segmentRangeInHost) = segment.rangeAlignedToHost ?: continue
if (segmentHost != host || !rangeInHost.contains(segmentRangeInHost)) continue // we don't support partial intersections
val segmentEnd = accumulated + segment.value.length
// assume that all content fits into one segment
if (rangeInPks.startOffset >= accumulated && rangeInPks.endOffset <= segmentEnd) {
val inSegmentStart = rangeInPks.startOffset - accumulated
val inSegmentEnd = rangeInPks.endOffset - accumulated
return getHostRangeEscapeAware(segmentRangeInHost, inSegmentStart, inSegmentEnd)
}
accumulated = segmentEnd
}
return null
}
/**
* @return the range in the [valueIfKnown] that corresponds to given [host]
*/
fun getRangeOfTheHostContent(host: PsiElement): TextRange? {
var accumulated = 0
var start = 0
var end = 0
var found = false
for (segment in segments) {
if (segment !is StringEntry.Known) continue
if (segment.host == host) {
if (!found) {
found = true
start = accumulated
}
end = accumulated + segment.value.length
}
accumulated += segment.value.length
}
if (found)
return TextRange.from(start, end)
else
return null
}
/**
* @return the cumulative range in the [originalHost] used by this [PartiallyKnownString]
*/
fun getRangeInHost(originalHost: PsiElement): TextRange? {
val ranges = segments.asSequence().mapNotNull { it.rangeAlignedToHost?.takeIf { it.first == originalHost } }.map { it.second }.toList()
if (ranges.isEmpty()) return null
return ranges.reduce(TextRange::union)
}
companion object {
val empty = PartiallyKnownString(emptyList())
}
}
@ApiStatus.Experimental
sealed class StringEntry {
abstract val sourcePsi: PsiElement? // maybe it should be PsiLanguageInjectionHost and only for `Known` values
/**
* A range in the [sourcePsi] that corresponds to the content of this segment
*/
abstract val range: TextRange
class Known(val value: String, override val sourcePsi: PsiElement?, override val range: TextRange) : StringEntry() {
override fun toString(): String = "StringEntry.Known('$value' at $range in $sourcePsi)"
}
class Unknown @JvmOverloads constructor(
override val sourcePsi: PsiElement?,
override val range: TextRange,
@ApiStatus.Internal
val possibleValues: Iterable<PartiallyKnownString>? = null
) : StringEntry() {
override fun toString(): String = "StringEntry.Unknown(at $range in $sourcePsi)"
}
val host: PsiElement?
get() = sourcePsi.takeIf { it.isSuitableHostClass() } ?: sourcePsi?.parent.takeIf { it.isSuitableHostClass() }
val rangeAlignedToHost: Pair<PsiElement, TextRange>?
get() {
val entry = this
val sourcePsi = entry.sourcePsi ?: return null
if (sourcePsi.isSuitableHostClass()) return sourcePsi to entry.range
val parent = sourcePsi.parent
if (parent is PsiLanguageInjectionHost) { // Kotlin interpolated string, TODO: encapsulate this logic to range retrieval
return parent to entry.range.shiftRight(sourcePsi.startOffsetInParent)
}
return null
}
private fun PsiElement?.isSuitableHostClass(): Boolean =
when (this) {
// this is primarily to workaround injections into YAMLKeyValue (which doesn't implement {@code PsiLanguageInjectionHost})
is ContributedReferenceHost, is PsiLanguageInjectionHost -> true
else -> false
}
}
@ApiStatus.Experimental
fun splitToTextRanges(charSequence: CharSequence,
pattern: String,
escaperFactory: (CharSequence, String) -> SplitEscaper = { _, _ -> SplitEscaper.AcceptAll }): Sequence<TextRange> {
var lastMatch = 0
var lastSplit = 0
val escaper = escaperFactory(charSequence, pattern)
return sequence {
while (true) {
val start = charSequence.indexOf(pattern, lastMatch)
if (start == -1) {
yield(TextRange(lastSplit, charSequence.length))
return@sequence
}
lastMatch = start + pattern.length
if (escaper.filter(lastSplit, start)) {
yield(TextRange(lastSplit, start))
lastSplit = lastMatch
}
}
}
}
@ApiStatus.Experimental
interface SplitEscaper {
fun filter(lastSplit: Int, currentPosition: Int): Boolean
object AcceptAll : SplitEscaper {
override fun filter(lastSplit: Int, currentPosition: Int): Boolean = true
}
} | apache-2.0 | 4fb0cb062b8a1602d9bb1707ba7b5157 | 36.377778 | 140 | 0.660721 | 4.530303 | false | false | false | false |
SDS-Studios/ScoreKeeper | app/src/main/java/io/github/sdsstudios/ScoreKeeper/GameListItem.kt | 1 | 5327 | package io.github.sdsstudios.ScoreKeeper
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Ignore
import android.arch.persistence.room.PrimaryKey
import android.arch.persistence.room.Relation
import android.content.Context
import android.view.View
import eu.davidea.flexibleadapter.FlexibleAdapter
import io.github.sdsstudios.ScoreKeeper.Database.Dao.GameDao
import io.github.sdsstudios.ScoreKeeper.Database.Dao.ScoresDao
import io.github.sdsstudios.ScoreKeeper.Game.Scores
import io.github.sdsstudios.ScoreKeeper.Game.ScoresWithPlayer
import io.github.sdsstudios.ScoreKeeper.ViewHolders.GameListItemHolder
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by sethsch1 on 29/10/17.
*/
class GameListItem(
@PrimaryKey @ColumnInfo(name = GameDao.KEY_ID) var id: Long = 0,
@ColumnInfo(name = GameDao.KEY_TITLE) var title: String = "",
@ColumnInfo(name = GameDao.KEY_COMPLETED) var completed: Boolean = false,
@ColumnInfo(name = GameDao.KEY_LAST_PLAYED_DATE) var date: Date = Date(),
@Relation(parentColumn = GameDao.KEY_ID,
entityColumn = ScoresDao.KEY_GAME_ID,
entity = Scores::class)
var sets: MutableList<ScoresWithPlayer> = ArrayList()
) : FlexibleItem<GameListItemHolder>(), Comparable<GameListItem> {
companion object {
const val IN_PROGRESS = 0
const val COMPLETED = 1
const val ALL = 2
private val mTodayDateFormat = SimpleDateFormat("HH:mm", Locale.ENGLISH)
private val mThisYearDateFormat = SimpleDateFormat("d MMM", Locale.ENGLISH)
private val mOtherDateFormat = SimpleDateFormat("d MMM yyyy", Locale.ENGLISH)
private var mCompletedString: String? = null
private var mInProgressString: String? = null
private var mNoPlayersString: String? = null
fun getCompletedString(ctx: Context): String {
if (mCompletedString == null) {
mCompletedString = ctx.getString(R.string.completed)
}
return mCompletedString!!
}
fun getInProgressString(ctx: Context): String {
if (mInProgressString == null) {
mInProgressString = ctx.getString(R.string.in_progress)
}
return mInProgressString!!
}
fun getNoPlayersString(ctx: Context): String {
if (mNoPlayersString == null) {
mNoPlayersString = ctx.getString(R.string.no_players)
}
return mNoPlayersString!!
}
}
@Ignore
private var mState: String? = null
@Ignore
private var mPlayersString: String? = null
@Ignore
private var mTimeString: String? = null
get() {
if (field == null) {
mTimeString = date.formatted()
}
return field
}
override fun createViewHolder(view: View, adapter: FlexibleAdapter<*>) =
GameListItemHolder(view, adapter)
override fun bindViewHolder(
adapter: FlexibleAdapter<*>,
holder: GameListItemHolder,
position: Int,
payloads: List<Any>
) {
adapter.getItem(position).apply {
holder.apply {
val ctx = holder.itemView.context
textViewTitle.text = title
textViewDate.text = mTimeString
textViewPlayers.text = getPlayersString(ctx)
textViewState.text = getState(ctx)
}
}
}
override fun isSelectable() = true
override fun getLayoutRes() = R.layout.game_list_adapter_layout
override fun hashCode() = id.toInt()
override fun equals(other: Any?) = this.id == (other as GameListItem).id
override fun compareTo(other: GameListItem) = other.date.compareTo(this.date)
private fun Date.formatted(): String {
val calToday = Calendar.getInstance()
val calPast = Calendar.getInstance()
calPast.time = this
if (calToday.get(Calendar.DATE) == calPast.get(Calendar.DATE))
return mTodayDateFormat.format(calPast.time)
if (calToday.get(Calendar.YEAR) != calPast.get(Calendar.YEAR))
return mOtherDateFormat.format(calPast.time)
return mThisYearDateFormat.format(calPast.time)
}
private fun getState(ctx: Context): String {
if (mState == null) {
mState = if (completed) {
getCompletedString(ctx)
} else {
getInProgressString(ctx)
}
}
return mState!!
}
private fun getPlayersString(ctx: Context): String {
if (mPlayersString == null) {
mPlayersString = buildPlayerString(ctx)
}
return mPlayersString!!
}
private fun buildPlayerString(ctx: Context): String {
return buildString {
if (sets.isEmpty()) {
append(getNoPlayersString(ctx))
} else {
val gamePlayerIds = sets.map { it.playerId }
sets.filter { gamePlayerIds.contains(it.playerId) }.forEachIndexed { i, p ->
append(p.player.name)
if (i != gamePlayerIds.size - 1) append(", ")
}
}
}
}
} | gpl-3.0 | cf98fd2131f8e00b98196078eefb2713 | 30.526627 | 92 | 0.617984 | 4.541347 | false | false | false | false |
NiciDieNase/chaosflix | touch/src/main/java/de/nicidienase/chaosflix/touch/favoritesimport/FavoritesImportFragment.kt | 1 | 5660 | package de.nicidienase.chaosflix.touch.favoritesimport
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.snackbar.Snackbar
import de.nicidienase.chaosflix.common.ImportItem
import de.nicidienase.chaosflix.common.viewmodel.FavoritesImportViewModel
import de.nicidienase.chaosflix.common.viewmodel.ViewModelFactory
import de.nicidienase.chaosflix.touch.R
import de.nicidienase.chaosflix.touch.browse.adapters.ImportItemAdapter
import de.nicidienase.chaosflix.touch.databinding.FragmentFavoritesImportBinding
class FavoritesImportFragment : Fragment() {
private lateinit var viewModel: FavoritesImportViewModel
private lateinit var adapter: ImportItemAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
setHasOptionsMenu(true)
val binding = FragmentFavoritesImportBinding.inflate(inflater, container, false)
binding.lifecycleOwner = this
viewModel = ViewModelProviders.of(requireActivity(), ViewModelFactory.getInstance(requireContext())).get(FavoritesImportViewModel::class.java)
binding.viewModel = viewModel
binding.importList.layoutManager = LinearLayoutManager(context)
val onItemClick: (ImportItem) -> Unit = {
viewModel.itemChanged(it)
}
val onLectureClick: (ImportItem) -> Unit = {
viewModel.unavailableItemClicked(it)
}
adapter = ImportItemAdapter(onListItemClick = onItemClick, onLectureClick = onLectureClick)
adapter.setHasStableIds(true)
binding.importList.setHasFixedSize(true)
binding.importList.adapter = adapter
viewModel.items.observe(viewLifecycleOwner, Observer { events ->
if (events != null) {
adapter.submitList(events.toList())
}
})
viewModel.selectAll.observe(viewLifecycleOwner, Observer {
activity?.invalidateOptionsMenu()
})
viewModel.state.observe(viewLifecycleOwner, Observer {
when (it.state) {
FavoritesImportViewModel.State.IMPORT_DONE -> {
// TODO navigate to favorites
activity?.finish()
}
}
})
viewModel.working.observe(viewLifecycleOwner, Observer { working ->
binding.incOverlay.loadingOverlay.visibility = if (working) View.VISIBLE else View.GONE
})
viewModel.processCount.observe(viewLifecycleOwner, Observer { pair ->
Log.i(TAG, "Progress ${pair.first}/${pair.second}")
binding.incOverlay.progressbar.apply {
if (pair.second != 0) {
visibility = View.VISIBLE
progress = (100 * pair.first / pair.second)
}
}
})
viewModel.errorMessage.observe(viewLifecycleOwner, Observer { errorMessage ->
if (errorMessage != null) {
Snackbar.make(binding.root, errorMessage, Snackbar.LENGTH_LONG).apply {
view.findViewById<TextView>(com.google.android.material.R.id.snackbar_text).maxLines = 5
setAction("OK", View.OnClickListener {
this.dismiss()
}).show()
}
viewModel.errorShown()
}
})
viewModel.importItemCount.observe(viewLifecycleOwner, Observer { count ->
if (count == 0) {
binding.buttonImport.hide()
} else {
binding.buttonImport.show()
}
})
val intent = activity?.intent
when {
intent?.action == Intent.ACTION_SEND -> {
when (intent.type) {
"text/json" -> handleJson(intent)
}
}
else -> {
// Handle other intents, such as being started from the home screen
}
}
return binding.root
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.import_menu, menu)
if (viewModel.selectAll.value != false) {
menu.removeItem(R.id.menu_item_unselect_all)
} else {
menu.removeItem(R.id.menu_item_select_all)
}
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_item_select_all -> {
viewModel.selectAll()
viewModel.selectAll.value = false
true
}
R.id.menu_item_unselect_all -> {
viewModel.selectNone()
viewModel.selectAll.value = true
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun handleJson(intent: Intent) {
val extra = intent.getStringExtra(Intent.EXTRA_TEXT)
if (extra.isNotEmpty()) {
viewModel.handleLectures(extra)
}
}
companion object {
private val TAG = FavoritesImportFragment::class.java.simpleName
}
}
| mit | 5260462c6aea4c8d6b86ef01252eadb4 | 35.282051 | 150 | 0.622261 | 5.117541 | false | false | false | false |
walleth/kethereum | hashes/src/main/kotlin/org/kethereum/hashes/IntExtensions.kt | 1 | 816 | package org.kethereum.hashes
const val INT_BYTES = 4
/**
* Returns the value obtained by rotating the two's complement binary representation of the specified [Int] value
* right by the specified number of bits.
* (Bits shifted out of the right hand, or low-order, side reenter on the left, or high-order.)
*/
internal fun Int.rotateRight(distance: Int): Int {
return this.ushr(distance) or (this shl -distance)
}
/**
* Converts an [Int] to an array of [Byte] using the big-endian conversion.
* (The [Int] will be converted into 4 bytes)
*/
internal fun Int.toBytes(): Array<Byte> {
val result = ByteArray(INT_BYTES)
result[0] = (this shr 24).toByte()
result[1] = (this shr 16).toByte()
result[2] = (this shr 8).toByte()
result[3] = this.toByte()
return result.toTypedArray()
} | mit | 20b00b0d14b24117ea62cfbe35131c8c | 29.259259 | 113 | 0.686275 | 3.594714 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/badges/self/featured/SelectFeaturedBadgeViewModel.kt | 2 | 2749 | package org.thoughtcrime.securesms.badges.self.featured
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.plusAssign
import io.reactivex.rxjava3.kotlin.subscribeBy
import io.reactivex.rxjava3.subjects.PublishSubject
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.badges.BadgeRepository
import org.thoughtcrime.securesms.badges.models.Badge
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.util.livedata.Store
private val TAG = Log.tag(SelectFeaturedBadgeViewModel::class.java)
class SelectFeaturedBadgeViewModel(private val repository: BadgeRepository) : ViewModel() {
private val store = Store(SelectFeaturedBadgeState())
private val eventSubject = PublishSubject.create<SelectFeaturedBadgeEvent>()
val state: LiveData<SelectFeaturedBadgeState> = store.stateLiveData
val events: Observable<SelectFeaturedBadgeEvent> = eventSubject.observeOn(AndroidSchedulers.mainThread())
private val disposables = CompositeDisposable()
init {
store.update(Recipient.live(Recipient.self().id).liveDataResolved) { recipient, state ->
val unexpiredBadges = recipient.badges.filterNot { it.isExpired() }
state.copy(
stage = if (state.stage == SelectFeaturedBadgeState.Stage.INIT) SelectFeaturedBadgeState.Stage.READY else state.stage,
selectedBadge = unexpiredBadges.firstOrNull(),
allUnlockedBadges = unexpiredBadges
)
}
}
fun setSelectedBadge(badge: Badge) {
store.update { it.copy(selectedBadge = badge) }
}
fun save() {
val snapshot = store.state
if (snapshot.selectedBadge == null) {
eventSubject.onNext(SelectFeaturedBadgeEvent.NO_BADGE_SELECTED)
return
}
store.update { it.copy(stage = SelectFeaturedBadgeState.Stage.SAVING) }
disposables += repository.setFeaturedBadge(snapshot.selectedBadge).subscribeBy(
onComplete = {
eventSubject.onNext(SelectFeaturedBadgeEvent.SAVE_SUCCESSFUL)
},
onError = { error ->
Log.e(TAG, "Failed to update profile.", error)
eventSubject.onNext(SelectFeaturedBadgeEvent.FAILED_TO_UPDATE_PROFILE)
}
)
}
override fun onCleared() {
disposables.clear()
}
class Factory(private val badgeRepository: BadgeRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return requireNotNull(modelClass.cast(SelectFeaturedBadgeViewModel(badgeRepository)))
}
}
}
| gpl-3.0 | 627de7723fdb43e4e6a82dab841d011c | 36.657534 | 126 | 0.766461 | 4.38437 | false | false | false | false |
ktorio/ktor | ktor-io/jvm/src/io/ktor/utils/io/ExceptionUtilsJvm.kt | 1 | 3825 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.utils.io
import io.ktor.utils.io.core.internal.*
import kotlinx.coroutines.*
import java.lang.reflect.*
import java.util.*
import java.util.concurrent.locks.*
import kotlin.concurrent.*
/**
* Print exception stacktrace.
*/
public actual fun Throwable.printStack() {
printStackTrace()
}
/**
* This file is a copy of the [kotlinx.coroutines.internal.ExceptionConstructor] with a single difference:
* [tryCopyException] takes additional argument with cause using in recovered exception.
*/
private val throwableFields = Throwable::class.java.fieldsCountOrDefault(-1)
private val cacheLock = ReentrantReadWriteLock()
private typealias Ctor = (Throwable) -> Throwable?
// Replace it with ClassValue when Java 6 support is over
private val exceptionCtors: WeakHashMap<Class<out Throwable>, Ctor> = WeakHashMap()
/**
* Try copy [exception] using [cause] as cause.
*/
@Suppress("UNCHECKED_CAST")
@OptIn(ExperimentalCoroutinesApi::class)
public fun <E : Throwable> tryCopyException(exception: E, cause: Throwable): E? {
// Fast path for CopyableThrowable
if (exception is CopyableThrowable<*>) {
return runCatching { exception.createCopy() as E? }.getOrNull()
}
// Use cached ctor if found
cacheLock.read { exceptionCtors[exception.javaClass] }?.let { cachedCtor ->
return cachedCtor(exception) as E?
}
/*
* Skip reflective copy if an exception has additional fields (that are usually populated in user-defined constructors)
*/
if (throwableFields != exception.javaClass.fieldsCountOrDefault(0)) {
cacheLock.write { exceptionCtors[exception.javaClass] = { null } }
return null
}
/*
* Try to reflectively find constructor(), constructor(message, cause), constructor(cause) or constructor(message).
* Exceptions are shared among coroutines, so we should copy exception before recovering current stacktrace.
*/
var ctor: Ctor? = null
val constructors = exception.javaClass.constructors.sortedByDescending { it.parameterTypes.size }
for (constructor in constructors) {
ctor = createConstructor(constructor)
if (ctor != null) break
}
// Store the resulting ctor to cache
cacheLock.write { exceptionCtors[exception.javaClass] = ctor ?: { null } }
return ctor?.invoke(cause) as E?
}
private fun createConstructor(constructor: Constructor<*>): Ctor? {
val p = constructor.parameterTypes
return when (p.size) {
2 -> when {
p[0] == String::class.java && p[1] == Throwable::class.java ->
safeCtor { e -> constructor.newInstance(e.message, e) as Throwable }
else -> null
}
1 -> when (p[0]) {
Throwable::class.java ->
safeCtor { e -> constructor.newInstance(e) as Throwable }
String::class.java ->
safeCtor { e -> (constructor.newInstance(e.message) as Throwable).also { it.initCause(e) } }
else -> null
}
0 -> safeCtor { e -> (constructor.newInstance() as Throwable).also { it.initCause(e) } }
else -> null
}
}
private inline fun safeCtor(crossinline block: (Throwable) -> Throwable): Ctor =
{ e -> runCatching { block(e) }.getOrNull() }
private fun Class<*>.fieldsCountOrDefault(defaultValue: Int) =
kotlin.runCatching { fieldsCount() }.getOrDefault(defaultValue)
private tailrec fun Class<*>.fieldsCount(accumulator: Int = 0): Int {
val fieldsCount = declaredFields.count { !Modifier.isStatic(it.modifiers) }
val totalFields = accumulator + fieldsCount
val superClass = superclass ?: return totalFields
return superClass.fieldsCount(totalFields)
}
| apache-2.0 | 43f09d1010132b8a411567c712e610a1 | 37.25 | 123 | 0.683137 | 4.288117 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-plugins/ktor-server-double-receive/jvmAndNix/src/io/ktor/server/plugins/doublereceive/ByteArrayCache.kt | 1 | 1502 | // ktlint-disable filename
/*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.plugins.doublereceive
import io.ktor.utils.io.*
import io.ktor.utils.io.core.*
import io.ktor.utils.io.pool.*
import kotlinx.coroutines.*
import kotlin.coroutines.*
internal class MemoryCache(
val body: ByteReadChannel,
coroutineContext: CoroutineContext = EmptyCoroutineContext
) : DoubleReceiveCache {
private var fullBody: ByteArray? = null
private var cause: Throwable? = null
@OptIn(DelicateCoroutinesApi::class)
private val reader: ByteReadChannel = GlobalScope.writer(coroutineContext) {
val buffer = ByteArrayPool.borrow()
val packet = BytePacketBuilder()
while (!body.isClosedForRead) {
val size = body.readAvailable(buffer)
if (size == -1) break
packet.writeFully(buffer, 0, size)
channel.writeFully(buffer, 0, size)
}
if (body.closedCause != null) {
cause = body.closedCause
channel.close(body.closedCause)
}
fullBody = packet.build().readBytes()
}.channel
override fun read(): ByteReadChannel {
val currentCause = cause
if (currentCause != null) {
return ByteChannel().apply { close(currentCause) }
}
return fullBody?.let { ByteReadChannel(it) } ?: reader
}
override fun dispose() {
}
}
| apache-2.0 | 862b1cc8839cfef38e77f6bdcaddc8ae | 27.884615 | 119 | 0.650466 | 4.470238 | false | false | false | false |
hantsy/spring-reactive-sample | kotlin/src/main/kotlin/com/example/demo/PostController.kt | 1 | 925 | package com.example.demo
import org.springframework.web.bind.annotation.*
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
@RestController
@RequestMapping(value = ["/posts"])
class PostController(val posts: PostRepository) {
@GetMapping("")
fun all(): Flux<Post> = this.posts.findAll()
@PostMapping("")
fun create(@RequestBody post: Post): Mono<Post> = this.posts.save(post)
@GetMapping("/{id}")
fun get(@PathVariable("id") id: String): Mono<Post> = this.posts.findById(id)
@PutMapping("/{id}")
fun update(@PathVariable("id") id: String, @RequestBody post: Post): Mono<Post> {
return this.posts.findById(id)
.map { it.copy(title = post.title, content = post.content) }
.flatMap { this.posts.save(it) }
}
@DeleteMapping("/{id}")
fun delete(@PathVariable("id") id: String): Mono<Void> = this.posts.deleteById(id)
} | gpl-3.0 | e4cb8aacb8ee44ce812b9be5b77f8e86 | 29.866667 | 86 | 0.654054 | 3.760163 | false | false | false | false |
ayatk/biblio | app/src/main/kotlin/com/ayatk/biblio/ui/ranking/RankingActivity.kt | 1 | 2570 | /*
* Copyright (c) 2016-2018 ayatk.
*
* 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.ayatk.biblio.ui.ranking
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.ayatk.biblio.R
import com.ayatk.biblio.databinding.ActivityRankingBinding
import com.ayatk.biblio.model.enums.RankingType
import com.ayatk.biblio.ui.util.initBackToolbar
import com.ayatk.biblio.util.ext.extraOf
import com.ayatk.biblio.util.ext.integer
import dagger.android.support.DaggerAppCompatActivity
class RankingActivity : DaggerAppCompatActivity() {
private val binding: ActivityRankingBinding by lazy {
DataBindingUtil.setContentView(this, R.layout.activity_ranking)
}
private val rankingType: RankingType by lazy {
intent?.getSerializableExtra(EXTRA_RANKING_TYPE)!! as RankingType
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initBackToolbar(binding.toolbar)
binding.rankingViewPager.apply {
adapter = RankingPagerAdapter(supportFragmentManager)
pageMargin = context.integer(R.integer.pager_margin)
currentItem = rankingType.ordinal
}
binding.tab.setupWithViewPager(binding.rankingViewPager)
}
companion object {
private const val EXTRA_RANKING_TYPE = "ranking_type"
fun createIntent(context: Context, rankingType: RankingType): Intent =
Intent(context, RankingActivity::class.java).extraOf(
EXTRA_RANKING_TYPE to rankingType
)
}
inner class RankingPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment =
RankingListFragment.newInstance(RankingType.values()[position])
override fun getCount(): Int = RankingType.values().size
override fun getPageTitle(position: Int): CharSequence = RankingType.values()[position].title
}
}
| apache-2.0 | 01ba9a37cd68abd4d7884e0a9ef59a88 | 32.815789 | 97 | 0.76965 | 4.431034 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/core/src/templates/kotlin/core/templates/MemoryAccessJNI.kt | 2 | 3420 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package core.templates
import org.lwjgl.generator.*
val MemoryAccessJNI = "MemoryAccessJNI".nativeClass(Module.CORE) {
nativeImport(
"<stdlib.h>",
"<stdint.h>"
)
access = Access.INTERNAL
documentation = "Memory access utilities."
Code(
nativeCall = "${t}return (jint)sizeof(void *);"
)..int(
"getPointerSize",
"Returns the {@code sizeof(void *)}.",
void()
)
val primitives = arrayOf(
Triple(int8_t, "Byte", "a byte value"),
Triple(int16_t, "Short", "a short value"),
Triple(int32_t, "Int", "an int value"),
Triple(int64_t, "Long", "a long value"),
Triple(float, "Float", "a float value"),
Triple(double, "Double", "a double value"),
Triple(uintptr_t, "Address", "a pointer address")
)
nativeDirective(
"""#ifdef LWJGL_WINDOWS
static void* __aligned_alloc(size_t alignment, size_t size) {
return _aligned_malloc(size, alignment);
}
#define __aligned_free _aligned_free
#else
#if defined(__USE_ISOC11) && !defined(LWJGL_LINUX)
#define __aligned_alloc aligned_alloc
#else
static void* __aligned_alloc(size_t alignment, size_t size) {
void *p;
return posix_memalign(&p, alignment, size) ? NULL : p;
}
#endif
#define __aligned_free free
#endif
// -----------
${primitives
.asSequence()
.map {
val (type, name) = it
"static inline ${type.name} get$name(void *ptr) { return *(${type.name} *)ptr; }"
}
.joinToString("\n")}
// -----------
${primitives
.asSequence()
.map {
val (type, name) = it
"static inline void put$name(void *ptr, ${type.name} value) { *(${type.name} *)ptr = value; }"
}
.joinToString("\n")}
// -----------""")
arrayOf(
"malloc" to "void * (*) (size_t)",
"calloc" to "void * (*) (size_t, size_t)",
"realloc" to "void * (*) (void *, size_t)",
"free" to "void (*) (void *)"
).forEach { (name, signature) ->
macro..Address..signature.handle(
name,
"Returns the address of the stdlib {@code $name} function.",
void()
)
}
Code(
nativeCall = "${t}return (jlong)(uintptr_t)&__aligned_alloc;"
)..macro..Address.."void * (*) (size_t, size_t)".handle(
"aligned_alloc",
"Returns the address of the stdlib {@code aligned_alloc} function.",
void()
)
Code(
nativeCall = "${t}return (jlong)(uintptr_t)&__aligned_free;"
)..macro..Address.."void (*) (void *)".handle(
"aligned_free",
"Returns the address of the stdlib {@code aligned_free} function.",
void()
)
for ((type, name, msg) in primitives)
type(
"get$name",
"Reads $msg from the specified memory address.",
opaque_p("ptr", "the memory address to read")
)
for ((type, name, msg) in primitives)
void(
"put$name",
"Writes $msg to the specified memory address.",
opaque_p("ptr", "the memory address to write"),
type("value", "the value to write")
)
} | bsd-3-clause | fa61c8af0fa43740e55c985cf9322f43 | 26.813008 | 110 | 0.519591 | 3.842697 | false | false | false | false |
cascheberg/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/settings/conversation/preferences/InternalPreference.kt | 1 | 2220 | package org.thoughtcrime.securesms.components.settings.conversation.preferences
import android.view.View
import android.widget.TextView
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.settings.PreferenceModel
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.util.Base64
import org.thoughtcrime.securesms.util.Hex
import org.thoughtcrime.securesms.util.MappingAdapter
import org.thoughtcrime.securesms.util.MappingViewHolder
import java.util.UUID
object InternalPreference {
fun register(adapter: MappingAdapter) {
adapter.registerFactory(Model::class.java, MappingAdapter.LayoutFactory(::ViewHolder, R.layout.conversation_settings_internal_preference))
}
class Model(
private val recipient: Recipient,
val onDisableProfileSharingClick: () -> Unit
) : PreferenceModel<Model>() {
val body: String get() {
return String.format(
"""
-- Profile Name --
[${recipient.profileName.givenName}] [${recipient.profileName.familyName}]
-- Profile Sharing --
${recipient.isProfileSharing}
-- Profile Key (Base64) --
${recipient.profileKey?.let(Base64::encodeBytes) ?: "None"}
-- Profile Key (Hex) --
${recipient.profileKey?.let(Hex::toStringCondensed) ?: "None"}
-- Sealed Sender Mode --
${recipient.unidentifiedAccessMode}
-- UUID --
${recipient.uuid.transform { obj: UUID -> obj.toString() }.or("None")}
-- RecipientId --
${recipient.id.serialize()}
""".trimIndent(),
)
}
override fun areItemsTheSame(newItem: Model): Boolean {
return recipient == newItem.recipient
}
}
private class ViewHolder(itemView: View) : MappingViewHolder<Model>(itemView) {
private val body: TextView = itemView.findViewById(R.id.internal_preference_body)
private val disableProfileSharing: View = itemView.findViewById(R.id.internal_disable_profile_sharing)
override fun bind(model: Model) {
body.text = model.body
disableProfileSharing.setOnClickListener { model.onDisableProfileSharingClick() }
}
}
}
| gpl-3.0 | 8efe313308fb787a4e9478d9e017fcd9 | 32.134328 | 142 | 0.68964 | 4.615385 | false | false | false | false |
android/location-samples | SleepSampleKotlin/app/src/main/java/com/android/example/sleepsamplekotlin/data/db/SleepClassifyEventEntity.kt | 2 | 1926 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.sleepsamplekotlin.data.db
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.android.gms.location.SleepClassifyEvent
/**
* Entity class (table version of the class) for [SleepClassifyEvent] which represents a sleep
* classification event including the classification timestamp, the sleep confidence, and the
* supporting data such as device motion and ambient light level. Classification events are
* reported regularly.
*/
@Entity(tableName = "sleep_classify_events_table")
data class SleepClassifyEventEntity(
@PrimaryKey
@ColumnInfo(name = "time_stamp_seconds")
val timestampSeconds: Int,
@ColumnInfo(name = "confidence")
val confidence: Int,
@ColumnInfo(name = "motion")
val motion: Int,
@ColumnInfo(name = "light")
val light: Int
) {
companion object {
fun from(sleepClassifyEvent: SleepClassifyEvent): SleepClassifyEventEntity {
return SleepClassifyEventEntity(
timestampSeconds = (sleepClassifyEvent.timestampMillis / 1000).toInt(),
confidence = sleepClassifyEvent.confidence,
motion = sleepClassifyEvent.motion,
light = sleepClassifyEvent.light
)
}
}
}
| apache-2.0 | 234f0570f45c5e23d5139e654da0f198 | 34.666667 | 94 | 0.717549 | 4.553191 | false | false | false | false |
burntcookie90/redditbot | bot/src/main/kotlin/io/dwak/reddit/bot/dagger/NetworkModule.kt | 1 | 8267 | package io.dwak.reddit.bot.dagger
import com.squareup.moshi.Moshi
import dagger.Module
import dagger.Provides
import io.dwak.reddit.bot.Bot
import io.dwak.reddit.bot.config.ConfigHelper
import io.dwak.reddit.bot.network.RedditLoginManager
import io.dwak.reddit.bot.network.RedditOauthInterceptor
import io.dwak.reddit.bot.network.SlackLoginManager
import io.dwak.reddit.bot.network.adapter.reddit.KindAdapter
import io.dwak.reddit.bot.network.adapter.slack.SlackWebhookUrlComponentAdapter
import io.dwak.reddit.bot.network.reddit.RedditLoginService
import io.dwak.reddit.bot.network.reddit.RedditService
import io.dwak.reddit.bot.network.slack.SlackOauthService
import io.dwak.reddit.bot.network.slack.SlackService
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.CallAdapter
import retrofit2.Converter
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import rx.schedulers.Schedulers
import java.util.*
import javax.inject.Named
import javax.inject.Singleton
@Suppress("unused")
@Module(library = true,
injects = arrayOf(Bot::class, ConfigHelper::class, SlackService::class, Moshi::class),
staticInjections = arrayOf(RedditLoginManager::class, SlackLoginManager::class))
class NetworkModule {
companion object {
const val REDDIT_SERVICE_BASE_URL = "redditServiceBaseUrl"
const val REDDIT_SERVICE = "redditService"
const val REDDIT_OKHTTP_BUILDER = "redditOkHttpBuilder"
const val REDDIT_OKHTTP = "redditOkhttp"
const val REDDIT_LOGIN_SERVICE_BASE_URL = "redditLoginServiceBaseUrl"
const val REDDIT_LOGIN_SERVICE = "redditLoginService"
const val REDDIT_LOGIN_OKHTTP_BUILDER = "redditLoginOkHttpBuilder"
const val REDDIT_LOGIN_OKHTTP = "redditLoginOkHttp"
const val SLACK_SERVICE_BASE_URL = "slackServiceBaseUrl"
const val SLACK_SERVICE = "slackService"
const val SLACK_OKHTTP_BUILDER = "slackOkHttpBuilder"
const val SLACK_OKHTTP = "slackOkHttp"
const val SLACK_OAUTH_SERVICE_BASE_URL = "slackOauthServiceBaseUrl"
const val SLACK_OAUTH_SERVICE = "slackOauthService"
const val SLACK_OAUTH_OKHTTP_BUILDER = "slackOauthOkHttpBuilder"
const val SLACK_OAUTH_OKHTTP = "slackOauthOkHttp"
}
@Provides
@Named(REDDIT_SERVICE_BASE_URL)
fun redditServiceBaseUrl() = "https://oauth.reddit.com/r/"
@Provides
@Named(REDDIT_LOGIN_SERVICE_BASE_URL)
fun loginServiceBaseUrl() = "https://www.reddit.com/"
@Provides
@Named(SLACK_SERVICE_BASE_URL)
fun slackServiceBaseUrl() = "https://hooks.slack.com/"
@Provides
@Named(SLACK_OAUTH_SERVICE_BASE_URL)
fun slackOauthServiceBaseUrl() = "https://slack.com/api/"
@Provides
@Singleton
fun moshi() : Moshi = Moshi.Builder()
.add(KindAdapter())
.add(SlackWebhookUrlComponentAdapter())
.build()
@Provides
@Singleton
fun moshiFactory(moshi : Moshi) : Converter.Factory
= MoshiConverterFactory.create(moshi).asLenient()
@Provides
fun interceptors() : ArrayList<Interceptor> {
val interceptors = arrayListOf<okhttp3.Interceptor>()
val loggingInterceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { println(it) })
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
interceptors.add(loggingInterceptor)
return interceptors
}
@Provides
@Named(REDDIT_LOGIN_OKHTTP)
fun loginOkHttp(@Named(REDDIT_LOGIN_OKHTTP_BUILDER) okHttpBuilder : OkHttpClient.Builder,
interceptors : ArrayList<Interceptor>)
: OkHttpClient {
okHttpBuilder.interceptors().addAll(interceptors)
return okHttpBuilder.build()
}
@Provides
@Named(REDDIT_OKHTTP)
fun redditOkHttp(@Named(REDDIT_OKHTTP_BUILDER) okHttpBuilder : OkHttpClient.Builder,
interceptors : ArrayList<Interceptor>)
: OkHttpClient {
okHttpBuilder.interceptors().addAll(interceptors)
return okHttpBuilder.build()
}
@Provides
@Named(SLACK_OKHTTP)
fun slackOkHttp(@Named(SLACK_OKHTTP_BUILDER) okHttpBuilder : OkHttpClient.Builder,
interceptors : ArrayList<Interceptor>)
: OkHttpClient {
okHttpBuilder.interceptors().addAll(interceptors)
return okHttpBuilder.build()
}
@Provides
@Named(SLACK_OAUTH_OKHTTP)
fun slackOauthOkHttp(@Named(SLACK_OAUTH_OKHTTP_BUILDER) okHttpBuilder : OkHttpClient.Builder,
interceptors : ArrayList<Interceptor>)
: OkHttpClient {
okHttpBuilder.interceptors().addAll(interceptors)
return okHttpBuilder.build()
}
@Provides
@Named(REDDIT_LOGIN_OKHTTP_BUILDER)
fun loginOkHttpBuilder() : OkHttpClient.Builder {
return OkHttpClient.Builder()
}
@Provides
@Named(SLACK_OKHTTP_BUILDER)
fun slackOkHttpBuilder() : OkHttpClient.Builder {
return OkHttpClient.Builder()
}
@Provides
@Named(SLACK_OAUTH_OKHTTP_BUILDER)
fun slackOauthOkHttpBuilder() : OkHttpClient.Builder {
return OkHttpClient.Builder()
}
@Provides
@Named(REDDIT_OKHTTP_BUILDER)
fun redditOkHttpBuilder(redditOauthInterceptor : RedditOauthInterceptor) : OkHttpClient.Builder {
val okHttpBuilder = OkHttpClient.Builder()
okHttpBuilder.addInterceptor(redditOauthInterceptor)
return okHttpBuilder
}
@Provides
fun adapterFactory() : CallAdapter.Factory = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())
@Provides
@Singleton
@Named(REDDIT_SERVICE)
fun redditServiceRetrofit(converterFactory : Converter.Factory,
callAdapterFactory : CallAdapter.Factory,
@Named(REDDIT_OKHTTP) client : OkHttpClient,
@Named(REDDIT_SERVICE_BASE_URL) baseUrl : String) : Retrofit
= Retrofit.Builder()
.addConverterFactory(converterFactory)
.addCallAdapterFactory(callAdapterFactory)
.client(client)
.baseUrl(baseUrl)
.build()
@Provides
@Singleton
@Named(REDDIT_LOGIN_SERVICE)
fun loginServiceRetrofit(converterFactory : Converter.Factory,
callAdapterFactory : CallAdapter.Factory,
@Named(REDDIT_LOGIN_OKHTTP) client : OkHttpClient,
@Named(REDDIT_LOGIN_SERVICE_BASE_URL) baseUrl : String) : Retrofit
= Retrofit.Builder()
.addConverterFactory(converterFactory)
.addCallAdapterFactory(callAdapterFactory)
.client(client)
.baseUrl(baseUrl)
.build()
@Provides
@Singleton
@Named(SLACK_SERVICE)
fun slackServiceRetrofit(converterFactory : Converter.Factory,
callAdapterFactory : CallAdapter.Factory,
@Named(SLACK_OKHTTP) client : OkHttpClient,
@Named(SLACK_SERVICE_BASE_URL) baseUrl : String) : Retrofit
= Retrofit.Builder()
.addConverterFactory(converterFactory)
.addCallAdapterFactory(callAdapterFactory)
.client(client)
.baseUrl(baseUrl)
.build()
@Provides
@Singleton
@Named(SLACK_OAUTH_SERVICE)
fun slackOauthServiceRetrofit(converterFactory : Converter.Factory,
callAdapterFactory : CallAdapter.Factory,
@Named(SLACK_OAUTH_OKHTTP) client : OkHttpClient,
@Named(SLACK_OAUTH_SERVICE_BASE_URL) baseUrl : String) : Retrofit
= Retrofit.Builder()
.addConverterFactory(converterFactory)
.addCallAdapterFactory(callAdapterFactory)
.client(client)
.baseUrl(baseUrl)
.build()
@Provides
@Singleton
fun redditService(@Named(REDDIT_SERVICE) retrofit : Retrofit) = retrofit.create(RedditService::class.java)
@Provides
@Singleton
fun loginService(@Named(REDDIT_LOGIN_SERVICE) retrofit : Retrofit) = retrofit.create(RedditLoginService::class.java)
@Provides
@Singleton
fun slackServices(@Named(SLACK_SERVICE) retrofit : Retrofit) = retrofit.create(SlackService::class.java)
@Provides
@Singleton
fun slackOauthServices(@Named(SLACK_OAUTH_SERVICE) retrofit : Retrofit) = retrofit.create(SlackOauthService::class.java)
}
| mit | a107cd0fbc317cb8fbd2ebef72441ee2 | 34.633621 | 122 | 0.711383 | 4.406716 | false | false | false | false |
DreierF/MyTargets | shared/src/main/java/de/dreier/mytargets/shared/models/db/BowImage.kt | 1 | 1282 | /*
* 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.models.db
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.ForeignKey.CASCADE
import androidx.room.Index
import androidx.room.PrimaryKey
import android.os.Parcelable
import de.dreier.mytargets.shared.models.Image
import kotlinx.android.parcel.Parcelize
@Parcelize
@Entity(
foreignKeys = [
ForeignKey(
entity = Bow::class,
parentColumns = ["id"],
childColumns = ["bowId"],
onDelete = CASCADE
)
],
indices = [
Index(value = ["bowId"])
]
)
data class BowImage(
@PrimaryKey(autoGenerate = true)
var id: Long = 0,
override var fileName: String = "",
var bowId: Long? = null
) : Image, Parcelable
| gpl-2.0 | 2befa7379be114eb9747a82ea7c1bbdd | 25.708333 | 68 | 0.692668 | 4.231023 | false | false | false | false |
JoelMarcey/buck | tools/ideabuck/src/com/facebook/buck/intellij/ideabuck/actions/select/detectors/BuckKotlinTestDetector.kt | 1 | 4263 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.facebook.buck.intellij.ideabuck.actions.select
/**
* Utility functions to detect tests that Buck can run in {@link KtNamedFunction} and {@link
* KtClass} elements.
*
* <p>Currently, these recognize JUnit3, JUnit4, and TestNG test classes and methods.
*/
class BuckKotlinTestDetector {
companion object {
/**
* Returns true if the given class is one of the kind of tests that Buck knows how to run.
* (Currently, JUnit3, JUnit4, and TestNG.)
*
* <p>Note that this is merely a syntactic check that makes no guarantee that the class appears
* in a file that is part of a buck test target (or even a buck cell).
*/
fun isTestClass(maybeTestClass: PotentialTestClass): Boolean {
// check that class is accessible
if (maybeTestClass.isPotentialTestClass()) {
return isAnnotatedJUnit4TestClass(maybeTestClass) ||
isJUnit3TestCaseClass(maybeTestClass) ||
isJUnit4TestClassWithAtLeastOneTestMethod(maybeTestClass) ||
isTestNGTestClassWithAtLeastOneTestMethod(maybeTestClass)
}
return false
}
/**
* Returns true if the given method is one of the kind of tests that Buck knows how to run.
* (Currently, JUnit3, JUnit4, and TestNG.)
*
* <p>Note that this is merely a syntactic check that makes no guarantee that the method appears
* in a file that is part of a buck test target (or even a buck cell).
*/
fun isTestFunction(function: PotentialTestFunction): Boolean {
val containingClass = function.getContainingClass() ?: return false
if (containingClass.isPotentialTestClass()) {
return when {
isAnnotatedJUnit4TestClass(containingClass) -> isJUnit4TestMethod(function)
isJUnit3TestCaseClass(containingClass) -> isJUnit3TestMethod(function)
else -> isJUnit4TestMethod(function) || isTestNGTestMethod(function)
}
}
return false
}
private fun isTestNGTestClassWithAtLeastOneTestMethod(testClass: PotentialTestClass): Boolean =
testClass.hasTestFunction("org.testng.annotations.Test")
private fun isJUnit4TestClassWithAtLeastOneTestMethod(testClass: PotentialTestClass): Boolean =
testClass.hasTestFunction("org.junit.Test")
private fun isAnnotatedJUnit4TestClass(testClass: PotentialTestClass): Boolean =
testClass.hasAnnotation("org.junit.runner.RunWith")
private fun isJUnit3TestCaseClass(testClass: PotentialTestClass): Boolean =
testClass.hasSuperClass("junit.framework.TestCase")
private fun isJUnit3TestMethod(function: PotentialTestFunction): Boolean =
function.isJUnit3TestMethod()
private fun isJUnit4TestMethod(function: PotentialTestFunction): Boolean =
function.isPotentialTestFunction() && function.hasAnnotation("org.junit.Test")
private fun isTestNGTestMethod(function: PotentialTestFunction): Boolean =
function.isPotentialTestFunction() && function.hasAnnotation("org.testng.annotations.Test")
}
}
/** Represent potential test class without dependency on PsiElements */
interface PotentialTestClass {
fun isPotentialTestClass(): Boolean
fun hasTestFunction(annotationName: String): Boolean
fun hasAnnotation(annotationName: String): Boolean
fun hasSuperClass(superClassQualifiedName: String): Boolean
}
/** Represent potential test function without dependency on PsiElements */
interface PotentialTestFunction {
fun isPotentialTestFunction(): Boolean
fun getContainingClass(): PotentialTestClass?
fun hasAnnotation(annotationName: String): Boolean
fun isJUnit3TestMethod(): Boolean
}
| apache-2.0 | 7eede08e6b876fa30cceaea1751449ac | 39.990385 | 100 | 0.734928 | 4.757813 | false | true | false | false |
paplorinc/intellij-community | plugins/devkit/devkit-core/src/inspections/missingApi/resolve/IdeExternalAnnotations.kt | 3 | 1472 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.devkit.inspections.missingApi.resolve
import com.intellij.openapi.util.BuildNumber
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
/**
* External annotations of IntelliJ API, which are to be included to the project.
*/
data class IdeExternalAnnotations(val annotationsBuild: BuildNumber, val annotationsRoot: VirtualFile)
private const val BUILD_TXT_FILE_NAME = "build.txt"
private val ANNOTATIONS_BUILD_NUMBER_KEY = Key.create<BuildNumber>("devkit.intellij.api.annotations.build.number")
fun getAnnotationsBuildNumber(annotationsRoot: VirtualFile): BuildNumber? {
val cachedValue = annotationsRoot.getUserData(ANNOTATIONS_BUILD_NUMBER_KEY)
if (cachedValue != null) {
return cachedValue
}
val loadedValue = loadBuildNumber(annotationsRoot)
annotationsRoot.putUserData(ANNOTATIONS_BUILD_NUMBER_KEY, loadedValue)
return loadedValue
}
private fun loadBuildNumber(annotationsRoot: VirtualFile): BuildNumber? {
val buildTxtFile = annotationsRoot.findFileByRelativePath(BUILD_TXT_FILE_NAME)
if (buildTxtFile != null) {
return BuildNumber.fromStringOrNull(VfsUtil.loadText(buildTxtFile))
}
return null
}
fun isAnnotationsRoot(virtualFile: VirtualFile) = getAnnotationsBuildNumber(virtualFile) != null
| apache-2.0 | cea97283892c9bf2dae71d7520617df6 | 39.888889 | 140 | 0.80231 | 4.242075 | false | false | false | false |
vladmm/intellij-community | platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/frame/CallFrameView.kt | 1 | 3943 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger.frame
import com.intellij.icons.AllIcons
import com.intellij.ui.ColoredTextContainer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XStackFrame
import org.jetbrains.debugger.*
// isInLibraryContent call could be costly, so we compute it only once (our customizePresentation called on each repaint)
class CallFrameView @JvmOverloads constructor(val callFrame: CallFrame,
private val viewSupport: DebuggerViewSupport,
val script: Script? = null,
private val sourceInfo: SourceInfo? = viewSupport.getSourceInfo(script, callFrame),
private val isInLibraryContent: Boolean = sourceInfo != null && viewSupport.isInLibraryContent(sourceInfo, script)) : XStackFrame(), VariableContext {
private var evaluator: XDebuggerEvaluator? = null
override fun getEqualityObject() = callFrame.equalityObject
override fun computeChildren(node: XCompositeNode) {
node.setAlreadySorted(true)
createAndAddScopeList(node, callFrame.variableScopes, this, callFrame)
}
override fun getEvaluateContext() = callFrame.evaluateContext
override fun getName() = null
override fun getParent() = null
override fun watchableAsEvaluationExpression() = true
override fun getViewSupport() = viewSupport
override fun getMemberFilter() = viewSupport.getMemberFilter(this)
fun getMemberFilter(scope: Scope) = createVariableContext(scope, this, callFrame).memberFilter
override fun getScope() = null
override fun getEvaluator(): XDebuggerEvaluator? {
if (evaluator == null) {
evaluator = viewSupport.createFrameEvaluator(this)
}
return evaluator
}
override fun getSourcePosition() = sourceInfo
override fun customizePresentation(component: ColoredTextContainer) {
if (sourceInfo == null) {
val scriptName = if (script == null) "unknown" else script.url.trimParameters().toDecodedForm()
val line = callFrame.line
component.append(if (line == -1) scriptName else "$scriptName:$line", SimpleTextAttributes.ERROR_ATTRIBUTES)
return
}
val fileName = sourceInfo.file.name
val line = sourceInfo.line + 1
val textAttributes = if (isInLibraryContent) SimpleTextAttributes.GRAYED_ATTRIBUTES else SimpleTextAttributes.REGULAR_ATTRIBUTES
val functionName = sourceInfo.functionName
if (functionName == null || (functionName.isEmpty() && callFrame.hasOnlyGlobalScope())) {
if (fileName.startsWith("index.")) {
sourceInfo.file.parent?.let {
component.append("${it.name}/", textAttributes)
}
}
component.append("$fileName:$line", textAttributes)
}
else {
if (functionName.isEmpty()) {
component.append("anonymous", if (isInLibraryContent) SimpleTextAttributes.GRAYED_ITALIC_ATTRIBUTES else SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES)
}
else {
component.append(functionName, textAttributes)
}
component.append("(), $fileName:$line", textAttributes)
}
component.setIcon(AllIcons.Debugger.StackFrame)
}
} | apache-2.0 | cfb3860867a12a1bdaa1abaee406dbe7 | 38.838384 | 196 | 0.712655 | 5.14752 | false | false | false | false |
vladmm/intellij-community | plugins/settings-repository/src/git/pull.kt | 4 | 14976 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository.git
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.SmartList
import com.intellij.util.containers.hash.LinkedHashMap
import org.eclipse.jgit.api.MergeCommand.FastForwardMode
import org.eclipse.jgit.api.MergeResult
import org.eclipse.jgit.api.MergeResult.MergeStatus
import org.eclipse.jgit.api.errors.CheckoutConflictException
import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException
import org.eclipse.jgit.api.errors.JGitInternalException
import org.eclipse.jgit.api.errors.NoHeadException
import org.eclipse.jgit.diff.RawText
import org.eclipse.jgit.diff.Sequence
import org.eclipse.jgit.dircache.DirCacheCheckout
import org.eclipse.jgit.internal.JGitText
import org.eclipse.jgit.lib.*
import org.eclipse.jgit.merge.MergeMessageFormatter
import org.eclipse.jgit.merge.MergeStrategy
import org.eclipse.jgit.merge.ResolveMerger
import org.eclipse.jgit.merge.SquashMessageFormatter
import org.eclipse.jgit.revwalk.RevWalk
import org.eclipse.jgit.revwalk.RevWalkUtils
import org.eclipse.jgit.transport.RemoteConfig
import org.eclipse.jgit.treewalk.FileTreeIterator
import org.jetbrains.settingsRepository.*
import java.io.IOException
import java.text.MessageFormat
open internal class Pull(val manager: GitRepositoryManager, val indicator: ProgressIndicator?, val commitMessageFormatter: CommitMessageFormatter = IdeaCommitMessageFormatter()) {
val repository = manager.repository
// we must use the same StoredConfig instance during the operation
val config = repository.config
val remoteConfig = RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME)
fun pull(mergeStrategy: MergeStrategy = MergeStrategy.RECURSIVE, commitMessage: String? = null, prefetchedRefToMerge: Ref? = null): UpdateResult? {
indicator?.checkCanceled()
LOG.debug("Pull")
val state = repository.fixAndGetState()
if (!state.canCheckout()) {
LOG.error("Cannot pull, repository in state ${state.description}")
return null
}
var refToMerge = prefetchedRefToMerge ?: fetch() ?: return null
val mergeResult = merge(refToMerge, mergeStrategy, commitMessage = commitMessage)
val mergeStatus = mergeResult.status
LOG.debug { mergeStatus.toString() }
if (mergeStatus == MergeStatus.CONFLICTING) {
return resolveConflicts(mergeResult, repository)
}
else if (!mergeStatus.isSuccessful) {
throw IllegalStateException(mergeResult.toString())
}
else {
return mergeResult.result
}
}
fun fetch(prevRefUpdateResult: RefUpdate.Result? = null): Ref? {
indicator?.checkCanceled()
val fetchResult = repository.fetch(remoteConfig, manager.credentialsProvider, indicator.asProgressMonitor()) ?: return null
if (LOG.isDebugEnabled) {
printMessages(fetchResult)
for (refUpdate in fetchResult.trackingRefUpdates) {
LOG.debug(refUpdate.toString())
}
}
indicator?.checkCanceled()
var hasChanges = false
for (fetchRefSpec in remoteConfig.fetchRefSpecs) {
val refUpdate = fetchResult.getTrackingRefUpdate(fetchRefSpec.destination)
if (refUpdate == null) {
LOG.debug("No ref update for $fetchRefSpec")
continue
}
val refUpdateResult = refUpdate.result
// we can have more than one fetch ref spec, but currently we don't worry about it
if (refUpdateResult == RefUpdate.Result.LOCK_FAILURE || refUpdateResult == RefUpdate.Result.IO_FAILURE) {
if (prevRefUpdateResult == refUpdateResult) {
throw IOException("Ref update result ${refUpdateResult.name()}, we have already tried to fetch again, but no luck")
}
LOG.warn("Ref update result ${refUpdateResult.name()}, trying again after 500 ms")
Thread.sleep(500)
return fetch(refUpdateResult)
}
if (!(refUpdateResult == RefUpdate.Result.FAST_FORWARD || refUpdateResult == RefUpdate.Result.NEW || refUpdateResult == RefUpdate.Result.FORCED)) {
throw UnsupportedOperationException("Unsupported ref update result")
}
if (!hasChanges) {
hasChanges = refUpdateResult != RefUpdate.Result.NO_CHANGE
}
}
if (!hasChanges) {
LOG.debug("No remote changes")
return null
}
return fetchResult.getAdvertisedRef(config.getRemoteBranchFullName()) ?: throw IllegalStateException("Could not get advertised ref")
}
fun merge(unpeeledRef: Ref,
mergeStrategy: MergeStrategy = MergeStrategy.RECURSIVE,
commit: Boolean = true,
fastForwardMode: FastForwardMode = FastForwardMode.FF,
squash: Boolean = false,
forceMerge: Boolean = false,
commitMessage: String? = null): MergeResultEx {
indicator?.checkCanceled()
val head = repository.getRef(Constants.HEAD) ?: throw NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported)
// handle annotated tags
val ref = repository.peel(unpeeledRef)
val objectId = ref.peeledObjectId ?: ref.objectId
// Check for FAST_FORWARD, ALREADY_UP_TO_DATE
val revWalk = RevWalk(repository)
var dirCacheCheckout: DirCacheCheckout? = null
try {
val srcCommit = revWalk.lookupCommit(objectId)
val headId = head.objectId
if (headId == null) {
revWalk.parseHeaders(srcCommit)
dirCacheCheckout = DirCacheCheckout(repository, repository.lockDirCache(), srcCommit.tree)
dirCacheCheckout.setFailOnConflict(true)
dirCacheCheckout.checkout()
val refUpdate = repository.updateRef(head.target.name)
refUpdate.setNewObjectId(objectId)
refUpdate.setExpectedOldObjectId(null)
refUpdate.setRefLogMessage("initial pull", false)
if (refUpdate.update() != RefUpdate.Result.NEW) {
throw NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported)
}
return MergeResultEx(MergeStatus.FAST_FORWARD, arrayOf(null, srcCommit), ImmutableUpdateResult(dirCacheCheckout.updated.keySet(), dirCacheCheckout.removed))
}
val refLogMessage = StringBuilder("merge ")
refLogMessage.append(ref.name)
val headCommit = revWalk.lookupCommit(headId)
if (!forceMerge && revWalk.isMergedInto(srcCommit, headCommit)) {
return MergeResultEx(MergeStatus.ALREADY_UP_TO_DATE, arrayOf<ObjectId?>(headCommit, srcCommit), EMPTY_UPDATE_RESULT)
}
else if (!forceMerge && fastForwardMode != FastForwardMode.NO_FF && revWalk.isMergedInto(headCommit, srcCommit)) {
// FAST_FORWARD detected: skip doing a real merge but only update HEAD
refLogMessage.append(": ").append(MergeStatus.FAST_FORWARD)
dirCacheCheckout = DirCacheCheckout(repository, headCommit.tree, repository.lockDirCache(), srcCommit.tree)
dirCacheCheckout.setFailOnConflict(true)
dirCacheCheckout.checkout()
val mergeStatus: MergeStatus
if (squash) {
mergeStatus = MergeStatus.FAST_FORWARD_SQUASHED
val squashedCommits = RevWalkUtils.find(revWalk, srcCommit, headCommit)
repository.writeSquashCommitMsg(SquashMessageFormatter().format(squashedCommits, head))
}
else {
updateHead(refLogMessage, srcCommit, headId, repository)
mergeStatus = MergeStatus.FAST_FORWARD
}
return MergeResultEx(mergeStatus, arrayOf<ObjectId?>(headCommit, srcCommit), ImmutableUpdateResult(dirCacheCheckout.updated.keySet(), dirCacheCheckout.removed))
}
else {
if (fastForwardMode == FastForwardMode.FF_ONLY) {
return MergeResultEx(MergeStatus.ABORTED, arrayOf<ObjectId?>(headCommit, srcCommit), EMPTY_UPDATE_RESULT)
}
val mergeMessage: String
if (squash) {
mergeMessage = ""
repository.writeSquashCommitMsg(SquashMessageFormatter().format(RevWalkUtils.find(revWalk, srcCommit, headCommit), head))
}
else {
mergeMessage = commitMessageFormatter.mergeMessage(listOf(ref), head)
repository.writeMergeCommitMsg(mergeMessage)
repository.writeMergeHeads(listOf(ref.objectId))
}
val merger = mergeStrategy.newMerger(repository)
val noProblems: Boolean
var lowLevelResults: Map<String, org.eclipse.jgit.merge.MergeResult<out Sequence>>? = null
var failingPaths: Map<String, ResolveMerger.MergeFailureReason>? = null
var unmergedPaths: List<String>? = null
if (merger is ResolveMerger) {
merger.commitNames = arrayOf("BASE", "HEAD", ref.name)
merger.setWorkingTreeIterator(FileTreeIterator(repository))
noProblems = merger.merge(headCommit, srcCommit)
lowLevelResults = merger.mergeResults
failingPaths = merger.failingPaths
unmergedPaths = merger.unmergedPaths
}
else {
noProblems = merger.merge(headCommit, srcCommit)
}
refLogMessage.append(": Merge made by ")
refLogMessage.append(if (revWalk.isMergedInto(headCommit, srcCommit)) "recursive" else mergeStrategy.name)
refLogMessage.append('.')
var result = if (merger is ResolveMerger) ImmutableUpdateResult(merger.toBeCheckedOut.keySet(), merger.toBeDeleted) else null
if (noProblems) {
// ResolveMerger does checkout
if (merger !is ResolveMerger) {
dirCacheCheckout = DirCacheCheckout(repository, headCommit.tree, repository.lockDirCache(), merger.resultTreeId)
dirCacheCheckout.setFailOnConflict(true)
dirCacheCheckout.checkout()
result = ImmutableUpdateResult(dirCacheCheckout.updated.keySet(), dirCacheCheckout.removed)
}
var mergeStatus: MergeResult.MergeStatus? = null
if (!commit && squash) {
mergeStatus = MergeResult.MergeStatus.MERGED_SQUASHED_NOT_COMMITTED
}
if (!commit && !squash) {
mergeStatus = MergeResult.MergeStatus.MERGED_NOT_COMMITTED
}
if (commit && !squash) {
repository.commit(commitMessage, refLogMessage.toString()).id
mergeStatus = MergeResult.MergeStatus.MERGED
}
if (commit && squash) {
mergeStatus = MergeResult.MergeStatus.MERGED_SQUASHED
}
return MergeResultEx(mergeStatus!!, arrayOf(headCommit.id, srcCommit.id), result!!)
}
else if (failingPaths == null) {
repository.writeMergeCommitMsg(MergeMessageFormatter().formatWithConflicts(mergeMessage, unmergedPaths))
return MergeResultEx(MergeResult.MergeStatus.CONFLICTING, arrayOf(headCommit.id, srcCommit.id), result!!, lowLevelResults)
}
else {
repository.writeMergeCommitMsg(null)
repository.writeMergeHeads(null)
return MergeResultEx(MergeResult.MergeStatus.FAILED, arrayOf(headCommit.id, srcCommit.id), result!!, lowLevelResults)
}
}
}
catch (e: org.eclipse.jgit.errors.CheckoutConflictException) {
throw CheckoutConflictException(dirCacheCheckout?.conflicts ?: listOf(), e)
}
finally {
revWalk.close()
}
}
}
class MergeResultEx(val status: MergeStatus, val mergedCommits: Array<ObjectId?>, val result: ImmutableUpdateResult, val conflicts: Map<String, org.eclipse.jgit.merge.MergeResult<out Sequence>>? = null)
private fun updateHead(refLogMessage: StringBuilder, newHeadId: ObjectId, oldHeadID: ObjectId, repository: Repository) {
val refUpdate = repository.updateRef(Constants.HEAD)
refUpdate.setNewObjectId(newHeadId)
refUpdate.setRefLogMessage(refLogMessage.toString(), false)
refUpdate.setExpectedOldObjectId(oldHeadID)
val rc = refUpdate.update()
when (rc) {
RefUpdate.Result.NEW, RefUpdate.Result.FAST_FORWARD -> return
RefUpdate.Result.REJECTED, RefUpdate.Result.LOCK_FAILURE -> throw ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, refUpdate.ref, rc)
else -> throw JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed, Constants.HEAD, newHeadId.toString(), rc))
}
}
private fun resolveConflicts(mergeResult: MergeResultEx, repository: Repository): MutableUpdateResult {
assert(mergeResult.mergedCommits.size() == 2)
val conflicts = mergeResult.conflicts!!
val mergeProvider = JGitMergeProvider(repository, conflicts, { path, index ->
val rawText = get(path)!!.getSequences().get(index) as RawText
// RawText.EMPTY_TEXT if content is null - deleted
if (rawText == RawText.EMPTY_TEXT) null else rawText.content
})
val mergedFiles = resolveConflicts(mergeProvider, conflictsToVirtualFiles(conflicts), repository)
return mergeResult.result.toMutable().addChanged(mergedFiles)
}
private fun resolveConflicts(mergeProvider: JGitMergeProvider<out Any>, unresolvedFiles: MutableList<VirtualFile>, repository: Repository): List<String> {
val mergedFiles = SmartList<String>()
while (true) {
val resolvedFiles = resolveConflicts(unresolvedFiles, mergeProvider)
for (file in resolvedFiles) {
mergedFiles.add(file.path)
}
if (resolvedFiles.size == unresolvedFiles.size) {
break
}
else {
unresolvedFiles.removeAll(mergedFiles)
}
}
// merge commit template will be used, so, we don't have to specify commit message explicitly
repository.commit()
return mergedFiles
}
internal fun Repository.fixAndGetState(): RepositoryState {
var state = repositoryState
if (state == RepositoryState.MERGING) {
resolveUnmergedConflicts(this)
// compute new state
state = repositoryState
}
return state
}
internal fun resolveUnmergedConflicts(repository: Repository) {
val conflicts = LinkedHashMap<String, Array<ByteArray?>>()
repository.newObjectReader().use { reader ->
val dirCache = repository.readDirCache()
for (i in 0..(dirCache.entryCount - 1)) {
val entry = dirCache.getEntry(i)
if (!entry.isMerged) {
conflicts.getOrPut(entry.pathString, { arrayOfNulls<ByteArray>(3) })[entry.stage - 1] = reader.open(entry.objectId, Constants.OBJ_BLOB).cachedBytes
}
}
}
resolveConflicts(JGitMergeProvider(repository, conflicts, { path, index -> get(path)!!.get(index) }), conflictsToVirtualFiles(conflicts), repository)
} | apache-2.0 | a57762712715f23ef0c9e33a528dfe00 | 42.286127 | 202 | 0.716814 | 4.691729 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/PanelBuilder.kt | 1 | 14383 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.dsl.builder.impl
import com.intellij.openapi.ui.DialogPanel
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.gridLayout.*
import com.intellij.ui.dsl.gridLayout.builders.RowsGridBuilder
import org.jetbrains.annotations.ApiStatus
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JRadioButton
import javax.swing.JToggleButton
import kotlin.math.min
@ApiStatus.Internal
internal class PanelBuilder(val rows: List<RowImpl>, private val dialogPanelConfig: DialogPanelConfig,
val spacingConfiguration: SpacingConfiguration,
val panel: DialogPanel, val grid: Grid) {
fun build() {
if (rows.isEmpty()) {
return
}
preprocess()
val maxColumnsCount = getMaxColumnsCount()
val rowsGridBuilder = RowsGridBuilder(panel, grid = grid)
.defaultVerticalAlign(VerticalAlign.CENTER)
.defaultBaselineAlign(true)
val allRowsGaps = getRowsGaps(rows)
for ((i, row) in rows.withIndex()) {
if (!checkRow(row)) {
continue
}
val rowGaps = allRowsGaps[i]
rowsGridBuilder.setRowGaps(VerticalGaps(top = rowGaps.top))
val subRowVerticalAlign = if (row.resizableRow) VerticalAlign.FILL else VerticalAlign.CENTER
when (row.rowLayout) {
RowLayout.INDEPENDENT -> {
val subGridBuilder = rowsGridBuilder.subGridBuilder(width = maxColumnsCount,
horizontalAlign = HorizontalAlign.FILL,
verticalAlign = subRowVerticalAlign,
gaps = Gaps(left = row.getIndent()))
val cells = row.cells
buildLabelRow(cells, 0, cells.size, row.rowLayout, subGridBuilder)
subGridBuilder.resizableRow()
buildRow(cells, 0, cells.size, panel, subGridBuilder)
subGridBuilder.row()
buildCommentRow(cells, 0, cells.size, row.rowLayout, subGridBuilder)
setLastColumnResizable(subGridBuilder)
if (row.resizableRow) {
rowsGridBuilder.resizableRow()
}
rowsGridBuilder.row()
}
RowLayout.LABEL_ALIGNED -> {
buildLabelRow(row.cells, row.getIndent(), maxColumnsCount, row.rowLayout, rowsGridBuilder)
buildCell(row.cells[0], isLabelGap(row.cells.getOrNull(1)), row.getIndent(), row.cells.size == 1, 1, panel, rowsGridBuilder)
if (row.cells.size > 1) {
val subGridBuilder = rowsGridBuilder.subGridBuilder(width = maxColumnsCount - 1,
horizontalAlign = HorizontalAlign.FILL,
verticalAlign = subRowVerticalAlign)
.resizableRow()
val cells = row.cells.subList(1, row.cells.size)
buildRow(cells, 0, cells.size, panel, subGridBuilder)
setLastColumnResizable(subGridBuilder)
}
if (row.resizableRow) {
rowsGridBuilder.resizableRow()
}
rowsGridBuilder.row()
buildCommentRow(row.cells, row.getIndent(), maxColumnsCount, row.rowLayout, rowsGridBuilder)
}
RowLayout.PARENT_GRID -> {
buildLabelRow(row.cells, row.getIndent(), maxColumnsCount, row.rowLayout, rowsGridBuilder)
buildRow(row.cells, row.getIndent(), maxColumnsCount, panel, rowsGridBuilder)
if (row.resizableRow) {
rowsGridBuilder.resizableRow()
}
rowsGridBuilder.row()
buildCommentRow(row.cells, row.getIndent(), maxColumnsCount, row.rowLayout, rowsGridBuilder)
}
}
row.rowComment?.let {
val gaps = Gaps(left = row.getIndent(), bottom = spacingConfiguration.verticalComponentGap)
rowsGridBuilder.cell(it, maxColumnsCount, gaps = gaps)
rowsGridBuilder.row()
}
val rowsGaps = rowsGridBuilder.grid.rowsGaps
rowsGaps[rowsGaps.size - 2] = rowsGaps[rowsGaps.size - 2].copy(bottom = rowGaps.bottom)
}
setLastColumnResizable(rowsGridBuilder)
checkNoDoubleRowGaps(grid)
}
/**
* Preprocesses rows/cells and adds necessary rows/cells
* 1. Labels, see [Cell.label]
*/
private fun preprocess() {
for (row in rows) {
var i = 0
while (i < row.cells.size) {
val cell = row.cells[i]
if (cell is CellImpl<*>) {
cell.label?.let {
if (cell.labelPosition == LabelPosition.LEFT) {
val labelCell = CellImpl(dialogPanelConfig, it, row)
row.cells.add(i, labelCell)
i++
}
if (isAllowedLabel(cell)) {
labelCell(it, cell)
}
else {
warn("Unsupported labeled component: ${cell.component.javaClass.name}")
}
}
}
i++
}
}
}
/**
* According to https://jetbrains.design/intellij/principles/layout/#checkboxes-and-radio-buttons
* space between label and CheckBox/RadioButton should be increased
*/
private fun isLabelGap(cellAfterLabel: CellBaseImpl<*>?): Boolean {
val component = (cellAfterLabel as? CellImpl<*>)?.component
return !(component is JCheckBox || component is JRadioButton)
}
private fun setLastColumnResizable(builder: RowsGridBuilder) {
if (builder.resizableColumns.isEmpty() && builder.columnsCount > 0) {
builder.resizableColumns.add(builder.columnsCount - 1)
}
}
private fun checkRow(row: RowImpl): Boolean {
if (row.cells.isEmpty()) {
warn("Row should not be empty")
return false
}
return true
}
private fun checkNoDoubleRowGaps(grid: Grid) {
val gaps = grid.rowsGaps
for (i in gaps.indices) {
if (i > 0 && gaps[i - 1].bottom > 0 && gaps[i].top > 0) {
warn("There is double gap between two near rows")
}
}
}
private fun buildRow(cells: List<CellBaseImpl<*>?>,
firstCellIndent: Int,
maxColumnsCount: Int,
panel: DialogPanel,
builder: RowsGridBuilder) {
for ((cellIndex, cell) in cells.withIndex()) {
val lastCell = cellIndex == cells.size - 1
val width = if (lastCell) maxColumnsCount - cellIndex else 1
val leftGap = if (cellIndex == 0) firstCellIndent else 0
val isLabel = cell is CellImpl<*> && (cell.component.getClientProperty(DslComponentProperty.ROW_LABEL) == true ||
cell.component.getClientProperty(DslComponentPropertyInternal.CELL_LABEL) == true)
buildCell(cell, isLabel && isLabelGap(cells.getOrNull(cellIndex + 1)), leftGap, lastCell, width, panel, builder)
}
}
private fun buildCell(cell: CellBaseImpl<*>?, isLabelGap: Boolean, leftGap: Int, lastCell: Boolean, width: Int,
panel: DialogPanel, builder: RowsGridBuilder) {
val rightGap = getRightGap(cell, lastCell, isLabelGap)
when (cell) {
is CellImpl<*> -> {
val gaps = cell.customGaps ?: getComponentGaps(leftGap, rightGap, cell.component, spacingConfiguration)
builder.cell(cell.viewComponent, width = width, horizontalAlign = cell.horizontalAlign, verticalAlign = cell.verticalAlign,
resizableColumn = cell.resizableColumn,
gaps = gaps, visualPaddings = prepareVisualPaddings(cell.viewComponent.origin),
widthGroup = cell.widthGroup)
}
is PanelImpl -> {
// todo visualPaddings
val gaps = cell.customGaps ?: Gaps(left = leftGap, right = rightGap)
val subGrid = builder.subGrid(width = width, horizontalAlign = cell.horizontalAlign, verticalAlign = cell.verticalAlign,
resizableColumn = cell.resizableColumn, gaps = gaps)
val subBuilder = PanelBuilder(cell.rows, dialogPanelConfig, cell.spacingConfiguration, panel, subGrid)
subBuilder.build()
}
is PlaceholderBaseImpl -> {
val gaps = cell.customGaps ?: Gaps(left = leftGap, right = rightGap)
if (cell.resizableColumn) {
builder.addResizableColumn()
}
val constraints = builder.constraints(width = width, horizontalAlign = cell.horizontalAlign, verticalAlign = cell.verticalAlign,
gaps = gaps)
cell.init(panel, constraints, spacingConfiguration)
}
else -> {
builder.skip(1)
}
}
}
private fun getMaxColumnsCount(): Int {
return rows.maxOf {
when (it.rowLayout) {
RowLayout.INDEPENDENT -> 1
RowLayout.LABEL_ALIGNED -> min(2, it.cells.size)
RowLayout.PARENT_GRID -> it.cells.size
}
}
}
private fun getRightGap(cell: CellBaseImpl<*>?, lastCell: Boolean, isLabelGap: Boolean): Int {
if (cell == null) {
return 0
}
val rightGap = cell.rightGap
if (lastCell) {
// Right gap is ignored for the last cell in a row
return 0
}
if (rightGap != null) {
return when (rightGap) {
RightGap.SMALL -> spacingConfiguration.horizontalSmallGap
RightGap.COLUMNS -> spacingConfiguration.horizontalColumnsGap
}
}
return if (isLabelGap) spacingConfiguration.horizontalSmallGap else spacingConfiguration.horizontalDefaultGap
}
/**
* Appends row with cell labels, which are marked as [LabelPosition.TOP]
*/
private fun buildLabelRow(cells: List<CellBaseImpl<*>?>,
firstCellIndent: Int,
maxColumnsCount: Int,
layout: RowLayout,
builder: RowsGridBuilder) {
val columnsAndLabels = cells.mapIndexedNotNull { index, cell ->
val cellImpl = cell as? CellImpl<*>
val label = cellImpl?.label
if (label == null || cellImpl.labelPosition != LabelPosition.TOP ||
(layout == RowLayout.LABEL_ALIGNED && index > 1)) {
null
}
else {
val left = if (index == 0) firstCellIndent else 0
GeneratedComponentData(label, Gaps(top = getDefaultVerticalGap(label, spacingConfiguration), left = left), index)
}
}
buildRow(columnsAndLabels, maxColumnsCount, VerticalAlign.BOTTOM, builder)
}
/**
* Appends row with cell comments
*/
private fun buildCommentRow(cells: List<CellBaseImpl<*>?>,
firstCellIndent: Int,
maxColumnsCount: Int,
layout: RowLayout,
builder: RowsGridBuilder) {
var columnsAndComments = cells.mapIndexedNotNull { index, cell ->
val cellImpl = cell as? CellImpl<*>
val comment = cellImpl?.comment
if (comment == null) {
null
}
else {
val left = getAdditionalHorizontalIndent(cell) + (if (index == 0) firstCellIndent else 0)
GeneratedComponentData(comment, Gaps(left = left, bottom = spacingConfiguration.verticalComponentGap), index)
}
}
// LABEL_ALIGNED: Always put comment for cells with index more than 1 at second cell because it's hard to implement
// more correct behaviour now. Can be fixed later
if (layout == RowLayout.LABEL_ALIGNED) {
val index = columnsAndComments.indexOfFirst { it.column >= 1 }
if (index >= 0) {
val mutableColumnsAndComments = columnsAndComments.subList(0, index + 1).toMutableList()
val lastData = mutableColumnsAndComments[index]
if (lastData.column > 1) {
mutableColumnsAndComments[index] = lastData.copy(column = 1, gaps = lastData.gaps.copy(left = 0))
}
columnsAndComments = mutableColumnsAndComments
}
}
buildRow(columnsAndComments, maxColumnsCount, VerticalAlign.TOP, builder)
}
/**
* Builds row with provided components from [columnsAndComponents]
*/
private fun buildRow(columnsAndComponents: List<GeneratedComponentData>,
maxColumnsCount: Int,
verticalAlign: VerticalAlign,
builder: RowsGridBuilder) {
if (columnsAndComponents.isEmpty()) {
return
}
builder.skip(columnsAndComponents[0].column)
for ((i, data) in columnsAndComponents.withIndex()) {
val nextColumn = if (i + 1 < columnsAndComponents.size) columnsAndComponents[i + 1].column else maxColumnsCount
builder.cell(data.component, nextColumn - data.column, verticalAlign = verticalAlign, baselineAlign = false, gaps = data.gaps)
}
builder.row()
}
private fun getAdditionalHorizontalIndent(cell: CellBaseImpl<*>?): Int {
return if (cell is CellImpl<*> && cell.viewComponent is JToggleButton)
spacingConfiguration.horizontalToggleButtonIndent
else
0
}
private fun getRowsGaps(rows: List<RowImpl>): List<VerticalGaps> {
val result = mutableListOf<VerticalGaps>()
for ((i, row) in rows.withIndex()) {
val rowGaps = getRowGaps(row, i == 0, i == rows.size - 1)
result.add(rowGaps)
// Only greatest gap of top and bottom gaps is used between two rows (or top gap if equal)
if (i > 0) {
val previousRowGaps = result[i - 1]
if (previousRowGaps.bottom != 0 && rowGaps.top != 0) {
if (previousRowGaps.bottom > rowGaps.top) {
result[i] = rowGaps.copy(top = 0)
}
else {
result[i - 1] = previousRowGaps.copy(bottom = 0)
}
}
}
}
return result
}
private fun getRowGaps(row: RowImpl, first: Boolean, last: Boolean): VerticalGaps {
val top = when (row.topGap) {
TopGap.NONE -> 0
TopGap.SMALL -> spacingConfiguration.verticalSmallGap
TopGap.MEDIUM -> spacingConfiguration.verticalMediumGap
null -> if (first) 0 else row.internalTopGap
}
val bottom = when (row.bottomGap) {
BottomGap.NONE -> 0
BottomGap.SMALL -> spacingConfiguration.verticalSmallGap
BottomGap.MEDIUM -> spacingConfiguration.verticalMediumGap
null -> if (last) 0 else row.internalBottomGap
}
return if (top > 0 || bottom > 0) VerticalGaps(top = top, bottom = bottom) else VerticalGaps.EMPTY
}
}
private data class GeneratedComponentData(val component: JComponent, val gaps: Gaps, val column: Int)
| apache-2.0 | 74aad54e12ba234d39a50de1bdcc4702 | 35.691327 | 158 | 0.631162 | 4.447434 | false | true | false | false |
dzharkov/intellij-markdown | src/org/intellij/markdown/parser/sequentialparsers/SequentialParserUtil.kt | 1 | 2283 | package org.intellij.markdown.parser.sequentialparsers
import org.intellij.markdown.MarkdownTokenTypes
import java.util.ArrayList
public class SequentialParserUtil {
companion object {
public fun textRangesToIndices(ranges: Collection<Range<Int>>): List<Int> {
val result = ArrayList<Int>()
for (range in ranges) {
for (i in range.start..range.end - 1) {
result.add(i)
}
}
result.sorted()
return result
}
public fun indicesToTextRanges(indices: List<Int>): Collection<Range<Int>> {
val result = ArrayList<Range<Int>>()
var starting = 0
for (i in indices.indices) {
if (i + 1 == indices.size() || indices.get(i) + 1 != indices.get(i + 1)) {
result.add(indices.get(starting)..indices.get(i) + 1)
starting = i + 1
}
}
return result
}
public fun isWhitespace(info: TokensCache.Iterator, lookup: Int): Boolean {
val `type` = info.rawLookup(lookup)
if (`type` == null) {
return false
}
if (`type` == MarkdownTokenTypes.EOL || `type` == MarkdownTokenTypes.WHITE_SPACE) {
return true
}
if (lookup == -1) {
return info.rollback().text.endsWith(' ', ignoreCase = false)
} else {
return info.advance().text.startsWith(' ', ignoreCase = false)
}
}
public fun filterBlockquotes(tokensCache: TokensCache, textRange: Range<Int>): Collection<Range<Int>> {
val result = ArrayList<Range<Int>>()
var lastStart = textRange.start
val R = textRange.end
for (i in lastStart..R - 1) {
if (tokensCache.Iterator(i).type == MarkdownTokenTypes.BLOCK_QUOTE) {
if (lastStart < i) {
result.add(lastStart..i)
}
lastStart = i + 1
}
}
if (lastStart < R) {
result.add(lastStart..R)
}
return result
}
}
}
| apache-2.0 | 92e9c4fe89704d300fa3dd60d52b6b00 | 32.086957 | 111 | 0.491021 | 4.726708 | false | false | false | false |
eugenkiss/kotlinfx | kotlinfx-core/src/main/kotlin/kotlinfx/builders/Text.kt | 2 | 1089 | // http://docs.oracle.com/javase/8/javafx/api/javafx/scene/text/package-summary.html
package kotlinfx.builders
// For javafx.scene.text.Font a builder does not make sense.
public fun Text(
f: javafx.scene.text.Text.() -> Unit = {}): javafx.scene.text.Text
{
val x = javafx.scene.text.Text()
x.f()
return x
}
public fun Text(
text: String,
f: javafx.scene.text.Text.() -> Unit = {}): javafx.scene.text.Text
{
val x = javafx.scene.text.Text(text)
x.f()
return x
}
public fun Text(
x: Double,
y: Double,
text: String,
f: javafx.scene.text.Text.() -> Unit = {}): javafx.scene.text.Text
{
val z = javafx.scene.text.Text(x, y, text)
z.f()
return z
}
public fun TextFlow(
vararg children: javafx.scene.Node?,
f: javafx.scene.text.TextFlow.() -> Unit = {}): javafx.scene.text.TextFlow
{
val x = javafx.scene.text.TextFlow(*children)
x.f()
return x
}
public fun TextFlow(
vararg children: javafx.scene.Node?): javafx.scene.text.TextFlow
{
val x = javafx.scene.text.TextFlow(*children)
return x
}
| mit | ab8145816c66824785aed7e140831a11 | 21.6875 | 84 | 0.6382 | 3.09375 | false | false | false | false |
JetBrains/intellij-community | platform/testFramework/src/com/intellij/testFramework/TemporaryDirectory.kt | 1 | 7452 | // 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.testFramework
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.common.runAllCatching
import com.intellij.util.SmartList
import com.intellij.util.io.Ksuid
import com.intellij.util.io.delete
import com.intellij.util.io.exists
import com.intellij.util.io.sanitizeFileName
import org.jetbrains.annotations.ApiStatus
import org.junit.jupiter.api.extension.AfterEachCallback
import org.junit.jupiter.api.extension.BeforeEachCallback
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.rules.ExternalResource
import org.junit.runner.Description
import org.junit.runners.model.Statement
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.function.Predicate
import kotlin.properties.Delegates
/**
* Provides the possibility to create a temporary directory during a test.
* The directory is not actually created by default; call [createDir] to do that.
*
* * The `fileName` argument is not used as is for generated file or dir name - sortable UID is added as suffix.
* * `hello.kt` will be created as `hello_1eSBtxBR5522COEjhRLR6AEz.kt`.
* * `.kt` will be created as `1eSBtxBR5522COEjhRLR6AEz.kt`.
*/
open class TemporaryDirectory : ExternalResource() {
private val paths = SmartList<Path>()
private var sanitizedName: String by Delegates.notNull()
private var virtualFileRoot: VirtualFile? = null
private var root: Path? = null
companion object {
@JvmStatic
@JvmOverloads
fun generateTemporaryPath(fileName: String, root: Path = Paths.get(FileUtilRt.getTempDirectory())): Path {
val path = root.resolve(generateName(fileName))
if (path.exists()) {
throw IllegalStateException("Path $path must be unique but already exists")
}
return path
}
@JvmStatic
fun testNameToFileName(name: String): String {
// remove prefix `test` or `test `
// ` symbols causes git tests failures, even if it is a valid symbol for file name
return sanitizeFileName(name.removePrefix("test").trimStart(), extraIllegalChars = Predicate { it == ' ' || it == '\'' })
}
@JvmStatic
@ApiStatus.Internal
fun createVirtualFile(parent: VirtualFile, exactFileName: String, data: String?): VirtualFile {
return WriteAction.computeAndWait<VirtualFile, IOException> {
val result = parent.createChildData(TemporaryDirectory::class.java, exactFileName)
if (!data.isNullOrEmpty()) {
result.setBinaryContent(data.toByteArray(Charsets.UTF_8))
}
result
}
}
}
override fun apply(base: Statement, description: Description): Statement {
before(description.methodName ?: description.className)
return super.apply(base, description)
}
protected fun before(testName: String) {
sanitizedName = testNameToFileName(testName)
root = Paths.get(FileUtilRt.getTempDirectory())
}
@ApiStatus.Internal
fun init(commonPrefix: String, root: Path) {
if (this.root != null) {
throw IllegalStateException("Already initialized (root=${this.root})")
}
sanitizedName = commonPrefix
this.root = root
}
private fun getVirtualRoot(): VirtualFile {
var result = virtualFileRoot
if (result == null) {
val nioRoot = root!!
Files.createDirectories(nioRoot)
result = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(nioRoot)
?: throw IllegalStateException("Cannot find virtual file by $nioRoot")
virtualFileRoot = result
}
return result
}
override fun after() {
virtualFileRoot = null
root = null
if (paths.isEmpty()) {
return
}
val error = runAllCatching(paths.asReversed()) {
it.delete()
}
paths.clear()
error?.let { throw it }
}
@JvmOverloads
fun newPath(fileName: String? = null, refreshVfs: Boolean = false): Path {
val path = generatePath(fileName)
if (refreshVfs) {
path.refreshVfs()
}
return path
}
/**
* Use only if you really need a virtual file and not possible to use [Path] (see [newPath]).
*/
@JvmOverloads
fun createVirtualFile(fileName: String? = null, data: String? = null): VirtualFile {
val result = createVirtualFile(getVirtualRoot(), generateName(fileName ?: ""), data)
paths.add(result.toNioPath())
return result
}
/**
* Use only and only if you really need virtual file and no way to use [Path] (see [newPath]).
*/
@JvmOverloads
fun createVirtualDir(dirName: String? = null): VirtualFile {
val virtualFileRoot = getVirtualRoot()
return WriteAction.computeAndWait<VirtualFile, IOException> {
val name = generateName(dirName ?: "")
val result = virtualFileRoot.createChildDirectory(TemporaryDirectory::class.java, name)
paths.add(result.toNioPath())
result
}
}
// temporary method for compatibility and reducing change set
fun createDir(): Path {
val file = newPath()
Files.createDirectories(file)
return file
}
@Deprecated(message = "Do not use, only for backward compatibility only.")
fun scheduleDelete(path: Path) {
paths.add(path)
}
private fun generatePath(suffix: String?): Path {
var fileName = sanitizedName
if (suffix != null) {
fileName = if (fileName.isEmpty()) suffix else "${fileName}_$suffix"
}
val path = generateTemporaryPath(fileName, root ?: throw IllegalStateException("not initialized yet"))
paths.add(path)
return path
}
}
fun VirtualFile.writeChild(relativePath: String, data: String) = VfsTestUtil.createFile(this, relativePath, data)
fun VirtualFile.writeChild(relativePath: String, data: ByteArray) = VfsTestUtil.createFile(this, relativePath, data)
fun Path.refreshVfs() {
// If a temp directory is reused from some previous test run, there might be cached children in its VFS. Ensure they're removed.
val virtualFile = (LocalFileSystem.getInstance() ?: return).refreshAndFindFileByNioFile(this) ?: return
VfsUtil.markDirtyAndRefresh(false, true, true, virtualFile)
}
private fun generateName(fileName: String): String {
// use unique postfix sortable by timestamp to avoid stale data in VFS and file exists check
// (file is not created at the moment of path generation)
val nameBuilder = StringBuilder(fileName.length + /* _ separator length */ 1 + Ksuid.MAX_ENCODED_LENGTH)
val extIndex = fileName.lastIndexOf('.')
if (fileName.isNotEmpty() && extIndex != 0) {
if (extIndex == -1) {
nameBuilder.append(fileName)
}
else {
nameBuilder.append(fileName, 0, extIndex)
}
nameBuilder.append('_')
}
nameBuilder.append(Ksuid.generate())
if (extIndex != -1) {
nameBuilder.append(fileName, extIndex, fileName.length)
}
return nameBuilder.toString()
}
class TemporaryDirectoryExtension : TemporaryDirectory(), BeforeEachCallback, AfterEachCallback {
override fun afterEach(context: ExtensionContext?) {
after()
}
override fun beforeEach(context: ExtensionContext) {
before(context.testMethod.map { it.name }.orElse(context.displayName))
}
} | apache-2.0 | a09f1965be04c4b246450dd4ca8bb21a | 33.031963 | 130 | 0.715244 | 4.325015 | false | true | false | false |
StephaneBg/ScoreIt | app/src/main/kotlin/com/sbgapps/scoreit/app/ui/scoreboard/ScoreBoardViewModel.kt | 1 | 2228 | /*
* Copyright 2020 Stéphane Baiget
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sbgapps.scoreit.app.ui.scoreboard
import com.sbgapps.scoreit.core.ui.BaseViewModel
import com.sbgapps.scoreit.data.interactor.ScoreBoardUseCase
import com.sbgapps.scoreit.data.model.PlayerPosition
import com.sbgapps.scoreit.data.model.ScoreBoard
import io.uniflow.core.flow.data.UIState
class ScoreBoardViewModel(private val useCase: ScoreBoardUseCase) : BaseViewModel() {
init {
action {
setState { Content(useCase.getScoreBoard()) }
}
}
fun incrementScore(increment: Int, player: PlayerPosition) {
action {
val currentInfo = getCurrentStateOrNull(Content::class)!!.scoreBoard
val newInfo = if (PlayerPosition.ONE == player) {
currentInfo.copy(scoreOne = currentInfo.scoreOne + increment)
} else {
currentInfo.copy(scoreTwo = currentInfo.scoreTwo + increment)
}
useCase.saveScoreBoard(newInfo)
setState { Content(newInfo) }
}
}
fun setPlayerName(name: String, player: PlayerPosition) {
action {
val currentInfo = getCurrentStateOrNull(Content::class)!!.scoreBoard
val newInfo = if (PlayerPosition.ONE == player) {
currentInfo.copy(nameOne = name)
} else {
currentInfo.copy(nameTwo = name)
}
useCase.saveScoreBoard(newInfo)
setState { Content(newInfo) }
}
}
fun reset() {
action {
setState { Content(useCase.reset()) }
}
}
}
data class Content(val scoreBoard: ScoreBoard) : UIState()
| apache-2.0 | 9a6f75b15e6bfefea3d7deb253fcc398 | 32.742424 | 85 | 0.653794 | 4.44511 | false | false | false | false |
tiarebalbi/okhttp | buildSrc/src/main/kotlin/deps.kt | 1 | 3799 | /*
* 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
*
* 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.
*/
object Versions {
const val animalSniffer = "1.19"
const val assertj = "3.15.0"
const val bnd = "5.1.2"
const val bouncycastle = "1.68"
const val brotli = "0.1.2"
const val checkstyle = "8.28"
const val conscrypt = "2.5.2"
const val corretto = "1.3.1"
const val equinox = "3.16.0"
const val findbugs = "3.0.2"
const val guava = "28.2-jre"
const val jnrUnixsocket = "0.28"
const val jsoup = "1.13.1"
const val junit = "4.13"
const val junit5 = "5.7.0"
const val kotlin = "1.4.31"
const val ktlint = "0.38.0"
const val moshi = "1.11.0"
const val okio = "3.0.0-alpha.4"
const val openjsse = "1.1.0"
const val picocli = "4.5.1"
}
object Dependencies {
const val android = "org.robolectric:android-all:11-robolectric-6757853"
const val animalSniffer = "org.codehaus.mojo:animal-sniffer-annotations:${Versions.animalSniffer}"
const val assertj = "org.assertj:assertj-core:${Versions.assertj}"
const val bnd = "biz.aQute.bnd:biz.aQute.bnd.gradle:${Versions.bnd}"
const val bndResolve = "biz.aQute.bnd:biz.aQute.resolve:${Versions.bnd}"
const val bouncycastle = "org.bouncycastle:bcprov-jdk15to18:${Versions.bouncycastle}"
const val bouncycastlepkix = "org.bouncycastle:bcpkix-jdk15to18:${Versions.bouncycastle}"
const val bouncycastletls = "org.bouncycastle:bctls-jdk15to18:${Versions.bouncycastle}"
const val brotli = "org.brotli:dec:${Versions.brotli}"
const val conscrypt = "org.conscrypt:conscrypt-openjdk-uber:${Versions.conscrypt}"
const val corretto = "software.amazon.cryptools:AmazonCorrettoCryptoProvider:${Versions.corretto}:linux-x86_64"
const val equinox = "org.eclipse.platform:org.eclipse.osgi:${Versions.equinox}"
const val guava = "com.google.guava:guava:${Versions.guava}"
const val hamcrest = "org.hamcrest:hamcrest-library:2.1"
const val jnrUnixsocket = "com.github.jnr:jnr-unixsocket:${Versions.jnrUnixsocket}"
const val jsoup = "org.jsoup:jsoup:${Versions.jsoup}"
const val jsr305 = "com.google.code.findbugs:jsr305:${Versions.findbugs}"
const val junit = "junit:junit:${Versions.junit}"
const val junit5Api = "org.junit.jupiter:junit-jupiter-api:${Versions.junit5}"
const val junit5JupiterEngine = "org.junit.jupiter:junit-jupiter-engine:${Versions.junit5}"
const val junit5JupiterParams = "org.junit.jupiter:junit-jupiter-params:${Versions.junit5}"
const val junit5VintageEngine = "org.junit.vintage:junit-vintage-engine:${Versions.junit5}"
const val junitPlatformConsole = "org.junit.platform:junit-platform-console:1.7.0"
const val kotlinStdlib = "org.jetbrains.kotlin:kotlin-stdlib:${Versions.kotlin}"
const val kotlinStdlibOsgi = "org.jetbrains.kotlin:kotlin-osgi-bundle:${Versions.kotlin}"
const val moshi = "com.squareup.moshi:moshi:${Versions.moshi}"
const val moshiKotlin = "com.squareup.moshi:moshi-kotlin-codegen:${Versions.moshi}"
const val okio = "com.squareup.okio:okio:${Versions.okio}"
const val okioFakeFileSystem = "com.squareup.okio:okio-fakefilesystem:${Versions.okio}"
const val openjsse = "org.openjsse:openjsse:${Versions.openjsse}"
const val picocli = "info.picocli:picocli:${Versions.picocli}"
object Kotlin {
const val version = "1.4.31"
}
}
| apache-2.0 | d462363eabd520fb6317d6deab30cbd4 | 48.337662 | 113 | 0.730455 | 3.205907 | false | false | false | false |
lomza/screenlookcount | app/src/main/java/com/totemsoft/screenlookcount/db/ScreenCounterDb.kt | 1 | 3184 | package com.totemsoft.screenlookcount.db
import android.arch.persistence.db.SupportSQLiteDatabase
import android.arch.persistence.room.Database
import android.arch.persistence.room.Room
import android.arch.persistence.room.RoomDatabase
import android.arch.persistence.room.migration.Migration
import android.content.Context
import android.util.Log
import com.totemsoft.screenlookcount.utils.C
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.schedulers.Schedulers
@Database(entities = [DayLookEntity::class], version = 2)
abstract class ScreenCounterDb : RoomDatabase() {
private var dbClearFlag = false
abstract fun dayLookDao(): DayLookDbDao
companion object {
@Volatile
private var INSTANCE: ScreenCounterDb? = null
private const val DB_NAME = "lookcount-db"
private val FROM_1_TO_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
// tables haven't changed, we're just moving from
// greenDAO impl to Room
}
}
fun getDatabase(context: Context): ScreenCounterDb =
INSTANCE ?: synchronized(this) {
INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(context.applicationContext,
ScreenCounterDb::class.java, DB_NAME)
.addMigrations(FROM_1_TO_2)
.build()
}
@Synchronized
fun getDayLook(date: String): Maybe<DayLookEntity> {
return if (dbClearFlag) {
Maybe.just(DayLookEntity(null, date, null, null, null))
} else {
dayLookDao().getDayLookByDate(date)
}
}
@Synchronized
fun addDayLook(dayLook: DayLookEntity): Disposable {
Log.d(C.TAG, "Insert/update daylook into the database.")
return Completable.fromAction {
dayLookDao().insert(dayLook)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeBy(
onComplete = {
Log.d(C.TAG, "addDayLook() insert() completed.")
}, onError = {
Log.e(C.TAG, "addDayLook() error: ${it.printStackTrace()}")
})
}
@Synchronized
fun dropDb() {
this.dbClearFlag = false
Completable.fromAction {
dayLookDao().deleteAll()
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeBy(
onError = {
Log.e(C.TAG, "dropDb() error: ${it.printStackTrace()}")
}
)
}
@Synchronized
fun setDbClearFlag(dbClearFlag: Boolean) {
this.dbClearFlag = dbClearFlag
}
}
| gpl-3.0 | a0a3c95ffec70f1d835381fdf1163d56 | 32.166667 | 87 | 0.594535 | 4.724036 | false | false | false | false |
Kotlin/kotlinx.coroutines | benchmarks/src/jmh/kotlin/benchmarks/ChannelSinkBenchmark.kt | 1 | 2278 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package benchmarks
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import org.openjdk.jmh.annotations.*
import java.util.concurrent.*
import kotlin.coroutines.*
@Warmup(iterations = 7, time = 1)
@Measurement(iterations = 5, time = 1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
@Fork(1)
open class ChannelSinkBenchmark {
private val tl = ThreadLocal.withInitial({ 42 })
private val tl2 = ThreadLocal.withInitial({ 239 })
private val unconfined = Dispatchers.Unconfined
private val unconfinedOneElement = Dispatchers.Unconfined + tl.asContextElement()
private val unconfinedTwoElements = Dispatchers.Unconfined + tl.asContextElement() + tl2.asContextElement()
@Benchmark
fun channelPipeline(): Int = runBlocking {
run(unconfined)
}
@Benchmark
fun channelPipelineOneThreadLocal(): Int = runBlocking {
run(unconfinedOneElement)
}
@Benchmark
fun channelPipelineTwoThreadLocals(): Int = runBlocking {
run(unconfinedTwoElements)
}
private suspend inline fun run(context: CoroutineContext): Int {
return Channel
.range(1, 10_000, context)
.filter(context) { it % 4 == 0 }
.fold(0) { a, b -> a + b }
}
private fun Channel.Factory.range(start: Int, count: Int, context: CoroutineContext) = GlobalScope.produce(context) {
for (i in start until (start + count))
send(i)
}
// Migrated from deprecated operators, are good only for stressing channels
private fun <E> ReceiveChannel<E>.filter(context: CoroutineContext = Dispatchers.Unconfined, predicate: suspend (E) -> Boolean): ReceiveChannel<E> =
GlobalScope.produce(context, onCompletion = { cancel() }) {
for (e in this@filter) {
if (predicate(e)) send(e)
}
}
private suspend inline fun <E, R> ReceiveChannel<E>.fold(initial: R, operation: (acc: R, E) -> R): R {
var accumulator = initial
consumeEach {
accumulator = operation(accumulator, it)
}
return accumulator
}
}
| apache-2.0 | ec3f85da335e7b40c79c3ec060884e24 | 31.084507 | 152 | 0.662862 | 4.306238 | false | false | false | false |
cortinico/myo-emg-visualizer | sensorgraphview/src/main/java/com/ncorti/myonnaise/sensorgraphview/SensorGraphView.kt | 1 | 4655 | package com.ncorti.myonnaise.sensorgraphview
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
/** Default point circle size */
private const val CIRCLE_SIZE_DEFAULT = 3
/** Now drawing point circle size */
private const val CIRCLE_SIZE_ACTUAL = 20
/** Graph size */
private const val MAX_DATA_SIZE = 150
private const val INITIAL_MAX_VALUE = 10.0f
private const val INITIAL_MIN_VALUE = -10.0f
class SensorGraphView(context: Context, attrs: AttributeSet) : View(context, attrs) {
var running = false
var channels = 0
set(value) {
field = value
normalizedPoints = arrayOf()
for (i in 0 until value) {
normalizedPoints += FloatArray(MAX_DATA_SIZE)
}
}
var maxValue = INITIAL_MAX_VALUE
var minValue = INITIAL_MIN_VALUE
val spread: Float
get() = maxValue - minValue
private val zeroLine: Float
get() = (0 - minValue) / spread
/** Paint brush for drawing samples */
private val rectPaints = arrayListOf<Paint>()
/** Paint brush for drawing info datas */
private val infoPaint: Paint
/** Matrix of points */
private var normalizedPoints: Array<FloatArray> = arrayOf()
/** Current index in matrix */
private var currentIndex = 0
init {
val colors = context.resources.getIntArray(R.array.graph_colors)
for (i in 0 until colors.size) {
val paint = Paint()
paint.color = Color.parseColor("#${Integer.toHexString(colors[i])}")
rectPaints += paint
}
infoPaint = Paint()
infoPaint.color = ContextCompat.getColor(context, R.color.graph_info)
infoPaint.textSize = context.resources
.getDimensionPixelSize(R.dimen.text_size).toFloat()
infoPaint.isAntiAlias = true
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val widthSize = MeasureSpec.getSize(widthMeasureSpec)
val heightSize = MeasureSpec.getSize(heightMeasureSpec)
val desiredWidth = suggestedMinimumWidth + paddingLeft + paddingRight
val width = when (MeasureSpec.getMode(widthMeasureSpec)) {
MeasureSpec.EXACTLY -> widthSize
MeasureSpec.AT_MOST -> Math.min(desiredWidth, widthSize)
MeasureSpec.UNSPECIFIED -> desiredWidth
else -> desiredWidth
}
val desiredHeight = suggestedMinimumHeight + paddingTop + paddingBottom
val height = when (MeasureSpec.getMode(heightMeasureSpec)) {
MeasureSpec.EXACTLY -> heightSize
MeasureSpec.AT_MOST -> Math.min(desiredHeight, heightSize)
MeasureSpec.UNSPECIFIED -> desiredHeight
else -> desiredHeight
}
setMeasuredDimension(width, height)
}
fun addPoint(points: FloatArray) {
for (i in 0 until channels) {
this.normalizedPoints[i][currentIndex] = (points[i] - minValue) / spread
}
currentIndex = (currentIndex + 1) % MAX_DATA_SIZE
invalidate()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val height = height
val width = width
val zeroLine = height - height * zeroLine
canvas.drawLine(0f, zeroLine, width.toFloat(), zeroLine, infoPaint)
if (normalizedPoints.isEmpty()) {
return
}
if (!running)
return
val pointSpan: Float = width.toFloat() / MAX_DATA_SIZE.toFloat()
var previousX = -1f
var previousY = -1f
for (i in 0 until channels) {
var currentX = pointSpan
for (j in 0 until MAX_DATA_SIZE) {
val y = height - height * normalizedPoints[i][j]
if (previousX != -1f && previousY != -1f) {
canvas.drawLine(previousX, previousY, currentX, y, rectPaints[i])
}
if (j == (currentIndex - 1) % MAX_DATA_SIZE) {
canvas.drawCircle(currentX, y, CIRCLE_SIZE_ACTUAL.toFloat(), infoPaint)
previousX = -1f
previousY = -1f
} else {
canvas.drawCircle(currentX, y, CIRCLE_SIZE_DEFAULT.toFloat(), rectPaints[i])
previousX = currentX
previousY = y
}
currentX += pointSpan
}
previousX = -1f
previousY = -1f
}
}
}
| mit | 34ff7759d3ff822041555d1030a69597 | 32.25 | 96 | 0.601074 | 4.65966 | false | false | false | false |
zdary/intellij-community | plugins/settings-repository/src/readOnlySourcesEditor.kt | 10 | 5586 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.settingsRepository
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.options.ConfigurableUi
import com.intellij.openapi.progress.runModalTask
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.components.dialog
import com.intellij.ui.layout.*
import com.intellij.util.Function
import com.intellij.util.containers.CollectionFactory
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.delete
import com.intellij.util.io.exists
import com.intellij.util.text.nullize
import com.intellij.util.text.trimMiddle
import com.intellij.util.ui.table.TableModelEditor
import org.jetbrains.settingsRepository.git.asProgressMonitor
import org.jetbrains.settingsRepository.git.cloneBare
import kotlin.properties.Delegates.notNull
private val COLUMNS = arrayOf(object : TableModelEditor.EditableColumnInfo<ReadonlySource, Boolean>() {
override fun getColumnClass() = Boolean::class.java
override fun valueOf(item: ReadonlySource) = item.active
override fun setValue(item: ReadonlySource, value: Boolean) {
item.active = value
}
},
object : TableModelEditor.EditableColumnInfo<ReadonlySource, String>() {
override fun valueOf(item: ReadonlySource) = item.url
override fun setValue(item: ReadonlySource, value: String) {
item.url = value
}
})
internal fun createReadOnlySourcesEditor(): ConfigurableUi<IcsSettings> {
val itemEditor = object : TableModelEditor.DialogItemEditor<ReadonlySource> {
override fun clone(item: ReadonlySource, forInPlaceEditing: Boolean) = ReadonlySource(item.url, item.active)
override fun getItemClass() = ReadonlySource::class.java
override fun edit(item: ReadonlySource, mutator: Function<in ReadonlySource, out ReadonlySource>, isAdd: Boolean) {
var urlField: TextFieldWithBrowseButton by notNull()
val panel = panel {
row(IcsBundle.message("readonly.sources.configuration.url.label")) {
urlField = textFieldWithBrowseButton(IcsBundle.message("readonly.sources.configuration.repository.chooser"),
fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor()).component
}
}
dialog(title = IcsBundle.message("readonly.sources.configuration.add.source"), panel = panel, focusedComponent = urlField) {
val url = urlField.text.nullize(true)
validateUrl(url, null)?.let {
return@dialog listOf(ValidationInfo(it))
}
mutator.`fun`(item).url = url
return@dialog null
}
.show()
}
override fun applyEdited(oldItem: ReadonlySource, newItem: ReadonlySource) {
newItem.url = oldItem.url
}
override fun isUseDialogToAdd() = true
}
val editor = TableModelEditor(COLUMNS, itemEditor, IcsBundle.message("readonly.sources.configuration.no.sources.configured"))
editor.reset(if (ApplicationManager.getApplication().isUnitTestMode) emptyList() else icsManager.settings.readOnlySources)
return object : ConfigurableUi<IcsSettings> {
override fun isModified(settings: IcsSettings) = editor.isModified
override fun apply(settings: IcsSettings) {
val oldList = settings.readOnlySources
val toDelete = CollectionFactory.createSmallMemoryFootprintSet<String>(oldList.size)
for (oldSource in oldList) {
ContainerUtil.addIfNotNull(toDelete, oldSource.path)
}
val toCheckout = CollectionFactory.createSmallMemoryFootprintSet<ReadonlySource>()
val newList = editor.apply()
for (newSource in newList) {
val path = newSource.path
if (path != null && !toDelete.remove(path)) {
toCheckout.add(newSource)
}
}
if (toDelete.isEmpty() && toCheckout.isEmpty()) {
return
}
runModalTask(icsMessage("task.sync.title")) { indicator ->
indicator.isIndeterminate = true
val root = icsManager.readOnlySourcesManager.rootDir
if (toDelete.isNotEmpty()) {
indicator.text = icsMessage("progress.deleting.old.repositories")
for (path in toDelete) {
indicator.checkCanceled()
LOG.runAndLogException {
indicator.text2 = path
root.resolve(path).delete()
}
}
}
if (toCheckout.isNotEmpty()) {
for (source in toCheckout) {
indicator.checkCanceled()
LOG.runAndLogException {
indicator.text = icsMessage("progress.cloning.repository", source.url!!.trimMiddle(255))
val dir = root.resolve(source.path!!)
if (dir.exists()) {
dir.delete()
}
cloneBare(source.url!!, dir, icsManager.credentialsStore, indicator.asProgressMonitor()).close()
}
}
}
icsManager.readOnlySourcesManager.setSources(newList)
// blindly reload all
icsManager.schemeManagerFactory.value.process {
it.reload()
}
}
}
override fun reset(settings: IcsSettings) {
editor.reset(settings.readOnlySources)
}
override fun getComponent() = editor.createComponent()
}
}
| apache-2.0 | 387bc2d4ef110c401d63d58a66d05be9 | 37 | 141 | 0.699427 | 4.938992 | false | true | false | false |
samirma/MeteoriteLandings | app/src/main/java/com/antonio/samir/meteoritelandingsspots/features/list/recyclerView/ViewHolderMeteorite.kt | 1 | 2626 | package com.antonio.samir.meteoritelandingsspots.features.list.recyclerView
import android.content.Context
import android.location.Location
import android.view.View
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import com.antonio.samir.meteoritelandingsspots.R
import com.antonio.samir.meteoritelandingsspots.data.repository.model.Meteorite
import com.antonio.samir.meteoritelandingsspots.features.getLocationText
import com.antonio.samir.meteoritelandingsspots.features.yearString
class ViewHolderMeteorite(private val view: View) : RecyclerView.ViewHolder(view) {
val context: Context = view.context
private val noAddressPlaceHolder = context.getString(R.string.without_address_placeholder)
var name: TextView = view.findViewById(R.id.title)
private var addressTV: TextView = view.findViewById(R.id.location)
private var cardView: CardView = view.findViewById(R.id.cardview)
var meteorite: Meteorite? = null
fun onBind(
meteorite: Meteorite,
selectedMeteorite: Boolean,
location: Location?,
onClick: () -> Unit
) {
if (this.meteorite?.id == meteorite.id) {
addressTV.text = meteorite.getLocationText(location, noAddressPlaceHolder)
} else {
this.meteorite = meteorite
populateViewHolder(meteorite, location, selectedMeteorite)
}
view.setOnClickListener {
onClick()
}
}
private fun populateViewHolder(meteorite: Meteorite, location: Location?, selectedMeteorite: Boolean) {
val meteoriteName = meteorite.name
val year = meteorite.yearString
name.text = if (!year.isNullOrBlank()) {
context.getString(R.string.name, meteoriteName, year)
} else {
meteoriteName
}
name.contentDescription = meteoriteName
addressTV.text = meteorite.getLocationText(location, noAddressPlaceHolder)
var color = R.color.unselected_item_color
var titleColor = R.color.title_color
var elevation = R.dimen.unselected_item_elevation
if (selectedMeteorite) {
color = R.color.selected_item_color
titleColor = R.color.selected_title_color
elevation = R.dimen.selected_item_elevation
}
cardView.setCardBackgroundColor(context.resources.getColor(color))
cardView.cardElevation = context.resources.getDimensionPixelSize(elevation).toFloat()
name.setTextColor(context.resources.getColor(titleColor))
}
} | mit | 2b37015a1b35b60dfd8d4c87614e9fcf | 32.253165 | 107 | 0.704113 | 4.809524 | false | false | false | false |
JuliusKunze/kotlin-native | shared/src/main/kotlin/org/jetbrains/kotlin/konan/file/File.kt | 1 | 7873 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.konan.file
import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.net.URI
import java.nio.file.*
import java.nio.file.attribute.BasicFileAttributes
data class File constructor(internal val javaPath: Path) {
constructor(parent: Path, child: String): this(parent.resolve(child))
constructor(parent: File, child: String): this(parent.javaPath.resolve(child))
constructor(path: String): this(Paths.get(path))
constructor(parent: String, child: String): this(Paths.get(parent, child))
val path: String
get() = javaPath.toString()
val absolutePath: String
get() = javaPath.toAbsolutePath().toString()
val absoluteFile: File
get() = File(absolutePath)
val name: String
get() = javaPath.fileName.toString()
val parent: String
get() = javaPath.parent.toString()
val parentFile: File
get() = File(javaPath.parent)
val exists
get() = Files.exists(javaPath)
val isDirectory
get() = Files.isDirectory(javaPath)
val isFile
get() = Files.isRegularFile(javaPath)
val isAbsolute
get() = javaPath.isAbsolute()
val listFiles: List<File>
get() = Files.newDirectoryStream(javaPath).use { stream -> stream.map { File(it) } }
fun child(name: String) = File(this, name)
fun copyTo(destination: File) {
Files.copy(javaPath, destination.javaPath, StandardCopyOption.REPLACE_EXISTING)
}
fun recursiveCopyTo(destination: File) {
val sourcePath = javaPath
val destPath = destination.javaPath
sourcePath.recursiveCopyTo(destPath)
}
fun mkdirs() = Files.createDirectories(javaPath)
fun delete() = Files.deleteIfExists(javaPath)
fun deleteRecursively() = postorder{Files.delete(it)}
fun deleteOnExitRecursively() = preorder{File(it).deleteOnExit()}
fun preorder(task: (Path) -> Unit) {
if (!this.exists) return
Files.walkFileTree(javaPath, object: SimpleFileVisitor<Path>() {
override fun visitFile(file: Path?, attrs: BasicFileAttributes?): FileVisitResult {
task(file!!)
return FileVisitResult.CONTINUE
}
override fun preVisitDirectory(dir: Path?, attrs: BasicFileAttributes?): FileVisitResult {
task(dir!!)
return FileVisitResult.CONTINUE
}
})
}
fun postorder(task: (Path) -> Unit) {
if (!this.exists) return
Files.walkFileTree(javaPath, object: SimpleFileVisitor<Path>() {
override fun visitFile(file: Path?, attrs: BasicFileAttributes?): FileVisitResult {
task(file!!)
return FileVisitResult.CONTINUE
}
override fun postVisitDirectory(dir: Path?, exc: java.io.IOException?): FileVisitResult {
task(dir!!)
return FileVisitResult.CONTINUE
}
})
}
fun deleteOnExit(): File {
// Works only on the default file system,
// but that's okay for now.
javaPath.toFile().deleteOnExit()
return this // Allow streaming.
}
fun readBytes() = Files.readAllBytes(javaPath)
fun writeBytes(bytes: ByteArray) = Files.write(javaPath, bytes)
fun appendBytes(bytes: ByteArray)
= Files.write(javaPath, bytes, StandardOpenOption.APPEND)
fun writeLines(lines: Iterable<String>) {
Files.write(javaPath, lines)
}
fun forEachLine(action: (String) -> Unit) {
Files.lines(javaPath).use { lines ->
lines.forEach { action(it) }
}
}
fun createAsSymlink(target: String) {
val targetPath = Paths.get(target)
if (Files.isSymbolicLink(this.javaPath) && Files.readSymbolicLink(javaPath) == targetPath) {
return
}
Files.createSymbolicLink(this.javaPath, targetPath)
}
override fun toString() = path
// TODO: Consider removeing these after konanazing java.util.Properties.
fun bufferedReader() = Files.newBufferedReader(javaPath)
fun outputStream() = Files.newOutputStream(javaPath)
fun printWriter() = javaPath.toFile().printWriter()
companion object {
val userDir
get() = File(System.getProperty("user.dir"))
val userHome
get() = File(System.getProperty("user.home"))
val jdkHome
get() = File(System.getProperty("java.home"))
}
fun readStrings() = mutableListOf<String>().also { list -> forEachLine{list.add(it)}}
}
fun String.File(): File = File(this)
fun Path.File(): File = File(this)
fun createTempFile(name: String, suffix: String? = null)
= Files.createTempFile(name, suffix).File()
fun createTempDir(name: String): File
= Files.createTempDirectory(name).File()
private val File.zipUri: URI
get() = URI.create("jar:${this.toPath().toUri()}")
fun File.zipFileSystem(mutable: Boolean = false): FileSystem {
val zipUri = this.zipUri
val attributes = hashMapOf("create" to mutable.toString())
return try {
FileSystems.newFileSystem(zipUri, attributes, null)
} catch (e: FileSystemAlreadyExistsException) {
FileSystems.getFileSystem(zipUri)
}
}
fun File.mutableZipFileSystem() = this.zipFileSystem(mutable = true)
fun File.zipPath(path: String): Path
= this.zipFileSystem().getPath(path)
val File.asZipRoot: File
get() = File(this.zipPath("/"))
val File.asWritableZipRoot: File
get() = File(this.mutableZipFileSystem().getPath("/"))
private fun File.toPath() = Paths.get(this.path)
fun File.zipDirAs(unixFile: File) {
val zipRoot = unixFile.asWritableZipRoot
this.recursiveCopyTo(zipRoot)
zipRoot.javaPath.fileSystem.close()
}
fun Path.recursiveCopyTo(destPath: Path) {
val sourcePath = this
Files.walk(sourcePath).forEach next@ { oldPath ->
val relative = sourcePath.relativize(oldPath)
val destFs = destPath.getFileSystem()
// We are copying files between file systems,
// so pass the relative path through the String.
val newPath = destFs.getPath(destPath.toString(), relative.toString())
// File systems don't allow replacing an existing root.
if (newPath == newPath.getRoot()) return@next
if (Files.isDirectory(newPath)) {
Files.createDirectories(newPath)
} else {
Files.copy(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING)
}
}
}
fun bufferedReader(errorStream: InputStream?) = BufferedReader(InputStreamReader(errorStream))
// stdlib `use` function adapted for AutoCloseable.
inline fun <T : AutoCloseable?, R> T.use(block: (T) -> R): R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
closed = true
try {
this?.close()
} catch (closeException: Exception) {
}
throw e
} finally {
if (!closed) {
this?.close()
}
}
}
fun Path.unzipTo(directory: Path) {
val zipUri = URI.create("jar:" + this.toUri())
FileSystems.newFileSystem(zipUri, emptyMap<String, Any?>(), null).use { zipfs ->
val zipPath = zipfs.getPath("/")
zipPath.recursiveCopyTo(directory)
}
}
| apache-2.0 | d62afc10d9c4f8ac84611983614ae2e4 | 31.266393 | 100 | 0.654007 | 4.313973 | false | false | false | false |
smmribeiro/intellij-community | java/java-tests/testSrc/com/intellij/java/codeInsight/completion/AtomicFieldUpdaterCompletionTest.kt | 12 | 3687 | // 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.java.codeInsight.completion
import com.intellij.codeInsight.completion.LightFixtureCompletionTestCase
import com.intellij.testFramework.NeedsIndex
@NeedsIndex.Full
class AtomicFieldUpdaterCompletionTest : LightFixtureCompletionTestCase() {
override fun setUp() {
super.setUp()
myFixture.addClass("""package foo.bar;
class Base{
public volatile int base;
}""")
myFixture.addClass("""package foo.bar;
class Data extends Base {
public volatile int updateableIntFirst;
public volatile int updateableIntSecond;
public volatile long updateableLong;
public volatile int[] updateableArray;
public volatile Object updateableObject;
public volatile String updateableString;
public String nonUpdateableStringFirst;
@SuppressWarnings("StaticNonFinalField")
public static volatile String nonUpdateableStringSecond;
public volatile byte nonUpdateableType;
public volatile Runnable other;
}""")
}
fun testUpdateableIntFirst() {
doTest("updateableInt", 0, "updateableIntFirst", "updateableIntSecond")
}
fun testUpdateableIntSecond() {
doTest("updateableIntS", 0, "updateableIntSecond")
}
fun testUpdateableLong() {
doTest("updateableL", 0, "updateableLong")
}
fun testUpdateableArray() {
doTest("updateableA", 0, "updateableArray")
}
fun testUpdateableString() {
doTest("updateableS", 0, "updateableString", "updateableIntSecond", "nonUpdateableStringFirst", "nonUpdateableStringSecond")
}
fun testUpdateableAll() {
doTest("updateable", 3,
"updateableArray", "updateableIntFirst", "updateableIntSecond", "updateableLong", "updateableObject",
"updateableString", "nonUpdateableStringFirst", "nonUpdateableStringSecond", "nonUpdateableType")
}
fun testAll() {
doTest("", 5, "other",
"updateableArray", "updateableIntFirst", "updateableIntSecond", "updateableLong", "updateableObject",
"updateableString", "nonUpdateableStringFirst", "nonUpdateableStringSecond", "nonUpdateableType")
}
fun testUpdateableBase() {
doTest("base", -1)
}
private fun doTest(prefix: String, index: Int, vararg expectedNames: String) {
val expectedName = if (expectedNames.isNotEmpty()) expectedNames[index] else ""
val updater = when {
expectedName.contains("Int") -> INTEGER
expectedName.contains("Long") -> LONG
else -> REFERENCE
}
myFixture.configureByText("Main.java", getMainClassText(prefix, updater))
complete()
val items = myItems
if (items == null) {
assertEquals("Only one item should auto-complete immediately", expectedNames.size, 1)
myFixture.checkResult(getMainClassText(expectedName, updater))
return
}
val lookupStrings = items.map { it.lookupString }
assertEquals("Lookup strings", expectedNames.asList(), lookupStrings)
if (index < 0) return
val lookupElement = items[index]
selectItem(lookupElement!!)
myFixture.checkResult(getMainClassText(expectedName, updater))
}
private fun getMainClassText(name: String, updater: String): String {
val data = if (updater === REFERENCE) "String.class," else ""
return """import foo.bar.*;
import java.util.concurrent.atomic.*;
class Main {
void foo() {
$updater.newUpdater(Data.class, $data "$name<caret>").get();
}
}"""
}
companion object {
private const val INTEGER = "AtomicIntegerFieldUpdater"
private const val LONG = "AtomicLongFieldUpdater"
private const val REFERENCE = "AtomicReferenceFieldUpdater"
}
} | apache-2.0 | 381f8c99e27163bc6edf936e282f4959 | 32.225225 | 140 | 0.723895 | 4.474515 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspections/redundantVisibilityModifierWithExplicitApi/redundantVisibilityModifierWithExplicitApi.kt | 24 | 720 | public class C {
public val foo: Int = 0
public fun bar() {}
}
open class D {
protected open fun willRemainProtected() {
}
protected open fun willBecomePublic() {
}
}
class E : D() {
protected override fun willRemainProtected() {
}
public override fun willBecomePublic() {
}
}
enum class F private constructor(val x: Int) {
FIRST(42)
}
sealed class G constructor(val y: Int) {
protected constructor(): this(42)
object H : G()
}
interface I {
fun bar()
}
fun f() {
val i = object : I {
internal var foo = 0
override fun bar() {}
}
i.foo = 1
class LocalClass {
internal var foo = 0
}
LocalClass().foo = 1
} | apache-2.0 | 72933f199681948ad99499b7577e37cb | 13.714286 | 50 | 0.570833 | 3.636364 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/MainActivity.kt | 1 | 33089 | package com.habitrpg.android.habitica.ui.activities
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.Canvas
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.*
import android.widget.FrameLayout
import android.widget.TextView
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.core.content.FileProvider
import androidx.core.content.edit
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.findNavController
import com.facebook.drawee.view.SimpleDraweeView
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.perf.FirebasePerformance
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.api.HostConfig
import com.habitrpg.android.habitica.api.MaintenanceApiService
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.*
import com.habitrpg.android.habitica.databinding.ActivityMainBinding
import com.habitrpg.android.habitica.events.*
import com.habitrpg.android.habitica.events.commands.FeedCommand
import com.habitrpg.android.habitica.extensions.dpToPx
import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler
import com.habitrpg.android.habitica.helpers.*
import com.habitrpg.android.habitica.helpers.notifications.PushNotificationManager
import com.habitrpg.android.habitica.interactors.CheckClassSelectionUseCase
import com.habitrpg.android.habitica.interactors.DisplayItemDropUseCase
import com.habitrpg.android.habitica.interactors.NotifyUserUseCase
import com.habitrpg.android.habitica.models.TutorialStep
import com.habitrpg.android.habitica.models.inventory.Egg
import com.habitrpg.android.habitica.models.inventory.HatchingPotion
import com.habitrpg.android.habitica.models.notifications.LoginIncentiveData
import com.habitrpg.android.habitica.models.responses.MaintenanceResponse
import com.habitrpg.android.habitica.models.responses.TaskScoringResult
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.proxy.CrashlyticsProxy
import com.habitrpg.android.habitica.ui.AvatarView
import com.habitrpg.android.habitica.ui.AvatarWithBarsViewModel
import com.habitrpg.android.habitica.ui.TutorialView
import com.habitrpg.android.habitica.ui.fragments.NavigationDrawerFragment
import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils
import com.habitrpg.android.habitica.ui.viewmodels.NotificationsViewModel
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar
import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar.SnackbarDisplayType
import com.habitrpg.android.habitica.ui.views.ValueBar
import com.habitrpg.android.habitica.ui.views.dialogs.AchievementDialog
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import com.habitrpg.android.habitica.ui.views.dialogs.QuestCompletedDialog
import com.habitrpg.android.habitica.ui.views.yesterdailies.YesterdailyDialog
import com.habitrpg.android.habitica.userpicture.BitmapUtils
import com.habitrpg.android.habitica.widget.AvatarStatsWidgetProvider
import com.habitrpg.android.habitica.widget.DailiesWidgetProvider
import com.habitrpg.android.habitica.widget.HabitButtonWidgetProvider
import com.habitrpg.android.habitica.widget.TodoListWidgetProvider
import io.reactivex.Completable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import io.realm.Realm
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.util.*
import javax.inject.Inject
open class MainActivity : BaseActivity(), TutorialView.OnTutorialReaction {
@Inject
internal lateinit var apiClient: ApiClient
@Inject
internal lateinit var soundManager: SoundManager
@Inject
internal lateinit var maintenanceService: MaintenanceApiService
@Inject
internal lateinit var hostConfig: HostConfig
@Inject
internal lateinit var sharedPreferences: SharedPreferences
@Inject
internal lateinit var crashlyticsProxy: CrashlyticsProxy
@Inject
internal lateinit var pushNotificationManager: PushNotificationManager
@Inject
internal lateinit var checkClassSelectionUseCase: CheckClassSelectionUseCase
@Inject
internal lateinit var displayItemDropUseCase: DisplayItemDropUseCase
@Inject
internal lateinit var notifyUserUseCase: NotifyUserUseCase
@Inject
internal lateinit var taskRepository: TaskRepository
@Inject
internal lateinit var userRepository: UserRepository
@Inject
internal lateinit var inventoryRepository: InventoryRepository
@Inject
internal lateinit var contentRepository: ContentRepository
@Inject
internal lateinit var taskAlarmManager: TaskAlarmManager
@Inject
internal lateinit var appConfigManager: AppConfigManager
lateinit var binding: ActivityMainBinding
val snackbarContainer: ViewGroup
get() = binding.snackbarContainer
var user: User? = null
private var avatarInHeader: AvatarWithBarsViewModel? = null
private var notificationsViewModel: NotificationsViewModel? = null
private var faintDialog: HabiticaAlertDialog? = null
private var sideAvatarView: AvatarView? = null
private var activeTutorialView: TutorialView? = null
private var drawerFragment: NavigationDrawerFragment? = null
private var drawerToggle: ActionBarDrawerToggle? = null
private var resumeFromActivity = false
private var userIsOnQuest = false
private var connectionIssueHandler: Handler? = null
val userID: String
get() = user?.id ?: ""
val isAppBarExpanded: Boolean
get() = binding.appbar.height - binding.appbar.bottom == 0
override fun getLayoutResId(): Int {
return R.layout.activity_main
}
override fun getContentView(): View {
binding = ActivityMainBinding.inflate(layoutInflater)
return binding.root
}
private var launchTrace: com.google.firebase.perf.metrics.Trace? = null
@SuppressLint("ObsoleteSdkInt")
public override fun onCreate(savedInstanceState: Bundle?) {
launchTrace = FirebasePerformance.getInstance().newTrace("MainActivityLaunch")
launchTrace?.start()
super.onCreate(savedInstanceState)
if (!HabiticaBaseApplication.checkUserAuthentication(this, hostConfig)) {
return
}
setupToolbar(binding.toolbar)
avatarInHeader = AvatarWithBarsViewModel(this, binding.avatarWithBars, userRepository)
sideAvatarView = AvatarView(this, showBackground = true, showMount = false, showPet = false)
compositeSubscription.add(userRepository.getUser()
.subscribe(Consumer { newUser ->
[email protected] = newUser
[email protected]()
}, RxErrorHandler.handleEmptyError()))
compositeSubscription.add(userRepository.getIsUserOnQuest().subscribeWithErrorHandler(Consumer {
userIsOnQuest = it
}))
val viewModel = ViewModelProviders.of(this)
.get(NotificationsViewModel::class.java)
notificationsViewModel = viewModel
val drawerLayout = findViewById<androidx.drawerlayout.widget.DrawerLayout>(R.id.drawer_layout)
drawerFragment = supportFragmentManager.findFragmentById(R.id.navigation_drawer) as? NavigationDrawerFragment
drawerFragment?.setUp(R.id.navigation_drawer, drawerLayout, viewModel)
drawerToggle = object : ActionBarDrawerToggle(
this, /* host Activity */
findViewById(R.id.drawer_layout), /* DrawerLayout object */
R.string.navigation_drawer_open, /* "open drawer" description */
R.string.navigation_drawer_close /* "close drawer" description */
) {
}
// Set the drawer toggle as the DrawerListener
drawerToggle?.let { drawerLayout.addDrawerListener(it) }
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeButtonEnabled(true)
val navigationController = findNavController(R.id.nav_host_fragment)
navigationController.addOnDestinationChangedListener { _, destination, _ ->
if (destination.label.isNullOrEmpty() && user?.isValid == true) {
binding.toolbarTitle.text = user?.profile?.name
} else if (user?.isValid == true && user?.profile != null) {
binding.toolbarTitle.text = destination.label
}
drawerFragment?.setSelection(destination.id, null, false)
}
MainNavigationController.setup(navigationController)
setupNotifications()
setupBottomnavigationLayoutListener()
try {
taskAlarmManager.scheduleAllSavedAlarms(sharedPreferences.getBoolean("preventDailyReminder", false))
} catch (e: Exception) {
crashlyticsProxy.logException(e)
}
}
private fun setupNotifications() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "default"
val channel = NotificationChannel(
channelId,
"Habitica Notifications",
NotificationManager.IMPORTANCE_DEFAULT)
val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(channel)
}
}
private fun setupBottomnavigationLayoutListener() {
binding.bottomNavigation.viewTreeObserver.addOnGlobalLayoutListener {
if (binding.bottomNavigation.visibility == View.VISIBLE) {
snackbarContainer.setPadding(0, 0, 0, binding.bottomNavigation.barHeight + 12.dpToPx(this))
} else {
snackbarContainer.setPadding(0, 0, 0, 0)
}
}
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle?.syncState()
}
override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
super.onRestoreInstanceState(savedInstanceState)
Log.e("RESTORED:", savedInstanceState.toString())
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
drawerToggle?.onConfigurationChanged(newConfig)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return if (drawerToggle?.onOptionsItemSelected(item) == true) {
true
} else super.onOptionsItemSelected(item)
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
override fun onResume() {
super.onResume()
if(!resumeFromActivity){
retrieveUser()
this.checkMaintenance()
}
resumeFromActivity = false
//Track when the app was last opened, so that we can use this to send out special reminders after a week of inactivity
sharedPreferences.edit {
putLong("lastAppLaunch", Date().time)
putBoolean("preventDailyReminder", false)
}
if (intent.hasExtra("notificationIdentifier")) {
val identifier = intent.getStringExtra("notificationIdentifier") ?: ""
val additionalData = HashMap<String, Any>()
additionalData["identifier"] = identifier
AmplitudeManager.sendEvent("open notification", AmplitudeManager.EVENT_CATEGORY_BEHAVIOUR, AmplitudeManager.EVENT_HITTYPE_EVENT, additionalData)
NotificationOpenHandler.handleOpenedByNotification(identifier, intent, user)
}
launchTrace?.stop()
launchTrace = null
}
override fun onPause() {
updateWidgets()
super.onPause()
}
override fun startActivity(intent: Intent?) {
resumeFromActivity = true
super.startActivity(intent)
}
override fun startActivityForResult(intent: Intent?, requestCode: Int) {
resumeFromActivity = true
super.startActivityForResult(intent, requestCode)
}
override fun startActivity(intent: Intent?, options: Bundle?) {
resumeFromActivity = true
super.startActivity(intent, options)
}
private fun updateWidgets() {
updateWidget(AvatarStatsWidgetProvider::class.java)
updateWidget(TodoListWidgetProvider::class.java)
updateWidget(DailiesWidgetProvider::class.java)
updateWidget(HabitButtonWidgetProvider::class.java)
}
private fun updateWidget(widgetClass: Class<*>) {
val intent = Intent(this, widgetClass)
intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
val ids = AppWidgetManager.getInstance(application).getAppWidgetIds(ComponentName(application, widgetClass))
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
sendBroadcast(intent)
}
fun navigate(transitionId: Int) {
findNavController(R.id.nav_host_fragment).navigate(transitionId)
}
private fun setUserData() {
if (user != null) {
val preferences = user?.preferences
preferences?.language?.let { apiClient.setLanguageCode(it) }
preferences?.sound?.let { soundManager.soundTheme = it }
displayDeathDialogIfNeeded()
YesterdailyDialog.showDialogIfNeeded(this, user?.id, userRepository, taskRepository)
if (user?.flags?.isVerifiedUsername == false && isActivityVisible) {
val intent = Intent(this, VerifyUsernameActivity::class.java)
startActivity(intent)
}
val quest = user?.party?.quest
if (quest?.completed?.isNotBlank() == true) {
compositeSubscription.add(inventoryRepository.getQuestContent(user?.party?.quest?.completed ?: "").firstElement().subscribe {
QuestCompletedDialog.showWithQuest(this, it)
userRepository.updateUser(user, "party.quest.completed", "").subscribe(Consumer {}, RxErrorHandler.handleEmptyError())
})
}
}
}
override fun onBackPressed() {
if (this.activeTutorialView != null) {
this.removeActiveTutorialView()
}
if (drawerFragment?.isDrawerOpen == true) {
drawerFragment?.closeDrawer()
} else {
try {
super.onBackPressed()
} catch (ignored: Exception) {
}
}
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == SELECT_CLASS_RESULT) {
retrieveUser()
} else if (requestCode == GEM_PURCHASE_REQUEST) {
retrieveUser()
}
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == NOTIFICATION_CLICK && data?.hasExtra("notificationId") == true) {
notificationsViewModel?.click(
data.getStringExtra("notificationId"),
MainNavigationController
)
}
if (resultCode == NOTIFICATION_ACCEPT && data?.hasExtra("notificationId") == true) {
notificationsViewModel?.accept(
data.getStringExtra("notificationId")
)
}
if (resultCode == NOTIFICATION_REJECT && data?.hasExtra("notificationId") == true) {
notificationsViewModel?.reject(
data.getStringExtra("notificationId")
)
}
PurchaseHandler.findForActivity(this)?.onResult(requestCode, resultCode, data)
}
// region Events
public override fun onDestroy() {
userRepository.close()
inventoryRepository.close()
super.onDestroy()
}
@Subscribe
fun onEvent(event: FeedCommand) {
if (event.usingFood == null || event.usingPet == null) {
return
}
val pet = event.usingPet
compositeSubscription.add(this.inventoryRepository.feedPet(event.usingPet, event.usingFood)
.subscribe(Consumer { feedResponse ->
HabiticaSnackbar.showSnackbar(snackbarContainer, getString(R.string.notification_pet_fed, pet.text), SnackbarDisplayType.NORMAL)
if (feedResponse.value == -1) {
val mountWrapper = View.inflate(this, R.layout.pet_imageview, null) as? FrameLayout
val mountImageView = mountWrapper?.findViewById(R.id.pet_imageview) as? SimpleDraweeView
DataBindingUtils.loadImage(mountImageView, "Mount_Icon_" + event.usingPet.key)
val dialog = HabiticaAlertDialog(this@MainActivity)
dialog.setTitle(getString(R.string.evolved_pet_title, pet.text))
dialog.setAdditionalContentView(mountWrapper)
dialog.addButton(R.string.onwards, true)
dialog.addButton(R.string.share, false) { hatchingDialog, _ ->
val event1 = ShareEvent()
event1.sharedMessage = getString(R.string.share_raised, pet.text)
val mountImageSideLength = 99
val sharedImage = Bitmap.createBitmap(mountImageSideLength, mountImageSideLength, Bitmap.Config.ARGB_8888)
val canvas = Canvas(sharedImage)
mountImageView?.drawable?.setBounds(0, 0, mountImageSideLength, mountImageSideLength)
mountImageView?.drawable?.draw(canvas)
event1.shareImage = sharedImage
EventBus.getDefault().post(event1)
hatchingDialog.dismiss()
}
dialog.enqueue()
}
}, RxErrorHandler.handleEmptyError()))
}
// endregion
internal fun displayTaskScoringResponse(data: TaskScoringResult?) {
if (user != null && data != null) {
compositeSubscription.add(notifyUserUseCase.observable(NotifyUserUseCase.RequestValues(this, snackbarContainer,
user, data.experienceDelta, data.healthDelta, data.goldDelta, data.manaDelta, if (userIsOnQuest) data.questDamage else 0.0, data.hasLeveledUp))
.subscribe(Consumer { }, RxErrorHandler.handleEmptyError()))
}
compositeSubscription.add(displayItemDropUseCase.observable(DisplayItemDropUseCase.RequestValues(data, this, snackbarContainer))
.subscribe(Consumer { }, RxErrorHandler.handleEmptyError()))
}
private fun displayDeathDialogIfNeeded() {
if (user?.stats?.hp ?: 1.0 > 0) {
return
}
if (this.faintDialog == null && !this.isFinishing) {
val customView = View.inflate(this, R.layout.dialog_faint, null)
if (customView != null) {
val hpBarView = customView.findViewById<View>(R.id.hpBar) as? ValueBar
hpBarView?.setLightBackground(true)
hpBarView?.setIcon(HabiticaIconsHelper.imageOfHeartLightBg())
val dialogAvatarView = customView.findViewById<View>(R.id.avatarView) as? AvatarView
user?.let { dialogAvatarView?.setAvatar(it) }
}
this.faintDialog = HabiticaAlertDialog(this)
faintDialog?.setTitle(R.string.faint_header)
faintDialog?.setAdditionalContentView(customView)
faintDialog?.addButton(R.string.faint_button, true) { _, _ ->
faintDialog = null
user?.let {
userRepository.revive(it).subscribe(Consumer { }, RxErrorHandler.handleEmptyError())
}
}
soundManager.loadAndPlayAudio(SoundManager.SoundDeath)
this.faintDialog?.enqueue()
}
}
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
if (keyCode == KeyEvent.KEYCODE_MENU) {
drawerFragment?.openDrawer()
return true
}
return super.onKeyUp(keyCode, event)
}
protected fun retrieveUser() {
if (hostConfig.hasAuthentication()) {
compositeSubscription.add(this.userRepository.retrieveUser(true)
.doOnNext { user1 ->
FirebaseAnalytics.getInstance(this).setUserProperty("has_party", if (user1.party?.id?.isNotEmpty() == true) "true" else "false")
FirebaseAnalytics.getInstance(this).setUserProperty("is_subscribed", if (user1.isSubscribed) "true" else "false")
pushNotificationManager.setUser(user1)
pushNotificationManager.addPushDeviceUsingStoredToken()
}
.flatMap { contentRepository.retrieveContent(this,false) }
.flatMap { contentRepository.retrieveWorldState() }
.subscribe(Consumer { }, RxErrorHandler.handleEmptyError()))
}
}
fun displayTutorialStep(step: TutorialStep, text: String, canBeDeferred: Boolean) {
removeActiveTutorialView()
val view = TutorialView(this, step, this)
this.activeTutorialView = view
view.setTutorialText(text)
view.onReaction = this
view.setCanBeDeferred(canBeDeferred)
binding.overlayFrameLayout.addView(view)
val additionalData = HashMap<String, Any>()
additionalData["eventLabel"] = step.identifier + "-android"
additionalData["eventValue"] = step.identifier ?: ""
additionalData["complete"] = false
AmplitudeManager.sendEvent("tutorial", AmplitudeManager.EVENT_CATEGORY_BEHAVIOUR, AmplitudeManager.EVENT_HITTYPE_EVENT, additionalData)
}
fun displayTutorialStep(step: TutorialStep, texts: List<String>, canBeDeferred: Boolean) {
removeActiveTutorialView()
val view = TutorialView(this, step, this)
this.activeTutorialView = view
view.setTutorialTexts(texts)
view.onReaction = this
view.setCanBeDeferred(canBeDeferred)
binding.overlayFrameLayout.addView(view)
val additionalData = HashMap<String, Any>()
additionalData["eventLabel"] = step.identifier + "-android"
additionalData["eventValue"] = step.identifier ?: ""
additionalData["complete"] = false
AmplitudeManager.sendEvent("tutorial", AmplitudeManager.EVENT_CATEGORY_BEHAVIOUR, AmplitudeManager.EVENT_HITTYPE_EVENT, additionalData)
}
override fun onTutorialCompleted(step: TutorialStep) {
val path = "flags.tutorial." + step.tutorialGroup + "." + step.identifier
val updateData = HashMap<String, Any>()
updateData[path] = true
compositeSubscription.add(userRepository.updateUser(user, updateData)
.subscribe(Consumer { }, RxErrorHandler.handleEmptyError()))
binding.overlayFrameLayout.removeView(this.activeTutorialView)
this.removeActiveTutorialView()
val additionalData = HashMap<String, Any>()
additionalData["eventLabel"] = step.identifier + "-android"
additionalData["eventValue"] = step.identifier ?: ""
additionalData["complete"] = true
AmplitudeManager.sendEvent("tutorial", AmplitudeManager.EVENT_CATEGORY_BEHAVIOUR, AmplitudeManager.EVENT_HITTYPE_EVENT, additionalData)
}
override fun onTutorialDeferred(step: TutorialStep) {
taskRepository.executeTransaction(Realm.Transaction { step.displayedOn = Date() })
this.removeActiveTutorialView()
}
private fun removeActiveTutorialView() {
if (this.activeTutorialView != null) {
binding.overlayFrameLayout.removeView(this.activeTutorialView)
this.activeTutorialView = null
}
}
@Subscribe
fun shareEvent(event: ShareEvent) {
val sharingIntent = Intent(Intent.ACTION_SEND)
sharingIntent.type = "*/*"
sharingIntent.putExtra(Intent.EXTRA_TEXT, event.sharedMessage)
BitmapUtils.clearDirectoryContent("$filesDir/shared_images")
val f = BitmapUtils.saveToShareableFile("$filesDir/shared_images", "${Date().toString()}.png", event.shareImage)
val fileUri = f?.let { FileProvider.getUriForFile(this, getString(R.string.content_provider), it) }
if (fileUri != null) {
sharingIntent.putExtra(Intent.EXTRA_STREAM, fileUri)
val resInfoList = this.packageManager.queryIntentActivities(sharingIntent, PackageManager.MATCH_DEFAULT_ONLY)
for (resolveInfo in resInfoList) {
val packageName = resolveInfo.activityInfo.packageName
this.grantUriPermission(packageName, fileUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
}
startActivity(Intent.createChooser(sharingIntent, getString(R.string.share_using)))
}
private fun checkMaintenance() {
compositeSubscription.add(this.maintenanceService.maintenanceStatus
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(Consumer { maintenanceResponse ->
if (maintenanceResponse == null) {
return@Consumer
}
if (maintenanceResponse.activeMaintenance) {
val intent = createMaintenanceIntent(maintenanceResponse, false)
startActivity(intent)
} else {
if (maintenanceResponse.minBuild != null) {
try {
val packageInfo = packageManager.getPackageInfo(packageName, 0)
@Suppress("DEPRECATION")
if (packageInfo.versionCode < maintenanceResponse.minBuild) {
val intent = createMaintenanceIntent(maintenanceResponse, true)
startActivity(intent)
}
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
}
}
}, RxErrorHandler.handleEmptyError()))
}
private fun createMaintenanceIntent(maintenanceResponse: MaintenanceResponse, isDeprecationNotice: Boolean): Intent {
val intent = Intent(this, MaintenanceActivity::class.java)
val data = Bundle()
data.putString("title", maintenanceResponse.title)
data.putString("imageUrl", maintenanceResponse.imageUrl)
data.putString("description", maintenanceResponse.description)
data.putBoolean("deprecationNotice", isDeprecationNotice)
intent.putExtras(data)
return intent
}
@Subscribe
fun showSnackBarEvent(event: ShowSnackbarEvent) {
HabiticaSnackbar.showSnackbar(snackbarContainer, event.leftImage, event.title, event.text, event.specialView, event.rightIcon, event.rightTextColor, event.rightText, event.type)
}
@Subscribe
fun showCheckinDialog(event: ShowCheckinDialog) {
val notificationData = event.notification.data as? LoginIncentiveData
val title = notificationData?.message
val factory = LayoutInflater.from(this)
val view = factory.inflate(R.layout.dialog_login_incentive, null)
val imageView = view.findViewById(R.id.imageView) as? SimpleDraweeView
var imageKey = notificationData?.rewardKey?.get(0)
if (imageKey?.contains("armor") == true) {
imageKey = "slim_$imageKey"
}
DataBindingUtils.loadImage(imageView, imageKey)
val youEarnedMessage = this.getString(R.string.checkInRewardEarned, notificationData?.rewardText)
val youEarnedTexView = view.findViewById(R.id.you_earned_message) as? TextView
youEarnedTexView?.text = youEarnedMessage
val nextUnlockTextView = view.findViewById(R.id.next_unlock_message) as? TextView
if (event.nextUnlockCount > 0) {
nextUnlockTextView?.text = event.nextUnlockText
} else {
nextUnlockTextView?.visibility = View.GONE
}
compositeSubscription.add(Completable.complete()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(Action {
val alert = HabiticaAlertDialog(this)
alert.setAdditionalContentView(view)
alert.setTitle(title)
alert.addButton(R.string.see_you_tomorrow, true) { _, _ ->
apiClient.readNotification(event.notification.id)
.subscribe(Consumer { }, RxErrorHandler.handleEmptyError())
}
alert.show()
}, RxErrorHandler.handleEmptyError()))
}
@Subscribe
fun showAchievementDialog(event: ShowAchievementDialog) {
compositeSubscription.add(Completable.complete()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(Action {
val dialog = AchievementDialog(this)
dialog.setType(event.type)
dialog.enqueue()
apiClient.readNotification(event.id)
.subscribe(Consumer { }, RxErrorHandler.handleEmptyError())
}, RxErrorHandler.handleEmptyError()))
}
override fun onEvent(event: ShowConnectionProblemEvent) {
if (event.title != null) {
super.onEvent(event)
} else {
connectionIssueHandler?.removeCallbacksAndMessages(null)
binding.connectionIssueTextview.visibility = View.VISIBLE
binding.connectionIssueTextview.text = event.message
connectionIssueHandler = Handler()
connectionIssueHandler?.postDelayed({
binding.connectionIssueTextview.visibility = View.GONE
}, 5000)
}
}
fun hatchPet(potion: HatchingPotion, egg: Egg) {
compositeSubscription.add(this.inventoryRepository.hatchPet(egg, potion) {
val petWrapper = View.inflate(this, R.layout.pet_imageview, null) as? FrameLayout
val petImageView = petWrapper?.findViewById(R.id.pet_imageview) as? SimpleDraweeView
DataBindingUtils.loadImage(petImageView, "social_Pet-" + egg.key + "-" + potion.key)
val potionName = potion.text
val eggName = egg.text
val dialog = HabiticaAlertDialog(this)
dialog.setTitle(getString(R.string.hatched_pet_title, potionName, eggName))
dialog.setAdditionalContentView(petWrapper)
dialog.addButton(R.string.onwards, true) { hatchingDialog, _ -> hatchingDialog.dismiss() }
dialog.addButton(R.string.share, false) { hatchingDialog, _ ->
val event1 = ShareEvent()
event1.sharedMessage = getString(R.string.share_hatched, potionName, eggName)
val petImageSideLength = 140
val sharedImage = Bitmap.createBitmap(petImageSideLength, petImageSideLength, Bitmap.Config.ARGB_8888)
val canvas = Canvas(sharedImage)
petImageView?.drawable?.setBounds(0, 0, petImageSideLength, petImageSideLength)
petImageView?.drawable?.draw(canvas)
event1.shareImage = sharedImage
EventBus.getDefault().post(event1)
hatchingDialog.dismiss()
}
dialog.enqueue()
}.subscribe(Consumer { }, RxErrorHandler.handleEmptyError()))
}
@Subscribe
fun onConsumablePurchased(event: ConsumablePurchasedEvent) {
userRepository.retrieveUser(false, true).subscribe(Consumer {}, RxErrorHandler.handleEmptyError())
}
companion object {
const val SELECT_CLASS_RESULT = 11
const val GEM_PURCHASE_REQUEST = 111
const val NOTIFICATION_CLICK = 222
const val NOTIFICATION_ACCEPT = 223
const val NOTIFICATION_REJECT = 224
}
}
| gpl-3.0 | c211f987b857b370aad4b7defb1eb394 | 42.942895 | 185 | 0.664511 | 5.224854 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/arguments/util.kt | 4 | 3280 | // 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.gradleTooling.arguments
import org.gradle.api.Task
import org.gradle.api.logging.Logger
import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder
import org.jetbrains.kotlin.idea.gradleTooling.getDeclaredMethodOrNull
import org.jetbrains.kotlin.idea.gradleTooling.getMethodOrNull
import org.jetbrains.kotlin.idea.projectModel.CompilerArgumentsCacheMapper
import java.io.File
import java.lang.reflect.Method
private fun buildDependencyClasspath(compileKotlinTask: Task): List<String> {
val abstractKotlinCompileClass =
compileKotlinTask.javaClass.classLoader.loadClass(AbstractKotlinGradleModelBuilder.ABSTRACT_KOTLIN_COMPILE_CLASS)
val getCompileClasspath =
abstractKotlinCompileClass.getDeclaredMethodOrNull("getCompileClasspath") ?: abstractKotlinCompileClass.getDeclaredMethodOrNull(
"getClasspath"
) ?: return emptyList()
@Suppress("UNCHECKED_CAST")
return (getCompileClasspath(compileKotlinTask) as? Collection<File>)?.map { it.path } ?: emptyList()
}
fun buildCachedArgsInfo(
compileKotlinTask: Task,
cacheMapper: CompilerArgumentsCacheMapper,
): CachedExtractedArgsInfo {
val cachedCurrentArguments = CompilerArgumentsCachingChain.extractAndCacheTask(compileKotlinTask, cacheMapper, defaultsOnly = false)
val cachedDefaultArguments = CompilerArgumentsCachingChain.extractAndCacheTask(compileKotlinTask, cacheMapper, defaultsOnly = true)
val dependencyClasspath =
buildDependencyClasspath(compileKotlinTask).map { KotlinCachedRegularCompilerArgument(cacheMapper.cacheArgument(it)) }
return CachedExtractedArgsInfo(cacheMapper.cacheOriginIdentifier, cachedCurrentArguments, cachedDefaultArguments, dependencyClasspath)
}
fun buildSerializedArgsInfo(
compileKotlinTask: Task,
cacheMapper: CompilerArgumentsCacheMapper,
logger: Logger
): CachedSerializedArgsInfo {
val compileTaskClass = compileKotlinTask.javaClass
val getCurrentArguments = compileTaskClass.getMethodOrNull("getSerializedCompilerArguments")
val getDefaultArguments = compileTaskClass.getMethodOrNull("getDefaultSerializedCompilerArguments")
val currentArguments = safelyGetArguments(compileKotlinTask, getCurrentArguments, logger)
.map { KotlinCachedRegularCompilerArgument(cacheMapper.cacheArgument(it)) }
val defaultArguments = safelyGetArguments(compileKotlinTask, getDefaultArguments, logger)
.map { KotlinCachedRegularCompilerArgument(cacheMapper.cacheArgument(it)) }
val dependencyClasspath = buildDependencyClasspath(compileKotlinTask)
.map { KotlinCachedRegularCompilerArgument(cacheMapper.cacheArgument(it)) }
return CachedSerializedArgsInfo(cacheMapper.cacheOriginIdentifier, currentArguments, defaultArguments, dependencyClasspath)
}
@Suppress("UNCHECKED_CAST")
private fun safelyGetArguments(compileKotlinTask: Task, accessor: Method?, logger: Logger) = try {
accessor?.invoke(compileKotlinTask) as? List<String>
} catch (e: Exception) {
logger.warn(e.message ?: "Unexpected exception: $e", e)
null
} ?: emptyList()
| apache-2.0 | 6cbba946a77bd42a052ffaba3182a1bc | 54.59322 | 158 | 0.810366 | 5.34202 | false | false | false | false |
michaelkourlas/voipms-sms-client | voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/sms/workers/SendMessageWorker.kt | 1 | 13096 | /*
* VoIP.ms SMS
* Copyright (C) 2017-2021 Michael Kourlas
*
* 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 net.kourlas.voipms_sms.sms.workers
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import androidx.work.*
import com.squareup.moshi.JsonClass
import com.squareup.moshi.JsonDataException
import net.kourlas.voipms_sms.R
import net.kourlas.voipms_sms.database.Database
import net.kourlas.voipms_sms.network.NetworkManager
import net.kourlas.voipms_sms.notifications.Notifications
import net.kourlas.voipms_sms.preferences.accountConfigured
import net.kourlas.voipms_sms.preferences.getEmail
import net.kourlas.voipms_sms.preferences.getPassword
import net.kourlas.voipms_sms.sms.ConversationId
import net.kourlas.voipms_sms.sms.Message
import net.kourlas.voipms_sms.utils.httpPostWithMultipartFormData
import net.kourlas.voipms_sms.utils.logException
import java.io.IOException
/**
* Worker used to send an SMS message using the VoIP.ms API.
*/
class SendMessageWorker(context: Context, params: WorkerParameters) :
CoroutineWorker(context, params) {
private var conversationId: ConversationId? = null
private var error: String? = null
private var markedAsSent: Boolean = false
private var markedAsNotSent: Boolean = false
override suspend fun doWork(): Result {
// Terminate quietly if we cannot find the message we are supposed
// to send.
val databaseId =
inputData.getLong(
applicationContext.getString(
R.string.send_message_database_id
), -1
)
if (databaseId == -1L) {
return Result.failure()
}
try {
// Send the message we were asked to send.
sendMessage(databaseId)
// Send a broadcast indicating that the message has been sent, or that
// an attempt to send it was made.
conversationId?.let {
val sentMessageBroadcastIntent = Intent(
applicationContext.getString(
R.string.sent_message_action, it.did, it.contact
)
)
if (error != null) {
sentMessageBroadcastIntent.putExtra(
applicationContext.getString(
R.string.sent_message_error
), error
)
}
applicationContext.sendBroadcast(sentMessageBroadcastIntent)
}
return if (error == null) {
Result.success()
} else {
Result.failure()
}
} finally {
// We are not going to try sending this message again unless the
// user triggers it by clicking on the message, so ensure the
// database is correctly updated even on failure.
if (!markedAsSent && !markedAsNotSent) {
try {
Database.getInstance(
applicationContext
).markMessageNotSent(
databaseId
)
} catch (e: Exception) {
}
}
}
}
override suspend fun getForegroundInfo(): ForegroundInfo {
val notification = Notifications.getInstance(applicationContext)
.getSyncMessageSendNotification()
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ForegroundInfo(
Notifications.SYNC_SEND_MESSAGE_NOTIFICATION_ID,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
)
} else {
ForegroundInfo(
Notifications.SYNC_SEND_MESSAGE_NOTIFICATION_ID,
notification
)
}
}
/**
* Sends the message we were asked to send using the VoIP.ms API and
* updates the database accordingly.
*/
private suspend fun sendMessage(databaseId: Long) {
try {
// Terminate quietly if it is impossible to send messages due to
// account configuration.
if (!accountConfigured(applicationContext)) {
return
}
// Retrieve the message we are supposed to send. Terminate quietly
// if it is not in a valid state.
val message = Database.getInstance(applicationContext)
.getMessageDatabaseId(databaseId)
conversationId = message?.conversationId
if (message == null || !message.isDeliveryInProgress) {
return
}
// Terminate if no network connection is available.
if (!NetworkManager.getInstance().isNetworkConnectionAvailable(
applicationContext
)
) {
error = applicationContext.getString(
R.string.send_message_error_network
)
Database.getInstance(
applicationContext
).markMessageNotSent(
message.databaseId
)
return
}
// Send the message using the VoIP.ms API. If we succeed, mark the
// the message was sent. If not, mark it as not having been sent.
val voipId = sendMessageWithVoipMsApi(message)
if (voipId != null) {
Database.getInstance(
applicationContext
).markMessageSent(
message.databaseId, voipId
)
markedAsSent = true
} else {
Database.getInstance(
applicationContext
).markMessageNotSent(
message.databaseId
)
markedAsNotSent = true
}
// If this request came from an inline reply, refresh the
// notification.
val inlineReply = inputData.getBoolean(
applicationContext.getString(
R.string.send_message_inline_reply
), false
)
if (inlineReply) {
val inlineReplyDid = inputData.getString(
applicationContext.getString(
R.string.send_message_inline_reply_did
)
) ?: return
val inlineReplyContact = inputData.getString(
applicationContext.getString(
R.string.send_message_inline_reply_contact
)
) ?: return
Notifications.getInstance(applicationContext).showNotifications(
setOf(ConversationId(inlineReplyDid, inlineReplyContact)),
inlineReplyMessages = listOf(message)
)
}
} catch (e: Exception) {
logException(e)
error = applicationContext.getString(
R.string.send_message_error_unknown
)
}
}
@JsonClass(generateAdapter = true)
data class MessageResponse(val status: String, val sms: Long?)
/**
* Sends the specified message using the VoIP.ms API
*
* @return Null if the message could not be sent.
*/
private suspend fun sendMessageWithVoipMsApi(message: Message): Long? {
// Get JSON response from API
val response: MessageResponse? = getMessageResponse(message)
// Get VoIP.ms ID from response
if (response?.status == "") {
error = applicationContext.getString(
R.string.send_message_error_api_parse
)
return null
}
if (response?.status != "success") {
error = when (response?.status) {
"invalid_credentials" -> applicationContext.getString(
R.string.send_message_error_api_error_invalid_credentials
)
"invalid_dst" -> applicationContext.getString(
R.string.send_message_error_api_error_invalid_dst
)
"invalid_sms" -> applicationContext.getString(
R.string.send_message_error_api_error_invalid_sms
)
"limit_reached" -> applicationContext.getString(
R.string.send_message_error_api_error_limit_reached
)
"message_empty" -> applicationContext.getString(
R.string.send_message_error_api_error_message_empty
)
"missing_sms" -> applicationContext.getString(
R.string.send_message_error_api_error_missing_sms
)
"sms_failed" -> applicationContext.getString(
R.string.send_message_error_api_error_sms_failed
)
"sms_toolong" -> applicationContext.getString(
R.string.send_message_error_api_error_sms_toolong
)
else -> applicationContext.getString(
R.string.send_message_error_api_error, response?.status
)
}
return null
}
if (response.sms == 0L) {
error = applicationContext.getString(
R.string.send_message_error_api_parse
)
return null
}
return response.sms
}
private suspend fun getMessageResponse(message: Message): MessageResponse? {
try {
repeat(3) {
try {
return httpPostWithMultipartFormData(
applicationContext,
"https://www.voip.ms/api/v1/rest.php",
mapOf(
"api_username" to getEmail(applicationContext),
"api_password" to getPassword(applicationContext),
"method" to "sendSMS",
"did" to message.did,
"dst" to message.contact,
"message" to message.text
)
)
} catch (e: IOException) {
// Try again...
}
}
error = applicationContext.getString(
R.string.send_message_error_api_request
)
return null
} catch (e: JsonDataException) {
logException(e)
error = applicationContext.getString(
R.string.send_message_error_api_parse
)
return null
} catch (e: Exception) {
logException(e)
error = applicationContext.getString(
R.string.send_message_error_unknown
)
return null
}
}
companion object {
/**
* Sends the message associated with the specified database ID.
*/
fun sendMessage(
context: Context, databaseId: Long,
inlineReplyConversationId: ConversationId? = null
) {
val work = OneTimeWorkRequestBuilder<SendMessageWorker>()
.setInputData(
workDataOf(
context.getString(
R.string.send_message_database_id
) to databaseId,
context.getString(
R.string.send_message_inline_reply
)
to (inlineReplyConversationId != null),
context.getString(
R.string.send_message_inline_reply_did
)
to inlineReplyConversationId?.did,
context.getString(
R.string.send_message_inline_reply_contact
)
to inlineReplyConversationId?.contact
)
)
.setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
.build()
WorkManager.getInstance(context).enqueueUniqueWork(
context.getString(R.string.send_message_work_id, databaseId),
ExistingWorkPolicy.KEEP, work
)
}
}
}
| apache-2.0 | 3470ea617f0c8f26af58ff06d076ecd3 | 36.849711 | 82 | 0.535125 | 5.465776 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/KotlinCopyPasteReferenceProcessor.kt | 2 | 37693 | // 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.codeInsight
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.editorActions.CopyPastePostProcessor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.util.ProgressIndicatorUtils
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.concurrency.AppExecutorUtil
import org.jetbrains.annotations.TestOnly
import org.jetbrains.concurrency.CancellablePromise
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.util.runReadActionInSmartMode
import org.jetbrains.kotlin.idea.caches.resolve.allowResolveInDispatchThread
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.codeInsight.ReviewAddedImports.reviewAddedImports
import org.jetbrains.kotlin.idea.codeInsight.shorten.performDelayedRefactoringRequests
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.references.*
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.invokeLater
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.kdoc.psi.api.KDocElement
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.utils.findFunction
import org.jetbrains.kotlin.resolve.scopes.utils.findVariable
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import java.awt.datatransfer.Transferable
import java.awt.datatransfer.UnsupportedFlavorException
import java.io.IOException
import java.util.*
import java.util.concurrent.Callable
class KotlinCopyPasteReferenceProcessor : CopyPastePostProcessor<BasicKotlinReferenceTransferableData>() {
override fun extractTransferableData(content: Transferable): List<BasicKotlinReferenceTransferableData> {
if (CodeInsightSettings.getInstance().ADD_IMPORTS_ON_PASTE != CodeInsightSettings.NO) {
try {
val flavor = BasicKotlinReferenceTransferableData.dataFlavor ?: return listOf()
val data = content.getTransferData(flavor) as? BasicKotlinReferenceTransferableData ?: return listOf()
// copy to prevent changing of original by convertLineSeparators
return listOf(data.clone())
} catch (ignored: UnsupportedFlavorException) {
} catch (ignored: IOException) {
}
}
return listOf()
}
override fun collectTransferableData(
file: PsiFile,
editor: Editor,
startOffsets: IntArray,
endOffsets: IntArray
): List<BasicKotlinReferenceTransferableData> {
if (file !is KtFile || DumbService.getInstance(file.getProject()).isDumb) return listOf()
check(startOffsets.size == endOffsets.size) {
"startOffsets ${startOffsets.contentToString()} has to have same size as endOffsets ${endOffsets.contentToString()}"
}
val packageName = file.packageDirective?.fqName?.asString() ?: ""
val imports = file.importDirectives.map { it.text }
val endOfImportsOffset = file.importDirectives.maxOfOrNull { it.endOffset } ?: file.packageDirective?.endOffset ?: 0
val offsetDelta = if (startOffsets.any { it <= endOfImportsOffset }) 0 else endOfImportsOffset
val text = file.text.substring(offsetDelta)
val ranges = startOffsets.indices.map { TextRange(startOffsets[it], endOffsets[it]) }
val references: List<KotlinReferenceData>? = run {
val anyMainReferenceTextRange = ranges.firstOrNull { textRange ->
file.elementsInRange(textRange).flatMap { it.collectDescendantsOfType<KtElement>() }.firstOrNull { it.mainReference != null } != null
}
if (anyMainReferenceTextRange != null) null else emptyList()
}
val locationFqName = if (startOffsets.size == 1) {
val fqName = file.namedDeclarationFqName(startOffsets[0] - 1)
fqName?.takeIf { it == file.namedDeclarationFqName(endOffsets[0] + 1) }
} else null
return listOf(
BasicKotlinReferenceTransferableData(
sourceFileUrl = file.virtualFile.url,
packageName = packageName,
imports = imports,
sourceTextOffset = offsetDelta,
sourceText = text,
textRanges = ranges,
references = references,
locationFqName = locationFqName
)
)
}
private fun KtFile.namedDeclarationFqName(offset: Int): String? =
if (offset in 0 until textLength)
PsiTreeUtil.getNonStrictParentOfType(this.findElementAt(offset), KtNamedDeclaration::class.java)?.fqName?.asString()
else null
private fun collectReferenceData(
textRanges: List<TextRange>,
file: KtFile,
targetFile: KtFile,
fakePackageName: String,
sourcePackageName: String,
indicator: ProgressIndicator
): List<KotlinReferenceData> =
collectReferenceData(
file = file,
startOffsets = textRanges.map { it.startOffset }.toIntArray(),
endOffsets = textRanges.map { it.endOffset }.toIntArray(),
fakePackageName = fakePackageName,
sourcePackageName = sourcePackageName,
targetPackageName = runReadAction { targetFile.packageDirective?.fqName?.asString() ?: "" },
indicator = indicator
)
fun collectReferenceData(
file: KtFile,
startOffsets: IntArray,
endOffsets: IntArray,
fakePackageName: String? = null,
sourcePackageName: String? = null,
targetPackageName: String? = null,
indicator: ProgressIndicator? = null
): List<KotlinReferenceData> {
val ranges = toTextRanges(startOffsets, endOffsets)
val elements = ranges.flatMap { textRange ->
runReadAction {
indicator?.checkCanceled()
file.elementsInRange(textRange).filter { it is KtElement || it is KDocElement }
}
}.takeIf { it.isNotEmpty() } ?: return emptyList()
val smartPointerManager = SmartPointerManager.getInstance(file.project)
val allElementRefsToResolve = runReadAction {
elements.flatMap { it.collectDescendantsOfType<KtElement>() }.map {
smartPointerManager.createSmartPsiElementPointer(it, file)
}
}.takeIf { it.isNotEmpty() } ?: return emptyList()
val project = file.project
val bindingContext =
ReadAction.nonBlocking<BindingContext> {
return@nonBlocking allowResolveInDispatchThread {
file.getResolutionFacade().analyze(allElementRefsToResolve.mapNotNull { it.element }, BodyResolveMode.PARTIAL)
}
}
.inSmartMode(project)
.expireWhen { val none = allElementRefsToResolve.none { it.element != null }
none
}
.run {
indicator?.let { this.wrapProgress(indicator) } ?: this
}
.expireWith(KotlinPluginDisposable.getInstance(project))
.executeSynchronously()
val result = mutableListOf<KotlinReferenceData>()
for (ktElementRef in allElementRefsToResolve) {
project.runReadActionInSmartMode {
indicator?.checkCanceled()
ktElementRef.element?.let {
result.addReferenceDataInsideElement(
it, file, ranges, bindingContext, fakePackageName = fakePackageName,
sourcePackageName = sourcePackageName, targetPackageName = targetPackageName
)
}
}
}
return result
}
private fun List<PsiElement>.forEachDescendant(consumer: (KtElement) -> Unit) {
this.forEach { it.forEachDescendant(consumer) }
}
private fun PsiElement.forEachDescendant(consumer: (KtElement) -> Unit) {
if (PsiTreeUtil.getNonStrictParentOfType(this, *IGNORE_REFERENCES_INSIDE) != null) return
this.forEachDescendantOfType<KtElement>(canGoInside = {
it::class.java as Class<*> !in IGNORE_REFERENCES_INSIDE
}) { ktElement ->
consumer(ktElement)
}
}
private fun MutableCollection<KotlinReferenceData>.addReferenceDataInsideElement(
ktElement: KtElement,
file: KtFile,
textRanges: List<TextRange>,
bindingContext: BindingContext,
fakePackageName: String? = null,
sourcePackageName: String? = null,
targetPackageName: String? = null
) {
val reference = file.project.runReadActionInSmartMode { ktElement.mainReference } ?: return
val descriptors = resolveReference(reference, bindingContext)
//check whether this reference is unambiguous
if (reference !is KtMultiReference<*> && descriptors.size > 1) return
for (descriptor in descriptors) {
val effectiveReferencedDescriptors =
DescriptorToSourceUtils.getEffectiveReferencedDescriptors(descriptor).asSequence()
val declaration = effectiveReferencedDescriptors
.map { DescriptorToSourceUtils.getSourceFromDescriptor(it) }
.singleOrNull()
if (declaration?.isInCopiedArea(file, textRanges) == true ||
!reference.canBeResolvedViaImport(descriptor, bindingContext)
) continue
val importableFqName = descriptor.importableFqName ?: continue
val importableName = importableFqName.asString()
val pkgName = descriptor.findPackageFqNameSafe()?.asString() ?: ""
val importableShortName = importableFqName.shortName().asString()
val fqName = if (fakePackageName == pkgName) {
// It is possible to resolve unnecessary references from a target package (as we resolve it from a fake package)
if (sourcePackageName == targetPackageName && importableName == "$fakePackageName.$importableShortName") {
continue
}
// roll back to original package name when we faced faked pkg name
sourcePackageName + importableName.substring(fakePackageName.length)
} else importableName
val kind = KotlinReferenceData.Kind.fromDescriptor(descriptor) ?: continue
val isQualifiable = KotlinReferenceData.isQualifiable(ktElement, descriptor)
val relativeStart = ktElement.textRange.startOffset
val relativeEnd = ktElement.textRange.endOffset
add(KotlinReferenceData(relativeStart, relativeEnd, fqName, isQualifiable, kind))
}
}
private data class ReferenceToRestoreData(
val reference: KtReference,
val refData: KotlinReferenceData,
val declarationDescriptors: Collection<DeclarationDescriptor>
)
private data class PsiElementByTextRange(val originalTextRange: TextRange, val element: SmartPsiElementPointer<KtElement>)
override fun processTransferableData(
project: Project,
editor: Editor,
bounds: RangeMarker,
caretOffset: Int,
indented: Ref<in Boolean>,
values: List<BasicKotlinReferenceTransferableData>
) {
if (DumbService.getInstance(project).isDumb ||
CodeInsightSettings.getInstance().ADD_IMPORTS_ON_PASTE == CodeInsightSettings.NO
) return
val document = editor.document
val file = PsiDocumentManager.getInstance(project).getPsiFile(document)
if (file !is KtFile) return
if (isPastedToTheSameOrigin(file, caretOffset, values)) return
processReferenceData(project, editor, file, bounds.startOffset, values.single())
}
private fun isPastedToTheSameOrigin(
file: KtFile,
caretOffset: Int,
values: List<BasicKotlinReferenceTransferableData>
): Boolean {
if (values.size == 1 && values[0].sourceFileUrl == file.virtualFile.url &&
values[0].locationFqName != null &&
// check locationFqName on position before pasted snippet
values[0].locationFqName == file.namedDeclarationFqName(caretOffset - 1)
) {
val currentImports = file.importDirectives.map { it.text }.toSet()
val originalImports = values.flatMap { it.imports }.toSet()
if (currentImports == originalImports) {
return true
}
}
return false
}
private fun processReferenceData(
project: Project,
editor: Editor,
file: KtFile,
blockStart: Int,
transferableData: BasicKotlinReferenceTransferableData
) {
if (transferableData.references?.isEmpty() == true) return
PsiDocumentManager.getInstance(project).commitAllDocuments()
var startOffsetDelta = blockStart
// figure out candidate elements in UI thread in paste phase
// as psi elements could be changed later on - relative offsets are used for mapping purposes
val elementsByRange = runReadAction {
transferableData.textRanges.flatMap { originalTextRange ->
val elementsList = mutableListOf<PsiElementByTextRange>()
val textRange = TextRange(
startOffsetDelta,
startOffsetDelta + originalTextRange.endOffset - originalTextRange.startOffset
)
startOffsetDelta = startOffsetDelta + originalTextRange.endOffset - originalTextRange.startOffset + 1
file.elementsInRange(textRange)
.filter { it is KtElement || it is KDocElement }
.forEachDescendant {
val range = TextRange(
originalTextRange.startOffset + it.textRange.startOffset - textRange.startOffset,
originalTextRange.startOffset + it.textRange.endOffset - textRange.startOffset
)
elementsList.add(PsiElementByTextRange(range, it.createSmartPointer()))
}
elementsList
}
}
processReferenceData(project, editor, file) { indicator: ProgressIndicator ->
findReferenceDataToRestore(
file,
indicator,
elementsByRange,
transferableData
)
}
}
fun processReferenceData(project: Project, editor: Editor, file: KtFile, blockStart: Int, referenceData: Array<KotlinReferenceData>) {
processReferenceData(project, editor, file) { indicator: ProgressIndicator ->
findReferencesToRestore(file, blockStart, referenceData)
}
}
private fun processReferenceData(
project: Project,
editor: Editor,
file: KtFile,
findReferenceProvider: (indicator: ProgressIndicator) -> List<ReferenceToRestoreData>
) {
val task = object : Task.Backgroundable(project, KotlinBundle.message("copy.paste.resolve.references"), true) {
override fun run(indicator: ProgressIndicator) {
assert(!ApplicationManager.getApplication().isWriteAccessAllowed) {
"Resolving references on dispatch thread leads to live lock"
}
val referencesPossibleToRestore = findReferenceProvider(indicator)
applyResolvedImports(project, referencesPossibleToRestore, file, editor)
}
}
ProgressManager.getInstance().run(task)
}
private fun applyResolvedImports(
project: Project,
referencesPossibleToRestore: List<ReferenceToRestoreData>,
file: KtFile,
editor: Editor
) {
invokeLater {
val selectedReferencesToRestore =
showRestoreReferencesDialog(project, referencesPossibleToRestore)
if (selectedReferencesToRestore.isEmpty()) return@invokeLater
project.executeWriteCommand(KotlinBundle.message("resolve.pasted.references")) {
val imported = TreeSet<String>()
restoreReferences(selectedReferencesToRestore, file, imported)
reviewAddedImports(project, editor, file, imported)
}
}
}
private fun findReferenceDataToRestore(
file: PsiFile,
indicator: ProgressIndicator,
elementsByRange: List<PsiElementByTextRange>,
transferableData: BasicKotlinReferenceTransferableData
): List<ReferenceToRestoreData> {
if (file !is KtFile) return emptyList()
val project = runReadAction { file.project }
val referencesByRange: Map<TextRange, KtReference> = elementsByRange.mapNotNull { elementByTextRange ->
val smartPsiElementPointer = elementByTextRange.element
ReadAction
.nonBlocking(Callable<KtReference?> {
smartPsiElementPointer.element?.mainReference
})
.inSmartMode(project)
.wrapProgress(indicator)
.expireWhen { smartPsiElementPointer.element == null }
.expireWith(KotlinPluginDisposable.getInstance(project))
.executeSynchronously()?.let { mainReference ->
runReadAction {
val textRange = mainReference.element.textRange
val findReference = findReference(file, textRange)
findReference?.let {
// remap reference to the original (as it was on paste phase) text range
val itTextRange = it.element.textRange
val refTextRange = mainReference.element.textRange
val originalTextRange = elementByTextRange.originalTextRange
val offset = originalTextRange.startOffset - refTextRange.startOffset
val range = TextRange(itTextRange.startOffset + offset, itTextRange.endOffset + offset)
range to it
}
}
}
}.toMap()
val sourcePackageName = transferableData.packageName
val imports: List<String> = transferableData.imports
// Step 0. Recreate original source file (i.e. source file as it was on copy action) and resolve references from it
val ctxFile = sourceFile(project, transferableData) ?: file
// put original source file to some fake package to avoid ambiguous resolution ( a real file VS a virtual file )
val fakePackageName = "__kotlin.__some.__funky.__package"
val dummyOrigFileProlog =
"""
package $fakePackageName
${buildDummySourceScope(sourcePackageName, indicator, imports, fakePackageName, file, transferableData, ctxFile)}
""".trimIndent()
val sourceFileUrl = transferableData.sourceFileUrl
val script = !sourceFileUrl.endsWith(KotlinFileType.EXTENSION)
val extension = run {
if (!script) return@run KotlinFileType.EXTENSION
ScriptDefinitionsManager.getInstance(project).getKnownFilenameExtensions().filter {
sourceFileUrl.endsWith(it)
}.sortedByDescending { it.length }.firstOrNull() ?: KotlinFileType.EXTENSION
}
val dummyOriginalFile = runReadAction {
KtPsiFactory(project)
.createAnalyzableFile(
"dummy-original.$extension",
"$dummyOrigFileProlog${transferableData.sourceText}",
ctxFile
)
}
if (script) {
val originalFile = runReadAction {
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(sourceFileUrl) ?: return@runReadAction null
PsiManager.getInstance(project).findFile(virtualFile)
} ?: return emptyList()
dummyOriginalFile.originalFile = originalFile
}
val offsetDelta = dummyOrigFileProlog.length - transferableData.sourceTextOffset
val dummyOriginalFileTextRanges =
// it is required as it is shifted by dummy prolog
transferableData.textRanges.map { TextRange(it.startOffset + offsetDelta, it.endOffset + offsetDelta) }
// Step 1. Find references in copied blocks of (recreated) source file
val sourceFileBasedReferences =
collectReferenceData(dummyOriginalFileTextRanges, dummyOriginalFile, file, fakePackageName, sourcePackageName, indicator).map {
it.copy(startOffset = it.startOffset - offsetDelta, endOffset = it.endOffset - offsetDelta)
}
indicator.checkCanceled()
// Step 2. Find references to restore in a target file
return ProgressIndicatorUtils.awaitWithCheckCanceled(
submitNonBlocking(project, indicator) {
return@submitNonBlocking findReferencesToRestore(file, indicator, sourceFileBasedReferences, referencesByRange)
}
)
}
private fun <T> submitNonBlocking(project: Project, indicator: ProgressIndicator, block: () -> T): CancellablePromise<T> =
ReadAction.nonBlocking<T> {
return@nonBlocking block()
}
.withDocumentsCommitted(project)
.wrapProgress(indicator)
.expireWith(KotlinPluginDisposable.getInstance(project))
.inSmartMode(project)
.submit(AppExecutorUtil.getAppExecutorService())
private fun buildDummySourceScope(
sourcePkgName: String,
indicator: ProgressIndicator,
imports: List<String>,
fakePkgName: String,
file: KtFile,
transferableData: BasicKotlinReferenceTransferableData,
ctxFile: KtFile
): String {
// it could be that copied block contains inner classes or enums
// to solve this problem a special file is build:
// it contains imports from source package replaced with a fake package prefix
//
// result scope has to contain
// - those fake package imports those are successfully resolved (i.e. present in copied block)
// - those source package imports those are not present in a fake package
// - all rest imports
val sourceImportPrefix = "import ${if (sourcePkgName.isEmpty()) fakePkgName else sourcePkgName}"
val fakeImportPrefix = "import $fakePkgName"
val affectedSourcePkgImports = imports.filter { it.startsWith(sourceImportPrefix) }
val fakePkgImports = affectedSourcePkgImports.map { fakeImportPrefix + it.substring(sourceImportPrefix.length) }
fun joinLines(items: Collection<String>) = items.joinToString("\n")
val project = file.project
val dummyImportsFile = runReadAction {
KtPsiFactory(project)
.createAnalyzableFile(
"dummy-imports.kt",
"package $fakePkgName\n" +
"${joinLines(fakePkgImports)}\n" +
transferableData.sourceText,
ctxFile
)
}
val dummyFileImports = ReadAction.nonBlocking(Callable {
dummyImportsFile.collectDescendantsOfType<KtImportDirective>().mapNotNull { directive ->
val importedReference =
directive.importedReference?.getQualifiedElementSelector()?.mainReference?.resolve() as? KtNamedDeclaration
importedReference?.let { directive.text }
}
}).inSmartMode(project)
.wrapProgress(indicator)
.expireWith(KotlinPluginDisposable.getInstance(project))
.executeSynchronously()
val dummyFileImportsSet = dummyFileImports.toSet()
val filteredImports = imports.filter {
!it.startsWith(sourceImportPrefix) ||
!dummyFileImportsSet.contains(fakeImportPrefix + it.substring(sourceImportPrefix.length))
}
return """
${joinLines(dummyFileImports)}
${if (sourcePkgName.isNotEmpty()) "import ${sourcePkgName}.*" else ""}
${joinLines(filteredImports)}
"""
}
private fun sourceFile(project: Project, transferableData: BasicKotlinReferenceTransferableData): KtFile? =
runReadAction {
val sourceFile = VirtualFileManager.getInstance().findFileByUrl(transferableData.sourceFileUrl) ?: return@runReadAction null
if (sourceFile.getSourceRoot(project) == null) return@runReadAction null
PsiManager.getInstance(project).findFile(sourceFile) as? KtFile
}
private fun filterReferenceData(
refData: KotlinReferenceData,
fileResolutionScope: LexicalScope
): Boolean {
if (refData.isQualifiable) return true
val originalFqName = FqName(refData.fqName)
val name = originalFqName.shortName()
return when (refData.kind) {
// filter if function is already imported
KotlinReferenceData.Kind.FUNCTION -> fileResolutionScope
.findFunction(name, NoLookupLocation.FROM_IDE) { it.importableFqName == originalFqName } == null
// filter if property is already imported
KotlinReferenceData.Kind.PROPERTY -> fileResolutionScope
.findVariable(name, NoLookupLocation.FROM_IDE) { it.importableFqName == originalFqName } == null
else -> true
}
}
private fun findReferencesToRestore(
file: PsiFile,
blockStart: Int,
referenceData: Array<out KotlinReferenceData>
): List<ReferenceToRestoreData> = findReferences(file, referenceData.map { it to findReference(it, file as KtFile, blockStart) })
private fun findReferencesToRestore(
file: PsiFile,
indicator: ProgressIndicator,
referenceData: List<KotlinReferenceData>,
referencesByPosition: Map<TextRange, KtReference>
): List<ReferenceToRestoreData> {
// use already found reference candidates - so file could be changed
return findReferences(file, referenceData.map {
indicator.checkCanceled()
val textRange = TextRange(it.startOffset, it.endOffset)
val reference = referencesByPosition[textRange]
it to reference
})
}
private fun findReferences(
file: PsiFile,
references: List<Pair<KotlinReferenceData, KtReference?>>
): List<ReferenceToRestoreData> {
val ktFile = file as? KtFile ?: return listOf()
val resolutionFacade = runReadAction { ktFile.getResolutionFacade() }
val referencesList = mutableListOf<Pair<KotlinReferenceData, KtReference?>>()
val bindingContext =
try {
runReadAction {
referencesList.addAll(references.mapNotNull { if (it.second?.element?.isValid == true) it.first to it.second else null })
resolutionFacade.analyze(
referencesList.mapNotNull { it.second?.element },
BodyResolveMode.PARTIAL
)
}
} catch (e: Throwable) {
if (e is ControlFlowException) throw e
LOG.error("Failed to analyze references after copy paste", e)
return emptyList()
}
val fileResolutionScope = runReadAction { resolutionFacade.getFileResolutionScope(ktFile) }
return referencesList.mapNotNull { pair ->
val data = pair.first
val reference = pair.second
reference?.let { createReferenceToRestoreData(it, data, ktFile, fileResolutionScope, bindingContext) }
}
}
private fun findReference(data: KotlinReferenceData, file: KtFile, blockStart: Int): KtReference? =
findReference(file, TextRange(data.startOffset + blockStart, data.endOffset + blockStart))
private fun findReference(file: KtFile, desiredRange: TextRange): KtReference? {
val element = runReadAction { file.findElementAt(desiredRange.startOffset) } ?: return null
return findReference(element, desiredRange)
}
private fun findReference(element: PsiElement, desiredRange: TextRange): KtReference? = runReadAction {
for (current in element.parentsWithSelf) {
val range = current.textRange
if (current is KtElement && range == desiredRange) {
current.mainReference?.let { return@runReadAction it }
}
if (range !in desiredRange) return@runReadAction null
}
return@runReadAction null
}
private fun createReferenceToRestoreData(
reference: KtReference,
refData: KotlinReferenceData,
file: KtFile,
fileResolutionScope: LexicalScope,
bindingContext: BindingContext
): ReferenceToRestoreData? {
if (!filterReferenceData(refData, fileResolutionScope)) return null
val originalFqName = FqName(refData.fqName)
val referencedDescriptors = resolveReference(reference, bindingContext)
val referencedFqNames = referencedDescriptors
.filterNot { ErrorUtils.isError(it) }
.mapNotNull { it.importableFqName }
.toSet()
if (referencedFqNames.singleOrNull() == originalFqName) return null
// check that descriptor to import exists and is accessible from the current module
if (findImportableDescriptors(originalFqName, file).none { KotlinReferenceData.Kind.fromDescriptor(it) == refData.kind }) {
return null
}
val fqName = FqName(refData.fqName)
val declarationDescriptors: Collection<DeclarationDescriptor> =
if (refData.isQualifiable) {
if (reference is KDocReference) {
findImportableDescriptors(fqName, file)
} else {
emptyList()
}
} else {
listOfNotNull(findCallableToImport(fqName, file))
}
return ReferenceToRestoreData(reference, refData, declarationDescriptors)
}
private fun resolveReference(reference: KtReference, bindingContext: BindingContext): List<DeclarationDescriptor> {
val element = reference.element
return runReadAction {
if (element.isValid && element is KtNameReferenceExpression && reference is KtSimpleNameReference) {
val classifierDescriptor =
bindingContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, element]
(classifierDescriptor ?: bindingContext[BindingContext.REFERENCE_TARGET, element])?.let { return@runReadAction listOf(it) }
}
reference.resolveToDescriptors(bindingContext).toList()
}
}
private fun restoreReferences(
referencesToRestore: Collection<ReferenceToRestoreData>,
file: KtFile,
imported: MutableSet<String>
) {
val importHelper = ImportInsertHelper.getInstance(file.project)
val smartPointerManager = SmartPointerManager.getInstance(file.project)
data class BindingRequest(
val pointer: SmartPsiElementPointer<KtSimpleNameExpression>,
val fqName: FqName
)
val bindingRequests = ArrayList<BindingRequest>()
val descriptorsToImport = ArrayList<DeclarationDescriptor>()
for (referenceToRestore in referencesToRestore) {
val reference = referenceToRestore.reference
val refData = referenceToRestore.refData
if (!reference.element.isValid) continue
descriptorsToImport.addAll(referenceToRestore.declarationDescriptors)
val fqName = FqName(refData.fqName)
if (refData.isQualifiable && reference is KtSimpleNameReference) {
val pointer =
smartPointerManager.createSmartPsiElementPointer(reference.element, file)
bindingRequests.add(BindingRequest(pointer, fqName))
}
}
for (descriptor in descriptorsToImport) {
importHelper.importDescriptor(file, descriptor)
descriptor.getImportableDescriptor().importableFqName?.let { imported.add(it.asString()) }
}
for ((pointer, fqName) in bindingRequests) {
pointer.element?.mainReference?.let {
it.bindToFqName(fqName, KtSimpleNameReference.ShorteningMode.DELAYED_SHORTENING)
imported.add(fqName.asString())
}
}
performDelayedRefactoringRequests(file.project)
}
private fun findImportableDescriptors(fqName: FqName, file: KtFile): Collection<DeclarationDescriptor> {
return runReadAction {
file.resolveImportReference(fqName).filterNot {
/*TODO: temporary hack until we don't have ability to insert qualified reference into root package*/
DescriptorUtils.getParentOfType(it, PackageFragmentDescriptor::class.java)?.fqName?.isRoot ?: false
}
}
}
private fun findCallableToImport(fqName: FqName, file: KtFile): CallableDescriptor? =
findImportableDescriptors(fqName, file).firstIsInstanceOrNull()
private tailrec fun DeclarationDescriptor.findPackageFqNameSafe(): FqName? {
return when {
this is PackageFragmentDescriptor -> this.fqNameOrNull()
containingDeclaration == null -> this.fqNameOrNull()
else -> this.containingDeclaration!!.findPackageFqNameSafe()
}
}
private fun showRestoreReferencesDialog(
project: Project,
referencesToRestore: List<ReferenceToRestoreData>
): Collection<ReferenceToRestoreData> {
val fqNames = referencesToRestore.map { it.refData.fqName }.toSortedSet()
if (isUnitTestMode()) {
declarationsToImportSuggested = fqNames
}
val shouldShowDialog = CodeInsightSettings.getInstance().ADD_IMPORTS_ON_PASTE == CodeInsightSettings.ASK
if (!shouldShowDialog || referencesToRestore.isEmpty()) {
return referencesToRestore
}
val dialog = RestoreReferencesDialog(project, fqNames.toTypedArray())
dialog.show()
val selectedFqNames = dialog.selectedElements!!.toSet()
return referencesToRestore.filter { selectedFqNames.contains(it.refData.fqName) }
}
private fun toTextRanges(startOffsets: IntArray, endOffsets: IntArray): List<TextRange> {
assert(startOffsets.size == endOffsets.size)
return startOffsets.indices.map { TextRange(startOffsets[it], endOffsets[it]) }
}
private fun PsiElement.isInCopiedArea(fileCopiedFrom: KtFile, textRanges: List<TextRange>): Boolean =
runReadAction {
if (containingFile != fileCopiedFrom) false else textRanges.any { this.textRange in it }
}
companion object {
@get:TestOnly
var declarationsToImportSuggested: Collection<String> = emptyList()
private val LOG = Logger.getInstance(KotlinCopyPasteReferenceProcessor::class.java)
private val IGNORE_REFERENCES_INSIDE: Array<Class<out KtElement>> = arrayOf(
KtImportList::class.java,
KtPackageDirective::class.java
)
}
}
| apache-2.0 | e32fb40cd877d398514b690a67a22934 | 43.872619 | 158 | 0.660441 | 5.583321 | false | false | false | false |
siosio/intellij-community | java/idea-ui/src/com/intellij/ide/starters/remote/wizard/WebStarterLibrariesStep.kt | 1 | 21141 | // 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.ide.starters.remote.wizard
import com.intellij.ide.starters.JavaStartersBundle
import com.intellij.ide.starters.remote.*
import com.intellij.ide.starters.shared.*
import com.intellij.ide.starters.shared.ui.LibrariesSearchTextField
import com.intellij.ide.starters.shared.ui.LibraryDescriptionPanel
import com.intellij.ide.starters.shared.ui.SelectedLibrariesPanel
import com.intellij.ide.IdeBundle
import com.intellij.ide.util.projectWizard.ModuleWizardStep
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.*
import com.intellij.ui.components.JBLabel
import com.intellij.ui.layout.*
import com.intellij.util.ModalityUiUtil
import com.intellij.util.concurrency.EdtExecutorService
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.HttpRequests.RequestProcessor
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil.DEFAULT_HGAP
import com.intellij.util.ui.UIUtil.DEFAULT_VGAP
import com.intellij.util.ui.components.BorderLayoutPanel
import com.intellij.util.ui.tree.TreeUtil
import com.intellij.util.ui.update.MergingUpdateQueue
import com.intellij.util.ui.update.Update
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.GridBagLayout
import java.io.IOException
import java.net.URLConnection
import java.net.UnknownHostException
import java.util.concurrent.TimeUnit
import javax.swing.DefaultComboBoxModel
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.JTree
import javax.swing.event.DocumentEvent
import javax.swing.event.ListDataEvent
import javax.swing.event.ListDataListener
import javax.swing.event.TreeSelectionListener
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.DefaultTreeModel
import javax.swing.tree.TreeSelectionModel
open class WebStarterLibrariesStep(contextProvider: WebStarterContextProvider) : ModuleWizardStep() {
protected val moduleBuilder: WebStarterModuleBuilder = contextProvider.moduleBuilder
protected val wizardContext: WizardContext = contextProvider.wizardContext
protected val starterContext: WebStarterContext = contextProvider.starterContext
protected val starterSettings: StarterWizardSettings = contextProvider.settings
protected val parentDisposable: Disposable = contextProvider.parentDisposable
private val topLevelPanel: JPanel = BorderLayoutPanel()
private val contentPanel: DialogPanel by lazy { createComponent() }
private val librariesList: CheckboxTreeBase by lazy { createLibrariesList() }
private val librariesSearchField: LibrariesSearchTextField by lazy { createLibrariesFilter() }
private val libraryDescriptionPanel: LibraryDescriptionPanel by lazy { LibraryDescriptionPanel() }
private val selectedLibrariesPanel: SelectedLibrariesPanel by lazy { createSelectedLibrariesPanel() }
private val frameworkVersionsModel: DefaultComboBoxModel<WebStarterFrameworkVersion> = DefaultComboBoxModel()
protected val propertyGraph: PropertyGraph = PropertyGraph()
private val frameworkVersionProperty: GraphProperty<WebStarterFrameworkVersion?> = propertyGraph.graphProperty { null }
private val selectedDependencies: MutableSet<WebStarterDependency> = mutableSetOf()
private var currentSearchString: String = ""
private val searchMergingUpdateQueue: MergingUpdateQueue by lazy {
MergingUpdateQueue("SearchLibs_" + moduleBuilder.builderId, 250, true, topLevelPanel, parentDisposable)
}
override fun getComponent(): JComponent = topLevelPanel
override fun getHelpId(): String? = moduleBuilder.getHelpId()
override fun getPreferredFocusedComponent(): JComponent? = librariesSearchField
override fun updateDataModel() {
starterContext.frameworkVersion = frameworkVersionProperty.get()
starterContext.dependencies.clear()
starterContext.dependencies.addAll(selectedDependencies)
}
override fun onStepLeaving() {
super.onStepLeaving()
updateDataModel()
}
override fun _init() {
super._init()
if (topLevelPanel.componentCount == 0) {
topLevelPanel.add(contentPanel, BorderLayout.CENTER)
}
if (topLevelPanel.isDisplayable && topLevelPanel.isShowing) {
// called after unsuccessful validation of step
return
}
// libraries list may depend on options specified on the first step
loadLibrariesList()
loadFrameworkVersions()
updateAvailableDependencies()
getLibrariesRoot()?.let {
selectFirstDependency(it)
}
}
final override fun validate(): Boolean {
val unavailable = selectedDependencies.filter { getDependencyState(it) is DependencyUnavailable }
if (unavailable.isNotEmpty()) {
val dependencyInfo = unavailable.joinToString { it.title }
val version = frameworkVersionProperty.get()?.title ?: ""
Messages.showErrorDialog(
JavaStartersBundle.message("message.unavailable.dependencies", dependencyInfo, version),
JavaStartersBundle.message("message.title.error"))
return false
}
if (!validateFields()) {
return false
}
if (starterContext.result == null) {
// commit selected dependencies to starterContext
updateDataModel()
// try to validate and download result
requestWebService()
if (starterContext.result == null) {
return false
}
}
return true
}
protected open fun validateFields(): Boolean {
return true
}
@RequiresBackgroundThread
protected open fun validateWithServer(progressIndicator: ProgressIndicator): Boolean {
return true
}
private fun requestWebService() {
ProgressManager.getInstance().runProcessWithProgressSynchronously(
{
val progressIndicator = ProgressManager.getInstance().progressIndicator
if (!validateWithServer(progressIndicator)) {
return@runProcessWithProgressSynchronously
}
progressIndicator.checkCanceled()
progressIndicator.text = JavaStartersBundle.message("message.state.downloading.template", moduleBuilder.presentableName)
val downloadResult: DownloadResult? = try {
downloadResult(progressIndicator)
}
catch (e: Exception) {
logger<WebStarterLibrariesStep>().info(e)
EdtExecutorService.getScheduledExecutorInstance().schedule(
{
var message = JavaStartersBundle.message("error.text.with.error.content", e.message)
message = StringUtil.shortenTextWithEllipsis(message, 1024, 0) // exactly 1024 because why not
Messages.showErrorDialog(message, moduleBuilder.presentableName)
},
3, TimeUnit.SECONDS)
null
}
starterContext.result = downloadResult
}, JavaStartersBundle.message("message.state.preparing.template"), true, wizardContext.project)
}
@RequiresBackgroundThread
private fun downloadResult(progressIndicator: ProgressIndicator): DownloadResult {
val tempFile = FileUtil.createTempFile(moduleBuilder.builderId, ".tmp", true)
val log = logger<WebStarterLibrariesStep>()
val url = moduleBuilder.getGeneratorUrlInternal(starterContext.serverUrl, starterContext).toExternalForm()
log.info("Loading project from ${url}")
return HttpRequests
.request(url)
.userAgent(moduleBuilder.getUserAgentInternal())
.connectTimeout(10000)
.isReadResponseOnError(true)
.connect(RequestProcessor { request ->
val connection: URLConnection = try {
request.connection
}
catch (e: IOException) {
log.warn("Can't download project. Message (with headers info): " + HttpRequests.createErrorMessage(e, request, true))
throw IOException(HttpRequests.createErrorMessage(e, request, false), e)
}
catch (he: UnknownHostException) {
log.warn("Can't download project: " + he.message)
throw IOException(HttpRequests.createErrorMessage(he, request, false), he)
}
val contentType = connection.contentType
val contentDisposition = connection.getHeaderField("Content-Disposition")
val filename = getFilename(contentDisposition)
val isZip = StringUtil.isNotEmpty(contentType) && contentType.startsWith("application/zip")
|| filename.endsWith(".zip")
// Micronaut has broken content-type (it's "text") but zip-file as attachment
// (https://github.com/micronaut-projects/micronaut-starter/issues/268)
request.saveToFile(tempFile, progressIndicator)
DownloadResult(isZip, tempFile, filename)
})
}
@NlsSafe
private fun getFilename(contentDisposition: String?): String {
val filenameField = "filename="
if (StringUtil.isEmpty(contentDisposition)) return "unknown"
val startIdx = contentDisposition!!.indexOf(filenameField)
val endIdx = contentDisposition.indexOf(';', startIdx)
var fileName = contentDisposition.substring(startIdx + filenameField.length, if (endIdx > 0) endIdx else contentDisposition.length)
if (StringUtil.startsWithChar(fileName, '\"') && StringUtil.endsWithChar(fileName, '\"')) {
fileName = fileName.substring(1, fileName.length - 1)
}
return fileName
}
private fun loadFrameworkVersions() {
val availableFrameworkVersions = getAvailableFrameworkVersions()
frameworkVersionsModel.removeAllElements()
frameworkVersionsModel.addAll(availableFrameworkVersions)
val defaultVersion = starterContext.frameworkVersion ?: availableFrameworkVersions.firstOrNull()
if (availableFrameworkVersions.contains(defaultVersion)) {
frameworkVersionProperty.set(defaultVersion)
}
else {
frameworkVersionProperty.set(availableFrameworkVersions.firstOrNull())
}
}
protected open fun addFieldsAfter(layout: LayoutBuilder) {}
private fun createComponent(): DialogPanel {
val messages = starterSettings.customizedMessages
selectedLibrariesPanel.emptyText.text = messages?.noDependenciesSelectedLabel
?: JavaStartersBundle.message("hint.dependencies.not.selected")
return panel(LCFlags.fillX, LCFlags.fillY) {
val frameworkVersions = getAvailableFrameworkVersions()
if (frameworkVersions.isNotEmpty()) {
row {
cell(isFullWidth = true) {
label(messages?.frameworkVersionLabel ?: JavaStartersBundle.message("title.project.version.label"))
if (frameworkVersions.size == 1) {
label(frameworkVersions[0].title)
}
else {
frameworkVersionsModel.addListDataListener(object : ListDataListener {
override fun intervalAdded(e: ListDataEvent?) = updateAvailableDependencies()
override fun intervalRemoved(e: ListDataEvent?) = updateAvailableDependencies()
override fun contentsChanged(e: ListDataEvent?) = updateAvailableDependencies()
})
comboBox(frameworkVersionsModel, frameworkVersionProperty, SimpleListCellRenderer.create("") { it?.title ?: "" })
}
}
}.largeGapAfter()
}
addFieldsAfter(this)
row {
label(messages?.dependenciesLabel ?: JavaStartersBundle.message("title.project.dependencies.label"))
}
row {
component(JPanel(GridBagLayout()).apply {
add(BorderLayoutPanel().apply {
preferredSize = Dimension(0, 0)
addToTop(librariesSearchField)
addToCenter(ScrollPaneFactory.createScrollPane(librariesList))
}, gridConstraint(0, 0))
add(JPanel(GridBagLayout()).apply {
border = JBUI.Borders.emptyLeft(DEFAULT_HGAP * 2)
preferredSize = Dimension(0, 0)
add(libraryDescriptionPanel.apply {
preferredSize = Dimension(0, 0)
}, gridConstraint(0, 0))
add(BorderLayoutPanel().apply {
preferredSize = Dimension(0, 0)
addToTop(JBLabel(messages?.selectedDependenciesLabel
?: JavaStartersBundle.message("title.project.dependencies.selected.label")).apply {
border = JBUI.Borders.empty(0, 0, DEFAULT_VGAP * 2, 0)
})
addToCenter(selectedLibrariesPanel)
}, gridConstraint(0, 1))
}, gridConstraint(1, 0))
}).constraints(push, grow)
}
}.withVisualPadding()
}
private fun getAvailableFrameworkVersions(): List<WebStarterFrameworkVersion> {
return starterContext.serverOptions.frameworkVersions.filter {
moduleBuilder.isVersionAvailableInternal(it)
}
}
private fun createLibrariesList(): CheckboxTreeBase {
val list = CheckboxTreeBase(object : CheckboxTree.CheckboxTreeCellRenderer() {
override fun customizeRenderer(
tree: JTree?,
value: Any?,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean
) {
if (value !is DefaultMutableTreeNode) return
this.border = JBUI.Borders.empty(2, 0)
when (val item = value.userObject) {
is WebStarterDependencyCategory -> textRenderer.append(item.title)
is WebStarterDependency -> {
val enabled = (value as CheckedTreeNode).isEnabled
val attributes = if (enabled) SimpleTextAttributes.REGULAR_ATTRIBUTES else SimpleTextAttributes.GRAYED_ATTRIBUTES
textRenderer.append(item.title, attributes)
}
}
}
}, null)
list.emptyText.text = IdeBundle.message("empty.text.nothing.found")
enableEnterKeyHandling(list)
list.rowHeight = 0
list.isRootVisible = false
list.selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION
list.addCheckboxTreeListener(object : CheckboxTreeListener {
override fun nodeStateChanged(node: CheckedTreeNode) {
val dependency = node.userObject as? WebStarterDependency ?: return
if (node.isChecked) {
selectedDependencies.add(dependency)
}
else {
selectedDependencies.remove(dependency)
}
librariesList.repaint()
selectedLibrariesPanel.update(selectedDependencies)
}
})
list.selectionModel.addTreeSelectionListener(TreeSelectionListener { e ->
val path = e.path
if (path != null && e.isAddedPath) {
when (val item = (path.lastPathComponent as? DefaultMutableTreeNode)?.userObject) {
is WebStarterDependency -> {
updateSelectedLibraryInfo(item)
}
is WebStarterDependencyCategory -> libraryDescriptionPanel.update(item.title, null)
}
}
else {
libraryDescriptionPanel.reset()
}
})
librariesSearchField.list = list
return list
}
private fun isDependencyMatched(item: WebStarterDependency, search: String): Boolean {
return item.title.contains(search, true)
|| (item.description ?: "").contains(search, true)
|| item.id.contains(search, true)
}
private fun createLibrariesFilter(): LibrariesSearchTextField {
val textField = LibrariesSearchTextField()
textField.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
searchMergingUpdateQueue.queue(Update.create("", Runnable {
ModalityUiUtil.invokeLaterIfNeeded(Runnable {
currentSearchString = textField.text
loadLibrariesList()
librariesList.repaint()
}, getModalityState())
}))
}
})
return textField
}
protected fun getModalityState(): ModalityState {
return ModalityState.stateForComponent(wizardContext.wizard.contentComponent)
}
protected fun getDisposed(): Condition<Any> = Condition<Any> { Disposer.isDisposed(parentDisposable) }
private fun createSelectedLibrariesPanel(): SelectedLibrariesPanel {
val panel = SelectedLibrariesPanel()
val messages = starterSettings.customizedMessages
panel.emptyText.text = messages?.noDependenciesSelectedLabel ?: JavaStartersBundle.message("hint.dependencies.not.selected")
panel.libraryRemoveListener = { libraryInfo ->
selectedDependencies.remove(libraryInfo)
walkCheckedTree(getLibrariesRoot()) {
if (it.userObject == libraryInfo) {
librariesList.setNodeState(it, false)
}
}
selectedLibrariesPanel.update(selectedDependencies)
}
if (starterContext.frameworkVersion != null) {
panel.dependencyStateFunction = { libraryInfo ->
getDependencyState(libraryInfo)
}
}
return panel
}
private fun getLibrariesRoot(): CheckedTreeNode? {
return librariesList.model.root as? CheckedTreeNode
}
private fun getDependencyState(libraryInfo: LibraryInfo): DependencyState {
val frameworkVersion = frameworkVersionProperty.get() ?: return DependencyAvailable
return moduleBuilder.getDependencyStateInternal(frameworkVersion, libraryInfo as WebStarterDependency)
}
private fun loadLibrariesList() {
val librariesRoot = CheckedTreeNode()
val search = currentSearchString.trim()
val dependencyCategories = starterContext.serverOptions.dependencyCategories
for (category in dependencyCategories) {
if (!category.isAvailable(starterContext)) continue
val categoryNode = DefaultMutableTreeNode(category, true)
for (dependency in category.dependencies) {
if (search.isBlank() || isDependencyMatched(dependency, search)) {
val libraryNode = CheckedTreeNode(dependency)
if (dependency.isDefault) {
selectedDependencies.add(dependency)
}
libraryNode.isChecked = selectedDependencies.contains(dependency)
if (dependency.isDefault) {
libraryNode.isEnabled = false
}
else {
val state = getDependencyState(dependency)
libraryNode.isEnabled = state is DependencyAvailable
}
if (dependencyCategories.size > 1) {
categoryNode.add(libraryNode)
}
else {
librariesRoot.add(libraryNode)
}
}
}
if (dependencyCategories.size > 1) {
if (categoryNode.childCount > 0) {
librariesRoot.add(categoryNode)
}
}
}
librariesList.model = DefaultTreeModel(librariesRoot)
if (search.isNotBlank()) {
for (category in librariesRoot.children()) {
librariesList.expandPath(TreeUtil.getPath(librariesRoot, category))
}
selectFirstDependency(librariesRoot)
}
}
private fun selectFirstDependency(librariesRoot: CheckedTreeNode) {
if (librariesRoot.childCount > 0) {
val firstNode = librariesRoot.getChildAt(0)
if (firstNode is CheckedTreeNode) {
librariesList.selectionModel.addSelectionPath(TreeUtil.getPath(librariesRoot, firstNode))
}
else {
librariesList.expandPath(TreeUtil.getPath(librariesRoot, firstNode))
if (firstNode.childCount > 0) {
librariesList.selectionModel.addSelectionPath(TreeUtil.getPath(librariesRoot, firstNode.getChildAt(0)))
}
}
}
}
private fun updateSelectedLibraryInfo(item: WebStarterDependency) {
val dependencyState = getDependencyState(item)
val versionInfo = if (dependencyState is DependencyUnavailable) dependencyState.hint else null
libraryDescriptionPanel.update(item, versionInfo)
}
private fun updateAvailableDependencies() {
selectedLibrariesPanel.update(selectedDependencies)
val root = getLibrariesRoot() ?: return
walkCheckedTree(root) {
val dependency = it.userObject as? WebStarterDependency
if (dependency != null) {
val state = getDependencyState(dependency)
it.isEnabled = state is DependencyAvailable
}
}
librariesList.repaint()
val selectedDependency = (librariesList.selectionPath?.lastPathComponent as? CheckedTreeNode)?.userObject
if (selectedDependency is WebStarterDependency) {
updateSelectedLibraryInfo(selectedDependency)
}
}
}
| apache-2.0 | 30076e21a7074f74e370c9add7956412 | 37.16065 | 140 | 0.715482 | 5.365736 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/compiler-plugins/sam-with-receiver/maven/src/org/jetbrains/kotlin/idea/maven/compilerPlugin/samWithReceiver/SamWithReceiverMavenProjectImportHandler.kt | 1 | 2131 | // 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.
// 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.maven.compilerPlugin.samWithReceiver
import org.jetbrains.kotlin.idea.maven.compilerPlugin.AbstractMavenImportHandler
import org.jetbrains.kotlin.idea.compilerPlugin.AnnotationBasedCompilerPluginSetup.PluginOption
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverCommandLineProcessor
class SamWithReceiverMavenProjectImportHandler : AbstractMavenImportHandler() {
private companion object {
val ANNOTATION_PARAMETER_PREFIX = "sam-with-receiver:${SamWithReceiverCommandLineProcessor.ANNOTATION_OPTION.optionName}="
}
override val compilerPluginId = SamWithReceiverCommandLineProcessor.PLUGIN_ID
override val pluginName = "samWithReceiver"
override val mavenPluginArtifactName = "kotlin-maven-sam-with-receiver"
override val pluginJarFileFromIdea = KotlinArtifacts.instance.samWithReceiverCompilerPlugin
override fun getOptions(enabledCompilerPlugins: List<String>, compilerPluginOptions: List<String>): List<PluginOption>? {
if ("sam-with-receiver" !in enabledCompilerPlugins) {
return null
}
val annotations = mutableListOf<String>()
for ((presetName, presetAnnotations) in SamWithReceiverCommandLineProcessor.SUPPORTED_PRESETS) {
if (presetName in enabledCompilerPlugins) {
annotations.addAll(presetAnnotations)
}
}
annotations.addAll(compilerPluginOptions.mapNotNull { text ->
if (!text.startsWith(ANNOTATION_PARAMETER_PREFIX)) return@mapNotNull null
text.substring(ANNOTATION_PARAMETER_PREFIX.length)
})
return annotations.map { PluginOption(SamWithReceiverCommandLineProcessor.ANNOTATION_OPTION.optionName, it) }
}
}
| apache-2.0 | e6708644a91c160ed9bf304582a01f12 | 50.97561 | 158 | 0.765838 | 5.210269 | false | false | false | false |
JetBrains/kotlin-native | Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/CodeBuilders.kt | 4 | 3086 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.native.interop.gen
interface NativeScope {
val mappingBridgeGenerator: MappingBridgeGenerator
}
class NativeCodeBuilder(val scope: NativeScope) {
val lines = mutableListOf<String>()
fun out(line: String): Unit {
lines.add(line)
}
}
inline fun buildNativeCodeLines(scope: NativeScope, block: NativeCodeBuilder.() -> Unit): List<String> {
val builder = NativeCodeBuilder(scope)
builder.block()
return builder.lines
}
private class Block(val nesting: Int, val start: String, val end: String) {
val prologue = mutableListOf<String>()
val body = mutableListOf<String>()
val epilogue = mutableListOf<String>()
fun indent(line: String) = " ".repeat(nesting) + line
fun indentBraces(line: String) = " ".repeat(nesting - 1) + line
}
class KotlinCodeBuilder(val scope: KotlinScope) {
private val blocks = mutableListOf<Block>()
init {
pushBlock("", "")
}
fun out(line: String) {
currentBlock().body += line
}
private var memScoped = false
fun pushMemScoped() {
if (!memScoped) {
memScoped = true
pushBlock("memScoped {")
}
}
fun getNativePointer(name: String): String {
return "$name?.getPointer(memScope)"
}
fun returnResult(result: String) {
currentBlock().body += "return $result"
}
private fun currentBlock() = blocks.last()
fun pushBlock(start: String, end: String = "}") {
val block = Block(blocks.size, start = start, end = end)
blocks += block
}
private fun emitBlockAndNested(position: Int, lines: MutableList<String>) {
if (position >= blocks.size) return
val block = blocks[position]
if (block.start.isNotEmpty()) lines += block.indentBraces(block.start)
lines += block.prologue.map { block.indent(it) }
lines += block.body.map { block.indent(it) }
emitBlockAndNested(position + 1, lines)
lines += block.epilogue.map { block.indent(it) }
if (block.end.isNotEmpty()) lines += block.indentBraces(block.end)
}
fun build(): List<String> {
val lines = mutableListOf<String>()
emitBlockAndNested(0, lines)
return lines.toList()
}
}
inline fun buildKotlinCodeLines(scope: KotlinScope, block: KotlinCodeBuilder.() -> Unit): List<String> {
val builder = KotlinCodeBuilder(scope)
builder.block()
return builder.build()
} | apache-2.0 | 4ffcaa5f071ef993f9695e5db70db345 | 28.970874 | 104 | 0.656837 | 4.087417 | false | false | false | false |
JetBrains/intellij-community | python/src/com/jetbrains/python/packaging/conda/CondaRepositoryManger.kt | 1 | 2391 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.packaging.conda
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.jetbrains.python.PyBundle
import com.jetbrains.python.packaging.common.PythonPackageDetails
import com.jetbrains.python.packaging.common.PythonPackageSpecification
import com.jetbrains.python.packaging.pip.PipBasedRepositoryManager
import com.jetbrains.python.packaging.repository.PyPackageRepository
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Experimental
class CondaRepositoryManger(project: Project, sdk: Sdk) : PipBasedRepositoryManager(project, sdk) {
override val repositories: List<PyPackageRepository>
get() = listOf(CondaPackageRepository) + super.repositories
override fun allPackages(): List<String> = service<CondaPackageCache>().packages
override fun packagesFromRepository(repository: PyPackageRepository): List<String> {
return if (repository is CondaPackageRepository) service<CondaPackageCache>().packages else super.packagesFromRepository(repository)
}
override fun buildPackageDetails(rawInfo: String?, spec: PythonPackageSpecification): PythonPackageDetails {
if (spec is CondaPackageSpecification) {
val versions = service<CondaPackageCache>()[spec.name] ?: error("No conda package versions in cache")
if (rawInfo == null) return CondaPackageDetails(spec.name, versions, PyBundle.message("conda.packaging.empty.pypi.info"))
val detailsFromPyPI = super.buildPackageDetails(rawInfo, spec)
return CondaPackageDetails(detailsFromPyPI.name,
versions,
detailsFromPyPI.summary,
detailsFromPyPI.description,
detailsFromPyPI.descriptionContentType,
detailsFromPyPI.documentationUrl)
}
return super.buildPackageDetails(rawInfo, spec)
}
override suspend fun initCaches() {
super.initCaches()
service<CondaPackageCache>().apply {
if (isEmpty()) refreshAll(sdk, project)
}
}
override suspend fun refreshCashes() {
super.refreshCashes()
service<CondaPackageCache>().refreshAll(sdk, project)
}
} | apache-2.0 | f0ea19c4b93914694cbffdf84bf92959 | 42.490909 | 136 | 0.739858 | 4.715976 | false | false | false | false |
nrizzio/Signal-Android | app/src/androidTest/java/org/thoughtcrime/securesms/database/MmsDatabaseTest_stories.kt | 1 | 10995 | package org.thoughtcrime.securesms.database
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import org.thoughtcrime.securesms.database.model.DistributionListId
import org.thoughtcrime.securesms.database.model.ParentStoryId
import org.thoughtcrime.securesms.database.model.StoryType
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.mms.IncomingMediaMessage
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.whispersystems.signalservice.api.push.ACI
import org.whispersystems.signalservice.api.push.PNI
import org.whispersystems.signalservice.api.push.ServiceId
import java.util.UUID
import java.util.concurrent.TimeUnit
@Suppress("ClassName")
@RunWith(AndroidJUnit4::class)
class MmsDatabaseTest_stories {
private lateinit var mms: MmsDatabase
private val localAci = ACI.from(UUID.randomUUID())
private val localPni = PNI.from(UUID.randomUUID())
private lateinit var myStory: Recipient
private lateinit var recipients: List<RecipientId>
private lateinit var releaseChannelRecipient: Recipient
@Before
fun setUp() {
mms = SignalDatabase.mms
mms.deleteAllThreads()
SignalStore.account().setAci(localAci)
SignalStore.account().setPni(localPni)
myStory = Recipient.resolved(SignalDatabase.recipients.getOrInsertFromDistributionListId(DistributionListId.MY_STORY))
recipients = (0 until 5).map { SignalDatabase.recipients.getOrInsertFromServiceId(ServiceId.from(UUID.randomUUID())) }
releaseChannelRecipient = Recipient.resolved(SignalDatabase.recipients.insertReleaseChannelRecipient())
SignalStore.releaseChannelValues().setReleaseChannelRecipientId(releaseChannelRecipient.id)
}
@Test
fun givenNoStories_whenIGetOrderedStoryRecipientsAndIds_thenIExpectAnEmptyList() {
// WHEN
val result = mms.getOrderedStoryRecipientsAndIds(false)
// THEN
assertEquals(0, result.size)
}
@Test
fun givenOneOutgoingAndOneIncomingStory_whenIGetOrderedStoryRecipientsAndIds_thenIExpectIncomingThenOutgoing() {
// GIVEN
val threadId = SignalDatabase.threads.getOrCreateThreadIdFor(myStory)
val sender = recipients[0]
MmsHelper.insert(
recipient = myStory,
sentTimeMillis = 1,
storyType = StoryType.STORY_WITH_REPLIES,
threadId = threadId
)
MmsHelper.insert(
IncomingMediaMessage(
from = sender,
sentTimeMillis = 2,
serverTimeMillis = 2,
receivedTimeMillis = 2,
storyType = StoryType.STORY_WITH_REPLIES
),
-1L
)
// WHEN
val result = mms.getOrderedStoryRecipientsAndIds(false)
// THEN
assertEquals(listOf(sender.toLong(), myStory.id.toLong()), result.map { it.recipientId.toLong() })
}
@Test
fun givenAStory_whenISetIncomingStoryMessageViewed_thenIExpectASetReceiptTimestamp() {
// GIVEN
val sender = recipients[0]
val messageId = MmsHelper.insert(
IncomingMediaMessage(
from = sender,
sentTimeMillis = 2,
serverTimeMillis = 2,
receivedTimeMillis = 2,
storyType = StoryType.STORY_WITH_REPLIES
),
-1L
).get().messageId
val messageBeforeMark = SignalDatabase.mms.getMessageRecord(messageId)
assertFalse(messageBeforeMark.incomingStoryViewedAtTimestamp > 0)
// WHEN
SignalDatabase.mms.setIncomingMessageViewed(messageId)
// THEN
val messageAfterMark = SignalDatabase.mms.getMessageRecord(messageId)
assertTrue(messageAfterMark.incomingStoryViewedAtTimestamp > 0)
}
@Ignore
@Test
fun given5ViewedStories_whenIGetOrderedStoryRecipientsAndIds_thenIExpectLatestViewedFirst() {
// GIVEN
val messageIds = recipients.take(5).map {
MmsHelper.insert(
IncomingMediaMessage(
from = it,
sentTimeMillis = 2,
serverTimeMillis = 2,
receivedTimeMillis = 2,
storyType = StoryType.STORY_WITH_REPLIES,
),
-1L
).get().messageId
}
val randomizedOrderedIds = messageIds.shuffled()
randomizedOrderedIds.forEach {
SignalDatabase.mms.setIncomingMessageViewed(it)
Thread.sleep(5)
}
// WHEN
val result = SignalDatabase.mms.getOrderedStoryRecipientsAndIds(false)
val resultOrderedIds = result.map { it.messageId }
// THEN
assertEquals(randomizedOrderedIds.reversed(), resultOrderedIds)
}
@Test
fun given15Stories_whenIGetOrderedStoryRecipientsAndIds_thenIExpectUnviewedThenInterspersedViewedAndSelfSendsAllDescending() {
val myStoryThread = SignalDatabase.threads.getOrCreateThreadIdFor(myStory)
val unviewedIds: List<Long> = (0 until 5).map {
Thread.sleep(5)
MmsHelper.insert(
IncomingMediaMessage(
from = recipients[it],
sentTimeMillis = System.currentTimeMillis(),
serverTimeMillis = 2,
receivedTimeMillis = 2,
storyType = StoryType.STORY_WITH_REPLIES,
),
-1L
).get().messageId
}
val viewedIds: List<Long> = (0 until 5).map {
Thread.sleep(5)
MmsHelper.insert(
IncomingMediaMessage(
from = recipients[it],
sentTimeMillis = System.currentTimeMillis(),
serverTimeMillis = 2,
receivedTimeMillis = 2,
storyType = StoryType.STORY_WITH_REPLIES,
),
-1L
).get().messageId
}
val interspersedIds: List<Long> = (0 until 10).map {
Thread.sleep(5)
if (it % 2 == 0) {
SignalDatabase.mms.setIncomingMessageViewed(viewedIds[it / 2])
viewedIds[it / 2]
} else {
MmsHelper.insert(
recipient = myStory,
sentTimeMillis = System.currentTimeMillis(),
storyType = StoryType.STORY_WITH_REPLIES,
threadId = myStoryThread
)
}
}
val result = SignalDatabase.mms.getOrderedStoryRecipientsAndIds(false)
val resultOrderedIds = result.map { it.messageId }
assertEquals(unviewedIds.reversed() + interspersedIds.reversed(), resultOrderedIds)
}
@Test
fun givenNoStories_whenICheckIsOutgoingStoryAlreadyInDatabase_thenIExpectFalse() {
// WHEN
val result = mms.isOutgoingStoryAlreadyInDatabase(recipients[0], 200)
// THEN
assertFalse(result)
}
@Test
fun givenNoOutgoingStories_whenICheckIsOutgoingStoryAlreadyInDatabase_thenIExpectFalse() {
// GIVEN
MmsHelper.insert(
IncomingMediaMessage(
from = recipients[0],
sentTimeMillis = 200,
serverTimeMillis = 2,
receivedTimeMillis = 2,
storyType = StoryType.STORY_WITH_REPLIES,
),
-1L
)
// WHEN
val result = mms.isOutgoingStoryAlreadyInDatabase(recipients[0], 200)
// THEN
assertFalse(result)
}
@Test
fun givenOutgoingStoryExistsForRecipientAndTime_whenICheckIsOutgoingStoryAlreadyInDatabase_thenIExpectTrue() {
// GIVEN
MmsHelper.insert(
recipient = myStory,
sentTimeMillis = 200,
storyType = StoryType.STORY_WITH_REPLIES,
threadId = -1L
)
// WHEN
val result = mms.isOutgoingStoryAlreadyInDatabase(myStory.id, 200)
// THEN
assertTrue(result)
}
@Test
fun givenAGroupStoryWithNoReplies_whenICheckHasSelfReplyInGroupStory_thenIExpectFalse() {
// GIVEN
val groupStoryId = MmsHelper.insert(
recipient = myStory,
sentTimeMillis = 200,
storyType = StoryType.STORY_WITH_REPLIES,
threadId = -1L
)
// WHEN
val result = mms.hasGroupReplyOrReactionInStory(groupStoryId)
// THEN
assertFalse(result)
}
@Ignore
@Test
fun givenAGroupStoryWithAReplyFromSelf_whenICheckHasSelfReplyInGroupStory_thenIExpectTrue() {
// GIVEN
val groupStoryId = MmsHelper.insert(
recipient = myStory,
sentTimeMillis = 200,
storyType = StoryType.STORY_WITH_REPLIES,
threadId = -1L
)
MmsHelper.insert(
recipient = myStory,
sentTimeMillis = 201,
storyType = StoryType.NONE,
parentStoryId = ParentStoryId.GroupReply(groupStoryId)
)
// WHEN
val result = mms.hasGroupReplyOrReactionInStory(groupStoryId)
// THEN
assertTrue(result)
}
@Test
fun givenAGroupStoryWithAReactionFromSelf_whenICheckHasSelfReplyInGroupStory_thenIExpectTrue() {
// GIVEN
val groupStoryId = MmsHelper.insert(
recipient = myStory,
sentTimeMillis = 200,
storyType = StoryType.STORY_WITH_REPLIES,
threadId = -1L
)
MmsHelper.insert(
recipient = myStory,
sentTimeMillis = 201,
storyType = StoryType.NONE,
parentStoryId = ParentStoryId.GroupReply(groupStoryId),
isStoryReaction = true
)
// WHEN
val result = mms.hasGroupReplyOrReactionInStory(groupStoryId)
// THEN
assertTrue(result)
}
@Test
fun givenAGroupStoryWithAReplyFromSomeoneElse_whenICheckHasSelfReplyInGroupStory_thenIExpectFalse() {
// GIVEN
val groupStoryId = MmsHelper.insert(
recipient = myStory,
sentTimeMillis = 200,
storyType = StoryType.STORY_WITH_REPLIES,
threadId = -1L
)
MmsHelper.insert(
IncomingMediaMessage(
from = myStory.id,
sentTimeMillis = 201,
serverTimeMillis = 201,
receivedTimeMillis = 202,
parentStoryId = ParentStoryId.GroupReply(groupStoryId)
),
-1
)
// WHEN
val result = mms.hasGroupReplyOrReactionInStory(groupStoryId)
// THEN
assertFalse(result)
}
@Test
fun givenNotViewedOnboardingAndOnlyStoryIsOnboardingAndAdded2DaysAgo_whenIGetOldestStoryTimestamp_thenIExpectNull() {
// GIVEN
val threadId = SignalDatabase.threads.getOrCreateThreadIdFor(releaseChannelRecipient)
MmsHelper.insert(
recipient = releaseChannelRecipient,
sentTimeMillis = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(2),
storyType = StoryType.STORY_WITH_REPLIES,
threadId = threadId
)
// WHEN
val oldestTimestamp = SignalDatabase.mms.getOldestStorySendTimestamp(false)
// THEN
assertNull(oldestTimestamp)
}
@Test
fun givenViewedOnboardingAndOnlyStoryIsOnboardingAndAdded2DaysAgo_whenIGetOldestStoryTimestamp_thenIExpectNotNull() {
// GIVEN
val expected = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(2)
val threadId = SignalDatabase.threads.getOrCreateThreadIdFor(releaseChannelRecipient)
MmsHelper.insert(
recipient = releaseChannelRecipient,
sentTimeMillis = expected,
storyType = StoryType.STORY_WITH_REPLIES,
threadId = threadId
)
// WHEN
val oldestTimestamp = SignalDatabase.mms.getOldestStorySendTimestamp(true)
// THEN
assertEquals(expected, oldestTimestamp)
}
}
| gpl-3.0 | 6d31bc6ebf5a50e1846cf58dba431718 | 27.782723 | 128 | 0.705866 | 4.215874 | false | false | false | false |
androidx/androidx | credentials/credentials/src/androidTest/java/androidx/credentials/CreatePublicKeyCredentialRequestTest.kt | 3 | 3410 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.credentials
import android.os.Bundle
import androidx.credentials.CreatePublicKeyCredentialRequest.Companion.BUNDLE_KEY_ALLOW_HYBRID
import androidx.credentials.CreatePublicKeyCredentialRequest.Companion.BUNDLE_KEY_REQUEST_JSON
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@SmallTest
class CreatePublicKeyCredentialRequestTest {
@Test
fun constructor_emptyJson_throwsIllegalArgumentException() {
Assert.assertThrows(
"Expected empty Json to throw error",
IllegalArgumentException::class.java
) { CreatePublicKeyCredentialRequest("") }
}
@Test
fun constructor_success() {
CreatePublicKeyCredentialRequest(
"{\"hi\":{\"there\":{\"lol\":\"Value\"}}}"
)
}
@Test
fun constructor_setsAllowHybridToTrueByDefault() {
val createPublicKeyCredentialRequest = CreatePublicKeyCredentialRequest(
"JSON"
)
val allowHybridActual = createPublicKeyCredentialRequest.allowHybrid
assertThat(allowHybridActual).isTrue()
}
@Test
fun constructor_setsAllowHybridToFalse() {
val allowHybridExpected = false
val createPublicKeyCredentialRequest = CreatePublicKeyCredentialRequest(
"testJson",
allowHybridExpected
)
val allowHybridActual = createPublicKeyCredentialRequest.allowHybrid
assertThat(allowHybridActual).isEqualTo(allowHybridExpected)
}
@Test
fun getter_requestJson_success() {
val testJsonExpected = "{\"hi\":{\"there\":{\"lol\":\"Value\"}}}"
val createPublicKeyCredentialReq = CreatePublicKeyCredentialRequest(testJsonExpected)
val testJsonActual = createPublicKeyCredentialReq.requestJson
assertThat(testJsonActual).isEqualTo(testJsonExpected)
}
@Test
fun getter_frameworkProperties_success() {
val requestJsonExpected = "{\"hi\":{\"there\":{\"lol\":\"Value\"}}}"
val allowHybridExpected = false
val expectedData = Bundle()
expectedData.putString(
BUNDLE_KEY_REQUEST_JSON, requestJsonExpected
)
expectedData.putBoolean(
BUNDLE_KEY_ALLOW_HYBRID, allowHybridExpected
)
val request = CreatePublicKeyCredentialRequest(
requestJsonExpected,
allowHybridExpected
)
assertThat(request.type).isEqualTo(PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL)
assertThat(equals(request.data, expectedData)).isTrue()
assertThat(request.requireSystemProvider).isFalse()
}
} | apache-2.0 | 53ccb633a40ae790830b109d25de5023 | 34.164948 | 94 | 0.705865 | 4.864479 | false | true | false | false |
androidx/androidx | compose/ui/ui/src/test/kotlin/androidx/compose/ui/autofill/FakeViewStructure.kt | 3 | 8787 | /*
* 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.autofill
import android.graphics.Matrix
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.os.LocaleList
import android.os.Parcel
import android.view.View
import android.view.ViewStructure
import android.view.autofill.AutofillId
import android.view.autofill.AutofillValue
import androidx.annotation.GuardedBy
import androidx.annotation.RequiresApi
/**
* A fake implementation of [ViewStructure] to use in tests.
*
* @param virtualId An ID that is unique for each viewStructure node in the viewStructure tree.
* @param packageName The package name of the app (Used as an autofill heuristic).
* @param typeName The type name of the view's identifier, or null if there is none.
* @param entryName The entry name of the view's identifier, or null if there is none.
* @param children A list of [ViewStructure]s that are children of the current [ViewStructure].
* @param bounds The bounds (Dimensions) of the component represented by this [ViewStructure].
* @param autofillId The [autofillId] for the parent component. The same autofillId is used for
* other child components.
* @param autofillType The data type. Can be one of the following:
* [View.AUTOFILL_TYPE_DATE],
* [View.AUTOFILL_TYPE_LIST],
* [View.AUTOFILL_TYPE_TEXT],
* [View.AUTOFILL_TYPE_TOGGLE] or
* [View.AUTOFILL_TYPE_NONE].
* @param autofillHints The autofill hint. If this value not specified, we use heuristics to
* determine what data to use while performing autofill.
*
* @suppress
*/
@RequiresApi(Build.VERSION_CODES.O)
internal data class FakeAndroidViewStructure(
var virtualId: Int = 0,
var packageName: String? = null,
var typeName: String? = null,
var entryName: String? = null,
var children: MutableList<FakeAndroidViewStructure> = mutableListOf(),
var bounds: Rect? = null,
private val autofillId: AutofillId? = generateAutofillId(),
private var autofillType: Int = View.AUTOFILL_TYPE_NONE,
private var autofillHints: Array<out String> = arrayOf()
) : ViewStructure() {
internal companion object {
@GuardedBy("this")
private var previousId = 0
private val NO_SESSION = 0
@Synchronized
private fun generateAutofillId(): AutofillId {
var autofillId: AutofillId? = null
useParcel { parcel ->
parcel.writeInt(++previousId) // View Id.
parcel.writeInt(NO_SESSION) // Flag.
parcel.setDataPosition(0)
autofillId = AutofillId.CREATOR.createFromParcel(parcel)
}
return autofillId ?: error("Could not generate autofill id")
}
}
override fun getChildCount() = children.count()
override fun addChildCount(childCount: Int): Int {
repeat(childCount) { children.add(FakeAndroidViewStructure(autofillId = autofillId)) }
return children.count() - childCount
}
override fun newChild(index: Int): FakeAndroidViewStructure {
if (index >= children.count()) error("Call addChildCount() before calling newChild()")
return children[index]
}
override fun getAutofillId() = autofillId
override fun setAutofillId(rootId: AutofillId, virtualId: Int) {
this.virtualId = virtualId
}
override fun setId(
virtualId: Int,
packageName: String?,
typeName: String?,
entryName: String?
) {
this.virtualId = virtualId
this.packageName = packageName
this.typeName = typeName
this.entryName = entryName
}
override fun setAutofillType(autofillType: Int) {
this.autofillType = autofillType
}
override fun setAutofillHints(autofillHints: Array<out String>?) {
autofillHints?.let { this.autofillHints = it }
}
override fun setDimens(left: Int, top: Int, x: Int, y: Int, width: Int, height: Int) {
this.bounds = Rect(left, top, width - left, height - top)
}
override fun equals(other: Any?) = other is FakeAndroidViewStructure &&
other.virtualId == virtualId &&
other.packageName == packageName &&
other.typeName == typeName &&
other.entryName == entryName &&
other.autofillType == autofillType &&
other.autofillHints.contentEquals(autofillHints) &&
other.bounds.contentEquals(bounds) &&
other.children == children
override fun hashCode() = super.hashCode()
// Unimplemented methods.
override fun setOpaque(p0: Boolean) { TODO("not implemented") }
override fun setHint(p0: CharSequence?) { TODO("not implemented") }
override fun setElevation(p0: Float) { TODO("not implemented") }
override fun getText(): CharSequence { TODO("not implemented") }
override fun setText(p0: CharSequence?) { TODO("not implemented") }
override fun setText(p0: CharSequence?, p1: Int, p2: Int) { TODO("not implemented") }
override fun asyncCommit() { TODO("not implemented") }
override fun setEnabled(p0: Boolean) { TODO("not implemented") }
override fun setLocaleList(p0: LocaleList?) { TODO("not implemented") }
override fun setChecked(p0: Boolean) { TODO("not implemented") }
override fun setContextClickable(p0: Boolean) { TODO("not implemented") }
override fun setAccessibilityFocused(p0: Boolean) { TODO("not implemented") }
override fun setAlpha(p0: Float) { TODO("not implemented") }
override fun setTransformation(p0: Matrix?) { TODO("not implemented") }
override fun setClassName(p0: String?) { TODO("not implemented") }
override fun setLongClickable(p0: Boolean) { TODO("not implemented") }
override fun getHint(): CharSequence { TODO("not implemented") }
override fun setInputType(p0: Int) { TODO("not implemented") }
override fun setWebDomain(p0: String?) { TODO("not implemented") }
override fun setAutofillOptions(p0: Array<out CharSequence>?) { TODO("not implemented") }
override fun setTextStyle(p0: Float, p1: Int, p2: Int, p3: Int) { TODO("not implemented") }
override fun setVisibility(p0: Int) { TODO("not implemented") }
override fun setHtmlInfo(p0: HtmlInfo) { TODO("not implemented") }
override fun setTextLines(p0: IntArray?, p1: IntArray?) { TODO("not implemented") }
override fun getExtras(): Bundle { TODO("not implemented") }
override fun setClickable(p0: Boolean) { TODO("not implemented") }
override fun newHtmlInfoBuilder(p0: String): HtmlInfo.Builder { TODO("not implemented") }
override fun getTextSelectionEnd(): Int { TODO("not implemented") }
override fun setAutofillId(p0: AutofillId) { TODO("not implemented") }
override fun hasExtras(): Boolean { TODO("not implemented") }
override fun setActivated(p0: Boolean) { TODO("not implemented") }
override fun setFocused(p0: Boolean) { TODO("not implemented") }
override fun getTextSelectionStart(): Int { TODO("not implemented") }
override fun setChildCount(p0: Int) { TODO("not implemented") }
override fun setAutofillValue(p0: AutofillValue?) { TODO("not implemented") }
override fun setContentDescription(p0: CharSequence?) { TODO("not implemented") }
override fun setFocusable(p0: Boolean) { TODO("not implemented") }
override fun setCheckable(p0: Boolean) { TODO("not implemented") }
override fun asyncNewChild(p0: Int): ViewStructure { TODO("not implemented") }
override fun setSelected(p0: Boolean) { TODO("not implemented") }
override fun setDataIsSensitive(p0: Boolean) { TODO("not implemented") }
}
private fun Rect?.contentEquals(other: Rect?) = when {
(other == null && this == null) -> true
(other == null || this == null) -> false
else ->
other.left == left &&
other.right == right &&
other.bottom == bottom &&
other.top == top
}
/** Obtains a parcel and then recycles it correctly whether an exception is thrown or not. */
private fun useParcel(block: (Parcel) -> Unit) {
var parcel: Parcel? = null
try {
parcel = Parcel.obtain()
block(parcel)
} finally {
parcel?.recycle()
}
}
| apache-2.0 | 4d47b755da4acce79c23ba12e2b714b6 | 35.160494 | 95 | 0.68351 | 4.234699 | false | false | false | false |
scenerygraphics/SciView | src/main/kotlin/sc/iview/commands/view/ResetCameraPosition.kt | 1 | 2343 | /*-
* #%L
* Scenery-backed 3D visualization package for ImageJ.
* %%
* Copyright (C) 2016 - 2021 SciView developers.
* %%
* 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.
*
* 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 HOLDERS 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.
* #L%
*/
package sc.iview.commands.view
import org.joml.Vector3f
import org.scijava.command.Command
import org.scijava.log.LogService
import org.scijava.plugin.Menu
import org.scijava.plugin.Parameter
import org.scijava.plugin.Plugin
import sc.iview.SciView
import sc.iview.commands.MenuWeights.VIEW
import sc.iview.commands.MenuWeights.VIEW_RESET_CAMERA_POSITION
/**
* Command to set the camera position to the default position
*
* @author Kyle Harrington
*/
@Plugin(type = Command::class, menuRoot = "SciView", menu = [Menu(label = "View", weight = VIEW), Menu(label = "Reset Camera Position", weight = VIEW_RESET_CAMERA_POSITION)])
class ResetCameraPosition : Command {
@Parameter
private lateinit var logService: LogService
@Parameter
private lateinit var sciView: SciView
override fun run() {
sciView.camera?.spatialOrNull()?.position = Vector3f(0.0f, 1.65f, 5f)
}
} | bsd-2-clause | 7b8af40a88d236a0d3076aea4e933ffe | 40.122807 | 174 | 0.755442 | 4.214029 | false | false | false | false |
GunoH/intellij-community | plugins/ide-features-trainer/src/training/ui/LearningUiUtil.kt | 8 | 8458 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.ui
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.IdeFrame
import com.intellij.util.ui.EDT
import com.intellij.util.ui.UIUtil
import org.assertj.swing.core.GenericTypeMatcher
import org.assertj.swing.core.Robot
import org.assertj.swing.exception.ComponentLookupException
import org.assertj.swing.exception.WaitTimedOutError
import org.assertj.swing.timing.Condition
import org.assertj.swing.timing.Pause
import org.assertj.swing.timing.Timeout
import java.awt.Component
import java.awt.Container
import java.awt.Rectangle
import java.awt.Window
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
/** It is a copy-paste from testGuiFramework to use minimal necessary subset to discover UI elements */
object LearningUiUtil {
@Volatile
private var myRobot: Robot? = null
val robot: Robot
get() {
if (myRobot == null)
synchronized(this) {
if (myRobot == null) initializeRobot()
}
return myRobot ?: throw IllegalStateException("Cannot initialize the robot")
}
val defaultComponentSearchShortTimeout = Timeout.timeout(500, TimeUnit.MILLISECONDS)
private fun initializeRobot() {
if (myRobot != null) releaseRobot()
myRobot = IftSmartWaitRobot()
}
private fun releaseRobot() {
if (myRobot != null) {
synchronized(this) {
if (myRobot != null) {
myRobot!!.cleanUpWithoutDisposingWindows() // releases ScreenLock
myRobot = null
}
}
}
}
/**
* Waits for a first component which passes the given matcher under the given root to become visible.
*/
private fun <T : Component> waitUntilFoundAll(robot: Robot,
matcher: GenericTypeMatcher<T>,
timeout: Timeout,
getRoots: () -> Collection<Container>): Collection<T> {
checkIsNotEdt()
val reference = AtomicReference<Collection<T>>()
Pause.pause(object : Condition("Find component using $matcher") {
override fun test(): Boolean {
val finder = robot.finder()
val allFound = getRoots().flatMap { finder.findAll(it, matcher) }
if (allFound.isNotEmpty()) {
reference.set(allFound)
return true
}
return false
}
}, timeout)
return reference.get()
}
fun <T : Component> waitUntilFound(robot: Robot,
matcher: GenericTypeMatcher<T>,
timeout: Timeout,
getRoots: () -> Collection<Container>): T {
checkIsNotEdt()
val allFound = waitUntilFoundAll(robot, matcher, timeout, getRoots)
if (allFound.size > 1) {
// Only allow a single component to be found, otherwise you can get some really confusing
// test failures; the matcher should pick a specific enough instance
val exceptionText = "Found more than one ${matcher.supportedType().simpleName} which matches the criteria: $allFound"
thisLogger().warn(exceptionText)
throw ComponentLookupException(exceptionText)
}
return allFound.single()
}
private fun checkIsNotEdt() {
if (EDT.isCurrentThreadEdt()) {
thisLogger().error("UI detection should not be called from the EDT thread. Please, move it to the background thread.")
}
}
fun <ComponentType : Component?> typeMatcher(componentTypeClass: Class<ComponentType>,
matcher: (ComponentType) -> Boolean): GenericTypeMatcher<ComponentType> {
return object : GenericTypeMatcher<ComponentType>(componentTypeClass) {
override fun isMatching(component: ComponentType): Boolean = matcher(component)
}
}
fun getUiRootsForProject(project: Project): List<Container> {
return robot.hierarchy().roots().filter { it is IdeFrame && it.isShowing && it.project == project }
}
private fun isReallyVisible(component: Component): Boolean {
val window = UIUtil.getParentOfType(Window::class.java, component) ?: return true
val locationOnScreen = component.locationOnScreen
val onScreenRect = Rectangle(locationOnScreen.x, locationOnScreen.y, component.width, component.height)
val bounds = window.bounds
return bounds.intersects(onScreenRect) && !component.bounds.isEmpty
}
fun <ComponentType : Component> findShowingComponentWithTimeout(project: Project,
componentClass: Class<ComponentType>,
timeout: Timeout = Timeout.timeout(10, TimeUnit.SECONDS),
selector: ((candidates: Collection<ComponentType>) -> ComponentType?)? = null,
finderFunction: (ComponentType) -> Boolean = { true }): ComponentType {
try {
val matcher = typeMatcher(componentClass) {
it.isShowing && finderFunction(it) && isReallyVisible(it)
}
return if (selector != null) {
val result = waitUntilFoundAll(robot, matcher, timeout) { getUiRootsForProject(project) }
selector(result) ?: throw ComponentLookupException("Cannot filter result component from: $result")
}
else {
waitUntilFound(robot, matcher, timeout) { getUiRootsForProject(project) }
}
}
catch (e: WaitTimedOutError) {
throw ComponentLookupException(
"Unable to find ${componentClass.simpleName} in containers ${getUiRootsForProject(project)} in ${timeout.duration()}(ms)")
}
}
fun <ComponentType : Component> findAllShowingComponentWithTimeout(project: Project,
componentClass: Class<ComponentType>,
timeout: Timeout = Timeout.timeout(10, TimeUnit.SECONDS),
finderFunction: (ComponentType) -> Boolean = { true }): Collection<ComponentType> {
try {
val matcher = typeMatcher(componentClass) {
it.isShowing && finderFunction(it) && isReallyVisible(it)
}
return waitUntilFoundAll(robot, matcher, timeout) { getUiRootsForProject(project) }
}
catch (e: WaitTimedOutError) {
throw ComponentLookupException(
"Unable to find ${componentClass.simpleName} in containers ${getUiRootsForProject(project)} in ${timeout.duration()}(ms)")
}
}
/**
* function to find component of returning type inside a container (gets from receiver).
*
* @throws ComponentLookupException if desired component haven't been found under the container (gets from receiver) in specified timeout
*/
inline fun <reified ComponentType : Component, ContainerComponentType : Container> IftTestContainerFixture<ContainerComponentType>.findComponentWithTimeout(
timeout: Timeout = Timeout.timeout(10, TimeUnit.SECONDS),
crossinline finderFunction: (ComponentType) -> Boolean = { true }): ComponentType {
try {
return waitUntilFound(robot,
typeMatcher(ComponentType::class.java) { finderFunction(it) },
timeout) { listOf(this.target() as Container) }
}
catch (e: WaitTimedOutError) {
throw ComponentLookupException(
"Unable to find ${ComponentType::class.java.name} in container ${this.target()} in ${timeout.duration()}")
}
}
fun <ComponentType : Component> findComponentOrNull(project: Project,
componentClass: Class<ComponentType>,
selector: ((candidates: Collection<ComponentType>) -> ComponentType?)? = null,
finderFunction: (ComponentType) -> Boolean = { true }): ComponentType? {
return try {
findShowingComponentWithTimeout(project, componentClass, defaultComponentSearchShortTimeout, selector, finderFunction)
}
catch (e: WaitTimedOutError) {
null
}
catch (e: ComponentLookupException) {
null
}
}
} | apache-2.0 | 401e65ffdb80486687e73c2d745c3c1b | 43.057292 | 158 | 0.635138 | 5.21455 | false | false | false | false |
GunoH/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/util/CoroutineLRUCache.kt | 3 | 4536 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* 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.jetbrains.packagesearch.intellij.plugin.util
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerializationException
import kotlinx.serialization.builtins.MapSerializer
import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.descriptors.element
import kotlinx.serialization.encoding.CompositeDecoder
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.encoding.decodeStructure
import kotlinx.serialization.encoding.encodeStructure
import kotlinx.serialization.serializer
import org.apache.commons.collections.map.LRUMap
@Suppress("UNCHECKED_CAST")
class CoroutineLRUCache<K : Any, V>(val maxSize: Int, initialValues: Map<K, V> = emptyMap()) {
companion object {
inline fun <reified K : Any, reified V> serializer(
keySerializer: KSerializer<K> = serializer<K>(),
valueSerializer: KSerializer<V> = serializer<V>()
) = object : KSerializer<CoroutineLRUCache<K, V>> {
private val mapSerializer = MapSerializer(keySerializer, valueSerializer)
override val descriptor = buildClassSerialDescriptor(
"${CoroutineLRUCache::class.qualifiedName}<${K::class.qualifiedName}, ${V::class.qualifiedName}>"
) {
element<Int>("maxSize")
element("map", mapSerializer.descriptor)
}
override fun deserialize(decoder: Decoder) = decoder.decodeStructure(descriptor) {
var maxSize: Int? = null
var map: Map<K, V>? = null
loop@ while (true) {
when (val index = decodeElementIndex(descriptor)) {
0 -> maxSize = decodeIntElement(descriptor, 0)
1 -> map = decodeSerializableElement(descriptor, 1, mapSerializer)
CompositeDecoder.DECODE_DONE -> break@loop
else -> throw SerializationException("Unexpected index $index")
}
}
CoroutineLRUCache(requireNotNull(maxSize), requireNotNull(map))
}
override fun serialize(encoder: Encoder, value: CoroutineLRUCache<K, V>) = encoder.encodeStructure(descriptor) {
encodeIntElement(descriptor, 0, value.maxSize)
encodeSerializableElement(descriptor, 1, mapSerializer, runBlocking { value.cachedElements() })
}
}
}
private val cache = LRUMap(maxSize).apply { putAll(initialValues) }
private val syncMutex = Mutex()
suspend fun get(key: K): V? = syncMutex.withLock { cache[key] as? V }
suspend fun getValue(key: K): V = checkNotNull(get(key)) { "Key $key not available" }
suspend fun put(key: K, value: V) {
syncMutex.withLock { cache.put(key, value) }
}
suspend fun getOrElse(key: K, default: suspend () -> V) = syncMutex.withLock {
val value = cache[key] as? V
value ?: default()
}
suspend fun getOrPut(key: K, default: suspend () -> V) = syncMutex.withLock {
val value = cache[key] as? V
value ?: default().also { cache[key] = it }
}
suspend fun getOrTryPutDefault(key: K, default: suspend () -> V) = syncMutex.withLock {
val value = cache[key] as? V
value ?: runCatching { default() }.getOrNull()?.also<V> { cache[key] = it }
}
suspend fun clear() {
syncMutex.withLock { cache.clear() }
}
suspend fun cachedElements() =
syncMutex.withLock { cache.map { (k, v) -> k as K to v as V }.toMap() }
}
| apache-2.0 | a371c654aa6cbde89b98ad752d1d0c1c | 41.392523 | 124 | 0.637787 | 4.705394 | false | false | false | false |
GunoH/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/indexedProperty/impl.kt | 7 | 1570 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.transformations.indexedProperty
import com.intellij.psi.CommonClassNames.JAVA_UTIL_LIST
import com.intellij.psi.PsiArrayType
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiType
import com.intellij.psi.util.CachedValueProvider.Result
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiUtil
import org.jetbrains.annotations.NonNls
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder
internal const val indexedPropertyFqn = "groovy.transform.IndexedProperty"
@NonNls
internal const val indexedPropertyOriginInfo = "by @IndexedProperty"
const val indexedMethodKind: String = "groovy.transform.IndexedProperty.kind"
internal fun GrField.getIndexedComponentType() = CachedValuesManager.getCachedValue(this) {
Result.create(doGetIndexedComponentType(this), containingFile)
}
private fun doGetIndexedComponentType(field: GrField): PsiType? {
return when (val fieldType = field.type) {
is PsiArrayType -> fieldType.componentType
is PsiClassType -> PsiUtil.substituteTypeParameter(fieldType, JAVA_UTIL_LIST, 0, true)
else -> null
}
}
internal fun findIndexedPropertyMethods(field: GrField) = field.containingClass?.methods?.filter {
it is GrLightMethodBuilder && it.methodKind == indexedMethodKind && it.navigationElement == field
}
| apache-2.0 | 48c7e5fd7e5b106de557d884f60c85d3 | 45.176471 | 140 | 0.815287 | 4.325069 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/ChangesViewCommitWorkflowHandler.kt | 2 | 11452 | // 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.vcs.commit
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectCloseListener
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsDataKeys.COMMIT_WORKFLOW_HANDLER
import com.intellij.openapi.vcs.changes.*
import com.intellij.util.EventDispatcher
import com.intellij.util.containers.CollectionFactory
import java.util.*
import kotlin.properties.Delegates.observable
private fun Collection<Change>.toPartialAwareSet() =
CollectionFactory.createCustomHashingStrategySet(ChangeListChange.HASHING_STRATEGY)
.also { it.addAll(this) }
internal class ChangesViewCommitWorkflowHandler(
override val workflow: ChangesViewCommitWorkflow,
override val ui: ChangesViewCommitWorkflowUi
) : NonModalCommitWorkflowHandler<ChangesViewCommitWorkflow, ChangesViewCommitWorkflowUi>(),
CommitAuthorListener,
ProjectCloseListener {
override val commitPanel: CheckinProjectPanel = CommitProjectPanelAdapter(this)
override val amendCommitHandler: NonModalAmendCommitHandler = NonModalAmendCommitHandler(this)
override val commitAuthorTracker: CommitAuthorTracker get() = ui
private fun getCommitState(): ChangeListCommitState {
val changes = getIncludedChanges()
val changeList = workflow.getAffectedChangeList(changes)
return ChangeListCommitState(changeList, changes, getCommitMessage())
}
private val activityEventDispatcher = EventDispatcher.create(ActivityListener::class.java)
private val changeListManager = ChangeListManagerEx.getInstanceEx(project)
private var knownActiveChanges: Collection<Change> = emptyList()
private val inclusionModel = PartialCommitInclusionModel(project)
private val commitMessagePolicy = ChangesViewCommitMessagePolicy(project)
private var currentChangeList by observable<LocalChangeList?>(null) { _, oldValue, newValue ->
if (oldValue?.id != newValue?.id) {
changeListChanged(oldValue, newValue)
changeListDataChanged()
}
else if (oldValue?.data != newValue?.data) {
changeListDataChanged()
}
}
init {
Disposer.register(this, inclusionModel)
Disposer.register(this, ui)
workflow.addListener(this, this)
workflow.addVcsCommitListener(GitCommitStateCleaner(), this)
workflow.addVcsCommitListener(PostCommitChecksRunner(), this)
ui.addCommitAuthorListener(this, this)
ui.addExecutorListener(this, this)
ui.addDataProvider(createDataProvider())
ui.addInclusionListener(this, this)
ui.inclusionModel = inclusionModel
Disposer.register(inclusionModel, Disposable { ui.inclusionModel = null })
ui.setCompletionContext(changeListManager.changeLists)
setupDumbModeTracking()
setupCommitHandlersTracking()
setupCommitChecksResultTracking()
vcsesChanged() // as currently vcses are set before handler subscribes to corresponding event
currentChangeList = workflow.getAffectedChangeList(emptySet())
if (isToggleMode()) deactivate(false)
val busConnection = project.messageBus.connect(this)
busConnection.subscribe(ProjectCloseListener.TOPIC, this)
CommitModeManager.subscribeOnCommitModeChange(busConnection, object : CommitModeManager.CommitModeListener {
override fun commitModeChanged() {
if (isToggleMode()) {
deactivate(false)
}
else {
activate()
}
}
})
DelayedCommitMessageProvider.init(project, ui, getCommitMessageFromPolicy(currentChangeList))
}
override fun createDataProvider(): DataProvider = object : DataProvider {
private val superProvider = [email protected]()
override fun getData(dataId: String): Any? =
if (COMMIT_WORKFLOW_HANDLER.`is`(dataId)) [email protected] { it.isActive }
else superProvider.getData(dataId)
}
override fun commitOptionsCreated() {
currentChangeList?.let { commitOptions.changeListChanged(it) }
}
override fun executionEnded() {
super.executionEnded()
ui.endExecution()
}
fun synchronizeInclusion(changeLists: List<LocalChangeList>, unversionedFiles: List<FilePath>) {
if (!inclusionModel.isInclusionEmpty()) {
val possibleInclusion = CollectionFactory.createCustomHashingStrategySet(ChangeListChange.HASHING_STRATEGY)
possibleInclusion.addAll(changeLists.asSequence().flatMap { it.changes })
possibleInclusion.addAll(unversionedFiles)
inclusionModel.retainInclusion(possibleInclusion)
}
if (knownActiveChanges.isNotEmpty()) {
val activeChanges = changeListManager.defaultChangeList.changes
knownActiveChanges = knownActiveChanges.intersect(activeChanges)
}
inclusionModel.changeLists = changeLists
ui.setCompletionContext(changeLists)
}
fun setCommitState(changeList: LocalChangeList, items: Collection<Any>, force: Boolean) {
setInclusion(items, force)
setSelection(changeList)
}
private fun setInclusion(items: Collection<Any>, force: Boolean) {
val activeChanges = changeListManager.defaultChangeList.changes
if (!isActive || force) {
inclusionModel.clearInclusion()
inclusionModel.addInclusion(items)
knownActiveChanges = if (!isActive) activeChanges else emptyList()
}
else {
// skip if we have inclusion from not active change lists
if ((inclusionModel.getInclusion() - activeChanges.toPartialAwareSet()).filterIsInstance<Change>().isNotEmpty()) return
// we have inclusion in active change list and/or unversioned files => include new active changes if any
val newChanges = activeChanges - knownActiveChanges
inclusionModel.addInclusion(newChanges)
// include all active changes if nothing is included
if (inclusionModel.isInclusionEmpty()) inclusionModel.addInclusion(activeChanges)
}
}
private fun setSelection(changeList: LocalChangeList) {
val inclusion = inclusionModel.getInclusion()
val isChangeListFullyIncluded = changeList.changes.run { isNotEmpty() && all { it in inclusion } }
if (isChangeListFullyIncluded) {
ui.select(changeList)
ui.expand(changeList)
}
else {
ui.selectFirst(inclusion)
}
}
val isActive: Boolean get() = ui.isActive
fun activate(): Boolean = fireActivityStateChanged { ui.activate() }
fun deactivate(isRestoreState: Boolean) {
fireActivityStateChanged { ui.deactivate(isRestoreState) }
if (isToggleMode()) {
resetCommitChecksResult()
ui.commitProgressUi.clearCommitCheckFailures()
}
}
fun addActivityListener(listener: ActivityListener) = activityEventDispatcher.addListener(listener)
private fun <T> fireActivityStateChanged(block: () -> T): T {
val oldValue = isActive
return block().also { if (oldValue != isActive) activityEventDispatcher.multicaster.activityStateChanged() }
}
private fun changeListChanged(oldChangeList: LocalChangeList?, newChangeList: LocalChangeList?) {
oldChangeList?.let { commitMessagePolicy.save(it, getCommitMessage(), false) }
val newCommitMessage = getCommitMessageFromPolicy(newChangeList)
setCommitMessage(newCommitMessage)
newChangeList?.let { commitOptions.changeListChanged(it) }
}
private fun getCommitMessageFromPolicy(changeList: LocalChangeList?): String? {
if (changeList == null) return null
return commitMessagePolicy.getCommitMessage(changeList) { getIncludedChanges() }
}
private fun changeListDataChanged() {
ui.commitAuthor = currentChangeList?.author
ui.commitAuthorDate = currentChangeList?.authorDate
}
override fun commitAuthorChanged() {
val changeList = changeListManager.getChangeList(currentChangeList?.id) ?: return
if (ui.commitAuthor == changeList.author) return
changeListManager.editChangeListData(changeList.name, ChangeListData.of(ui.commitAuthor, ui.commitAuthorDate))
}
override fun commitAuthorDateChanged() {
val changeList = changeListManager.getChangeList(currentChangeList?.id) ?: return
if (ui.commitAuthorDate == changeList.authorDate) return
changeListManager.editChangeListData(changeList.name, ChangeListData.of(ui.commitAuthor, ui.commitAuthorDate))
}
override fun inclusionChanged() {
val inclusion = inclusionModel.getInclusion()
val activeChanges = changeListManager.defaultChangeList.changes
val includedActiveChanges = activeChanges.filter { it in inclusion }
// ensure all included active changes are known => if user explicitly checks and unchecks some change, we know it is unchecked
knownActiveChanges = knownActiveChanges.union(includedActiveChanges)
currentChangeList = workflow.getAffectedChangeList(inclusion.filterIsInstance<Change>())
super.inclusionChanged()
}
override fun beforeCommitChecksEnded(sessionInfo: CommitSessionInfo, result: CommitChecksResult) {
super.beforeCommitChecksEnded(sessionInfo, result)
if (result.shouldCommit) {
// commit message could be changed during before-commit checks - ensure updated commit message is used for commit
workflow.commitState = workflow.commitState.copy(getCommitMessage())
if (isToggleMode()) deactivate(true)
}
}
private fun isToggleMode(): Boolean {
val commitMode = CommitModeManager.getInstance(project).getCurrentCommitMode()
return commitMode is CommitMode.NonModalCommitMode && commitMode.isToggleMode
}
override fun updateWorkflow(sessionInfo: CommitSessionInfo): Boolean {
workflow.commitState = getCommitState()
return configureCommitSession(project, sessionInfo,
workflow.commitState.changes,
workflow.commitState.commitMessage)
}
override fun prepareForCommitExecution(sessionInfo: CommitSessionInfo): Boolean {
if (sessionInfo.isVcsCommit) {
val changeList = workflow.getAffectedChangeList(getIncludedChanges())
if (!addUnversionedFiles(project, getIncludedUnversionedFiles(), changeList, inclusionModel)) return false
}
return super.prepareForCommitExecution(sessionInfo)
}
override fun saveCommitMessage(success: Boolean) = commitMessagePolicy.save(currentChangeList, getCommitMessage(), success)
// save state on project close
// using this method ensures change list comment and commit options are updated before project state persisting
override fun projectClosingBeforeSave(project: Project) {
saveStateBeforeDispose()
disposeCommitOptions()
currentChangeList = null
}
// save state on other events - like "settings changed to use commit dialog"
override fun dispose() {
saveStateBeforeDispose()
disposeCommitOptions()
super.dispose()
}
private fun saveStateBeforeDispose() {
commitOptions.saveState()
saveCommitMessage(false)
}
interface ActivityListener : EventListener {
fun activityStateChanged()
}
private inner class GitCommitStateCleaner : CommitStateCleaner() {
override fun onSuccess() {
setCommitMessage(getCommitMessageFromPolicy(currentChangeList))
super.onSuccess()
}
}
}
| apache-2.0 | b5c5acb0cb4766d91a76b848cc221fc7 | 37.046512 | 140 | 0.760129 | 5.062776 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/InlayTextMetrics.kt | 1 | 4577 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInsight.hints.presentation
import com.intellij.ide.ui.AntialiasingType
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.editor.impl.FontInfo
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.StartupUiUtil
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.ApiStatus
import java.awt.Font
import java.awt.FontMetrics
import java.awt.font.FontRenderContext
import javax.swing.JComponent
import kotlin.math.ceil
import kotlin.math.max
@ApiStatus.Internal
class InlayTextMetricsStorage(val editor: EditorImpl) {
private var smallTextMetrics : InlayTextMetrics? = null
private var normalTextMetrics : InlayTextMetrics? = null
private val smallTextSize: Float
@RequiresEdt
get() = max(1f, editor.colorsScheme.editorFontSize2D - 1f)
private val normalTextSize: Float
@RequiresEdt
get() = editor.colorsScheme.editorFontSize2D
@RequiresEdt
fun getFontMetrics(small: Boolean): InlayTextMetrics {
var metrics: InlayTextMetrics?
val familyName = if (EditorSettingsExternalizable.getInstance().isUseEditorFontInInlays) {
EditorColorsManager.getInstance().globalScheme.editorFontName
} else {
StartupUiUtil.getLabelFont().family
}
val fontType = editor.colorsScheme.getAttributes(DefaultLanguageHighlighterColors.INLAY_DEFAULT).fontType
if (small) {
metrics = smallTextMetrics
val fontSize = smallTextSize
if (metrics == null || !metrics.isActual(smallTextSize, familyName)) {
metrics = InlayTextMetrics.create(editor, fontSize, fontType)
smallTextMetrics = metrics
}
} else {
metrics = normalTextMetrics
val fontSize = normalTextSize
if (metrics == null || !metrics.isActual(normalTextSize, familyName)) {
metrics = InlayTextMetrics.create(editor, fontSize, fontType)
normalTextMetrics = metrics
}
}
return metrics
}
}
class InlayTextMetrics(
editor: EditorImpl,
val fontHeight: Int,
val fontBaseline: Int,
private val fontMetrics: FontMetrics,
val fontType: Int
) {
companion object {
internal fun create(editor: EditorImpl, size: Float, fontType: Int) : InlayTextMetrics {
val font = if (EditorSettingsExternalizable.getInstance().isUseEditorFontInInlays) {
val editorFont = EditorUtil.getEditorFont()
editorFont.deriveFont(fontType, size)
} else {
val familyName = StartupUiUtil.getLabelFont().family
UIUtil.getFontWithFallback(familyName, fontType, size)
}
val context = getCurrentContext(editor.component)
val metrics = FontInfo.getFontMetrics(font, context)
// We assume this will be a better approximation to a real line height for a given font
val fontHeight = ceil(font.createGlyphVector(context, "Albpq@").visualBounds.height).toInt()
val fontBaseline = ceil(font.createGlyphVector(context, "Alb").visualBounds.height).toInt()
return InlayTextMetrics(editor, fontHeight, fontBaseline, metrics, fontType)
}
private fun getCurrentContext(editorComponent: JComponent): FontRenderContext {
val editorContext = FontInfo.getFontRenderContext(editorComponent)
return FontRenderContext(editorContext.transform,
AntialiasingType.getKeyForCurrentScope(false),
UISettings.editorFractionalMetricsHint)
}
}
val font: Font
get() = fontMetrics.font
// Editor metrics:
val ascent: Int = editor.ascent
val descent: Int = editor.descent
private val lineHeight = editor.lineHeight
private val editorComponent = editor.component
fun isActual(size: Float, familyName: String) : Boolean {
if (size != font.size2D) return false
if (font.family != familyName) return false
return getCurrentContext(editorComponent).equals(fontMetrics.fontRenderContext)
}
/**
* Offset from the top edge of drawing rectangle to rectangle with text.
*/
fun offsetFromTop(): Int = (lineHeight - fontHeight) / 2
fun getStringWidth(text: String): Int {
return fontMetrics.stringWidth(text)
}
} | apache-2.0 | 8a19712ea9101ecbd46af0ec3e2a4ac6 | 36.52459 | 120 | 0.743063 | 4.699179 | false | false | false | false |
rei-m/HBFav_material | app/src/main/kotlin/me/rei_m/hbfavmaterial/model/NewEntryModel.kt | 1 | 4647 | /*
* Copyright (c) 2017. Rei Matsushita
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package me.rei_m.hbfavmaterial.model
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject
import me.rei_m.hbfavmaterial.constant.EntryTypeFilter
import me.rei_m.hbfavmaterial.extension.subscribeAsync
import me.rei_m.hbfavmaterial.infra.network.HatenaRssService
import me.rei_m.hbfavmaterial.model.entity.Article
import me.rei_m.hbfavmaterial.model.entity.Entry
import me.rei_m.hbfavmaterial.model.util.ApiUtil
import me.rei_m.hbfavmaterial.model.util.RssXmlUtil
import org.jsoup.Jsoup
class NewEntryModel(private val hatenaRssService: HatenaRssService) {
private val isLoadingSubject = BehaviorSubject.create<Boolean>()
private val isRefreshingSubject = BehaviorSubject.create<Boolean>()
private val entryListSubject = BehaviorSubject.create<List<Entry>>()
private val entryTypeFilterSubject = BehaviorSubject.create<EntryTypeFilter>()
private val isRaisedGetErrorSubject = BehaviorSubject.create<Boolean>()
private val isRaisedRefreshErrorSubject = PublishSubject.create<Unit>()
val isLoading: Observable<Boolean> = isLoadingSubject
val isRefreshing: Observable<Boolean> = isRefreshingSubject
val entryList: Observable<List<Entry>> = entryListSubject
val entryTypeFilter: Observable<EntryTypeFilter> = entryTypeFilterSubject
val isRaisedGetError: Observable<Boolean> = isRaisedGetErrorSubject
val isRaisedRefreshError: Observable<Unit> = isRaisedRefreshErrorSubject
init {
isLoadingSubject.onNext(false)
isRefreshingSubject.onNext(false)
}
fun getList(entryTypeFilter: EntryTypeFilter) {
if (isLoadingSubject.value) {
return
}
if (entryListSubject.hasValue() && entryTypeFilterSubject.hasValue()) {
if (entryTypeFilterSubject.value == entryTypeFilter) {
entryListSubject.retry()
entryTypeFilterSubject.retry()
return
} else {
entryListSubject.onNext(listOf())
}
}
isLoadingSubject.onNext(true)
fetch(entryTypeFilter).subscribeAsync({
entryListSubject.onNext(it)
entryTypeFilterSubject.onNext(entryTypeFilter)
isRaisedGetErrorSubject.onNext(false)
}, {
isRaisedGetErrorSubject.onNext(true)
}, {
isLoadingSubject.onNext(false)
})
}
fun refreshList() {
if (isRefreshingSubject.value) {
return
}
isRefreshingSubject.onNext(true)
fetch(entryTypeFilterSubject.value).subscribeAsync({
entryListSubject.onNext(listOf())
entryListSubject.onNext(it)
isRaisedGetErrorSubject.onNext(false)
}, {
isRaisedRefreshErrorSubject.onNext(Unit)
}, {
isRefreshingSubject.onNext(false)
})
}
private fun fetch(entryTypeFilter: EntryTypeFilter): Single<List<Entry>> {
val rss = if (entryTypeFilter == EntryTypeFilter.ALL) {
hatenaRssService.new()
} else {
hatenaRssService.new(ApiUtil.getEntryTypeRss(entryTypeFilter))
}
return rss.map { response ->
response.list.map {
val parsedContent = Jsoup.parse(it.content)
val article = Article(
title = it.title,
url = it.link,
bookmarkCount = it.bookmarkCount,
iconUrl = RssXmlUtil.extractArticleIcon(parsedContent),
body = RssXmlUtil.extractArticleBodyForEntry(parsedContent),
bodyImageUrl = RssXmlUtil.extractArticleImageUrl(parsedContent))
Entry(
article = article,
description = it.description,
date = RssXmlUtil.parseStringToDate(it.dateString),
subject = it.subject)
}
}
}
}
| apache-2.0 | 185db33621f80b1f6f7b294c3ab300b5 | 36.176 | 112 | 0.661717 | 4.87618 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/blacklist/BlacklistUsersFragment.kt | 1 | 2101 | package io.github.feelfreelinux.wykopmobilny.ui.modules.blacklist
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.base.BaseFragment
import io.github.feelfreelinux.wykopmobilny.ui.adapters.BlacklistAdapter
import io.github.feelfreelinux.wykopmobilny.utils.preferences.BlacklistPreferences
import io.github.feelfreelinux.wykopmobilny.utils.prepare
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.blacklist_fragment.*
import javax.inject.Inject
class BlacklistUsersFragment : BaseFragment() {
companion object {
fun createFragment() = BlacklistUsersFragment()
}
@Inject lateinit var adapter: BlacklistAdapter
@Inject lateinit var blacklistPreferences: BlacklistPreferences
private val disposable = CompositeDisposable()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.blacklist_fragment, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
adapter.isBlockUser = true
adapter.unblockListener = {
(activity as BlacklistActivity).unblockUser(it)
}
adapter.blockListener = {
(activity as BlacklistActivity).blockUser(it)
}
recyclerView.prepare()
recyclerView.adapter = adapter
updateData()
}
private fun updateData() {
adapter.items.clear()
adapter.items.addAll(blacklistPreferences.blockedUsers)
adapter.notifyDataSetChanged()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
disposable.add((activity as BlacklistActivity).updateDataSubject.subscribe {
updateData()
})
}
override fun onDestroy() {
disposable.dispose()
super.onDestroy()
}
} | mit | 9a1869545884c8c0eaa8889d8f664d82 | 33.459016 | 116 | 0.734888 | 5.12439 | false | false | false | false |
GunoH/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/ext/ginq/GinqUtils.kt | 8 | 4109 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("GinqUtils")
package org.jetbrains.plugins.groovy.ext.ginq
import com.intellij.psi.CommonClassNames.JAVA_LANG_LONG
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.JAVA_MATH_BIG_DECIMAL
const val GROOVY_GINQ_TRANSFORM_GQ = "groovy.ginq.transform.GQ"
val GINQ_METHODS: Set<String> = setOf(
"GQ",
"GQL",
)
val JOINS : Set<String> = setOf(
"join",
"innerjoin",
"innerhashjoin",
"leftjoin",
"lefthashjoin",
"crossjoin",
"rightjoin",
"righthashjoin",
"fulljoin",
"fullhashjoin",
)
const val KW_CROSSJOIN: String = "crossjoin"
const val KW_FROM: String = "from"
const val KW_ON: String = "on"
const val KW_WHERE: String = "where"
const val KW_GROUPBY: String = "groupby"
const val KW_HAVING: String = "having"
const val KW_ORDERBY: String = "orderby"
const val KW_LIMIT: String = "limit"
const val KW_SELECT = "select"
const val KW_ASC: String = "asc"
const val KW_DESC: String = "desc"
const val KW_NULLSFIRST: String = "nullsfirst"
const val KW_NULLSLAST: String = "nullslast"
const val GINQ_EXISTS: String = "exists"
const val KW_SHUTDOWN = "shutdown"
const val KW_IMMEDIATE = "immediate"
const val KW_ABORT = "abort"
const val ORG_APACHE_GROOVY_GINQ_PROVIDER_COLLECTION_RUNTIME_QUERYABLE : String =
"org.apache.groovy.ginq.provider.collection.runtime.Queryable"
const val ORG_APACHE_GROOVY_GINQ_PROVIDER_COLLECTION_RUNTIME_WINDOW : String =
"org.apache.groovy.ginq.provider.collection.runtime.Window"
const val ORG_APACHE_GROOVY_GINQ_PROVIDER_COLLECTION_RUNTIME_NAMED_RECORD: String =
"org.apache.groovy.ginq.provider.collection.runtime.NamedRecord"
internal const val OVER_ORIGIN_INFO = "Ginq over"
internal interface GinqSupport {
fun getQueryable(context: PsiElement): PsiClass? =
JavaPsiFacade.getInstance(context.project).findClass(ORG_APACHE_GROOVY_GINQ_PROVIDER_COLLECTION_RUNTIME_QUERYABLE, context.resolveScope)
fun findQueryableMethod(context: PsiElement, methodName: String): PsiMethod? =
getQueryable(context)?.findMethodsByName(methodName, false)?.singleOrNull()
fun getNamedRecord(context: PsiElement) : PsiClass? =
JavaPsiFacade.getInstance(context.project).findClass(ORG_APACHE_GROOVY_GINQ_PROVIDER_COLLECTION_RUNTIME_NAMED_RECORD, context.resolveScope)
fun getWindow(context: PsiElement): PsiClass? =
JavaPsiFacade.getInstance(context.project).findClass(ORG_APACHE_GROOVY_GINQ_PROVIDER_COLLECTION_RUNTIME_WINDOW, context.resolveScope)
}
data class Signature(val returnType: String, val parameters: List<Pair<String, String>>)
val windowFunctions : Map<String, Signature> = mapOf(
"rowNumber" to Signature(JAVA_LANG_LONG, emptyList()),
"rank" to Signature(JAVA_LANG_LONG, emptyList()),
"denseRank" to Signature(JAVA_LANG_LONG, emptyList()),
"percentRank" to Signature(JAVA_MATH_BIG_DECIMAL, emptyList()),
"cumeDist" to Signature(JAVA_MATH_BIG_DECIMAL, emptyList()),
"ntile" to Signature(JAVA_LANG_LONG, listOf("expr" to JAVA_LANG_LONG)),
"lead" to Signature("T", listOf("expr" to "T", "?offset" to JAVA_LANG_LONG, "?default" to "T")),
"lag" to Signature("T", listOf("expr" to "T", "?offset" to JAVA_LANG_LONG, "?default" to "T")),
"firstValue" to Signature("T", listOf("expr" to "T")),
"lastValue" to Signature("T", listOf("expr" to "T")),
"nthValue" to Signature("T", listOf("expr" to "T", "n" to JAVA_LANG_LONG)),
)
sealed interface GinqRootPsiElement {
val psi: GroovyPsiElement
@JvmInline
value class Call(override val psi: GrMethodCall) : GinqRootPsiElement
@JvmInline
value class Method(override val psi: GrMethod) : GinqRootPsiElement
}
| apache-2.0 | 6de97e3030ae5ca8a07e1d1283174886 | 36.354545 | 143 | 0.751521 | 3.381893 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesViewContentManager.kt | 5 | 11463 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vcs.changes.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataKey
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.options.advanced.AdvancedSettings
import com.intellij.openapi.options.advanced.AdvancedSettingsChangeListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.ui.content.Content
import com.intellij.ui.content.ContentManager
import com.intellij.ui.content.ContentManagerEvent
import com.intellij.ui.content.ContentManagerListener
import com.intellij.util.IJSwingUtilities
import com.intellij.util.ObjectUtils.tryCast
import com.intellij.vcs.commit.CommitModeManager
import org.jetbrains.annotations.NonNls
import java.util.function.Predicate
import kotlin.properties.Delegates.observable
private const val COMMIT_TOOL_WINDOW = "vcs.commit.tool.window"
internal val Project.isCommitToolWindowShown: Boolean
get() = ChangesViewContentManager.isCommitToolWindowShown(this)
internal fun ContentManager.selectFirstContent() {
val firstContent = getContent(0)
if (firstContent != null) setSelectedContent(firstContent)
}
private val LOG = logger<ChangesViewContentManager>()
class ChangesViewContentManager(private val project: Project) : ChangesViewContentI, Disposable {
private val addedContents = mutableListOf<Content>()
private val toolWindows = mutableSetOf<ToolWindow>()
private val contentManagers: Collection<ContentManager> get() = toolWindows.map { it.contentManager }
private fun Content.resolveToolWindowId(): String {
val isInCommitToolWindow = IS_IN_COMMIT_TOOLWINDOW_KEY.get(this) == true
if (isInCommitToolWindow && isCommitToolWindowShown) return COMMIT_TOOLWINDOW_ID
return TOOLWINDOW_ID
}
private fun Content.resolveContentManager(): ContentManager? {
val toolWindowId = resolveToolWindowId()
val toolWindow = toolWindows.find { it.id == toolWindowId }
return toolWindow?.contentManager
}
private var isCommitToolWindowShown: Boolean by observable(shouldUseCommitToolWindow()) { _, oldValue, newValue ->
if (oldValue == newValue) return@observable
remapContents()
project.messageBus.syncPublisher(ChangesViewContentManagerListener.TOPIC).toolWindowMappingChanged()
}
init {
ApplicationManager.getApplication().messageBus.connect(project)
.subscribe(AdvancedSettingsChangeListener.TOPIC, object : AdvancedSettingsChangeListener {
override fun advancedSettingChanged(id: String, oldValue: Any, newValue: Any) {
if (id == COMMIT_TOOL_WINDOW) {
updateToolWindowMapping()
}
}
})
val projectBusConnection = project.messageBus.connect()
CommitModeManager.subscribeOnCommitModeChange(projectBusConnection, object : CommitModeManager.CommitModeListener {
override fun commitModeChanged() = updateToolWindowMapping()
})
}
private fun updateToolWindowMapping() {
isCommitToolWindowShown = shouldUseCommitToolWindow()
}
private fun shouldUseCommitToolWindow(): Boolean {
return AdvancedSettings.getBoolean(COMMIT_TOOL_WINDOW) &&
CommitModeManager.getInstance(project).getCurrentCommitMode().useCommitToolWindow()
}
private fun remapContents() {
val remapped = findContents { it.resolveContentManager() != it.manager }
remapped.forEach { removeContent(it, false) }
remapped.forEach { addContent(it) }
}
override fun attachToolWindow(toolWindow: ToolWindow) {
toolWindows.add(toolWindow)
initContentManager(toolWindow)
}
private fun initContentManager(toolWindow: ToolWindow) {
val contentManager = toolWindow.contentManager
val listener = ContentProvidersListener(toolWindow)
contentManager.addContentManagerListener(listener)
Disposer.register(this, Disposable { contentManager.removeContentManagerListener(listener) })
project.messageBus.connect(this).subscribe(ToolWindowManagerListener.TOPIC, listener)
val contents = addedContents.filter { it.resolveContentManager() === contentManager }
contents.forEach {
addIntoCorrectPlace(contentManager, it)
IJSwingUtilities.updateComponentTreeUI(it.component)
}
addedContents.removeAll(contents)
// Ensure that first tab is selected after tabs reordering
contentManager.selectFirstContent()
}
override fun dispose() {
for (content in addedContents) {
Disposer.dispose(content)
}
addedContents.clear()
}
override fun addContent(content: Content) {
val contentManager = content.resolveContentManager()
if (contentManager == null) {
addedContents.add(content)
}
else {
addIntoCorrectPlace(contentManager, content)
}
}
override fun removeContent(content: Content) = removeContent(content, true)
private fun removeContent(content: Content, dispose: Boolean) {
val contentManager = content.manager
if (contentManager == null || contentManager.isDisposed) {
addedContents.remove(content)
if (dispose) Disposer.dispose(content)
}
else {
contentManager.removeContent(content, dispose)
}
}
override fun setSelectedContent(content: Content) {
setSelectedContent(content, false)
}
override fun setSelectedContent(content: Content, requestFocus: Boolean) {
content.manager?.setSelectedContent(content, requestFocus)
}
override fun <T : Any> getActiveComponent(aClass: Class<T>): T? =
contentManagers.firstNotNullOfOrNull { tryCast(it.selectedContent?.component, aClass) }
fun isContentSelected(tabName: String): Boolean =
contentManagers.any { it.selectedContent?.tabName == tabName }
override fun selectContent(tabName: String) {
selectContent(tabName, false)
}
fun selectContent(tabName: String, requestFocus: Boolean) {
LOG.debug("select content: $tabName")
val content = contentManagers.flatMap { it.contents.asList() }.find { it.tabName == tabName } ?: return
content.manager?.setSelectedContent(content, requestFocus)
}
override fun findContents(predicate: Predicate<Content>): List<Content> {
val allContents = contentManagers.flatMap { it.contents.asList() } + addedContents
return allContents.filter { predicate.test(it) }
}
private fun getContentToolWindowId(tabName: String): String? {
val content = findContents { it.tabName == tabName }.firstOrNull() ?: return null
return content.resolveToolWindowId()
}
fun initLazyContent(content: Content) {
val provider = content.getUserData(CONTENT_PROVIDER_SUPPLIER_KEY)?.invoke() ?: return
content.putUserData(CONTENT_PROVIDER_SUPPLIER_KEY, null)
provider.initTabContent(content)
IJSwingUtilities.updateComponentTreeUI(content.component)
}
private inner class ContentProvidersListener(val toolWindow: ToolWindow) : ContentManagerListener, ToolWindowManagerListener {
override fun stateChanged(toolWindowManager: ToolWindowManager) {
if (toolWindow.isVisible) {
val content = toolWindow.contentManager.selectedContent ?: return
initLazyContent(content)
}
}
override fun selectionChanged(event: ContentManagerEvent) {
if (toolWindow.isVisible) {
initLazyContent(event.content)
}
}
}
enum class TabOrderWeight(val tabName: String?, val weight: Int) {
LOCAL_CHANGES(ChangesViewContentManager.LOCAL_CHANGES, 10),
REPOSITORY(ChangesViewContentManager.REPOSITORY, 20),
INCOMING(ChangesViewContentManager.INCOMING, 30),
SHELF(ChangesViewContentManager.SHELF, 40),
BRANCHES(ChangesViewContentManager.BRANCHES, 50),
OTHER(null, 100),
LAST(null, Integer.MAX_VALUE)
}
private fun addIntoCorrectPlace(contentManager: ContentManager, content: Content) {
val weight = getContentWeight(content)
val contents = contentManager.contents
var index = -1
for (i in contents.indices) {
val oldWeight = getContentWeight(contents[i])
if (oldWeight > weight) {
index = i
break
}
}
if (index == -1) index = contents.size
contentManager.addContent(content, index)
}
companion object {
const val TOOLWINDOW_ID = ToolWindowId.VCS
internal const val COMMIT_TOOLWINDOW_ID = ToolWindowId.COMMIT
@JvmField
internal val CONTENT_PROVIDER_SUPPLIER_KEY = Key.create<() -> ChangesViewContentProvider>("CONTENT_PROVIDER_SUPPLIER")
/**
* Whether [Content] should be shown in [ToolWindowId.COMMIT] toolwindow.
*/
@JvmField
val IS_IN_COMMIT_TOOLWINDOW_KEY = Key.create<Boolean>("ChangesViewContentManager.IS_IN_COMMIT_TOOLWINDOW_KEY")
@JvmField
val CONTENT_TAB_NAME_KEY = DataKey.create<@NonNls String>("ChangesViewContentManager.CONTENT_TAB_KEY")
@JvmStatic
fun getInstance(project: Project) = project.service<ChangesViewContentI>()
fun getInstanceImpl(project: Project): ChangesViewContentManager? =
getInstance(project) as? ChangesViewContentManager
@JvmStatic
fun isCommitToolWindowShown(project: Project): Boolean = getInstanceImpl(project)?.isCommitToolWindowShown == true
@JvmStatic
fun getToolWindowIdFor(project: Project, tabName: String): String {
val manager = getInstanceImpl(project) ?: return TOOLWINDOW_ID
val toolWindowId = manager.getContentToolWindowId(tabName)
if (toolWindowId != null) {
return toolWindowId
}
val extension = ChangesViewContentEP.EP_NAME.getExtensions(project).find { it.tabName == tabName }
if (extension != null) return getToolWindowId(project, extension)
return TOOLWINDOW_ID
}
internal fun getToolWindowId(project: Project, contentEp: ChangesViewContentEP): String {
return if (contentEp.isInCommitToolWindow && isCommitToolWindowShown(project)) COMMIT_TOOLWINDOW_ID else TOOLWINDOW_ID
}
@JvmStatic
fun getToolWindowFor(project: Project, tabName: String): ToolWindow? {
return ToolWindowManager.getInstance(project).getToolWindow(getToolWindowIdFor(project, tabName))
}
/**
* Specified tab order in toolwindow.
*
* @see ChangesViewContentManager.TabOrderWeight
*/
@JvmField
val ORDER_WEIGHT_KEY = Key.create<Int>("ChangesView.ContentOrderWeight")
const val LOCAL_CHANGES: @NonNls String = "Local Changes"
const val REPOSITORY: @NonNls String = "Repository"
const val INCOMING: @NonNls String = "Incoming"
const val SHELF: @NonNls String = "Shelf"
const val BRANCHES: @NonNls String = "Branches"
}
}
private fun getContentWeight(content: Content): Int {
val userData = content.getUserData(ChangesViewContentManager.ORDER_WEIGHT_KEY)
if (userData != null) return userData
val tabName: @NonNls String = content.tabName
for (value in ChangesViewContentManager.TabOrderWeight.values()) {
if (value.tabName != null && value.tabName == tabName) {
return value.weight
}
}
return ChangesViewContentManager.TabOrderWeight.OTHER.weight
} | apache-2.0 | 0b61f30df4e0d80e0a9f64d90521cb6f | 35.980645 | 128 | 0.748408 | 4.696026 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/inference/graph/InferenceUnitNode.kt | 13 | 4974 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.intentions.style.inference.graph
import com.intellij.psi.PsiIntersectionType
import com.intellij.psi.PsiType
import com.intellij.psi.PsiWildcardType
import org.jetbrains.plugins.groovy.intentions.style.inference.driver.BoundConstraint.ContainMarker.INHABIT
import org.jetbrains.plugins.groovy.intentions.style.inference.driver.TypeUsageInformation
import org.jetbrains.plugins.groovy.intentions.style.inference.graph.InferenceUnitNode.Companion.InstantiationHint.*
import org.jetbrains.plugins.groovy.intentions.style.inference.removeWildcard
import org.jetbrains.plugins.groovy.intentions.style.inference.resolve
import org.jetbrains.plugins.groovy.lang.resolve.processors.inference.type
import kotlin.LazyThreadSafetyMode.NONE
/**
* An analogue for inference variable.
*
* Unit is [direct] if it should be instantiated directly to it's supertype.
*/
class InferenceUnitNode internal constructor(val core: InferenceUnit,
parents: Set<() -> InferenceUnitNode>,
children: Set<() -> InferenceUnitNode>,
val typeInstantiation: PsiType,
val direct: Boolean = false) {
companion object {
enum class InstantiationHint {
REIFIED_AS_TYPE_PARAMETER,
REIFIED_AS_PROPER_TYPE,
ENDPOINT_TYPE_PARAMETER,
NEW_TYPE_PARAMETER,
EXTENDS_WILDCARD
}
}
/**
* direct supertypes of [InferenceUnit.initialTypeParameter]
*/
val supertypes: Set<InferenceUnitNode> by lazy { parents.map { it() }.toSet() }
/**
* direct subtypes of [InferenceUnit.initialTypeParameter]
*/
val subtypes: Set<InferenceUnitNode> by lazy { children.map { it() }.toSet() }
val type = core.type
fun smartTypeInstantiation(usage: TypeUsageInformation,
equivalenceClasses: Map<PsiType, List<InferenceUnitNode>>): Pair<PsiType, InstantiationHint> {
if (core.constant) {
return if (core.initialTypeParameter.extendsListTypes.isEmpty()) {
typeInstantiation to NEW_TYPE_PARAMETER
}
else {
type to REIFIED_AS_TYPE_PARAMETER
}
}
if (parent == null) {
if (typeInstantiation == PsiType.NULL) {
return PsiWildcardType.createUnbounded(core.initialTypeParameter.manager) to REIFIED_AS_PROPER_TYPE
}
if (typeInstantiation.resolve()?.hasModifierProperty("final") == true) {
return typeInstantiation to REIFIED_AS_PROPER_TYPE
}
val flushedTypeInstantiation = removeWildcard(typeInstantiation)
if (flushedTypeInstantiation is PsiIntersectionType) {
return flushedTypeInstantiation to NEW_TYPE_PARAMETER
}
}
if (parent != null) {
if (!usage.contravariantTypes.contains(core.initialTypeParameter.type()) && subtypes.isEmpty()) {
return parent!!.type to EXTENDS_WILDCARD
}
else {
return parent!!.type to NEW_TYPE_PARAMETER
}
}
val inhabitedByUniqueType = lazy(NONE) {
usage.requiredClassTypes[core.initialTypeParameter]?.filter { it.marker == INHABIT }?.run { isNotEmpty() && all { first().type == it.type } }
?: false
}
if (equivalenceClasses[type]?.all { it.core.initialTypeParameter !in usage.dependentTypes } == true) {
if (direct || typeInstantiation is PsiWildcardType || inhabitedByUniqueType.value) {
return typeInstantiation to REIFIED_AS_PROPER_TYPE
}
else {
return typeInstantiation to EXTENDS_WILDCARD
}
}
if (equivalenceClasses[type]?.any { usage.invariantTypes.contains(it.type) || it.subtypes.isNotEmpty() } == true) {
val advice = parent?.type ?: typeInstantiation
return if (advice == typeInstantiation) {
(if (advice == PsiType.NULL) type else advice) to ENDPOINT_TYPE_PARAMETER
}
else {
advice to NEW_TYPE_PARAMETER
}
}
if (direct) {
return typeInstantiation to REIFIED_AS_PROPER_TYPE
}
if (typeInstantiation == PsiType.NULL) {
return type to REIFIED_AS_TYPE_PARAMETER
}
return if (subtypes.isNotEmpty()) {
type to REIFIED_AS_TYPE_PARAMETER
}
else {
typeInstantiation to REIFIED_AS_PROPER_TYPE
}
}
/**
* Direct dependency on other unit.
* It appears when we know that this [InferenceUnit.initialTypeParameter] must be a subtype of some other one.
* In java code it might be expressed as `<T extends U> void foo(){}`, so unit for `T` will have [parent] set to `U`
*/
val parent: InferenceUnitNode? by lazy { supertypes.firstOrNull() }
override fun toString(): String {
return "Unit node: ${core.initialTypeParameter.type().canonicalText} (${typeInstantiation.presentableText})"
}
} | apache-2.0 | 3a3b5b77e8ab9b26ccfe0f9dbd403ebf | 37.269231 | 147 | 0.677523 | 4.433155 | false | false | false | false |
hsz/idea-gitignore | src/main/kotlin/mobi/hsz/idea/gitignore/highlighter/IgnoreColorSettingsPage.kt | 1 | 2842 | // 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 mobi.hsz.idea.gitignore.highlighter
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.options.colors.AttributesDescriptor
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import mobi.hsz.idea.gitignore.IgnoreBundle
import mobi.hsz.idea.gitignore.util.Resources
import org.jetbrains.annotations.NonNls
import javax.swing.Icon
/**
* [ColorSettingsPage] that allows to modify color scheme.
*/
class IgnoreColorSettingsPage : ColorSettingsPage {
companion object {
@NonNls private val SAMPLE_GITIGNORE_PATH = "/sample.gitignore"
@NonNls private val DISPLAY_NAME = IgnoreBundle.message("ignore.colorSettings.displayName")
private val SAMPLE_GITIGNORE = loadSampleGitignore()
private val DESCRIPTORS = arrayOf(
AttributesDescriptor(IgnoreBundle.message("highlighter.header"), IgnoreHighlighterColors.HEADER),
AttributesDescriptor(IgnoreBundle.message("highlighter.section"), IgnoreHighlighterColors.SECTION),
AttributesDescriptor(IgnoreBundle.message("highlighter.comment"), IgnoreHighlighterColors.COMMENT),
AttributesDescriptor(IgnoreBundle.message("highlighter.negation"), IgnoreHighlighterColors.NEGATION),
AttributesDescriptor(IgnoreBundle.message("highlighter.brackets"), IgnoreHighlighterColors.BRACKET),
AttributesDescriptor(IgnoreBundle.message("highlighter.slash"), IgnoreHighlighterColors.SLASH),
AttributesDescriptor(IgnoreBundle.message("highlighter.syntax"), IgnoreHighlighterColors.SYNTAX),
AttributesDescriptor(IgnoreBundle.message("highlighter.value"), IgnoreHighlighterColors.VALUE),
AttributesDescriptor(IgnoreBundle.message("highlighter.unused"), IgnoreHighlighterColors.UNUSED)
)
/**
* Loads sample .gitignore file
*
* @return the text loaded from [.SAMPLE_GITIGNORE_PATH]
*
* @see .getDemoText
* @see .SAMPLE_GITIGNORE_PATH
* @see .SAMPLE_GITIGNORE
*/
private fun loadSampleGitignore() = Resources.getResourceContent(SAMPLE_GITIGNORE_PATH) ?: ""
}
override fun getIcon(): Icon? = null
override fun getHighlighter() = IgnoreHighlighter(null)
override fun getDemoText() = SAMPLE_GITIGNORE
override fun getAdditionalHighlightingTagToDescriptorMap(): Map<String, TextAttributesKey>? = null
override fun getAttributeDescriptors() = DESCRIPTORS
override fun getColorDescriptors(): Array<ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY
override fun getDisplayName(): String = DISPLAY_NAME
}
| mit | 2f008f4f9f0e19f39c0958457c6bb2ce | 47.169492 | 140 | 0.745954 | 5.434034 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/WifiSSIDActionType.kt | 1 | 628 | package ch.rmy.android.http_shortcuts.scripting.actions.types
import ch.rmy.android.http_shortcuts.scripting.ActionAlias
import ch.rmy.android.http_shortcuts.scripting.actions.ActionDTO
class WifiSSIDActionType : BaseActionType() {
override val type = TYPE
override fun fromDTO(actionDTO: ActionDTO) = WifiSSIDAction()
override fun getAlias() = ActionAlias(
functionName = FUNCTION_NAME,
parameters = 1,
functionNameAliases = setOf("getWifiSsid"),
)
companion object {
private const val TYPE = "wifi_ssid"
private const val FUNCTION_NAME = "getWifiSSID"
}
}
| mit | 87e1d024d99a4de6ced028227edfe92a | 27.545455 | 65 | 0.710191 | 4.15894 | false | false | false | false |
filipproch/reactor-android | library/src/androidTest/java/cz/filipproch/reactor/util/view/ReactorViewTestHelper.kt | 1 | 1304 | package cz.filipproch.reactor.util.view
import cz.filipproch.reactor.base.view.ReactorUiAction
import cz.filipproch.reactor.base.view.ReactorUiModel
import cz.filipproch.reactor.util.MethodCalled
import org.assertj.core.api.Java6Assertions
/**
* TODO: add description
*
* @author Filip Prochazka (@filipproch)
*/
class ReactorViewTestHelper {
/* State variables */
var methodCalls = mutableListOf<MethodCalled>()
val receivedUiModels = mutableListOf<ReactorUiModel>()
val receivedUiActions = mutableListOf<ReactorUiAction>()
fun methodCalled(methodName: String) {
methodCalls.add(MethodCalled(methodName, System.currentTimeMillis()))
}
fun uiModelReceived(model: ReactorUiModel) {
receivedUiModels.add(model)
}
fun uiActionReceived(action: ReactorUiAction) {
receivedUiActions.add(action)
}
fun assertMethodsCalledInOrder(vararg methodNames: String) {
Java6Assertions.assertThat(methodCalls)
.extracting<String> { it.methodName }
.containsExactly(*methodNames)
}
companion object {
val METHOD_EMITTERS_INIT = "onEmittersInit"
val METHOD_CONNECT_MODEL_STREAM = "onConnectModelStream"
val METHOD_CONNECT_ACTION_STREAM = "onConnectActionStream"
}
} | mit | a5d1d3c52363660549398c657b438957 | 27.369565 | 77 | 0.716258 | 4.450512 | false | false | false | false |
aosp-mirror/platform_frameworks_support | jetifier/jetifier/core/src/main/kotlin/com/android/tools/build/jetifier/core/config/Config.kt | 1 | 9473 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.build.jetifier.core.config
import com.android.tools.build.jetifier.core.PackageMap
import com.android.tools.build.jetifier.core.pom.DependencyVersionsMap
import com.android.tools.build.jetifier.core.pom.PomRewriteRule
import com.android.tools.build.jetifier.core.proguard.ProGuardType
import com.android.tools.build.jetifier.core.proguard.ProGuardTypesMap
import com.android.tools.build.jetifier.core.rule.RewriteRule
import com.android.tools.build.jetifier.core.rule.RewriteRulesMap
import com.android.tools.build.jetifier.core.type.JavaType
import com.android.tools.build.jetifier.core.type.PackageName
import com.android.tools.build.jetifier.core.type.TypesMap
import com.google.gson.annotations.SerializedName
import java.util.regex.Pattern
/**
* The main and only one configuration that is used by the tool and all its transformers.
*
* @param restrictToPackagePrefixes Package prefixes that limit the scope of the rewriting. In most
* cases the rules have priority over this. We use this mainly to determine if we are actually
* missing a rule in case we fail to rewrite.
* @param reversedRestrictToPackagePrefixes Same as [restrictToPackagePrefixes] but used when
* running in reversed mode.
* @param rulesMap Rules to scan support libraries to generate [TypesMap]
* @param slRule List of rules used when rewriting the support library itself in the reversed mode
* to ignore packages that don't need rewriting anymore.
* @param pomRewriteRules Rules to rewrite POM files
* @param typesMap Map of all java types and fields to be used to rewrite libraries.
* @param proGuardMap Proguard types map to be used for ProGuard files rewriting.
* @param versionsMap Pre-defined maps of versions to be substituted in pom dependency rules.
* @param packageMap Package map to be used to rewrite packages, used only during the support
* library rewrite.
*/
data class Config(
val restrictToPackagePrefixes: Set<String>,
val reversedRestrictToPackagePrefixes: Set<String>,
val rulesMap: RewriteRulesMap,
val slRules: List<RewriteRule>,
val pomRewriteRules: Set<PomRewriteRule>,
val typesMap: TypesMap,
val proGuardMap: ProGuardTypesMap,
val versionsMap: DependencyVersionsMap,
val packageMap: PackageMap = PackageMap(PackageMap.DEFAULT_RULES)
) {
init {
// Verify pom rules
val testSet = mutableSetOf<String>()
pomRewriteRules.forEach {
val raw = "${it.from.groupId}:${it.from.artifactId}"
if (!testSet.add(raw)) {
throw IllegalArgumentException("Artifact '$raw' is defined twice in pom rules!")
}
}
}
// Merges all packages prefixes into one regEx pattern
private val packagePrefixPattern = Pattern.compile(
"^(" + restrictToPackagePrefixes.map { "($it)" }.joinToString("|") + ").*$")
val restrictToPackagePrefixesWithDots: List<String> = restrictToPackagePrefixes
.map { it.replace("/", ".") }
companion object {
/** Path to the default config file located within the jar file. */
const val DEFAULT_CONFIG_RES_PATH = "/default.generated.config"
val EMPTY = fromOptional()
fun fromOptional(
restrictToPackagePrefixes: Set<String> = emptySet(),
reversedRestrictToPackagesPrefixes: Set<String> = emptySet(),
rulesMap: RewriteRulesMap = RewriteRulesMap.EMPTY,
slRules: List<RewriteRule> = emptyList(),
pomRewriteRules: Set<PomRewriteRule> = emptySet(),
typesMap: TypesMap = TypesMap.EMPTY,
proGuardMap: ProGuardTypesMap = ProGuardTypesMap.EMPTY,
versionsMap: DependencyVersionsMap = DependencyVersionsMap.EMPTY,
packageMap: PackageMap = PackageMap.EMPTY
): Config {
return Config(
restrictToPackagePrefixes = restrictToPackagePrefixes,
reversedRestrictToPackagePrefixes = reversedRestrictToPackagesPrefixes,
rulesMap = rulesMap,
slRules = slRules,
pomRewriteRules = pomRewriteRules,
typesMap = typesMap,
proGuardMap = proGuardMap,
versionsMap = versionsMap,
packageMap = packageMap
)
}
}
fun setNewMap(mappings: TypesMap): Config {
return Config(
restrictToPackagePrefixes = restrictToPackagePrefixes,
reversedRestrictToPackagePrefixes = reversedRestrictToPackagePrefixes,
rulesMap = rulesMap,
slRules = slRules,
pomRewriteRules = pomRewriteRules,
typesMap = mappings,
proGuardMap = proGuardMap,
versionsMap = versionsMap,
packageMap = packageMap
)
}
/**
* Returns whether the given type is eligible for rewrite.
*
* If not, the transformers should ignore it.
*/
fun isEligibleForRewrite(type: JavaType): Boolean {
if (!isEligibleForRewriteInternal(type.fullName)) {
return false
}
val isIgnored = rulesMap.runtimeIgnoreRules
.any { it.apply(type) == RewriteRule.TypeRewriteResult.IGNORED }
return !isIgnored
}
/**
* Returns whether the given ProGuard type reference is eligible for rewrite.
*
* Keep in mind that his has limited capabilities - mainly when * is used as a prefix. Rules
* like *.v7 are not matched by prefix support.v7. So don't rely on it and use
* the [ProGuardTypesMap] as first.
*/
fun isEligibleForRewrite(type: ProGuardType): Boolean {
if (!isEligibleForRewriteInternal(type.value)) {
return false
}
val isIgnored = rulesMap.runtimeIgnoreRules.any { it.doesThisIgnoreProGuard(type) }
return !isIgnored
}
fun isEligibleForRewrite(type: PackageName): Boolean {
if (!isEligibleForRewriteInternal(type.fullName + "/")) {
return false
}
val javaType = JavaType(type.fullName + "/")
val isIgnored = rulesMap.runtimeIgnoreRules
.any { it.apply(javaType) == RewriteRule.TypeRewriteResult.IGNORED }
return !isIgnored
}
private fun isEligibleForRewriteInternal(type: String): Boolean {
if (restrictToPackagePrefixes.isEmpty()) {
return false
}
return packagePrefixPattern.matcher(type).matches()
}
/** Returns JSON data model of this class */
fun toJson(): JsonData {
return JsonData(
restrictToPackagePrefixes.toList(),
reversedRestrictToPackagePrefixes.toList(),
rulesMap.toJson().rules.toList(),
slRules.map { it.toJson() }.toList(),
pomRewriteRules.map { it.toJson() }.toList(),
versionsMap.data,
typesMap.toJson(),
proGuardMap.toJson()
)
}
/**
* JSON data model for [Config].
*/
data class JsonData(
@SerializedName("restrictToPackagePrefixes")
val restrictToPackages: List<String?>,
@SerializedName("reversedRestrictToPackagePrefixes")
val reversedRestrictToPackages: List<String?>,
@SerializedName("rules")
val rules: List<RewriteRule.JsonData?>?,
@SerializedName("slRules")
val slRules: List<RewriteRule.JsonData?>?,
@SerializedName("pomRules")
val pomRules: List<PomRewriteRule.JsonData?>,
@SerializedName("versions")
val versions: Map<String, Map<String, String>>? = null,
@SerializedName("map")
val mappings: TypesMap.JsonData? = null,
@SerializedName("proGuardMap")
val proGuardMap: ProGuardTypesMap.JsonData? = null
) {
/** Creates instance of [Config] */
fun toConfig(): Config {
return Config(
restrictToPackagePrefixes = restrictToPackages.filterNotNull().toSet(),
reversedRestrictToPackagePrefixes = reversedRestrictToPackages
.filterNotNull().toSet(),
rulesMap = rules
?.let { RewriteRulesMap(it.filterNotNull().map { it.toRule() }.toList()) }
?: RewriteRulesMap.EMPTY,
slRules = slRules
?.let { it.filterNotNull().map { it.toRule() }.toList() }
?: emptyList(),
pomRewriteRules = pomRules.filterNotNull().map { it.toRule() }.toSet(),
versionsMap = versions
?.let { DependencyVersionsMap(versions) }
?: DependencyVersionsMap.EMPTY,
typesMap = mappings?.toMappings() ?: TypesMap.EMPTY,
proGuardMap = proGuardMap?.toMappings() ?: ProGuardTypesMap.EMPTY
)
}
}
}
| apache-2.0 | 324cf1caf0935166b7a7b5b31075362f | 38.970464 | 99 | 0.655547 | 4.80619 | false | true | false | false |
seventhroot/elysium | bukkit/rpk-item-quality-bukkit/src/main/kotlin/com/rpkit/itemquality/bukkit/command/itemquality/ItemQualitySetCommand.kt | 1 | 2472 | /*
* Copyright 2019 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.itemquality.bukkit.command.itemquality
import com.rpkit.itemquality.bukkit.RPKItemQualityBukkit
import com.rpkit.itemquality.bukkit.itemquality.RPKItemQualityProvider
import org.bukkit.Material
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
class ItemQualitySetCommand(private val plugin: RPKItemQualityBukkit): CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (sender !is Player) {
sender.sendMessage(plugin.messages["not-from-console"])
return true
}
if (!sender.hasPermission("rpkit.itemquality.command.itemquality.set")) {
sender.sendMessage(plugin.messages["no-permission-itemquality-set"])
return true
}
if (args.isEmpty()) {
sender.sendMessage(plugin.messages["itemquality-set-usage"])
return true
}
val itemQualityProvider = plugin.core.serviceManager.getServiceProvider(RPKItemQualityProvider::class)
val itemQuality = itemQualityProvider.getItemQuality(args.joinToString(" "))
if (itemQuality == null) {
sender.sendMessage(plugin.messages["itemquality-set-invalid-quality"])
return true
}
val item = sender.inventory.itemInMainHand
if (item.type == Material.AIR) {
sender.sendMessage(plugin.messages["itemquality-set-invalid-item-none"])
return true
}
itemQualityProvider.setItemQuality(item, itemQuality)
sender.inventory.setItemInMainHand(item)
sender.sendMessage(plugin.messages["itemquality-set-valid", mapOf(
Pair("quality", itemQuality.name)
)])
return true
}
} | apache-2.0 | e7946596a98317bd7803ae45e591b19e | 38.887097 | 118 | 0.700647 | 4.672968 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/database/table/RPKMinecraftProfileTable.kt | 1 | 6465 | /*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.players.bukkit.database.table
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.players.bukkit.RPKPlayersBukkit
import com.rpkit.players.bukkit.database.jooq.rpkit.Tables.RPKIT_MINECRAFT_PROFILE
import com.rpkit.players.bukkit.profile.*
import org.bukkit.OfflinePlayer
import org.ehcache.config.builders.CacheConfigurationBuilder
import org.ehcache.config.builders.ResourcePoolsBuilder
import org.jooq.impl.DSL.constraint
import org.jooq.impl.SQLDataType
import java.util.*
class RPKMinecraftProfileTable(database: Database, private val plugin: RPKPlayersBukkit): Table<RPKMinecraftProfile>(database, RPKMinecraftProfile::class) {
private val cache = if (plugin.config.getBoolean("caching.rpkit_minecraft_profile.id.enabled")) {
database.cacheManager.createCache("rpk-players-bukkit.rpkit_minecraft_profile.id",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKMinecraftProfile::class.java,
ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_minecraft_profile.id.size"))))
} else {
null
}
override fun create() {
database.create
.createTableIfNotExists(RPKIT_MINECRAFT_PROFILE)
.column(RPKIT_MINECRAFT_PROFILE.ID, SQLDataType.INTEGER.identity(true))
.column(RPKIT_MINECRAFT_PROFILE.PROFILE_ID, SQLDataType.INTEGER)
.column(RPKIT_MINECRAFT_PROFILE.MINECRAFT_UUID, SQLDataType.VARCHAR(36))
.constraints(
constraint("pk_rpkit_minecraft_profile").primaryKey(RPKIT_MINECRAFT_PROFILE.ID)
)
.execute()
}
override fun applyMigrations() {
if (database.getTableVersion(this) == null) {
database.setTableVersion(this, "1.3.0")
}
}
override fun insert(entity: RPKMinecraftProfile): Int {
val profile = entity.profile
database.create
.insertInto(
RPKIT_MINECRAFT_PROFILE,
RPKIT_MINECRAFT_PROFILE.PROFILE_ID,
RPKIT_MINECRAFT_PROFILE.MINECRAFT_UUID
)
.values(
if (profile is RPKProfile) {
profile.id
} else {
null
},
entity.minecraftUUID.toString()
)
.execute()
val id = database.create.lastID().toInt()
entity.id = id
cache?.put(id, entity)
return id
}
override fun update(entity: RPKMinecraftProfile) {
val profile = entity.profile
database.create
.update(RPKIT_MINECRAFT_PROFILE)
.set(
RPKIT_MINECRAFT_PROFILE.PROFILE_ID,
if (profile is RPKProfile) {
profile.id
} else {
null
}
)
.set(RPKIT_MINECRAFT_PROFILE.MINECRAFT_UUID, entity.minecraftUUID.toString())
.where(RPKIT_MINECRAFT_PROFILE.ID.eq(entity.id))
.execute()
cache?.put(entity.id, entity)
}
override fun get(id: Int): RPKMinecraftProfile? {
if (cache?.containsKey(id) == true) {
return cache.get(id)
} else {
val result = database.create
.select(
RPKIT_MINECRAFT_PROFILE.PROFILE_ID,
RPKIT_MINECRAFT_PROFILE.MINECRAFT_UUID
)
.from(RPKIT_MINECRAFT_PROFILE)
.where(RPKIT_MINECRAFT_PROFILE.ID.eq(id))
.fetchOne() ?: return null
val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class)
val profileId = result.get(RPKIT_MINECRAFT_PROFILE.PROFILE_ID)
val profile = if (profileId != null) {
profileProvider.getProfile(profileId)
} else {
null
} ?: RPKThinProfileImpl(
plugin.server.getOfflinePlayer(
UUID.fromString(result.get(RPKIT_MINECRAFT_PROFILE.MINECRAFT_UUID))
).name ?: "Unknown Minecraft user"
)
val minecraftProfile = RPKMinecraftProfileImpl(
id,
profile,
UUID.fromString(result.get(RPKIT_MINECRAFT_PROFILE.MINECRAFT_UUID))
)
cache?.put(id, minecraftProfile)
return minecraftProfile
}
}
fun get(profile: RPKProfile): List<RPKMinecraftProfile> {
val results = database.create
.select(RPKIT_MINECRAFT_PROFILE.ID)
.from(RPKIT_MINECRAFT_PROFILE)
.where(RPKIT_MINECRAFT_PROFILE.PROFILE_ID.eq(profile.id))
.fetch()
return results.map { result ->
get(result.get(RPKIT_MINECRAFT_PROFILE.ID))
}.filterNotNull()
}
fun get(player: OfflinePlayer): RPKMinecraftProfile? {
val result = database.create
.select(RPKIT_MINECRAFT_PROFILE.ID)
.from(RPKIT_MINECRAFT_PROFILE)
.where(RPKIT_MINECRAFT_PROFILE.MINECRAFT_UUID.eq(player.uniqueId.toString()))
.fetchOne() ?: return null
return get(result.get(RPKIT_MINECRAFT_PROFILE.ID))
}
override fun delete(entity: RPKMinecraftProfile) {
database.create
.deleteFrom(RPKIT_MINECRAFT_PROFILE)
.where(RPKIT_MINECRAFT_PROFILE.ID.eq(entity.id))
.execute()
cache?.remove(entity.id)
}
} | apache-2.0 | ccaa3bfa79a4d6929e4255eace7c667c | 39.161491 | 156 | 0.585305 | 4.98074 | false | false | false | false |
blastrock/kaqui | app/src/main/java/org/kaqui/settings/ItemSelectionAdapter.kt | 1 | 3341 | package org.kaqui.settings
import android.content.Context
import android.view.Gravity
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import org.jetbrains.anko.*
import org.kaqui.*
import org.kaqui.model.LearningDbView
import org.kaqui.model.description
import org.kaqui.model.text
class ItemSelectionAdapter(private val view: LearningDbView, private val context: Context, private val statsFragment: StatsFragment) : RecyclerView.Adapter<ItemSelectionViewHolder>() {
private val ankoContext = AnkoContext.createReusable(context, this)
private var ids: List<Int> = listOf()
fun setup() {
ids = view.getAllItems()
notifyDataSetChanged()
}
fun searchFor(text: String) {
ids = view.search(text)
notifyDataSetChanged()
}
fun clearAll() {
ids = listOf()
notifyDataSetChanged()
}
override fun getItemCount(): Int = ids.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemSelectionViewHolder {
val selectionItem = ankoContext.apply {
verticalLayout {
linearLayout {
orientation = LinearLayout.HORIZONTAL
verticalPadding = dip(6)
horizontalPadding = dip(8)
checkBox {
id = R.id.item_checkbox
scaleX = 1.5f
scaleY = 1.5f
}.lparams(width = wrapContent, height = wrapContent) {
gravity = Gravity.CENTER
margin = dip(8)
}
textView {
id = R.id.item_text
typeface = TypefaceManager.getTypeface(context)
textSize = 25f
textAlignment = TextView.TEXT_ALIGNMENT_CENTER
gravity = Gravity.CENTER
}.lparams(width = sp(35), height = sp(35)) {
margin = dip(8)
gravity = Gravity.CENTER
}
textView {
id = R.id.item_description
typeface = TypefaceManager.getTypeface(context)
}.lparams(width = matchParent, height = wrapContent, weight = 1f) {
gravity = Gravity.CENTER_VERTICAL
horizontalMargin = dip(8)
}
}.lparams(width = matchParent, height = wrapContent)
separator(context)
}
}.view
return ItemSelectionViewHolder(view, selectionItem, statsFragment)
}
override fun onBindViewHolder(holder: ItemSelectionViewHolder, position: Int) {
val item = view.getItem(ids[position])
holder.itemId = item.id
holder.enabled.isChecked = item.enabled
holder.itemText.text = item.text
if (item.text.length > 1)
(holder.itemText.layoutParams as LinearLayout.LayoutParams).width = LinearLayout.LayoutParams.WRAP_CONTENT
holder.itemText.background = getColoredCircle(context, getColorFromScore(item.shortScore))
holder.itemDescription.text = item.description
}
}
| mit | c8202bc3131e518273dc876780a13b28 | 36.539326 | 184 | 0.579168 | 5.303175 | false | false | false | false |
commonsguy/cwac-saferoom | demo/src/main/java/com/commonsware/android/auth/note/RxPassphrase.kt | 1 | 5784 | /***
* Copyright (c) 2018 CommonsWare, LLC
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
* by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
* OF ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
* Covered in detail in the book _The Busy Coder's Guide to Android Development_
* https://commonsware.com/Android
*/
package com.commonsware.android.auth.note
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Log
import java.io.File
import java.nio.ByteBuffer
import java.nio.CharBuffer
import java.nio.charset.Charset
import java.security.KeyStore
import java.security.SecureRandom
import java.util.Arrays
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.IvParameterSpec
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.ObservableOnSubscribe
import okio.BufferedSink
import okio.BufferedSource
import okio.Okio
private const val BASE36_SYMBOLS = "abcdefghijklmnopqrstuvwxyz0123456789"
private const val KEYSTORE = "AndroidKeyStore"
object RxPassphrase {
private val BLOCK_SIZE: Int
init {
var blockSize = -1
try {
blockSize = Cipher.getInstance("AES/CBC/PKCS7Padding").blockSize
} catch (e: Exception) {
Log.e("RxKeyBodega", "Could not get AES/CBC/PKCS7Padding cipher", e)
}
BLOCK_SIZE = blockSize
}
internal operator fun get(
encryptedFile: File,
keyName: String,
timeout: Int
): Observable<CharArray> {
return Observable.create(
RxPassphrase.PassphraseObservable(
encryptedFile,
keyName,
timeout
)
)
}
class PassphraseObservable(
private val encryptedFile: File,
private val keyName: String,
private val timeout: Int
) : ObservableOnSubscribe<CharArray> {
@Throws(Exception::class)
override fun subscribe(emitter: ObservableEmitter<CharArray>) {
val ks = KeyStore.getInstance(KEYSTORE)
ks.load(null)
if (encryptedFile.exists()) {
load(ks, emitter)
} else {
create(ks, emitter)
}
}
@Throws(Exception::class)
private fun create(ks: KeyStore, emitter: ObservableEmitter<CharArray>) {
val rand = SecureRandom()
val passphrase = CharArray(128)
for (i in passphrase.indices) {
passphrase[i] = BASE36_SYMBOLS[rand.nextInt(BASE36_SYMBOLS.length)]
}
createKey(ks, keyName, timeout)
val secretKey = ks.getKey(keyName, null) as SecretKey
val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
val iv = ByteArray(BLOCK_SIZE)
rand.nextBytes(iv)
val ivParams = IvParameterSpec(iv)
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParams)
val toEncrypt = toBytes(passphrase)
val encrypted = cipher.doFinal(toEncrypt)
val sink = Okio.buffer(Okio.sink(encryptedFile))
sink.write(iv)
sink.write(encrypted)
sink.close()
emitter.onNext(passphrase)
}
@Throws(Exception::class)
private fun createKey(ks: KeyStore, keyName: String, timeout: Int) {
val entry = ks.getEntry(keyName, null)
if (entry == null) {
val spec = KeyGenParameterSpec.Builder(
keyName,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
.setUserAuthenticationRequired(true)
.setUserAuthenticationValidityDurationSeconds(timeout)
.setRandomizedEncryptionRequired(false)
.build()
val keygen =
KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE)
keygen.init(spec)
keygen.generateKey()
}
}
@Throws(Exception::class)
private fun load(ks: KeyStore, emitter: ObservableEmitter<CharArray>) {
val source = Okio.buffer(Okio.source(encryptedFile))
val iv = source.readByteArray(BLOCK_SIZE.toLong())
val encrypted = source.readByteArray()
source.close()
val secretKey = ks.getKey(keyName, null) as SecretKey
val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
cipher.init(Cipher.DECRYPT_MODE, secretKey, IvParameterSpec(iv))
val decrypted = cipher.doFinal(encrypted)
val passphrase = toChars(decrypted)
emitter.onNext(passphrase)
}
}
// based on https://stackoverflow.com/a/9670279/115145
internal fun toBytes(chars: CharArray): ByteArray {
val charBuffer = CharBuffer.wrap(chars)
val byteBuffer = Charset.forName("UTF-8").encode(charBuffer)
val bytes = Arrays.copyOfRange(
byteBuffer.array(), byteBuffer.position(),
byteBuffer.limit()
)
// Arrays.fill(charBuffer.array(), '\u0000'); // clear the cleartext
Arrays.fill(byteBuffer.array(), 0.toByte()) // clear the ciphertext
return bytes
}
internal fun toChars(bytes: ByteArray): CharArray {
val charset = Charset.forName("UTF-8")
val byteBuffer = ByteBuffer.wrap(bytes)
val charBuffer = charset.decode(byteBuffer)
val chars = Arrays.copyOf(charBuffer.array(), charBuffer.limit())
Arrays.fill(charBuffer.array(), '\u0000') // clear the cleartext
Arrays.fill(byteBuffer.array(), 0.toByte()) // clear the ciphertext
return chars
}
}
| apache-2.0 | 0dcbb402c6b3c21dc041f4b67d3d01c6 | 28.814433 | 80 | 0.698824 | 4.234261 | false | false | false | false |
RocketChat/Rocket.Chat.Android | app/src/main/java/chat/rocket/android/server/presentation/CheckServerPresenter.kt | 2 | 24170 | package chat.rocket.android.server.presentation
import chat.rocket.android.BuildConfig
import chat.rocket.android.authentication.server.presentation.VersionCheckView
import chat.rocket.android.core.lifecycle.CancelStrategy
import chat.rocket.android.db.DatabaseManager
import chat.rocket.android.db.DatabaseManagerFactory
import chat.rocket.android.helper.OauthHelper
import chat.rocket.android.server.domain.GetSettingsInteractor
import chat.rocket.android.server.domain.PublicSettings
import chat.rocket.android.server.domain.RefreshSettingsInteractor
import chat.rocket.android.server.domain.casLoginUrl
import chat.rocket.android.server.domain.gitlabUrl
import chat.rocket.android.server.domain.isCasAuthenticationEnabled
import chat.rocket.android.server.domain.isFacebookAuthenticationEnabled
import chat.rocket.android.server.domain.isGithubAuthenticationEnabled
import chat.rocket.android.server.domain.isGitlabAuthenticationEnabled
import chat.rocket.android.server.domain.isGoogleAuthenticationEnabled
import chat.rocket.android.server.domain.isLinkedinAuthenticationEnabled
import chat.rocket.android.server.domain.isLoginFormEnabled
import chat.rocket.android.server.domain.isRegistrationEnabledForNewUsers
import chat.rocket.android.server.domain.isWordpressAuthenticationEnabled
import chat.rocket.android.server.domain.wordpressUrl
import chat.rocket.android.server.infrastructure.ConnectionManager
import chat.rocket.android.server.infrastructure.ConnectionManagerFactory
import chat.rocket.android.server.infrastructure.RocketChatClientFactory
import chat.rocket.android.util.VersionInfo
import chat.rocket.android.util.extension.launchUI
import chat.rocket.android.util.extensions.casUrl
import chat.rocket.android.util.extensions.generateRandomString
import chat.rocket.android.util.extensions.parseColor
import chat.rocket.android.util.extensions.samlUrl
import chat.rocket.android.util.retryIO
import chat.rocket.common.RocketChatException
import chat.rocket.common.RocketChatInvalidProtocolException
import chat.rocket.common.model.ServerInfo
import chat.rocket.core.RocketChatClient
import chat.rocket.core.internal.rest.serverInfo
import chat.rocket.core.internal.rest.settingsOauth
import kotlinx.coroutines.Job
import timber.log.Timber
private const val SERVICE_NAME_FACEBOOK = "facebook"
private const val SERVICE_NAME_GITHUB = "github"
private const val SERVICE_NAME_GOOGLE = "google"
private const val SERVICE_NAME_LINKEDIN = "linkedin"
private const val SERVICE_NAME_GILAB = "gitlab"
private const val SERVICE_NAME_WORDPRESS = "wordpress"
abstract class CheckServerPresenter constructor(
private val strategy: CancelStrategy,
private val factory: RocketChatClientFactory,
private val settingsInteractor: GetSettingsInteractor? = null,
private val managerFactory: ConnectionManagerFactory? = null,
private val dbManagerFactory: DatabaseManagerFactory? = null,
private val versionCheckView: VersionCheckView? = null,
private val refreshSettingsInteractor: RefreshSettingsInteractor? = null
) {
private lateinit var currentServer: String
private var client: RocketChatClient? = null
private lateinit var settings: PublicSettings
private var connectionManager: ConnectionManager? = null
private var dbManager: DatabaseManager? = null
internal var state: String = ""
internal var facebookOauthUrl: String? = null
internal var githubOauthUrl: String? = null
internal var googleOauthUrl: String? = null
internal var linkedinOauthUrl: String? = null
internal var gitlabOauthUrl: String? = null
internal var wordpressOauthUrl: String? = null
internal var casLoginUrl: String? = null
internal var casToken: String? = null
internal var casServiceName: String? = null
internal var casServiceNameTextColor: Int = 0
internal var casServiceButtonColor: Int = 0
internal var customOauthUrl: String? = null
internal var customOauthServiceName: String? = null
internal var customOauthServiceNameTextColor: Int = 0
internal var customOauthServiceButtonColor: Int = 0
internal var samlUrl: String? = null
internal var samlToken: String? = null
internal var samlServiceName: String? = null
internal var samlServiceNameTextColor: Int = 0
internal var samlServiceButtonColor: Int = 0
internal var totalSocialAccountsEnabled = 0
internal var isLoginFormEnabled = false
internal var isNewAccountCreationEnabled = false
internal fun setupConnectionInfo(serverUrl: String) {
currentServer = serverUrl
client = factory.get(serverUrl)
managerFactory?.create(serverUrl)?.let {
connectionManager = it
}
dbManagerFactory?.create(serverUrl)?.let {
dbManager = it
}
}
internal suspend fun refreshServerAccounts() {
refreshSettingsInteractor?.refresh(currentServer)
settingsInteractor?.get(currentServer)?.let {
settings = it
}
state = ""
facebookOauthUrl = null
githubOauthUrl = null
googleOauthUrl = null
linkedinOauthUrl = null
gitlabOauthUrl = null
wordpressOauthUrl = null
casLoginUrl = null
casToken = null
casServiceName = null
casServiceNameTextColor = 0
casServiceButtonColor = 0
customOauthUrl = null
customOauthServiceName = null
customOauthServiceNameTextColor = 0
customOauthServiceButtonColor= 0
samlUrl = null
samlToken = null
samlServiceName = null
samlServiceNameTextColor = 0
samlServiceButtonColor = 0
totalSocialAccountsEnabled = 0
isLoginFormEnabled = false
isNewAccountCreationEnabled = false
}
internal fun checkServerInfo(serverUrl: String): Job {
return launchUI(strategy) {
try {
currentServer = serverUrl
retryIO(description = "serverInfo", times = 5) {
client?.serverInfo()?.let { serverInfo ->
if (serverInfo.redirected) {
versionCheckView?.updateServerUrl(serverInfo.url)
}
when (val version = checkServerVersion(serverInfo)) {
is Version.VersionOk -> {
Timber.i("Your version is nice! (Requires: 0.62.0, Yours: ${version.version})")
versionCheckView?.versionOk()
}
is Version.RecommendedVersionWarning -> {
Timber.i("Your server ${version.version} is bellow recommended version ${BuildConfig.RECOMMENDED_SERVER_VERSION}")
versionCheckView?.alertNotRecommendedVersion()
}
is Version.OutOfDateError -> {
Timber.i("Oops. Looks like your server ${version.version} is out-of-date! Minimum server version required ${BuildConfig.REQUIRED_SERVER_VERSION}!")
versionCheckView?.blockAndAlertNotRequiredVersion()
}
}
}
}
} catch (ex: Exception) {
Timber.d(ex, "Error getting server info")
when (ex) {
is RocketChatInvalidProtocolException -> versionCheckView?.errorInvalidProtocol()
else -> versionCheckView?.errorCheckingServerVersion()
}
}
}
}
internal suspend fun checkEnabledAccounts(serverUrl: String) {
try {
retryIO("settingsOauth()") {
client?.settingsOauth()?.services?.let { services ->
if (services.isNotEmpty()) {
state = OauthHelper.getState()
checkEnabledOauthAccounts(services, serverUrl)
checkEnabledCasAccounts(services, serverUrl)
checkEnabledCustomOauthAccounts(services, serverUrl)
checkEnabledSamlAccounts(services, serverUrl)
}
}
}
} catch (exception: RocketChatException) {
Timber.e(exception)
}
}
private fun checkEnabledOauthAccounts(services: List<Map<String,Any>>, serverUrl: String) {
if (settings.isFacebookAuthenticationEnabled()) {
getServiceMap(services, SERVICE_NAME_FACEBOOK)?.let { serviceMap ->
getOauthClientId(serviceMap)?.let { clientId ->
facebookOauthUrl =
OauthHelper.getFacebookOauthUrl(clientId, serverUrl, state)
totalSocialAccountsEnabled++
}
}
}
if (settings.isGithubAuthenticationEnabled()) {
getServiceMap(services, SERVICE_NAME_GITHUB)?.let { serviceMap ->
getOauthClientId(serviceMap)?.let { clientId ->
githubOauthUrl =
OauthHelper.getGithubOauthUrl(clientId, state)
totalSocialAccountsEnabled++
}
}
}
if (settings.isGoogleAuthenticationEnabled()) {
getServiceMap(services, SERVICE_NAME_GOOGLE)?.let { serviceMap ->
getOauthClientId(serviceMap)?.let { clientId ->
googleOauthUrl =
OauthHelper.getGoogleOauthUrl(clientId, serverUrl, state)
totalSocialAccountsEnabled++
}
}
}
if (settings.isLinkedinAuthenticationEnabled()) {
getServiceMap(services, SERVICE_NAME_LINKEDIN)?.let { serviceMap ->
getOauthClientId(serviceMap)?.let { clientId ->
linkedinOauthUrl =
OauthHelper.getLinkedinOauthUrl(clientId, serverUrl, state)
totalSocialAccountsEnabled++
}
}
}
if (settings.isGitlabAuthenticationEnabled()) {
getServiceMap(services, SERVICE_NAME_GILAB)?.let { serviceMap ->
getOauthClientId(serviceMap)?.let { clientId ->
gitlabOauthUrl = if (settings.gitlabUrl() != null) {
OauthHelper.getGitlabOauthUrl(
host = settings.gitlabUrl(),
clientId = clientId,
serverUrl = serverUrl,
state = state
)
} else {
OauthHelper.getGitlabOauthUrl(
clientId = clientId,
serverUrl = serverUrl,
state = state
)
}
totalSocialAccountsEnabled++
}
}
}
if (settings.isWordpressAuthenticationEnabled()) {
getServiceMap(services, SERVICE_NAME_WORDPRESS)?.let { serviceMap ->
getOauthClientId(serviceMap)?.let { clientId ->
wordpressOauthUrl =
if (settings.wordpressUrl().isNullOrEmpty()) {
OauthHelper.getWordpressComOauthUrl(
clientId,
serverUrl,
state
)
} else {
OauthHelper.getWordpressCustomOauthUrl(
getCustomOauthHost(serviceMap)
?: "https://public-api.wordpress.com",
getCustomOauthAuthorizePath(serviceMap)
?: "/oauth/authorize",
clientId,
serverUrl,
SERVICE_NAME_WORDPRESS,
state,
getCustomOauthScope(serviceMap) ?: "openid"
)
}
totalSocialAccountsEnabled++
}
}
}
}
private fun checkEnabledCasAccounts(services: List<Map<String,Any>>, serverUrl: String) {
if (settings.isCasAuthenticationEnabled()) {
casToken = generateRandomString(17)
casLoginUrl = settings.casLoginUrl().casUrl(serverUrl, casToken.toString())
getCasServices(services).let {
for (serviceMap in it) {
casServiceName = getServiceName(serviceMap)
val serviceNameTextColor = getServiceNameColor(serviceMap)
val serviceButtonColor = getServiceButtonColor(serviceMap)
if (casServiceName != null &&
serviceNameTextColor != null &&
serviceButtonColor != null
) {
casServiceNameTextColor = serviceNameTextColor
casServiceButtonColor = serviceButtonColor
totalSocialAccountsEnabled++
}
}
}
}
}
private fun checkEnabledCustomOauthAccounts(services: List<Map<String,Any>>, serverUrl: String) {
getCustomOauthServices(services).let {
for (serviceMap in it) {
customOauthServiceName = getCustomOauthServiceName(serviceMap)
val host = getCustomOauthHost(serviceMap)
val authorizePath = getCustomOauthAuthorizePath(serviceMap)
val clientId = getOauthClientId(serviceMap)
val scope = getCustomOauthScope(serviceMap)
val serviceNameTextColor =
getServiceNameColor(serviceMap)
val serviceButtonColor = getServiceButtonColor(serviceMap)
if (customOauthServiceName != null &&
host != null &&
authorizePath != null &&
clientId != null &&
scope != null &&
serviceNameTextColor != null &&
serviceButtonColor != null
) {
customOauthUrl = OauthHelper.getCustomOauthUrl(
host,
authorizePath,
clientId,
serverUrl,
customOauthServiceName.toString(),
state,
scope
)
customOauthServiceNameTextColor = serviceNameTextColor
customOauthServiceButtonColor = serviceButtonColor
totalSocialAccountsEnabled++
}
}
}
}
private fun checkEnabledSamlAccounts(services: List<Map<String,Any>>, serverUrl: String) {
getSamlServices(services).let {
samlToken = generateRandomString(17)
for (serviceMap in it) {
val provider = getSamlProvider(serviceMap)
samlServiceName = getServiceName(serviceMap)
val serviceNameTextColor =
getServiceNameColor(serviceMap)
val serviceButtonColor = getServiceButtonColor(serviceMap)
if (provider != null &&
samlServiceName != null &&
serviceNameTextColor != null &&
serviceButtonColor != null
) {
samlUrl = serverUrl.samlUrl(provider, samlToken.toString())
samlServiceNameTextColor = serviceNameTextColor
samlServiceButtonColor = serviceButtonColor
totalSocialAccountsEnabled++
}
}
}
}
internal fun checkIfLoginFormIsEnabled() {
if (settings.isLoginFormEnabled()) {
isLoginFormEnabled = true
}
}
internal fun checkIfCreateNewAccountIsEnabled() {
if (settings.isRegistrationEnabledForNewUsers() && settings.isLoginFormEnabled()) {
isNewAccountCreationEnabled = true
}
}
/** Returns an OAuth service map given a [serviceName].
*
* @param listMap The list of [Map] to get the service from.
* @param serviceName The service name to get in the [listMap]
* @return The OAuth service map or null otherwise.
*/
private fun getServiceMap(
listMap: List<Map<String, Any>>,
serviceName: String
): Map<String, Any>? = listMap.find { map -> map.containsValue(serviceName) }
/**
* Returns the OAuth client ID of a [serviceMap].
* REMARK: This function works for common OAuth providers (Google, Facebook, GitHub and so on)
* as well as custom OAuth.
*
* @param serviceMap The service map to get the OAuth client ID.
* @return The OAuth client ID or null otherwise.
*/
private fun getOauthClientId(serviceMap: Map<String, Any>): String? =
serviceMap["clientId"] as? String ?: serviceMap["appId"] as? String
/**
* Returns a custom OAuth service list.
*
* @return A custom OAuth service list, otherwise an empty list if there is no custom OAuth service.
*/
private fun getCustomOauthServices(listMap: List<Map<String, Any>>): List<Map<String, Any>> =
listMap.filter { map -> map["custom"] == true }
/** Returns the custom OAuth service host.
*
* @param serviceMap The service map to get the custom OAuth service host.
* @return The custom OAuth service host, otherwise null.
*/
private fun getCustomOauthHost(serviceMap: Map<String, Any>): String? =
serviceMap["serverURL"] as? String
/** Returns the custom OAuth service authorize path.
*
* @param serviceMap The service map to get the custom OAuth service authorize path.
* @return The custom OAuth service authorize path, otherwise null.
*/
private fun getCustomOauthAuthorizePath(serviceMap: Map<String, Any>): String? =
serviceMap["authorizePath"] as? String
/** Returns the custom OAuth service scope.
*
* @param serviceMap The service map to get the custom OAuth service scope.
* @return The custom OAuth service scope, otherwise null.
*/
private fun getCustomOauthScope(serviceMap: Map<String, Any>): String? =
serviceMap["scope"] as? String
/** Returns the text of the custom OAuth service.
*
* @param serviceMap The service map to get the text of the custom OAuth service.
* @return The text of the custom OAuth service, otherwise null.
*/
private fun getCustomOauthServiceName(serviceMap: Map<String, Any>): String? =
serviceMap["service"] as? String
/**
* Returns a CAS service list.
*
* @return A CAS service list, otherwise an empty list if there is no CAS service.
*/
private fun getCasServices(listMap: List<Map<String, Any>>): List<Map<String, Any>> =
listMap.filter { map -> map["service"] == "cas" }
/**
* Returns a SAML OAuth service list.
*
* @return A SAML service list, otherwise an empty list if there is no SAML OAuth service.
*/
private fun getSamlServices(listMap: List<Map<String, Any>>): List<Map<String, Any>> =
listMap.filter { map -> map["service"] == "saml" }
/**
* Returns the SAML provider.
*
* @param serviceMap The service map to provider from.
* @return The SAML provider, otherwise null.
*/
private fun getSamlProvider(serviceMap: Map<String, Any>): String? =
(serviceMap["clientConfig"] as Map<*, *>)["provider"] as? String
/**
* Returns the text of the SAML service.
* REMARK: This can be used SAML or CAS.
*
* @param serviceMap The service map to get the text of the SAML service.
* @return The text of the SAML service, otherwise null.
*/
private fun getServiceName(serviceMap: Map<String, Any>): String? =
serviceMap["buttonLabelText"] as? String
/**
* Returns the text color of the service name.
* REMARK: This can be used for custom OAuth, SAML or CAS.
*
* @param serviceMap The service map to get the text color from.
* @return The text color of the service (custom OAuth or SAML), otherwise null.
*/
private fun getServiceNameColor(serviceMap: Map<String, Any>): Int? =
(serviceMap["buttonLabelColor"] as? String)?.parseColor()
/**
* Returns the button color of the service name.
* REMARK: This can be used for custom OAuth, SAML or CAS.
*
* @param serviceMap The service map to get the button color from.
* @return The button color of the service (custom OAuth or SAML), otherwise null.
*/
private fun getServiceButtonColor(serviceMap: Map<String, Any>): Int? =
(serviceMap["buttonColor"] as? String)?.parseColor()
private fun checkServerVersion(serverInfo: ServerInfo): Version {
val thisServerVersion = serverInfo.version
val isRequiredVersion = isRequiredServerVersion(thisServerVersion)
val isRecommendedVersion = isRecommendedServerVersion(thisServerVersion)
return if (isRequiredVersion) {
if (isRecommendedVersion) {
Timber.i("Your version is nice! (Requires: 0.62.0, Yours: $thisServerVersion)")
Version.VersionOk(thisServerVersion)
} else {
Version.RecommendedVersionWarning(thisServerVersion)
}
} else {
Version.OutOfDateError(thisServerVersion)
}
}
private fun isRequiredServerVersion(version: String): Boolean {
return isMinimumVersion(version, getVersionDistilled(BuildConfig.REQUIRED_SERVER_VERSION))
}
private fun isRecommendedServerVersion(version: String): Boolean {
return isMinimumVersion(
version,
getVersionDistilled(BuildConfig.RECOMMENDED_SERVER_VERSION)
)
}
private fun isMinimumVersion(version: String, required: VersionInfo): Boolean {
val thisVersion = getVersionDistilled(version)
with(thisVersion) {
if (major < required.major) {
return false
} else if (major > required.major) {
return true
}
if (minor < required.minor) {
return false
} else if (minor > required.minor) {
return true
}
return update >= required.update
}
}
private fun getVersionDistilled(version: String): VersionInfo {
var split = version.split("-")
if (split.isEmpty()) {
return VersionInfo(0, 0, 0, null, "0.0.0")
}
val ver = split[0]
var release: String? = null
if (split.size > 1) {
release = split[1]
}
split = ver.split(".")
val major = getVersionNumber(split, 0)
val minor = getVersionNumber(split, 1)
val update = getVersionNumber(split, 2)
return VersionInfo(
major = major,
minor = minor,
update = update,
release = release,
full = version
)
}
private fun getVersionNumber(split: List<String>, index: Int): Int {
return try {
split.getOrNull(index)?.toInt() ?: 0
} catch (ex: NumberFormatException) {
0
}
}
sealed class Version(val version: String) {
data class VersionOk(private val currentVersion: String) : Version(currentVersion)
data class RecommendedVersionWarning(private val currentVersion: String) :
Version(currentVersion)
data class OutOfDateError(private val currentVersion: String) : Version(currentVersion)
}
}
| mit | 377cb684db284e583f3485798f1ab510 | 41.034783 | 179 | 0.60211 | 5.271538 | false | false | false | false |
aleksanderwozniak/WhatsThatFlag | app/src/main/java/me/wozappz/whatsthatflag/di/app/AppModule.kt | 1 | 1114 | package me.wozappz.whatsthatflag.di.app
import dagger.Module
import dagger.Provides
import me.wozappz.whatsthatflag.app.App
import me.wozappz.whatsthatflag.data.Repository
import me.wozappz.whatsthatflag.data.model.DataLoader
import me.wozappz.whatsthatflag.data.model.Model
import me.wozappz.whatsthatflag.data.model.ModelImpl
import me.wozappz.whatsthatflag.data.prefs.SharedPrefsRepository
import me.wozappz.whatsthatflag.data.prefs.SharedPrefsRepositoryImpl
import javax.inject.Singleton
/**
* Created by olq on 07.01.18.
*/
@Module
class AppModule(private val app: App) {
@Provides
@Singleton
fun provideApp(): App = app
@Provides
@Singleton
fun provideDataLoader(app: App) = DataLoader(app)
@Provides
@Singleton
fun provideModel(dataLoader: DataLoader): Model = ModelImpl(dataLoader)
@Provides
@Singleton
fun provideSharedPrefsRepository(app: App): SharedPrefsRepository = SharedPrefsRepositoryImpl(app)
@Provides
@Singleton
fun provideRepository(model: Model, sharedPrefsRepo: SharedPrefsRepository) = Repository(model, sharedPrefsRepo)
} | apache-2.0 | a743ace1f8dedea7d7ee120014e486af | 27.589744 | 116 | 0.780072 | 3.713333 | false | false | false | false |
fluidsonic/jetpack-kotlin | Sources/Measurement/Speed.kt | 1 | 1890 | package com.github.fluidsonic.jetpack
import java.util.Locale
public class Speed : Measurement<Speed, Speed.Unit> {
private constructor(rawValue: Double) : super(rawValue)
public constructor(speed: Speed) : super(speed.rawValue)
protected override val description: Description<Speed, Unit>
get() = Speed.description
public fun kilometersPerHour() =
rawValue
public fun knots() =
kilometersPerHour() * knotsPerKmh
public fun milesPerHour() =
kilometersPerHour() * mphPerKmh
public override fun valueInUnit(unit: Unit) =
when (unit) {
Speed.Unit.kilometersPerHour -> kilometersPerHour()
Speed.Unit.knots -> knots()
Speed.Unit.milesPerHour -> milesPerHour()
}
public enum class Unit private constructor(key: String) : _StandardUnitType<Unit, Speed> {
kilometersPerHour("kilometerPerHour"),
knots("knot"),
milesPerHour("milePerHour");
public override val _descriptor = _StandardUnitType.Descriptor(key)
public override fun toString() =
pluralName(Locale.getDefault())
public override fun value(value: Double) =
when (this) {
kilometersPerHour -> kilometersPerHour(value)
knots -> knots(value)
milesPerHour -> milesPerHour(value)
}
}
public companion object {
private val description = Measurement.Description("Speed", Unit.kilometersPerHour)
private val kmhPerKnot = 1.852
private val kmhPerMph = 1.609344
private val knotsPerKmh = 1.0 / kmhPerKnot
private val mphPerKmh = 1.0 / kmhPerMph
public fun kilometersPerHour(kilometersPerHour: Double) =
Speed(rawValue = Measurement.validatedValue(kilometersPerHour))
public fun knots(knots: Double) =
kilometersPerHour(Measurement.validatedValue(knots) * kmhPerKnot)
public fun milesPerHour(milesPerHour: Double) =
kilometersPerHour(Measurement.validatedValue(milesPerHour) * kmhPerMph)
}
}
| mit | c0ed8f1655e314ed5170460479ccab22 | 22.04878 | 91 | 0.726984 | 3.506494 | false | false | false | false |
VerifAPS/verifaps-lib | lang/src/main/kotlin/edu/kit/iti/formal/automation/scope/InstanceScope.kt | 1 | 6187 | /*
* #%L
* iec61131lang
* %%
* Copyright (C) 2017 Alexander Weigl
* %%
* This program isType 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 isType 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 clone of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package edu.kit.iti.formal.automation.scope
/*
* Scope representing class and FB instances in the program being analyzed.
*
* @author Augusto Modanese
*
@ToString
class InstanceScope(private val globalScope: Scope) : Serializable {
// Use TreeMap to assure instances are always in order;
// needed to write tests with explicit instance IDs
private val classInstances = TreeMap<ClassDeclaration, List<Instance>>()
private val interfaceInstances = TreeMap<InterfaceDeclaration, List<Instance>>()
private val classPolymorphInstances = TreeMap<ClassDeclaration, List<Instance>>()
private var allInstances: List<Instance>? = null
private val instanceSets = InstanceSets()
init {
for (interfaceDeclaration in globalScope.interfaces.values())
interfaceInstances[interfaceDeclaration] = ArrayList()
for (classDeclaration in globalScope.classes.values()) {
//TODOglobalScope.getFunctionBlocks().values())) {
classInstances[classDeclaration] = ArrayList()
//classPolymorphInstances.put(classDeclaration, new ArrayList<>());
}
}
/**
* @return The instances of a class, disregarding polymorphy.
*/
fun getInstancesOfClass(className: String): List<Instance> {
return getInstancesOfClass(globalScope.resolveClass(className))
}
/**
* @return The instances of a class, disregarding polymorphy.
*/
fun getInstancesOfClass(classDeclaration: ClassDeclaration?): List<Instance> {
return classInstances.get(classDeclaration)
}
/**
* @return The instances of a function block, disregarding polymorphy.
*/
fun getInstancesOfFunctionBlock(functionBlockDeclaration: FunctionBlockDeclaration): List<Instance> {
//return getInstancesOfClass(functionBlockDeclaration);
//return functionBlockInstances.get(functionBlockDeclaration);
}
/**
* @return The instances which are compatible with the given interface.
*/
fun getInstancesOfInterface(interfaceName: String): List<Instance> {
return getInstancesOfInterface(globalScope.resolveInterface(interfaceName))
}
/**
* @return The instances which are compatible with the given interface.
*/
fun getInstancesOfInterface(interfaceDeclaration: InterfaceDeclaration?): List<Instance> {
return interfaceInstances.get(interfaceDeclaration)
}
/**
* @return The instances which can have the given class as their type. Takes polymorphy into account.
*/
fun getPolymorphInstancesOfClass(classDeclaration: ClassDeclaration): List<Instance> {
return classPolymorphInstances[classDeclaration]
}
/**
* @return A (flat) list of all instances in the scope.
*/
fun getAllInstances(): List<Instance> {
if (allInstances == null)
allInstances = classInstances.values.stream()
.flatMap<Instance>(Function<List<Instance>, Stream<out Instance>> { it.stream() })
.sorted(Comparator.comparing<Instance, String> { i ->
assert(i.variableDeclaration!!.dataType isType ClassDataType)
val instanceClass = (i.variableDeclaration!!.dataType as ClassDataType).clazz
val sortName = StringBuilder(instanceClass.name)
var parent = instanceClass.parentClass
while (parent != null) {
sortName.insert(0, parent.name + "$")
parent = parent.parentClass
}
sortName.toString()
}).collect<List<Instance>, Any>(Collectors.toList())
return allInstances
}
/**
* Register a new instance of instanceClass to variable
*
* @param variable the variable containing the instance
* @param instanceClass the instance's class
* @param instance the instance to register
*/
fun registerClassInstance(variable: VariableDeclaration, instanceClass: ClassDeclaration,
instance: Instance) {
classInstances[instanceClass].add(instance)
OOUtils.getImplementedInterfaces(instanceClass).forEach { i -> interfaceInstances[i].add(instance) }
OOUtils.getExtendedClasses(instanceClass).forEach { c -> classPolymorphInstances[c].add(instance) }
instanceSets.addInstance(variable.parent!!, variable, instance)
}
fun getInstances(variable: VariableDeclaration): Set<Instance> {
return instanceSets.getInstances(variable.parent!!, variable)
}
/**
* Model an instance of a class or function block.
* Maintains a reference to where the instance isType declared.
*/
@Data
@AllArgsConstructor
class Instance {
/**
* Null iff parent isType a program.
*/
val parent: Instance? = null
val variableDeclaration: VariableDeclaration? = null
private var initialization: StructureInitialization? = null
constructor(parent: Instance, variableDeclaration: VariableDeclaration) : this(parent, variableDeclaration, variableDeclaration.init as StructureInitialization?) {
// Add initialization if none
if (initialization == null)
initialization = StructureInitialization()
}
}
}
*/ | gpl-3.0 | 641d43a960cd5dbfcac9c0ed347db6e7 | 37.918239 | 171 | 0.668014 | 4.997577 | false | false | false | false |
SoulBeaver/Arena--7DRL- | src/test/java/com/sbg/arena/core/LevelSpec.kt | 1 | 3895 | package com.sbg.arena.core.level
import org.spek.Spek
import com.sbg.arena.core.Dimension
import com.sbg.arena.core.Level
import com.sbg.arena.util.iterator
import com.sbg.arena.util.withIndices
import kotlin.test.assertEquals
import kotlin.test.failsWith
import com.sbg.arena.core.geom.Point
class LevelSpec: Spek() {{
given("A 3x3 Level") {
val level = Level(Dimension(3, 3), array(FloorType.Wall, FloorType.Floor, FloorType.Wall,
FloorType.Floor, FloorType.Floor, FloorType.Floor,
FloorType.Wall, FloorType.Floor, FloorType.Wall))
on("inspecting the area") {
val area = level.area
it("should be nine") {
assertEquals(3 * 3, area)
}
}
on("getting arbitrary coordinates") {
val topLeft = level[0, 0]
val top = level[1, 0]
val topRight = level[2, 0]
val centerLeft = level[0, 1]
val center = level[1, 1]
val centerRight = level[2, 1]
val bottomLeft = level[0, 2]
val bottom = level[1, 2]
val bottomRight = level[2, 2]
it("should return the correct FloorType") {
assertEquals(FloorType.Wall, topLeft)
assertEquals(FloorType.Floor, top)
assertEquals(FloorType.Wall, topRight)
assertEquals(FloorType.Floor, centerLeft)
assertEquals(FloorType.Floor, center)
assertEquals(FloorType.Floor, centerRight)
assertEquals(FloorType.Wall, bottomLeft)
assertEquals(FloorType.Floor, bottom)
assertEquals(FloorType.Wall, bottomRight)
}
}
on("iterating through all the floors") {
val levelIterator = level.iterator()
it("should iterate exactly nine times") {
var iterations = 0
for (floor in level)
iterations += 1
assertEquals(9, iterations)
}
it("should iterate in order") {
assertEquals(FloorType.Wall, levelIterator.next())
assertEquals(FloorType.Floor, levelIterator.next())
assertEquals(FloorType.Wall, levelIterator.next())
assertEquals(FloorType.Floor, levelIterator.next())
assertEquals(FloorType.Floor, levelIterator.next())
assertEquals(FloorType.Floor, levelIterator.next())
assertEquals(FloorType.Wall, levelIterator.next())
assertEquals(FloorType.Floor, levelIterator.next())
assertEquals(FloorType.Wall, levelIterator.next())
}
it ("should throw IndexOutOfBoundsException on iterating past end") {
failsWith(javaClass<IndexOutOfBoundsException>()) {
levelIterator.next()
}
}
}
on("iterating with index") {
val levelWithIndices = level.withIndices()
it("should contain current coordinates") {
assertEquals(Point(0, 0), levelWithIndices.next().first)
assertEquals(Point(1, 0), levelWithIndices.next().first)
assertEquals(Point(2, 0), levelWithIndices.next().first)
assertEquals(Point(0, 1), levelWithIndices.next().first)
assertEquals(Point(1, 1), levelWithIndices.next().first)
assertEquals(Point(2, 1), levelWithIndices.next().first)
assertEquals(Point(0, 2), levelWithIndices.next().first)
assertEquals(Point(1, 2), levelWithIndices.next().first)
assertEquals(Point(2, 2), levelWithIndices.next().first)
}
}
}
}} | apache-2.0 | cd728ee3b10e510e4bda6310ee95bfc0 | 36.461538 | 100 | 0.559178 | 4.692771 | false | false | false | false |
ChrisZhong/twitter-following-management-tool | buildSrc/src/main/kotlin/Version.kt | 1 | 496 | object Version {
const val KOTLIN_VERSION = "1.3.11"
const val SPRING_BOOT_VERSION = "2.1.1.RELEASE"
const val SPRING_DEPENDENCY_MANAGEMENT_VERSION = "1.0.6.RELEASE"
const val springPlatformVersion = "2.0.0.RELEASE"
const val springVersion = "4.2.3.RELEASE"
const val springBootVersion = "1.5.18.RELEASE"
const val springSocialVersion = "1.1.6.RELEASE"
const val springSocialTwitterVersion = "1.1.2.RELEASE"
const val springSecurityVersion = "4.0.3.RELEASE"
} | apache-2.0 | dc29ee4a434e10eec53212e85e0fc9a2 | 40.416667 | 68 | 0.705645 | 3.179487 | false | false | false | false |
Fondesa/RecyclerViewDivider | recycler-view-divider/src/main/kotlin/com/fondesa/recyclerviewdivider/StaggeredDividerItemDecoration.kt | 1 | 6451 | /*
* Copyright (c) 2020 Giorgio Antonioli
*
* 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.fondesa.recyclerviewdivider
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.view.View
import androidx.annotation.Px
import androidx.annotation.VisibleForTesting
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.fondesa.recyclerviewdivider.drawable.drawWithBounds
import com.fondesa.recyclerviewdivider.offset.StaggeredDividerOffsetProvider
import kotlin.math.roundToInt
/**
* Implementation of [BaseDividerItemDecoration] used in a [StaggeredGridLayoutManager].
*
* @param asSpace true if the divider should behave as a space.
* @param drawable the divider's drawable.
* @param size the divider's size.
* @param areSideDividersVisible true if the side dividers should be shown.
* @param offsetProvider balances the offsets of the divider.
*/
internal class StaggeredDividerItemDecoration(
asSpace: Boolean,
@VisibleForTesting internal val drawable: Drawable,
@[VisibleForTesting Px] internal val size: Int,
@VisibleForTesting internal val areSideDividersVisible: Boolean,
private val offsetProvider: StaggeredDividerOffsetProvider
) : BaseDividerItemDecoration(asSpace) {
override fun getItemOffsets(
layoutManager: RecyclerView.LayoutManager,
outRect: Rect,
itemView: View,
itemCount: Int,
itemIndex: Int
) = layoutManager.withStaggered {
val grid = staggeredGrid()
val cell = itemView.staggeredCell()
@Px val topSize = offsetProvider.getOffsetFromSize(grid, cell, Side.TOP, size)
@Px val bottomSize = offsetProvider.getOffsetFromSize(grid, cell, Side.BOTTOM, size)
@Px val startSize = offsetProvider.getOffsetFromSize(grid, cell, Side.START, size)
@Px val endSize = offsetProvider.getOffsetFromSize(grid, cell, Side.END, size)
val layoutRightToLeft = grid.layoutDirection.isRightToLeft
val layoutBottomToTop = grid.layoutDirection.isBottomToTop
outRect.top = if (layoutBottomToTop) bottomSize else topSize
outRect.bottom = if (layoutBottomToTop) topSize else bottomSize
outRect.left = if (layoutRightToLeft) endSize else startSize
outRect.right = if (layoutRightToLeft) startSize else endSize
}
override fun onDraw(
canvas: Canvas,
recyclerView: RecyclerView,
layoutManager: RecyclerView.LayoutManager,
itemCount: Int
) = layoutManager.withStaggered {
val grid = staggeredGrid()
recyclerView.forEachItem(itemCount) { _, itemView -> itemView.drawDividersOfItem(canvas, grid) }
}
private fun View.drawDividersOfItem(canvas: Canvas, grid: StaggeredGrid) {
val layoutRightToLeft = grid.layoutDirection.isRightToLeft
val layoutBottomToTop = grid.layoutDirection.isBottomToTop
val translationX = translationX.roundToInt()
val translationY = translationY.roundToInt()
val left = leftWithMargin + translationX
val right = rightWithMargin + translationX
val top = topWithMargin + translationY
val bottom = bottomWithMargin + translationY
val cell = staggeredCell()
val adjacentGridSides = grid.sidesAdjacentToCell(cell)
val shouldDrawTop: Boolean
val shouldDrawBottom: Boolean
val shouldDrawStart: Boolean
val shouldDrawEnd: Boolean
if (grid.orientation.isVertical) {
shouldDrawBottom = true
shouldDrawTop = true
shouldDrawEnd = Side.END !in adjacentGridSides || areSideDividersVisible
shouldDrawStart = Side.START !in adjacentGridSides || areSideDividersVisible
} else {
shouldDrawBottom = Side.BOTTOM !in adjacentGridSides || areSideDividersVisible
shouldDrawTop = Side.TOP !in adjacentGridSides || areSideDividersVisible
shouldDrawEnd = true
shouldDrawStart = true
}
if (shouldDrawEnd) {
val leftBound = if (layoutRightToLeft) left - size else right
val rightBound = if (layoutRightToLeft) left else right + size
drawable.drawWithBounds(canvas = canvas, left = leftBound, top = top - size, right = rightBound, bottom = bottom + size)
}
if (shouldDrawStart) {
val leftBound = if (layoutRightToLeft) right else left - size
val rightBound = if (layoutRightToLeft) right + size else left
drawable.drawWithBounds(canvas = canvas, left = leftBound, top = top - size, right = rightBound, bottom = bottom + size)
}
if (shouldDrawTop) {
val topBound = if (layoutBottomToTop) bottom else top - size
val bottomBound = if (layoutBottomToTop) bottom + size else top
drawable.drawWithBounds(canvas = canvas, left = left, top = topBound, right = right, bottom = bottomBound)
}
if (shouldDrawBottom) {
val topBound = if (layoutBottomToTop) top - size else bottom
val bottomBound = if (layoutBottomToTop) top else bottom + size
drawable.drawWithBounds(canvas = canvas, left = left, top = topBound, right = right, bottom = bottomBound)
}
}
private inline fun RecyclerView.LayoutManager.withStaggered(onStaggered: StaggeredGridLayoutManager.() -> Unit) {
when (this) {
is StaggeredGridLayoutManager -> onStaggered()
is LinearLayoutManager -> throw IllegalLayoutManagerException(
layoutManagerClass = this::class.java,
suggestedBuilderClass = DividerBuilder::class.java
)
else -> throw IllegalLayoutManagerException(layoutManagerClass = this::class.java)
}
}
}
| apache-2.0 | f675ae5c29abd28e3bb2a3b816c511e9 | 44.429577 | 132 | 0.703302 | 4.835832 | false | false | false | false |
kozake/kotlin-koans | src/i_introduction/_4_Lambdas/Lambdas.kt | 1 | 761 | package i_introduction._4_Lambdas
import util.TODO
import util.doc4
fun example() {
val sum = { x: Int, y: Int -> x + y }
val square: (Int) -> Int = { x -> x * x }
sum(1, square(2)) == 5
}
fun todoTask4(collection: Collection<Int>): Nothing = TODO(
"""
Task 4.
'JavaCode4.task4()'をラムダを用いたKotlinコードに置き換えてください。
IntelliJのIDEAのコード補完機能を使用して、'collection'を呼び出す適切な関数を見つけることができます。
('Iterables'クラスは使わないように)。
""",
documentation = doc4(),
references = { JavaCode4().task4(collection) })
fun task4(collection: Collection<Int>): Boolean = todoTask4(collection)
| mit | 48cd72c28b42b27430e59e202f4980d5 | 21.035714 | 71 | 0.632091 | 2.830275 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/glNext/tut05/overlapNoDepth.kt | 2 | 8365 | package glNext.tut05
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL.*
import com.jogamp.opengl.GL2ES3.GL_COLOR
import com.jogamp.opengl.GL2ES3.GL_DEPTH
import com.jogamp.opengl.GL3
import glNext.*
import glm.f
import glm.size
import glm.vec._3.Vec3
import glm.vec._4.Vec4
import main.framework.Framework
import uno.buffer.*
import uno.glsl.programOf
/**
* Created by GBarbieri on 23.02.2017.
*/
fun main(args: Array<String>) {
OverlapNoDepth_Next().setup("Tutorial 05 - Overlap No Depth")
}
class OverlapNoDepth_Next : Framework() {
object Buffer {
val VERTEX = 0
val INDEX = 1
val MAX = 2
}
object Vao {
val A = 0
val B = 1
val MAX = 2
}
var theProgram = 0
var offsetUniform = 0
var perspectiveMatrixUnif = 0
val numberOfVertices = 36
val perspectiveMatrix = FloatArray(16)
val frustumScale = 1.0f
val bufferObject = intBufferBig(Buffer.MAX)
val vao = intBufferBig(Vao.MAX)
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
initializeBuffers(gl)
initializeVertexArrays(gl)
cullFace {
enable()
cullFace = back
frontFace = cw
}
}
fun initializeProgram(gl: GL3) = with(gl) {
theProgram = programOf(gl, javaClass, "tut05", "standard.vert", "standard.frag")
withProgram(theProgram) {
offsetUniform = "offset".location
perspectiveMatrixUnif = "perspectiveMatrix".location
val zNear = 1.0f
val zFar = 3.0f
perspectiveMatrix[0] = frustumScale
perspectiveMatrix[5] = frustumScale
perspectiveMatrix[10] = (zFar + zNear) / (zNear - zFar)
perspectiveMatrix[14] = 2f * zFar * zNear / (zNear - zFar)
perspectiveMatrix[11] = -1.0f
glUseProgram(theProgram)
glUniformMatrix4f(perspectiveMatrixUnif, perspectiveMatrix)
}
}
fun initializeBuffers(gl: GL3) = with(gl) {
glGenBuffers(bufferObject)
withArrayBuffer(bufferObject[Buffer.VERTEX]) { data(vertexData, GL_STATIC_DRAW) }
withElementBuffer(bufferObject[Buffer.INDEX]) { data(indexData, GL_STATIC_DRAW) }
}
fun initializeVertexArrays(gl: GL3) = with(gl) {
glGenVertexArrays(vao)
glBindVertexArray(vao[Vao.A])
var colorDataOffset = Vec3.SIZE * numberOfVertices
glBindBuffer(GL_ARRAY_BUFFER, bufferObject[Buffer.VERTEX])
glEnableVertexAttribArray(glf.pos3_col4)
glEnableVertexAttribArray(glf.pos3_col4[1])
glVertexAttribPointer(glf.pos3_col4, 0)
glVertexAttribPointer(glf.pos3_col4[1], colorDataOffset)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferObject[Buffer.INDEX])
glBindVertexArray(vao[Vao.B])
val positionDataOffset = Vec3.SIZE * (numberOfVertices / 2)
colorDataOffset += Vec4.SIZE * (numberOfVertices / 2)
//Use the same buffer object previously bound to GL_ARRAY_BUFFER.
glEnableVertexAttribArray(glf.pos3_col4)
glEnableVertexAttribArray(glf.pos3_col4[1])
glVertexAttribPointer(glf.pos3_col4, positionDataOffset)
glVertexAttribPointer(glf.pos3_col4[1], colorDataOffset)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferObject[Buffer.INDEX])
glBindVertexArray()
}
override fun display(gl: GL3) = with(gl) {
glClearBufferf(GL_COLOR, 0)
glClearBufferf(GL_DEPTH)
glUseProgram(theProgram)
glBindVertexArray(vao[Vao.A])
glUniform3f(offsetUniform)
glDrawElements(GL_TRIANGLES, indexData.size, GL_UNSIGNED_SHORT)
glBindVertexArray(vao[Vao.B])
glUniform3f(offsetUniform, 0.0f, 0.0f, -1.0f)
glDrawElements(GL_TRIANGLES, indexData.size, GL_UNSIGNED_SHORT)
glBindVertexArray()
glUseProgram()
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
perspectiveMatrix[0] = frustumScale * (h / w.f)
perspectiveMatrix[5] = frustumScale
glUseProgram(theProgram)
glUniformMatrix4f(perspectiveMatrixUnif, perspectiveMatrix)
glUseProgram()
glViewport(w, h)
}
override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
glDeleteBuffers(bufferObject)
glDeleteVertexArrays(vao)
destroyBuffers(vao, bufferObject, vertexData, indexData)
}
override fun keyPressed(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
}
}
val RIGHT_EXTENT = 0.8f
val LEFT_EXTENT = -RIGHT_EXTENT
val TOP_EXTENT = 0.20f
val MIDDLE_EXTENT = 0.0f
val BOTTOM_EXTENT = -TOP_EXTENT
val FRONT_EXTENT = -1.25f
val REAR_EXTENT = -1.75f
val GREEN_COLOR = floatArrayOf(0.75f, 0.75f, 1.0f, 1.0f)
val BLUE_COLOR = floatArrayOf(0.0f, 0.5f, 0.0f, 1.0f)
val RED_COLOR = floatArrayOf(1.0f, 0.0f, 0.0f, 1.0f)
val GREY_COLOR = floatArrayOf(0.8f, 0.8f, 0.8f, 1.0f)
val BROWN_COLOR = floatArrayOf(0.5f, 0.5f, 0.0f, 1.0f)
val vertexData = floatBufferOf(
//Object 1 positions
LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT,
LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT,
LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT,
LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT,
RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT,
RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT,
RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
//Object 2 positions
TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT,
BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,
TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT,
MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,
BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT,
BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,
//Object 1 colors
*GREEN_COLOR,
*GREEN_COLOR,
*GREEN_COLOR,
*GREEN_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*RED_COLOR,
*RED_COLOR,
*RED_COLOR,
*GREY_COLOR,
*GREY_COLOR,
*GREY_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
//Object 2 colors
*RED_COLOR,
*RED_COLOR,
*RED_COLOR,
*RED_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*GREEN_COLOR,
*GREEN_COLOR,
*GREEN_COLOR,
*GREY_COLOR,
*GREY_COLOR,
*GREY_COLOR,
*GREY_COLOR)
val indexData = shortBufferOf(
0, 2, 1,
3, 2, 0,
4, 5, 6,
6, 7, 4,
8, 9, 10,
11, 13, 12,
14, 16, 15,
17, 16, 14)
} | mit | 6d198edceb280762371efb090f22d579 | 26.886667 | 89 | 0.588165 | 3.987131 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/diagnostic/github/issues/GitHubIssuesApis.kt | 1 | 1155 | package cn.yiiguxing.plugin.translate.diagnostic.github.issues
import cn.yiiguxing.plugin.translate.util.Http
import cn.yiiguxing.plugin.translate.util.UrlBuilder
internal object GitHubIssuesApis {
private const val API_BASE_URL = "https://api.github.com"
private const val ISSUES_SEARCH_URL = "$API_BASE_URL/search/issues"
private const val ACCEPT = "application/vnd.github.v3+json"
fun search(query: String, page: Int = 1, perPage: Int = 30): IssueSearchResult {
val url = UrlBuilder(ISSUES_SEARCH_URL)
.addQueryParameters("q", query)
.addQueryParameters("page", page.toString())
.addQueryParameters("per_page", perPage.toString())
.build()
return Http.request(url) {
accept(ACCEPT)
}
}
fun create(repositoryId: String, title: String, body: String, authToken: String): Issue {
val url = "$API_BASE_URL/repos/$repositoryId/issues"
return Http.postJson<Issue>(url, mapOf("title" to title, "body" to body)) {
accept(ACCEPT)
tuner { it.setRequestProperty("Authorization", authToken) }
}
}
} | mit | 548a7da9ac6c14c9427c450c6f321f65 | 35.125 | 93 | 0.652814 | 3.955479 | false | false | false | false |
sugarmanz/Pandroid | app/src/main/java/com/jeremiahzucker/pandroid/ui/station/StationListPresenter.kt | 1 | 3754 | package com.jeremiahzucker.pandroid.ui.station
import android.util.Log
import com.jeremiahzucker.pandroid.PandroidApplication.Companion.Preferences
import com.jeremiahzucker.pandroid.request.Pandora
import com.jeremiahzucker.pandroid.request.json.v5.method.auth.UserLogin
import com.jeremiahzucker.pandroid.request.json.v5.method.user.GetStationList
import com.jeremiahzucker.pandroid.request.json.v5.method.user.GetStationListChecksum
import com.jeremiahzucker.pandroid.request.json.v5.model.ExpandedStationModel
import io.realm.Realm
/**
* StationListPresenter
*
* Author: Jeremiah Zucker
* Date: 9/2/2017
* Desc: TODO: Complete
*/
class StationListPresenter : StationListContract.Presenter {
private val TAG: String = StationListPresenter::class.java.simpleName
private var view: StationListContract.View? = null
private var realm: Realm = Realm.getDefaultInstance()
override fun attach(view: StationListContract.View) {
this.view = view
// 1. Try to load stations from database
if (Preferences.stationListChecksum != null) {
val stations = realm.where(ExpandedStationModel::class.java).findAll()
Log.i(TAG, stations.toString())
view.showProgress(false)
view.updateStationList(stations)
// Verify checksum
verifyChecksum()
} else {
getStationList()
}
}
override fun detach() {
this.view = null
}
override fun getStationList(body: GetStationList.RequestBody) {
Pandora.HTTP.RequestBuilder(GetStationList)
.body(body)
.build<GetStationList.ResponseBody>()
.subscribe(this::handleGetStationListSuccess, this::handleGetStationListError)
}
private fun handleGetStationListSuccess(responseBody: GetStationList.ResponseBody) {
Preferences.stationListChecksum = responseBody.checksum
realm.executeTransaction {
realm.delete(ExpandedStationModel::class.java)
realm.insert(responseBody.stations)
}
view?.showProgress(false)
view?.updateStationList(responseBody.stations)
}
private fun handleGetStationListError(throwable: Throwable? = null) {
// Oh no!
Log.e(TAG, throwable?.message ?: "Error!", throwable)
view?.showProgress(false)
}
private fun verifyChecksum() {
Log.i(TAG, "VERIFY")
Pandora.HTTP.RequestBuilder(GetStationListChecksum)
.body(GetStationListChecksum.RequestBody())
.build<GetStationListChecksum.ResponseBody>()
.subscribe(this::handleGetStationListChecksumSuccess, this::handleGetStationListChecksumError)
}
private fun handleGetStationListChecksumSuccess(checksum: GetStationListChecksum.ResponseBody) {
if (checksum.checksum != Preferences.stationListChecksum) getStationList()
}
private fun handleGetStationListChecksumError(throwable: Throwable) {
if ("1001" == throwable.message)
doUserLogin()
}
private fun doUserLogin() {
Pandora.RequestBuilder(UserLogin)
.authToken(Preferences.partnerAuthToken)
.body(UserLogin.RequestBody(Preferences.username ?: "", Preferences.password ?: ""))
.build<UserLogin.ResponseBody>()
.subscribe(this::handleUserLoginSuccess, this::handleUserLoginError)
}
private fun handleUserLoginSuccess(result: UserLogin.ResponseBody) {
// TODO: Pass to model? Maybe?
Preferences.userId = result.userId
Preferences.userAuthToken = result.userAuthToken
verifyChecksum()
}
private fun handleUserLoginError(throwable: Throwable) {
view?.showAuth()
}
}
| mit | 34214f6d062e1e485f19bf31cd6fd60b | 34.084112 | 106 | 0.694193 | 4.583639 | false | false | false | false |
rcgroot/open-gpstracker-exporter | studio/app/src/main/java/nl/renedegroot/android/opengpstracker/exporter/ExportActivity.kt | 1 | 4463 | /*------------------------------------------------------------------------------
** Author: René de Groot
** Copyright: (c) 2016 René de Groot All Rights Reserved.
**------------------------------------------------------------------------------
** No part of this file may be reproduced
** or transmitted in any form or by any
** means, electronic or mechanical, for the
** purpose, without the express written
** permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of "Open GPS Tracker - Exporter".
*
* "Open GPS Tracker - Exporter" 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.
*
* "Open GPS Tracker - Exporter" 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 "Open GPS Tracker - Exporter". If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.renedegroot.android.opengpstracker.exporter
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import nl.renedegroot.android.opengpstracker.exporter.about.AboutFragment
import nl.renedegroot.android.opengpstracker.exporter.export.ExportFragment
import nl.renedegroot.android.opengpstracker.exporter.export.ExportModel
import nl.renedegroot.android.opengpstracker.exporter.exporting.driveManager
import nl.sogeti.android.gpstracker.integration.PermissionRequestor
import nl.sogeti.android.log.Log
/**
* Owns the export model and communicated the the Android system regarding
* permissions.
*/
class ExportActivity : AppCompatActivity(), ExportFragment.Listener {
private val model = ExportModel()
private val permissionRequestor = PermissionRequestor()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_export)
val toolbar = findViewById(R.id.toolbar) as Toolbar?
setSupportActionBar(toolbar)
connectToServices()
}
override fun onDestroy() {
permissionRequestor.stop()
driveManager.stop()
super.onDestroy()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
driveManager.processResult(requestCode, resultCode)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
permissionRequestor.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_export, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == R.id.action_settings) {
showAboutDialog()
return true
}
return super.onOptionsItemSelected(item)
}
override fun getExportModel(): ExportModel = model
override fun connectGoogleDrive() {
driveManager.start(this, { isConnected ->
model?.isDriveConnected?.set(isConnected)
})
}
override fun connectTracksDatabase() {
permissionRequestor.checkTracksPermission(this, {
model?.isTrackerConnected?.set(true)
})
}
private fun connectToServices() {
permissionRequestor.checkTracksPermission(this, {
model?.isTrackerConnected?.set(true)
driveManager.start(this, { isConnected ->
model?.isDriveConnected?.set(isConnected)
if (isConnected) {
Log.d(this, "Everything is connected")
} else {
Log.d(this, "Drive failed")
}
})
})
}
fun showAboutDialog() {
AboutFragment().show(supportFragmentManager, "ABOUT")
}
}
| gpl-2.0 | 9daa09568362d0fcd5bf1a911683ef4f | 35.268293 | 119 | 0.655683 | 4.956667 | false | false | false | false |
rectangle-dbmi/Realtime-Port-Authority | pat-static/src/test/kotlin/com/rectanglel/patstatic/patterns/PatternDataManagerTest.kt | 1 | 7263 | package com.rectanglel.patstatic.patterns
import com.rectanglel.patstatic.TestHelperMethods
import com.rectanglel.patstatic.buildutils.getTestFilesFolder
import com.rectanglel.patstatic.mock.PatApiMock
import com.rectanglel.patstatic.model.RetrofitPatApi
import com.rectanglel.patstatic.model.StaticData
import com.rectanglel.patstatic.patterns.response.Ptr
import com.rectanglel.patstatic.wrappers.WifiChecker
import io.reactivex.subscribers.TestSubscriber
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStreamReader
/**
* Tests for the [PatternDataManager] class.
*
* Created by epicstar on 8/13/17.
*/
class PatternDataManagerTest {
private lateinit var dir : File
private lateinit var patternDataManager : PatternDataManager
private lateinit var patapi : RetrofitPatApi
private lateinit var staticData : StaticData
private lateinit var wifiChecker : WifiChecker
@Before
fun setUp() {
dir = File ("testDirectory")
dir.mkdirs()
patapi = PatApiMock.getPatApiMock()
staticData = Mockito.mock(StaticData::class.java)
wifiChecker = Mockito.mock(WifiChecker::class.java)
patternDataManager = Mockito.spy(PatternDataManager(
dir,
patapi,
staticData,
wifiChecker
))
// patternDataManager = PatternDataManager(
// dir,
// patapi,
// staticData,
// wifiChecker
// )
}
@After
fun tearDown() {
TestHelperMethods.deleteFiles(dir)
}
/**
* Testing on retrieving something from "71A":
* <ul>
* <li>polyline gets from the mock REST call 1x</li>
* <li>polyline gets from disk 1x after a call to the REST API</li>
* <li>Ensures that the data from disk and internet are equivalent</li>
* </ul>
*/
@Test
fun `testGetPatterns - get from internet then get from disk when wifi is on`() {
// region setup
val ts1 = TestSubscriber<List<Ptr>>()
val ts2 = TestSubscriber<List<Ptr>>()
Mockito.`when`(wifiChecker.isWifiOn()).thenReturn(true)
patternDataManager.getPatterns(PatApiMock.testRoute1).subscribe(ts1)
patternDataManager.getPatterns(PatApiMock.testRoute1).subscribe(ts2)
// endregion setup
//region verify
Mockito.verify(patapi, Mockito.times(1)).getPatterns(PatApiMock.testRoute1)
Mockito.verify(patternDataManager, Mockito.times(1)).getPatternsFromInternet(PatApiMock.testRoute1)
Mockito.verify(patternDataManager, Mockito.times(1)).getPatternsFromDisk(PatApiMock.testRoute1)
//endregion verify
//region assert
Assert.assertEquals(1, ts1.values().size)
Assert.assertEquals(ts1.values().size, ts2.values().size)
Assert.assertEquals(PatApiMock.getPatterns(), ts1.values()[0])
Assert.assertEquals(PatApiMock.getPatterns(), ts2.values()[0])
//endregion assert
}
/**
* Testing on retrieving something from "71A":
* <ul>
* <li>polyline gets from the mock REST call 1x</li>
* <li>polyline gets from disk 1x after a call to the REST API</li>
* <li>Ensures that the data from disk and internet are equivalent</li>
* </ul>
*/
@Test
fun `testGetPatterns - always get from disk if no wifi`() {
// region setup
// make sure that we are populating the disk first
PatternDataManager(
dir,
patapi,
staticData,
wifiChecker
).getPatterns(PatApiMock.testRoute1).subscribe()
val ts1 = TestSubscriber<List<Ptr>>()
val ts2 = TestSubscriber<List<Ptr>>()
Mockito.`when`(wifiChecker.isWifiOn()).thenReturn(false)
patternDataManager.getPatterns(PatApiMock.testRoute1).subscribe(ts1)
patternDataManager.getPatterns(PatApiMock.testRoute1).subscribe(ts2)
// endregion setup
//region verify
Mockito.verify(patapi, Mockito.times(1)).getPatterns(PatApiMock.testRoute1)
Mockito.verify(patternDataManager, Mockito.times(0)).getPatternsFromInternet(PatApiMock.testRoute1)
Mockito.verify(patternDataManager, Mockito.times(2)).getPatternsFromDisk(PatApiMock.testRoute1)
//endregion verify
//region assert
Assert.assertEquals(1, ts1.values().size)
Assert.assertEquals(ts1.values().size, ts2.values().size)
Assert.assertEquals(PatApiMock.getPatterns(), ts1.values()[0])
Assert.assertEquals(PatApiMock.getPatterns(), ts2.values()[0])
//endregion assert
}
/**
* Reads route json from disk using the StaticData class.
*/
@Test
fun `testGetPatterns - always get from internet`() {
//region setup
val ts1 = TestSubscriber<List<Ptr>>()
val ts2 = TestSubscriber<List<Ptr>>()
val filename = "lineinfo/${PatApiMock.testRoute1}.json"
val file = File(getTestFilesFolder(), filename)
// jeremy.... RIP backticks for when because kotlin has
// a keyword called when that replaces switch cases
Mockito.`when`(wifiChecker.isWifiOn()).thenReturn(true)
Mockito.`when`(staticData.getInputStreamForFileName(filename))
.thenReturn(InputStreamReader(FileInputStream(file)))
patternDataManager.getPatternsFromInternet(PatApiMock.testRoute1).subscribe(ts1)
patternDataManager.getPatternsFromInternet(PatApiMock.testRoute1).subscribe(ts2)
//endregion setup
//region verify
Mockito.verify(patapi, Mockito.times(2)).getPatterns(PatApiMock.testRoute1)
Mockito.verify(staticData, Mockito.times(0)).getInputStreamForFileName(filename)
Mockito.verify(patternDataManager, Mockito.times(2)).getPatternsFromInternet(PatApiMock.testRoute1)
Mockito.verify(patternDataManager, Mockito.times(0)).getPatternsFromDisk(PatApiMock.testRoute1)
//endregion verify
//region assert
Assert.assertEquals(1, ts1.values().size)
Assert.assertEquals(ts1.values().size, ts2.values().size)
Assert.assertEquals(ts1.values()[0], ts2.values()[0])
//endregion assert
}
/**
* Throws an error (via a mock object) when the data does not exist.
*/
@Test
fun `testGetPatterns - propagate error if there is an error`() {
//region setup
val nonExistentPattern = "71C"
val ts1 = TestSubscriber<List<Ptr>>()
val filename = "lineinfo/$nonExistentPattern.json"
val mockedException = IOException("error")
Mockito.`when`(staticData.getInputStreamForFileName(filename))
.thenThrow(mockedException)
patternDataManager.getPatternsFromDisk(nonExistentPattern).subscribe(ts1)
//endregion setup
//region assert
Assert.assertEquals(0, ts1.values().size)
Assert.assertEquals(1, ts1.errorCount())
Assert.assertEquals(mockedException, ts1.errors()[0].cause)
//endregion assert
}
} | gpl-3.0 | cf92371e364b22600727e0d1bb162a58 | 36.833333 | 107 | 0.668732 | 4.23993 | false | true | false | false |
google-home/sample-app-for-matter-android | app/src/main/java/com/google/homesampleapp/screens/settings/DeveloperUtilitiesViewModel.kt | 1 | 3855 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.homesampleapp.screens.settings
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.homesampleapp.DUMMY_DEVICE_NAME_PREFIX
import com.google.homesampleapp.DUMMY_DEVICE_NAME_SUFFIX
import com.google.homesampleapp.DUMMY_DEVICE_ROOM_PREFIX
import com.google.homesampleapp.DUMMY_PRODUCT_ID
import com.google.homesampleapp.DUMMY_VENDOR_ID
import com.google.homesampleapp.Device
import com.google.homesampleapp.data.DevicesRepository
import com.google.homesampleapp.data.DevicesStateRepository
import com.google.homesampleapp.data.UserPreferencesRepository
import com.google.homesampleapp.getTimestampForNow
import com.google.homesampleapp.screens.home.DeviceUiModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.launch
import timber.log.Timber
@HiltViewModel
class DeveloperUtilitiesViewModel
@Inject
constructor(
private val devicesRepository: DevicesRepository,
private val userPreferencesRepository: UserPreferencesRepository,
private val devicesStateRepository: DevicesStateRepository,
) : ViewModel() {
fun printRepositories() {
viewModelScope.launch {
val divider = "-".repeat(20)
val userPreferences = userPreferencesRepository.getData()
Timber.d(
"UserPreferences Repository\n${divider} [UserPreferences Repository] ${divider}\n${userPreferences}\n${divider} End of [UserPreferences Repository] $divider")
val devices = devicesRepository.getAllDevices()
Timber.d(
"Devices Repository\n${divider} [Devices Repository] ${divider}\n${devices}\n${divider} End of [Devices Repository] $divider")
val devicesState = devicesStateRepository.getAllDevicesState()
Timber.d(
"DevicesState Repository\n${divider} [DevicesState Repository] ${divider}\n${devicesState}\n${divider} End of [DevicesState Repository] $divider")
}
}
/**
* Adds a dummy device to the app. Useful to test the various components of the app without having
* to commission a large number of physical devices.
*
* deviceType: "Light" or "Outlet"
*/
fun addDummyDevice(_deviceType: String, isOnline: Boolean, isOn: Boolean) {
val timestamp = getTimestampForNow()
val deviceType =
when (_deviceType) {
"Light" -> Device.DeviceType.TYPE_LIGHT
"Outlet" -> Device.DeviceType.TYPE_OUTLET
else -> Device.DeviceType.TYPE_UNSPECIFIED
}
viewModelScope.launch {
val deviceId = devicesRepository.incrementAndReturnLastDeviceId()
val device =
Device.newBuilder()
.setDateCommissioned(timestamp)
.setVendorId(DUMMY_VENDOR_ID)
.setProductId(DUMMY_PRODUCT_ID)
.setDeviceType(deviceType)
.setDeviceId(deviceId)
.setName(DUMMY_DEVICE_NAME_PREFIX + deviceId + DUMMY_DEVICE_NAME_SUFFIX)
.setRoom(DUMMY_DEVICE_ROOM_PREFIX + deviceId)
.build()
val deviceUiModel = DeviceUiModel(device, isOnline, isOn)
// Add the device to the repository.
devicesRepository.addDevice(deviceUiModel.device)
devicesStateRepository.addDeviceState(deviceId, isOnline, isOn)
}
}
}
| apache-2.0 | 818e669492f2886b59dee1b98c25203b | 40.451613 | 168 | 0.733593 | 4.535294 | false | false | false | false |
jeffbanks/Lotto-Sessions | lotto-session-3/src/main/kotlin/com/jjbanks/lotto/model/PowerDrawing.kt | 1 | 2160 | /*
* MIT License
*
* Copyright (c) 2017 Jeff Banks
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
*/
package com.jjbanks.lotto.model
import java.time.LocalDate
import java.util.stream.IntStream
class PowerDrawing(date: LocalDate, corePicks: Set<Int>, val powerPick:Int) : Drawing(date, corePicks) {
companion object {
@JvmField val MAX_CORE_PICK : Int = 65
@JvmField val MAX_POWER_PICK : Int = 36
@JvmField val CORE_PICKS_SIZE : Int = 5
}
override fun validate() {
super.validateCorePicksSize(CORE_PICKS_SIZE)
val corePicksInRange = corePicks.stream()
.allMatch { x -> IntStream.rangeClosed(1, MAX_CORE_PICK).anyMatch { r -> r == x } }
if (!corePicksInRange) {
throw IllegalArgumentException("Core picks not in acceptable range 1 ... " + MAX_CORE_PICK)
}
val powerPickInRange = IntStream.rangeClosed(1, MAX_POWER_PICK).anyMatch { r -> r == powerPick }
if (!powerPickInRange) {
throw IllegalArgumentException("Power pick not in acceptable range 1 ... " + MAX_POWER_PICK)
}
}
} | mit | 0e53e6b096969f2bc0aa7611fbf2d9e2 | 38.290909 | 104 | 0.698148 | 4.194175 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/ide/intentions/SpecifyTypeExplicitlyIntention.kt | 2 | 1902 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.ide.presentation.insertionSafeText
import org.rust.lang.core.psi.RsLetDecl
import org.rust.lang.core.psi.RsPatIdent
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.ext.ancestorStrict
import org.rust.lang.core.types.infer.containsTyOfClass
import org.rust.lang.core.types.ty.Ty
import org.rust.lang.core.types.ty.TyInfer
import org.rust.lang.core.types.ty.TyUnknown
import org.rust.lang.core.types.type
class SpecifyTypeExplicitlyIntention : RsElementBaseIntentionAction<SpecifyTypeExplicitlyIntention.Context>() {
override fun getFamilyName() = "Specify type explicitly"
override fun getText() = "Specify type explicitly"
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
val letDecl = element.ancestorStrict<RsLetDecl>() ?: return null
if(letDecl.typeReference != null) {
return null
}
val ident = letDecl.pat as? RsPatIdent ?: return null
val type = ident.patBinding.type
if (type.containsTyOfClass(listOf(TyUnknown::class.java, TyInfer::class.java))) {
return null
}
return Context(type, letDecl)
}
override fun invoke(project: Project, editor: Editor, ctx: Context) {
val factory = RsPsiFactory(project)
val createdType = factory.createType(ctx.type.insertionSafeText)
val letDecl = ctx.letDecl
val colon = letDecl.addAfter(factory.createColon(), letDecl.pat)
letDecl.addAfter(createdType, colon)
}
data class Context(
val type: Ty,
val letDecl: RsLetDecl
)
}
| mit | f6761a042317b1ca27081103e64f8a42 | 34.222222 | 111 | 0.721346 | 4.072805 | false | false | false | false |
fython/PackageTracker | mobile/src/main/kotlin/info/papdt/express/helper/ui/items/DetailsTwoLineItemBinder.kt | 1 | 4655 | package info.papdt.express.helper.ui.items
import android.app.Activity
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.widget.AppCompatImageButton
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.TooltipCompat
import info.papdt.express.helper.R
import info.papdt.express.helper.support.ClipboardUtils
import info.papdt.express.helper.ui.DetailsActivity
import me.drakeet.multitype.ItemViewBinder
class DetailsTwoLineItemBinder : ItemViewBinder<DetailsTwoLineItem, DetailsTwoLineItemBinder.ItemHolder>() {
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): ItemHolder {
return ItemHolder(inflater.inflate(R.layout.item_list_details_info_normal, parent, false))
}
override fun onBindViewHolder(holder: ItemHolder, item: DetailsTwoLineItem) {
holder.setData(item)
}
inner class ItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private var data: DetailsTwoLineItem? = null
var title: AppCompatTextView = itemView.findViewById(R.id.tv_title)
var summary: AppCompatTextView = itemView.findViewById(R.id.tv_summary)
var button: AppCompatImageButton = itemView.findViewById(R.id.btn_action)
fun setData(newData: DetailsTwoLineItem) {
this.data = newData
if (DetailsTwoLineItem.TYPE_NAME == data!!.type) {
title.setText(R.string.list_package_name)
summary.text = data!!.content
button.visibility = View.GONE
itemView.setOnLongClickListener { v ->
if (v.context is DetailsActivity) {
(v.context as DetailsActivity).showNameEditDialog()
}
true
}
} else if (DetailsTwoLineItem.TYPE_NUMBER == data!!.type) {
title.setText(R.string.list_package_number)
summary.text = String.format(
STRING_NUMBER_FORMAT,
data!!.content,
data!!.optional
)
if (button.tag != null && button.tag as Boolean) {
button.setImageResource(R.drawable.ic_visibility_off_black_24dp)
summary.text = String.format(STRING_NUMBER_FORMAT, data!!.content, data!!.optional)
} else {
val length = data!!.content!!.length
var str = if (length >= 4) data!!.content!!.substring(0, 4) else data!!.content!!
for (i in 4 until length) str += "*"
summary.text = String.format(STRING_NUMBER_FORMAT, str, data!!.optional)
button.setImageResource(R.drawable.ic_visibility_black_24dp)
button.contentDescription = itemView.resources
.getString(R.string.list_package_show_toggle_desc)
TooltipCompat.setTooltipText(button, button.contentDescription)
}
button.visibility = View.VISIBLE
button.setOnClickListener {
if (button.tag != null && button.tag as Boolean) {
val length = data!!.content!!.length
var str = if (length >= 4) data!!.content!!.substring(0, 4) else data!!.content!!
for (i in 4 until length) str += "*"
summary.text = String.format(STRING_NUMBER_FORMAT, str, data!!.optional)
button.setImageResource(R.drawable.ic_visibility_black_24dp)
button.tag = false
} else {
button.setImageResource(R.drawable.ic_visibility_off_black_24dp)
summary.text = String.format(STRING_NUMBER_FORMAT, data!!.content, data!!.optional)
button.tag = true
}
}
itemView.setOnLongClickListener { v ->
ClipboardUtils.putString(v.context, data!!.content!!)
Snackbar.make((v.context as Activity).findViewById(R.id.coordinator_layout),
R.string.toast_copied_code,
Snackbar.LENGTH_LONG
).show()
true
}
}
}
}
companion object {
private const val STRING_NUMBER_FORMAT = "%1\$s (%2\$s)"
}
}
| gpl-3.0 | c1f5014cbb7c09274237c4a07daff831 | 45.089109 | 108 | 0.583673 | 4.973291 | false | false | false | false |
SUPERCILEX/Robot-Scouter | app/android-base/src/main/java/com/supercilex/robotscouter/HomeActivity.kt | 1 | 19693 | package com.supercilex.robotscouter
import android.content.Intent
import android.graphics.Outline
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewOutlineProvider
import androidx.activity.viewModels
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.core.net.toUri
import androidx.core.view.GravityCompat
import androidx.core.view.children
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.fragment.app.commit
import androidx.fragment.app.commitNow
import androidx.transition.TransitionInflater
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.material.navigation.NavigationView
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import com.google.android.play.core.install.model.AppUpdateType
import com.google.android.play.core.install.model.UpdateAvailability
import com.google.firebase.dynamiclinks.FirebaseDynamicLinks
import com.supercilex.robotscouter.core.RobotScouter
import com.supercilex.robotscouter.core.data.SCOUT_ARGS_KEY
import com.supercilex.robotscouter.core.data.TEMPLATE_ARGS_KEY
import com.supercilex.robotscouter.core.data.asLiveData
import com.supercilex.robotscouter.core.data.enableAutoScout
import com.supercilex.robotscouter.core.data.getTeam
import com.supercilex.robotscouter.core.data.isSignedIn
import com.supercilex.robotscouter.core.data.isTemplateEditingAllowed
import com.supercilex.robotscouter.core.data.logFailures
import com.supercilex.robotscouter.core.data.logSelect
import com.supercilex.robotscouter.core.data.minimumAppVersion
import com.supercilex.robotscouter.core.data.prefs
import com.supercilex.robotscouter.core.fastAddOnSuccessListener
import com.supercilex.robotscouter.core.fullVersionCode
import com.supercilex.robotscouter.core.longToast
import com.supercilex.robotscouter.core.model.Team
import com.supercilex.robotscouter.core.ui.ActivityBase
import com.supercilex.robotscouter.core.ui.hasPermsOnActivityResult
import com.supercilex.robotscouter.core.ui.hasPermsOnRequestPermissionsResult
import com.supercilex.robotscouter.core.ui.isInTabletMode
import com.supercilex.robotscouter.core.ui.showStoreListing
import com.supercilex.robotscouter.core.ui.transitionAnimationDuration
import com.supercilex.robotscouter.core.unsafeLazy
import com.supercilex.robotscouter.shared.launchUrl
import kotlinx.android.synthetic.main.activity_home_base.*
import kotlinx.android.synthetic.main.activity_home_content.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
internal class HomeActivity : ActivityBase(), NavigationView.OnNavigationItemSelectedListener,
TeamSelectionListener, DrawerToggler, TeamExporter, SignInResolver {
private val authHelper by unsafeLazy { AuthHelper(this) }
private val moduleRequestHolder by viewModels<ModuleRequestHolder>()
private val updateManager by lazy { AppUpdateManagerFactory.create(this) }
private val drawerToggle by unsafeLazy {
ActionBarDrawerToggle(
this,
drawerLayout,
toolbar,
R.string.navigation_drawer_open_desc,
R.string.navigation_drawer_close_desc
)
}
/**
* Properly handling tablet mode changes is one of the hardest problems to solve in Robot
* Scouter. The main issue arises from there being so many dependent fragment transactions and
* simultaneous UI changes. These will be broken down here.
*
* ### Phone -> tablet
*
* 1. In the activity's super.onCreate, the [IntegratedScoutListFragmentCompanion]'s
* [Fragment.onCreate] will realize it's no longer valid and must be replaced by its
* [TabletScoutListFragmentCompanion] counterpart. The fragment will call [onTeamSelected]
* which will kick of a series of transactions.
* 1. The back stack will be popped to remove the integrated fragment.
* 1. The tablet fragment will replace anything in the [R.id.scoutList] container.
* 1. The [R.id.content] container will be forced to be a [TeamListFragmentCompanion].
* 1. The bottom nav will attempt to be updated to point to the teams fragment, but it will be
* null b/c we're still in [onCreate] and haven't called [setContentView] yet.
* 1. This flag will be flipped which re-triggers a bottom nav update in [onStart].
*
* ### Tablet -> phone
*
* Everything is the same as above except for the fragment transactions.
*
* 1. The integrated fragment is still popped.
* 1. A new integrated fragment is created and added while the teams fragment is detached. These
* transactions are now added to the back stack.
* 1. Another transaction is created to remove any non-team fragments currently in the content
* container which isn't added to the back stack.
*/
private var bottomNavStatusNeedsUpdatingHack = false
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.RobotScouter_NoActionBar_TransparentStatusBar)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
if (savedInstanceState == null) {
supportFragmentManager.commit {
add(R.id.content,
TeamListFragmentCompanion().getInstance(supportFragmentManager),
TeamListFragmentCompanion.TAG)
}
} else if (bottomNavStatusNeedsUpdatingHack) {
updateBottomNavStatusAfterTeamSelection()
}
moduleRequestHolder.onSuccess.observe(this) { (comp, args) ->
if (
comp is ExportServiceCompanion &&
@Suppress("UNCHECKED_CAST") // We know our inputs
comp.exportAndShareSpreadSheet(this, args.single() as List<Team>) &&
onBackPressedDispatcher.hasEnabledCallbacks()
) onBackPressedDispatcher.onBackPressed()
}
setSupportActionBar(toolbar)
drawerLayout.addDrawerListener(drawerToggle)
drawerToggle.syncState()
drawer.setNavigationItemSelectedListener(this)
if (enableAutoScout) bottomNavigation.menu.findItem(R.id.autoScout).isVisible = true
bottomNavigation.setOnNavigationItemSelectedListener listener@{
if (bottomNavStatusNeedsUpdatingHack) return@listener true
val manager = supportFragmentManager
val currentFragment = checkNotNull(manager.findFragmentById(R.id.content))
val newTag = destIdToTag(it.itemId)
if (currentFragment.tag == newTag) {
(currentFragment as? Refreshable)?.refresh()
return@listener true
}
if (
it.itemId == R.id.teams &&
currentFragment.tag == ScoutListFragmentCompanionBase.TAG
) {
manager.popBackStack()
return@listener true
}
appBar.setExpanded(true)
manager.commitNow {
val newFragment = manager.destTagToFragment(newTag)
setCustomAnimations(R.anim.pop_fade_in, R.anim.fade_out)
detach(currentFragment)
addOrAttachContent(newFragment, newTag)
}
true
}
prefs.asLiveData().observe(this) {
bottomNavigation.menu.findItem(R.id.templates).isEnabled = isTemplateEditingAllowed
}
if (isInTabletMode() && Build.VERSION.SDK_INT >= 21) {
scoutList.outlineProvider = object : ViewOutlineProvider() {
private val padding = resources.getDimensionPixelSize(R.dimen.spacing_mini)
override fun getOutline(view: View, outline: Outline) {
// Without negative starting values, the outline will show up on top of the
// toolbar.
outline.setRect(-bottomNavigation.width - 100, -100, padding, view.height)
}
}
}
handleModuleInstalls(moduleInstallProgress)
authHelper.init().logFailures("authInit").addOnSuccessListener(this) {
handleIntent()
}
GoogleApiAvailability.getInstance().makeGooglePlayServicesAvailable(this)
}
private fun destIdToTag(id: Int) = when (id) {
R.id.teams -> TeamListFragmentCompanion.TAG
R.id.autoScout -> AutoScoutFragmentCompanion.TAG
R.id.templates -> TemplateListFragmentCompanion.TAG
else -> error("Unknown id: $id")
}
private fun FragmentManager.destTagToFragment(tag: String) = when (tag) {
TeamListFragmentCompanion.TAG -> IntegratedScoutListFragmentCompanion().getInstance(this)
?: TeamListFragmentCompanion().getInstance(this)
AutoScoutFragmentCompanion.TAG -> AutoScoutFragmentCompanion().getInstance(this)
TemplateListFragmentCompanion.TAG -> TemplateListFragmentCompanion().getInstance(
this, intent.extras?.getBundle(TEMPLATE_ARGS_KEY))
else -> error("Unknown tag: $tag")
}
private fun FragmentTransaction.addOrAttachContent(
fragment: Fragment,
tag: String
) = if (fragment.isDetached) {
attach(fragment)
} else {
add(R.id.content, fragment, tag)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
this.intent = intent
handleIntent()
}
override fun onStart() {
super.onStart()
if (!BuildConfig.DEBUG && fullVersionCode < minimumAppVersion) {
updateManager.appUpdateInfo.asRealTask().fastAddOnSuccessListener(this) {
val availability = it.updateAvailability()
val isUpdateAvailable = availability == UpdateAvailability.UPDATE_AVAILABLE ||
availability == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS
if (isUpdateAvailable && it.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)) {
updateManager.startUpdateFlowForResult(it, AppUpdateType.IMMEDIATE, this, 1958)
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.home_menu, menu)
authHelper.initMenu(menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem) = if (item.itemId == R.id.action_sign_in) {
authHelper.signIn()
true
} else {
false
}
override fun toggle(enabled: Boolean) {
drawerToggle.isDrawerIndicatorEnabled = enabled
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
authHelper.onActivityResult(requestCode, resultCode, data)
if (hasPermsOnActivityResult(ExportServiceCompanion.perms, requestCode)) {
export()
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (val id = item.itemId) {
R.id.action_donate_patreon ->
launchUrl(this, "https://www.patreon.com/SUPERCILEX".toUri())
else -> runIfSignedIn {
when (id) {
R.id.action_export_all_teams -> export()
R.id.action_view_trash -> startActivity(TrashActivityCompanion().createIntent())
R.id.action_settings -> startActivity(SettingsActivityCompanion().createIntent())
else -> error("Unknown item id: $id")
}
}
}
drawerLayout.closeDrawer(GravityCompat.START)
return false
}
override fun onShortcut(keyCode: Int, event: KeyEvent): Boolean {
when (keyCode) {
KeyEvent.KEYCODE_E -> export()
else -> return false
}
return true
}
override fun onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START)
} else {
val homeId = bottomNavigation.menu.children.first().itemId
if (bottomNavigation.selectedItemId == homeId) {
super.onBackPressed()
} else {
bottomNavigation.selectedItemId = homeId
}
}
}
/** @see bottomNavStatusNeedsUpdatingHack */
override fun onTeamSelected(args: Bundle, transitionView: View?) {
args.getTeam().logSelect()
val manager = supportFragmentManager
val existingScoutFragment = IntegratedScoutListFragmentCompanion().getInstance(manager)
val existingContainerFragment = checkNotNull(manager.findFragmentById(R.id.content))
if (existingScoutFragment != null) manager.popBackStack()
if (isInTabletMode()) {
manager.commit {
setCustomAnimations(R.anim.pop_fade_in_right, R.anim.fade_out)
replace(R.id.scoutList,
TabletScoutListFragmentCompanion().newInstance(args),
ScoutListFragmentCompanionBase.TAG)
val teamsTag = TeamListFragmentCompanion.TAG
if (existingContainerFragment.tag != teamsTag) {
addOrAttachContent(TeamListFragmentCompanion().getInstance(manager), teamsTag)
detach(existingContainerFragment)
}
}
} else {
manager.commit {
val fragment = IntegratedScoutListFragmentCompanion().newInstance(args)
setReorderingAllowed(true)
if (existingScoutFragment != null) {
setReorderingAllowed(false)
} else if (
transitionView != null &&
Build.VERSION.SDK_INT >= 21
) {
addSharedElement(transitionView, "media")
fragment.sharedElementEnterTransition = fragmentTransition.clone()
fragment.sharedElementReturnTransition = null
}
setCustomAnimations(
R.anim.pop_fade_in,
R.anim.fade_out,
R.anim.fade_in,
R.anim.pop_fade_out
)
add(R.id.content, fragment, ScoutListFragmentCompanionBase.TAG)
detach(TeamListFragmentCompanion().getInstance(manager))
addToBackStack(null)
}
// Don't include detaching non-team fragments in the back stack
if (
existingScoutFragment == null &&
existingContainerFragment.tag != TeamListFragmentCompanion.TAG
) manager.commit { detach(existingContainerFragment) }
}
updateBottomNavStatusAfterTeamSelection()
}
/** @see bottomNavStatusNeedsUpdatingHack */
private fun updateBottomNavStatusAfterTeamSelection() {
bottomNavStatusNeedsUpdatingHack = true
val nav = bottomNavigation ?: return
nav.post {
nav.selectedItemId = R.id.teams
bottomNavStatusNeedsUpdatingHack = false
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (
requestCode == ExportServiceCompanion.PERMS_RC &&
hasPermsOnRequestPermissionsResult(permissions, grantResults)
) {
export()
}
}
override fun onTrimMemory(level: Int) {
super.onTrimMemory(level)
if (level == TRIM_MEMORY_MODERATE || level == TRIM_MEMORY_RUNNING_LOW) {
supportFragmentManager.apply {
val currentDestId = bottomNavigation.selectedItemId
val unfocusedFragments = bottomNavigation.menu.children
.filterNot { it.itemId == currentDestId }
.map(MenuItem::getItemId)
.map(::destIdToTag)
.map(::findFragmentByTag)
.filterNotNull()
.toList()
commit(allowStateLoss = true) { for (f in unfocusedFragments) remove(f) }
}
}
}
override fun export() {
val selectedTeams = supportFragmentManager.fragments
.filterIsInstance<SelectedTeamsRetriever>()
.map { it.selectedTeams }
.singleOrNull { it.isNotEmpty() }
.orEmpty()
moduleRequestHolder += ExportServiceCompanion().logFailures("downloadExportModule") to
listOf(selectedTeams)
}
private fun handleIntent() {
intent.extras?.apply {
when {
containsKey(SCOUT_ARGS_KEY) ->
onTeamSelected(checkNotNull(getBundle(SCOUT_ARGS_KEY)))
containsKey(TEMPLATE_ARGS_KEY) -> {
val args = checkNotNull(getBundle(TEMPLATE_ARGS_KEY))
if (bottomNavigation.selectedItemId == R.id.templates) {
// Handles args
TemplateListFragmentCompanion().getInstance(supportFragmentManager, args)
} else {
bottomNavigation.selectedItemId = R.id.templates
}
}
containsKey(DONATE_EXTRA) ->
launchUrl(this@HomeActivity, "https://www.patreon.com/SUPERCILEX".toUri())
containsKey(UPDATE_EXTRA) -> showStoreListing()
}
}
intent.data?.let {
if (it.toString() == ADD_SCOUT_INTENT) runIfSignedIn {
NewTeamDialogCompanion().show(supportFragmentManager)
}
if (it.toString() == EXPORT_ALL_TEAMS_INTENT) runIfSignedIn { export() }
}
// When the app is installed through a dynamic link, we can only get it from the launcher
// activity so we have to check to see if there are any pending links and then forward those
// along to the LinkReceiverActivity
FirebaseDynamicLinks.getInstance().getDynamicLink(intent).addOnSuccessListener(this) {
it?.link?.let {
startActivity(Intent(this, LinkReceiverActivity::class.java).setData(it))
}
}.addOnFailureListener(this) {
longToast(R.string.link_uri_parse_error)
}.logFailures("getDynamicLink")
intent = Intent() // Consume Intent
}
override fun showSignInResolution() {
authHelper.showSignInResolution()
}
private inline fun runIfSignedIn(block: () -> Unit) =
if (isSignedIn) block() else showSignInResolution()
private companion object {
const val DONATE_EXTRA = "donate_extra"
const val UPDATE_EXTRA = "update_extra"
const val ADD_SCOUT_INTENT = "add_scout"
const val EXPORT_ALL_TEAMS_INTENT = "export_all_teams"
val fragmentTransition by unsafeLazy {
TransitionInflater.from(RobotScouter)
.inflateTransition(android.R.transition.move)
.setDuration(transitionAnimationDuration)
}
init {
if (Build.VERSION.SDK_INT >= 21) {
GlobalScope.launch { fragmentTransition }
}
}
}
}
| gpl-3.0 | f5a8d16f68585fd7446549095f4aa519 | 40.198745 | 101 | 0.64297 | 5.089946 | false | false | false | false |
lehaSVV2009/dnd | api/src/main/kotlin/kadet/dnd/api/model/Skills.kt | 1 | 1250 | package kadet.dnd.api.model
class Skills {
/**
* Акробатика
*/
val acrobatics: Int = 0
/**
* Атлетика
*/
val athletics: Int = 0
/**
* Внимательность
*/
val perception: Int = 0
/**
* Воровство
*/
val stealing: Int = 0
/**
* Выносливость
*/
val endurance: Int = 0
/**
* Запугивание
*/
val intimidation: Int = 0
/**
* Знание улиц
*/
val investigation: Int = 0
/**
* История
*/
val history: Int = 0
/**
* Магия
*/
val magic: Int = 0
/**
* Обман
*/
val deception: Int = 0
/**
* Переговоры
*/
val persuasion: Int = 0
/**
* Подземелья
*/
val dungeons: Int = 0
/**
* Природа
*/
val nature: Int = 0
/**
* Религия
*/
val religion: Int = 0
/**
* Скрытность
*/
val stealth: Int = 0
/**
* Проницательность
*/
val insights: Int = 0
/**
* Целительство
*/
val medicine: Int = 0
} | mit | 1f53d9feeb5dec5a88fdbd01fb5608eb | 11.224719 | 30 | 0.425943 | 3.070621 | false | false | false | false |
SergeyLukashevich/elektrum-lv-unofficial-api | cli/src/main/kotlin/settings/Password.kt | 1 | 3579 | package settings
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import oshi.SystemInfo
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.nio.charset.Charset
import java.security.GeneralSecurityException
import java.security.NoSuchAlgorithmException
import java.security.spec.InvalidKeySpecException
import java.util.*
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
const val encryptionPass = "Y2lwaGVyLmluaXQoQ2lwaGVyLkVOQ1JZUFRfTU9ERSwga2V5KQ"
data class Password(var plain: String = "", var encrypted: String = "") {
private val log: Logger = LoggerFactory.getLogger(this::class.java.canonicalName)
fun process(): Boolean {
var changed = false
val key = createSecretKey(encryptionPass.toCharArray(), calcSalt().toByteArray(),
iterationCount = 40000, keyLength = 128)
if (plain.isEmpty() && !encrypted.isEmpty()) {
plain = decrypt(encrypted, key)
} else if (!plain.isEmpty()) {
encrypted = encrypt(plain, key)
changed = true
} else {
throw IllegalArgumentException("Password is empty")
}
return changed
}
private fun calcSalt(): String {
try {
return SystemInfo().hardware.processor.processorID!!
} catch (e: Exception) {
log.warn("Fail to calculate salt for passwords encryption", e)
return "85f74d7b93cb8cbd74ac5a7f53a00b80"
}
}
@Throws(GeneralSecurityException::class, UnsupportedEncodingException::class)
private fun encrypt(password: String, key: SecretKeySpec): String {
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, key)
val parameters = cipher.parameters
val ivParameterSpec = parameters.getParameterSpec(IvParameterSpec::class.java)
val cryptoText = cipher.doFinal(password.toByteArray(charset("UTF-8")))
val iv = ivParameterSpec.iv
return base64Encode(iv) + ":" + base64Encode(cryptoText)
}
@Throws(GeneralSecurityException::class, IOException::class)
private fun decrypt(string: String, key: SecretKeySpec): String {
val iv = string.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
val property = string.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1]
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(base64Decode(iv)))
val array: ByteArray = cipher.doFinal(base64Decode(property))
return array.toString(Charset.forName("UTF-8"))
}
@Throws(NoSuchAlgorithmException::class, InvalidKeySpecException::class)
private fun createSecretKey(password: CharArray, salt: ByteArray, iterationCount: Int, keyLength: Int)
: SecretKeySpec {
val keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512")
val keySpec = PBEKeySpec(password, salt, iterationCount, keyLength)
val keyTmp = keyFactory.generateSecret(keySpec)
return SecretKeySpec(keyTmp.encoded, "AES")
}
private fun base64Encode(bytes: ByteArray): String {
return Base64.getEncoder().encodeToString(bytes)
}
@Throws(IOException::class)
private fun base64Decode(property: String): ByteArray {
return Base64.getDecoder().decode(property)
}
}
| apache-2.0 | 2eea53714a7d714fc4079fc01df7f12c | 38.766667 | 106 | 0.696004 | 4.457036 | false | false | false | false |
adelnizamutdinov/headphone-reminder | app/src/main/kotlin/common/view/ViewPagerAdapter.kt | 1 | 896 | package common.view
import android.support.v4.view.PagerAdapter
import android.view.View
import android.view.ViewGroup
import rx.Observer
class ViewPagerAdapter(val cnt: Int,
val detaches: Observer<View>,
val inflates: (ViewGroup, Int) -> View,
val titles: (Int) -> CharSequence) : PagerAdapter() {
override fun isViewFromObject(view: View?, `object`: Any?): Boolean = view === `object`
override fun getCount(): Int = cnt
override fun instantiateItem(container: ViewGroup, position: Int): Any? =
inflates(container, position).apply { container.addView(this) }
override fun getPageTitle(position: Int): CharSequence? = titles(position)
override fun destroyItem(container: ViewGroup, position: Int, obj: Any): Unit {
if (obj is View) {
container.removeView(obj)
detaches.onNext(obj)
}
}
} | mit | dca23e7b8c627528b982d34198f801ce | 36.375 | 89 | 0.668527 | 4.307692 | false | false | false | false |
AllanWang/Frost-for-Facebook | app/src/main/kotlin/com/pitchedapps/frost/facebook/parsers/MessageParser.kt | 1 | 5290 | /*
* Copyright 2018 Allan Wang
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pitchedapps.frost.facebook.parsers
import com.pitchedapps.frost.db.CookieEntity
import com.pitchedapps.frost.facebook.FB_EPOCH_MATCHER
import com.pitchedapps.frost.facebook.FB_MESSAGE_NOTIF_ID_MATCHER
import com.pitchedapps.frost.facebook.FbItem
import com.pitchedapps.frost.facebook.formattedFbUrl
import com.pitchedapps.frost.facebook.get
import com.pitchedapps.frost.services.NotificationContent
import com.pitchedapps.frost.utils.L
import com.pitchedapps.frost.utils.urlEncode
import org.apache.commons.text.StringEscapeUtils
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
/**
* Created by Allan Wang on 2017-10-06.
*
* In Facebook, messages are passed through scripts and loaded into view via react afterwards We can
* parse out the content we want directly and load it ourselves
*/
object MessageParser : FrostParser<FrostMessages> by MessageParserImpl() {
fun queryUser(cookie: String?, name: String) =
parseFromUrl(cookie, "${FbItem.MESSAGES.url}/?q=${name.urlEncode()}")
}
data class FrostMessages(
val threads: List<FrostThread>,
val seeMore: FrostLink?,
val extraLinks: List<FrostLink>
) : ParseNotification {
override val isEmpty: Boolean
get() = threads.isEmpty()
override fun toString() =
StringBuilder()
.apply {
append("FrostMessages {\n")
append(threads.toJsonString("threads", 1))
append("\tsee more: $seeMore\n")
append(extraLinks.toJsonString("extra links", 1))
append("}")
}
.toString()
override fun getUnreadNotifications(data: CookieEntity) =
threads
.asSequence()
.filter(FrostThread::unread)
.map {
with(it) {
NotificationContent(
data = data,
id = id,
href = url,
title = title,
text = content ?: "",
timestamp = time,
profileUrl = img,
unread = unread
)
}
}
.toList()
}
/**
* [id] user/thread id, or current time fallback [img] parsed url for profile img [time] time of
* message [url] link to thread [unread] true if image is unread, false otherwise [content] optional
* string for thread
*/
data class FrostThread(
val id: Long,
val img: String?,
val title: String,
val time: Long,
val url: String,
val unread: Boolean,
val content: String?,
val contentImgUrl: String?
)
private class MessageParserImpl : FrostParserBase<FrostMessages>(true) {
override var nameRes = FbItem.MESSAGES.titleId
override val url = FbItem.MESSAGES.url
override fun textToDoc(text: String): Document? {
var content = StringEscapeUtils.unescapeEcmaScript(text)
val begin = content.indexOf("id=\"threadlist_rows\"")
if (begin <= 0) {
L.d { "Threadlist not found" }
return null
}
content = content.substring(begin)
val end = content.indexOf("</script>")
if (end <= 0) {
L.d { "Script tail not found" }
return null
}
content = content.substring(0, end).substringBeforeLast("</div>")
return Jsoup.parseBodyFragment("<div $content")
}
override fun parseImpl(doc: Document): FrostMessages? {
val threadList = doc.getElementById("threadlist_rows") ?: return null
val threads: List<FrostThread> =
threadList
.getElementsByAttributeValueMatching("id", ".*${FB_MESSAGE_NOTIF_ID_MATCHER.pattern}.*")
.mapNotNull(this::parseMessage)
val seeMore = parseLink(doc.getElementById("see_older_threads"))
val extraLinks =
threadList.nextElementSibling()?.select("a")?.mapNotNull(this::parseLink) ?: emptyList()
return FrostMessages(threads, seeMore, extraLinks)
}
private fun parseMessage(element: Element): FrostThread? {
val a = element.getElementsByTag("a").first() ?: return null
val abbr = element.getElementsByTag("abbr")
val epoch = FB_EPOCH_MATCHER.find(abbr.attr("data-store"))[1]?.toLongOrNull() ?: -1L
// fetch id
val id =
FB_MESSAGE_NOTIF_ID_MATCHER.find(element.id())[1]?.toLongOrNull()
?: System.currentTimeMillis() % FALLBACK_TIME_MOD
val snippet = element.select("span.snippet").firstOrNull()
val content = snippet?.text()?.trim()
val contentImg = snippet?.select("i[style*=url]")?.getStyleUrl()
val img = element.getInnerImgStyle()
return FrostThread(
id = id,
img = img,
title = a.text(),
time = epoch,
url = a.attr("href").formattedFbUrl,
unread = !element.hasClass("acw"),
content = content,
contentImgUrl = contentImg
)
}
}
| gpl-3.0 | 2e0ce47a57d1e8128879d6a6a3ae7fe7 | 32.0625 | 100 | 0.679395 | 3.995468 | false | false | false | false |
OurFriendIrony/MediaNotifier | app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/rawg/game/get/GameGetStore.kt | 1 | 1067 | package uk.co.ourfriendirony.medianotifier.clients.rawg.game.get
import com.fasterxml.jackson.annotation.*
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder("id", "name", "slug", "domain", "games_count", "image_background")
class GameGetStore {
@get:JsonProperty("id")
@set:JsonProperty("id")
@JsonProperty("id")
var id: Int? = null
@get:JsonProperty("name")
@set:JsonProperty("name")
@JsonProperty("name")
var name: String? = null
@get:JsonProperty("slug")
@set:JsonProperty("slug")
@JsonProperty("slug")
var slug: String? = null
@get:JsonProperty("domain")
@set:JsonProperty("domain")
@JsonProperty("domain")
var domain: String? = null
@get:JsonProperty("games_count")
@set:JsonProperty("games_count")
@JsonProperty("games_count")
var gamesCount: Int? = null
@get:JsonProperty("image_background")
@set:JsonProperty("image_background")
@JsonProperty("image_background")
var imageBackground: String? = null
} | apache-2.0 | 60305c3a7e191abc4e0dc5d0723fdf81 | 27.105263 | 85 | 0.68135 | 3.865942 | false | false | false | false |
toastkidjp/Yobidashi_kt | app/src/main/java/jp/toastkid/yobidashi/settings/view/screen/ColorSettingUi.kt | 1 | 10767 | /*
* Copyright (c) 2022 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.settings.view.screen
import androidx.activity.ComponentActivity
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.Icon
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.model.OptionMenu
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.ui.dialog.DestructiveChangeConfirmDialog
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.libs.db.DatabaseFinder
import jp.toastkid.yobidashi.settings.color.DefaultColorInsertion
import jp.toastkid.yobidashi.settings.color.RandomColorInsertion
import jp.toastkid.yobidashi.settings.color.SavedColor
import jp.toastkid.yobidashi.settings.color.SavedColorRepository
import jp.toastkid.yobidashi.settings.view.ColorPaletteUi
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun ColorSettingUi() {
val context = LocalContext.current
val preferenceApplier = PreferenceApplier(context)
val repository = DatabaseFinder().invoke(context).savedColorRepository()
val colorPair = preferenceApplier.colorPair()
val initialBgColor = colorPair.bgColor()
val initialFontColor = colorPair.fontColor()
val coroutineScope = rememberCoroutineScope()
val contentViewModel = (context as? ViewModelStoreOwner)?.let {
viewModel(ContentViewModel::class.java, it)
}
val savedColors = remember { mutableStateListOf<SavedColor>() }
val currentBackgroundColor =
remember { mutableStateOf(Color(preferenceApplier.color)) }
val currentFontColor =
remember { mutableStateOf(Color(preferenceApplier.fontColor)) }
val openConfirmDialog = remember { mutableStateOf(false) }
Column(
modifier = Modifier.padding(start = 8.dp, end = 8.dp, top = 8.dp)
) {
ColorPaletteUi(
currentBackgroundColor,
currentFontColor,
initialBgColor,
initialFontColor,
onCommit = {
val bgColor = currentBackgroundColor.value
val fontColor = currentFontColor.value
commitNewColor(
preferenceApplier,
currentBackgroundColor,
currentFontColor,
bgColor,
fontColor
)
contentViewModel?.snackShort(R.string.settings_color_done_commit)
contentViewModel?.refresh()
CoroutineScope(Dispatchers.IO).launch {
val savedColor =
SavedColor.make(
bgColor.toArgb(),
fontColor.toArgb()
)
val newId = repository.add(savedColor)
savedColor.id = newId
savedColors.add(savedColor)
}
},
onReset = {
commitNewColor(
preferenceApplier,
currentBackgroundColor,
currentFontColor,
Color(initialBgColor),
Color(initialFontColor)
)
contentViewModel?.snackShort(R.string.settings_color_done_reset)
contentViewModel?.refresh()
}
)
if (savedColors.isNotEmpty()) {
Surface(
elevation = 4.dp,
modifier = Modifier
.height(44.dp)
.fillMaxWidth()
.padding(top = 8.dp)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(8.dp)
) {
Text(
stringResource(id = R.string.settings_color_saved_title),
fontSize = 18.sp
)
}
}
}
LazyVerticalGrid(columns = GridCells.Fixed(3)) {
items(savedColors, { it.id }) { savedColor ->
Surface(
elevation = 4.dp,
modifier = Modifier
.clickable {
commitNewColor(
preferenceApplier,
currentBackgroundColor,
currentFontColor,
Color(savedColor.bgColor),
Color(savedColor.fontColor)
)
contentViewModel?.snackShort(R.string.settings_color_done_commit)
contentViewModel?.refresh()
}
.weight(1f)
.padding(8.dp)
.animateItemPlacement()
) {
Box(
modifier = Modifier
.height(100.dp)
.background(Color(savedColor.bgColor))
.padding(8.dp)
) {
Text(
text = stringResource(id = R.string.sample_a),
color = Color(savedColor.fontColor),
modifier = Modifier.align(
Alignment.Center
)
)
Icon(
painterResource(id = R.drawable.ic_remove_circle),
contentDescription = stringResource(
id = R.string.delete
),
modifier = Modifier
.width(40.dp)
.height(40.dp)
.clickable {
coroutineScope.launch {
withContext(Dispatchers.IO) {
repository.delete(savedColor)
savedColors.remove(savedColor)
}
}
}
.align(Alignment.TopEnd))
}
}
}
}
}
viewModel(modelClass = ContentViewModel::class.java).optionMenus(
OptionMenu(
titleId = R.string.title_clear_saved_color,
action = {
openConfirmDialog.value = true
}
),
OptionMenu(
titleId = R.string.title_add_recommended_colors,
action = {
DefaultColorInsertion().insert(context)
coroutineScope.launch {
reload(repository, savedColors)
}
}
),
OptionMenu(
titleId = R.string.title_add_random,
action = {
RandomColorInsertion(repository)() {
coroutineScope.launch {
reload(repository, savedColors)
}
}
contentViewModel?.snackShort(R.string.done_addition)
}
)
)
DestructiveChangeConfirmDialog(
openConfirmDialog,
titleId = R.string.title_clear_saved_color
) {
CoroutineScope(Dispatchers.Main).launch {
withContext(Dispatchers.IO) {
DatabaseFinder().invoke(context).searchHistoryRepository().deleteAll()
}
(context as? ComponentActivity)?.let { activity ->
ViewModelProvider(activity).get(ContentViewModel::class.java)
.snackShort(R.string.settings_color_delete)
}
}
}
LaunchedEffect("initial_load") {
reload(repository, savedColors)
}
}
private suspend fun reload(
repository: SavedColorRepository,
savedColors: SnapshotStateList<SavedColor>
) {
withContext(Dispatchers.IO) {
savedColors.clear()
savedColors.addAll(
repository.findAll()
)
}
}
/**
* Commit new color.
*
* @param bgColor Background color int
* @param fontColor Font color int
*/
private fun commitNewColor(
preferenceApplier: PreferenceApplier,
currentBackgroundColor: MutableState<Color>,
currentFontColor: MutableState<Color>,
bgColor: Color,
fontColor: Color
) {
preferenceApplier.color = bgColor.toArgb()
preferenceApplier.fontColor = fontColor.toArgb()
currentBackgroundColor.value = bgColor
currentFontColor.value = fontColor
} | epl-1.0 | ef401752acf2e85c64040518dc5d802e | 35.378378 | 93 | 0.575091 | 5.654937 | false | false | false | false |
KotlinBy/awesome-kotlin | src/main/kotlin/link/kotlin/scripts/utils/Utils.kt | 1 | 1995 | package link.kotlin.scripts.utils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import java.time.Duration
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
inline fun <reified T> logger(): Logger = LoggerFactory.getLogger(T::class.java)
@Suppress("NOTHING_TO_INLINE")
inline fun logger(noinline lambda: () -> Unit): Logger {
val name = lambda.javaClass.name
val contextName = when {
name.contains("Kt$") -> name.substringBefore("Kt$")
name.contains("$") -> name.substringBefore("$")
else -> name
}
return LoggerFactory.getLogger(contextName)
}
fun parseInstant(date: String): LocalDateTime {
return LocalDateTime.ofInstant(Instant.parse(date), ZoneId.of("UTC"))
}
@Suppress("ObjectLiteralToLambda")
inline fun <reified T : Any> callLogger(instance: T): T {
return Proxy.newProxyInstance(
T::class.java.classLoader,
arrayOf(T::class.java),
object : InvocationHandler {
override fun invoke(proxy: Any, method: Method, args: Array<out Any>?): Any? {
val log = logger<T>()
log.info("Start: ${method.name}.")
val start = System.nanoTime()
val result: Any? = try {
if (args != null) {
method.invoke(instance, *args)
} else {
method.invoke(instance)
}
} catch (e: RuntimeException) {
throw e
} catch (e: Exception) {
throw RuntimeException(e)
}
val total = System.nanoTime() - start
val duration = Duration.ofNanos(total).seconds
log.info("Done: ${method.name}. Time taken: ${duration}s")
return result
}
}
) as T
}
| apache-2.0 | 988d1ddf8a7ed6e94bf97fc16c40dcc5 | 31.177419 | 90 | 0.579449 | 4.483146 | false | false | false | false |
orbit/orbit | src/orbit-client/src/main/kotlin/orbit/client/addressable/AddressableProxy.kt | 1 | 2521 | /*
Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved.
This file is part of the Orbit Project <https://www.orbit.cloud>.
See license in LICENSE.
*/
package orbit.client.addressable
import orbit.client.util.DeferredWrappers
import orbit.shared.addressable.AddressableInvocation
import orbit.shared.addressable.AddressableReference
import orbit.shared.addressable.Key
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
internal class AddressableProxy(
private val reference: AddressableReference,
private val invocationSystem: InvocationSystem
) : InvocationHandler {
override fun invoke(proxy: Any, method: Method, args: Array<Any?>?): Any {
val isSuspended = args?.lastOrNull() is Continuation<*>
val continuation = (if (isSuspended) {
args!!.last()
} else null) as Continuation<Any?>?
val mappedArgs = (if (isSuspended) {
args!!.take(args.size - 1).toTypedArray()
} else args)
?.mapIndexed { index, value ->
value to method.parameterTypes[index]
}?.toTypedArray() ?: emptyArray()
val invocation = AddressableInvocation(
reference = reference,
method = method.name,
args = mappedArgs
)
val completion = invocationSystem.sendInvocation(invocation)
return if (isSuspended) {
completion.invokeOnCompletion { error ->
if (error == null)
continuation?.resume(completion.getCompleted())
else
continuation?.resumeWith(Result.failure(error))
}
kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED
} else {
DeferredWrappers.wrapReturn(completion, method)
}
}
}
internal class AddressableProxyFactory(
private val invocationSystem: InvocationSystem
) {
fun <T : Addressable> createProxy(interfaceClass: Class<T>, key: Key): T {
@Suppress("UNCHECKED_CAST")
return Proxy.newProxyInstance(
javaClass.classLoader,
arrayOf(interfaceClass),
AddressableProxy(
reference = AddressableReference(
type = interfaceClass.canonicalName,
key = key
),
invocationSystem = invocationSystem
)
) as T
}
}
| bsd-3-clause | 4f22a217e2e91c215a5a3e62ce8592b1 | 33.067568 | 78 | 0.632685 | 5.13442 | false | false | false | false |
http4k/http4k | http4k-resilience4j/src/test/kotlin/org/http/filter/ResilienceFiltersTest.kt | 1 | 5449 | package org.http.filter
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import io.github.resilience4j.bulkhead.Bulkhead
import io.github.resilience4j.bulkhead.BulkheadConfig
import io.github.resilience4j.circuitbreaker.CircuitBreaker.State.CLOSED
import io.github.resilience4j.circuitbreaker.CircuitBreaker.State.HALF_OPEN
import io.github.resilience4j.circuitbreaker.CircuitBreaker.State.OPEN
import io.github.resilience4j.circuitbreaker.CircuitBreaker.of
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig.SlidingWindowType
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig.SlidingWindowType.COUNT_BASED
import io.github.resilience4j.ratelimiter.RateLimiter
import io.github.resilience4j.ratelimiter.RateLimiterConfig
import io.github.resilience4j.retry.Retry
import io.github.resilience4j.retry.RetryConfig
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status.Companion.BAD_GATEWAY
import org.http4k.core.Status.Companion.INTERNAL_SERVER_ERROR
import org.http4k.core.Status.Companion.OK
import org.http4k.core.Status.Companion.SERVICE_UNAVAILABLE
import org.http4k.core.Status.Companion.TOO_MANY_REQUESTS
import org.http4k.core.then
import org.http4k.filter.ResilienceFilters
import org.http4k.filter.ResilienceFilters.Bulkheading
import org.http4k.filter.ResilienceFilters.CircuitBreak
import org.http4k.filter.ResilienceFilters.RateLimit
import org.http4k.filter.ResilienceFilters.RetryFailures
import org.http4k.hamkrest.hasStatus
import org.junit.jupiter.api.Test
import java.time.Duration
import java.util.ArrayDeque
import java.util.concurrent.CountDownLatch
import kotlin.concurrent.thread
class ResilienceFiltersTest {
@Test
fun `circuit break filter`() {
val minimumOpenStateApparently = Duration.ofSeconds(1)
val config = CircuitBreakerConfig.custom()
.slidingWindow(2, 2, COUNT_BASED)
.permittedNumberOfCallsInHalfOpenState(2)
.waitDurationInOpenState(minimumOpenStateApparently)
.build()
val responses = ArrayDeque<Response>().apply {
add(Response(INTERNAL_SERVER_ERROR))
add(Response(INTERNAL_SERVER_ERROR))
add(Response(OK))
add(Response(OK))
add(Response(OK))
}
val circuitBreaker = of("hello", config)
val circuited = CircuitBreak(circuitBreaker).then { responses.removeFirst() }
assertThat(circuitBreaker.state, equalTo(CLOSED))
assertThat(circuited(Request(GET, "/")), hasStatus(INTERNAL_SERVER_ERROR))
assertThat(circuited(Request(GET, "/")), hasStatus(INTERNAL_SERVER_ERROR))
assertThat(circuitBreaker.state, equalTo(OPEN))
assertThat(circuited(Request(GET, "/")), hasStatus(SERVICE_UNAVAILABLE))
Thread.sleep(1100)
assertThat(circuited(Request(GET, "/")), hasStatus(OK))
assertThat(circuitBreaker.state, equalTo(HALF_OPEN))
assertThat(circuited(Request(GET, "/")), hasStatus(OK))
assertThat(circuitBreaker.state, equalTo(CLOSED))
}
@Test
fun `retrying stops when successful result returned`() {
val config = RetryConfig.custom<RetryConfig>().intervalFunction { 0 }.build()
val retry = Retry.of("retrying", config)
val responses = ArrayDeque<Response>().apply {
add(Response(INTERNAL_SERVER_ERROR))
add(Response(OK))
}
val retrying = RetryFailures(retry).then {
responses.removeFirst()
}
assertThat(retrying(Request(GET, "/")).status, equalTo(OK))
}
@Test
fun `retrying eventually runs out and returns the last result`() {
val config = RetryConfig.custom<RetryConfig>().intervalFunction { 0 }.build()
val retry = Retry.of("retrying", config)
val responses = ArrayDeque<Response>().apply {
add(Response(INTERNAL_SERVER_ERROR))
add(Response(BAD_GATEWAY))
add(Response(SERVICE_UNAVAILABLE))
}
val retrying = RetryFailures(retry).then {
responses.removeFirst()
}
assertThat(retrying(Request(GET, "/")).status, equalTo(SERVICE_UNAVAILABLE))
}
@Test
fun `rate limit filter`() {
val config = RateLimiterConfig.custom()
.limitRefreshPeriod(Duration.ofSeconds(1))
.limitForPeriod(1)
.timeoutDuration(Duration.ofMillis(10)).build()
val rateLimits = RateLimit(RateLimiter.of("ratelimiter", config)).then { Response(OK) }
assertThat(rateLimits(Request(GET, "/")).status, equalTo(OK))
assertThat(rateLimits(Request(GET, "/")).status, equalTo(TOO_MANY_REQUESTS))
}
@Test
fun `bulkhead filter`() {
val config = BulkheadConfig.custom()
.maxConcurrentCalls(1)
.maxWaitDuration(Duration.ZERO)
.build()
val latch = CountDownLatch(1)
val bulkheading = Bulkheading(Bulkhead.of("bulkhead", config)).then {
latch.countDown()
Thread.sleep(1000)
Response(OK)
}
thread {
bulkheading(Request(GET, "/first"))
}
latch.await()
assertThat(bulkheading(Request(GET, "/second")).status, equalTo(TOO_MANY_REQUESTS))
}
}
| apache-2.0 | 0020a565111e30a9ba06469e85daf232 | 36.840278 | 95 | 0.699211 | 4.150038 | false | true | false | false |
Vavassor/Tusky | app/src/main/java/com/keylesspalace/tusky/util/Resource.kt | 1 | 383 | package com.keylesspalace.tusky.util
sealed class Resource<T>(open val data: T?)
class Loading<T> (override val data: T? = null) : Resource<T>(data)
class Success<T> (override val data: T? = null) : Resource<T>(data)
class Error<T> (override val data: T? = null,
val errorMessage: String? = null,
var consumed: Boolean = false
): Resource<T>(data) | gpl-3.0 | 1c37854e1e187e45b7c86b4e3355e220 | 31 | 67 | 0.64752 | 3.45045 | false | false | false | false |
rock3r/detekt | detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/LateinitUsageSpec.kt | 1 | 4157 | package io.gitlab.arturbosch.detekt.rules.bugs
import io.gitlab.arturbosch.detekt.test.compileAndLint
import io.gitlab.arturbosch.detekt.test.TestConfig
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatExceptionOfType
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.util.regex.PatternSyntaxException
class LateinitUsageSpec : Spek({
describe("LateinitUsage rule") {
val code = """
import kotlin.SinceKotlin
class SomeRandomTest {
lateinit var v1: String
@SinceKotlin("1.0.0") lateinit var v2: String
}
"""
it("should report lateinit usages") {
val findings = LateinitUsage().compileAndLint(code)
assertThat(findings).hasSize(2)
}
it("should only report lateinit property with no @SinceKotlin annotation") {
val findings = LateinitUsage(TestConfig(mapOf(LateinitUsage.EXCLUDE_ANNOTATED_PROPERTIES to listOf("SinceKotlin")))).compileAndLint(code)
assertThat(findings).hasSize(1)
}
it("should only report lateinit properties not matching kotlin.*") {
val findings = LateinitUsage(TestConfig(mapOf(LateinitUsage.EXCLUDE_ANNOTATED_PROPERTIES to listOf("kotlin.*")))).compileAndLint(code)
assertThat(findings).hasSize(1)
}
it("should only report lateinit properties matching kotlin.") {
val findings = LateinitUsage(TestConfig(mapOf(LateinitUsage.EXCLUDE_ANNOTATED_PROPERTIES to listOf("kotlin.")))).compileAndLint(code)
assertThat(findings).hasSize(1)
}
it("should only report lateinit properties matching kotlin.SinceKotlin") {
val config = TestConfig(mapOf(LateinitUsage.EXCLUDE_ANNOTATED_PROPERTIES to listOf("kotlin.SinceKotlin")))
val findings = LateinitUsage(config).compileAndLint(code)
assertThat(findings).hasSize(1)
}
it("should only report lateinit property with no @SinceKotlin annotation with config string") {
val findings = LateinitUsage(TestConfig(mapOf(LateinitUsage.EXCLUDE_ANNOTATED_PROPERTIES to "SinceKotlin"))).compileAndLint(code)
assertThat(findings).hasSize(1)
}
it("should only report lateinit property with no @SinceKotlin annotation containing whitespaces with config string") {
val findings = LateinitUsage(TestConfig(mapOf(LateinitUsage.EXCLUDE_ANNOTATED_PROPERTIES to " SinceKotlin "))).compileAndLint(code)
assertThat(findings).hasSize(1)
}
it("should report lateinit properties not matching the exclude pattern") {
val findings = LateinitUsage(TestConfig(mapOf(LateinitUsage.EXCLUDE_ANNOTATED_PROPERTIES to "IgnoreThis"))).compileAndLint(code)
assertThat(findings).hasSize(2)
}
it("should report lateinit properties when ignoreOnClassesPattern does not match") {
val findings = LateinitUsage(TestConfig(mapOf(LateinitUsage.IGNORE_ON_CLASSES_PATTERN to "[\\w]+Test1234"))).compileAndLint(code)
assertThat(findings).hasSize(2)
}
it("should not report lateinit properties when ignoreOnClassesPattern does match") {
val findings = LateinitUsage(TestConfig(mapOf(LateinitUsage.IGNORE_ON_CLASSES_PATTERN to "[\\w]+Test"))).compileAndLint(code)
assertThat(findings).isEmpty()
}
it("should fail when enabled with faulty regex pattern") {
assertThatExceptionOfType(PatternSyntaxException::class.java).isThrownBy {
LateinitUsage(TestConfig(mapOf(LateinitUsage.IGNORE_ON_CLASSES_PATTERN to "*Test"))).compileAndLint(code)
}
}
it("should not fail when disabled with faulty regex pattern") {
val configValues = mapOf("active" to "false", LateinitUsage.IGNORE_ON_CLASSES_PATTERN to "*Test")
val findings = LateinitUsage(TestConfig(configValues)).compileAndLint(code)
assertThat(findings).isEmpty()
}
}
})
| apache-2.0 | 26fb132254080f7877a209f9ba03515b | 47.337209 | 149 | 0.685109 | 4.896349 | false | true | false | false |
Aidanvii7/Toolbox | delegates-observable-rxjava/src/main/java/com/aidanvii/toolbox/delegates/observable/rxjava/RxFilterNotNullDecorator.kt | 1 | 2422 | package com.aidanvii.toolbox.delegates.observable.rxjava
import androidx.annotation.RestrictTo
import com.aidanvii.toolbox.delegates.observable.Functions
import io.reactivex.Observable
import kotlin.reflect.KProperty
/**
* Returns an [RxObservableProperty] that will only forward change events to subsequent property delegate
* decorators when the value is not null.
* @param ST the base type of the source observable ([RxObservableProperty.SourceTransformer]).
* @param TT the type on which this [RxObservableProperty] operates.
*/
fun <ST, TT> RxObservableProperty<ST, TT?>.filterNotNull() = RxFilterNotNullDecorator(this, Functions.alwaysTrue)
/**
* Returns an [RxObservableProperty] that will only forward change events to subsequent property delegate
* decorators when the value is not null and the given [predicate] is returns true.
* @param predicate a function that evaluates each item emitted by the receiver [RxObservableProperty],
* returning true if it passes the filter
* @param ST the base type of the source observable ([RxObservableProperty.SourceTransformer]).
* @param TT the type on which this [RxObservableProperty] operates.
*/
fun <ST, TT> RxObservableProperty<ST, TT?>.filterNotNullWith(
predicate: (TT) -> Boolean
) = RxFilterNotNullDecorator(this, Functions.forceUnwrap(predicate))
class RxFilterNotNullDecorator<ST, TT>(
private val decorated: RxObservableProperty<ST, TT?>,
private val predicate: (TT) -> Boolean
) : RxObservableProperty<ST, TT> {
override val observable: Observable<RxObservableProperty.ValueContainer<TT>>
get() = decorated.observable
.filter { it.newValue != null && predicate(it.newValue) }
.map { RxObservableProperty.ValueContainer(it.property, it.oldValue, it.newValue!!) }
@RestrictTo(RestrictTo.Scope.LIBRARY)
override fun subscribe(observable: Observable<*>) {
decorated.subscribe(observable)
}
override fun getValue(thisRef: Any?, property: KProperty<*>) =
decorated.getValue(thisRef, property)
override fun setValue(thisRef: Any?, property: KProperty<*>, value: ST) {
decorated.setValue(thisRef, property, value)
}
operator fun provideDelegate(thisRef: Any?, property: KProperty<*>): RxFilterNotNullDecorator<ST, TT> {
onProvideDelegate(thisRef, property)
subscribe(observable)
return this
}
} | apache-2.0 | 8edcaa184b6f6bff9a2803b26ea35200 | 43.054545 | 113 | 0.736168 | 4.630975 | false | false | false | false |
kesco/SlideBack | library/src/main/kotlin/com/kesco/adk/sliding/SlideLayout.kt | 1 | 13606 | package com.kesco.adk.sliding
import android.app.Activity
import android.app.ActivityOptions
import android.content.Context
import android.content.res.Resources
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.os.Build
import android.support.v4.view.ViewCompat
import android.support.v4.widget.ViewDragHelper
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
interface SlideListener {
fun onSlideStart()
fun onSlide(percent: Float, state: SlideState)
fun onSlideFinish()
}
enum class SlideState {
DRAGGING, IDLE, SETTLING
}
enum class SlideEdge(val edge: Int) {
NONE(-1), LEFT(0), RIGHT(1)
}
enum class SlideShadow(val type: Int) {
NONE(-1), EDGE(0), FULL(1)
}
internal fun val2Edge(edge: Int): SlideEdge {
return when (edge) {
0 -> SlideEdge.LEFT
1 -> SlideEdge.RIGHT
else -> SlideEdge.NONE
}
}
internal fun val2Shadow(type: Int): SlideShadow {
return when (type) {
0 -> SlideShadow.EDGE
1 -> SlideShadow.FULL
else -> SlideShadow.NONE
}
}
private fun _getColorCompat(res: Resources, id: Int) = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) res.getColor(id, null) else res.getColor(id)
private fun _drawShadowDrawable(ctx: Context, edge: SlideEdge): Drawable {
val shadow = GradientDrawable()
shadow.colors = intArrayOf(
_getColorCompat(ctx.resources, R.color.start_shadow_color),
_getColorCompat(ctx.resources, R.color.center_shadow_color),
_getColorCompat(ctx.resources, R.color.end_shadow_color))
shadow.shape = GradientDrawable.RECTANGLE
shadow.orientation = when (edge) {
SlideEdge.LEFT -> GradientDrawable.Orientation.LEFT_RIGHT
SlideEdge.RIGHT -> GradientDrawable.Orientation.RIGHT_LEFT
SlideEdge.NONE -> throw IllegalArgumentException("None has no shadow")
}
return shadow
}
private val SHADOW_COVER_COLOR = 0x99000000
private val TAG = "Slider"
class SlideLayout(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : FrameLayout(context, attrs, defStyleAttr) {
private var _slideHelper: ViewDragHelper
private var _vTarget: View? = null
private var _edge: SlideEdge
private var _inLayout = false
private var _slideViewLeft = 0
private var _slideViewTop = 0
private var _slideState = SlideState.IDLE
private var _shadow: SlideShadow
private var _slidePercent = 0f
private var _listener: SlideListener? = null
private var _shadowDrawable: Drawable? = null
private var _shadowWidth = 0
private var _shadowRect = Rect()
var edge: SlideEdge
set(value) {
_edge = value
_shadowDrawable = if (value == SlideEdge.NONE) null else _drawShadowDrawable(context, value)
}
get() = _edge
var shadow: SlideShadow
set(value) {
_shadow = value
_shadowWidth = if (_shadow != SlideShadow.NONE) context.resources.getDimensionPixelSize(R.dimen.shadow_width) else 0
}
get() = _shadow
var listener: SlideListener
set(l) {
_listener = l
}
get() {
if (_listener != null) {
return _listener as SlideListener
} else {
return object : SlideListener {
override fun onSlideStart() {
}
override fun onSlide(percent: Float, state: SlideState) {
}
override fun onSlideFinish() {
}
}
}
}
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
init {
val typeArray = context.theme.obtainStyledAttributes(attrs, R.styleable.SlideLayout, defStyleAttr, 0)
_edge = val2Edge(typeArray.getInt(R.styleable.SlideLayout_slide_edge, -1))
_shadow = val2Shadow(typeArray.getInt(R.styleable.SlideLayout_slide_shadow, -1))
typeArray.recycle()
_slideHelper = ViewDragHelper.create(this, 1.0f, SlideCallBack())
}
override fun requestLayout() {
if (!_inLayout) super.requestLayout()
}
private fun _ensureTarget() {
if (_vTarget == null) {
if (childCount > 1 && !isInEditMode) {
throw IllegalStateException("SlideLayout can host only one direct child")
}
_vTarget = getChildAt(0)
}
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
_inLayout = true
_ensureTarget()
val width = _vTarget?.measuredWidth ?: 0
val height = _vTarget?.measuredHeight ?: 0
_vTarget?.layout(_slideViewLeft, _slideViewTop, _slideViewLeft + width,
_slideViewTop + height)
_inLayout = false
}
override fun drawChild(canvas: Canvas?, child: View?, drawingTime: Long): Boolean {
val ret = super.drawChild(canvas, child, drawingTime)
_ensureTarget()
if (_shadow == SlideShadow.FULL) _drawCover(canvas)
if (_shadow != SlideShadow.NONE) _drawShadow(canvas)
return ret
}
private fun _drawShadow(canvas: Canvas?) {
if (_vTarget != null) {
when (_edge) {
SlideEdge.LEFT -> {
_vTarget?.getHitRect(_shadowRect)
_shadowDrawable?.setBounds(_shadowRect.left - _shadowWidth, _shadowRect.top,
_shadowRect.left, _shadowRect.bottom)
_shadowDrawable?.draw(canvas)
}
SlideEdge.RIGHT -> {
_vTarget?.getHitRect(_shadowRect)
_shadowDrawable?.setBounds(_shadowRect.right, _shadowRect.top,
_shadowRect.right + _shadowWidth, _shadowRect.bottom)
_shadowDrawable?.draw(canvas)
}
SlideEdge.NONE -> {
/* Do nothing. */
}
}
}
}
private fun _drawCover(canvas: Canvas?) {
val baseAlpha = (SHADOW_COVER_COLOR and 0xff000000).ushr(24)
val alpha = (baseAlpha * (1 - _slidePercent)).toInt()
val color = alpha.shl(24) or (SHADOW_COVER_COLOR and 0xffffff).toInt()
if (_vTarget != null) {
when (_edge) {
SlideEdge.LEFT -> {
canvas?.clipRect(0, 0, _vTarget!!.left, height)
canvas?.drawColor(color)
}
SlideEdge.RIGHT -> {
canvas?.clipRect(_vTarget!!.right, 0, right, height)
canvas?.drawColor(color)
}
SlideEdge.NONE -> {
/* Do nothing. */
}
}
}
}
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
try {
return _slideHelper.shouldInterceptTouchEvent(ev)
} catch (ex: Exception) {
return false
}
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
try {
_slideHelper.processTouchEvent(event)
return true
} catch (ex: IllegalArgumentException) {
return super.onTouchEvent(event)
}
}
override fun computeScroll() {
if (_slideHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this)
}
}
private inner class SlideCallBack() : ViewDragHelper.Callback() {
override fun tryCaptureView(child: View?, pointerId: Int): Boolean {
_ensureTarget()
val edge = when (_edge) {
SlideEdge.LEFT -> ViewDragHelper.EDGE_LEFT
SlideEdge.RIGHT -> ViewDragHelper.EDGE_RIGHT
else -> ViewDragHelper.EDGE_ALL
}
val ret = _vTarget != null && edge != ViewDragHelper.EDGE_ALL && _slideHelper.isEdgeTouched(edge, pointerId)
if (ret) _listener?.onSlideStart()
return ret
}
override fun clampViewPositionHorizontal(child: View?, left: Int, dx: Int): Int {
_ensureTarget()
val width = _vTarget?.measuredWidth ?: 0
return when (_edge) {
SlideEdge.LEFT -> Math.max(0, Math.min(left, width))
SlideEdge.RIGHT -> Math.min(0, Math.max(left, width))
SlideEdge.NONE -> 0
}
}
override fun getViewHorizontalDragRange(child: View?): Int = measuredWidth
override fun onViewDragStateChanged(state: Int) {
_slideState = when (state) {
ViewDragHelper.STATE_DRAGGING -> SlideState.DRAGGING
ViewDragHelper.STATE_SETTLING -> SlideState.SETTLING
else -> SlideState.IDLE
}
if (_slidePercent > 0.9f && _slideState != SlideState.DRAGGING) {
_listener?.onSlideFinish()
}
}
override fun onViewPositionChanged(changedView: View?, left: Int, top: Int, dx: Int, dy: Int) {
_ensureTarget()
_slideViewLeft = left
_slideViewTop = top
invalidate()
if (_vTarget != null) {
val width = _vTarget?.width ?: 0
when (_edge) {
SlideEdge.LEFT -> {
_slidePercent = Math.abs(left.toFloat() / (width))
}
SlideEdge.RIGHT -> {
_slidePercent = Math.abs(left.toFloat() / (width))
}
SlideEdge.NONE -> {
/* Do nothing. */
}
}
}
_listener?.onSlide(_slidePercent, _slideState)
}
override fun onViewReleased(releasedChild: View?, xvel: Float, yvel: Float) {
_ensureTarget()
val top = _vTarget?.top ?: 0
val left = _vTarget?.left ?: 0
val width = _vTarget?.width ?: 0
if (_vTarget != null) {
val settleLeft: Int
if (_edge == SlideEdge.LEFT) {
val threshold = width / 2
if (xvel > threshold) {
settleLeft = width
} else if (xvel < 0 && Math.abs(xvel) > threshold) {
settleLeft = 0
} else {
settleLeft = if (left > threshold) width else 0
}
} else if (_edge == SlideEdge.RIGHT) {
val threshold = width / 2
settleLeft = if ((xvel < 0 && Math.abs(xvel) > threshold) || Math.abs(left) > threshold) -width else 0
} else {
settleLeft = 0
}
_slideHelper.settleCapturedViewAt(settleLeft, top)
invalidate()
}
}
}
}
/**
* 参考SwipbackLayout的实现
*/
fun convertActivityFromTranslucent(act: Activity) {
try {
val method = Activity::class.java.getDeclaredMethod("convertFromTranslucent")
method.isAccessible = true
method.invoke(act)
} catch (t: Throwable) {
Log.e(TAG, "Can not call the convertFromTranslucent method of Activity")
}
}
fun convertActivityToTranslucent(act: Activity) {
if (Build.VERSION.SDK_INT >= 21 /* Build.VERSION_CODES.LOLLIPOP */) {
_convertActivityToTranslucentAfterL(act)
} else {
_convertActivityToTranslucentBeforeL(act)
}
}
/**
* 参考SwipbackLayout的实现
*/
private fun _convertActivityToTranslucentBeforeL(act: Activity) {
try {
val classes = Activity::class.java.declaredClasses
var translucentConversionListenerClazz: Class<*>? = null
for (clazz in classes) {
if (clazz.simpleName.contains("TranslucentConversionListener")) {
translucentConversionListenerClazz = clazz
}
}
val method = Activity::class.java.getDeclaredMethod("convertToTranslucent", translucentConversionListenerClazz)
method.isAccessible = true
method.invoke(act, null)
} catch (t: Throwable) {
Log.e(TAG, "Can not call the convertToTranslucent method of Activity")
}
}
/**
* Android L之后Activity内部实现改变了,所以反射方法要改变下
*/
private fun _convertActivityToTranslucentAfterL(act: Activity) {
try {
val getActivityOptions = Activity::class.java.getDeclaredMethod("getActivityOptions")
getActivityOptions.isAccessible = true
val options = getActivityOptions.invoke(act)
val classes = Activity::class.java.declaredClasses
var translucentConversionListenerClazz: Class<*>? = null
for (clazz in classes) {
if (clazz.simpleName.contains("TranslucentConversionListener")) {
translucentConversionListenerClazz = clazz
}
}
val convertToTranslucent = Activity::class.java.getDeclaredMethod("convertToTranslucent", translucentConversionListenerClazz, ActivityOptions::class.java)
convertToTranslucent.isAccessible = true
convertToTranslucent.invoke(act, null, options)
} catch (t: Throwable) {
Log.e(TAG, "Can not call the convertToTranslucent method of Activity")
}
}
object Slider {
fun attachToScreen(act: Activity, edge: SlideEdge, shadow: SlideShadow, l: SlideListener) {
val decorView: ViewGroup = act.window.decorView as ViewGroup
val bg: Drawable = decorView.background
act.window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
decorView.background = ColorDrawable(Color.TRANSPARENT)
val screenView: View = decorView.getChildAt(0)
decorView.removeViewAt(0)
val slideLayout: SlideLayout = SlideLayout(act)
screenView.background = bg
slideLayout.addView(screenView)
decorView.addView(slideLayout, 0)
slideLayout.edge = edge
slideLayout.shadow = shadow
slideLayout.listener = l
convertActivityFromTranslucent(act)
}
fun attachToScreen(act: Activity, edge: SlideEdge, shadow: SlideShadow) {
attachToScreen(act, edge, shadow, object : SlideListener {
override fun onSlideStart() {
Log.d(TAG, "Sliding: ${act.toString()} Start")
convertActivityToTranslucent(act)
}
override fun onSlide(percent: Float, state: SlideState) {
Log.d(TAG, "Sliding $percent : ${state.toString()}")
}
override fun onSlideFinish() {
Log.d(TAG, "Sliding ${act.toString()} Finish")
act.finish()
act.overridePendingTransition(0, 0)
}
})
}
fun attachToScreen(act: Activity, edge: SlideEdge) {
attachToScreen(act, edge, SlideShadow.FULL)
}
} | mit | 9f92b4e71eebebf67e3041ba0c53b36c | 30.504651 | 161 | 0.659309 | 3.978267 | false | false | false | false |
pdvrieze/ProcessManager | ProcessEngine/core/src/commonMain/kotlin/nl/adaptivity/process/engine/processModel/PseudoInstance.kt | 1 | 8049 | /*
* Copyright (c) 2021.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine.processModel
import net.devrieze.util.Handle
import net.devrieze.util.security.SecureObject
import nl.adaptivity.process.engine.*
import nl.adaptivity.process.processModel.StartNode
import nl.adaptivity.process.processModel.engine.ExecutableProcessNode
import nl.adaptivity.process.util.IdentifyableSet
import nl.adaptivity.util.security.Principal
class PseudoInstance(
override val processContext: PseudoContext,
override val handle: Handle<SecureObject<ProcessNodeInstance<*>>>,
override val node: ExecutableProcessNode,
override val entryNo: Int,
predecessors: Set<Handle<SecureObject<ProcessNodeInstance<*>>>>
) : IProcessNodeInstance {
override val predecessors = predecessors.toMutableSet()
override val owner: Principal
get() = processContext.processInstance.processModel.rootModel.owner
override var state: NodeInstanceState = NodeInstanceState.Pending
override val hProcessInstance: Handle<SecureObject<ProcessInstance>>
get() = processContext.processInstance.handle
override val results: List<ProcessData>
get() = emptyList()
override fun builder(processInstanceBuilder: ProcessInstance.Builder): ProcessNodeInstance.Builder<*, *> {
throw UnsupportedOperationException("Pseudo instances should not be made into builders")
}
override fun toString(): String {
return "pseudo instance ($handle, ${node.id}[$entryNo] - $state)"
}
class PseudoContext(
val processInstance: IProcessInstance,
) : ProcessInstanceContext {
constructor(readAccess: ProcessEngineDataAccess, hProcessInstance: Handle<SecureObject<ProcessInstance>>) :
this(readAccess.instance(hProcessInstance).withPermission())
private val handleOffset: Int =
(processInstance.allChildNodeInstances().maxOf { it.handle.handleValue } + 1).toInt()
private val overlay = arrayOfNulls<IProcessNodeInstance>(handleOffset)
private val pseudoNodes: MutableList<PseudoInstance> = mutableListOf()
override val handle: Handle<SecureObject<ProcessInstance>>
get() = processInstance.handle
init {
for (child in processInstance.allChildNodeInstances()) {
val p = child
overlay[p.handle.handleValue.toInt()] = p
}
}
fun getNodeInstance(handle: Handle<SecureObject<ProcessNodeInstance<*>>>): IProcessNodeInstance? = when {
handle.handleValue < handleOffset
-> overlay[handle.handleValue.toInt()]
else -> pseudoNodes[(handle.handleValue - handleOffset).toInt()]
}
private fun getNodeInstance(node: ExecutableProcessNode, hPred: Handle<SecureObject<ProcessNodeInstance<*>>>): IProcessNodeInstance? {
return (overlay.asSequence() + pseudoNodes.asSequence())
.firstOrNull { it?.node == node && hPred in it.predecessors }
}
private fun getNodeInstance(node: ExecutableProcessNode, entryNo: Int): IProcessNodeInstance? {
return (overlay.asSequence() + pseudoNodes.asSequence())
.firstOrNull { it?.node == node && (!it.node.isMultiInstance || it.entryNo == entryNo) }
}
fun create(
pred: Handle<SecureObject<ProcessNodeInstance<*>>>,
node: ExecutableProcessNode,
entryNo: Int
): PseudoInstance {
val inst = PseudoInstance(
this,
Handle((handleOffset + pseudoNodes.size).toLong()),
node,
entryNo,
setOf(pred)
)
pseudoNodes.add(inst)
return inst
}
fun create(
pred: Handle<SecureObject<ProcessNodeInstance<*>>>,
base: IProcessNodeInstance
): PseudoInstance {
val inst = PseudoInstance(
this,
base.handle.takeIf { it.isValid } ?: Handle((handleOffset + pseudoNodes.size).toLong()),
base.node,
base.entryNo,
base.predecessors + pred
).apply { state = base.state }
if (inst.handle.handleValue<handleOffset) {
overlay[inst.handle.handleValue.toInt()] = inst
} else {
pseudoNodes.add(inst)
}
return inst
}
fun getOrCreate(
hPred: Handle<SecureObject<ProcessNodeInstance<*>>>,
node: ExecutableProcessNode,
entryNo: Int
): IProcessNodeInstance {
getNodeInstance(node, hPred)?.let { return it } // the predecessor is already known
val instance = getNodeInstance(node, entryNo) // predecessor not linked yet
if (instance != null) {
if (! instance.handle.isValid) {
return create(hPred, instance )
} else {
when (instance) {
is PseudoInstance -> instance.predecessors.add(hPred)
is ProcessNodeInstance.Builder<*, *> -> instance.predecessors.add(hPred)
else -> return create(hPred, instance)
}
return instance
}
}
return create(hPred, node, entryNo)
}
fun populatePredecessorsFor(handle: Handle<SecureObject<ProcessNodeInstance<*>>>) {
val interestedNodes: IdentifyableSet<ExecutableProcessNode>
val targetEntryNo: Int
run {
val targetInstance = getNodeInstance(handle) ?: throw IllegalArgumentException("No such node exists")
interestedNodes = targetInstance.node.transitivePredecessors()
targetEntryNo = targetInstance.entryNo
}
val toProcess = ArrayDeque<IProcessNodeInstance>()
processInstance.allChildNodeInstances().filterTo(toProcess) {
it.node is StartNode && it.node in interestedNodes
}
while (toProcess.isNotEmpty()) {
val child = toProcess.removeFirst()
if (! child.node.isMultiInstance || child.entryNo <= targetEntryNo) {
for (successorNodeId in child.node.successors) {
val updatedTarget = getNodeInstance(handle)!!
if (successorNodeId == updatedTarget.node.identifier) {
if (child.handle !in updatedTarget.predecessors) {
// Create a new overlay node to record the new predecessor
when (updatedTarget) {
is PseudoInstance -> updatedTarget.predecessors.add(child.handle)
else -> create(child.handle, updatedTarget)
}
}
} else {
val successorNode = interestedNodes.get(successorNodeId)
if (successorNode != null) {
toProcess.add(getOrCreate(child.handle, successorNode, child.entryNo))
}
}
}
}
}
}
}
}
| lgpl-3.0 | 4227764e2f38451fe52ab33315980001 | 40.704663 | 142 | 0.602311 | 5.505472 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/duchy/daemon/mill/liquidlegionsv2/LiquidLegionsV2Mill.kt | 1 | 42468 | // Copyright 2020 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.duchy.daemon.mill.liquidlegionsv2
import com.google.protobuf.ByteString
import io.opentelemetry.api.OpenTelemetry
import io.opentelemetry.api.metrics.LongHistogram
import io.opentelemetry.api.metrics.Meter
import java.nio.file.Paths
import java.time.Clock
import java.util.logging.Logger
import kotlin.math.min
import org.wfanet.anysketch.crypto.CombineElGamalPublicKeysRequest
import org.wfanet.measurement.api.Version
import org.wfanet.measurement.api.v2alpha.MeasurementSpec
import org.wfanet.measurement.common.crypto.SigningKeyHandle
import org.wfanet.measurement.common.crypto.readCertificate
import org.wfanet.measurement.common.flatten
import org.wfanet.measurement.common.loadLibrary
import org.wfanet.measurement.common.throttler.MinimumIntervalThrottler
import org.wfanet.measurement.consent.client.duchy.encryptResult
import org.wfanet.measurement.consent.client.duchy.signElgamalPublicKey
import org.wfanet.measurement.consent.client.duchy.signResult
import org.wfanet.measurement.consent.client.duchy.verifyDataProviderParticipation
import org.wfanet.measurement.consent.client.duchy.verifyElGamalPublicKey
import org.wfanet.measurement.duchy.daemon.mill.CRYPTO_LIB_CPU_DURATION
import org.wfanet.measurement.duchy.daemon.mill.Certificate
import org.wfanet.measurement.duchy.daemon.mill.MillBase
import org.wfanet.measurement.duchy.daemon.mill.PermanentComputationError
import org.wfanet.measurement.duchy.daemon.mill.liquidlegionsv2.crypto.LiquidLegionsV2Encryption
import org.wfanet.measurement.duchy.daemon.utils.ReachAndFrequency
import org.wfanet.measurement.duchy.daemon.utils.toAnySketchElGamalPublicKey
import org.wfanet.measurement.duchy.daemon.utils.toCmmsElGamalPublicKey
import org.wfanet.measurement.duchy.daemon.utils.toV2AlphaElGamalPublicKey
import org.wfanet.measurement.duchy.daemon.utils.toV2AlphaEncryptionPublicKey
import org.wfanet.measurement.duchy.daemon.utils.toV2AlphaMeasurementResult
import org.wfanet.measurement.duchy.db.computation.ComputationDataClients
import org.wfanet.measurement.duchy.service.internal.computations.outputPathList
import org.wfanet.measurement.duchy.service.system.v1alpha.advanceComputationHeader
import org.wfanet.measurement.duchy.toProtocolStage
import org.wfanet.measurement.internal.duchy.ComputationDetails.CompletedReason
import org.wfanet.measurement.internal.duchy.ComputationDetails.KingdomComputationDetails
import org.wfanet.measurement.internal.duchy.ComputationStage
import org.wfanet.measurement.internal.duchy.ComputationStatsGrpcKt.ComputationStatsCoroutineStub
import org.wfanet.measurement.internal.duchy.ComputationToken
import org.wfanet.measurement.internal.duchy.ComputationTypeEnum.ComputationType
import org.wfanet.measurement.internal.duchy.ElGamalPublicKey
import org.wfanet.measurement.internal.duchy.RequisitionMetadata
import org.wfanet.measurement.internal.duchy.UpdateComputationDetailsRequest
import org.wfanet.measurement.internal.duchy.config.LiquidLegionsV2SetupConfig.RoleInComputation.AGGREGATOR
import org.wfanet.measurement.internal.duchy.config.LiquidLegionsV2SetupConfig.RoleInComputation.NON_AGGREGATOR
import org.wfanet.measurement.internal.duchy.config.LiquidLegionsV2SetupConfig.RoleInComputation.UNKNOWN
import org.wfanet.measurement.internal.duchy.config.LiquidLegionsV2SetupConfig.RoleInComputation.UNRECOGNIZED
import org.wfanet.measurement.internal.duchy.protocol.CompleteExecutionPhaseOneAtAggregatorRequest
import org.wfanet.measurement.internal.duchy.protocol.CompleteExecutionPhaseOneAtAggregatorResponse
import org.wfanet.measurement.internal.duchy.protocol.CompleteExecutionPhaseOneRequest
import org.wfanet.measurement.internal.duchy.protocol.CompleteExecutionPhaseOneResponse
import org.wfanet.measurement.internal.duchy.protocol.CompleteExecutionPhaseThreeAtAggregatorRequest
import org.wfanet.measurement.internal.duchy.protocol.CompleteExecutionPhaseThreeAtAggregatorResponse
import org.wfanet.measurement.internal.duchy.protocol.CompleteExecutionPhaseThreeRequest
import org.wfanet.measurement.internal.duchy.protocol.CompleteExecutionPhaseThreeResponse
import org.wfanet.measurement.internal.duchy.protocol.CompleteExecutionPhaseTwoAtAggregatorRequest
import org.wfanet.measurement.internal.duchy.protocol.CompleteExecutionPhaseTwoAtAggregatorResponse
import org.wfanet.measurement.internal.duchy.protocol.CompleteExecutionPhaseTwoRequest
import org.wfanet.measurement.internal.duchy.protocol.CompleteExecutionPhaseTwoResponse
import org.wfanet.measurement.internal.duchy.protocol.CompleteInitializationPhaseRequest
import org.wfanet.measurement.internal.duchy.protocol.CompleteSetupPhaseRequest
import org.wfanet.measurement.internal.duchy.protocol.CompleteSetupPhaseResponse
import org.wfanet.measurement.internal.duchy.protocol.FlagCountTupleNoiseGenerationParameters
import org.wfanet.measurement.internal.duchy.protocol.LiquidLegionsSketchAggregationV2
import org.wfanet.measurement.internal.duchy.protocol.LiquidLegionsSketchAggregationV2.ComputationDetails.ComputationParticipant
import org.wfanet.measurement.internal.duchy.protocol.LiquidLegionsSketchAggregationV2.ComputationDetails.Parameters
import org.wfanet.measurement.internal.duchy.protocol.LiquidLegionsSketchAggregationV2.Stage
import org.wfanet.measurement.system.v1alpha.ComputationControlGrpcKt.ComputationControlCoroutineStub
import org.wfanet.measurement.system.v1alpha.ComputationLogEntriesGrpcKt.ComputationLogEntriesCoroutineStub
import org.wfanet.measurement.system.v1alpha.ComputationParticipantKey
import org.wfanet.measurement.system.v1alpha.ComputationParticipantsGrpcKt.ComputationParticipantsCoroutineStub
import org.wfanet.measurement.system.v1alpha.ComputationsGrpcKt
import org.wfanet.measurement.system.v1alpha.ConfirmComputationParticipantRequest
import org.wfanet.measurement.system.v1alpha.LiquidLegionsV2
import org.wfanet.measurement.system.v1alpha.SetParticipantRequisitionParamsRequest
/**
* Mill works on computations using the LiquidLegionSketchAggregationProtocol.
*
* @param millId The identifier of this mill, used to claim a work.
* @param duchyId The identifier of this duchy who owns this mill.
* @param signingKey handle to a signing private key for consent signaling.
* @param consentSignalCert The [Certificate] used for consent signaling.
* @param dataClients clients that have access to local computation storage, i.e., spanner table and
* blob store.
* @param systemComputationParticipantsClient client of the kingdom's system
* ComputationParticipantsService.
* @param systemComputationsClient client of the kingdom's system computationsService.
* @param systemComputationLogEntriesClient client of the kingdom's system
* computationLogEntriesService.
* @param computationStatsClient client of the duchy's internal ComputationStatsService.
* @param throttler A throttler used to rate limit the frequency of the mill polling from the
* computation table.
* @param requestChunkSizeBytes The size of data chunk when sending result to other duchies.
* @param clock A clock
* @param maximumAttempts The maximum number of attempts on a computation at the same stage.
* @param workerStubs A map from other duchies' Ids to their corresponding
* computationControlClients, used for passing computation to other duchies.
* @param cryptoWorker The cryptoWorker that performs the actual computation.
*/
class LiquidLegionsV2Mill(
millId: String,
duchyId: String,
signingKey: SigningKeyHandle,
consentSignalCert: Certificate,
dataClients: ComputationDataClients,
systemComputationParticipantsClient: ComputationParticipantsCoroutineStub,
systemComputationsClient: ComputationsGrpcKt.ComputationsCoroutineStub,
systemComputationLogEntriesClient: ComputationLogEntriesCoroutineStub,
computationStatsClient: ComputationStatsCoroutineStub,
throttler: MinimumIntervalThrottler,
requestChunkSizeBytes: Int = 1024 * 32, // 32 KiB
maximumAttempts: Int = 10,
clock: Clock = Clock.systemUTC(),
private val workerStubs: Map<String, ComputationControlCoroutineStub>,
private val cryptoWorker: LiquidLegionsV2Encryption,
openTelemetry: OpenTelemetry,
) :
MillBase(
millId,
duchyId,
signingKey,
consentSignalCert,
dataClients,
systemComputationParticipantsClient,
systemComputationsClient,
systemComputationLogEntriesClient,
computationStatsClient,
throttler,
ComputationType.LIQUID_LEGIONS_SKETCH_AGGREGATION_V2,
requestChunkSizeBytes,
maximumAttempts,
clock,
openTelemetry
) {
private val meter: Meter = openTelemetry.getMeter(LiquidLegionsV2Mill::class.java.name)
private val initializationPhaseCryptoCpuTimeDurationHistogram: LongHistogram =
meter.histogramBuilder("initialization_phase_crypto_cpu_time_duration_millis").ofLongs().build()
private val setupPhaseCryptoCpuTimeDurationHistogram: LongHistogram =
meter.histogramBuilder("setup_phase_crypto_cpu_time_duration_millis").ofLongs().build()
private val executionPhaseOneCryptoCpuTimeDurationHistogram: LongHistogram =
meter.histogramBuilder("execution_phase_one_crypto_cpu_time_duration_millis").ofLongs().build()
private val executionPhaseTwoCryptoCpuTimeDurationHistogram: LongHistogram =
meter.histogramBuilder("execution_phase_two_crypto_cpu_time_duration_millis").ofLongs().build()
private val executionPhaseThreeCryptoCpuTimeDurationHistogram: LongHistogram =
meter
.histogramBuilder("execution_phase_three_crypto_cpu_time_duration_millis")
.ofLongs()
.build()
override val endingStage: ComputationStage =
ComputationStage.newBuilder()
.apply { liquidLegionsSketchAggregationV2 = Stage.COMPLETE }
.build()
private val actions =
mapOf(
Pair(Stage.INITIALIZATION_PHASE, AGGREGATOR) to ::initializationPhase,
Pair(Stage.INITIALIZATION_PHASE, NON_AGGREGATOR) to ::initializationPhase,
Pair(Stage.CONFIRMATION_PHASE, AGGREGATOR) to ::confirmationPhase,
Pair(Stage.CONFIRMATION_PHASE, NON_AGGREGATOR) to ::confirmationPhase,
Pair(Stage.SETUP_PHASE, AGGREGATOR) to ::completeSetupPhaseAtAggregator,
Pair(Stage.SETUP_PHASE, NON_AGGREGATOR) to ::completeSetupPhaseAtNonAggregator,
Pair(Stage.EXECUTION_PHASE_ONE, AGGREGATOR) to ::completeExecutionPhaseOneAtAggregator,
Pair(Stage.EXECUTION_PHASE_ONE, NON_AGGREGATOR) to ::completeExecutionPhaseOneAtNonAggregator,
Pair(Stage.EXECUTION_PHASE_TWO, AGGREGATOR) to ::completeExecutionPhaseTwoAtAggregator,
Pair(Stage.EXECUTION_PHASE_TWO, NON_AGGREGATOR) to ::completeExecutionPhaseTwoAtNonAggregator,
Pair(Stage.EXECUTION_PHASE_THREE, AGGREGATOR) to ::completeExecutionPhaseThreeAtAggregator,
Pair(Stage.EXECUTION_PHASE_THREE, NON_AGGREGATOR) to
::completeExecutionPhaseThreeAtNonAggregator
)
override suspend fun processComputationImpl(token: ComputationToken) {
require(token.computationDetails.hasLiquidLegionsV2()) {
"Only Liquid Legions V2 computation is supported in this mill."
}
val stage = token.computationStage.liquidLegionsSketchAggregationV2
val role = token.computationDetails.liquidLegionsV2.role
val action = actions[Pair(stage, role)] ?: error("Unexpected stage or role: ($stage, $role)")
val updatedToken = action(token)
val globalId = token.globalComputationId
val updatedStage = updatedToken.computationStage.liquidLegionsSketchAggregationV2
logger.info("$globalId@$millId: Stage transitioned from $stage to $updatedStage")
}
/** Sends requisition params to the kingdom. */
private suspend fun sendRequisitionParamsToKingdom(token: ComputationToken) {
val llv2ComputationDetails = token.computationDetails.liquidLegionsV2
require(llv2ComputationDetails.hasLocalElgamalKey()) { "Missing local elgamal key." }
val signedElgamalPublicKey =
when (Version.fromString(token.computationDetails.kingdomComputation.publicApiVersion)) {
Version.V2_ALPHA ->
signElgamalPublicKey(
llv2ComputationDetails.localElgamalKey.publicKey.toV2AlphaElGamalPublicKey(),
signingKey
)
Version.VERSION_UNSPECIFIED -> error("Public api version is invalid or unspecified.")
}
val request =
SetParticipantRequisitionParamsRequest.newBuilder()
.apply {
name = ComputationParticipantKey(token.globalComputationId, duchyId).toName()
requisitionParamsBuilder.apply {
duchyCertificate = consentSignalCert.name
liquidLegionsV2Builder.apply {
elGamalPublicKey = signedElgamalPublicKey.data
elGamalPublicKeySignature = signedElgamalPublicKey.signature
}
}
}
.build()
systemComputationParticipantsClient.setParticipantRequisitionParams(request)
}
/** Processes computation in the initialization phase */
private suspend fun initializationPhase(token: ComputationToken): ComputationToken {
val llv2ComputationDetails = token.computationDetails.liquidLegionsV2
val ellipticCurveId = llv2ComputationDetails.parameters.ellipticCurveId
require(ellipticCurveId > 0) { "invalid ellipticCurveId $ellipticCurveId" }
val nextToken =
if (llv2ComputationDetails.hasLocalElgamalKey()) {
// Reuses the key if it is already generated for this computation.
token
} else {
// Generates a new set of ElGamalKeyPair.
val request =
CompleteInitializationPhaseRequest.newBuilder()
.apply { curveId = ellipticCurveId.toLong() }
.build()
val cryptoResult = cryptoWorker.completeInitializationPhase(request)
logStageDurationMetric(
token,
CRYPTO_LIB_CPU_DURATION,
cryptoResult.elapsedCpuTimeMillis,
initializationPhaseCryptoCpuTimeDurationHistogram
)
// Updates the newly generated localElgamalKey to the ComputationDetails.
dataClients.computationsClient
.updateComputationDetails(
UpdateComputationDetailsRequest.newBuilder()
.also {
it.token = token
it.details =
token.computationDetails
.toBuilder()
.apply { liquidLegionsV2Builder.localElgamalKey = cryptoResult.elGamalKeyPair }
.build()
}
.build()
)
.token
}
sendRequisitionParamsToKingdom(nextToken)
return dataClients.transitionComputationToStage(
nextToken,
stage = Stage.WAIT_REQUISITIONS_AND_KEY_SET.toProtocolStage()
)
}
/**
* Verifies that all EDPs have participated.
*
* @return a list of error messages if anything is wrong, otherwise an empty list.
*/
private fun verifyEdpParticipation(
details: KingdomComputationDetails,
requisitions: Iterable<RequisitionMetadata>,
): List<String> {
when (Version.fromString(details.publicApiVersion)) {
Version.V2_ALPHA -> {}
Version.VERSION_UNSPECIFIED -> error("Public api version is invalid or unspecified.")
}
val errorList = mutableListOf<String>()
val measurementSpec = MeasurementSpec.parseFrom(details.measurementSpec)
if (!verifyDataProviderParticipation(measurementSpec, requisitions.map { it.details.nonce })) {
errorList.add("Cannot verify participation of all DataProviders.")
}
for (requisition in requisitions) {
if (requisition.details.externalFulfillingDuchyId == duchyId && requisition.path.isBlank()) {
errorList.add(
"Missing expected data for requisition ${requisition.externalKey.externalRequisitionId}."
)
}
}
return errorList
}
/**
* Verifies the duchy Elgamal Key signature. Returns a list of error messages if anything is
* wrong. Otherwise return an empty list.
*/
private fun verifyDuchySignature(
duchy: ComputationParticipant,
publicApiVersion: Version
): List<String> {
val errorList = mutableListOf<String>()
if (duchy.duchyId != duchyId && !workerStubs.containsKey(duchy.duchyId)) {
errorList.add("Unrecognized duchy ${duchy.duchyId}.")
}
when (publicApiVersion) {
Version.V2_ALPHA -> {
if (
!verifyElGamalPublicKey(
duchy.elGamalPublicKey,
duchy.elGamalPublicKeySignature,
readCertificate(duchy.duchyCertificateDer)
)
) {
errorList.add("ElGamalPublicKey signature of ${duchy.duchyId} is invalid.")
}
}
Version.VERSION_UNSPECIFIED -> error("Public api version is invalid or unspecified.")
}
return errorList
}
/** Fails a computation both locally and at the kingdom when the confirmation fails. */
private fun failComputationAtConfirmationPhase(
token: ComputationToken,
errorList: List<String>
): ComputationToken {
val errorMessage =
"@Mill $millId, Computation ${token.globalComputationId} failed due to:\n" +
errorList.joinToString(separator = "\n")
throw PermanentComputationError(Exception(errorMessage))
}
private fun List<ElGamalPublicKey>.toCombinedPublicKey(curveId: Int): ElGamalPublicKey {
val request =
CombineElGamalPublicKeysRequest.newBuilder()
.also {
it.curveId = curveId.toLong()
it.addAllElGamalKeys(this.map { key -> key.toAnySketchElGamalPublicKey() })
}
.build()
return cryptoWorker.combineElGamalPublicKeys(request).elGamalKeys.toCmmsElGamalPublicKey()
}
/**
* Computes the fully and partially combined Elgamal public keys and caches the result in the
* computationDetails.
*/
private suspend fun updatePublicElgamalKey(token: ComputationToken): ComputationToken {
val llv2Details = token.computationDetails.liquidLegionsV2
val fullParticipantList = llv2Details.participantList
val combinedPublicKey =
fullParticipantList
.map { it.publicKey }
.toCombinedPublicKey(llv2Details.parameters.ellipticCurveId)
@Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Proto enum fields are never null.
val partiallyCombinedPublicKey =
when (llv2Details.role) {
// For aggregator, the partial list is the same as the full list.
AGGREGATOR -> combinedPublicKey
NON_AGGREGATOR ->
fullParticipantList
.subList(
fullParticipantList.indexOfFirst { it.duchyId == duchyId } + 1,
fullParticipantList.size
)
.map { it.publicKey }
.toCombinedPublicKey(llv2Details.parameters.ellipticCurveId)
UNKNOWN,
UNRECOGNIZED -> error("Invalid role ${llv2Details.role}")
}
return dataClients.computationsClient
.updateComputationDetails(
UpdateComputationDetailsRequest.newBuilder()
.apply {
this.token = token
details =
token.computationDetails
.toBuilder()
.apply {
liquidLegionsV2Builder.also {
it.combinedPublicKey = combinedPublicKey
it.partiallyCombinedPublicKey = partiallyCombinedPublicKey
}
}
.build()
}
.build()
)
.token
}
/** Sends confirmation to the kingdom and transits the local computation to the next stage. */
private suspend fun passConfirmationPhase(token: ComputationToken): ComputationToken {
systemComputationParticipantsClient.confirmComputationParticipant(
ConfirmComputationParticipantRequest.newBuilder()
.apply { name = ComputationParticipantKey(token.globalComputationId, duchyId).toName() }
.build()
)
val latestToken = updatePublicElgamalKey(token)
return dataClients.transitionComputationToStage(
latestToken,
stage =
when (checkNotNull(token.computationDetails.liquidLegionsV2.role)) {
AGGREGATOR -> Stage.WAIT_SETUP_PHASE_INPUTS.toProtocolStage()
NON_AGGREGATOR -> Stage.WAIT_TO_START.toProtocolStage()
else -> error("Unknown role: ${latestToken.computationDetails.liquidLegionsV2.role}")
}
)
}
/** Processes computation in the confirmation phase */
private suspend fun confirmationPhase(token: ComputationToken): ComputationToken {
val errorList = mutableListOf<String>()
val kingdomComputation = token.computationDetails.kingdomComputation
errorList.addAll(verifyEdpParticipation(kingdomComputation, token.requisitionsList))
token.computationDetails.liquidLegionsV2.participantList.forEach {
errorList.addAll(
verifyDuchySignature(it, Version.fromString(kingdomComputation.publicApiVersion))
)
}
return if (errorList.isEmpty()) {
passConfirmationPhase(token)
} else {
failComputationAtConfirmationPhase(token, errorList)
}
}
private suspend fun completeSetupPhaseAtAggregator(token: ComputationToken): ComputationToken {
val llv2Details = token.computationDetails.liquidLegionsV2
require(AGGREGATOR == llv2Details.role) { "invalid role for this function." }
val (bytes, nextToken) =
existingOutputOr(token) {
val request =
dataClients
.readAllRequisitionBlobs(token, duchyId)
.concat(readAndCombineAllInputBlobs(token, workerStubs.size))
.toCompleteSetupPhaseRequest(token, llv2Details, token.requisitionsCount)
val cryptoResult: CompleteSetupPhaseResponse = cryptoWorker.completeSetupPhase(request)
logStageDurationMetric(
token,
CRYPTO_LIB_CPU_DURATION,
cryptoResult.elapsedCpuTimeMillis,
setupPhaseCryptoCpuTimeDurationHistogram
)
cryptoResult.combinedRegisterVector
}
sendAdvanceComputationRequest(
header =
advanceComputationHeader(
LiquidLegionsV2.Description.EXECUTION_PHASE_ONE_INPUT,
token.globalComputationId
),
content = addLoggingHook(token, bytes),
stub = nextDuchyStub(llv2Details.participantList)
)
return dataClients.transitionComputationToStage(
nextToken,
inputsToNextStage = nextToken.outputPathList(),
stage = Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage()
)
}
private suspend fun completeSetupPhaseAtNonAggregator(token: ComputationToken): ComputationToken {
val llv2Details = token.computationDetails.liquidLegionsV2
require(NON_AGGREGATOR == llv2Details.role) { "invalid role for this function." }
val (bytes, nextToken) =
existingOutputOr(token) {
val request =
dataClients
.readAllRequisitionBlobs(token, duchyId)
.toCompleteSetupPhaseRequest(token, llv2Details, token.requisitionsCount)
val cryptoResult: CompleteSetupPhaseResponse = cryptoWorker.completeSetupPhase(request)
logStageDurationMetric(
token,
CRYPTO_LIB_CPU_DURATION,
cryptoResult.elapsedCpuTimeMillis,
setupPhaseCryptoCpuTimeDurationHistogram
)
cryptoResult.combinedRegisterVector
}
sendAdvanceComputationRequest(
header =
advanceComputationHeader(
LiquidLegionsV2.Description.SETUP_PHASE_INPUT,
token.globalComputationId
),
content = addLoggingHook(token, bytes),
stub = aggregatorDuchyStub(llv2Details.participantList.last().duchyId)
)
return dataClients.transitionComputationToStage(
nextToken,
inputsToNextStage = nextToken.outputPathList(),
stage = Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS.toProtocolStage()
)
}
private suspend fun completeExecutionPhaseOneAtAggregator(
token: ComputationToken
): ComputationToken {
val llv2Details = token.computationDetails.liquidLegionsV2
val llv2Parameters = llv2Details.parameters
require(AGGREGATOR == llv2Details.role) { "invalid role for this function." }
val (bytes, nextToken) =
existingOutputOr(token) {
val requestBuilder =
CompleteExecutionPhaseOneAtAggregatorRequest.newBuilder().apply {
localElGamalKeyPair = llv2Details.localElgamalKey
compositeElGamalPublicKey = llv2Details.combinedPublicKey
curveId = llv2Details.parameters.ellipticCurveId.toLong()
combinedRegisterVector = readAndCombineAllInputBlobs(token, 1)
totalSketchesCount = token.requisitionsCount
}
if (
llv2Parameters.noise.hasFrequencyNoiseConfig() &&
(getMaximumRequestedFrequency(token) > 1)
) {
requestBuilder.noiseParameters = getFrequencyNoiseParams(token, llv2Parameters)
}
val cryptoResult: CompleteExecutionPhaseOneAtAggregatorResponse =
cryptoWorker.completeExecutionPhaseOneAtAggregator(requestBuilder.build())
logStageDurationMetric(
token,
CRYPTO_LIB_CPU_DURATION,
cryptoResult.elapsedCpuTimeMillis,
executionPhaseOneCryptoCpuTimeDurationHistogram
)
cryptoResult.flagCountTuples
}
// Passes the computation to the next duchy.
sendAdvanceComputationRequest(
header =
advanceComputationHeader(
LiquidLegionsV2.Description.EXECUTION_PHASE_TWO_INPUT,
token.globalComputationId
),
content = addLoggingHook(token, bytes),
stub = nextDuchyStub(llv2Details.participantList)
)
return dataClients.transitionComputationToStage(
nextToken,
inputsToNextStage = nextToken.outputPathList(),
stage = Stage.WAIT_EXECUTION_PHASE_TWO_INPUTS.toProtocolStage()
)
}
private suspend fun completeExecutionPhaseOneAtNonAggregator(
token: ComputationToken
): ComputationToken {
val llv2Details = token.computationDetails.liquidLegionsV2
require(NON_AGGREGATOR == llv2Details.role) { "invalid role for this function." }
val (bytes, nextToken) =
existingOutputOr(token) {
val cryptoResult: CompleteExecutionPhaseOneResponse =
cryptoWorker.completeExecutionPhaseOne(
CompleteExecutionPhaseOneRequest.newBuilder()
.apply {
localElGamalKeyPair = llv2Details.localElgamalKey
compositeElGamalPublicKey = llv2Details.combinedPublicKey
curveId = llv2Details.parameters.ellipticCurveId.toLong()
combinedRegisterVector = readAndCombineAllInputBlobs(token, 1)
}
.build()
)
logStageDurationMetric(
token,
CRYPTO_LIB_CPU_DURATION,
cryptoResult.elapsedCpuTimeMillis,
executionPhaseOneCryptoCpuTimeDurationHistogram
)
cryptoResult.combinedRegisterVector
}
// Passes the computation to the next duchy.
sendAdvanceComputationRequest(
header =
advanceComputationHeader(
LiquidLegionsV2.Description.EXECUTION_PHASE_ONE_INPUT,
token.globalComputationId
),
content = addLoggingHook(token, bytes),
stub = nextDuchyStub(llv2Details.participantList)
)
return dataClients.transitionComputationToStage(
nextToken,
inputsToNextStage = nextToken.outputPathList(),
stage = Stage.WAIT_EXECUTION_PHASE_TWO_INPUTS.toProtocolStage()
)
}
private suspend fun completeExecutionPhaseTwoAtAggregator(
token: ComputationToken
): ComputationToken {
val llv2Details = token.computationDetails.liquidLegionsV2
val llv2Parameters = llv2Details.parameters
require(AGGREGATOR == token.computationDetails.liquidLegionsV2.role) {
"invalid role for this function."
}
var reach = 0L
val maximumRequestedFrequency = getMaximumRequestedFrequency(token)
val (bytes, tempToken) =
existingOutputOr(token) {
when (Version.fromString(token.computationDetails.kingdomComputation.publicApiVersion)) {
Version.V2_ALPHA -> {}
Version.VERSION_UNSPECIFIED -> error("Public api version is invalid or unspecified.")
}
val measurementSpec =
MeasurementSpec.parseFrom(token.computationDetails.kingdomComputation.measurementSpec)
val requestBuilder =
CompleteExecutionPhaseTwoAtAggregatorRequest.newBuilder().apply {
localElGamalKeyPair = llv2Details.localElgamalKey
compositeElGamalPublicKey = llv2Details.combinedPublicKey
curveId = llv2Parameters.ellipticCurveId.toLong()
flagCountTuples = readAndCombineAllInputBlobs(token, 1)
maximumFrequency = maximumRequestedFrequency
liquidLegionsParametersBuilder.apply {
decayRate = llv2Parameters.liquidLegionsSketch.decayRate
size = llv2Parameters.liquidLegionsSketch.size
}
vidSamplingIntervalWidth = measurementSpec.vidSamplingInterval.width
}
val noiseConfig = llv2Parameters.noise
if (noiseConfig.hasReachNoiseConfig()) {
requestBuilder.reachDpNoiseBaselineBuilder.apply {
contributorsCount = workerStubs.size + 1
globalReachDpNoise = noiseConfig.reachNoiseConfig.globalReachDpNoise
}
}
if (noiseConfig.hasFrequencyNoiseConfig() && (maximumRequestedFrequency > 1)) {
requestBuilder.frequencyNoiseParametersBuilder.apply {
contributorsCount = workerStubs.size + 1
maximumFrequency = maximumRequestedFrequency
dpParams = noiseConfig.frequencyNoiseConfig
}
}
val cryptoResult: CompleteExecutionPhaseTwoAtAggregatorResponse =
cryptoWorker.completeExecutionPhaseTwoAtAggregator(requestBuilder.build())
logStageDurationMetric(
token,
CRYPTO_LIB_CPU_DURATION,
cryptoResult.elapsedCpuTimeMillis,
executionPhaseTwoCryptoCpuTimeDurationHistogram
)
reach = cryptoResult.reach
cryptoResult.sameKeyAggregatorMatrix
}
val nextToken =
if (llv2Details.hasReachEstimate()) {
// Do nothing if the token has already contained the ReachEstimate
tempToken
} else {
// Update the newly calculated reach to the ComputationDetails.
dataClients.computationsClient
.updateComputationDetails(
UpdateComputationDetailsRequest.newBuilder()
.also {
it.token = tempToken
it.details =
token.computationDetails
.toBuilder()
.apply { liquidLegionsV2Builder.reachEstimateBuilder.reach = reach }
.build()
}
.build()
)
.token
}
// If this is a reach-only computation, then our job is done.
if (maximumRequestedFrequency == 1) {
sendResultToKingdom(token, reach, mapOf(1L to 1.0))
return completeComputation(nextToken, CompletedReason.SUCCEEDED)
}
// Passes the computation to the next duchy.
sendAdvanceComputationRequest(
header =
advanceComputationHeader(
LiquidLegionsV2.Description.EXECUTION_PHASE_THREE_INPUT,
token.globalComputationId
),
content = addLoggingHook(token, bytes),
stub = nextDuchyStub(llv2Details.participantList)
)
return dataClients.transitionComputationToStage(
nextToken,
inputsToNextStage = nextToken.outputPathList(),
stage = Stage.WAIT_EXECUTION_PHASE_THREE_INPUTS.toProtocolStage()
)
}
private suspend fun completeExecutionPhaseTwoAtNonAggregator(
token: ComputationToken
): ComputationToken {
val llv2Details = token.computationDetails.liquidLegionsV2
val llv2Parameters = llv2Details.parameters
require(NON_AGGREGATOR == llv2Details.role) { "invalid role for this function." }
val maximumRequestedFrequency = getMaximumRequestedFrequency(token)
val (bytes, nextToken) =
existingOutputOr(token) {
val requestBuilder =
CompleteExecutionPhaseTwoRequest.newBuilder().apply {
localElGamalKeyPair = llv2Details.localElgamalKey
compositeElGamalPublicKey = llv2Details.combinedPublicKey
curveId = llv2Parameters.ellipticCurveId.toLong()
flagCountTuples = readAndCombineAllInputBlobs(token, 1)
}
if (llv2Parameters.noise.hasFrequencyNoiseConfig()) {
requestBuilder.apply {
partialCompositeElGamalPublicKey = llv2Details.partiallyCombinedPublicKey
if (maximumRequestedFrequency > 1) {
noiseParameters = getFrequencyNoiseParams(token, llv2Parameters)
}
}
}
val cryptoResult: CompleteExecutionPhaseTwoResponse =
cryptoWorker.completeExecutionPhaseTwo(requestBuilder.build())
logStageDurationMetric(
token,
CRYPTO_LIB_CPU_DURATION,
cryptoResult.elapsedCpuTimeMillis,
executionPhaseTwoCryptoCpuTimeDurationHistogram
)
cryptoResult.flagCountTuples
}
// Passes the computation to the next duchy.
sendAdvanceComputationRequest(
header =
advanceComputationHeader(
LiquidLegionsV2.Description.EXECUTION_PHASE_TWO_INPUT,
token.globalComputationId
),
content = addLoggingHook(token, bytes),
stub = nextDuchyStub(llv2Details.participantList)
)
return if (maximumRequestedFrequency == 1) {
// If this is a reach-only computation, then our job is done.
completeComputation(nextToken, CompletedReason.SUCCEEDED)
} else {
dataClients.transitionComputationToStage(
nextToken,
inputsToNextStage = nextToken.outputPathList(),
stage = Stage.WAIT_EXECUTION_PHASE_THREE_INPUTS.toProtocolStage()
)
}
}
private suspend fun completeExecutionPhaseThreeAtAggregator(
token: ComputationToken
): ComputationToken {
val llv2Details = token.computationDetails.liquidLegionsV2
val llv2Parameters = llv2Details.parameters
require(AGGREGATOR == llv2Details.role) { "invalid role for this function." }
require(llv2Details.hasReachEstimate()) { "Reach estimate is missing." }
val (bytes, nextToken) =
existingOutputOr(token) {
val requestBuilder =
CompleteExecutionPhaseThreeAtAggregatorRequest.newBuilder().apply {
localElGamalKeyPair = llv2Details.localElgamalKey
curveId = llv2Parameters.ellipticCurveId.toLong()
sameKeyAggregatorMatrix = readAndCombineAllInputBlobs(token, 1)
maximumFrequency = getMaximumRequestedFrequency(token)
}
if (llv2Parameters.noise.hasFrequencyNoiseConfig()) {
requestBuilder.globalFrequencyDpNoisePerBucketBuilder.apply {
contributorsCount = workerStubs.size + 1
dpParams = llv2Parameters.noise.frequencyNoiseConfig
}
}
val cryptoResult: CompleteExecutionPhaseThreeAtAggregatorResponse =
cryptoWorker.completeExecutionPhaseThreeAtAggregator(requestBuilder.build())
logStageDurationMetric(
token,
CRYPTO_LIB_CPU_DURATION,
cryptoResult.elapsedCpuTimeMillis,
executionPhaseThreeCryptoCpuTimeDurationHistogram
)
cryptoResult.toByteString()
}
val frequencyDistributionMap =
CompleteExecutionPhaseThreeAtAggregatorResponse.parseFrom(bytes.flatten())
.frequencyDistributionMap
sendResultToKingdom(token, llv2Details.reachEstimate.reach, frequencyDistributionMap)
return completeComputation(nextToken, CompletedReason.SUCCEEDED)
}
private suspend fun completeExecutionPhaseThreeAtNonAggregator(
token: ComputationToken
): ComputationToken {
val llv2Details = token.computationDetails.liquidLegionsV2
val llv2Parameters = llv2Details.parameters
require(NON_AGGREGATOR == llv2Details.role) { "invalid role for this function." }
val (bytes, nextToken) =
existingOutputOr(token) {
val cryptoResult: CompleteExecutionPhaseThreeResponse =
cryptoWorker.completeExecutionPhaseThree(
CompleteExecutionPhaseThreeRequest.newBuilder()
.apply {
localElGamalKeyPair = llv2Details.localElgamalKey
curveId = llv2Parameters.ellipticCurveId.toLong()
sameKeyAggregatorMatrix = readAndCombineAllInputBlobs(token, 1)
}
.build()
)
logStageDurationMetric(
token,
CRYPTO_LIB_CPU_DURATION,
cryptoResult.elapsedCpuTimeMillis,
executionPhaseThreeCryptoCpuTimeDurationHistogram
)
cryptoResult.sameKeyAggregatorMatrix
}
// Passes the computation to the next duchy.
sendAdvanceComputationRequest(
header =
advanceComputationHeader(
LiquidLegionsV2.Description.EXECUTION_PHASE_THREE_INPUT,
token.globalComputationId
),
content = addLoggingHook(token, bytes),
stub = nextDuchyStub(llv2Details.participantList)
)
// This duchy's responsibility for the computation is done. Mark it COMPLETED locally.
return completeComputation(nextToken, CompletedReason.SUCCEEDED)
}
private suspend fun sendResultToKingdom(
token: ComputationToken,
reach: Long,
frequency: Map<Long, Double>
) {
val reachAndFrequency = ReachAndFrequency(reach, frequency)
val kingdomComputation = token.computationDetails.kingdomComputation
val serializedPublicApiEncryptionPublicKey: ByteString
val encryptedResult =
when (Version.fromString(kingdomComputation.publicApiVersion)) {
Version.V2_ALPHA -> {
val signedResult = signResult(reachAndFrequency.toV2AlphaMeasurementResult(), signingKey)
val publicApiEncryptionPublicKey =
kingdomComputation.measurementPublicKey.toV2AlphaEncryptionPublicKey()
serializedPublicApiEncryptionPublicKey = publicApiEncryptionPublicKey.toByteString()
encryptResult(signedResult, publicApiEncryptionPublicKey)
}
Version.VERSION_UNSPECIFIED -> error("Public api version is invalid or unspecified.")
}
sendResultToKingdom(
globalId = token.globalComputationId,
certificate = consentSignalCert,
resultPublicKey = serializedPublicApiEncryptionPublicKey,
encryptedResult = encryptedResult
)
}
private fun nextDuchyStub(
duchyList: List<ComputationParticipant>
): ComputationControlCoroutineStub {
val index = duchyList.indexOfFirst { it.duchyId == duchyId }
val nextDuchy = duchyList[(index + 1) % duchyList.size].duchyId
return workerStubs[nextDuchy]
?: throw PermanentComputationError(
IllegalArgumentException("No ComputationControlService stub for next duchy '$nextDuchy'")
)
}
private fun aggregatorDuchyStub(aggregatorId: String): ComputationControlCoroutineStub {
return workerStubs[aggregatorId]
?: throw PermanentComputationError(
IllegalArgumentException(
"No ComputationControlService stub for the Aggregator duchy '$aggregatorId'"
)
)
}
private fun ByteString.toCompleteSetupPhaseRequest(
token: ComputationToken,
llv2Details: LiquidLegionsSketchAggregationV2.ComputationDetails,
totalRequisitionsCount: Int
): CompleteSetupPhaseRequest {
val noiseConfig = llv2Details.parameters.noise
val requestBuilder = CompleteSetupPhaseRequest.newBuilder().setCombinedRegisterVector(this)
requestBuilder.maximumFrequency = getMaximumRequestedFrequency(token)
if (noiseConfig.hasReachNoiseConfig()) {
requestBuilder.noiseParametersBuilder.apply {
compositeElGamalPublicKey = llv2Details.combinedPublicKey
curveId = llv2Details.parameters.ellipticCurveId.toLong()
contributorsCount = workerStubs.size + 1
totalSketchesCount = totalRequisitionsCount
dpParamsBuilder.apply {
blindHistogram = noiseConfig.reachNoiseConfig.blindHistogramNoise
noiseForPublisherNoise = noiseConfig.reachNoiseConfig.noiseForPublisherNoise
globalReachDpNoise = noiseConfig.reachNoiseConfig.globalReachDpNoise
}
}
}
return requestBuilder.build()
}
private fun getFrequencyNoiseParams(
token: ComputationToken,
llv2Parameters: Parameters
): FlagCountTupleNoiseGenerationParameters {
return FlagCountTupleNoiseGenerationParameters.newBuilder()
.apply {
maximumFrequency = getMaximumRequestedFrequency(token)
contributorsCount = workerStubs.size + 1
dpParams = llv2Parameters.noise.frequencyNoiseConfig
}
.build()
}
private fun getMaximumRequestedFrequency(token: ComputationToken): Int {
var maximumRequestedFrequency =
token.computationDetails.liquidLegionsV2.parameters.maximumFrequency
val measurementSpec =
MeasurementSpec.parseFrom(token.computationDetails.kingdomComputation.measurementSpec)
val measurementSpecMaximumFrequency = measurementSpec.reachAndFrequency.maximumFrequencyPerUser
if (measurementSpecMaximumFrequency > 0) {
maximumRequestedFrequency = min(maximumRequestedFrequency, measurementSpecMaximumFrequency)
}
return maximumRequestedFrequency
}
companion object {
init {
loadLibrary(
name = "estimators",
directoryPath = Paths.get("any_sketch_java/src/main/java/org/wfanet/estimation")
)
loadLibrary(
name = "sketch_encrypter_adapter",
directoryPath = Paths.get("any_sketch_java/src/main/java/org/wfanet/anysketch/crypto")
)
}
private val logger: Logger = Logger.getLogger(this::class.java.name)
}
}
| apache-2.0 | 3988737c6ecda4471154a1ea6ff3f3b8 | 42.378958 | 128 | 0.7346 | 4.771149 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.