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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/chain/AbstractCallChainHintsProvider.kt | 1 | 6456 | // 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.codeInsight.hints.chain
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.hints.*
import com.intellij.codeInsight.hints.presentation.InlayPresentation
import com.intellij.codeInsight.hints.presentation.PresentationFactory
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.ui.JBIntSpinner
import com.intellij.ui.layout.*
import com.intellij.util.asSafely
import com.intellij.util.ui.JBUI
import javax.swing.JPanel
import javax.swing.JSpinner
import javax.swing.text.DefaultFormatter
abstract class AbstractCallChainHintsProvider<DotQualifiedExpression : PsiElement, ExpressionType, TypeComputationContext> :
InlayHintsProvider<AbstractCallChainHintsProvider.Settings> {
override fun getCollectorFor(file: PsiFile, editor: Editor, settings: Settings, sink: InlayHintsSink): InlayHintsCollector? {
if (file.project.isDefault) return null
return object : FactoryInlayHintsCollector(editor) {
override fun collect(element: PsiElement, editor: Editor, sink: InlayHintsSink): Boolean {
if (file.project.service<DumbService>().isDumb) return true
val topmostDotQualifiedExpression = element.safeCastUsing(dotQualifiedClass)
// We will process the whole chain using topmost DotQualifiedExpression.
// If the current one has parent then it means that it's not topmost DotQualifiedExpression
?.takeIf { it.getParentDotQualifiedExpression() == null }
?: return true
data class ExpressionWithType(val expression: PsiElement, val type: ExpressionType)
val context = getTypeComputationContext(topmostDotQualifiedExpression)
var someTypeIsUnknown = false
val reversedChain =
generateSequence<PsiElement>(topmostDotQualifiedExpression) {
it.skipParenthesesAndPostfixOperatorsDown()?.safeCastUsing(dotQualifiedClass)?.getReceiver()
}
.drop(1) // Except last to avoid builder.build() which has obvious type
.filter { it.nextSibling.asSafely<PsiWhiteSpace>()?.textContains('\n') == true }
.map { it to it.getType(context) }
.takeWhile { (_, type) -> (type != null).also { if (!it) someTypeIsUnknown = true } }
.map { (expression, type) -> ExpressionWithType(expression, type!!) }
.windowed(2, partialWindows = true) { it.first() to it.getOrNull(1) }
.filter { (expressionWithType, prevExpressionWithType) ->
if (prevExpressionWithType == null) {
// Show type for expression in call chain on the first line only if it's dot qualified
dotQualifiedClass.isInstance(expressionWithType.expression.skipParenthesesAndPostfixOperatorsDown())
}
else {
expressionWithType.type != prevExpressionWithType.type ||
!dotQualifiedClass.isInstance(prevExpressionWithType.expression.skipParenthesesAndPostfixOperatorsDown())
}
}
.map { it.first }
.toList()
if (someTypeIsUnknown) return true
if (reversedChain.asSequence().distinctBy { it.type }.count() < settings.uniqueTypeCount) return true
for ((expression, type) in reversedChain) {
sink.addInlineElement(
expression.textRange.endOffset,
true,
type.getInlayPresentation(expression, factory, file.project, context),
false
)
}
return true
}
}
}
override val name: String
get() = CodeInsightBundle.message("inlay.hints.chain.call.chain")
final override fun createConfigurable(settings: Settings): ImmediateConfigurable = object : ImmediateConfigurable {
val uniqueTypeCountName = CodeInsightBundle.message("inlay.hints.chain.minimal.unique.type.count.to.show.hints")
private val uniqueTypeCount = JBIntSpinner(1, 1, 10)
override fun createComponent(listener: ChangeListener): JPanel {
reset()
// Workaround to get immediate change, not only when focus is lost. To be changed after moving to polling model
val formatter = (uniqueTypeCount.editor as JSpinner.NumberEditor).textField.formatter as DefaultFormatter
formatter.commitsOnValidEdit = true
uniqueTypeCount.addChangeListener {
handleChange(listener)
}
val panel = panel {
row {
label(uniqueTypeCountName)
uniqueTypeCount(pushX)
}
}
panel.border = JBUI.Borders.empty(5)
return panel
}
override fun reset() {
uniqueTypeCount.value = settings.uniqueTypeCount
}
private fun handleChange(listener: ChangeListener) {
settings.uniqueTypeCount = uniqueTypeCount.number
listener.settingsChanged()
}
}
protected abstract fun ExpressionType.getInlayPresentation(
expression: PsiElement,
factory: PresentationFactory,
project: Project,
context: TypeComputationContext
): InlayPresentation
protected abstract fun PsiElement.getType(context: TypeComputationContext): ExpressionType?
protected abstract val dotQualifiedClass: Class<DotQualifiedExpression>
/**
* Implementation must NOT skip parentheses and postfix operators
*/
protected abstract fun DotQualifiedExpression.getReceiver(): PsiElement?
protected abstract fun DotQualifiedExpression.getParentDotQualifiedExpression(): DotQualifiedExpression?
protected abstract fun PsiElement.skipParenthesesAndPostfixOperatorsDown(): PsiElement?
protected abstract fun getTypeComputationContext(topmostDotQualifiedExpression: DotQualifiedExpression): TypeComputationContext
private fun <T> Any.safeCastUsing(clazz: Class<T>) = if (clazz.isInstance(this)) clazz.cast(this) else null
final override fun createSettings() = Settings()
data class Settings(var uniqueTypeCount: Int) {
constructor() : this(2)
}
}
| apache-2.0 | f37b2adfa53fceb1f07b5a80adfbea51 | 42.918367 | 158 | 0.706939 | 5.144223 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/index/actions/GitStageShowVersionAction.kt | 6 | 3212 | // 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 git4idea.index.actions
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.impl.LineStatusTrackerManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.OpenSourceUtil
import git4idea.index.*
import git4idea.index.vfs.GitIndexFileSystemRefresher
import git4idea.index.vfs.GitIndexVirtualFile
import git4idea.index.vfs.filePath
abstract class GitStageShowVersionAction(private val showStaged: Boolean) : DumbAwareAction() {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun update(e: AnActionEvent) {
val project = e.project
val file = e.getData(CommonDataKeys.VIRTUAL_FILE)
if (project == null || !isStagingAreaAvailable(project) || file == null
|| (file is GitIndexVirtualFile == showStaged)) {
e.presentation.isEnabledAndVisible = false
return
}
val status = GitStageTracker.getInstance(project).status(file)
e.presentation.isVisible = (status != null)
e.presentation.isEnabled = (status?.has(if (showStaged) ContentVersion.STAGED else ContentVersion.LOCAL) == true)
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val sourceFile = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE)
val root = getRoot(project, sourceFile) ?: return
val targetFile = if (showStaged) {
GitIndexFileSystemRefresher.getInstance(project).getFile(root, sourceFile.filePath())
}
else {
sourceFile.filePath().virtualFile
} ?: return
val caret = e.getData(CommonDataKeys.CARET)
if (caret == null) {
OpenSourceUtil.navigate(OpenFileDescriptor(project, targetFile))
return
}
val targetPosition = getTargetPosition(project, sourceFile, targetFile, caret)
OpenSourceUtil.navigate(OpenFileDescriptor(project, targetFile, targetPosition.line, targetPosition.column))
}
private fun getTargetPosition(project: Project, sourceFile: VirtualFile, targetFile: VirtualFile, caret: Caret): LogicalPosition {
val lst = LineStatusTrackerManager.getInstance(project).getLineStatusTracker(if (showStaged) sourceFile else targetFile)
?: return caret.logicalPosition
if (lst !is GitStageLineStatusTracker) return caret.logicalPosition
val line = if (showStaged) {
lst.transferLineFromLocalToStaged(caret.logicalPosition.line, true)
}
else {
lst.transferLineFromStagedToLocal(caret.logicalPosition.line, true)
}
return LogicalPosition(line, caret.logicalPosition.column)
}
}
class GitShowStagedVersionAction : GitStageShowVersionAction(true)
class GitShowLocalVersionAction : GitStageShowVersionAction(false) | apache-2.0 | 7a98c7e8fe8cd8ba64911a22e0a22dd8 | 42.418919 | 140 | 0.773973 | 4.628242 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/routing/HostsRoutingBuilder.kt | 1 | 5728 | /*
* 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.server.routing
import io.ktor.http.*
import io.ktor.server.plugins.*
/**
* Creates a route to match a request's host and port.
* There are no any host resolutions/transformations applied to a host: a request host is treated as a string.
*
* When passes, it puts a request host and port into
* call parameters by the [HostRouteSelector.HostNameParameter] and [HostRouteSelector.PortParameter] keys.
*
* @param host exact host name that is treated literally
* @param port to be tested or `0` to pass all ports
*/
public fun Route.host(host: String, port: Int = 0, build: Route.() -> Unit): Route {
return host(listOf(host), emptyList(), if (port > 0) listOf(port) else emptyList(), build)
}
/**
* Creates a route to match a request host and port.
* There are no any host resolutions/transformations applied to a host: a request host is treated as a string.
*
* When passes, it puts a request host and port into
* call parameters by the [HostRouteSelector.HostNameParameter] and [HostRouteSelector.PortParameter] keys.
*
* @param hostPattern is a regular expression to match request host
* @param port to be tested or `0` to pass all ports
*/
public fun Route.host(hostPattern: Regex, port: Int = 0, build: Route.() -> Unit): Route {
return host(emptyList(), listOf(hostPattern), if (port > 0) listOf(port) else emptyList(), build)
}
/**
* Creates a route to match a request host and port.
* There are no any host resolutions/transformations applied to a host: a request host is treated as a string.
*
* When passes, it puts request host and port into
* call parameters by the [HostRouteSelector.HostNameParameter] and [HostRouteSelector.PortParameter] keys.
*
* @param hosts a list of exact host names that are treated literally
* @param ports a list of ports to be passed or empty to pass all ports
*
* @throws IllegalArgumentException when no constraints were applied in [hosts] and [ports]
*/
public fun Route.host(hosts: List<String>, ports: List<Int> = emptyList(), build: Route.() -> Unit): Route {
return host(hosts, emptyList(), ports, build)
}
/**
* Creates a route to match s request host and port.
* There are no any host resolutions/transformations applied to a host: a request host is treated as a string.
*
* When passes, it puts request host and port into
* call parameters by the [HostRouteSelector.HostNameParameter] and [HostRouteSelector.PortParameter] keys.
*
* @param hosts a list of exact host names that are treated literally
* @param hostPatterns a list of regular expressions to match request host
* @param ports a list of ports to be passed or empty to pass all ports
*
* @throws IllegalArgumentException when no constraints were applied in [host], [hostPatterns] and [ports]
*/
public fun Route.host(
hosts: List<String>,
hostPatterns: List<Regex>,
ports: List<Int> = emptyList(),
build: Route.() -> Unit
): Route {
val selector = HostRouteSelector(hosts, hostPatterns, ports)
return createChild(selector).apply(build)
}
/**
* Creates a route to match a request port.
*
* When passes, it puts a request host and port into
* call parameters by the [HostRouteSelector.HostNameParameter] and [HostRouteSelector.PortParameter] keys.
*
* @param ports a list of ports to be passed
*
* @throws IllegalArgumentException if no ports were specified
*/
public fun Route.port(vararg ports: Int, build: Route.() -> Unit): Route {
require(ports.isNotEmpty()) { "At least one port need to be specified" }
val selector = HostRouteSelector(emptyList(), emptyList(), ports.toList())
return createChild(selector).apply(build)
}
/**
* Evaluates a route against a request's host and port.
* @param hostList contains exact host names
* @param hostPatterns contains host patterns to match
* @param portsList contains possible ports or empty to match all ports
*/
public data class HostRouteSelector(
val hostList: List<String>,
val hostPatterns: List<Regex>,
val portsList: List<Int>
) : RouteSelector() {
init {
require(hostList.isNotEmpty() || hostPatterns.isNotEmpty() || portsList.isNotEmpty())
}
override fun evaluate(context: RoutingResolveContext, segmentIndex: Int): RouteSelectorEvaluation {
val requestHost = context.call.request.origin.serverHost
val requestPort = context.call.request.origin.serverPort
if (hostList.isNotEmpty() || hostPatterns.isNotEmpty()) {
val matches1 = requestHost in hostList
val matches2 = if (!matches1) hostPatterns.any { it.matches(requestHost) } else false
if (!matches1 && !matches2) {
return RouteSelectorEvaluation.Failed
}
}
if (portsList.isNotEmpty()) {
if (requestPort !in portsList) return RouteSelectorEvaluation.Failed
}
val params = Parameters.build {
append(HostNameParameter, requestHost)
append(PortParameter, requestPort.toString())
}
return RouteSelectorEvaluation.Success(RouteSelectorEvaluation.qualityConstant, params)
}
override fun toString(): String = "($hostList, $hostPatterns, $portsList)"
public companion object {
/**
* A parameter name for [RoutingApplicationCall.parameters] for a request host.
*/
public const val HostNameParameter: String = "\$RequestHost"
/**
* A parameter name for [RoutingApplicationCall.parameters] for a request port.
*/
public const val PortParameter: String = "\$RequestPort"
}
}
| apache-2.0 | 1a781961758d731623c27421c1aaf2b8 | 37.965986 | 118 | 0.705133 | 4.199413 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/util/lang/RetryWithDelay.kt | 2 | 781 | package eu.kanade.tachiyomi.util.lang
import rx.Observable
import rx.Scheduler
import rx.functions.Func1
import rx.schedulers.Schedulers
import java.util.concurrent.TimeUnit.MILLISECONDS
class RetryWithDelay(
private val maxRetries: Int = 1,
private val retryStrategy: (Int) -> Int = { 1000 },
private val scheduler: Scheduler = Schedulers.computation()
) : Func1<Observable<out Throwable>, Observable<*>> {
private var retryCount = 0
override fun call(attempts: Observable<out Throwable>) = attempts.flatMap { error ->
val count = ++retryCount
if (count <= maxRetries) {
Observable.timer(retryStrategy(count).toLong(), MILLISECONDS, scheduler)
} else {
Observable.error(error as Throwable)
}
}
}
| apache-2.0 | b0341c9e5d80a68e996e7e01f0bcaf75 | 30.24 | 88 | 0.690141 | 4.412429 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/Kitsu.kt | 1 | 4782 | package eu.kanade.tachiyomi.data.track.kitsu
import android.content.Context
import android.graphics.Color
import androidx.annotation.StringRes
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.track.TrackService
import eu.kanade.tachiyomi.data.track.model.TrackSearch
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import uy.kohesive.injekt.injectLazy
import java.text.DecimalFormat
class Kitsu(private val context: Context, id: Int) : TrackService(id) {
companion object {
const val READING = 1
const val COMPLETED = 2
const val ON_HOLD = 3
const val DROPPED = 4
const val PLAN_TO_READ = 5
}
@StringRes
override fun nameRes() = R.string.tracker_kitsu
override val supportsReadingDates: Boolean = true
private val json: Json by injectLazy()
private val interceptor by lazy { KitsuInterceptor(this) }
private val api by lazy { KitsuApi(client, interceptor) }
override fun getLogo() = R.drawable.ic_tracker_kitsu
override fun getLogoColor() = Color.rgb(51, 37, 50)
override fun getStatusList(): List<Int> {
return listOf(READING, COMPLETED, ON_HOLD, DROPPED, PLAN_TO_READ)
}
override fun getStatus(status: Int): String = with(context) {
when (status) {
READING -> getString(R.string.reading)
PLAN_TO_READ -> getString(R.string.plan_to_read)
COMPLETED -> getString(R.string.completed)
ON_HOLD -> getString(R.string.on_hold)
DROPPED -> getString(R.string.dropped)
else -> ""
}
}
override fun getReadingStatus(): Int = READING
override fun getRereadingStatus(): Int = -1
override fun getCompletionStatus(): Int = COMPLETED
override fun getScoreList(): List<String> {
val df = DecimalFormat("0.#")
return listOf("0") + IntRange(2, 20).map { df.format(it / 2f) }
}
override fun indexToScore(index: Int): Float {
return if (index > 0) (index + 1) / 2f else 0f
}
override fun displayScore(track: Track): String {
val df = DecimalFormat("0.#")
return df.format(track.score)
}
private suspend fun add(track: Track): Track {
return api.addLibManga(track, getUserId())
}
override suspend fun update(track: Track, didReadChapter: Boolean): Track {
if (track.status != COMPLETED) {
if (didReadChapter) {
if (track.last_chapter_read.toInt() == track.total_chapters && track.total_chapters > 0) {
track.status = COMPLETED
track.finished_reading_date = System.currentTimeMillis()
} else {
track.status = READING
if (track.last_chapter_read == 1F) {
track.started_reading_date = System.currentTimeMillis()
}
}
}
}
return api.updateLibManga(track)
}
override suspend fun bind(track: Track, hasReadChapters: Boolean): Track {
val remoteTrack = api.findLibManga(track, getUserId())
return if (remoteTrack != null) {
track.copyPersonalFrom(remoteTrack)
track.media_id = remoteTrack.media_id
if (track.status != COMPLETED) {
track.status = if (hasReadChapters) READING else track.status
}
update(track)
} else {
track.status = if (hasReadChapters) READING else PLAN_TO_READ
track.score = 0F
add(track)
}
}
override suspend fun search(query: String): List<TrackSearch> {
return api.search(query)
}
override suspend fun refresh(track: Track): Track {
val remoteTrack = api.getLibManga(track)
track.copyPersonalFrom(remoteTrack)
track.total_chapters = remoteTrack.total_chapters
return track
}
override suspend fun login(username: String, password: String) {
val token = api.login(username, password)
interceptor.newAuth(token)
val userId = api.getCurrentUser()
saveCredentials(username, userId)
}
override fun logout() {
super.logout()
interceptor.newAuth(null)
}
private fun getUserId(): String {
return getPassword()
}
fun saveToken(oauth: OAuth?) {
preferences.trackToken(this).set(json.encodeToString(oauth))
}
fun restoreToken(): OAuth? {
return try {
json.decodeFromString<OAuth>(preferences.trackToken(this).get())
} catch (e: Exception) {
null
}
}
}
| apache-2.0 | d9760fcbfd02b0b5bacf6ef800c52635 | 30.051948 | 106 | 0.620033 | 4.427778 | false | false | false | false |
ClearVolume/scenery | src/test/kotlin/graphics/scenery/tests/examples/basic/TexturedCubeExample.kt | 1 | 1804 | package graphics.scenery.tests.examples.basic
import org.joml.Vector3f
import graphics.scenery.*
import graphics.scenery.backends.Renderer
import graphics.scenery.textures.Texture
import graphics.scenery.utils.Image
import kotlin.concurrent.thread
/**
* <Description>
*
* @author Ulrik Günther <[email protected]>
*/
class TexturedCubeExample : SceneryBase("TexturedCubeExample", wantREPL = System.getProperty("scenery.master", "false").toBoolean()) {
override fun init() {
renderer = hub.add(SceneryElement.Renderer,
Renderer.createRenderer(hub, applicationName, scene, 512, 512))
val box = Box(Vector3f(1.0f, 1.0f, 1.0f))
box.name = "le box du win"
box.material {
textures["diffuse"] = Texture.fromImage(Image.fromResource("textures/helix.png", TexturedCubeExample::class.java))
metallic = 0.3f
roughness = 0.9f
}
scene.addChild(box)
val light = PointLight(radius = 15.0f)
light.spatial().position = Vector3f(0.0f, 0.0f, 2.0f)
light.intensity = 5.0f
light.emissionColor = Vector3f(1.0f, 1.0f, 1.0f)
scene.addChild(light)
val cam: Camera = DetachedHeadCamera()
with(cam) {
spatial {
position = Vector3f(0.0f, 0.0f, 5.0f)
}
perspectiveCamera(50.0f, 512, 512)
scene.addChild(this)
}
thread {
while (running) {
box.spatial {
rotation.rotateY(0.01f)
needsUpdate = true
}
Thread.sleep(20)
}
}
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
TexturedCubeExample().main()
}
}
}
| lgpl-3.0 | 226e45f3082982fee4637eb376698f4d | 27.171875 | 134 | 0.576816 | 3.902597 | false | false | false | false |
JonathanxD/CodeAPI | src/main/kotlin/com/github/jonathanxd/kores/MutableInstructions.kt | 1 | 5318 | /*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* 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.github.jonathanxd.kores
import java.util.*
import java.util.function.Predicate
import java.util.function.UnaryOperator
/**
* A mutable [Instructions] backing to a [ArrayList] instead of to an [Array].
*/
abstract class MutableInstructions : Instructions(), Cloneable {
/**
* Removes all [Instruction]s that matches [filter].
*/
abstract fun removeIf(filter: Predicate<in Instruction>): Boolean
/**
* Replaces each element with element returned by [operator].
*/
abstract fun replaceAll(operator: UnaryOperator<Instruction>)
/**
* Sorts this [MutableInstructions] using [Comparator] [c].
*/
abstract fun sort(c: Comparator<in Instruction>)
/**
* Adds [instruction] to list.
*/
abstract fun add(instruction: Instruction): Boolean
/**
* Removes [o] from list.
*/
abstract fun remove(o: Any): Boolean
/**
* Adds all [Instruction] of [c] into this list.
*/
abstract fun addAll(c: Collection<Instruction>): Boolean
/**
* Adds all [Instruction] of [c] into this list.
*/
fun addAll(c: Iterable<Instruction>): Boolean {
var any = false
for (part in c) {
any = any or this.add(part)
}
return any
}
/**
* Adds all [Instruction] of [c] into this list at [index].
*/
abstract fun addAll(index: Int, c: Collection<Instruction>): Boolean
/**
* Adds all [Instruction] of [c] into this list at [index].
*/
abstract fun addAll(index: Int, c: Iterable<Instruction>): Boolean
/**
* Removes all elements which is present in [c] from this list.
*/
abstract fun removeAll(c: Collection<*>): Boolean
/**
* Retains all elements which is present in [c] in this list.
*/
abstract fun retainAll(c: Collection<*>): Boolean
/**
* Removes all elements which is present in [c] from this list.
*/
abstract fun removeAll(c: Iterable<Instruction>): Boolean
/**
* Retains all elements which is present in [c] in this list.
*/
abstract fun retainAll(c: Iterable<Instruction>): Boolean
/**
* Clears this list.
*/
abstract fun clear()
/**
* Adds [element] at [index].
*/
abstract fun add(index: Int, element: Instruction)
/**
* Sets element at [index] to [element].
*/
abstract operator fun set(index: Int, element: Instruction): Instruction
/**
* Removes [Instruction] which is at [index]. And returns removed element.
*/
abstract fun remove(index: Int): Instruction
/**
* Adds all elements of [other] to this list.
*/
abstract operator fun plusAssign(other: Iterable<Instruction>)
/**
* Removes all elements of [other] from this list.
*/
abstract operator fun minusAssign(other: Iterable<Instruction>)
/**
* Adds [other] to this list.
*/
abstract operator fun plusAssign(other: Instruction)
/**
* Removes [other] from this list.
*/
abstract operator fun minusAssign(other: Instruction)
override fun toString(): String =
if (this.isEmpty) "MutableInstructions[]" else "MutableInstructions[...]"
companion object {
/**
* Create a [MutableInstructions].
*/
@JvmStatic
fun create(): MutableInstructions = ListInstructions()
/**
* Create a [MutableInstructions] from a copy of [list].
*/
@JvmStatic
fun create(list: List<Instruction>): MutableInstructions =
ListInstructions(list.toMutableList())
/**
* Create a [MutableInstructions] delegating to [list].
*/
@JvmStatic
fun delegate(list: MutableList<Instruction>): MutableInstructions =
ListInstructions(list)
}
}
| mit | 39f3e295288f6451f45eb2bef69d37d2 | 28.876404 | 118 | 0.635013 | 4.560892 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/actions/AddDependencyAction.kt | 2 | 4340 | /*******************************************************************************
* 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.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiUtilBase
import com.jetbrains.packagesearch.PackageSearchIcons
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleOperationProvider
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.PackageSearchToolWindowFactory
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ModuleModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules
import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectService
import com.jetbrains.packagesearch.intellij.plugin.util.uiStateModifier
class AddDependencyAction : AnAction(
PackageSearchBundle.message("packagesearch.actions.addDependency.text"),
PackageSearchBundle.message("packagesearch.actions.addDependency.description"),
PackageSearchIcons.Artifact
) {
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = run {
val project = e.project ?: return@run false
val dataContext = e.dataContext
val editor = CommonDataKeys.EDITOR.getData(dataContext) ?: return@run false
val psiFile: PsiFile? = PsiUtilBase.getPsiFileInEditor(editor, project)
if (psiFile == null || ProjectModuleOperationProvider.forProjectPsiFileOrNull(project, psiFile) == null) {
return@run false
}
val modules = project.packageSearchProjectService.moduleModelsStateFlow.value
findSelectedModule(e, modules) != null
}
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val modules = project.packageSearchProjectService.moduleModelsStateFlow.value
if (modules.isEmpty()) return
val selectedModule = findSelectedModule(e, modules) ?: return
PackageSearchToolWindowFactory.activateToolWindow(project) {
project.uiStateModifier.setTargetModules(TargetModules.One(selectedModule))
}
}
private fun findSelectedModule(e: AnActionEvent, modules: List<ModuleModel>): ModuleModel? {
val project = e.project ?: return null
val file = obtainSelectedProjectDirIfSingle(e)?.virtualFile ?: return null
val selectedModule = runReadAction { ModuleUtilCore.findModuleForFile(file, project) } ?: return null
// Sanity check that the module we got actually exists
ModuleManager.getInstance(project).findModuleByName(selectedModule.name)
?: return null
return modules.firstOrNull { module -> module.projectModule.nativeModule == selectedModule }
}
private fun obtainSelectedProjectDirIfSingle(e: AnActionEvent): PsiDirectory? {
val dataContext = e.dataContext
val ideView = LangDataKeys.IDE_VIEW.getData(dataContext)
val selectedDirectories = ideView?.directories ?: return null
if (selectedDirectories.size != 1) return null
return selectedDirectories.first()
}
}
| apache-2.0 | 953b2fcc5f113d12a1347716aba4b4d7 | 44.684211 | 118 | 0.730184 | 5.210084 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/ide-features-trainer/src/training/ui/LessonMessagePane.kt | 2 | 26181 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package training.ui
import com.intellij.icons.AllIcons
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.FontPreferences
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManagerListener
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.*
import training.FeaturesTrainerIcons
import training.dsl.TaskTextProperties
import training.learn.lesson.LessonManager
import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.font.GlyphVector
import java.awt.geom.Point2D
import java.awt.geom.Rectangle2D
import java.awt.geom.RoundRectangle2D
import javax.swing.Icon
import javax.swing.JTextPane
import javax.swing.text.AttributeSet
import javax.swing.text.BadLocationException
import javax.swing.text.SimpleAttributeSet
import javax.swing.text.StyleConstants
import kotlin.math.roundToInt
internal class LessonMessagePane(private val panelMode: Boolean = true) : JTextPane(), Disposable {
//Style Attributes for LessonMessagePane(JTextPane)
private val INACTIVE = SimpleAttributeSet()
private val REGULAR = SimpleAttributeSet()
private val BOLD = SimpleAttributeSet()
private val SHORTCUT = SimpleAttributeSet()
private val ROBOTO = SimpleAttributeSet()
private val CODE = SimpleAttributeSet()
private val LINK = SimpleAttributeSet()
private var codeFontSize = UISettings.getInstance().fontSize.toInt()
private val TASK_PARAGRAPH_STYLE = SimpleAttributeSet()
private val INTERNAL_PARAGRAPH_STYLE = SimpleAttributeSet()
private val BALLOON_STYLE = SimpleAttributeSet()
private val textColor: Color = if (panelMode) UISettings.getInstance().defaultTextColor else UISettings.getInstance().tooltipTextColor
private val codeForegroundColor: Color = if (panelMode) UISettings.getInstance().codeForegroundColor else UISettings.getInstance().tooltipTextColor
enum class MessageState { NORMAL, PASSED, INACTIVE, RESTORE, INFORMER }
data class MessageProperties(val state: MessageState = MessageState.NORMAL,
val visualIndex: Int? = null,
val useInternalParagraphStyle: Boolean = false,
val textProperties: TaskTextProperties? = null)
private data class LessonMessage(
val messageParts: List<MessagePart>,
var state: MessageState,
val visualIndex: Int?,
val useInternalParagraphStyle: Boolean,
val textProperties: TaskTextProperties?,
var start: Int = 0,
var end: Int = 0
)
private data class RangeData(var range: IntRange, val action: (Point, Int) -> Unit)
private val activeMessages = mutableListOf<LessonMessage>()
private val restoreMessages = mutableListOf<LessonMessage>()
private val inactiveMessages = mutableListOf<LessonMessage>()
private val fontFamily: String get() = StartupUiUtil.getLabelFont().fontName
private val ranges = mutableSetOf<RangeData>()
private var insertOffset: Int = 0
private var paragraphStyle = SimpleAttributeSet()
private fun allLessonMessages() = activeMessages + restoreMessages + inactiveMessages
var currentAnimation = 0
var totalAnimation = 0
//, fontFace, check_width + check_right_indent
init {
UIUtil.doNotScrollToCaret(this)
initStyleConstants()
isEditable = false
val listener = object : MouseAdapter() {
override fun mouseClicked(me: MouseEvent) {
val rangeData = getRangeDataForMouse(me) ?: return
val middle = (rangeData.range.first + rangeData.range.last) / 2
val rectangle = modelToView2D(middle)
rangeData.action(Point(rectangle.x.roundToInt(), (rectangle.y.roundToInt() + rectangle.height.roundToInt() / 2)),
rectangle.height.roundToInt())
}
override fun mouseMoved(me: MouseEvent) {
val rangeData = getRangeDataForMouse(me)
cursor = if (rangeData == null) {
Cursor.getDefaultCursor()
}
else {
Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
}
}
}
addMouseListener(listener)
addMouseMotionListener(listener)
val connect = ApplicationManager.getApplication().messageBus.connect(this)
connect.subscribe(KeymapManagerListener.TOPIC, object : KeymapManagerListener {
override fun activeKeymapChanged(keymap: Keymap?) {
redrawMessages()
}
override fun shortcutChanged(keymap: Keymap, actionId: String) {
redrawMessages()
}
})
}
override fun dispose() = Unit
private fun getRangeDataForMouse(me: MouseEvent): RangeData? {
val offset = viewToModel2D(Point2D.Double(me.x.toDouble(), me.y.toDouble()))
val result = ranges.find { offset in it.range } ?: return null
if (offset < 0 || offset >= document.length) return null
for (i in result.range) {
val rectangle = modelToView2D(i)
if (me.x >= rectangle.x && me.y >= rectangle.y && me.y <= rectangle.y + rectangle.height) {
return result
}
}
return null
}
override fun addNotify() {
super.addNotify()
initStyleConstants()
redrawMessages()
}
override fun updateUI() {
super.updateUI()
ApplicationManager.getApplication().invokeLater(Runnable {
initStyleConstants()
redrawMessages()
})
}
private fun initStyleConstants() {
val fontSize = UISettings.getInstance().fontSize.toInt()
StyleConstants.setForeground(INACTIVE, UISettings.getInstance().inactiveColor)
StyleConstants.setFontFamily(REGULAR, fontFamily)
StyleConstants.setFontSize(REGULAR, fontSize)
StyleConstants.setFontFamily(BOLD, fontFamily)
StyleConstants.setFontSize(BOLD, fontSize)
StyleConstants.setBold(BOLD, true)
StyleConstants.setFontFamily(SHORTCUT, fontFamily)
StyleConstants.setFontSize(SHORTCUT, fontSize)
StyleConstants.setBold(SHORTCUT, true)
EditorColorsManager.getInstance().globalScheme.editorFontName
StyleConstants.setFontFamily(CODE, EditorColorsManager.getInstance().globalScheme.editorFontName)
StyleConstants.setFontSize(CODE, codeFontSize)
StyleConstants.setFontFamily(LINK, fontFamily)
StyleConstants.setUnderline(LINK, true)
StyleConstants.setFontSize(LINK, fontSize)
StyleConstants.setSpaceAbove(TASK_PARAGRAPH_STYLE, UISettings.getInstance().taskParagraphAbove.toFloat())
setCommonParagraphAttributes(TASK_PARAGRAPH_STYLE)
StyleConstants.setSpaceAbove(INTERNAL_PARAGRAPH_STYLE, UISettings.getInstance().taskInternalParagraphAbove.toFloat())
setCommonParagraphAttributes(INTERNAL_PARAGRAPH_STYLE)
StyleConstants.setLineSpacing(BALLOON_STYLE, 0.2f)
StyleConstants.setLeftIndent(BALLOON_STYLE, UISettings.getInstance().balloonIndent.toFloat())
StyleConstants.setForeground(REGULAR, textColor)
StyleConstants.setForeground(BOLD, textColor)
StyleConstants.setForeground(SHORTCUT, UISettings.getInstance().shortcutTextColor)
StyleConstants.setForeground(LINK, UISettings.getInstance().lessonLinkColor)
StyleConstants.setForeground(CODE, codeForegroundColor)
}
private fun setCommonParagraphAttributes(attributeSet: SimpleAttributeSet) {
StyleConstants.setLeftIndent(attributeSet, UISettings.getInstance().checkIndent.toFloat())
StyleConstants.setRightIndent(attributeSet, 0f)
StyleConstants.setSpaceBelow(attributeSet, 0.0f)
StyleConstants.setLineSpacing(attributeSet, 0.2f)
}
fun messagesNumber(): Int = activeMessages.size
@Suppress("SameParameterValue")
private fun removeMessagesRange(startIdx: Int, endIdx: Int, list: MutableList<LessonMessage>) {
if (startIdx == endIdx) return
list.subList(startIdx, endIdx).clear()
}
fun clearRestoreMessages(): () -> Rectangle? {
removeMessagesRange(0, restoreMessages.size, restoreMessages)
redrawMessages()
val lastOrNull = activeMessages.lastOrNull()
return { lastOrNull?.let { getRectangleToScroll(it) } }
}
fun removeInactiveMessages(number: Int) {
removeMessagesRange(0, number, inactiveMessages)
redrawMessages()
}
fun resetMessagesNumber(number: Int): () -> Rectangle? {
val move = activeMessages.subList(number, activeMessages.size)
move.forEach {
it.state = MessageState.INACTIVE
}
inactiveMessages.addAll(0, move)
move.clear()
return clearRestoreMessages()
}
fun getCurrentMessageRectangle(): Rectangle? {
val lessonMessage = restoreMessages.lastOrNull() ?: activeMessages.lastOrNull() ?: return null
return getRectangleToScroll(lessonMessage)
}
private fun insertText(text: String, attributeSet: AttributeSet) {
document.insertString(insertOffset, text, attributeSet)
styledDocument.setParagraphAttributes(insertOffset, text.length - 1, paragraphStyle, true)
insertOffset += text.length
}
fun addMessage(messageParts: List<MessagePart>, properties: MessageProperties = MessageProperties()): () -> Rectangle? {
val lessonMessage = LessonMessage(messageParts,
properties.state,
properties.visualIndex,
properties.useInternalParagraphStyle,
properties.textProperties,
)
when (properties.state) {
MessageState.INACTIVE -> inactiveMessages
MessageState.RESTORE -> restoreMessages
else -> activeMessages
}.add(lessonMessage)
redrawMessages()
return { getRectangleToScroll(lessonMessage) }
}
fun removeMessage(index: Int) {
activeMessages.removeAt(index)
}
private fun getRectangleToScroll(lessonMessage: LessonMessage): Rectangle? {
val startRect = modelToView2D(lessonMessage.start + 1)?.toRectangle() ?: return null
val endRect = modelToView2D(lessonMessage.end - 1)?.toRectangle() ?: return null
return Rectangle(startRect.x, startRect.y - activeTaskInset, endRect.x + endRect.width - startRect.x,
endRect.y + endRect.height - startRect.y + activeTaskInset * 2)
}
fun redrawMessages() {
initStyleConstants()
ranges.clear()
text = ""
insertOffset = 0
var previous: LessonMessage? = null
for (lessonMessage in allLessonMessages()) {
if (previous?.messageParts?.firstOrNull()?.type != MessagePart.MessageType.ILLUSTRATION) {
val textProperties = previous?.textProperties
paragraphStyle = when {
textProperties != null -> {
val customStyle = SimpleAttributeSet()
setCommonParagraphAttributes(customStyle)
StyleConstants.setSpaceAbove(customStyle, textProperties.spaceAbove.toFloat())
StyleConstants.setSpaceBelow(customStyle, textProperties.spaceBelow.toFloat())
customStyle
}
previous?.useInternalParagraphStyle == true -> INTERNAL_PARAGRAPH_STYLE
panelMode -> TASK_PARAGRAPH_STYLE
else -> BALLOON_STYLE
}
}
val messageParts: List<MessagePart> = lessonMessage.messageParts
lessonMessage.start = insertOffset
if (insertOffset != 0)
insertText("\n", paragraphStyle)
for (part in messageParts) {
part.updateTextAndSplit()
val startOffset = insertOffset
part.startOffset = startOffset
when (part.type) {
MessagePart.MessageType.TEXT_REGULAR -> insertText(part.text, REGULAR)
MessagePart.MessageType.TEXT_BOLD -> insertText(part.text, BOLD)
MessagePart.MessageType.SHORTCUT -> appendShortcut(part)?.let { ranges.add(it) }
MessagePart.MessageType.CODE -> insertText(part.text, CODE)
MessagePart.MessageType.CHECK -> insertText(part.text, ROBOTO)
MessagePart.MessageType.LINK -> appendLink(part)?.let { ranges.add(it) }
MessagePart.MessageType.ICON_IDX -> LearningUiManager.iconMap[part.text]?.let { addPlaceholderForIcon(it) }
MessagePart.MessageType.PROPOSE_RESTORE -> insertText(part.text, BOLD)
MessagePart.MessageType.ILLUSTRATION -> addPlaceholderForIllustration(part)
MessagePart.MessageType.LINE_BREAK -> {
insertText("\n", REGULAR)
paragraphStyle = INTERNAL_PARAGRAPH_STYLE
}
}
part.endOffset = insertOffset
}
lessonMessage.end = insertOffset
if (lessonMessage.state == MessageState.INACTIVE) {
setInactiveStyle(lessonMessage)
}
previous = lessonMessage
}
}
private fun addPlaceholderForIllustration(part: MessagePart) {
val illustration = LearningUiManager.iconMap[part.text]
if (illustration == null) {
thisLogger().error("No illustration for ${part.text}")
}
else {
val spaceAbove = spaceAboveIllustrationParagraph(illustration) + UISettings.getInstance().illustrationAbove
val illustrationStyle = SimpleAttributeSet()
StyleConstants.setSpaceAbove(illustrationStyle, spaceAbove.toFloat())
setCommonParagraphAttributes(illustrationStyle)
paragraphStyle = illustrationStyle
}
insertText(" ", REGULAR)
}
private fun spaceAboveIllustrationParagraph(illustration: Icon) = illustration.iconHeight - getFontMetrics(this.font).height + UISettings.getInstance().illustrationBelow
private fun addPlaceholderForIcon(icon: Icon) {
var placeholder = " "
while (this.getFontMetrics(this.font).stringWidth(placeholder) <= icon.iconWidth) {
placeholder += " "
}
placeholder += " "
insertText(placeholder, REGULAR)
}
fun passPreviousMessages() {
for (message in activeMessages) {
message.state = MessageState.PASSED
}
redrawMessages()
}
private fun setInactiveStyle(lessonMessage: LessonMessage) {
styledDocument.setCharacterAttributes(lessonMessage.start, lessonMessage.end, INACTIVE, false)
}
fun clear() {
text = ""
activeMessages.clear()
restoreMessages.clear()
inactiveMessages.clear()
ranges.clear()
}
/**
* Appends link inside JTextPane to Run another lesson
* @param messagePart - should have LINK type. message.runnable starts when the message has been clicked.
*/
@Throws(BadLocationException::class)
private fun appendLink(messagePart: MessagePart): RangeData? {
val clickRange = appendClickableRange(messagePart.text, LINK)
val runnable = messagePart.runnable ?: return null
return RangeData(clickRange) { _, _ -> runnable.run() }
}
private fun appendShortcut(messagePart: MessagePart): RangeData? {
val range = appendClickableRange(messagePart.text, SHORTCUT)
val actionId = messagePart.link ?: return null
val clickRange = IntRange(range.first + 1, range.last - 1) // exclude around spaces
return RangeData(clickRange) { p, h -> showShortcutBalloon(p, h, actionId) }
}
private fun showShortcutBalloon(point: Point2D, height: Int, actionName: String?) {
if (actionName == null) return
showActionKeyPopup(this, point.toPoint(), height, actionName)
}
private fun appendClickableRange(clickable: String, attributeSet: SimpleAttributeSet): IntRange {
val startLink = insertOffset
insertText(clickable, attributeSet)
val endLink = insertOffset
return startLink..endLink
}
override fun paintComponent(g: Graphics) {
adjustCodeFontSize(g)
try {
paintMessages(g)
}
catch (e: BadLocationException) {
LOG.warn(e)
}
super.paintComponent(g)
paintLessonCheckmarks(g)
drawTaskNumbers(g)
}
private fun adjustCodeFontSize(g: Graphics) {
val fontSize = StyleConstants.getFontSize(CODE)
val labelFont = UISettings.getInstance().plainFont
val (numberFont, _, _) = getNumbersFont(labelFont, g)
if (numberFont.size != fontSize) {
StyleConstants.setFontSize(CODE, numberFont.size)
codeFontSize = numberFont.size
redrawMessages()
}
}
private fun paintLessonCheckmarks(g: Graphics) {
val plainFont = UISettings.getInstance().plainFont
val fontMetrics = g.getFontMetrics(plainFont)
val height = if (g is Graphics2D) letterHeight(plainFont, g, "A") else fontMetrics.height
val baseLineOffset = fontMetrics.ascent + fontMetrics.leading
for (lessonMessage in allLessonMessages()) {
var startOffset = lessonMessage.start
if (startOffset != 0) startOffset++
val rectangle = modelToView2D(startOffset).toRectangle()
if (lessonMessage.messageParts.singleOrNull()?.type == MessagePart.MessageType.ILLUSTRATION) {
continue
}
val icon = if (lessonMessage.state == MessageState.PASSED) {
FeaturesTrainerIcons.Img.GreenCheckmark
}
else if (!LessonManager.instance.lessonIsRunning()) {
AllIcons.General.Information
}
else continue
val xShift = icon.iconWidth + UISettings.getInstance().numberTaskIndent
val y = rectangle.y + baseLineOffset - (height + icon.iconHeight + 1) / 2
icon.paintIcon(this, g, rectangle.x - xShift, y)
}
}
private data class FontSearchResult(val numberFont: Font, val numberHeight: Int, val textLetterHeight: Int)
private fun drawTaskNumbers(g: Graphics) {
val oldFont = g.font
val labelFont = UISettings.getInstance().plainFont
val (numberFont, numberHeight, textLetterHeight) = getNumbersFont(labelFont, g)
val textFontMetrics = g.getFontMetrics(labelFont)
val baseLineOffset = textFontMetrics.ascent + textFontMetrics.leading
g.font = numberFont
fun paintNumber(lessonMessage: LessonMessage, color: Color) {
var startOffset = lessonMessage.start
if (startOffset != 0) startOffset++
val s = lessonMessage.visualIndex?.toString()?.padStart(2, '0') ?: return
val width = textFontMetrics.stringWidth(s)
val modelToView2D = modelToView2D(startOffset)
val rectangle = modelToView2D.toRectangle()
val xOffset = rectangle.x - (width + UISettings.getInstance().numberTaskIndent)
val baseLineY = rectangle.y + baseLineOffset
val yOffset = baseLineY + (numberHeight - textLetterHeight)
val backupColor = g.color
g.color = color
GraphicsUtil.setupAAPainting(g)
g.drawString(s, xOffset, yOffset)
g.color = backupColor
}
for (lessonMessage in inactiveMessages) {
paintNumber(lessonMessage, UISettings.getInstance().futureTaskNumberColor)
}
if (activeMessages.lastOrNull()?.state != MessageState.PASSED || !panelMode) { // lesson can be opened as passed
val firstActiveMessage = firstActiveMessage()
if (firstActiveMessage != null) {
val color = if (panelMode) UISettings.getInstance().activeTaskNumberColor else UISettings.getInstance().tooltipTaskNumberColor
paintNumber(firstActiveMessage, color)
}
}
g.font = oldFont
}
private fun getNumbersFont(textFont: Font, g: Graphics): FontSearchResult {
val style = Font.PLAIN
val monoFontName = FontPreferences.DEFAULT_FONT_NAME
if (g is Graphics2D) {
val textHeight = letterHeight(textFont, g, "A")
var size = textFont.size
var numberHeight = 0
lateinit var numberFont: Font
fun calculateHeight(): Int {
numberFont = Font(monoFontName, style, size)
numberHeight = letterHeight(numberFont, g, "0")
return numberHeight
}
calculateHeight()
if (numberHeight > textHeight) {
size--
while (calculateHeight() >= textHeight) {
size--
}
size++
calculateHeight()
}
else if (numberHeight < textHeight) {
size++
while (calculateHeight() < textHeight) {
size++
}
}
return FontSearchResult(numberFont, numberHeight, textHeight)
}
return FontSearchResult(Font(monoFontName, style, textFont.size), 0, 0)
}
private fun letterHeight(font: Font, g: Graphics2D, str: String): Int {
val gv: GlyphVector = font.createGlyphVector(g.fontRenderContext, str)
return gv.getGlyphMetrics(0).bounds2D.height.roundToInt()
}
@Throws(BadLocationException::class)
private fun paintMessages(g: Graphics) {
val g2d = g as Graphics2D
for (lessonMessage in allLessonMessages()) {
val myMessages = lessonMessage.messageParts
for (myMessage in myMessages) {
when (myMessage.type) {
MessagePart.MessageType.SHORTCUT -> {
val bg = UISettings.getInstance().shortcutBackgroundColor
val needColor = if (lessonMessage.state == MessageState.INACTIVE) Color(bg.red, bg.green, bg.blue, 255 * 3 / 10) else bg
for (part in myMessage.splitMe()) {
drawRectangleAroundText(part, g2d, needColor) { r2d ->
g2d.fill(r2d)
}
}
}
MessagePart.MessageType.CODE -> {
val needColor = UISettings.getInstance().codeBorderColor
drawRectangleAroundText(myMessage, g2d, needColor) { r2d ->
if (panelMode) {
g2d.draw(r2d)
}
else {
g2d.fill(r2d)
}
}
}
MessagePart.MessageType.ICON_IDX -> {
val rect = modelToView2D(myMessage.startOffset)
var icon = LearningUiManager.iconMap[myMessage.text] ?: continue
if (inactiveMessages.contains(lessonMessage)) {
icon = getInactiveIcon(icon)
}
icon.paintIcon(this, g2d, (rect.x + JBUIScale.scale(1f)).toInt(), rect.y.toInt())
}
MessagePart.MessageType.ILLUSTRATION -> {
val x = modelToView2D(myMessage.startOffset).x.toInt()
val y = modelToView2D(myMessage.endOffset - 1).y.toInt()
var icon = LearningUiManager.iconMap[myMessage.text] ?: continue
if (inactiveMessages.contains(lessonMessage)) {
icon = getInactiveIcon(icon)
}
icon.paintIcon(this, g2d, x, y - spaceAboveIllustrationParagraph(icon))
}
else -> {}
}
}
}
val lastActiveMessage = activeMessages.lastOrNull()
val firstActiveMessage = firstActiveMessage()
if (panelMode && lastActiveMessage != null && lastActiveMessage.state == MessageState.NORMAL) {
val c = UISettings.getInstance().activeTaskBorder
val a = if (totalAnimation == 0) 255 else 255 * currentAnimation / totalAnimation
val needColor = Color(c.red, c.green, c.blue, a)
drawRectangleAroundMessage(firstActiveMessage, lastActiveMessage, g2d, needColor)
}
}
private fun getInactiveIcon(icon: Icon) = WatermarkIcon(icon, UISettings.getInstance().transparencyInactiveFactor.toFloat())
private fun firstActiveMessage(): LessonMessage? = activeMessages.indexOfLast { it.state == MessageState.PASSED }
.takeIf { it != -1 && it < activeMessages.size - 1 }
?.let { activeMessages[it + 1] } ?: activeMessages.firstOrNull()
private fun drawRectangleAroundText(myMessage: MessagePart,
g2d: Graphics2D,
needColor: Color,
draw: (r2d: RoundRectangle2D) -> Unit) {
val startOffset = myMessage.startOffset
val endOffset = myMessage.endOffset
val rectangleStart = modelToView2D(startOffset)
val rectangleEnd = modelToView2D(endOffset)
val color = g2d.color
val fontSize = UISettings.getInstance().fontSize
g2d.color = needColor
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val shift = if (SystemInfo.isMac) 1f else 2f
val r2d = RoundRectangle2D.Double(rectangleStart.x - 2 * indent, rectangleStart.y - indent + JBUIScale.scale(shift),
rectangleEnd.x - rectangleStart.x + 4 * indent, (fontSize + 2 * indent).toDouble(),
arc.toDouble(), arc.toDouble())
draw(r2d)
g2d.color = color
}
private fun drawRectangleAroundMessage(lastPassedMessage: LessonMessage? = null,
lastActiveMessage: LessonMessage,
g2d: Graphics2D,
needColor: Color) {
val startOffset = lastPassedMessage?.let { if (it.start == 0) 0 else it.start + 1 } ?: 0
val endOffset = lastActiveMessage.end
val topLineY = modelToView2D(startOffset).y
val bottomLineY = modelToView2D(endOffset - 1).let { it.y + it.height }
val textHeight = bottomLineY - topLineY
val color = g2d.color
g2d.color = needColor
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val xOffset = JBUI.scale(2).toDouble()
val yOffset = topLineY - activeTaskInset
val width = this.bounds.width - 2*xOffset - JBUIScale.scale(2) // 1 + 1 line width
val height = textHeight + 2 * activeTaskInset - JBUIScale.scale(2) + (lastActiveMessage.textProperties?.spaceBelow ?: 0)
g2d.draw(RoundRectangle2D.Double(xOffset, yOffset, width, height, arc.toDouble(), arc.toDouble()))
g2d.color = color
}
override fun getMaximumSize(): Dimension {
return preferredSize
}
companion object {
private val LOG = Logger.getInstance(LessonMessagePane::class.java)
//arc & indent for shortcut back plate
private val arc by lazy { JBUI.scale(4) }
private val indent by lazy { JBUI.scale(2) }
private val activeTaskInset by lazy { JBUI.scale(12) }
private fun Point2D.toPoint(): Point {
return Point(x.roundToInt(), y.roundToInt())
}
private fun Rectangle2D.toRectangle(): Rectangle {
return Rectangle(x.roundToInt(), y.roundToInt(), width.roundToInt(), height.roundToInt())
}
}
}
| apache-2.0 | 3a5b749c5bc8a7b2a9d1d132262f5b34 | 38.193114 | 171 | 0.689011 | 4.511632 | false | false | false | false |
kpob/KotlinLearning | app/src/main/java/pl/kpob/kotlinlearning/ForecastListAdapter.kt | 1 | 2010 | package pl.kpob.kotlinlearning
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.squareup.picasso.Picasso
import org.jetbrains.anko.find
import org.jetbrains.anko.layoutInflater
import org.jetbrains.anko.onClick
import pl.kpob.kotlinlearning.domain.model.Forecast
import pl.kpob.kotlinlearning.domain.model.ForecastList
/**
* Created by kpob on 20.01.2016.
*/
class ForecastListAdapter(val weekForecast: ForecastList, val itemClick: (Forecast) -> Unit) : RecyclerView.Adapter<ForecastListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = parent.context.layoutInflater.inflate(R.layout.item_forecast, parent, false)
return ViewHolder(view, itemClick)
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
holder?.bindForecast(weekForecast[position])
}
override fun getItemCount(): Int = weekForecast.size()
class ViewHolder(val view: View, val itemClick: (Forecast) -> Unit) : RecyclerView.ViewHolder(view) {
private val iconView by lazy { view.find<ImageView>(R.id.icon) }
private val dateView by lazy { view.find<TextView>(R.id.date) }
private val descriptionView by lazy { view.find<TextView>(R.id.description) }
private val maxTempView by lazy { view.find<TextView>(R.id.maxTemperature) }
private val minTempView by lazy { view.find<TextView>(R.id.minTemperature) }
fun bindForecast(forecast: Forecast) {
with(forecast) {
Picasso.with(itemView.context).load(iconUrl).into(iconView)
dateView.text = date
descriptionView.text = description
maxTempView.text = "${high.toString()}"
minTempView.text = "${low.toString()}"
itemView.onClick { itemClick(this) }
}
}
}
} | mit | 8f40bd50263a845f6b7fb758892b1d62 | 37.673077 | 151 | 0.697015 | 4.285714 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/notification/PollingChecker.kt | 1 | 23642 | package jp.juggler.subwaytooter.notification
import android.content.Context
import androidx.core.app.NotificationCompat
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.api.TootApiCallback
import jp.juggler.subwaytooter.api.TootApiClient
import jp.juggler.subwaytooter.api.TootParser
import jp.juggler.subwaytooter.api.entity.*
import jp.juggler.subwaytooter.global.appDispatchers
import jp.juggler.subwaytooter.notification.CheckerWakeLocks.Companion.checkerWakeLocks
import jp.juggler.subwaytooter.notification.MessageNotification.getMessageNotifications
import jp.juggler.subwaytooter.notification.MessageNotification.removeMessageNotification
import jp.juggler.subwaytooter.notification.MessageNotification.showMessageNotification
import jp.juggler.subwaytooter.pref.PrefB
import jp.juggler.subwaytooter.table.*
import jp.juggler.util.JsonObject
import jp.juggler.util.LogCategory
import jp.juggler.util.notEmpty
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import kotlin.coroutines.coroutineContext
import kotlin.math.min
/**
* 1アカウント,1回ごとの通知チェック処理
*/
class PollingChecker(
val context: Context,
private val accountDbId: Long,
private var injectData: List<TootNotification> = emptyList(),
) {
companion object {
val log = LogCategory("PollingChecker")
val commonMutex = Mutex()
private val mutexMap = ConcurrentHashMap<Long, Mutex>()
fun accountMutex(accountDbId: Long): Mutex = mutexMap.getOrPut(accountDbId) { Mutex() }
private val activeCheckers = LinkedList<PollingChecker>()
private fun addActiveChecker(c: PollingChecker) {
synchronized(activeCheckers) {
activeCheckers.add(c)
}
}
private fun removeActiveChecker(c: PollingChecker) {
synchronized(activeCheckers) {
activeCheckers.remove(c)
}
}
suspend fun cancelAllChecker() {
synchronized(activeCheckers) {
for (c in activeCheckers) {
try {
c.checkJob.cancel()
} catch (ex: Throwable) {
log.trace(ex)
}
}
}
while (true) {
val activeCount = synchronized(activeCheckers) {
activeCheckers.size
}
if (activeCount == 0) break
log.w("cancelAllChecker: waiting activeCheckers. $activeCount")
delay(333L)
}
}
}
private val wakelocks = checkerWakeLocks(context)
private lateinit var cache: NotificationCache
private val client = TootApiClient(
context,
callback = object : TootApiCallback {
override suspend fun isApiCancelled(): Boolean {
if (!coroutineContext.isActive) {
log.w("coroutineContext is not active!")
}
return !coroutineContext.isActive
}
}
)
private val checkJob = Job()
private fun NotificationData.getNotificationLine(): String {
val name = when (PrefB.bpShowAcctInSystemNotification()) {
false -> notification.accountRef?.decoded_display_name
true -> {
val acctPretty = notification.accountRef?.get()?.acct?.pretty
if (acctPretty?.isNotEmpty() == true) {
"@$acctPretty"
} else {
null
}
}
} ?: "?"
return "- " + when (notification.type) {
TootNotification.TYPE_MENTION,
TootNotification.TYPE_REPLY,
-> context.getString(R.string.display_name_replied_by, name)
TootNotification.TYPE_RENOTE,
TootNotification.TYPE_REBLOG,
-> context.getString(R.string.display_name_boosted_by, name)
TootNotification.TYPE_QUOTE,
-> context.getString(R.string.display_name_quoted_by, name)
TootNotification.TYPE_STATUS,
-> context.getString(R.string.display_name_posted_by, name)
TootNotification.TYPE_UPDATE,
-> context.getString(R.string.display_name_updates_post, name)
TootNotification.TYPE_STATUS_REFERENCE,
-> context.getString(R.string.display_name_references_post, name)
TootNotification.TYPE_FOLLOW,
-> context.getString(R.string.display_name_followed_by, name)
TootNotification.TYPE_UNFOLLOW,
-> context.getString(R.string.display_name_unfollowed_by, name)
TootNotification.TYPE_ADMIN_SIGNUP,
-> context.getString(R.string.display_name_signed_up, name)
TootNotification.TYPE_FAVOURITE,
-> context.getString(R.string.display_name_favourited_by, name)
TootNotification.TYPE_EMOJI_REACTION_PLEROMA,
TootNotification.TYPE_EMOJI_REACTION,
TootNotification.TYPE_REACTION,
-> context.getString(R.string.display_name_reaction_by, name)
TootNotification.TYPE_VOTE,
TootNotification.TYPE_POLL_VOTE_MISSKEY,
-> context.getString(R.string.display_name_voted_by, name)
TootNotification.TYPE_FOLLOW_REQUEST,
TootNotification.TYPE_FOLLOW_REQUEST_MISSKEY,
-> context.getString(R.string.display_name_follow_request_by, name)
TootNotification.TYPE_FOLLOW_REQUEST_ACCEPTED_MISSKEY,
-> context.getString(R.string.display_name_follow_request_accepted_by, name)
TootNotification.TYPE_POLL,
-> context.getString(R.string.end_of_polling_from, name)
else -> "?"
}
}
private fun createPolicyFilter(
account: SavedAccount,
): (TootNotification) -> Boolean = when (account.push_policy) {
"followed" -> { it ->
val who = it.account
when {
who == null -> true
account.isMe(who) -> true
else -> UserRelation.load(account.db_id, who.id).following
}
}
"follower" -> { it ->
val who = it.account
when {
it.type == TootNotification.TYPE_FOLLOW ||
it.type == TootNotification.TYPE_FOLLOW_REQUEST -> true
who == null -> true
account.isMe(who) -> true
else -> UserRelation.load(account.db_id, who.id).followed_by
}
}
"none" -> { _ -> false }
else -> { _ -> true }
}
suspend fun check(
checkNetwork: Boolean = true,
onlySubscription: Boolean = false,
progress: suspend (SavedAccount, PollingState) -> Unit,
) {
try {
addActiveChecker(this@PollingChecker)
// double check
if (importProtector.get()) {
log.w("aborted by importProtector.")
return
}
withContext(appDispatchers.default + checkJob) {
if (importProtector.get()) {
log.w("aborted by importProtector.")
return@withContext
}
val account = SavedAccount.loadAccount(context, accountDbId)
if (account == null || account.isPseudo || !account.isConfirmed) {
// 疑似アカウントはチェック対象外
// 未確認アカウントはチェック対象外
return@withContext
}
client.account = account
if (checkNetwork) {
progress(account, PollingState.CheckNetworkConnection)
wakelocks.checkConnection()
}
commonMutex.withLock {
// グローバル変数の暖気
if (TootStatus.muted_app == null) {
TootStatus.muted_app = MutedApp.nameSet
}
if (TootStatus.muted_word == null) {
TootStatus.muted_word = MutedWord.nameSet
}
}
// installIdとデバイストークンの取得
val deviceToken = loadFirebaseMessagingToken(context)
loadInstallId(context, account, deviceToken, progress)
val favMuteSet = commonMutex.withLock {
FavMute.acctSet
}
accountMutex(accountDbId).withLock {
val wps = PushSubscriptionHelper(context, account)
if (wps.flags != 0) {
progress(account, PollingState.CheckServerInformation)
val (instance, instanceResult) = TootInstance.get(client)
if (instance == null) {
account.updateNotificationError("${instanceResult?.error} ${instanceResult?.requestInfo}".trim())
error("can't get server information. ${instanceResult?.error} ${instanceResult?.requestInfo}".trim())
}
}
wps.updateSubscription(client, progress = progress)
?: throw CancellationException()
val wpsLog = wps.logString
if (wpsLog.isNotEmpty()) {
log.w("subsctiption warning: ${account.acct.pretty} $wpsLog")
}
if (wps.flags == 0) {
if (account.lastNotificationError != null) {
account.updateNotificationError(null)
}
log.i("notification check not required.")
return@withLock
}
progress(account, PollingState.CheckNotifications)
PollingWorker2.enqueuePolling(context)
if (onlySubscription) {
log.i("exit due to onlySubscription")
return@withLock
}
injectData.notEmpty()?.let { list ->
log.d("processInjectedData ${account.acct} size=${list.size}")
NotificationCache(accountDbId).apply {
load()
inject(account, list)
}
}
cache = NotificationCache(account.db_id).apply {
load()
if (account.isMisskey && !PrefB.bpMisskeyNotificationCheck()) {
log.d("skip misskey server. ${account.acct}")
} else {
requestAsync(
client,
account,
wps.flags,
) { result ->
account.updateNotificationError("${result.error} ${result.requestInfo}".trim())
if (result.error?.contains("Timeout") == true &&
!account.dont_show_timeout
) {
progress(account, PollingState.Timeout)
}
}
}
}
if (PrefB.bpSeparateReplyNotificationGroup()) {
var tr = TrackingRunner(
account = account,
favMuteSet = favMuteSet,
trackingType = TrackingType.NotReply,
trackingName = MessageNotification.TRACKING_NAME_DEFAULT
)
tr.checkAccount()
yield()
tr.updateNotification()
//
tr = TrackingRunner(
account = account,
favMuteSet = favMuteSet,
trackingType = TrackingType.Reply,
trackingName = MessageNotification.TRACKING_NAME_REPLY
)
tr.checkAccount()
yield()
tr.updateNotification()
} else {
val tr = TrackingRunner(
account = account,
favMuteSet = favMuteSet,
trackingType = TrackingType.All,
trackingName = MessageNotification.TRACKING_NAME_DEFAULT
)
tr.checkAccount()
yield()
tr.updateNotification()
}
}
}
} finally {
removeActiveChecker(this)
}
}
inner class TrackingRunner(
val account: SavedAccount,
val favMuteSet: HashSet<Acct>,
var trackingType: TrackingType = TrackingType.All,
var trackingName: String = "",
) {
private val notificationManager = wakelocks.notificationManager
private lateinit var nr: NotificationTracking
private val duplicateCheck = HashSet<EntityId>()
private val dstListData = LinkedList<NotificationData>()
val policyFilter = createPolicyFilter(account)
private val parser = TootParser(context, account)
suspend fun checkAccount() {
this.nr =
NotificationTracking.load(account.acct.pretty, account.db_id, trackingName)
fun JsonObject.isMention() =
when (NotificationCache.parseNotificationType(account, this)) {
TootNotification.TYPE_REPLY, TootNotification.TYPE_MENTION -> true
else -> false
}
val jsonList = when (trackingType) {
TrackingType.All -> cache.data
TrackingType.Reply -> cache.data.filter { it.isMention() }
TrackingType.NotReply -> cache.data.filter { !it.isMention() }
}
// 新しい順に並んでいる。先頭から10件までを処理する。ただし処理順序は古い方から
val size = min(10, jsonList.size)
for (i in (0 until size).reversed()) {
yield()
updateSub(jsonList[i])
}
yield()
// 種別チェックより先に、cache中の最新のIDを「最後に表示した通知」に指定する
// nid_show は通知タップ時に参照されるので、通知を表示する際は必ず更新・保存する必要がある
// 種別チェックより優先する
val latestId = cache.filterLatestId(account) {
when (trackingType) {
TrackingType.Reply -> it.isMention()
TrackingType.NotReply -> !it.isMention()
else -> true
}
}
if (latestId != null) nr.nid_show = latestId
nr.save(account.acct.pretty)
}
private fun updateSub(src: JsonObject) {
val id = NotificationCache.getEntityOrderId(account, src)
if (id.isDefault || duplicateCheck.contains(id)) return
duplicateCheck.add(id)
// タップ・削除した通知のIDと同じか古いなら対象外
if (!id.isNewerThan(nr.nid_read)) {
log.d("update_sub: ${account.acct} skip old notification $id")
return
}
log.d("update_sub: found data that id=$id, > read id ${nr.nid_read}")
val notification = parser.notification(src) ?: return
// アプリミュートと単語ミュート
if (notification.status?.checkMuted() == true) return
// ふぁぼ魔ミュート
when (notification.type) {
TootNotification.TYPE_REBLOG,
TootNotification.TYPE_FAVOURITE,
TootNotification.TYPE_FOLLOW,
TootNotification.TYPE_FOLLOW_REQUEST,
TootNotification.TYPE_FOLLOW_REQUEST_MISSKEY,
TootNotification.TYPE_ADMIN_SIGNUP,
-> {
val who = notification.account
if (who != null && favMuteSet.contains(account.getFullAcct(who))) {
log.d("${account.getFullAcct(who)} is in favMuteSet.")
return
}
}
}
// Mastodon 3.4.0rc1 push policy
if (!policyFilter(notification)) return
// 後から処理したものが先頭に来る
dstListData.add(0, NotificationData(account, notification))
}
fun updateNotification() {
val notificationTag = when (trackingName) {
"" -> "${account.db_id}/_"
else -> "${account.db_id}/$trackingName"
}
val nt = NotificationTracking.load(account.acct.pretty, account.db_id, trackingName)
when (val first = dstListData.firstOrNull()) {
null -> {
log.d("showNotification[${account.acct.pretty}/$notificationTag] cancel notification.")
notificationManager.removeMessageNotification(account, notificationTag)
}
else -> {
when {
// 先頭にあるデータが同じなら、通知を更新しない
// このマーカーは端末再起動時にリセットされるので、再起動後は通知が出るはず
first.notification.time_created_at == nt.post_time && first.notification.id == nt.post_id ->
log.d("showNotification[${account.acct.pretty}] id=${first.notification.id} is already shown.")
PrefB.bpDivideNotification() -> {
updateNotificationDivided(notificationTag, nt)
nt.updatePost(
first.notification.id,
first.notification.time_created_at
)
}
else -> {
updateNotificationMerged(notificationTag, first)
nt.updatePost(
first.notification.id,
first.notification.time_created_at
)
}
}
}
}
}
private fun updateNotificationDivided(
notificationTag: String,
nt: NotificationTracking,
) {
log.d("updateNotificationDivided[${account.acct.pretty}] creating notification(1)")
val activeNotificationMap = notificationManager.getMessageNotifications(notificationTag)
val lastPostTime = nt.post_time
val lastPostId = nt.post_id
for (item in dstListData.reversed()) {
val itemTag = "$notificationTag/${item.notification.id}"
if (lastPostId != null &&
item.notification.time_created_at <= lastPostTime &&
item.notification.id <= lastPostId
) {
// 掲載済みデータより古い通知は再表示しない
log.d("ignore $itemTag ${item.notification.time_created_at} <= $lastPostTime && ${item.notification.id} <= $lastPostId")
continue
}
// ignore if already showing
if (activeNotificationMap.remove(itemTag) != null) {
log.d("ignore $itemTag is in activeNotificationMap")
continue
}
notificationManager.showMessageNotification(
context,
account,
trackingName,
trackingType,
itemTag,
notificationId = item.notification.id.toString()
) { builder ->
builder.setWhen(item.notification.time_created_at)
val summary = item.getNotificationLine()
builder.setContentTitle(summary)
when (val content = item.notification.status?.decoded_content?.notEmpty()) {
null -> builder.setContentText(item.accessInfo.acct.pretty)
else -> {
val style = NotificationCompat.BigTextStyle()
.setBigContentTitle(summary)
.setSummaryText(item.accessInfo.acct.pretty)
.bigText(content)
builder.setStyle(style)
}
}
}
}
// リストにない通知は消さない。ある通知をユーザが指で削除した際に他の通知が残ってほしい場合がある
}
private fun updateNotificationMerged(
notificationTag: String,
first: NotificationData,
) {
log.d("updateNotificationMerged[${account.acct.pretty}] creating notification(1)")
notificationManager.showMessageNotification(
context,
account,
trackingName,
trackingType,
notificationTag
) { builder ->
builder.setWhen(first.notification.time_created_at)
val a = first.getNotificationLine()
val dataList = dstListData
if (dataList.size == 1) {
builder.setContentTitle(a)
builder.setContentText(account.acct.pretty)
} else {
val header = context.getString(R.string.notification_count, dataList.size)
builder.setContentTitle(header).setContentText(a)
val style = NotificationCompat.InboxStyle()
.setBigContentTitle(header)
.setSummaryText(account.acct.pretty)
for (i in 0 until min(4, dataList.size)) {
style.addLine(dataList[i].getNotificationLine())
}
builder.setStyle(style)
}
}
}
}
}
| apache-2.0 | 8b63c1e7f3f74f24d002b8c536f6be25 | 37.674177 | 140 | 0.499913 | 5.239643 | false | false | false | false |
JuliaSoboleva/SmartReceiptsLibrary | app/src/main/java/co/smartreceipts/android/apis/moshi/adapters/CategoryJsonAdapter.kt | 2 | 945 | package co.smartreceipts.android.apis.moshi.adapters
import co.smartreceipts.android.model.Category
import co.smartreceipts.android.model.factory.CategoryBuilderFactory
import com.squareup.moshi.FromJson
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.squareup.moshi.ToJson
import java.util.*
class CategoryJsonAdapter {
@FromJson
fun categoryFromJson(categoryJson: CategoryJson) =
CategoryBuilderFactory().setUuid(UUID.fromString(categoryJson.uuid))
.setName(categoryJson.name)
.setCode(categoryJson.code)
.build()
@ToJson
fun categoryToJson(category: Category) = CategoryJson(category.uuid.toString(), category.name, category.code)
@JsonClass(generateAdapter = true)
data class CategoryJson(
@Json(name = "uuid") val uuid: String,
@Json(name = "Name") val name: String,
@Json(name = "Code") val code: String
)
} | agpl-3.0 | d36fa2261bc9bedb4000c03b419c51fa | 30.533333 | 113 | 0.721693 | 4.162996 | false | false | false | false |
LookitheFirst/redditlive | src/main/java/io/looki/redditlive/LiveMessage.kt | 1 | 5686 | package io.looki.redditlive
import com.google.gson.JsonElement
import com.google.gson.annotations.SerializedName
import java.util.*
data class LiveMessage<out T>(
val type: PayloadType,
val payload: T
) {
enum class PayloadType(val payload: Class<out LiveMessage.GenericPayload>) {
@SerializedName("update") Update(LiveMessage.Update::class.java),
@SerializedName("activity") Activity(LiveMessage.Activity::class.java),
@SerializedName("settings") Settings(LiveMessage.Settings::class.java),
@SerializedName("delete") Delete(LiveMessage.Delete::class.java),
@SerializedName("strike") Strike(LiveMessage.Strike::class.java),
@SerializedName("embeds_ready") EmbedsReady(LiveMessage.EmbedsReady::class.java),
@SerializedName("complete") Complete(LiveMessage.Complete::class.java)
}
abstract class GenericPayload
data class Update(
val kind: BodyKind,
val data: Data
) : GenericPayload() {
enum class BodyKind {
LiveUpdateEvent, LiveUpdate
}
data class Data(
val name: String,
val id: String,
val body: String,
val body_html: String,
val created: Int,
val created_utc: Int,
val author: String,
val embeds: Array<JsonElement>,
val mobile_embeds: Array<JsonElement>,
val stricken: Boolean
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Data
if (name != other.name) return false
if (id != other.id) return false
if (body != other.body) return false
if (body_html != other.body_html) return false
if (created != other.created) return false
if (created_utc != other.created_utc) return false
if (author != other.author) return false
if (!Arrays.equals(embeds, other.embeds)) return false
if (!Arrays.equals(mobile_embeds, other.mobile_embeds)) return false
if (stricken != other.stricken) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + id.hashCode()
result = 31 * result + body.hashCode()
result = 31 * result + body_html.hashCode()
result = 31 * result + created
result = 31 * result + created_utc
result = 31 * result + author.hashCode()
result = 31 * result + Arrays.hashCode(embeds)
result = 31 * result + Arrays.hashCode(mobile_embeds)
result = 31 * result + stricken.hashCode()
return result
}
}
}
data class Activity(
val count: Int,
val fuzzed: Boolean
) : GenericPayload()
data class Settings(
val title: String?,
val name: String?,
val id: String?,
val state: ThreadState?,
val websocket_url: String?,
val description: String?,
val description_html: String?,
val created: Int?,
val created_utc: Int?,
val nsfw: Boolean?,
val viewer_count: Int?,
val viewer_count_fuzzed: Boolean?,
val resources_html: String?,
val resources: String?
) : GenericPayload() {
enum class ThreadState {
@SerializedName("complete") Complete,
@SerializedName("live") Live
}
}
data class Delete(val liveupdate_id: String) : GenericPayload()
data class Strike(val liveupdate_id: String) : GenericPayload()
data class EmbedsReady(
val mobile_embeds: Array<JsonElement>,
val media_embeds: Array<JsonElement>, //TODO
val liveupdate_id: String
) : GenericPayload() {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as EmbedsReady
if (!Arrays.equals(mobile_embeds, other.mobile_embeds)) return false
if (!Arrays.equals(media_embeds, other.media_embeds)) return false
if (liveupdate_id != other.liveupdate_id) return false
return true
}
override fun hashCode(): Int {
var result = Arrays.hashCode(mobile_embeds)
result = 31 * result + Arrays.hashCode(media_embeds)
result = 31 * result + liveupdate_id.hashCode()
return result
}
}
class Complete : GenericPayload() {
override fun toString() = "Complete()"
}
}
/*data class About(
val title: String,
val name: String,
val id: String,
val state: ThreadState,
val websocket_url: String?,
val description: String,
val description_html: String,
val created: Int,
val created_utc: Int,
val nsfw: Boolean,
val viewer_count: Int?,
val viewer_count_fuzzed: Boolean?,
val resources_html: String,
val resources: String
) : GenericPayload() {
enum class ThreadState {
@SerializedName("complete") Complete,
@SerializedName("live") Live
}
}*/ | gpl-3.0 | 8be273a748158cb602c8ab76988110e3 | 34.322981 | 89 | 0.551178 | 4.770134 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/mixin/util/MixinConstants.kt | 1 | 3764 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.util
@Suppress("MemberVisibilityCanBePrivate")
object MixinConstants {
const val PACKAGE = "org.spongepowered.asm.mixin."
const val SMAP_STRATUM = "Mixin"
const val DEFAULT_SHADOW_PREFIX = "shadow$"
object Classes {
const val CALLBACK_INFO = "org.spongepowered.asm.mixin.injection.callback.CallbackInfo"
const val CALLBACK_INFO_RETURNABLE = "org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable"
const val COMPATIBILITY_LEVEL = "org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel"
const val INJECTION_POINT = "org.spongepowered.asm.mixin.injection.InjectionPoint"
const val MIXIN_AGENT = "org.spongepowered.tools.agent.MixinAgent"
const val MIXIN_CONFIG = "org.spongepowered.asm.mixin.transformer.MixinConfig"
const val MIXIN_PLUGIN = "org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin"
const val SERIALIZED_NAME = "com.google.gson.annotations.SerializedName"
}
object Annotations {
const val ACCESSOR = "org.spongepowered.asm.mixin.gen.Accessor"
const val AT = "org.spongepowered.asm.mixin.injection.At"
const val AT_CODE = "org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode"
const val DEBUG = "org.spongepowered.asm.mixin.Debug"
const val DYNAMIC = "org.spongepowered.asm.mixin.Dynamic"
const val FINAL = "org.spongepowered.asm.mixin.Final"
const val IMPLEMENTS = "org.spongepowered.asm.mixin.Implements"
const val INTERFACE = "org.spongepowered.asm.mixin.Interface"
const val INTRINSIC = "org.spongepowered.asm.mixin.Intrinsic"
const val MIXIN = "org.spongepowered.asm.mixin.Mixin"
const val MUTABLE = "org.spongepowered.asm.mixin.Mutable"
const val OVERWRITE = "org.spongepowered.asm.mixin.Overwrite"
const val SHADOW = "org.spongepowered.asm.mixin.Shadow"
const val SLICE = "org.spongepowered.asm.mixin.injection.Slice"
const val SOFT_OVERRIDE = "org.spongepowered.asm.mixin.SoftOverride"
const val UNIQUE = "org.spongepowered.asm.mixin.Unique"
const val INJECT = "org.spongepowered.asm.mixin.injection.Inject"
const val INVOKER = "org.spongepowered.asm.mixin.gen.Invoker"
const val MODIFY_ARG = "org.spongepowered.asm.mixin.injection.ModifyArg"
const val MODIFY_ARGS = "org.spongepowered.asm.mixin.injection.ModifyArgs"
const val MODIFY_CONSTANT = "org.spongepowered.asm.mixin.injection.ModifyConstant"
const val MODIFY_VARIABLE = "org.spongepowered.asm.mixin.injection.ModifyVariable"
const val REDIRECT = "org.spongepowered.asm.mixin.injection.Redirect"
const val SURROGATE = "org.spongepowered.asm.mixin.injection.Surrogate"
val METHOD_INJECTORS = listOf(INJECT, MODIFY_ARG, MODIFY_ARGS, MODIFY_CONSTANT, MODIFY_VARIABLE, REDIRECT)
val ENTRY_POINTS =
arrayOf(INJECT, MODIFY_ARG, MODIFY_ARGS, MODIFY_CONSTANT, MODIFY_VARIABLE, REDIRECT, SURROGATE, OVERWRITE)
val MIXIN_ANNOTATIONS = setOf(
ACCESSOR,
AT,
DEBUG,
DYNAMIC,
FINAL,
IMPLEMENTS,
INTERFACE,
INTRINSIC,
MIXIN,
MUTABLE,
OVERWRITE,
SHADOW,
SLICE,
SOFT_OVERRIDE,
UNIQUE,
INJECT,
INVOKER,
MODIFY_ARG,
MODIFY_ARGS,
MODIFY_CONSTANT,
MODIFY_VARIABLE,
REDIRECT,
SURROGATE
)
}
}
| mit | 38e57a265e34f9a3a2f0c4a24e124f06 | 42.767442 | 118 | 0.668969 | 4.205587 | false | false | false | false |
RuneSuite/client | api/src/main/java/org/runestar/client/api/util/AwtSystem.kt | 1 | 1728 | @file:JvmName("AwtSystem")
package org.runestar.client.api.util
import org.kxtra.slf4j.debug
import org.kxtra.slf4j.getLogger
import java.awt.*
import java.nio.file.Files
import java.nio.file.Path
private val logger = getLogger()
private inline fun <T> safe(f: () -> T): T? {
return try {
f()
} catch (e: Exception) {
logger.debug(e.message)
null
}
}
fun safeTrayIcon(image: Image, tooltip: String) = safe { TrayIcon(image, tooltip) }
val taskbar: Taskbar? get() = safe { Taskbar.getTaskbar() }
fun Taskbar.safeSetWindowProgressValue(w: Window, value: Int) {
safe { setWindowProgressValue(w, value) }
}
fun Taskbar.safeSetWindowProgressState(w: Window, state: Taskbar.State) {
safe { setWindowProgressState(w, state) }
}
fun Taskbar.safeRequestWindowUserAttention(w: Window) {
safe { requestWindowUserAttention(w) }
}
var Taskbar.safeMenu: PopupMenu?
get() = safe { menu }
set(value) { safe { menu = value } }
var Taskbar.safeIconImage: Image?
get() = safe { iconImage }
set(value) { safe { iconImage = value } }
val desktop: Desktop? get() = safe { Desktop.getDesktop() }
fun Desktop.safeOpen(path: Path) {
if (isSupported(Desktop.Action.OPEN)) {
try {
open(path.toFile())
} catch (e: Exception) {
logger.debug { "Desktop failed to open $path" }
if (Files.isRegularFile(path)) {
val dir = path.parent
logger.debug { "Desktop opening parent directory $dir" }
safeOpen(dir)
}
}
} else {
logger.debug { "Desktop open is not supported" }
}
}
val systemTray: SystemTray? get() = safe { SystemTray.getSystemTray() } | mit | 4cf42b4f404452dd914255f21cc99da8 | 25.6 | 83 | 0.631366 | 3.476861 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/quickfixUtil.kt | 1 | 2799 | // 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.util
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoAfter
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.ifEmpty
inline fun <reified T : PsiElement> Diagnostic.createIntentionForFirstParentOfType(
factory: (T) -> KotlinQuickFixAction<T>?
) = psiElement.getNonStrictParentOfType<T>()?.let(factory)
fun createIntentionFactory(
factory: (Diagnostic) -> IntentionAction?
) = object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic) = factory(diagnostic)
}
fun KtPrimaryConstructor.addConstructorKeyword(): PsiElement? {
val modifierList = this.modifierList ?: return null
val psiFactory = KtPsiFactory(project)
val constructor = if (valueParameterList == null) {
psiFactory.createPrimaryConstructor("constructor()")
} else {
psiFactory.createConstructorKeyword()
}
return addAfter(constructor, modifierList)
}
fun getDataFlowAwareTypes(
expression: KtExpression,
bindingContext: BindingContext = expression.analyze(),
originalType: KotlinType? = bindingContext.getType(expression)
): Collection<KotlinType> {
if (originalType == null) return emptyList()
val dataFlowInfo = bindingContext.getDataFlowInfoAfter(expression)
val dataFlowValueFactory = expression.getResolutionFacade().dataFlowValueFactory
val expressionType = bindingContext.getType(expression) ?: return listOf(originalType)
val dataFlowValue = dataFlowValueFactory.createDataFlowValue(
expression, expressionType, bindingContext, expression.getResolutionFacade().moduleDescriptor
)
return dataFlowInfo.getCollectedTypes(dataFlowValue, expression.languageVersionSettings).ifEmpty { listOf(originalType) }
}
| apache-2.0 | 5602c30d31a3bc7f841b16dede647aba | 46.440678 | 158 | 0.811004 | 5.089091 | false | false | false | false |
SixRQ/KAXB | src/main/kotlin/com/sixrq/kaxb/main/SchemaGenerator.kt | 1 | 1979 | /*
* Copyright 2017 SixRQ Ltd.
*
* 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.sixrq.kaxb.main
import com.sixrq.kaxb.generators.ClassFileGenerator
import java.lang.System.exit
class SchemaGenerator {
companion object {
@JvmStatic fun main(args: Array<String>) {
val schemaGenerator = SchemaGenerator()
exit(schemaGenerator.generate(args))
}
}
fun generate(args: Array<String>): Int {
val validArgs = listOf("--P", "--S", "--T")
if (args.size != 6 ||
!validArgs.containsAll(args.filter { it.startsWith("--") } ) ||
!args.filter { it.startsWith("--") }.containsAll(validArgs)) {
println("Usage: SchemaGenerator --P <destination package> --S <schema file> --T <target directory>")
return 999
}
var packageName = ""
var schemaLocation = ""
var targetDirectory = ""
args.forEachIndexed { index, value ->
when {
value.toUpperCase() == "--P" -> packageName = args[index + 1]
value.toUpperCase() == "--S" -> schemaLocation = args[index + 1]
value.toUpperCase() == "--T" -> targetDirectory = args[index + 1]
}
}
val classFileGenerator = ClassFileGenerator(schemaLocation, packageName, targetDirectory)
classFileGenerator.generateClasses()
return 0
}
} | apache-2.0 | f278b75c9fd05f95f85306053dcc7342 | 34.357143 | 112 | 0.610409 | 4.397778 | false | false | false | false |
leafclick/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/SourceFolderManagerImpl.kt | 1 | 10516 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project.manage
import com.intellij.ProjectTopics
import com.intellij.ide.projectView.actions.MarkRootActionBase
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.externalSystem.util.PathPrefixTreeMap
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.ModuleListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.roots.SourceFolder
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.containers.MultiMap
import gnu.trove.THashMap
import gnu.trove.THashSet
import org.jetbrains.annotations.TestOnly
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
@State(name = "sourceFolderManager", storages = [Storage(StoragePathMacros.CACHE_FILE)])
class SourceFolderManagerImpl(private val project: Project) : SourceFolderManager, Disposable, PersistentStateComponent<SourceFolderManagerState> {
private val moduleNamesToSourceFolderState: MultiMap<String, SourceFolderModelState> = MultiMap.create()
private var isDisposed = false
private val mutex = Any()
private var sourceFolders = PathPrefixTreeMap<SourceFolderModel>()
private var sourceFoldersByModule = THashMap<String, ModuleModel>()
override fun addSourceFolder(module: Module, url: String, type: JpsModuleSourceRootType<*>) {
synchronized(mutex) {
sourceFolders[url] = SourceFolderModel(module, url, type)
addUrlToModuleModel(module, url)
}
ApplicationManager.getApplication().invokeLater(Runnable {
VirtualFileManager.getInstance().refreshAndFindFileByUrl(url)
}, project.disposed)
}
override fun setSourceFolderPackagePrefix(url: String, packagePrefix: String?) {
synchronized(mutex) {
val sourceFolder = sourceFolders[url] ?: return
sourceFolder.packagePrefix = packagePrefix
}
}
override fun setSourceFolderGenerated(url: String, generated: Boolean) {
synchronized(mutex) {
val sourceFolder = sourceFolders[url] ?: return
sourceFolder.generated = generated
}
}
override fun removeSourceFolders(module: Module) {
synchronized(mutex) {
val moduleModel = sourceFoldersByModule.remove(module.name) ?: return
moduleModel.sourceFolders.forEach { sourceFolders.remove(it) }
}
}
override fun dispose() {
assert(!isDisposed) { "Source folder manager already disposed" }
isDisposed = true
}
@TestOnly
fun isDisposed() = isDisposed
@TestOnly
fun getSourceFolders(moduleName: String) = synchronized(mutex) {
sourceFoldersByModule[moduleName]?.sourceFolders
}
private fun removeSourceFolder(url: String) {
synchronized(mutex) {
val sourceFolder = sourceFolders.remove(url) ?: return
val module = sourceFolder.module
val moduleModel = sourceFoldersByModule[module.name] ?: return
val sourceFolders = moduleModel.sourceFolders
sourceFolders.remove(url)
if (sourceFolders.isEmpty()) {
sourceFoldersByModule.remove(module.name)
}
}
}
private data class SourceFolderModel(
val module: Module,
val url: String,
val type: JpsModuleSourceRootType<*>,
var packagePrefix: String? = null,
var generated: Boolean = false
)
private data class ModuleModel(
val module: Module,
val sourceFolders: MutableSet<String> = THashSet(FileUtil.PATH_HASHING_STRATEGY)
)
init {
project.messageBus.connect().subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
val sourceFoldersToChange = HashMap<Module, ArrayList<Pair<VirtualFile, SourceFolderModel>>>()
val virtualFileManager = VirtualFileManager.getInstance()
for (event in events) {
if (event !is VFileCreateEvent) {
continue
}
val allDescendantValues = synchronized(mutex) { sourceFolders.getAllDescendantValues(VfsUtilCore.pathToUrl(event.path)) }
for (sourceFolder in allDescendantValues) {
val sourceFolderFile = virtualFileManager.refreshAndFindFileByUrl(sourceFolder.url)
if (sourceFolderFile != null && sourceFolderFile.isValid) {
sourceFoldersToChange.computeIfAbsent(sourceFolder.module) { ArrayList() }.add(Pair(event.file!!, sourceFolder))
removeSourceFolder(sourceFolder.url)
}
}
}
updateSourceFolders(sourceFoldersToChange)
}
})
project.messageBus.connect().subscribe(ProjectTopics.MODULES, object : ModuleListener {
override fun moduleAdded(project: Project, module: Module) {
synchronized(mutex) {
moduleNamesToSourceFolderState[module.name].forEach {
loadSourceFolderState(it, module)
}
moduleNamesToSourceFolderState.remove(module.name)
}
}
});
}
fun rescanAndUpdateSourceFolders() {
val sourceFoldersToChange = HashMap<Module, ArrayList<Pair<VirtualFile, SourceFolderModel>>>()
val virtualFileManager = VirtualFileManager.getInstance()
val values = synchronized(mutex) { sourceFolders.values }
for (sourceFolder in values) {
val sourceFolderFile = virtualFileManager.refreshAndFindFileByUrl(sourceFolder.url)
if (sourceFolderFile != null && sourceFolderFile.isValid) {
sourceFoldersToChange.computeIfAbsent(sourceFolder.module) { ArrayList() }.add(Pair(sourceFolderFile, sourceFolder))
removeSourceFolder(sourceFolder.url)
}
updateSourceFolders(sourceFoldersToChange)
}
}
private fun updateSourceFolders(sourceFoldersToChange: Map<Module, List<Pair<VirtualFile, SourceFolderModel>>>) {
for ((module, p) in sourceFoldersToChange) {
ModuleRootModificationUtil.updateModel(module) { model ->
for ((eventFile, sourceFolders) in p) {
val (_, url, type, packagePrefix, generated) = sourceFolders
val contentEntry = MarkRootActionBase.findContentEntry(model, eventFile)
?: model.addContentEntry(url)
val sourceFolder = contentEntry.addSourceFolder(url, type)
if (packagePrefix != null && packagePrefix.isNotEmpty()) {
sourceFolder.packagePrefix = packagePrefix
}
setForGeneratedSources(sourceFolder, generated)
}
}
}
}
private fun setForGeneratedSources(folder: SourceFolder, generated: Boolean) {
val jpsElement = folder.jpsElement
val properties = jpsElement.getProperties(JavaModuleSourceRootTypes.SOURCES)
if (properties != null) properties.isForGeneratedSources = generated
}
override fun getState(): SourceFolderManagerState? {
synchronized(mutex) {
return SourceFolderManagerState(sourceFolders.values.map { model ->
val modelTypeName = dictionary.entries.find { it.value == model.type }?.key ?: return@map null
SourceFolderModelState(model.module.name,
model.url,
modelTypeName,
model.packagePrefix,
model.generated)
}.filterNotNull())
}
}
override fun loadState(state: SourceFolderManagerState) {
synchronized(mutex) {
resetModuleAddedListeners()
if (isDisposed) {
return
}
sourceFolders = PathPrefixTreeMap()
sourceFoldersByModule = THashMap()
val moduleManager = ModuleManager.getInstance(project)
state.sourceFolders.forEach { model ->
val module = moduleManager.findModuleByName(model.moduleName)
if (module == null) {
listenToModuleAdded(model)
return@forEach
}
loadSourceFolderState(model, module)
}
}
}
private fun resetModuleAddedListeners() = moduleNamesToSourceFolderState.clear()
private fun listenToModuleAdded(model: SourceFolderModelState) = moduleNamesToSourceFolderState.putValue(model.moduleName, model)
private fun loadSourceFolderState(model: SourceFolderModelState,
module: Module) {
val rootType: JpsModuleSourceRootType<*> = dictionary[model.type] ?: return
val url = model.url
sourceFolders[url] = SourceFolderModel(module, url, rootType, model.packagePrefix, model.generated)
addUrlToModuleModel(module, url)
}
private fun addUrlToModuleModel(module: Module, url: String) {
val moduleModel = sourceFoldersByModule.getOrPut(module.name) {
ModuleModel(module).also {
Disposer.register(module, Disposable {
removeSourceFolders(module)
})
}
}
moduleModel.sourceFolders.add(url)
}
companion object {
val dictionary = mapOf<String, JpsModuleSourceRootType<*>>(
"SOURCE" to JavaSourceRootType.SOURCE,
"TEST_SOURCE" to JavaSourceRootType.TEST_SOURCE,
"RESOURCE" to JavaResourceRootType.RESOURCE,
"TEST_RESOURCE" to JavaResourceRootType.TEST_RESOURCE
)
}
}
data class SourceFolderManagerState(var sourceFolders: Collection<SourceFolderModelState>) {
constructor() : this(listOf<SourceFolderModelState>())
}
data class SourceFolderModelState(var moduleName: String,
var url: String,
var type: String,
var packagePrefix: String?,
var generated: Boolean) {
constructor(): this("", "", "", null, false)
}
| apache-2.0 | 07d8a26c47294ecbccd1f5e9f78b9e57 | 38.385768 | 147 | 0.71415 | 5.072841 | false | false | false | false |
leafclick/intellij-community | java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaInjectedFileChangesHandler.kt | 1 | 10204 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.source.tree.injected
import com.intellij.codeInsight.editorActions.CopyPastePreProcessor
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.ex.DocumentEx
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.component1
import com.intellij.openapi.util.component2
import com.intellij.psi.*
import com.intellij.psi.PsiLanguageInjectionHost.Shred
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.impl.PsiDocumentManagerBase
import com.intellij.psi.impl.source.resolve.FileContextUtil
import com.intellij.psi.impl.source.tree.injected.changesHandler.*
import com.intellij.psi.util.createSmartPointer
import com.intellij.util.SmartList
import com.intellij.util.containers.ContainerUtil
import kotlin.math.max
internal class JavaInjectedFileChangesHandler(shreds: List<Shred>, editor: Editor, newDocument: Document, injectedFile: PsiFile) :
CommonInjectedFileChangesHandler(shreds, editor, newDocument, injectedFile) {
init {
// Undo breaks fragment markers completely, so rebuilding them in that case
myHostDocument.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
if (UndoManager.getInstance(myProject).isUndoInProgress) {
PsiDocumentManagerBase.addRunOnCommit(myHostDocument) {
rebuildMarkers(markersWholeRange(markers) ?: failAndReport("can't get marker range in undo", event))
}
}
}
}, this)
}
override fun commitToOriginal(e: DocumentEvent) {
val psiDocumentManager = PsiDocumentManager.getInstance(myProject)
val hostPsiFile = psiDocumentManager.getPsiFile(myHostDocument) ?: failAndReport("no psiFile $myHostDocument", e)
val affectedRange = TextRange.from(e.offset, max(e.newLength, e.oldLength))
val affectedMarkers = markers.filter { affectedRange.intersects(it.fragmentMarker) }
val guardedRanges = guardedBlocks.mapTo(HashSet()) { it.range }
if (affectedMarkers.isEmpty() && guardedRanges.any { it.intersects(affectedRange) }) {
// changed guarded blocks are on fragment document editor conscience, we just ignore them silently
return
}
if (!hasInjectionsInOriginFile(affectedMarkers, hostPsiFile)) {
// can't go on if there is already no injection, maybe someone just uninjected them?
myInvalidated = true
return
}
var workingRange: TextRange? = null
val markersToRemove = SmartList<MarkersMapping>()
for ((affectedMarker, markerText) in distributeTextToMarkers(affectedMarkers, affectedRange, e.offset + e.newLength)
.let(this::promoteLinesEnds)) {
val rangeInHost = affectedMarker.hostMarker.range
myHostEditor.caretModel.moveToOffset(rangeInHost.startOffset)
val newText = CopyPastePreProcessor.EP_NAME.extensionList.fold(markerText) { newText, preProcessor ->
preProcessor.preprocessOnPaste(myProject, hostPsiFile, myHostEditor, newText, null)
}
//TODO: cover additional clauses with tests (multiple languages injected into one host)
if (newText.isEmpty() && affectedMarker.fragmentRange !in guardedRanges && affectedMarker.host?.contentRange == rangeInHost) {
markersToRemove.add(affectedMarker)
}
myHostDocument.replaceString(rangeInHost.startOffset, rangeInHost.endOffset, newText)
workingRange = workingRange union TextRange.from(rangeInHost.startOffset, newText.length)
}
workingRange = workingRange ?: failAndReport("no workingRange", e)
psiDocumentManager.commitDocument(myHostDocument)
if (markersToRemove.isNotEmpty()) {
val remainingRange = removeHostsFromConcatenation(markersToRemove)
if (remainingRange != null) {
workingRange = remainingRange
getInjectionHostAtRange(hostPsiFile, remainingRange)?.let { host ->
myHostEditor.caretModel.moveToOffset(
ElementManipulators.getOffsetInElement(host) + host.textRange.startOffset
)
}
}
}
val wholeRange = markersWholeRange(affectedMarkers) union workingRange ?: failAndReport("no wholeRange", e)
CodeStyleManager.getInstance(myProject).reformatRange(
hostPsiFile, wholeRange.startOffset, wholeRange.endOffset, true)
rebuildMarkers(workingRange)
updateFileContextElementIfNeeded(hostPsiFile, workingRange)
}
private fun updateFileContextElementIfNeeded(hostPsiFile: PsiFile, workingRange: TextRange) {
val fragmentPsiFile = PsiDocumentManager.getInstance(myProject).getCachedPsiFile(myFragmentDocument) ?: return
val injectedPointer = fragmentPsiFile.getUserData(FileContextUtil.INJECTED_IN_ELEMENT) ?: return
if (injectedPointer.element != null) return // still valid no need to update
val newHost = getInjectionHostAtRange(hostPsiFile, workingRange) ?: return
fragmentPsiFile.putUserData(FileContextUtil.INJECTED_IN_ELEMENT, newHost.createSmartPointer())
}
private var myInvalidated = false
override fun isValid(): Boolean = !myInvalidated && super.isValid()
private fun hasInjectionsInOriginFile(affectedMarkers: List<MarkersMapping>, hostPsiFile: PsiFile): Boolean {
val injectedLanguageManager = InjectedLanguageManager.getInstance(myProject)
return affectedMarkers.any { marker ->
marker.hostElementRange?.let { injectedLanguageManager.getCachedInjectedDocumentsInRange(hostPsiFile, it).isNotEmpty() } ?: false
}
}
private fun rebuildMarkers(contextRange: TextRange) {
val psiDocumentManager = PsiDocumentManager.getInstance(myProject)
psiDocumentManager.commitDocument(myHostDocument)
val hostPsiFile = psiDocumentManager.getPsiFile(myHostDocument) ?: failAndReport("no psiFile $myHostDocument")
val injectedLanguageManager = InjectedLanguageManager.getInstance(myProject)
val newInjectedFile = getInjectionHostAtRange(hostPsiFile, contextRange)?.let { host ->
val injectionRange = run {
val hostRange = host.textRange
val contextRangeTrimmed = hostRange.intersection(contextRange) ?: hostRange
contextRangeTrimmed.shiftLeft(hostRange.startOffset)
}
injectedLanguageManager.getInjectedPsiFiles(host)
.orEmpty()
.asSequence()
.filter { (_, range) -> range.length > 0 && injectionRange.contains(range) }
.mapNotNull { it.first as? PsiFile }
.firstOrNull()
}
if (newInjectedFile !== myInjectedFile) {
myInjectedFile = newInjectedFile ?: myInjectedFile
markers.forEach { it.dispose() }
markers.clear()
//some hostless shreds could exist for keeping guarded values
val hostfulShreds = InjectedLanguageUtil.getShreds(myInjectedFile).filter { it.host != null }
val markersFromShreds = getMarkersFromShreds(hostfulShreds)
markers.addAll(markersFromShreds)
}
}
private val guardedBlocks get() = (myFragmentDocument as DocumentEx).guardedBlocks
private fun promoteLinesEnds(mapping: List<Pair<MarkersMapping, String>>): Iterable<Pair<MarkersMapping, String>> {
val result = ArrayList<Pair<MarkersMapping, String>>(mapping.size)
var transfer = ""
val reversed = ContainerUtil.reverse(mapping)
for (i in reversed.indices) {
val (marker, text) = reversed[i]
if (text == "\n" && reversed.getOrNull(i + 1)?.second?.endsWith("\n") == false) {
result.add(Pair(marker, ""))
transfer += "\n"
}
else if (transfer != "") {
result.add(Pair(marker, text + transfer))
transfer = ""
}
else {
result.add(reversed[i])
}
}
return ContainerUtil.reverse(result)
}
private fun markersWholeRange(affectedMarkers: List<MarkersMapping>): TextRange? =
affectedMarkers.asSequence()
.filter { it.host?.isValid ?: false }
.mapNotNull { it.hostElementRange }
.takeIf { it.any() }?.reduce(TextRange::union)
private fun getFollowingElements(host: PsiLanguageInjectionHost): List<PsiElement>? {
val result = SmartList<PsiElement>()
for (sibling in host.nextSiblings) {
if (intermediateElement(sibling)) {
result.add(sibling)
}
else {
return result
}
}
return null
}
private fun removeHostsFromConcatenation(hostsToRemove: List<MarkersMapping>): TextRange? {
val psiPolyadicExpression = hostsToRemove.asSequence().mapNotNull { it.host?.parent as? PsiPolyadicExpression }.distinct().singleOrNull()
for (marker in hostsToRemove.reversed()) {
val host = marker.host ?: continue
val relatedElements = getFollowingElements(host) ?: host.prevSiblings.takeWhile(::intermediateElement).toList()
if (relatedElements.isNotEmpty()) {
host.delete()
marker.hostMarker.dispose()
for (related in relatedElements) {
if (related.isValid) {
related.delete()
}
}
}
}
if (psiPolyadicExpression != null) {
// distinct because Java could duplicate operands sometimes (EA-142380), mb something is wrong with the removal code upper ?
psiPolyadicExpression.operands.distinct().singleOrNull()?.let { onlyRemaining ->
return psiPolyadicExpression.replace(onlyRemaining).textRange
}
}
return null
}
}
private infix fun TextRange?.union(another: TextRange?) = another?.let { this?.union(it) ?: it } ?: this
private fun intermediateElement(psi: PsiElement) =
psi is PsiWhiteSpace || (psi is PsiJavaToken && psi.tokenType == JavaTokenType.PLUS)
private val PsiElement.nextSiblings: Sequence<PsiElement>
get() = generateSequence(this.nextSibling) { it.nextSibling }
private val PsiElement.prevSiblings: Sequence<PsiElement>
get() = generateSequence(this.prevSibling) { it.prevSibling }
| apache-2.0 | 9d281c723d0c7c46356afd7bfd1785d8 | 40.64898 | 141 | 0.732948 | 4.730644 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/mapping/types/memberFunctions.kt | 2 | 746 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.reflect.jvm.javaType
import kotlin.test.assertEquals
class A {
fun foo(t: Long?): Long = t!!
}
object O {
@JvmStatic
fun bar(a: A): String = ""
}
fun box(): String {
val foo = A::foo
assertEquals(listOf(A::class.java, java.lang.Long::class.java), foo.parameters.map { it.type.javaType })
assertEquals(java.lang.Long.TYPE, foo.returnType.javaType)
val bar = O::class.members.single { it.name == "bar" }
assertEquals(listOf(O::class.java, A::class.java), bar.parameters.map { it.type.javaType })
assertEquals(String::class.java, bar.returnType.javaType)
return "OK"
}
| apache-2.0 | 83495771343b013d45c87357de053f11 | 25.642857 | 108 | 0.678284 | 3.345291 | false | false | false | false |
JuliusKunze/kotlin-native | performance/src/main/kotlin/org/jetbrains/ring/ClassArrayBenchmark.kt | 2 | 2592 | /*
* 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.ring
open class ClassArrayBenchmark {
private var _data: Array<Value>? = null
val data: Array<Value>
get() = _data!!
fun setup() {
val list = ArrayList<Value>(BENCHMARK_SIZE)
for (n in classValues(BENCHMARK_SIZE))
list.add(n)
_data = list.toTypedArray()
}
//Benchmark
fun copy(): List<Value> {
return data.toList()
}
//Benchmark
fun copyManual(): List<Value> {
val list = ArrayList<Value>(data.size)
for (item in data) {
list.add(item)
}
return list
}
//Benchmark
fun filterAndCount(): Int {
return data.filter { filterLoad(it) }.count()
}
//Benchmark
fun filterAndMap(): List<String> {
return data.filter { filterLoad(it) }.map { mapLoad(it) }
}
//Benchmark
fun filterAndMapManual(): ArrayList<String> {
val list = ArrayList<String>()
for (it in data) {
if (filterLoad(it)) {
val value = mapLoad(it)
list.add(value)
}
}
return list
}
//Benchmark
fun filter(): List<Value> {
return data.filter { filterLoad(it) }
}
//Benchmark
fun filterManual(): List<Value> {
val list = ArrayList<Value>()
for (it in data) {
if (filterLoad(it))
list.add(it)
}
return list
}
//Benchmark
fun countFilteredManual(): Int {
var count = 0
for (it in data) {
if (filterLoad(it))
count++
}
return count
}
//Benchmark
fun countFiltered(): Int {
return data.count { filterLoad(it) }
}
//Benchmark
fun countFilteredLocal(): Int {
return data.cnt { filterLoad(it) }
}
//Benchmark
// fun reduce(): Int {
// return data.fold(0) { acc, it -> if (filterLoad(it)) acc + 1 else acc }
// }
}
| apache-2.0 | 7c5036f8b25fd30fe8e4b13d58a4bc13 | 23.45283 | 81 | 0.565586 | 4.088328 | false | false | false | false |
vicboma1/Kotlin-Koans | src/main/java/iii_conventions/_30_MultiAssignment.kt | 1 | 545 | package iii_conventions.multiAssignemnt
import util.TODO
import util.doc30
fun todoTask30(): Nothing = TODO(
"""
Task 30.
Read about multi-declarations and make the following code compile by adding one word (after uncommenting it).
""",
documentation = doc30()
)
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)
fun isLeapDay(date: MyDate): Boolean {
val (year, month, dayOfMonth) = date
// 29 February of a leap year
return (year % 4 == 0) && (month == 2) && (dayOfMonth == 29)
} | mit | 8895dd2ee3cf9c374916153bd95404e7 | 26.3 | 117 | 0.662385 | 3.732877 | false | false | false | false |
QuixomTech/DeviceInfo | app/src/main/java/com/quixom/apps/deviceinfo/fragments/BlueToothFragment.kt | 1 | 6328 | package com.quixom.apps.deviceinfo.fragments
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Activity.RESULT_OK
import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.view.*
import com.quixom.apps.deviceinfo.R
import kotlinx.android.synthetic.main.fragment_blue_tooth.*
import kotlinx.android.synthetic.main.toolbar_ui.*
/**
* A simple [Fragment] subclass.
*/
class BlueToothFragment : BaseFragment() {
val REQUEST_ENABLE_BT = 1
var mBluetoothAdapter: BluetoothAdapter? = null
private val mbluetoothStateReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val action = intent?.action
if (action == BluetoothAdapter.ACTION_STATE_CHANGED) {
val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
when (state) {
BluetoothAdapter.STATE_OFF -> {
tv_bluetooth_state.text = mActivity.resources.getString(R.string.switch_off)
bluetoothAnimationView.visibility = View.GONE
bluetoothOnOff.isEnabled = true
bluetoothOnOff.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.colorPrimary))
}
BluetoothAdapter.STATE_ON -> {
bluetoothAnimationView.visibility = View.VISIBLE
bluetoothOnOff.isEnabled = false
bluetoothOnOff.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.divider))
}
}
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// return inflater.inflate(R.layout.fragment_blue_tooth, container, false)
val contextThemeWrapper = ContextThemeWrapper(activity, R.style.BluetoothTheme)
val localInflater = inflater.cloneInContext(contextThemeWrapper)
val view = localInflater.inflate(R.layout.fragment_blue_tooth, container, false)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val window = activity!!.window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = resources.getColor(R.color.dark_blue_one)
window.navigationBarColor = resources.getColor(R.color.dark_blue_one)
}
return view;
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
initToolbar()
// Register broadcasts receiver for bluetooth state change
val filter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)
mActivity.registerReceiver(mbluetoothStateReceiver, filter)
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
getLocalBluetoothName()
bluetoothOnOff.setOnClickListener(View.OnClickListener {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
})
}
override fun onHiddenChanged(hidden: Boolean) {
super.onHiddenChanged(hidden)
if (!hidden && isAdded) {
initToolbar()
}
}
override fun onDestroy() {
super.onDestroy()
mActivity.unregisterReceiver(mbluetoothStateReceiver)
}
private fun initToolbar(): Unit {
mActivity?.iv_menu?.visibility = View.VISIBLE
mActivity?.iv_back?.visibility = View.GONE
mActivity?.tv_title?.text = mResources.getString(R.string.bluetooth)
mActivity?.iv_menu?.setOnClickListener {
mActivity.openDrawer()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == RESULT_OK) {
bluetoothAnimationView.visibility = View.VISIBLE
} else {
bluetoothAnimationView.visibility = View.GONE
}
}
if (mBluetoothAdapter?.isEnabled!!) {
bluetoothOnOff.isEnabled = false
bluetoothOnOff.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.divider))
} else {
bluetoothOnOff.isEnabled = true
bluetoothOnOff.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.blueetooth_color))
}
}
@TargetApi(Build.VERSION_CODES.O)
@SuppressLint("HardwareIds", "WrongConstant")
private fun getLocalBluetoothName() {
if (mBluetoothAdapter == null) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
bluetoothOnOff.isEnabled = false
}
tv_bluetooth_name.text = mBluetoothAdapter?.name
tv_bluetooth_address.text = mBluetoothAdapter?.address
tv_bluetooth_scan_mode.text = mBluetoothAdapter?.scanMode.toString()
if (mBluetoothAdapter?.isEnabled!!) {
tv_bluetooth_state.text = mActivity.resources.getString(R.string.switch_on)
bluetoothAnimationView.visibility = View.VISIBLE
bluetoothOnOff.isEnabled = false
bluetoothOnOff.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.divider))
} else {
bluetoothAnimationView.visibility = View.GONE
tv_bluetooth_state.text = mActivity.resources.getString(R.string.switch_off)
bluetoothOnOff.text = mActivity.resources.getString(R.string.turn_on_bluetooth)
bluetoothOnOff.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.blueetooth_color))
}
if (mBluetoothAdapter!!.isDiscovering) {
} else {
tv_bluetooth_discovery.text = mActivity.resources.getString(R.string.switch_off)
}
}
}
| apache-2.0 | bbda40a62b70347fa6f50813b00b8baf | 37.585366 | 114 | 0.664981 | 5.070513 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt | 1 | 5611 | package info.nightscout.androidaps.utils.wizard
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.JsonHelper.safeGetInt
import info.nightscout.androidaps.utils.JsonHelper.safeGetString
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONException
import org.json.JSONObject
import java.util.*
import javax.inject.Inject
class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjector) {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var sp: SP
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
@Inject lateinit var loopPlugin: LoopPlugin
@Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
lateinit var storage: JSONObject
var position: Int = -1
companion object {
const val YES = 0
const val NO = 1
private const val POSITIVE_ONLY = 2
private const val NEGATIVE_ONLY = 3
}
init {
injector.androidInjector().inject(this)
val emptyData = "{\"buttonText\":\"\",\"carbs\":0,\"validFrom\":0,\"validTo\":86340}"
try {
storage = JSONObject(emptyData)
} catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e)
}
}
/*
{
buttonText: "Meal",
carbs: 36,
validFrom: 8 * 60 * 60, // seconds from midnight
validTo: 9 * 60 * 60, // seconds from midnight
useBG: 0,
useCOB: 0,
useBolusIOB: 0,
useBasalIOB: 0,
useTrend: 0,
useSuperBolus: 0,
useTemptarget: 0
}
*/
fun from(entry: JSONObject, position: Int): QuickWizardEntry {
storage = entry
this.position = position
return this
}
fun isActive(): Boolean = Profile.secondsFromMidnight() >= validFrom() && Profile.secondsFromMidnight() <= validTo()
fun doCalc(profile: Profile, profileName: String, lastBG: BgReading, _synchronized: Boolean): BolusWizard {
val tempTarget = treatmentsPlugin.tempTargetFromHistory
//BG
var bg = 0.0
if (useBG() == YES) {
bg = lastBG.valueToUnits(profileFunction.getUnits())
}
// COB
var cob = 0.0
if (useCOB() == YES) {
val cobInfo = iobCobCalculatorPlugin.getCobInfo(_synchronized, "QuickWizard COB")
if (cobInfo.displayCob != null) cob = cobInfo.displayCob
}
// Bolus IOB
var bolusIOB = false
if (useBolusIOB() == YES) {
bolusIOB = true
}
// Basal IOB
treatmentsPlugin.updateTotalIOBTempBasals()
val basalIob = treatmentsPlugin.lastCalculationTempBasals.round()
var basalIOB = false
if (useBasalIOB() == YES) {
basalIOB = true
} else if (useBasalIOB() == POSITIVE_ONLY && basalIob.iob > 0) {
basalIOB = true
} else if (useBasalIOB() == NEGATIVE_ONLY && basalIob.iob < 0) {
basalIOB = true
}
// SuperBolus
var superBolus = false
if (useSuperBolus() == YES && sp.getBoolean(R.string.key_usesuperbolus, false)) {
superBolus = true
}
if (loopPlugin.isEnabled(loopPlugin.getType()) && loopPlugin.isSuperBolus) superBolus = false
// Trend
val glucoseStatus = GlucoseStatus(injector).glucoseStatusData
var trend = false
if (useTrend() == YES) {
trend = true
} else if (useTrend() == POSITIVE_ONLY && glucoseStatus != null && glucoseStatus.short_avgdelta > 0) {
trend = true
} else if (useTrend() == NEGATIVE_ONLY && glucoseStatus != null && glucoseStatus.short_avgdelta < 0) {
trend = true
}
val percentage = sp.getDouble(R.string.key_boluswizard_percentage, 100.0)
return BolusWizard(injector).doCalc(profile, profileName, tempTarget, carbs(), cob, bg, 0.0, percentage, true, useCOB() == YES, bolusIOB, basalIOB, superBolus, useTempTarget() == YES, trend, false, "QuickWizard")
}
fun buttonText(): String = safeGetString(storage, "buttonText", "")
fun carbs(): Int = safeGetInt(storage, "carbs")
fun validFromDate(): Date = DateUtil.toDate(validFrom())
fun validToDate(): Date = DateUtil.toDate(validTo())
fun validFrom(): Int = safeGetInt(storage, "validFrom")
fun validTo(): Int = safeGetInt(storage, "validTo")
fun useBG(): Int = safeGetInt(storage, "useBG", YES)
fun useCOB(): Int = safeGetInt(storage, "useCOB", NO)
fun useBolusIOB(): Int = safeGetInt(storage, "useBolusIOB", YES)
fun useBasalIOB(): Int = safeGetInt(storage, "useBasalIOB", YES)
fun useTrend(): Int = safeGetInt(storage, "useTrend", NO)
fun useSuperBolus(): Int = safeGetInt(storage, "useSuperBolus", NO)
fun useTempTarget(): Int = safeGetInt(storage, "useTempTarget", NO)
} | agpl-3.0 | 25029c959f3d0450e96ba9fd1dde1ebf | 36.918919 | 220 | 0.651577 | 4.373344 | false | false | false | false |
siosio/intellij-community | plugins/gradle/java/src/execution/build/GradleBaseApplicationEnvironmentProvider.kt | 1 | 8205 | // 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.plugins.gradle.execution.build
import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil
import com.intellij.compiler.options.CompileStepBeforeRun
import com.intellij.execution.CantRunException
import com.intellij.execution.ExecutionBundle
import com.intellij.execution.Executor
import com.intellij.execution.JavaRunConfigurationBase
import com.intellij.execution.configurations.JavaParameters
import com.intellij.execution.configurations.JavaRunConfigurationModule
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.execution.impl.RunManagerImpl
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.target.getEffectiveConfiguration
import com.intellij.execution.util.ExecutionErrorDialog
import com.intellij.execution.util.JavaParametersUtil
import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemRunConfiguration
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdkType
import com.intellij.openapi.projectRoots.JavaSdkVersion
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.ex.JavaSdkUtil
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiJavaModule
import com.intellij.task.ExecuteRunConfigurationTask
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.plugins.gradle.codeInspection.GradleInspectionBundle
import org.jetbrains.plugins.gradle.execution.GradleRunnerUtil
import org.jetbrains.plugins.gradle.execution.target.GradleServerEnvironmentSetup
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverUtil
import org.jetbrains.plugins.gradle.service.task.GradleTaskManager
import org.jetbrains.plugins.gradle.util.GradleConstants
@ApiStatus.Experimental
abstract class GradleBaseApplicationEnvironmentProvider<T : JavaRunConfigurationBase> : GradleExecutionEnvironmentProvider {
abstract fun generateInitScript(
applicationConfiguration: T, module: Module, params: JavaParameters,
gradleTaskPath: String, runAppTaskName: String, mainClass: PsiClass, javaExePath: String,
sourceSetName: String, javaModuleName: String?
): String?
override fun createExecutionEnvironment(project: Project,
executeRunConfigurationTask: ExecuteRunConfigurationTask,
executor: Executor?): ExecutionEnvironment? {
if (!isApplicable(executeRunConfigurationTask)) return null
val runProfile = executeRunConfigurationTask.runProfile
if (runProfile !is JavaRunConfigurationBase) return null
val runClass = runProfile.runClass
val mainClass = runProfile.configurationModule.findClass(runClass) ?: return null
val virtualFile = mainClass.containingFile.virtualFile
val module = ProjectFileIndex.SERVICE.getInstance(project).getModuleForFile(virtualFile) ?: return null
val params = JavaParameters().apply {
JavaParametersUtil.configureConfiguration(this, runProfile)
this.vmParametersList.addParametersString(runProfile.vmParameters)
}
val javaModuleName: String?
val javaExePath: String
try {
if (getEffectiveConfiguration(runProfile, project) != null) {
javaModuleName = null
javaExePath = GradleServerEnvironmentSetup.targetJavaExecutablePathMappingKey
}
else {
val jdk = JavaParametersUtil.createProjectJdk(project, runProfile.alternativeJrePath)
?: throw RuntimeException(ExecutionBundle.message("run.configuration.error.no.jdk.specified"))
val type = jdk.sdkType
if (type !is JavaSdkType) throw RuntimeException(ExecutionBundle.message("run.configuration.error.no.jdk.specified"))
javaExePath = (type as JavaSdkType).getVMExecutablePath(jdk)?.let {
FileUtil.toSystemIndependentName(it)
} ?: throw RuntimeException(ExecutionBundle.message("run.configuration.cannot.find.vm.executable"))
javaModuleName = findJavaModuleName(jdk, runProfile.configurationModule, mainClass)
}
}
catch (e: CantRunException) {
ExecutionErrorDialog.show(e, GradleInspectionBundle.message("dialog.title.cannot.use.specified.jre"), project)
throw RuntimeException(ExecutionBundle.message("run.configuration.cannot.find.vm.executable"))
}
val taskSettings = ExternalSystemTaskExecutionSettings()
taskSettings.isPassParentEnvs = params.isPassParentEnvs
taskSettings.env = if (params.env.isEmpty()) emptyMap() else HashMap(params.env)
taskSettings.externalSystemIdString = GradleConstants.SYSTEM_ID.id
val gradleModuleData = CachedModuleDataFinder.getGradleModuleData(module)
taskSettings.externalProjectPath = gradleModuleData?.directoryToRunTask ?: GradleRunnerUtil.resolveProjectPath(module)
val runAppTaskName = mainClass.name!! + ".main()"
taskSettings.taskNames = listOf((gradleModuleData?.getTaskPath(runAppTaskName) ?: runAppTaskName))
val executorId = executor?.id ?: DefaultRunExecutor.EXECUTOR_ID
val environment = ExternalSystemUtil.createExecutionEnvironment(project, GradleConstants.SYSTEM_ID, taskSettings, executorId)
?: return null
val runnerAndConfigurationSettings = environment.runnerAndConfigurationSettings!!
val gradleRunConfiguration = runnerAndConfigurationSettings.configuration as ExternalSystemRunConfiguration
val gradlePath = GradleProjectResolverUtil.getGradlePath(module) ?: return null
val sourceSetName = when {
GradleConstants.GRADLE_SOURCE_SET_MODULE_TYPE_KEY == ExternalSystemApiUtil.getExternalModuleType(
module) -> GradleProjectResolverUtil.getSourceSetName(module)
ModuleRootManager.getInstance(module).fileIndex.isInTestSourceContent(virtualFile) -> "test"
else -> "main"
} ?: return null
val initScript = generateInitScript(runProfile as T, module, params, gradlePath,
runAppTaskName, mainClass, javaExePath, sourceSetName, javaModuleName)
gradleRunConfiguration.putUserData<String>(GradleTaskManager.INIT_SCRIPT_KEY, initScript)
gradleRunConfiguration.putUserData<String>(GradleTaskManager.INIT_SCRIPT_PREFIX_KEY, runAppTaskName)
// reuse all before tasks except 'Make' as it doesn't make sense for delegated run
gradleRunConfiguration.beforeRunTasks = RunManagerImpl.getInstanceImpl(project).getBeforeRunTasks(runProfile)
.filter { it.providerId !== CompileStepBeforeRun.ID }
return environment
}
companion object {
fun createEscapedParameters(parameters: List<String>, prefix: String): String {
val result = StringBuilder()
for (parameter in parameters) {
if (StringUtil.isEmpty(parameter)) continue
val escaped = StringUtil.escapeChars(parameter, '\\', '"', '\'')
result.append(prefix).append(" '").append(escaped).append("'\n")
}
return result.toString()
}
private fun findJavaModuleName(sdk: Sdk, module: JavaRunConfigurationModule, mainClass: PsiClass): String? {
return if (JavaSdkUtil.isJdkAtLeast(sdk, JavaSdkVersion.JDK_1_9)) {
DumbService.getInstance(module.project).computeWithAlternativeResolveEnabled<PsiJavaModule, RuntimeException> {
JavaModuleGraphUtil.findDescriptorByElement(module.findClass(mainClass.qualifiedName))
}?.name ?: return null
}
else null
}
}
} | apache-2.0 | 42ca15c06626535dfce4750020578a65 | 54.073826 | 158 | 0.774893 | 5.189753 | false | true | false | false |
siosio/intellij-community | plugins/kotlin/jps/jps-plugin/src/org/jetbrains/kotlin/jps/incremental/KotlinDataContainerTargetType.kt | 1 | 2244 | // 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.jps.incremental
import org.jetbrains.jps.builders.*
import org.jetbrains.jps.builders.storage.BuildDataPaths
import org.jetbrains.jps.incremental.CompileContext
import org.jetbrains.jps.indices.IgnoredFileIndex
import org.jetbrains.jps.indices.ModuleExcludeIndex
import org.jetbrains.jps.model.JpsModel
import org.jetbrains.kotlin.config.SettingConstants
import java.io.File
object KotlinDataContainerTargetType : BuildTargetType<KotlinDataContainerTarget>(SettingConstants.KOTLIN_DATA_CONTAINER_ID) {
override fun computeAllTargets(model: JpsModel): List<KotlinDataContainerTarget> = listOf(KotlinDataContainerTarget)
override fun createLoader(model: JpsModel): BuildTargetLoader<KotlinDataContainerTarget> =
object : BuildTargetLoader<KotlinDataContainerTarget>() {
override fun createTarget(targetId: String): KotlinDataContainerTarget = KotlinDataContainerTarget
}
}
// Fake target to store data per project for incremental compilation
object KotlinDataContainerTarget : BuildTarget<BuildRootDescriptor>(KotlinDataContainerTargetType) {
override fun getId(): String = SettingConstants.KOTLIN_DATA_CONTAINER_ID
override fun getPresentableName(): String = SettingConstants.KOTLIN_DATA_CONTAINER_ID
override fun computeRootDescriptors(
model: JpsModel?,
index: ModuleExcludeIndex?,
ignoredFileIndex: IgnoredFileIndex?,
dataPaths: BuildDataPaths?
): List<BuildRootDescriptor> = listOf()
override fun getOutputRoots(context: CompileContext): Collection<File> {
val dataManager = context.projectDescriptor.dataManager
val storageRoot = dataManager.dataPaths.dataStorageRoot
return listOf(File(storageRoot, SettingConstants.KOTLIN_DATA_CONTAINER_ID))
}
override fun findRootDescriptor(rootId: String?, rootIndex: BuildRootIndex?): BuildRootDescriptor? = null
override fun computeDependencies(
targetRegistry: BuildTargetRegistry?,
outputIndex: TargetOutputIndex?
): Collection<BuildTarget<*>> = listOf()
}
| apache-2.0 | 71aa4f48f3c85324ac7f211b6f4c2996 | 46.744681 | 158 | 0.782531 | 4.867679 | false | false | false | false |
actions-on-google/app-actions-dynamic-shortcuts | app/src/main/java/com/example/android/architecture/blueprints/todoapp/taskdetail/TaskDetailFragment.kt | 1 | 4013 | /*
* Copyright (C) 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp.taskdetail
import android.os.Bundle
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 androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.example.android.architecture.blueprints.todoapp.EventObserver
import com.example.android.architecture.blueprints.todoapp.R
import com.example.android.architecture.blueprints.todoapp.databinding.TaskdetailFragBinding
import com.example.android.architecture.blueprints.todoapp.tasks.DELETE_RESULT_OK
import com.example.android.architecture.blueprints.todoapp.util.getViewModelFactory
import com.example.android.architecture.blueprints.todoapp.util.setupRefreshLayout
import com.example.android.architecture.blueprints.todoapp.util.setupSnackbar
import com.google.android.material.snackbar.Snackbar
/**
* Main UI for the task detail screen.
*/
class TaskDetailFragment : Fragment() {
private lateinit var viewDataBinding: TaskdetailFragBinding
private val args: TaskDetailFragmentArgs by navArgs()
private val viewModel by viewModels<TaskDetailViewModel> { getViewModelFactory() }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupFab()
view.setupSnackbar(this, viewModel.snackbarText, Snackbar.LENGTH_SHORT)
setupNavigation()
this.setupRefreshLayout(viewDataBinding.refreshLayout)
}
private fun setupNavigation() {
viewModel.deleteTaskEvent.observe(viewLifecycleOwner, EventObserver {
val action = TaskDetailFragmentDirections
.actionTaskDetailFragmentToTasksFragment(DELETE_RESULT_OK)
findNavController().navigate(action)
})
viewModel.editTaskEvent.observe(viewLifecycleOwner, EventObserver {
val action = TaskDetailFragmentDirections
.actionTaskDetailFragmentToAddEditTaskFragment(
args.taskId,
resources.getString(R.string.edit_task)
)
findNavController().navigate(action)
})
}
private fun setupFab() {
activity?.findViewById<View>(R.id.edit_task_fab)?.setOnClickListener {
viewModel.editTask()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.taskdetail_frag, container, false)
viewDataBinding = TaskdetailFragBinding.bind(view).apply {
viewmodel = viewModel
}
viewDataBinding.lifecycleOwner = this.viewLifecycleOwner
viewModel.start(args.taskId)
setHasOptionsMenu(true)
return view
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_delete -> {
viewModel.deleteTask()
true
}
else -> false
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.taskdetail_fragment_menu, menu)
}
}
| apache-2.0 | 37f80b773b951a8ef7e8563fe63c2b34 | 36.157407 | 92 | 0.718166 | 4.870146 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateEqualsWizard.kt | 1 | 5120 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.actions.generate
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.generation.ui.AbstractGenerateEqualsWizard
import com.intellij.ide.wizard.StepAdapter
import com.intellij.java.JavaBundle
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.refactoring.classMembers.AbstractMemberInfoModel
import com.intellij.ui.NonFocusableCheckBox
import com.intellij.util.containers.HashMap
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.core.isInheritable
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberSelectionPanel
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.utils.keysToMap
import javax.swing.JLabel
import javax.swing.JPanel
class KotlinGenerateEqualsWizard(
project: Project,
klass: KtClass,
properties: List<KtNamedDeclaration>,
needEquals: Boolean,
needHashCode: Boolean
) : AbstractGenerateEqualsWizard<KtClass, KtNamedDeclaration, KotlinMemberInfo>(
project, BuilderImpl(klass, properties, needEquals, needHashCode)
) {
private object MemberInfoModelImpl : AbstractMemberInfoModel<KtNamedDeclaration, KotlinMemberInfo>()
private class BuilderImpl(
private val klass: KtClass,
properties: List<KtNamedDeclaration>,
needEquals: Boolean,
needHashCode: Boolean
) : AbstractGenerateEqualsWizard.Builder<KtClass, KtNamedDeclaration, KotlinMemberInfo>() {
private val equalsPanel: KotlinMemberSelectionPanel?
private val hashCodePanel: KotlinMemberSelectionPanel?
private val memberInfos = properties.map { createMemberInfo(it) }
private val membersToHashCode = HashMap(properties.keysToMap { createMemberInfo(it) })
init {
equalsPanel = if (needEquals) {
KotlinMemberSelectionPanel(KotlinBundle.message("action.generate.equals.choose.equals"), memberInfos, null).apply {
table.memberInfoModel = MemberInfoModelImpl
}
} else null
hashCodePanel = if (needHashCode) {
KotlinMemberSelectionPanel(KotlinBundle.message("action.generate.equals.choose.hashcode"), memberInfos, null).apply {
table.memberInfoModel = MemberInfoModelImpl
}
} else null
}
private fun createMemberInfo(it: KtNamedDeclaration): KotlinMemberInfo {
return KotlinMemberInfo(it).apply {
val descriptor = it.unsafeResolveToDescriptor()
isChecked = (descriptor as? PropertyDescriptor)?.getter?.isDefault ?: true
}
}
override fun getPsiClass() = klass
override fun getClassFields() = memberInfos
override fun getFieldsToHashCode() = membersToHashCode
override fun getFieldsToNonNull() = HashMap<KtNamedDeclaration, KotlinMemberInfo>()
override fun getEqualsPanel() = equalsPanel
override fun getHashCodePanel() = hashCodePanel
override fun getNonNullPanel() = null
override fun updateHashCodeMemberInfos(equalsMemberInfos: MutableCollection<out KotlinMemberInfo>) {
hashCodePanel?.table?.setMemberInfos(equalsMemberInfos.map { membersToHashCode[it.member] })
}
override fun updateNonNullMemberInfos(equalsMemberInfos: MutableCollection<out KotlinMemberInfo>?) {
}
}
private object OptionsStep : StepAdapter() {
private val panel = JPanel(VerticalFlowLayout())
init {
with(NonFocusableCheckBox(JavaBundle.message("generate.equals.hashcode.accept.sublcasses"))) {
isSelected = CodeInsightSettings.getInstance().USE_INSTANCEOF_ON_EQUALS_PARAMETER
addActionListener { CodeInsightSettings.getInstance().USE_INSTANCEOF_ON_EQUALS_PARAMETER = isSelected }
panel.add(this)
}
panel.add(JLabel(JavaBundle.message("generate.equals.hashcode.accept.sublcasses.explanation")))
}
override fun getComponent() = panel
}
override fun addSteps() {
if (myEqualsPanel != null && myClass.isInheritable()) {
addStep(OptionsStep)
}
super.addSteps()
}
override fun doOKAction() {
myEqualsPanel?.let { updateHashCodeMemberInfos(it.table.selectedMemberInfos) }
super.doOKAction()
}
fun getPropertiesForEquals() = myEqualsPanel?.table?.selectedMemberInfos?.map { it.member } ?: emptyList()
fun getPropertiesForHashCode() = myHashCodePanel?.table?.selectedMemberInfos?.map { it.member } ?: emptyList()
} | apache-2.0 | 66c9aafd2858bd88d6f78a7271b9d22d | 40.298387 | 158 | 0.720703 | 5.187437 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/mapSum2.kt | 2 | 399 | // API_VERSION: 1.3
// WITH_RUNTIME
// PROBLEM: none
data class OrderItem(val name: String, val price: Double, val count: Int)
fun main() {
val order = listOf<OrderItem>(
OrderItem("Cake", price = 10.0, count = 1),
OrderItem("Coffee", price = 2.5, count = 3),
OrderItem("Tea", price = 1.5, count = 2)
)
println(order.map<caret> { it.price * it.count }.sum())
} | apache-2.0 | 0bc740729a3afd9b5f0e86f16c55b271 | 25.666667 | 73 | 0.593985 | 3.217742 | false | false | false | false |
siosio/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/hprof/analysis/AnalyzeDisposer.kt | 2 | 14420 | /*
* Copyright (C) 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.intellij.diagnostic.hprof.analysis
import com.intellij.diagnostic.hprof.classstore.ClassDefinition
import com.intellij.diagnostic.hprof.navigator.ObjectNavigator
import com.intellij.diagnostic.hprof.util.HeapReportUtils.toPaddedShortStringAsSize
import com.intellij.diagnostic.hprof.util.HeapReportUtils.toShortStringAsCount
import com.intellij.diagnostic.hprof.util.HeapReportUtils.toShortStringAsSize
import com.intellij.diagnostic.hprof.util.TruncatingPrintBuffer
import it.unimi.dsi.fastutil.longs.LongArrayList
import it.unimi.dsi.fastutil.longs.LongList
import it.unimi.dsi.fastutil.longs.LongOpenHashSet
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import java.util.*
internal class AnalyzeDisposer(private val analysisContext: AnalysisContext) {
data class Grouping(val childClass: ClassDefinition,
val parentClass: ClassDefinition?,
val rootClass: ClassDefinition)
class InstanceStats {
private val parentIds = LongArrayList()
private val rootIds = LongOpenHashSet()
fun parentCount() = LongOpenHashSet(parentIds).size
fun rootCount() = rootIds.size
fun objectCount() = parentIds.size
fun registerObject(parentId: Long, rootId: Long) {
parentIds.add(parentId)
rootIds.add(rootId)
}
}
data class DisposedDominatorReportEntry(val classDefinition: ClassDefinition, val count: Long, val size: Long)
companion object {
val TOP_REPORTED_CLASSES = setOf(
"com.intellij.openapi.project.impl.ProjectImpl"
)
}
fun prepareDisposerTreeSection(): String {
if (!analysisContext.classStore.containsClass("com.intellij.openapi.util.Disposer")) {
return ""
}
val nav = analysisContext.navigator
val result = StringBuilder()
nav.goToStaticField("com.intellij.openapi.util.Disposer", "ourTree")
assert(!nav.isNull())
nav.goToInstanceField("com.intellij.openapi.util.ObjectTree", "myObject2NodeMap")
nav.goToInstanceField("it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap", "value")
val groupingToObjectStats = HashMap<Grouping, InstanceStats>()
val maxTreeDepth = 200
val tooDeepObjectClasses = HashSet<ClassDefinition>()
nav.getReferencesCopy().forEach {
if (it == 0L) {
return@forEach
}
nav.goTo(it)
val objectNodeParentId = nav.getInstanceFieldObjectId("com.intellij.openapi.util.ObjectNode", "myParent")
val objectNodeObjectId = nav.getInstanceFieldObjectId("com.intellij.openapi.util.ObjectNode", "myObject")
nav.goTo(objectNodeParentId)
val parentId =
if (nav.isNull())
0L
else
nav.getInstanceFieldObjectId("com.intellij.openapi.util.ObjectNode", "myObject")
val parentClass =
if (parentId == 0L)
null
else {
nav.goTo(parentId)
nav.getClass()
}
nav.goTo(objectNodeObjectId)
val objectClass = nav.getClass()
val rootClass: ClassDefinition
val rootId: Long
if (parentId == 0L) {
rootClass = objectClass
rootId = objectNodeObjectId
}
else {
var rootObjectNodeId = objectNodeParentId
var rootObjectId: Long
var iterationCount = 0
do {
nav.goTo(rootObjectNodeId)
rootObjectNodeId = nav.getInstanceFieldObjectId("com.intellij.openapi.util.ObjectNode", "myParent")
rootObjectId = nav.getInstanceFieldObjectId("com.intellij.openapi.util.ObjectNode", "myObject")
iterationCount++
}
while (rootObjectNodeId != 0L && iterationCount < maxTreeDepth)
if (iterationCount >= maxTreeDepth) {
tooDeepObjectClasses.add(objectClass)
rootId = parentId
rootClass = parentClass!!
}
else {
nav.goTo(rootObjectId)
rootId = rootObjectId
rootClass = nav.getClass()
}
}
groupingToObjectStats
.getOrPut(Grouping(objectClass, parentClass, rootClass)) { InstanceStats() }
.registerObject(parentId, rootId)
}
TruncatingPrintBuffer(400, 0, result::appendln).use { buffer ->
groupingToObjectStats
.entries
.asSequence()
.sortedByDescending { it.value.objectCount() }
.groupBy { it.key.rootClass }
.forEach { (rootClass, entries) ->
buffer.println("Root: ${rootClass.name}")
TruncatingPrintBuffer(100, 0, buffer::println).use { buffer ->
entries.forEach { (mapping, groupedObjects) ->
printDisposerTreeReportLine(buffer, mapping, groupedObjects)
}
}
buffer.println()
}
}
if (tooDeepObjectClasses.size > 0) {
result.appendln("Skipped analysis of objects too deep in disposer tree:")
tooDeepObjectClasses.forEach {
result.appendln(" * ${nav.classStore.getShortPrettyNameForClass(it)}")
}
}
return result.toString()
}
private fun printDisposerTreeReportLine(buffer: TruncatingPrintBuffer,
mapping: Grouping,
groupedObjects: InstanceStats) {
val (sourceClass, parentClass, rootClass) = mapping
val nav = analysisContext.navigator
val objectCount = groupedObjects.objectCount()
val parentCount = groupedObjects.parentCount()
// Ignore 1-1 mappings
if (parentClass != null && objectCount == parentCount)
return
val parentString: String
if (parentClass == null) {
parentString = "(no parent)"
}
else {
val parentClassName = nav.classStore.getShortPrettyNameForClass(parentClass)
val rootCount = groupedObjects.rootCount()
if (rootClass != parentClass || rootCount != parentCount) {
parentString = "<-- $parentCount $parentClassName [...] $rootCount"
}
else
parentString = "<-- $parentCount"
}
val sourceClassName = nav.classStore.getShortPrettyNameForClass(sourceClass)
buffer.println(" ${String.format("%6d", objectCount)} $sourceClassName $parentString")
}
fun computeDisposedObjectsIDs() {
val disposedObjectsIDs = analysisContext.disposedObjectsIDs
disposedObjectsIDs.clear()
val nav = analysisContext.navigator
val parentList = analysisContext.parentList
if (!nav.classStore.containsClass("com.intellij.openapi.util.Disposer")) {
return
}
nav.goToStaticField("com.intellij.openapi.util.Disposer", "ourTree")
assert(!nav.isNull())
nav.goToInstanceField("com.intellij.openapi.util.ObjectTree", "myDisposedObjects")
nav.goToInstanceField("com.intellij.util.containers.WeakHashMap", "myMap")
nav.goToInstanceField("com.intellij.util.containers.RefHashMap\$MyMap", "keys")
val weakKeyClass = nav.classStore["com.intellij.util.containers.WeakHashMap\$WeakKey"]
nav.getReferencesCopy().forEach {
if (it == 0L) {
return@forEach
}
nav.goTo(it, ObjectNavigator.ReferenceResolution.ALL_REFERENCES)
if (nav.getClass() != weakKeyClass) {
return@forEach
}
nav.goToInstanceField("com.intellij.util.containers.WeakHashMap\$WeakKey", "referent")
if (nav.id == 0L) {
return@forEach
}
val leakId = nav.id.toInt()
if (parentList[leakId] == 0) {
// If there is no parent, then the object does not have a strong-reference path to GC root
return@forEach
}
disposedObjectsIDs.add(leakId)
}
}
fun prepareDisposedObjectsSection(): String {
val result = StringBuilder()
val leakedInstancesByClass = HashMap<ClassDefinition, LongList>()
val countByClass = Object2IntOpenHashMap<ClassDefinition>()
var totalCount = 0
val nav = analysisContext.navigator
val disposedObjectsIDs = analysisContext.disposedObjectsIDs
val disposerOptions = analysisContext.config.disposerOptions
disposedObjectsIDs.forEach {
nav.goTo(it.toLong(), ObjectNavigator.ReferenceResolution.ALL_REFERENCES)
val leakClass = nav.getClass()
val leakId = nav.id
leakedInstancesByClass.computeIfAbsent(leakClass) { LongArrayList() }.add(leakId)
countByClass.put(leakClass, countByClass.getInt(leakClass) + 1)
totalCount++
}
// Convert TObjectIntHashMap to list of entries
data class TObjectIntMapEntry<T>(val key: T, val value: Int)
val entries = mutableListOf<TObjectIntMapEntry<ClassDefinition>>()
countByClass.object2IntEntrySet().fastForEach {
entries.add(TObjectIntMapEntry(it.key, it.intValue))
}
if (disposerOptions.includeDisposedObjectsSummary) {
// Print counts of disposed-but-strong-referenced objects
TruncatingPrintBuffer(100, 0, result::appendln).use { buffer ->
buffer.println("Count of disposed-but-strong-referenced objects: $totalCount")
entries
.sortedByDescending { it.value }
.partition { TOP_REPORTED_CLASSES.contains(it.key.name) }
.let { it.first + it.second }
.forEach { entry ->
buffer.println(" ${entry.value} ${entry.key.prettyName}")
}
}
result.appendln()
}
val disposedTree = GCRootPathsTree(analysisContext, AnalysisConfig.TreeDisplayOptions.all(), null)
val iterator = disposedObjectsIDs.iterator()
while (iterator.hasNext()) {
disposedTree.registerObject(iterator.nextInt())
}
val disposedDominatorNodesByClass = disposedTree.getDisposedDominatorNodes()
var allDominatorsCount = 0L
var allDominatorsSubgraphSize = 0L
val disposedDominatorClassSizeList = mutableListOf<DisposedDominatorReportEntry>()
disposedDominatorNodesByClass.forEach { (classDefinition, nodeList) ->
var dominatorClassSubgraphSize = 0L
var dominatorClassInstanceCount = 0L
nodeList.forEach {
dominatorClassInstanceCount += it.instances.size
dominatorClassSubgraphSize += it.totalSizeInDwords.toLong() * 4
}
allDominatorsCount += dominatorClassInstanceCount
allDominatorsSubgraphSize += dominatorClassSubgraphSize
disposedDominatorClassSizeList.add(
DisposedDominatorReportEntry(classDefinition, dominatorClassInstanceCount, dominatorClassSubgraphSize))
}
if (disposerOptions.includeDisposedObjectsSummary) {
TruncatingPrintBuffer(30, 0, result::appendln).use { buffer ->
buffer.println("Disposed-but-strong-referenced dominator object count: $allDominatorsCount")
buffer.println(
"Disposed-but-strong-referenced dominator sub-graph size: ${toShortStringAsSize(allDominatorsSubgraphSize)}")
disposedDominatorClassSizeList
.sortedByDescending { it.size }
.forEach { entry ->
buffer.println(
" ${toPaddedShortStringAsSize(entry.size)} - ${toShortStringAsCount(entry.count)} ${entry.classDefinition.name}")
}
}
result.appendln()
}
if (disposerOptions.includeDisposedObjectsDetails) {
val instancesListInOrder = getInstancesListInPriorityOrder(
leakedInstancesByClass,
disposedDominatorClassSizeList
)
TruncatingPrintBuffer(700, 0, result::appendln).use { buffer ->
instancesListInOrder
.forEach { instances ->
nav.goTo(instances.getLong(0))
buffer.println(
"Disposed but still strong-referenced objects: ${instances.size} ${nav.getClass().prettyName}, most common paths from GC-roots:")
val gcRootPathsTree = GCRootPathsTree(analysisContext, disposerOptions.disposedObjectsDetailsTreeDisplayOptions, nav.getClass())
instances.forEach { leakId ->
gcRootPathsTree.registerObject(leakId.toInt())
}
gcRootPathsTree.printTree().lineSequence().forEach(buffer::println)
}
}
}
return result.toString()
}
private fun getInstancesListInPriorityOrder(
classToLeakedIdsList: HashMap<ClassDefinition, LongList>,
disposedDominatorReportEntries: List<DisposedDominatorReportEntry>): List<LongList> {
val result = mutableListOf<LongList>()
// Make a mutable copy. When a class instances are added to the result list, remove the class entry from the copy.
val classToLeakedIdsListCopy = HashMap(classToLeakedIdsList)
// First, all top classes
TOP_REPORTED_CLASSES.forEach { topClassName ->
classToLeakedIdsListCopy
.filterKeys { it.name == topClassName }
.forEach { (classDefinition, list) ->
result.add(list)
classToLeakedIdsListCopy.remove(classDefinition)
}
}
// Alternate between class with most instances leaked and class with most bytes leaked
// Prepare instance count class list by priority
val classOrderByInstanceCount = ArrayDeque<ClassDefinition>(
classToLeakedIdsListCopy
.entries
.sortedByDescending { it.value.size }
.map { it.key }
)
// Prepare dominator bytes count class list by priority
val classOrderByByteCount = ArrayDeque<ClassDefinition>(
disposedDominatorReportEntries
.sortedByDescending { it.size }
.map { it.classDefinition }
)
// zip, but ignore duplicates
var nextByInstanceCount = true
while (!classOrderByInstanceCount.isEmpty() ||
!classOrderByByteCount.isEmpty()) {
val nextCollection = if (nextByInstanceCount) classOrderByInstanceCount else classOrderByByteCount
if (!nextCollection.isEmpty()) {
val nextClass = nextCollection.removeFirst()
val list = classToLeakedIdsListCopy.remove(nextClass) ?: continue
result.add(list)
}
nextByInstanceCount = !nextByInstanceCount
}
return result
}
} | apache-2.0 | 91950781dec25580e41ac9ce877a2b3d | 35.882353 | 143 | 0.687101 | 4.442391 | false | false | false | false |
apollographql/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/introspection/introspection_to_schema.kt | 1 | 11991 | package com.apollographql.apollo3.compiler.introspection
import com.apollographql.apollo3.annotations.ApolloExperimental
import com.apollographql.apollo3.ast.ConversionException
import com.apollographql.apollo3.ast.GQLArgument
import com.apollographql.apollo3.ast.GQLArguments
import com.apollographql.apollo3.ast.GQLBooleanValue
import com.apollographql.apollo3.ast.GQLDirective
import com.apollographql.apollo3.ast.GQLDocument
import com.apollographql.apollo3.ast.GQLEnumTypeDefinition
import com.apollographql.apollo3.ast.GQLEnumValueDefinition
import com.apollographql.apollo3.ast.GQLFieldDefinition
import com.apollographql.apollo3.ast.GQLFloatValue
import com.apollographql.apollo3.ast.GQLInputObjectTypeDefinition
import com.apollographql.apollo3.ast.GQLInputValueDefinition
import com.apollographql.apollo3.ast.GQLIntValue
import com.apollographql.apollo3.ast.GQLInterfaceTypeDefinition
import com.apollographql.apollo3.ast.GQLListType
import com.apollographql.apollo3.ast.GQLListValue
import com.apollographql.apollo3.ast.GQLNamedType
import com.apollographql.apollo3.ast.GQLNonNullType
import com.apollographql.apollo3.ast.GQLObjectField
import com.apollographql.apollo3.ast.GQLObjectTypeDefinition
import com.apollographql.apollo3.ast.GQLObjectValue
import com.apollographql.apollo3.ast.GQLOperationTypeDefinition
import com.apollographql.apollo3.ast.GQLScalarTypeDefinition
import com.apollographql.apollo3.ast.GQLSchemaDefinition
import com.apollographql.apollo3.ast.GQLStringValue
import com.apollographql.apollo3.ast.GQLType
import com.apollographql.apollo3.ast.GQLUnionTypeDefinition
import com.apollographql.apollo3.ast.GQLValue
import com.apollographql.apollo3.ast.Schema
import com.apollographql.apollo3.ast.SourceLocation
import com.apollographql.apollo3.ast.parseAsGQLDocument
import com.apollographql.apollo3.ast.parseAsGQLValue
import com.apollographql.apollo3.ast.toSchema
import com.apollographql.apollo3.ast.validateAsSchema
import com.apollographql.apollo3.ast.withoutBuiltinDefinitions
import com.apollographql.apollo3.compiler.buffer
import okio.buffer
import okio.source
import java.io.File
@OptIn(ApolloExperimental::class)
private class GQLDocumentBuilder(private val introspectionSchema: IntrospectionSchema, filePath: String?) {
private val sourceLocation = SourceLocation(
filePath = filePath,
line = -1,
position = -1
)
fun toGQLDocument(): GQLDocument {
return with(introspectionSchema.__schema) {
GQLDocument(
definitions = types.map {
when (it) {
is IntrospectionSchema.Schema.Type.Union -> it.toGQLUnionTypeDefinition()
is IntrospectionSchema.Schema.Type.Interface -> it.toGQLInterfaceTypeDefinition()
is IntrospectionSchema.Schema.Type.Enum -> it.toGQLEnumTypeDefinition()
is IntrospectionSchema.Schema.Type.Object -> it.toGQLObjectTypeDefinition()
is IntrospectionSchema.Schema.Type.InputObject -> it.toGQLInputObjectTypeDefinition()
is IntrospectionSchema.Schema.Type.Scalar -> it.toGQLScalarTypeDefinition()
}
} + schemaDefinition(),
filePath = sourceLocation.filePath
)
}
}
private fun IntrospectionSchema.Schema.Type.Object.toGQLObjectTypeDefinition(): GQLObjectTypeDefinition {
return GQLObjectTypeDefinition(
sourceLocation = sourceLocation,
description = description,
name = name,
directives = emptyList(),
fields = fields?.map { it.toGQLFieldDefinition() } ?: throw ConversionException("Object '$name' did not define any field"),
implementsInterfaces = findInterfacesImplementedBy(name)
)
}
private fun findInterfacesImplementedBy(name: String): List<String> {
return introspectionSchema.__schema.types.filterIsInstance<IntrospectionSchema.Schema.Type.Interface>()
.filter {
it.possibleTypes?.map { it.name }?.contains(name) == true
}
.map {
it.name
}
}
private fun IntrospectionSchema.Schema.Type.Enum.toGQLEnumTypeDefinition(): GQLEnumTypeDefinition {
return GQLEnumTypeDefinition(
sourceLocation = sourceLocation,
description = description,
name = name,
enumValues = enumValues.map { it.toGQLEnumValueDefinition() },
directives = emptyList()
)
}
private fun IntrospectionSchema.Schema.Type.Enum.Value.toGQLEnumValueDefinition(): GQLEnumValueDefinition {
return GQLEnumValueDefinition(
sourceLocation = sourceLocation,
description = description,
name = name,
directives = makeDirectives(deprecationReason)
)
}
private fun IntrospectionSchema.Schema.Type.Interface.toGQLInterfaceTypeDefinition(): GQLInterfaceTypeDefinition {
return GQLInterfaceTypeDefinition(
sourceLocation = sourceLocation,
name = name,
description = description,
fields = fields?.map { it.toGQLFieldDefinition() } ?: throw ConversionException("interface '$name' did not define any field"),
implementsInterfaces = emptyList(), // TODO
directives = emptyList()
)
}
private fun IntrospectionSchema.Schema.Field.toGQLFieldDefinition(): GQLFieldDefinition {
return GQLFieldDefinition(
sourceLocation = sourceLocation,
name = name,
description = description,
arguments = this.args.map { it.toGQLInputValueDefinition() },
directives = makeDirectives(deprecationReason),
type = type.toGQLType()
)
}
private fun IntrospectionSchema.Schema.Field.Argument.toGQLInputValueDefinition(): GQLInputValueDefinition {
return GQLInputValueDefinition(
sourceLocation = sourceLocation,
name = name,
description = description,
directives = makeDirectives(deprecationReason),
defaultValue = defaultValue.toGQLValue(),
type = type.toGQLType(),
)
}
private fun Any?.toGQLValue(): GQLValue? {
if (this == null) {
// no default value
return null
}
try {
if (this is String) {
return buffer().parseAsGQLValue().valueAssertNoErrors()
}
} catch (e: Exception) {
println("Wrongly encoded default value: $this: ${e.message}")
}
// All the below should theoretically not happen because the spec says defaultValue should be
// a GQLValue encoded as a string
return when {
this is String -> GQLStringValue(value = this)
this is Int -> GQLIntValue(value = this)
this is Long -> GQLIntValue(value = this.toInt())
this is Double -> GQLFloatValue(value = this)
this is Boolean -> GQLBooleanValue(value = this)
this is Map<*, *> -> GQLObjectValue(fields = this.map {
GQLObjectField(name = it.key as String, value = it.value.toGQLValue()!!)
})
this is List<*> -> GQLListValue(values = map { it.toGQLValue()!! })
else -> throw ConversionException("cannot convert $this to a GQLValue")
}
}
fun makeDirectives(deprecationReason: String?): List<GQLDirective> {
if (deprecationReason == null) {
return emptyList()
}
return listOf(
GQLDirective(
name = "deprecated",
arguments = GQLArguments(listOf(
GQLArgument(name = "reason", value = GQLStringValue(value = deprecationReason))
))
)
)
}
private fun IntrospectionSchema.Schema.Type.Union.toGQLUnionTypeDefinition(): GQLUnionTypeDefinition {
return GQLUnionTypeDefinition(
sourceLocation = sourceLocation,
name = name,
description = "",
memberTypes = possibleTypes?.map { it.toGQLNamedType() } ?: throw ConversionException("Union '$name' must have members"),
directives = emptyList(),
)
}
private fun IntrospectionSchema.Schema.TypeRef.toGQLNamedType(): GQLNamedType {
return toGQLType() as? GQLNamedType ?: throw ConversionException("expected a NamedType")
}
private fun IntrospectionSchema.Schema.TypeRef.toGQLType(): GQLType {
return when (this.kind) {
IntrospectionSchema.Schema.Kind.NON_NULL -> GQLNonNullType(
type = ofType?.toGQLType() ?: throw ConversionException("ofType must not be null for non null types")
)
IntrospectionSchema.Schema.Kind.LIST -> GQLListType(
type = ofType?.toGQLType() ?: throw ConversionException("ofType must not be null for list types")
)
else -> GQLNamedType(
name = name!!
)
}
}
private fun IntrospectionSchema.Schema.schemaDefinition(): GQLSchemaDefinition {
val rootOperationTypeDefinitions = mutableListOf<GQLOperationTypeDefinition>()
rootOperationTypeDefinitions.add(
GQLOperationTypeDefinition(
sourceLocation = sourceLocation,
operationType = "query",
namedType = queryType.name
)
)
if (mutationType != null) {
rootOperationTypeDefinitions.add(
GQLOperationTypeDefinition(
sourceLocation = sourceLocation,
operationType = "mutation",
namedType = mutationType.name
)
)
}
if (subscriptionType != null) {
rootOperationTypeDefinitions.add(
GQLOperationTypeDefinition(
sourceLocation = sourceLocation,
operationType = "subscription",
namedType = subscriptionType.name
)
)
}
return GQLSchemaDefinition(
sourceLocation = sourceLocation,
description = "",
directives = emptyList(),
rootOperationTypeDefinitions = rootOperationTypeDefinitions
)
}
private fun IntrospectionSchema.Schema.Type.InputObject.toGQLInputObjectTypeDefinition(): GQLInputObjectTypeDefinition {
return GQLInputObjectTypeDefinition(
sourceLocation = sourceLocation,
description = description,
name = name,
inputFields = inputFields.map { it.toGQLInputValueDefinition() },
directives = emptyList()
)
}
private fun IntrospectionSchema.Schema.InputField.toGQLInputValueDefinition(): GQLInputValueDefinition {
return GQLInputValueDefinition(
sourceLocation = sourceLocation,
description = description,
name = name,
directives = makeDirectives(deprecationReason),
type = type.toGQLType(),
defaultValue = defaultValue.toGQLValue()
)
}
private fun IntrospectionSchema.Schema.Type.Scalar.toGQLScalarTypeDefinition(): GQLScalarTypeDefinition {
return GQLScalarTypeDefinition(
sourceLocation = sourceLocation,
description = description,
name = name,
directives = emptyList()
)
}
}
/**
* Parses the [IntrospectionSchema] into a [GQLDocument]
*
* The returned [GQLDocument] does not contain any of the builtin definitions (scalars, directives, introspection)
*
* See https://spec.graphql.org/draft/#sel-GAHXJHABuCB_Dn6F
*/
@ApolloExperimental
fun IntrospectionSchema.toGQLDocument(filePath: String? = null): GQLDocument = GQLDocumentBuilder(this, filePath)
.toGQLDocument()
/**
* Introspection already contains builtin types like Int, Boolean, __Schema, etc...
*/
.withoutBuiltinDefinitions()
/**
* Transforms the [IntrospectionSchema] into a [Schema] that contains builtin definitions
*
* In the process, the builtin definitions are removed and added again.
*/
@ApolloExperimental
fun IntrospectionSchema.toSchema(): Schema = toGQLDocument().validateAsSchema().valueAssertNoErrors()
/**
* Transforms the given file to a [GQLDocument] without doing validation
*/
@ApolloExperimental
fun File.toSchemaGQLDocument(): GQLDocument {
return if (extension == "json") {
toIntrospectionSchema().toGQLDocument(filePath = path)
} else {
source().buffer().parseAsGQLDocument(filePath = path).valueAssertNoErrors()
}
}
@ApolloExperimental
fun File.toSchema(): Schema = toSchemaGQLDocument().validateAsSchema().valueAssertNoErrors() | mit | 7ecadf578b469b4199cf4082a324a14a | 36.829653 | 134 | 0.712868 | 4.732044 | false | false | false | false |
DSteve595/Put.io | app/src/main/java/com/stevenschoen/putionew/transfers/add/BaseFragment.kt | 1 | 1295 | package com.stevenschoen.putionew.transfers.add
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.Fragment
abstract class BaseFragment(val destinationPickerContainerId: Int) : AppCompatDialogFragment() {
val destinationPickerFragment: DestinationPickerFragment?
get() = childFragmentManager.findFragmentByTag(FRAGTAG_DESTINATION_PICKER) as DestinationPickerFragment?
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val addTransferActivity = activity as AddTransferActivity
if (!addTransferActivity.hasPrechosenDestinationFolder) {
if (childFragmentManager.findFragmentByTag(FRAGTAG_DESTINATION_PICKER) == null) {
val fragment = Fragment.instantiate(addTransferActivity, DestinationPickerFragment::class.java.name)
childFragmentManager.beginTransaction()
.add(destinationPickerContainerId, fragment, FRAGTAG_DESTINATION_PICKER)
.commitNow()
}
} else {
val holderView = view.findViewById<View>(destinationPickerContainerId)
holderView.visibility = View.GONE
}
}
companion object {
const val FRAGTAG_DESTINATION_PICKER = "dest_picker"
}
}
| mit | 2199246f14be8acbe01e5c59a3ec918b | 38.242424 | 108 | 0.772973 | 4.961686 | false | false | false | false |
androidx/androidx | room/room-testing/src/main/java/androidx/room/testing/MigrationTestHelper.kt | 3 | 27955 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.testing
import android.annotation.SuppressLint
import android.app.Instrumentation
import android.content.Context
import android.util.Log
import androidx.arch.core.executor.ArchTaskExecutor
import androidx.room.DatabaseConfiguration
import androidx.room.Room
import androidx.room.Room.getGeneratedImplementation
import androidx.room.RoomDatabase
import androidx.room.RoomOpenHelper
import androidx.room.migration.AutoMigrationSpec
import androidx.room.migration.Migration
import androidx.room.migration.bundle.DatabaseBundle
import androidx.room.migration.bundle.DatabaseViewBundle
import androidx.room.migration.bundle.EntityBundle
import androidx.room.migration.bundle.FieldBundle
import androidx.room.migration.bundle.ForeignKeyBundle
import androidx.room.migration.bundle.FtsEntityBundle
import androidx.room.migration.bundle.IndexBundle
import androidx.room.migration.bundle.SchemaBundle
import androidx.room.migration.bundle.SchemaBundle.Companion.deserialize
import androidx.room.util.FtsTableInfo
import androidx.room.util.TableInfo
import androidx.room.util.ViewInfo
import androidx.room.util.useCursor
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.sqlite.db.SupportSQLiteOpenHelper
import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.lang.ref.WeakReference
import org.junit.rules.TestWatcher
import org.junit.runner.Description
/**
* A class that can be used in your Instrumentation tests that can create the database in an
* older schema.
*
* You must copy the schema json files (created by passing `room.schemaLocation` argument
* into the annotation processor) into your test assets and pass in the path for that folder into
* the constructor. This class will read the folder and extract the schemas from there.
*
* ```
* android {
* defaultConfig {
* javaCompileOptions {
* annotationProcessorOptions {
* arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
* }
* }
* }
* sourceSets {
* androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
* }
* }
* ```
*/
open class MigrationTestHelper : TestWatcher {
private val assetsFolder: String
private val openFactory: SupportSQLiteOpenHelper.Factory
private val managedDatabases = mutableListOf<WeakReference<SupportSQLiteDatabase>>()
private val managedRoomDatabases = mutableListOf<WeakReference<RoomDatabase>>()
private var testStarted = false
private val instrumentation: Instrumentation
private val specs: List<AutoMigrationSpec>
private val databaseClass: Class<out RoomDatabase>?
internal lateinit var databaseConfiguration: DatabaseConfiguration
/**
* Creates a new migration helper. It uses the Instrumentation context to load the schema
* (falls back to the app resources) and the target context to create the database.
*
* @param instrumentation The instrumentation instance.
* @param assetsFolder The asset folder in the assets directory.
* @param openFactory factory for creating an [SupportSQLiteOpenHelper]
*/
@Deprecated(
"""
Cannot be used to run migration tests involving [AutoMigration].
To test [AutoMigration], you must use [MigrationTestHelper(Instrumentation, Class, List,
SupportSQLiteOpenHelper.Factory)] for tests containing a
[androidx.room.ProvidedAutoMigrationSpec], or use
[MigrationTestHelper(Instrumentation, Class, List)] otherwise.
"""
)
@JvmOverloads
constructor(
instrumentation: Instrumentation,
assetsFolder: String,
openFactory: SupportSQLiteOpenHelper.Factory = FrameworkSQLiteOpenHelperFactory()
) {
this.instrumentation = instrumentation
this.assetsFolder = assetsFolder
this.openFactory = openFactory
databaseClass = null
specs = mutableListOf()
}
/**
* Creates a new migration helper. It uses the Instrumentation context to load the schema
* (falls back to the app resources) and the target context to create the database.
*
* An instance of a class annotated with [androidx.room.ProvidedAutoMigrationSpec] has
* to be provided to Room using this constructor. MigrationTestHelper will map auto migration
* spec classes to their provided instances before running and validating the Migrations.
*
* @param instrumentation The instrumentation instance.
* @param databaseClass The Database class to be tested.
*/
constructor(
instrumentation: Instrumentation,
databaseClass: Class<out RoomDatabase>
) : this(
instrumentation, databaseClass, emptyList(), FrameworkSQLiteOpenHelperFactory()
)
/**
* Creates a new migration helper. It uses the Instrumentation context to load the schema
* (falls back to the app resources) and the target context to create the database.
*
*
* An instance of a class annotated with [androidx.room.ProvidedAutoMigrationSpec] has
* to be provided to Room using this constructor. MigrationTestHelper will map auto migration
* spec classes to their provided instances before running and validating the Migrations.
*
* @param instrumentation The instrumentation instance.
* @param databaseClass The Database class to be tested.
* @param specs The list of available auto migration specs that will be provided to
* Room at runtime.
* @param openFactory factory for creating an [SupportSQLiteOpenHelper]
*/
@JvmOverloads
constructor(
instrumentation: Instrumentation,
databaseClass: Class<out RoomDatabase>,
specs: List<AutoMigrationSpec>,
openFactory: SupportSQLiteOpenHelper.Factory = FrameworkSQLiteOpenHelperFactory()
) {
this.assetsFolder = checkNotNull(databaseClass.canonicalName).let {
if (it.endsWith("/")) {
it.substring(0, databaseClass.canonicalName!!.length - 1)
} else {
it
}
}
this.instrumentation = instrumentation
this.openFactory = openFactory
this.databaseClass = databaseClass
this.specs = specs
}
override fun starting(description: Description?) {
super.starting(description)
testStarted = true
}
/**
* Creates the database in the given version.
* If the database file already exists, it tries to delete it first. If delete fails, throws
* an exception.
*
* @param name The name of the database.
* @param version The version in which the database should be created.
* @return A database connection which has the schema in the requested version.
*/
@SuppressLint("RestrictedApi")
@Throws(IOException::class)
open fun createDatabase(name: String, version: Int): SupportSQLiteDatabase {
val dbPath: File = instrumentation.targetContext.getDatabasePath(name)
if (dbPath.exists()) {
Log.d(TAG, "deleting database file $name")
check(dbPath.delete()) {
"There is a database file and I could not delete" +
" it. Make sure you don't have any open connections to that database" +
" before calling this method."
}
}
val schemaBundle = loadSchema(version)
val container: RoomDatabase.MigrationContainer = RoomDatabase.MigrationContainer()
val configuration = DatabaseConfiguration(
context = instrumentation.targetContext,
name = name,
sqliteOpenHelperFactory = openFactory,
migrationContainer = container,
callbacks = null,
allowMainThreadQueries = true,
journalMode = RoomDatabase.JournalMode.TRUNCATE,
queryExecutor = ArchTaskExecutor.getIOThreadExecutor(),
transactionExecutor = ArchTaskExecutor.getIOThreadExecutor(),
multiInstanceInvalidationServiceIntent = null,
requireMigration = true,
allowDestructiveMigrationOnDowngrade = false,
migrationNotRequiredFrom = emptySet(),
copyFromAssetPath = null,
copyFromFile = null,
copyFromInputStream = null,
prepackagedDatabaseCallback = null,
typeConverters = emptyList(),
autoMigrationSpecs = emptyList()
)
val roomOpenHelper = RoomOpenHelper(
configuration = configuration,
delegate = CreatingDelegate(schemaBundle.database),
identityHash = schemaBundle.database.identityHash,
// we pass the same hash twice since an old schema does not necessarily have
// a legacy hash and we would not even persist it.
legacyHash = schemaBundle.database.identityHash
)
return openDatabase(name, roomOpenHelper)
}
/**
* Runs the given set of migrations on the provided database.
*
* It uses the same algorithm that Room uses to choose migrations so the migrations instances
* that are provided to this method must be sufficient to bring the database from current
* version to the desired version.
*
* After the migration, the method validates the database schema to ensure that migration
* result matches the expected schema. Handling of dropped tables depends on the
* `validateDroppedTables` argument. If set to true, the verification will fail if it
* finds a table that is not registered in the Database. If set to false, extra tables in the
* database will be ignored (this is the runtime library behavior).
*
* @param name The database name. You must first create this database via
* [createDatabase].
* @param version The final version after applying the migrations.
* @param validateDroppedTables If set to true, validation will fail if the database has
* unknown tables.
* @param migrations The list of available migrations.
* @throws IllegalArgumentException If the schema validation fails.
*/
@SuppressLint("RestrictedApi")
open fun runMigrationsAndValidate(
name: String,
version: Int,
validateDroppedTables: Boolean,
vararg migrations: Migration
): SupportSQLiteDatabase {
val dbPath = instrumentation.targetContext.getDatabasePath(name)
check(dbPath.exists()) {
"Cannot find the database file for $name. " +
"Before calling runMigrations, you must first create the database via " +
"createDatabase."
}
val schemaBundle = loadSchema(version)
val container = RoomDatabase.MigrationContainer()
container.addMigrations(*migrations)
val autoMigrations = getAutoMigrations(specs)
autoMigrations.forEach { autoMigration ->
val migrationExists = container.contains(
autoMigration.startVersion,
autoMigration.endVersion
)
if (!migrationExists) {
container.addMigrations(autoMigration)
}
}
databaseConfiguration = DatabaseConfiguration(
context = instrumentation.targetContext,
name = name,
sqliteOpenHelperFactory = openFactory,
migrationContainer = container,
callbacks = null,
allowMainThreadQueries = true,
journalMode = RoomDatabase.JournalMode.TRUNCATE,
queryExecutor = ArchTaskExecutor.getIOThreadExecutor(),
transactionExecutor = ArchTaskExecutor.getIOThreadExecutor(),
multiInstanceInvalidationServiceIntent = null,
requireMigration = true,
allowDestructiveMigrationOnDowngrade = false,
migrationNotRequiredFrom = emptySet(),
copyFromAssetPath = null,
copyFromFile = null,
copyFromInputStream = null,
prepackagedDatabaseCallback = null,
typeConverters = emptyList(),
autoMigrationSpecs = emptyList()
)
val roomOpenHelper = RoomOpenHelper(
configuration = databaseConfiguration,
delegate = MigratingDelegate(
databaseBundle = schemaBundle.database,
// we pass the same hash twice since an old schema does not necessarily have
// a legacy hash and we would not even persist it.
mVerifyDroppedTables = validateDroppedTables
),
identityHash = schemaBundle.database.identityHash,
legacyHash = schemaBundle.database.identityHash
)
return openDatabase(name, roomOpenHelper)
}
/**
* Returns a list of [Migration] of a database that has been generated using
* [androidx.room.AutoMigration].
*/
private fun getAutoMigrations(userProvidedSpecs: List<AutoMigrationSpec>): List<Migration> {
if (databaseClass == null) {
return if (userProvidedSpecs.isEmpty()) {
// TODO: Detect that there are auto migrations to test when a deprecated
// constructor is used.
Log.e(
TAG, "If you have any AutoMigrations in your implementation, you must use " +
"a non-deprecated MigrationTestHelper constructor to provide the " +
"Database class in order to test them. If you do not have any " +
"AutoMigrations to test, you may ignore this warning."
)
mutableListOf()
} else {
error(
"You must provide the database class in the " +
"MigrationTestHelper constructor in order to test auto migrations."
)
}
}
val db: RoomDatabase = getGeneratedImplementation(
databaseClass, "_Impl"
)
val requiredAutoMigrationSpecs = db.getRequiredAutoMigrationSpecs()
return db.getAutoMigrations(
createAutoMigrationSpecMap(requiredAutoMigrationSpecs, userProvidedSpecs)
)
}
/**
* Maps auto migration spec classes to their provided instance.
*/
private fun createAutoMigrationSpecMap(
requiredAutoMigrationSpecs: Set<Class<out AutoMigrationSpec>>,
userProvidedSpecs: List<AutoMigrationSpec>
): Map<Class<out AutoMigrationSpec>, AutoMigrationSpec> {
if (requiredAutoMigrationSpecs.isEmpty()) {
return emptyMap()
}
return buildMap {
requiredAutoMigrationSpecs.forEach { spec ->
val match = userProvidedSpecs.firstOrNull { provided ->
spec.isAssignableFrom(provided.javaClass)
}
require(match != null) {
"A required auto migration spec (${spec.canonicalName}) has not been provided."
}
put(spec, match)
}
}
}
private fun openDatabase(name: String, roomOpenHelper: RoomOpenHelper): SupportSQLiteDatabase {
val config = SupportSQLiteOpenHelper.Configuration.builder(instrumentation.targetContext)
.callback(roomOpenHelper)
.name(name)
.build()
val db = openFactory.create(config).writableDatabase
managedDatabases.add(WeakReference(db))
return db
}
override fun finished(description: Description?) {
super.finished(description)
managedDatabases.forEach { dbRef ->
val db = dbRef.get()
if (db != null && db.isOpen) {
try {
db.close()
} catch (ignored: Throwable) {
}
}
}
managedRoomDatabases.forEach { dbRef ->
val roomDatabase = dbRef.get()
roomDatabase?.close()
}
}
/**
* Registers a database connection to be automatically closed when the test finishes.
*
* This only works if `MigrationTestHelper` is registered as a Junit test rule via
* [Rule][org.junit.Rule] annotation.
*
* @param db The database connection that should be closed after the test finishes.
*/
open fun closeWhenFinished(db: SupportSQLiteDatabase) {
check(testStarted) {
"You cannot register a database to be closed before" +
" the test starts. Maybe you forgot to annotate MigrationTestHelper as a" +
" test rule? (@Rule)"
}
managedDatabases.add(WeakReference(db))
}
/**
* Registers a database connection to be automatically closed when the test finishes.
*
* This only works if `MigrationTestHelper` is registered as a Junit test rule via
* [Rule][org.junit.Rule] annotation.
*
* @param db The RoomDatabase instance which holds the database.
*/
open fun closeWhenFinished(db: RoomDatabase) {
check(testStarted) {
"You cannot register a database to be closed before" +
" the test starts. Maybe you forgot to annotate MigrationTestHelper as a" +
" test rule? (@Rule)"
}
managedRoomDatabases.add(WeakReference(db))
}
private fun loadSchema(version: Int): SchemaBundle {
return try {
loadSchema(instrumentation.context, version)
} catch (testAssetsIOExceptions: FileNotFoundException) {
Log.w(
TAG, "Could not find the schema file in the test assets. Checking the" +
" application assets"
)
try {
loadSchema(instrumentation.targetContext, version)
} catch (appAssetsException: FileNotFoundException) {
// throw the test assets exception instead
throw FileNotFoundException(
"Cannot find the schema file in the assets folder. " +
"Make sure to include the exported json schemas in your test assert " +
"inputs. See " +
"https://developer.android.com/training/data-storage/room/" +
"migrating-db-versions#export-schema for details. Missing file: " +
testAssetsIOExceptions.message
)
}
}
}
private fun loadSchema(context: Context, version: Int): SchemaBundle {
val input = context.assets.open("$assetsFolder/$version.json")
return deserialize(input)
}
internal class MigratingDelegate(
databaseBundle: DatabaseBundle,
private val mVerifyDroppedTables: Boolean
) : RoomOpenHelperDelegate(databaseBundle) {
override fun createAllTables(db: SupportSQLiteDatabase) {
throw UnsupportedOperationException(
"Was expecting to migrate but received create." +
"Make sure you have created the database first."
)
}
override fun onValidateSchema(
db: SupportSQLiteDatabase
): RoomOpenHelper.ValidationResult {
val tables = mDatabaseBundle.entitiesByTableName
tables.values.forEach { entity ->
if (entity is FtsEntityBundle) {
val expected = toFtsTableInfo(entity)
val found = FtsTableInfo.read(db, entity.tableName)
if (expected != found) {
return RoomOpenHelper.ValidationResult(
false,
"""
${expected.name}
Expected: $expected
Found: $found
""".trimIndent()
)
}
} else {
val expected = toTableInfo(entity)
val found = TableInfo.read(db, entity.tableName)
if (expected != found) {
return RoomOpenHelper.ValidationResult(
false,
"""
${expected.name}
Expected: $expected
found: $found
""".trimIndent()
)
}
}
}
mDatabaseBundle.views.forEach { view ->
val expected = toViewInfo(view)
val found = ViewInfo.read(db, view.viewName)
if (expected != found) {
return RoomOpenHelper.ValidationResult(
false,
"""
${expected.name}
Expected: $expected
Found: $found
""".trimIndent()
)
}
}
if (mVerifyDroppedTables) {
// now ensure tables that should be removed are removed.
val expectedTables = buildSet {
tables.values.forEach { entity ->
add(entity.tableName)
if (entity is FtsEntityBundle) {
addAll(entity.shadowTableNames)
}
}
}
db.query(
"SELECT name FROM sqlite_master WHERE type='table'" +
" AND name NOT IN(?, ?, ?)",
arrayOf(
Room.MASTER_TABLE_NAME, "android_metadata",
"sqlite_sequence"
)
).useCursor { cursor ->
while (cursor.moveToNext()) {
val tableName = cursor.getString(0)
if (!expectedTables.contains(tableName)) {
return RoomOpenHelper.ValidationResult(
false, "Unexpected table $tableName"
)
}
}
}
}
return RoomOpenHelper.ValidationResult(true, null)
}
}
internal class CreatingDelegate(
databaseBundle: DatabaseBundle
) : RoomOpenHelperDelegate(databaseBundle) {
override fun createAllTables(db: SupportSQLiteDatabase) {
mDatabaseBundle.buildCreateQueries().forEach { query ->
db.execSQL(query)
}
}
override fun onValidateSchema(
db: SupportSQLiteDatabase
): RoomOpenHelper.ValidationResult {
throw UnsupportedOperationException(
"This open helper just creates the database but it received a migration request."
)
}
}
internal abstract class RoomOpenHelperDelegate(
val mDatabaseBundle: DatabaseBundle
) : RoomOpenHelper.Delegate(
mDatabaseBundle.version
) {
override fun dropAllTables(db: SupportSQLiteDatabase) {
throw UnsupportedOperationException("cannot drop all tables in the test")
}
override fun onCreate(db: SupportSQLiteDatabase) {}
override fun onOpen(db: SupportSQLiteDatabase) {}
}
internal companion object {
private const val TAG = "MigrationTestHelper"
@JvmStatic
internal fun toTableInfo(entityBundle: EntityBundle): TableInfo {
return TableInfo(
name = entityBundle.tableName,
columns = toColumnMap(entityBundle),
foreignKeys = toForeignKeys(entityBundle.foreignKeys),
indices = toIndices(entityBundle.indices)
)
}
@JvmStatic
internal fun toFtsTableInfo(ftsEntityBundle: FtsEntityBundle): FtsTableInfo {
return FtsTableInfo(
name = ftsEntityBundle.tableName,
columns = toColumnNamesSet(ftsEntityBundle),
createSql = ftsEntityBundle.createSql
)
}
@JvmStatic
internal fun toViewInfo(viewBundle: DatabaseViewBundle): ViewInfo {
return ViewInfo(
name = viewBundle.viewName,
sql = viewBundle.createView()
)
}
@JvmStatic
internal fun toIndices(indices: List<IndexBundle>?): Set<TableInfo.Index> {
if (indices == null) {
return emptySet()
}
val result = indices.map { bundle ->
TableInfo.Index(
name = bundle.name,
unique = bundle.isUnique,
columns = bundle.columnNames!!,
orders = bundle.orders!!
)
}.toSet()
return result
}
@JvmStatic
internal fun toForeignKeys(
bundles: List<ForeignKeyBundle>?
): Set<TableInfo.ForeignKey> {
if (bundles == null) {
return emptySet()
}
val result = bundles.map { bundle ->
TableInfo.ForeignKey(
referenceTable = bundle.table,
onDelete = bundle.onDelete,
onUpdate = bundle.onUpdate,
columnNames = bundle.columns,
referenceColumnNames = bundle.referencedColumns
)
}.toSet()
return result
}
@JvmStatic
internal fun toColumnNamesSet(entity: EntityBundle): Set<String> {
val result = entity.fields.map { field ->
field.columnName
}.toSet()
return result
}
@JvmStatic
internal fun toColumnMap(entity: EntityBundle): Map<String, TableInfo.Column> {
val result: MutableMap<String, TableInfo.Column> = HashMap()
entity.fields.associateBy { bundle ->
val column = toColumn(entity, bundle)
result[column.name] = column
}
return result
}
@JvmStatic
internal fun toColumn(entity: EntityBundle, field: FieldBundle): TableInfo.Column {
return TableInfo.Column(
name = field.columnName,
type = field.affinity,
notNull = field.isNonNull,
primaryKeyPosition = findPrimaryKeyPosition(entity, field),
defaultValue = field.defaultValue,
createdFrom = TableInfo.CREATED_FROM_ENTITY
)
}
@JvmStatic
internal fun findPrimaryKeyPosition(entity: EntityBundle, field: FieldBundle): Int {
return entity.primaryKey.columnNames.indexOfFirst { columnName ->
field.columnName.equals(columnName, ignoreCase = true)
} + 1 // Shift by 1 to get primary key position
}
}
} | apache-2.0 | 4adfa38ea30ca598a6af512da037d1e7 | 40.172312 | 100 | 0.604436 | 5.558759 | false | true | false | false |
androidx/androidx | tv/tv-foundation/src/main/java/androidx/tv/foundation/lazy/grid/LazyGridScrollPosition.kt | 3 | 5587 | /*
* 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.tv.foundation.lazy.grid
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.Snapshot
/**
* Contains the current scroll position represented by the first visible item index and the first
* visible item scroll offset.
*/
@Suppress("IllegalExperimentalApiUsage") // TODO (b/233188423): Address before moving to beta
@OptIn(ExperimentalFoundationApi::class)
internal class LazyGridScrollPosition(
initialIndex: Int = 0,
initialScrollOffset: Int = 0
) {
var index by mutableStateOf(ItemIndex(initialIndex))
private set
var scrollOffset by mutableStateOf(initialScrollOffset)
private set
private var hadFirstNotEmptyLayout = false
/** The last known key of the first item at [index] line. */
private var lastKnownFirstItemKey: Any? = null
/**
* Updates the current scroll position based on the results of the last measurement.
*/
fun updateFromMeasureResult(measureResult: TvLazyGridMeasureResult) {
lastKnownFirstItemKey = measureResult.firstVisibleLine?.items?.firstOrNull()?.key
// we ignore the index and offset from measureResult until we get at least one
// measurement with real items. otherwise the initial index and scroll passed to the
// state would be lost and overridden with zeros.
if (hadFirstNotEmptyLayout || measureResult.totalItemsCount > 0) {
hadFirstNotEmptyLayout = true
val scrollOffset = measureResult.firstVisibleLineScrollOffset
check(scrollOffset >= 0f) { "scrollOffset should be non-negative ($scrollOffset)" }
Snapshot.withoutReadObservation {
update(
ItemIndex(
measureResult.firstVisibleLine?.items?.firstOrNull()?.index?.value ?: 0
),
scrollOffset
)
}
}
}
/**
* Updates the scroll position - the passed values will be used as a start position for
* composing the items during the next measure pass and will be updated by the real
* position calculated during the measurement. This means that there is guarantee that
* exactly this index and offset will be applied as it is possible that:
* a) there will be no item at this index in reality
* b) item at this index will be smaller than the asked scrollOffset, which means we would
* switch to the next item
* c) there will be not enough items to fill the viewport after the requested index, so we
* would have to compose few elements before the asked index, changing the first visible item.
*/
fun requestPosition(index: ItemIndex, scrollOffset: Int) {
update(index, scrollOffset)
// clear the stored key as we have a direct request to scroll to [index] position and the
// next [checkIfFirstVisibleItemWasMoved] shouldn't override this.
lastKnownFirstItemKey = null
}
/**
* In addition to keeping the first visible item index we also store the key of this item.
* When the user provided custom keys for the items this mechanism allows us to detect when
* there were items added or removed before our current first visible item and keep this item
* as the first visible one even given that its index has been changed.
*/
fun updateScrollPositionIfTheFirstItemWasMoved(itemProvider: LazyGridItemProvider) {
Snapshot.withoutReadObservation {
update(
ItemIndex(itemProvider.findIndexByKey(lastKnownFirstItemKey, index.value)),
scrollOffset
)
}
}
private fun update(index: ItemIndex, scrollOffset: Int) {
require(index.value >= 0f) { "Index should be non-negative (${index.value})" }
if (index != this.index) {
this.index = index
}
if (scrollOffset != this.scrollOffset) {
this.scrollOffset = scrollOffset
}
}
}
/**
* Finds a position of the item with the given key in the lists. This logic allows us to
* detect when there were items added or removed before our current first item.
*/
@OptIn(ExperimentalFoundationApi::class)
internal fun LazyGridItemProvider.findIndexByKey(
key: Any?,
lastKnownIndex: Int,
): Int {
if (key == null) {
// there were no real item during the previous measure
return lastKnownIndex
}
if (lastKnownIndex < itemCount &&
key == getKey(lastKnownIndex)
) {
// this item is still at the same index
return lastKnownIndex
}
val newIndex = keyToIndexMap[key]
if (newIndex != null) {
return newIndex
}
// fallback to the previous index if we don't know the new index of the item
return lastKnownIndex
}
| apache-2.0 | e32ea923911ac70e6a3eb7c89312f616 | 39.485507 | 98 | 0.686773 | 4.900877 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/NonModalCommitWorkflowHandler.kt | 1 | 23775 | // 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.vcs.commit
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationType
import com.intellij.notification.SingletonNotificationManager
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.EDT
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.DumbService.DumbModeListener
import com.intellij.openapi.project.DumbService.isDumb
import com.intellij.openapi.roots.ex.ProjectRootManagerEx
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil.capitalize
import com.intellij.openapi.util.text.StringUtil.toLowerCase
import com.intellij.openapi.vcs.*
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.CommitExecutor
import com.intellij.openapi.vcs.changes.actions.DefaultCommitExecutorAction
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.Companion.LOCAL_CHANGES
import com.intellij.openapi.vcs.checkin.*
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.containers.nullize
import com.intellij.vcs.commit.AbstractCommitWorkflow.Companion.getCommitExecutors
import kotlinx.coroutines.*
import org.jetbrains.annotations.Nls
import java.lang.Runnable
import kotlin.properties.Delegates.observable
private val LOG = logger<NonModalCommitWorkflowHandler<*, *>>()
abstract class NonModalCommitWorkflowHandler<W : NonModalCommitWorkflow, U : NonModalCommitWorkflowUi> :
AbstractCommitWorkflowHandler<W, U>() {
abstract override val amendCommitHandler: NonModalAmendCommitHandler
private var areCommitOptionsCreated = false
private val coroutineScope =
CoroutineScope(CoroutineName("commit workflow") + Dispatchers.EDT + SupervisorJob())
private var isCommitChecksResultUpToDate: RecentCommitChecks by observable(RecentCommitChecks.UNKNOWN) { _, oldValue, newValue ->
if (oldValue == newValue) return@observable
updateDefaultCommitActionName()
}
private val checkinErrorNotifications = SingletonNotificationManager(VcsNotifier.IMPORTANT_ERROR_NOTIFICATION.displayId,
NotificationType.ERROR)
private val postCommitChecksHandler: PostCommitChecksHandler get() = PostCommitChecksHandler.getInstance(project)
private var pendingPostCommitChecks: PendingPostCommitChecks? = null
protected fun setupCommitHandlersTracking() {
CheckinHandlerFactory.EP_NAME.addChangeListener(Runnable { commitHandlersChanged() }, this)
VcsCheckinHandlerFactory.EP_NAME.addChangeListener(Runnable { commitHandlersChanged() }, this)
}
private fun commitHandlersChanged() {
if (workflow.isExecuting) return
commitOptions.saveState()
disposeCommitOptions()
initCommitHandlers()
}
override fun vcsesChanged() {
initCommitHandlers()
workflow.initCommitExecutors(getCommitExecutors(project, workflow.vcses) + RunCommitChecksExecutor)
updateDefaultCommitActionEnabled()
updateDefaultCommitActionName()
ui.setPrimaryCommitActions(createPrimaryCommitActions())
ui.setCustomCommitActions(createCommitExecutorActions())
}
protected fun setupDumbModeTracking() {
if (isDumb(project)) ui.commitProgressUi.isDumbMode = true
project.messageBus.connect(this).subscribe(DumbService.DUMB_MODE, object : DumbModeListener {
override fun enteredDumbMode() {
ui.commitProgressUi.isDumbMode = true
}
override fun exitDumbMode() {
ui.commitProgressUi.isDumbMode = false
}
})
}
override fun executionStarted() = updateDefaultCommitActionEnabled()
override fun executionEnded() = updateDefaultCommitActionEnabled()
override fun updateDefaultCommitActionName() {
val isAmend = amendCommitHandler.isAmendCommitMode
val isSkipCommitChecks = willSkipCommitChecks()
ui.defaultCommitActionName = getDefaultCommitActionName(workflow.vcses, isAmend, isSkipCommitChecks)
}
private fun getCommitActionTextForNotification(
executor: CommitExecutor?,
isSkipCommitChecks: Boolean
): @Nls(capitalization = Nls.Capitalization.Sentence) String {
val isAmend = amendCommitHandler.isAmendCommitMode
val actionText: @Nls String = getActionTextWithoutEllipsis(workflow.vcses, executor, isAmend, isSkipCommitChecks)
return capitalize(toLowerCase(actionText))
}
fun updateDefaultCommitActionEnabled() {
ui.isDefaultCommitActionEnabled = isReady()
}
protected open fun isReady() = workflow.vcses.isNotEmpty() && !workflow.isExecuting && !amendCommitHandler.isLoading
override fun isExecutorEnabled(executor: CommitExecutor): Boolean = super.isExecutorEnabled(executor) && isReady()
private fun createPrimaryCommitActions(): List<AnAction> {
val group = ActionManager.getInstance().getAction(VcsActions.PRIMARY_COMMIT_EXECUTORS_GROUP) as ActionGroup
return group.getChildren(null).toList()
}
private fun createCommitExecutorActions(): List<AnAction> {
val group = ActionManager.getInstance().getAction(VcsActions.COMMIT_EXECUTORS_GROUP) as ActionGroup
val executors = workflow.commitExecutors.filter { it.useDefaultAction() }
return group.getChildren(null).toList() +
executors.map { DefaultCommitExecutorAction(it) }
}
override fun checkCommit(sessionInfo: CommitSessionInfo): Boolean {
val superCheckResult = super.checkCommit(sessionInfo)
val executorWithoutChangesAllowed = sessionInfo.executor?.areChangesRequired() == false
ui.commitProgressUi.isEmptyChanges = !amendCommitHandler.isAmendWithoutChangesAllowed() && !executorWithoutChangesAllowed && isCommitEmpty()
ui.commitProgressUi.isEmptyMessage = getCommitMessage().isBlank()
return superCheckResult &&
!ui.commitProgressUi.isEmptyChanges &&
!ui.commitProgressUi.isEmptyMessage
}
/**
* Subscribe to VFS and documents changes to reset commit checks results
*/
protected fun setupCommitChecksResultTracking() {
fun areFilesAffectsCommitChecksResult(files: Collection<VirtualFile>): Boolean {
val vcsManager = ProjectLevelVcsManager.getInstance(project)
val filesFromVcs = files.filter { vcsManager.getVcsFor(it) != null }.nullize() ?: return false
val changeListManager = ChangeListManager.getInstance(project)
val fileIndex = ProjectRootManagerEx.getInstanceEx(project).fileIndex
return filesFromVcs.any {
fileIndex.isInContent(it) && changeListManager.getStatus(it) != FileStatus.IGNORED
}
}
// reset commit checks on VFS updates
project.messageBus.connect(this).subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: MutableList<out VFileEvent>) {
if (isCommitChecksResultUpToDate == RecentCommitChecks.UNKNOWN) {
return
}
val updatedFiles = events.mapNotNull { it.file }
if (areFilesAffectsCommitChecksResult(updatedFiles)) {
resetCommitChecksResult()
}
}
})
// reset commit checks on documents modification (e.g. user typed in the editor)
EditorFactory.getInstance().eventMulticaster.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
if (isCommitChecksResultUpToDate == RecentCommitChecks.UNKNOWN) {
return
}
val file = FileDocumentManager.getInstance().getFile(event.document)
if (file != null && areFilesAffectsCommitChecksResult(listOf(file))) {
resetCommitChecksResult()
}
}
}, this)
}
private fun willSkipCommitChecks() = isCommitChecksResultUpToDate == RecentCommitChecks.EARLY_FAILED ||
isCommitChecksResultUpToDate == RecentCommitChecks.MODIFICATIONS_FAILED ||
isCommitChecksResultUpToDate == RecentCommitChecks.POST_FAILED
private fun willSkipEarlyCommitChecks() = isCommitChecksResultUpToDate == RecentCommitChecks.EARLY_FAILED ||
isCommitChecksResultUpToDate == RecentCommitChecks.MODIFICATIONS_FAILED ||
isCommitChecksResultUpToDate == RecentCommitChecks.POST_FAILED
private fun willSkipModificationCommitChecks() = isCommitChecksResultUpToDate == RecentCommitChecks.MODIFICATIONS_FAILED ||
isCommitChecksResultUpToDate == RecentCommitChecks.POST_FAILED
private fun willSkipLateCommitChecks() = isCommitChecksResultUpToDate == RecentCommitChecks.POST_FAILED
private fun willSkipPostCommitChecks() = isCommitChecksResultUpToDate == RecentCommitChecks.POST_FAILED
protected fun resetCommitChecksResult() {
isCommitChecksResultUpToDate = RecentCommitChecks.UNKNOWN
hideCommitChecksFailureNotification()
}
override fun beforeCommitChecksStarted(sessionInfo: CommitSessionInfo) {
super.beforeCommitChecksStarted(sessionInfo)
hideCommitChecksFailureNotification()
}
override fun beforeCommitChecksEnded(sessionInfo: CommitSessionInfo, result: CommitChecksResult) {
hideCommitChecksFailureNotification()
super.beforeCommitChecksEnded(sessionInfo, result)
if (result.shouldCommit) {
ui.commitProgressUi.clearCommitCheckFailures()
}
if (result is CommitChecksResult.Failed ||
result is CommitChecksResult.ExecutionError) {
val executor = sessionInfo.executor
val failures = ui.commitProgressUi.getCommitCheckFailures()
val commitActionText = getCommitActionTextForNotification(executor, false)
val commitAnywayActionText = getCommitActionTextForNotification(executor, true)
val title = message("commit.checks.failed.notification.title", commitActionText)
val description = getCommitCheckFailureDescription(failures)
checkinErrorNotifications.notify(title, description, project) {
it.setDisplayId(VcsNotificationIdsHolder.COMMIT_CHECKS_FAILED)
it.addAction(
NotificationAction.createExpiring(commitAnywayActionText) { _, _ ->
if (!workflow.isExecuting) {
executorCalled(executor)
}
})
appendShowDetailsNotificationActions(it, failures)
}
}
if (result is CommitChecksResult.OnlyChecks && !result.checksPassed) {
val failures = ui.commitProgressUi.getCommitCheckFailures()
val commitActionText = getCommitActionTextForNotification(null, false)
val title = message("commit.checks.failed.notification.title", commitActionText)
val description = getCommitCheckFailureDescription(failures)
checkinErrorNotifications.notify(title, description, project) {
it.setDisplayId(VcsNotificationIdsHolder.COMMIT_CHECKS_ONLY_FAILED)
appendShowDetailsNotificationActions(it, failures)
}
}
}
private fun getCommitCheckFailureDescription(failures: List<CommitCheckFailure>): @NlsContexts.NotificationContent String {
return failures.filterIsInstance<CommitCheckFailure.WithDescription>().joinToString("<br>") { it.text }
}
private fun appendShowDetailsNotificationActions(notification: Notification, failures: List<CommitCheckFailure>) {
for (failure in failures.filterIsInstance<CommitCheckFailure.WithDetails>()) {
notification.addAction(NotificationAction.create(failure.viewDetailsActionText) { _, _ -> failure.viewDetails() })
}
val hasGenericFailure = failures.any { it !is CommitCheckFailure.WithDetails }
if (hasGenericFailure) {
notification.addAction(NotificationAction.create(message("commit.checks.failed.notification.show.details.action")) { _, _ ->
showCommitCheckFailuresPanel()
})
}
}
private fun showCommitCheckFailuresPanel() {
val toolWindow = ChangesViewContentManager.getToolWindowFor(project, LOCAL_CHANGES)
toolWindow?.activate {
ChangesViewContentManager.getInstance(project).selectContent(LOCAL_CHANGES)
}
}
override fun doExecuteSession(sessionInfo: CommitSessionInfo, commitInfo: DynamicCommitInfo): Boolean {
if (!sessionInfo.isVcsCommit) {
return workflow.executeSession(sessionInfo, commitInfo)
}
workflow.asyncSession(coroutineScope, sessionInfo) {
pendingPostCommitChecks = null
val isOnlyRunCommitChecks = commitContext.isOnlyRunCommitChecks
commitContext.isOnlyRunCommitChecks = false
val skipEarlyCommitChecks = !isOnlyRunCommitChecks && willSkipEarlyCommitChecks()
val skipModificationCommitChecks = !isOnlyRunCommitChecks && willSkipModificationCommitChecks()
val skipLateCommitChecks = !isOnlyRunCommitChecks && willSkipLateCommitChecks()
val skipPostCommitChecks = !isOnlyRunCommitChecks && willSkipPostCommitChecks()
resetCommitChecksResult()
ui.commitProgressUi.runWithProgress(isOnlyRunCommitChecks) {
val failure = runNonModalBeforeCommitChecks(commitInfo, skipEarlyCommitChecks, skipModificationCommitChecks,
skipLateCommitChecks, skipPostCommitChecks)
handleCommitProblem(failure, isOnlyRunCommitChecks)
}
}
return true
}
private suspend fun runNonModalBeforeCommitChecks(commitInfo: DynamicCommitInfo,
skipEarlyCommitChecks: Boolean,
skipModificationCommitChecks: Boolean,
skipLateCommitChecks: Boolean,
skipPostCommitChecks: Boolean): NonModalCommitChecksFailure? {
try {
val handlers = workflow.commitHandlers
val commitChecks = handlers
.map { it.asCommitCheck(commitInfo) }
.filter { it.isEnabled() }
.groupBy { it.getExecutionOrder() }
val earlyChecks = commitChecks[CommitCheck.ExecutionOrder.EARLY].orEmpty()
val modificationChecks = commitChecks[CommitCheck.ExecutionOrder.MODIFICATION].orEmpty()
val lateChecks = commitChecks[CommitCheck.ExecutionOrder.LATE].orEmpty()
val postCommitChecks = commitChecks[CommitCheck.ExecutionOrder.POST_COMMIT].orEmpty()
@Suppress("DEPRECATION") val metaHandlers = handlers.filterIsInstance<CheckinMetaHandler>()
if (!skipEarlyCommitChecks) {
runEarlyCommitChecks(commitInfo, earlyChecks)?.let { return it }
}
if (!skipModificationCommitChecks) {
runModificationCommitChecks(commitInfo, modificationChecks, metaHandlers)?.let { return it }
}
if (!skipLateCommitChecks) {
runLateCommitChecks(commitInfo, lateChecks)?.let { return it }
}
if (!skipPostCommitChecks) {
if (postCommitChecks.isNotEmpty()) {
if (Registry.`is`("vcs.non.modal.post.commit.checks") &&
commitInfo.executor?.requiresSyncCommitChecks() != true &&
postCommitChecksHandler.canHandle(commitInfo)) {
pendingPostCommitChecks = PendingPostCommitChecks(commitInfo.asStaticInfo(), postCommitChecks)
}
else {
postCommitChecksHandler.resetPendingCommits()
runSyncPostCommitChecks(commitInfo, postCommitChecks)?.let { return it }
}
}
}
return null // checks passed
}
catch (ce: CancellationException) {
// Do not report error on cancellation
throw ce
}
catch (e: Throwable) {
LOG.warn(Throwable(e))
reportCommitCheckFailure(CommitProblem.createError(e))
return NonModalCommitChecksFailure.ERROR
}
}
private suspend fun runEarlyCommitChecks(commitInfo: DynamicCommitInfo, commitChecks: List<CommitCheck>): NonModalCommitChecksFailure? {
val problems = mutableListOf<CommitProblem>()
for (commitCheck in commitChecks) {
problems += AbstractCommitWorkflow.runCommitCheck(project, commitCheck, commitInfo) ?: continue
}
if (problems.isEmpty()) return null
problems.forEach { reportCommitCheckFailure(it) }
return NonModalCommitChecksFailure.EARLY_FAILED
}
private suspend fun runModificationCommitChecks(commitInfo: DynamicCommitInfo,
commitChecks: List<CommitCheck>,
@Suppress("DEPRECATION")
metaHandlers: List<CheckinMetaHandler>): NonModalCommitChecksFailure? {
if (metaHandlers.isEmpty() && commitChecks.isEmpty()) return null
return workflow.runModificationCommitChecks underChangelist@{
AbstractCommitWorkflow.runMetaHandlers(metaHandlers)
for (commitCheck in commitChecks) {
val problem = AbstractCommitWorkflow.runCommitCheck(project, commitCheck, commitInfo) ?: continue
reportCommitCheckFailure(problem)
return@underChangelist NonModalCommitChecksFailure.MODIFICATIONS_FAILED
}
FileDocumentManager.getInstance().saveAllDocuments()
return@underChangelist null
}
}
private suspend fun runLateCommitChecks(commitInfo: DynamicCommitInfo, commitChecks: List<CommitCheck>): NonModalCommitChecksFailure? {
for (commitCheck in commitChecks) {
val problem = AbstractCommitWorkflow.runCommitCheck(project, commitCheck, commitInfo) ?: continue
val solution = problem.showModalSolution(project, commitInfo)
if (solution == CheckinHandler.ReturnResult.COMMIT) continue
reportCommitCheckFailure(problem)
return NonModalCommitChecksFailure.ABORTED
}
return null
}
private suspend fun runSyncPostCommitChecks(commitInfo: DynamicCommitInfo,
commitChecks: List<CommitCheck>): NonModalCommitChecksFailure? {
val problems = mutableListOf<CommitProblem>()
for (commitCheck in commitChecks) {
problems += AbstractCommitWorkflow.runCommitCheck(project, commitCheck, commitInfo) ?: continue
}
if (problems.isEmpty()) return null
problems.forEach { reportCommitCheckFailure(it) }
return NonModalCommitChecksFailure.POST_FAILED
}
private fun reportCommitCheckFailure(problem: CommitProblem) {
val checkFailure = when (problem) {
is UnknownCommitProblem -> CommitCheckFailure.Unknown
is CommitProblemWithDetails -> CommitCheckFailure.WithDetails(problem.text, problem.showDetailsAction) {
problem.showDetails(project)
}
else -> CommitCheckFailure.WithDescription(problem.text)
}
ui.commitProgressUi.addCommitCheckFailure(checkFailure)
}
private fun handleCommitProblem(failure: NonModalCommitChecksFailure?, isOnlyRunCommitChecks: Boolean): CommitChecksResult {
val checksPassed = failure == null
val aborted = failure == NonModalCommitChecksFailure.ABORTED
when (failure) {
null -> {
if (isOnlyRunCommitChecks) {
isCommitChecksResultUpToDate = RecentCommitChecks.PASSED
}
else {
isCommitChecksResultUpToDate = RecentCommitChecks.UNKNOWN // We are going to commit, remembering the result is not needed.
}
}
NonModalCommitChecksFailure.EARLY_FAILED -> {
isCommitChecksResultUpToDate = RecentCommitChecks.EARLY_FAILED
}
NonModalCommitChecksFailure.MODIFICATIONS_FAILED -> {
isCommitChecksResultUpToDate = RecentCommitChecks.MODIFICATIONS_FAILED
}
NonModalCommitChecksFailure.POST_FAILED -> {
isCommitChecksResultUpToDate = RecentCommitChecks.POST_FAILED
}
NonModalCommitChecksFailure.ABORTED,
NonModalCommitChecksFailure.ERROR -> {
isCommitChecksResultUpToDate = RecentCommitChecks.FAILED
}
}
if (aborted) {
return CommitChecksResult.Cancelled
}
else if (isOnlyRunCommitChecks) {
return CommitChecksResult.OnlyChecks(checksPassed)
}
else if (checksPassed) {
return CommitChecksResult.Passed
}
else {
return CommitChecksResult.Failed()
}
}
override fun dispose() {
hideCommitChecksFailureNotification()
coroutineScope.cancel()
project.getServiceIfCreated(PostCommitChecksHandler::class.java)?.resetPendingCommits() // null during Project dispose
super.dispose()
}
fun hideCommitChecksFailureNotification() {
checkinErrorNotifications.clear()
}
fun showCommitOptions(isFromToolbar: Boolean, dataContext: DataContext) =
ui.showCommitOptions(ensureCommitOptions(), getDefaultCommitActionName(workflow.vcses), isFromToolbar, dataContext)
override fun saveCommitOptionsOnCommit(): Boolean {
ensureCommitOptions()
// restore state in case settings were changed via configurable
commitOptions.allOptions
.filter { it is UnnamedConfigurable }
.forEach { it.restoreState() }
return super.saveCommitOptionsOnCommit()
}
private fun ensureCommitOptions(): CommitOptions {
if (!areCommitOptionsCreated) {
areCommitOptionsCreated = true
workflow.initCommitOptions(createCommitOptions())
commitOptions.restoreState()
commitOptionsCreated()
}
return commitOptions
}
protected open fun commitOptionsCreated() = Unit
protected fun disposeCommitOptions() {
workflow.disposeCommitOptions()
areCommitOptionsCreated = false
}
override fun getState(): CommitWorkflowHandlerState {
val isAmend = amendCommitHandler.isAmendCommitMode
val isSkipCommitChecks = willSkipCommitChecks()
return CommitWorkflowHandlerState(isAmend, isSkipCommitChecks)
}
protected open inner class CommitStateCleaner : CommitterResultHandler {
override fun onSuccess() = resetState()
override fun onCancel() = Unit
override fun onFailure() = resetState()
protected open fun resetState() {
disposeCommitOptions()
workflow.clearCommitContext()
initCommitHandlers()
resetCommitChecksResult()
updateDefaultCommitActionName()
}
}
protected inner class PostCommitChecksRunner : CommitterResultHandler {
override fun onSuccess() {
pendingPostCommitChecks?.let { postCommitChecksHandler.startPostCommitChecksTask(it.commitInfo, it.commitChecks) }
pendingPostCommitChecks = null
}
override fun onCancel() {
pendingPostCommitChecks = null
}
override fun onFailure() {
pendingPostCommitChecks = null
}
}
}
private class PendingPostCommitChecks(val commitInfo: StaticCommitInfo, val commitChecks: List<CommitCheck>)
private enum class NonModalCommitChecksFailure { EARLY_FAILED, MODIFICATIONS_FAILED, POST_FAILED, ABORTED, ERROR }
private enum class RecentCommitChecks { UNKNOWN, PASSED, EARLY_FAILED, MODIFICATIONS_FAILED, POST_FAILED, FAILED }
| apache-2.0 | a7e1bb62d997ee78b881d2e3c113c260 | 41.30427 | 158 | 0.738212 | 5.277469 | false | false | false | false |
GunoH/intellij-community | uast/uast-common/src/org/jetbrains/uast/qualifiedUtils.kt | 2 | 10154 | /*
* Copyright 2000-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.
*/
@file:JvmMultifileClass
@file:JvmName("UastUtils")
package org.jetbrains.uast
import com.intellij.psi.*
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.util.PsiMethodUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.visitor.UastVisitor
/**
* Get the topmost parent qualified expression for the call expression.
*
* Example 1:
* Code: variable.call(args)
* Call element: E = call(args)
* Qualified parent (return value): Q = [getQualifiedCallElement](E) = variable.call(args)
*
* Example 2:
* Code: call(args)
* Call element: E = call(args)
* Qualified parent (return value): Q = [getQualifiedCallElement](E) = call(args) (no qualifier)
*
* @return containing qualified expression if the call is a child of the qualified expression, call element otherwise.
*/
fun UExpression.getQualifiedParentOrThis(): UExpression {
fun findParent(current: UExpression?, previous: UExpression): UExpression? = when (current) {
is UQualifiedReferenceExpression -> {
if (current.selector == previous)
findParent(current.uastParent as? UExpression, current) ?: current
else
previous
}
is UParenthesizedExpression -> findParent(current.expression, previous) ?: previous
else -> null
}
return findParent(uastParent as? UExpression, this) ?: this
}
fun UExpression.asQualifiedPath(): List<String>? {
if (this is USimpleNameReferenceExpression) {
return listOf(this.identifier)
}
else if (this !is UQualifiedReferenceExpression) {
return null
}
var error = false
val list = mutableListOf<String>()
fun addIdentifiers(expr: UQualifiedReferenceExpression) {
val receiver = expr.receiver.unwrapParenthesis()
val selector = expr.selector as? USimpleNameReferenceExpression ?: run { error = true; return }
when (receiver) {
is UQualifiedReferenceExpression -> addIdentifiers(receiver)
is USimpleNameReferenceExpression -> list += receiver.identifier
else -> {
error = true
return
}
}
list += selector.identifier
}
addIdentifiers(this)
return if (error) null else list
}
/**
* Return the list of qualified expressions.
*
* Example:
* Code: obj.call(param).anotherCall(param2).getter
* Qualified chain: [obj, call(param), anotherCall(param2), getter]
*
* @return list of qualified expressions, or the empty list if the received expression is not a qualified expression.
*/
fun UExpression?.getQualifiedChain(): List<UExpression> {
fun collect(expr: UQualifiedReferenceExpression, chains: MutableList<UExpression>) {
val receiver = expr.receiver.unwrapParenthesis()
if (receiver is UQualifiedReferenceExpression) {
collect(receiver, chains)
}
else {
chains += receiver
}
val selector = expr.selector.unwrapParenthesis()
if (selector is UQualifiedReferenceExpression) {
collect(selector, chains)
}
else {
chains += selector
}
}
if (this == null) return emptyList()
val qualifiedExpression = this as? UQualifiedReferenceExpression ?: return listOf(this)
val chains = mutableListOf<UExpression>()
collect(qualifiedExpression, chains)
return chains
}
/**
* Return the outermost qualified expression.
*
* @return the outermost qualified expression,
* this element if the parent expression is not a qualified expression,
* or null if the element is not a qualified expression.
*
* Example:
* Code: a.b.c(asd).g
* Call element: c(asd)
* Outermost qualified (return value): a.b.c(asd).g
*/
fun UExpression.getOutermostQualified(): UQualifiedReferenceExpression? {
tailrec fun getOutermostQualified(current: UElement?, previous: UExpression): UQualifiedReferenceExpression? = when (current) {
is UQualifiedReferenceExpression -> getOutermostQualified(current.uastParent, current)
is UParenthesizedExpression -> getOutermostQualified(current.uastParent, previous)
else -> if (previous is UQualifiedReferenceExpression) previous else null
}
return getOutermostQualified(this.uastParent, this)
}
/**
* Checks if the received expression is a qualified chain of identifiers, and the trailing part of such chain is [fqName].
*
* @param fqName the chain part to check against. Sequence of identifiers, separated by dot ('.'). Example: "com.example".
* @return true, if the received expression is a qualified chain of identifiers, and the trailing part of such chain is [fqName].
*/
fun UExpression.matchesQualified(fqName: String): Boolean {
val identifiers = this.asQualifiedPath() ?: return false
val passedIdentifiers = fqName.trim('.').split('.')
return identifiers == passedIdentifiers
}
/**
* Checks if the received expression is a qualified chain of identifiers, and the leading part of such chain is [fqName].
*
* @param fqName the chain part to check against. Sequence of identifiers, separated by dot ('.'). Example: "com.example".
* @return true, if the received expression is a qualified chain of identifiers, and the leading part of such chain is [fqName].
*/
fun UExpression.startsWithQualified(fqName: String): Boolean {
val identifiers = this.asQualifiedPath() ?: return false
val passedIdentifiers = fqName.trim('.').split('.')
if (identifiers.size < passedIdentifiers.size) return false
passedIdentifiers.forEachIndexed { i, passedIdentifier ->
if (passedIdentifier != identifiers[i]) return false
}
return true
}
/**
* Checks if the received expression is a qualified chain of identifiers, and the trailing part of such chain is [fqName].
*
* @param fqName the chain part to check against. Sequence of identifiers, separated by dot ('.'). Example: "com.example".
* @return true, if the received expression is a qualified chain of identifiers, and the trailing part of such chain is [fqName].
*/
fun UExpression.endsWithQualified(fqName: String): Boolean {
val identifiers = this.asQualifiedPath()?.asReversed() ?: return false
val passedIdentifiers = fqName.trim('.').split('.').asReversed()
if (identifiers.size < passedIdentifiers.size) return false
passedIdentifiers.forEachIndexed { i, passedIdentifier ->
if (passedIdentifier != identifiers[i]) return false
}
return true
}
@JvmOverloads
fun UElement.asRecursiveLogString(render: (UElement) -> String = { it.asLogString() }): String {
val stringBuilder = StringBuilder()
val indent = " "
accept(object : UastVisitor {
private var level = 0
override fun visitElement(node: UElement): Boolean {
stringBuilder.append(indent.repeat(level))
stringBuilder.append(render(node))
stringBuilder.append('\n')
level++
return false
}
override fun afterVisitElement(node: UElement) {
super.afterVisitElement(node)
level--
}
})
return stringBuilder.toString()
}
/**
* @return method's containing class if the given method is main method,
* or companion object's containing class if the given method is main method annotated with [kotlin.jvm.JvmStatic] in companion object,
* otherwise *null*.
*/
fun getMainMethodClass(uMainMethod: UMethod): PsiClass? {
if ("main" != uMainMethod.name) return null
val containingClass = uMainMethod.uastParent as? UClass ?: return null
val mainMethod = uMainMethod.javaPsi
if (PsiMethodUtil.isMainMethod(mainMethod)) return containingClass.javaPsi
//a workaround for KT-33956
if (isKotlinParameterlessMain(mainMethod)) return containingClass.javaPsi
if (isKotlinSuspendMain(uMainMethod)) return containingClass.javaPsi
// Check for @JvmStatic main method in companion object
val parentClassForCompanionObject = (containingClass.uastParent as? UClass)?.javaPsi ?: return null
val mainInClass = PsiMethodUtil.findMainInClass(parentClassForCompanionObject)
if (mainMethod.manager.areElementsEquivalent(mainMethod, mainInClass)) {
return parentClassForCompanionObject
}
return null
}
private fun isKotlinParameterlessMain(mainMethod: PsiMethod) =
mainMethod.language.id == "kotlin"
&& mainMethod.parameterList.parameters.isEmpty()
&& PsiType.VOID == mainMethod.returnType
&& mainMethod.hasModifierProperty(PsiModifier.STATIC)
private fun isKotlinSuspendMain(uMainMethod: UMethod): Boolean {
val sourcePsi = uMainMethod.sourcePsi ?: return false
if (sourcePsi.language.id != "kotlin") return false
if (!SyntaxTraverser.psiTraverser(sourcePsi.children.first()).any { it is LeafPsiElement && it.textMatches("suspend") }) return false
val method = uMainMethod.javaPsi
val parameters: Array<PsiParameter> = method.parameterList.parameters
if (parameters.size > 2) return false
// suspend main method has additional parameter kotlin.coroutines.Continuation but it could be seen as java.lang.Object
// on the PSI level, so we don't check it directly
if (parameters.size == 2) {
val argsType = parameters[0].type as? PsiArrayType ?: return false
if (!argsType.componentType.equalsToText(CommonClassNames.JAVA_LANG_STRING)) return false
}
return method.hasModifierProperty(PsiModifier.STATIC) && method.returnType?.equalsToText(CommonClassNames.JAVA_LANG_OBJECT) == true
}
@ApiStatus.Experimental
fun findMainInClass(uClass: UClass?): PsiMethod? {
val javaPsi = uClass?.javaPsi ?: return null
PsiMethodUtil.findMainInClass(javaPsi)?.let { return it }
//a workaround for KT-33956
javaPsi.methods.find(::isKotlinParameterlessMain)?.let { return it }
uClass.methods.find(::isKotlinSuspendMain)?.javaPsi?.let { return it }
return null
} | apache-2.0 | 92751fce8ba8ee064b8dd3d5ca382260 | 36.472325 | 135 | 0.737049 | 4.477072 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database-tests/src/test/kotlin/database/query/SelectIndexTest.kt | 1 | 8133 | package database.query
import com.onyx.persistence.IManagedEntity
import com.onyx.persistence.query.*
import database.base.DatabaseBaseTest
import entities.SelectIdentifierTestEntity
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import kotlin.reflect.KClass
import kotlin.test.assertEquals
@RunWith(Parameterized::class)
class SelectIndexTest(override var factoryClass: KClass<*>) : DatabaseBaseTest(factoryClass) {
@Before
fun seedData() {
manager.from(SelectIdentifierTestEntity::class).delete()
var entity = SelectIdentifierTestEntity()
entity.id = 1L
entity.index = 1
entity.attribute = "1"
manager.saveEntity<IManagedEntity>(entity)
entity = SelectIdentifierTestEntity()
entity.id = 2L
entity.index = 2
entity.attribute = "2"
manager.saveEntity<IManagedEntity>(entity)
entity = SelectIdentifierTestEntity()
entity.id = 3L
entity.index = 3
entity.attribute = "3"
manager.saveEntity<IManagedEntity>(entity)
entity = SelectIdentifierTestEntity()
entity.id = 4L
entity.index = 4
entity.attribute = "4"
manager.saveEntity<IManagedEntity>(entity)
entity = SelectIdentifierTestEntity()
entity.id = 5L
entity.index = 5
entity.attribute = "5"
manager.saveEntity<IManagedEntity>(entity)
entity = SelectIdentifierTestEntity()
entity.id = 6L
entity.index = 6
entity.attribute = "6"
manager.saveEntity<IManagedEntity>(entity)
entity = SelectIdentifierTestEntity()
entity.id = 7L
entity.index = 7
entity.attribute = "7"
manager.saveEntity<IManagedEntity>(entity)
entity = SelectIdentifierTestEntity()
entity.id = 8L
entity.index = 8
entity.attribute = "8"
manager.saveEntity<IManagedEntity>(entity)
entity = SelectIdentifierTestEntity()
entity.id = 9L
entity.index = 9
entity.attribute = "9"
manager.saveEntity<IManagedEntity>(entity)
entity = SelectIdentifierTestEntity()
entity.id = 10L
entity.index = 10
entity.attribute = "10"
manager.saveEntity<IManagedEntity>(entity)
}
@Test
fun testIdentifierAndCriteria() {
val first = QueryCriteria("index", QueryCriteriaOperator.GREATER_THAN, 5L)
val second = QueryCriteria("index", QueryCriteriaOperator.LESS_THAN, 8L)
val query = Query()
query.entityType = SelectIdentifierTestEntity::class.java
query.criteria = first.and(second)
assertEquals(2, manager.executeQuery<Any>(query).size, "Expected 2 results")
}
@Test
fun testIdentifierOrCriteria() {
val first = QueryCriteria("index", QueryCriteriaOperator.GREATER_THAN, 5L)
val second = QueryCriteria("index", QueryCriteriaOperator.EQUAL, 3L)
val query = Query()
query.entityType = SelectIdentifierTestEntity::class.java
query.criteria = first.or(second)
assertEquals(6, manager.executeQuery<Any>(query).size, "Expected 6 results")
}
@Test
fun testIdentifierCompoundCriteria() {
val first = QueryCriteria("index", QueryCriteriaOperator.GREATER_THAN, 5L)
val second = QueryCriteria("index", QueryCriteriaOperator.LESS_THAN, 3L)
val third = QueryCriteria("index", QueryCriteriaOperator.EQUAL, 3L)
val fourth = QueryCriteria("index", QueryCriteriaOperator.EQUAL, 2L)
val query = Query()
query.entityType = SelectIdentifierTestEntity::class.java
query.criteria = first.or(second.and(third.or(fourth)))
assertEquals(6, manager.executeQuery<Any>(query).size, "Expected 6 results")
}
@Test
fun testIdentifierAndCriteriaWithNot() {
val first = QueryCriteria("index", QueryCriteriaOperator.GREATER_THAN, 5L)
val second = QueryCriteria("index", QueryCriteriaOperator.LESS_THAN, 8L)
val query = Query()
query.entityType = SelectIdentifierTestEntity::class.java
query.criteria = first.and(second.not())
assertEquals(3, manager.executeQuery<Any>(query).size, "Expected 3 results")
}
@Test
fun testIdentifierAndCriteriaWithNotGroup() {
val first = QueryCriteria("index", QueryCriteriaOperator.GREATER_THAN, 5L)
val second = QueryCriteria("index", QueryCriteriaOperator.LESS_THAN, 8L)
val query = Query()
query.entityType = SelectIdentifierTestEntity::class.java
query.criteria = first.and(second).not()
assertEquals(8, manager.executeQuery<Any>(query).size, "Expected 8 results")
}
@Test
fun testIdentifierOrCriteriaWithNot() {
val first = QueryCriteria("index", QueryCriteriaOperator.GREATER_THAN, 5L)
val second = QueryCriteria("index", QueryCriteriaOperator.LESS_THAN, 8L)
val query = Query()
query.entityType = SelectIdentifierTestEntity::class.java
query.criteria = first.or(second.not())
assertEquals(5, manager.executeQuery<Any>(query).size, "Expected 5 results")
}
@Test
fun testIdentifierOrCriteriaWithNotGroup() {
val first = QueryCriteria("index", QueryCriteriaOperator.GREATER_THAN, 5L)
val second = QueryCriteria("index", QueryCriteriaOperator.LESS_THAN, 8L)
val query = Query()
query.entityType = SelectIdentifierTestEntity::class.java
query.criteria = first.or(second).not()
assertEquals(0, manager.executeQuery<Any>(query).size, "Expected no results")
}
@Test
fun testIdentifierCompoundCriteriaWithNot() {
val first = QueryCriteria("index", QueryCriteriaOperator.GREATER_THAN, 5L)
val second = QueryCriteria("index", QueryCriteriaOperator.LESS_THAN, 3L)
val third = QueryCriteria("index", QueryCriteriaOperator.EQUAL, 3L)
val fourth = QueryCriteria("index", QueryCriteriaOperator.EQUAL, 2L)
val query = Query()
query.entityType = SelectIdentifierTestEntity::class.java
query.criteria = first.or(second.and(third.or(fourth).not()))
assertEquals(6, manager.executeQuery<Any>(query).size, "Expected 6 results")
}
@Test
fun testIdentifierCompoundCriteriaWithNotFullScan() {
val first = QueryCriteria("index", QueryCriteriaOperator.GREATER_THAN, 5L)
val second = QueryCriteria("index", QueryCriteriaOperator.LESS_THAN, 3L)
val third = QueryCriteria("index", QueryCriteriaOperator.EQUAL, 3L)
val fourth = QueryCriteria("index", QueryCriteriaOperator.EQUAL, 2L)
val query = Query()
query.entityType = SelectIdentifierTestEntity::class.java
query.criteria = first.or(second.and(third.or(fourth))).not()
assertEquals(4, manager.executeQuery<Any>(query).size, "Expected 4 results")
}
@Test
fun testMixMatchOfCriteria() {
val first = QueryCriteria("index", QueryCriteriaOperator.GREATER_THAN, 5L)
val second = QueryCriteria("id", QueryCriteriaOperator.LESS_THAN, 3L)
val third = QueryCriteria("index", QueryCriteriaOperator.EQUAL, 3L)
val fourth = QueryCriteria("id", QueryCriteriaOperator.EQUAL, 2L)
val query = Query()
query.entityType = SelectIdentifierTestEntity::class.java
query.criteria = first.or(second.and(third.or(fourth).not()))
assertEquals(6, manager.executeQuery<Any>(query).size, "Expected 6 results")
}
@Test
fun testMixMatchOfCriteriaIncludeFull() {
val count = manager.from(SelectIdentifierTestEntity::class).where(
("index" gt 5L)
.or( ("id" lt 3)
.and((("index" eq 3) or !("id" eq 2)))
.and(("attribute" eq 3) or ("attribute" eq 2))
)
).count()
assertEquals(5, count, "Expected 5 results from compound query")
}
} | agpl-3.0 | e4c03245c7e3c4a80801e2745eb1ce3f | 34.675439 | 94 | 0.657199 | 4.639475 | false | true | false | false |
danesc87/wifi-discloser | app/src/main/java/com/nano_bytes/wifi_discloser/AboutActivity.kt | 1 | 2000 | package com.nano_bytes.wifi_discloser
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.ImageButton
import com.nano_bytes.wifi_discloser.adapter.AboutAdapter
import kotlinx.android.synthetic.main.activity_about.*
import java.util.*
import kotlin.collections.LinkedHashMap
class AboutActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_about)
aboutToolbar.title = "About Wifi Discloser"
setSupportActionBar(aboutToolbar)
backToMain()
val linearLayoutManager = LinearLayoutManager(baseContext, LinearLayoutManager.VERTICAL,
false)
aboutRecyclerView.layoutManager = linearLayoutManager
addAboutSection()
}
private fun addAboutSection(){
var passObject:LinkedHashMap<String, String> = LinkedHashMap()
var keysArray:ArrayList<String> = ArrayList()
passObject.put("App Title", "Wifi Discloser")
passObject.put("Description", "Wifi Discloser is an App that show your stored wifi's " +
"with it's passwords")
passObject.put("Developers", "Daniel Córdova A.")
passObject.put("Licenses", "This Project is under GPLv3, feel free to use, modify or " +
"redistribute it")
for(item in passObject){
keysArray.add(item.key)
}
val adapter = AboutAdapter(keysArray, passObject, baseContext)
aboutRecyclerView.adapter = adapter
adapter.notifyDataSetChanged()
}
private fun backToMain(){
val about = findViewById(R.id.backToMain) as ImageButton
about.setOnClickListener(View.OnClickListener {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
})
}
}
| gpl-3.0 | 9d04f8812163ddf63824dcc830854c77 | 36.716981 | 96 | 0.696348 | 4.648837 | false | false | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/formatting/visualLayer/VisualFormattingLayerService.kt | 4 | 5014 | // 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.formatting.visualLayer
import com.intellij.application.options.RegistryManager
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorCustomElementRenderer
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiFile
import com.intellij.psi.codeStyle.CodeStyleScheme
import com.intellij.psi.codeStyle.CodeStyleSchemes
private const val REGISTRY_KEY = "editor.visual.formatting.layer.enabled"
val visualFormattingElementKey = Key.create<Boolean>("visual.formatting.element")
abstract class VisualFormattingLayerService {
val editorFactory: EditorFactory by lazy { EditorFactory.getInstance() }
val enabledByRegistry: Boolean
get() = RegistryManager.getInstance().`is`(REGISTRY_KEY)
val enabledBySettings: Boolean
get() = UISettings.getInstance().showVisualFormattingLayer
var enabledGlobally: Boolean = false
var scheme: CodeStyleScheme
get() = with(CodeStyleSchemes.getInstance()) {
allSchemes.find { it.isUsedForVisualFormatting } ?: defaultScheme
}
set(scheme) = with(CodeStyleSchemes.getInstance()) {
allSchemes.forEach { it.isUsedForVisualFormatting = false }
scheme.isUsedForVisualFormatting = true
}
fun getSchemes(): List<CodeStyleScheme> = CodeStyleSchemes.getInstance().allSchemes
val disabledGlobally: Boolean
get() = !enabledGlobally
fun enabledForEditor(editor: Editor) =
editor.settings.isShowVisualFormattingLayer ?: enabledGlobally
fun disabledForEditor(editor: Editor) =
!enabledForEditor(editor)
fun enableForEditor(editor: Editor) {
if (disabledForEditor(editor)) {
if (enabledGlobally) {
editor.settings.isShowVisualFormattingLayer = null
}
else {
editor.settings.isShowVisualFormattingLayer = true
}
}
}
fun disableForEditor(editor: Editor) {
if (enabledForEditor(editor)) {
if (disabledGlobally) {
editor.settings.isShowVisualFormattingLayer = null
}
else {
editor.settings.isShowVisualFormattingLayer = false
}
}
}
//------------------------------
// Global stuff
fun enableGlobally() {
editorFactory.allEditors.forEach { it.settings.isShowVisualFormattingLayer = null }
enabledGlobally = true
}
fun disableGlobally() {
editorFactory.allEditors.forEach { it.settings.isShowVisualFormattingLayer = null }
enabledGlobally = false
}
//------------------------------
abstract fun getVisualFormattingLayerElements(file: PsiFile): List<VisualFormattingLayerElement>
companion object {
@JvmStatic
fun getInstance(): VisualFormattingLayerService =
ApplicationManager.getApplication().getService(VisualFormattingLayerService::class.java)
}
}
sealed class VisualFormattingLayerElement {
abstract fun applyToEditor(editor: Editor): Unit
data class InlineInlay(val offset: Int, val length: Int) : VisualFormattingLayerElement() {
override fun applyToEditor(editor: Editor) {
editor.inlayModel
.addInlineElement(
offset,
false,
InlayPresentation(editor, length)
)
}
}
data class BlockInlay(val offset: Int, val lines: Int) : VisualFormattingLayerElement() {
override fun applyToEditor(editor: Editor) {
editor.inlayModel
.addBlockElement(
offset,
true,
true,
0,
InlayPresentation(editor, lines, vertical = true)
)
}
}
data class Folding(val offset: Int, val length: Int) : VisualFormattingLayerElement() {
override fun applyToEditor(editor: Editor) {
editor.foldingModel.runBatchFoldingOperation {
editor.foldingModel
.addFoldRegion(offset, offset + length, "")
?.apply {
isExpanded = false
shouldNeverExpand()
putUserData(visualFormattingElementKey, true)
}
}
}
}
}
data class InlayPresentation(val editor: Editor,
val fillerLength: Int,
val vertical: Boolean = false) : EditorCustomElementRenderer {
private val editorFontMetrics by lazy {
val editorFont = EditorColorsManager.getInstance().globalScheme.getFont(EditorFontType.PLAIN)
editor.contentComponent.getFontMetrics(editorFont)
}
override fun calcWidthInPixels(inlay: Inlay<*>) =
if (vertical) 0 else editorFontMetrics.stringWidth(" ".repeat(fillerLength))
override fun calcHeightInPixels(inlay: Inlay<*>) =
(if (vertical) fillerLength else 1) * editorFontMetrics.height
}
| apache-2.0 | 4b6b2a01141ca02a6bf3f68bf439d8b2 | 30.3375 | 120 | 0.709214 | 4.76616 | false | false | false | false |
JetBrains/kotlin-native | runtime/src/main/kotlin/kotlin/Enum.kt | 4 | 1249 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlin
import kotlin.native.internal.enumValueOfIntrinsic
import kotlin.native.internal.enumValuesIntrinsic
/**
* The common base class of all enum classes.
* See the [Kotlin language documentation](https://kotlinlang.org/docs/reference/enum-classes.html) for more
* information on enum classes.
*/
public abstract class Enum<E: Enum<E>>(public val name: String, public val ordinal: Int): Comparable<E> {
public companion object {
}
public override final fun compareTo(other: E): Int { return ordinal - other.ordinal }
public override final fun equals(other: Any?): Boolean {
return this === other
}
public override final fun hashCode(): Int {
return ordinal
}
public override fun toString(): String {
return name
}
}
/**
* Returns an enum entry with specified name.
*/
public inline fun <reified T: Enum<T>> enumValueOf(name: String): T = enumValueOfIntrinsic<T>(name)
/**
* Returns an array containing enum T entries.
*/
public inline fun <reified T: Enum<T>> enumValues(): Array<T> = enumValuesIntrinsic<T>()
| apache-2.0 | 590390c88a3fd4b4b275d7cacbf8ba49 | 27.386364 | 108 | 0.70056 | 4.068404 | false | false | false | false |
vovagrechka/fucking-everything | attic/photlin/src/photlinc/gen.kt | 1 | 48644 | package photlinc
import org.jetbrains.kotlin.js.backend.ast.JsVisitor
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.js.backend.ast.JsNumberLiteral.JsDoubleLiteral
import org.jetbrains.kotlin.js.backend.ast.JsNumberLiteral.JsIntLiteral
import org.jetbrains.kotlin.js.backend.ast.JsVars.JsVar
import org.jetbrains.kotlin.js.util.TextOutput
import gnu.trove.THashSet
import org.jetbrains.kotlin.backend.jvm.codegen.psiElement
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotated
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl
import org.jetbrains.kotlin.js.backend.JsConstructExpressionVisitor
import org.jetbrains.kotlin.js.backend.JsFirstExpressionVisitor
import org.jetbrains.kotlin.js.backend.JsPrecedenceVisitor
import org.jetbrains.kotlin.js.backend.JsRequiresSemiVisitor
import org.jetbrains.kotlin.js.translate.utils.name
import org.jetbrains.kotlin.js.util.TextOutputImpl
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.annotations.argumentValue
import org.jetbrains.kotlin.resolve.constants.BooleanValue
import org.jetbrains.kotlin.resolve.constants.StringValue
import java.util.*
import photlin.*
import vgrechka.*
open class JsToStringGenerationVisitor2(out:TextOutput): JsVisitor() {
protected var needSemi = true
private var lineBreakAfterBlock = true
/**
* "Global" blocks are either the global block of a fragment, or a block
* nested directly within some other global block. This definition matters
* because the statements designated by statementEnds and statementStarts are
* those that appear directly within these global blocks.
*/
private val globalBlocks = THashSet<JsBlock>()
val p:TextOutput
init{
p = out
}
override fun visitSingleLineComment(x: JsSingleLineComment) {
p.print("// ${x.text}\n")
}
override fun visitPHPPlainCodeExpression(x: PHPPlainCodeExpression) {
p.print(x.spewCode())
}
override fun visitArrayAccess(x:JsArrayAccess) {
printPair(x, x.getArrayExpression())
leftSquare()
accept(x.getIndexExpression())
rightSquare()
}
override fun visitArray(x: JsArrayLiteral) {
printDebugTag(x)
fun fuck(gen: JsToStringGenerationVisitor2) {
gen.p.print("array(")
gen.printExpressions(x.getExpressions())
gen.p.print(")")
}
fuck(this)
}
private fun printExpressions(expressions:List<JsExpression>) {
var notFirst = false
for ((expressionIndex, expression) in expressions.withIndex())
{
notFirst = sepCommaOptSpace(notFirst) && !(expression is JsDocComment)
val isEnclosed = parenPushIfCommaExpression(expression)
// if (expression.debugTag == "1646") {
// "break on me"
// }
if (expression is JsArrayLiteral || expression.valueParameterDescriptor?.type?.typeName == "kotlin.Array") {
pizdavalue(byReference = expression !is JsArrayLiteral) {gen-> gen.accept(expression)}
} else {
accept(expression)
}
if (isEnclosed)
{
rightParen()
}
}
}
private fun pizdavalue(byReference: Boolean = false, fuck: (JsToStringGenerationVisitor2) -> Unit) {
val tag = PhotlincDebugGlobal.nextDebugTag()
if (tag == PhotlincDebugGlobal.breakOnPizdavalue) {
"break on me"
}
val varName = "pizdavalue" + tag
val out = TextOutputImpl()
val generator = JsToStringGenerationVisitor2(out)
fuck(generator)
val eq = when {
byReference -> "=&"
else -> "="
}
printLineAbove("\$$varName $eq ${out.out};")
p.print("\$$varName")
}
override fun visitBinaryExpression(binaryOperation: JsBinaryOperation) {
val operator = binaryOperation.getOperator()
val arg1 = binaryOperation.getArg1()
val isExpressionEnclosed = parenPush(binaryOperation, arg1, !operator.isLeftAssociative())
accept(arg1)
if (operator.isKeyword())
{
_parenPopOrSpace(binaryOperation, arg1, !operator.isLeftAssociative())
}
else if (operator !== JsBinaryOperator.COMMA)
{
if (isExpressionEnclosed)
{
rightParen()
}
spaceOpt()
}
printDebugTag(binaryOperation)
if (binaryOperation.elvis) {
p.print("?:")
} else {
p.print(run {
val type = arg1.kotlinTypeName
if (type == "kotlin.String") {
if (operator.symbol == "+") return@run "."
if (operator.symbol == "+=") return@run ".="
}
return@run operator.symbol
})
}
// if (operator.symbol == "=") {
// if (binaryOperation.arg2.kotlinTypeName == "kotlin.Array") {
// p.print("&")
// }
// }
val arg2 = binaryOperation.getArg2()
val isParenOpened:Boolean
if (operator === JsBinaryOperator.COMMA)
{
isParenOpened = false
spaceOpt()
}
else if (arg2 is JsBinaryOperation && (arg2 as JsBinaryOperation).getOperator() === JsBinaryOperator.AND)
{
spaceOpt()
leftParen()
isParenOpened = true
}
else
{
if (spaceCalc(operator, arg2))
{
isParenOpened = _parenPushOrSpace(binaryOperation, arg2, operator.isLeftAssociative())
}
else
{
spaceOpt()
isParenOpened = parenPush(binaryOperation, arg2, operator.isLeftAssociative())
}
}
accept(arg2)
if (isParenOpened)
{
rightParen()
}
}
override fun visitBlock(x:JsBlock) {
printJsBlock(x, true)
}
override fun visitPHPClass(x: PHPClass) {
printAnnotations(x.classDescriptor, x)
val fuckingName = escapeIdent(x.className.ident)
printDebugTag(x)
p.print("class $fuckingName ")
x.classDescriptor.phpSuperPrototypeNameRef?.let {
val superClassName = (it.qualifier as JsNameRef).ident
p.print("extends ${escapeIdent(superClassName)} ")
}
blockOpen()
x.statements.forEach {accept(it); newlineOpt()}
blockClose()
p.newline()
p.print("\$$fuckingName = new stdClassWithPhotlinProps(); // Fuck...")
p.newline()
}
private fun printAnnotations(x: Annotated, node: JsNode) {
val annotations = x.annotations
if (!annotations.isEmpty()) {
p.print("/**")
for (ann in annotations) {
val annAnnotations = ann.type.constructor.declarationDescriptor?.annotations
if (annAnnotations != null) {
val emitAnnotationAsPHPCommentAnnotation = annAnnotations.find {
it.type.typeName == "photlin.EmitAnnotationAsPHPComment"
}
if (emitAnnotationAsPHPCommentAnnotation != null) {
val annotationTypeName = ann.type.typeName ?: wtf("0afd9e3c-b8f5-4cef-8d82-45de409b8e6a")
val nameArgValue = emitAnnotationAsPHPCommentAnnotation.argumentValue("name") as String
val phpName = when (nameArgValue) {
"" -> annotationTypeName.substringAfterLast(".")
else -> nameArgValue
}
p.print(" @" + phpName)
if (ann.allValueArguments.isNotEmpty()) {
p.print("(")
for ((key, value) in ann.allValueArguments) {
p.print(key.name.asString())
p.print("=")
when (value) {
is StringValue -> {
p.print(phpString(value.value, forceDoubleQuote = true))
}
is BooleanValue -> {
p.print(value.value.toString())
}
else -> imf("7a2b3251-0044-4b96-a9c4-5ca3cbabe207")
}
}
p.print(")")
}
}
}
}
p.print(" **/ ")
}
}
override fun visitBoolean(x:JsLiteral.JsBooleanLiteral) {
if (x.getValue())
{
p.print(CHARS_TRUE)
}
else
{
p.print(CHARS_FALSE)
}
}
override fun visitBreak(x:JsBreak) {
p.print(CHARS_BREAK)
continueOrBreakLabel(x)
}
override fun visitContinue(x:JsContinue) {
p.print(CHARS_CONTINUE)
continueOrBreakLabel(x)
}
private fun continueOrBreakLabel(x:JsContinue) {
val label = x.getLabel()
if (label != null && label.getIdent() != null)
{
space()
p.print("1") // XXX PHP...
// p.print(escapeIdent(label.getIdent()))
}
}
override fun visitCase(x:JsCase) {
p.print(CHARS_CASE)
space()
accept(x.getCaseExpression())
_colon()
newlineOpt()
printSwitchMemberStatements(x)
}
private fun printSwitchMemberStatements(x:JsSwitchMember) {
p.indentIn()
for (stmt in x.getStatements())
{
needSemi = true
accept(stmt)
if (needSemi)
{
semi()
}
newlineOpt()
}
p.indentOut()
needSemi = false
}
override fun visitCatch(x: JsCatch) {
spaceOpt()
p.print(CHARS_CATCH)
spaceOpt()
leftParen()
// val catchParam = ShitToShit.attrs(x).catchParam
// if (catchParam != null) {
// p.print(catchParam.typeReference!!.text + " $")
// }
accept(x.typeExpression)
p.print(" $")
nameDef(x.parameter.name)
// Optional catch condition.
//
val catchCond = x.condition
if (catchCond != null)
{
space()
_if()
space()
accept(catchCond)
}
rightParen()
spaceOpt()
accept(x.body)
}
override fun visitConditional(x:JsConditional) {
// Associativity: for the then and else branches, it is safe to insert
// another
// ternary expression, but if the test expression is a ternary, it should
// get parentheses around it.
printPair(x, x.getTestExpression(), true)
spaceOpt()
p.print('?')
spaceOpt()
printPair(x, x.getThenExpression())
spaceOpt()
_colon()
spaceOpt()
printPair(x, x.getElseExpression())
}
private fun printPair(parent:JsExpression, expression:JsExpression, wrongAssoc:Boolean = false) {
val isNeedParen = parenCalc(parent, expression, wrongAssoc)
if (isNeedParen)
{
leftParen()
}
accept(expression)
if (isNeedParen)
{
rightParen()
}
}
override fun visitDebugger(x:JsDebugger) {
p.print(CHARS_DEBUGGER)
}
override fun visitDefault(x:JsDefault) {
p.print(CHARS_DEFAULT)
_colon()
printSwitchMemberStatements(x)
}
override fun visitWhile(x:JsWhile) {
_while()
spaceOpt()
leftParen()
accept(x.getCondition())
rightParen()
nestedPush(x.getBody())
accept(x.getBody())
nestedPop(x.getBody())
}
override fun visitDoWhile(x:JsDoWhile) {
p.print(CHARS_DO)
nestedPush(x.getBody())
accept(x.getBody())
nestedPop(x.getBody())
if (needSemi)
{
semi()
newlineOpt()
}
else
{
spaceOpt()
needSemi = true
}
_while()
spaceOpt()
leftParen()
accept(x.getCondition())
rightParen()
}
override fun visitEmpty(x:JsEmpty) {}
override fun visitExpressionStatement(x:JsExpressionStatement) {
val surroundWithParentheses = JsFirstExpressionVisitor.exec(x)
if (surroundWithParentheses)
{
leftParen()
}
val expr = x.expression
if (expr is JsFunction) {
expr.shouldPrintName = true
}
accept(expr)
if (surroundWithParentheses)
{
rightParen()
}
}
override fun visitFor(x: JsFor) {
_for()
spaceOpt()
leftParen()
// The init expressions or var decl.
//
if (x.getInitExpression() != null)
{
accept(x.getInitExpression())
}
else if (x.getInitVars() != null)
{
accept(x.getInitVars())
}
semi()
// The loop test.
//
if (x.getCondition() != null)
{
spaceOpt()
accept(x.getCondition())
}
semi()
// The incr expression.
//
if (x.getIncrementExpression() != null)
{
spaceOpt()
accept(x.getIncrementExpression())
}
rightParen()
nestedPush(x.getBody())
accept(x.getBody())
nestedPop(x.getBody())
}
override fun visitForIn(x:JsForIn) {
wtf("visitForIn 7cd8a5a3-136d-4a4a-bfd4-78502e2dd11c")
// _for()
// spaceOpt()
// leftParen()
// if (x.getIterVarName() != null)
// {
// printVar()
// space()
// nameDef(x.getIterVarName())
// if (x.getIterExpression() != null)
// {
// spaceOpt()
// assignment()
// spaceOpt()
// accept(x.getIterExpression())
// }
// }
// else
// {
// // Just a name ref.
// //
// accept(x.getIterExpression())
// }
// space()
// p.print(CHARS_IN)
// space()
// accept(x.getObjectExpression())
// rightParen()
// nestedPush(x.getBody())
// accept(x.getBody())
// nestedPop(x.getBody())
}
override fun visitFunction(x: JsFunction) {
val shouldDumpBodyToContainer = x.declarationDescriptor?.annotations
?.any {it.type.typeName == "photlin.PHPDumpBodyToContainer"}
?: false
if (!shouldDumpBodyToContainer) {
printDebugTag(x)
p.print(CHARS_FUNCTION)
if (x.declarationDescriptor != null) {
val functionDescriptor = x.declarationDescriptor as? FunctionDescriptor
?: wtf("19b83dc5-1876-4a36-a82a-7feb392655d8")
if (functionDescriptor.returnType?.typeName == "kotlin.Array") {
p.print("&")
}
}
space()
if (x.getName() != null && x.shouldPrintName)
{
nameOf(x)
}
leftParen()
var notFirst = false
for (element in x.getParameters())
{
val param = element as JsParameter
notFirst = sepCommaOptSpace(notFirst)
accept(param)
}
rightParen()
space()
if (x.useNames.isNotEmpty()) {
p.print("use (")
for ((i, nameRef) in x.useNames.withIndex()) {
if (i > 0) p.print(", ")
if (isByRefShit(nameRef)) p.print("&")
p.print("$" + escapeIdent(nameRef.ident))
}
p.print(")")
}
lineBreakAfterBlock = false
}
accept(x.getBody())
needSemi = true
}
override fun visitIf(x:JsIf) {
_if()
spaceOpt()
leftParen()
accept(x.getIfExpression())
rightParen()
var thenStmt = x.getThenStatement()
var elseStatement = x.getElseStatement()
// @fucking if-then-else printing
thenStmt = JsBlock(thenStmt)
elseStatement = JsBlock(elseStatement)
if (elseStatement != null && thenStmt is JsIf && (thenStmt as JsIf).getElseStatement() == null)
{
thenStmt = JsBlock(thenStmt)
}
nestedPush(thenStmt)
accept(thenStmt)
nestedPop(thenStmt)
if (elseStatement != null)
{
if (needSemi)
{
semi()
newlineOpt()
}
else
{
spaceOpt()
needSemi = true
}
p.print(CHARS_ELSE)
val elseIf = elseStatement is JsIf
if (!elseIf)
{
nestedPush(elseStatement)
}
else
{
space()
}
accept(elseStatement)
if (!elseIf)
{
nestedPop(elseStatement)
}
}
}
// override fun visitPHPVarRef(varRef: PHPVarRef) {
// printDebugTag(varRef)
// p.print("$" + escapeDollar(varRef.getIdent()))
// }
override fun visitPHPGlobalVarRef(varRef: PHPGlobalVarRef) {
printDebugTag(varRef)
p.print("\$GLOBALS['" + escapeIdent(varRef.getIdent()) + "']")
}
// override fun visitPHPFieldRef(x: PHPFieldRef) {
// accept(x.receiver)
// p.print("->${x.fieldName}")
// }
override fun visitPHPMethodCall(call: PHPMethodCall) {
accept(call.receiver)
printDebugTag(call, spaceBefore = true)
p.print("->${call.methodName}")
leftParen()
printExpressions(call.arguments)
rightParen()
}
override fun visitPHPStaticMethodCall(call: PHPStaticMethodCall) {
p.print("${call.className}::${call.methodName}")
leftParen()
printExpressions(call.arguments)
rightParen()
}
// override fun visitPHPInvocation(invocation: PHPInvocation) {
//// val c = invocation.callee
// accept(invocation.callee)
//
// leftParen()
// printExpressions(invocation.arguments)
// rightParen()
// }
override fun visitInvocation(invocation: JsInvocation) {
printDebugTag(invocation)
val callee = invocation.qualifier
if (callee is JsNameRef) {
if (callee.qualifier?.kotlinTypeName == "kotlin.String") {
"break on me"
val builtInFunction = when (callee.ident) {
"charCodeAt" -> "Kotlin::charCodeAt"
"substring" -> "Kotlin::substring"
"split" -> "pizdasplit"
else -> wtf("d140179a-26b4-4726-bd6d-be69c62f42ed callee.ident = ${callee.ident}")
// else -> "pizdunishka"
}
p.print("$builtInFunction(")
accept(callee.qualifier)
p.print(", ")
printExpressions(invocation.arguments)
p.print(")")
return
}
accept(callee)
// printPair(invocation, callee)
} else {
pizdavalue {gen-> gen.accept(callee)}
}
leftParen()
printExpressions(invocation.arguments)
rightParen()
}
override fun visitLabel(x:JsLabel) {
nameOf(x)
_colon()
spaceOpt()
accept(x.getStatement())
}
override fun visitNameRef(nameRef: JsNameRef) {
printDebugTag(nameRef)
if (nameRef.suppressWarnings)
p.print("@")
exhaustive=when (nameRef.kind) {
PHPNameRefKind.STRING_LITERAL -> {
if (nameRef.qualifier != null) {
wtf("STRING_LITERAL with qualifier 210ac0a8-eaf1-44fe-933f-4e78a7cf07a6")
}
p.print("'" + escapeIdent(nameRef.ident) + "'")
return
}
PHPNameRefKind.GLOBAL_VAR -> {
if (nameRef.qualifier != null) {
wtf("GLOBALVAR with qualifier 1325766c-29a4-44f9-b773-428a4f097e84")
}
p.print("\$GLOBALS['" + escapeIdent(nameRef.getIdent()) + "']")
}
PHPNameRefKind.VAR -> {
if (nameRef.qualifier != null) {
wtf("VAR with qualifier 562283b3-071e-4fac-bcae-6be7f2fbc1ba")
}
p.print("$" + escapeIdent(nameRef.ident))
return
}
PHPNameRefKind.FIELD -> {
val qualifier = nameRef.qualifier
if (qualifier != null) {
if (nameRef.qualifier?.kotlinTypeName == "kotlin.String") {
val builtInFunction = when (nameRef.ident) {
"length" -> "strlen"
else -> wtf("39e634a3-a9c7-4cef-bc57-01bd2e4ae195 nameRef.ident = ${nameRef.ident}")
}
p.print("$builtInFunction(")
accept(nameRef.qualifier)
p.print(")")
return
}
}
accept(nameRef.qualifier)
p.print("->${escapeIdent(nameRef.ident)}")
return
}
PHPNameRefKind.STATIC -> {
accept(nameRef.qualifier)
p.print("::${escapeIdent(nameRef.ident)}")
return
}
PHPNameRefKind.LAMBDA,
PHPNameRefKind.LAMBDA_CREATOR -> {
val varName = "pizda_" + PhotlincDebugGlobal.nextDebugTag()
// if (varName == "pizda_3485") {
// "break on me"
// }
val crappyPHPLambda = StringBuilder()-{s->
s.append("function(")
val callableDescriptor = nameRef.callableDescriptor ?: wtf("ddb4e1a5-457a-4d51-b5d5-b999247e0b07")
val paramDescriptors = when (nameRef.kind) {
PHPNameRefKind.LAMBDA_CREATOR -> nameRef.additionalArgDescriptors ?: listOf()
else -> callableDescriptor.valueParameters + (nameRef.additionalArgDescriptors ?: listOf())
}
for ((i, valueParameter) in paramDescriptors.withIndex()) {
if (i > 0)
s.append(", ")
if (valueParameter is ValueDescriptor) {
if (valueParameter.type.typeName == "kotlin.Array")
s.append("&")
}
s.append("\$p$i")
}
s.append(") {")
s.append("return ${escapeIdent(nameRef.ident)}(")
for (i in 0..paramDescriptors.lastIndex) {
if (i > 0)
s.append(", ")
s.append("\$p$i")
}
s.append(");")
s.append("}")
}
printLineAbove("\$$varName = $crappyPHPLambda;")
p.print("\$$varName")
return
}
PHPNameRefKind.DUNNO -> {
val qualifier = nameRef.qualifier
if (qualifier != null)
{
if (nameRef.qualifier?.kotlinTypeName == "kotlin.String") {
val builtInFunction = when (nameRef.ident) {
"length" -> "strlen"
else -> wtf("3c1a8c8c-4fe0-4d8b-bd4f-2bcab38a84f5 nameRef.ident = ${nameRef.ident}")
}
p.print("$builtInFunction(")
accept(nameRef.qualifier)
p.print(")")
return
}
var enclose:Boolean
if (qualifier is JsLiteral.JsValueLiteral)
{
// "42.foo" is not allowed, but "(42).foo" is.
enclose = qualifier is JsNumberLiteral
}
else
{
enclose = parenCalc(nameRef, qualifier, false)
}
if (qualifier !is JsNameRef)
enclose = false
if (enclose)
{
leftParen()
}
if (qualifier !is JsNameRef) {
// "break on me"
pizdavalue {gen-> gen.accept(qualifier)}
} else {
accept(qualifier)
}
if (enclose)
{
rightParen()
}
p.print("->")
}
p.maybeIndent()
beforeNodePrinted(nameRef)
p.print(escapeIdent(nameRef.ident))
}
}
}
private fun printLineAbove(s: String) {
try {
val out = (p as TextOutputImpl).out
var index = out.length - 1
while (out[index] != '\n' && index > 0) {
--index
}
if (out[index] == '\r' && index > 0)
--index
out.insert(index, "\n$s")
} catch(e: StringIndexOutOfBoundsException) {
"break on me"
throw e
}
}
private fun printDebugTag(shit: AbstractNode, spaceBefore: Boolean = false) {
val debugTag = shit.debugTag
if (debugTag != null) {
if (debugTag == PhotlincDebugGlobal.breakOnDebugTag) {
"break on me"
}
// val mappedFrom = shit.mappedFromDebugTag?.let {"<$it>"} ?: ""
val mappedFrom = ""
p.printTagged(spaceBefore.ifOrEmpty{" "} + debugTag + mappedFrom + "@")
}
}
fun escapeIdent(s: String): String {
// PHP reserved words and alike
if (s == "die") return "die__photlin_umri_skotina"
if (s == "const") return "const__photlin_konstantinovich"
if (s == "split") return "split__photlin_v_zhopu_zalit"
return s.replace("$", "__dollar__")
}
protected fun beforeNodePrinted(node:JsNode) {}
override fun visitNew(x: JsNew) {
printDebugTag(x)
p.print(CHARS_NEW)
space()
val constructorExpression = x.getConstructorExpression()
val needsParens = JsConstructExpressionVisitor.exec(constructorExpression)
if (needsParens)
{
leftParen()
}
accept(constructorExpression)
if (needsParens)
{
rightParen()
}
leftParen()
printExpressions(x.getArguments())
rightParen()
}
override fun visitNull(x:JsNullLiteral) {
printDebugTag(x)
p.print(CHARS_NULL)
}
override fun visitInt(x:JsIntLiteral) {
p.print(x.value)
}
override fun visitDouble(x:JsDoubleLiteral) {
p.print(x.value)
}
override fun visitObjectLiteral(objectLiteral: JsObjectLiteral) {
printDebugTag(objectLiteral)
if (objectLiteral.propertyInitializers.isEmpty()) {
p.print("new stdClassWithPhotlinProps()")
} else {
// imf("Generate non-empty object literal 653f3b11-ea9c-4f14-9b41-7d17a44c2d0d")
p.print("array(")
if (objectLiteral.isMultiline)
{
p.indentIn()
}
var notFirst = false
for (item in objectLiteral.propertyInitializers)
{
if (notFirst)
{
p.print(',')
}
if (objectLiteral.isMultiline)
{
newlineOpt()
}
else if (notFirst)
{
spaceOpt()
}
notFirst = true
val labelExpr = item.labelExpr
// labels can be either string, integral, or decimal literals
p.print("'")
if (labelExpr is JsNameRef)
{
p.print((labelExpr as JsNameRef).ident)
}
else if (labelExpr is JsStringLiteral)
{
p.print((labelExpr as JsStringLiteral).value)
}
else
{
accept(labelExpr)
}
p.print("'")
p.print(" => ")
// _colon()
space()
val valueExpr = item.valueExpr
val wasEnclosed = parenPushIfCommaExpression(valueExpr)
accept(valueExpr)
if (wasEnclosed)
{
rightParen()
}
}
if (objectLiteral.isMultiline())
{
p.indentOut()
newlineOpt()
}
p.print(')')
}
}
fun isByRefShit(node: JsNode): Boolean {
return node.kotlinTypeName == "kotlin.Array"
}
override fun visitParameter(x: JsParameter) {
printDebugTag(x)
if (isByRefShit(x)) {
p.print("&")
}
p.print("$" + escapeIdent(x.name.ident))
}
override fun visitPostfixOperation(x:JsPostfixOperation) {
val op = x.getOperator()
val arg = x.getArg()
// unary operators always associate correctly (I think)
printPair(x, arg)
p.print(op.getSymbol())
}
override fun visitPrefixOperation(x:JsPrefixOperation) {
val op = x.getOperator()
p.print(op.getSymbol())
val arg = x.getArg()
if (spaceCalc(op, arg))
{
space()
}
// unary operators always associate correctly (I think)
printPair(x, arg)
}
override fun visitProgram(x:JsProgram) {
p.print("<JsProgram>")
}
override fun visitProgramFragment(x:JsProgramFragment) {
p.print("<JsProgramFragment>")
}
override fun visitRegExp(x:JsRegExp) {
slash()
p.print(x.getPattern())
slash()
val flags = x.getFlags()
if (flags != null)
{
p.print(flags)
}
}
override fun visitReturn(x:JsReturn) {
printDebugTag(x)
p.print(CHARS_RETURN)
val expr = x.getExpression()
if (expr != null)
{
space()
accept(expr)
}
}
override fun visitString(x:JsStringLiteral) {
p.print(phpString(x.value, forceDoubleQuote = true))
}
override fun visit(x:JsSwitch) {
p.print(CHARS_SWITCH)
spaceOpt()
leftParen()
accept(x.getExpression())
rightParen()
spaceOpt()
blockOpen()
acceptList(x.getCases())
blockClose()
}
override fun visitThis(x:JsLiteral.JsThisRef) {
p.print(CHARS_THIS)
}
override fun visitThrow(x: JsThrow) {
printDebugTag(x)
p.print(CHARS_THROW)
space()
accept(x.expression)
}
override fun visitTry(x:JsTry) {
p.print(CHARS_TRY)
spaceOpt()
accept(x.getTryBlock())
acceptList(x.getCatches())
val finallyBlock = x.getFinallyBlock()
if (finallyBlock != null)
{
p.print(CHARS_FINALLY)
spaceOpt()
accept(finallyBlock)
}
}
override fun visit(v: JsVar) {
v.propertyDescriptor?.let {printAnnotations(it, v)}
v.visibility?.let {p.print("$it ")}
printDebugTag(v)
p.print("$" + escapeIdent(v.name.ident))
val initExpr = v.initExpression
if (initExpr != null) {
spaceOpt()
// if (v.debugTag == DebugGlobal.breakOnDebugTag) {
// "break on me"
// }
assignment(byRef = isByRefShit(v) && initExpr is JsNameRef)
spaceOpt()
val isEnclosed = parenPushIfCommaExpression(initExpr)
accept(initExpr)
if (isEnclosed)
{
rightParen()
}
}
}
override fun visitVars(vars: JsVars) {
space()
var sep = false
for (v in vars)
{
if (sep)
{
if (vars.isMultiline)
{
newlineOpt()
}
spaceOpt()
}
else
{
sep = true
}
accept(v)
p.print(';')
}
}
override fun visitDocComment(comment:JsDocComment) {
val asSingleLine = comment.getTags().size === 1
if (!asSingleLine)
{
newlineOpt()
}
p.print("/**")
if (asSingleLine)
{
space()
}
else
{
p.newline()
}
var notFirst = false
for (entry in comment.getTags().entries)
{
if (notFirst)
{
p.newline()
p.print(' ')
p.print('*')
}
else
{
notFirst = true
}
p.print('@')
p.print(entry.key)
val value = entry.value
if (value != null)
{
space()
if (value is CharSequence)
{
p.print(value as CharSequence)
}
else
{
visitNameRef(value as JsNameRef)
}
}
if (!asSingleLine)
{
p.newline()
}
}
if (asSingleLine)
{
space()
}
else
{
newlineOpt()
}
p.print('*')
p.print('/')
if (asSingleLine)
{
spaceOpt()
}
}
protected fun newlineOpt() {
if (!p.isCompact())
{
p.newline()
}
// @debug
// val breakOnLine = 37
// if (p.line == breakOnLine - 1) {
// "break on me"
// }
}
protected fun printJsBlock(x:JsBlock, _finalNewline:Boolean) {
var finalNewline = _finalNewline
if (!lineBreakAfterBlock)
{
finalNewline = false
lineBreakAfterBlock = true
}
val needBraces = !x.isGlobalBlock()
if (needBraces)
{
blockOpen()
}
val iterator = x.getStatements().iterator()
while (iterator.hasNext())
{
val isGlobal = x.isGlobalBlock() || globalBlocks.contains(x)
val statement = iterator.next()
if (statement is JsEmpty)
{
continue
}
needSemi = true
var stmtIsGlobalBlock = false
if (isGlobal)
{
if (statement is JsBlock)
{
// A block inside a global block is still considered global
stmtIsGlobalBlock = true
globalBlocks.add(statement as JsBlock)
}
}
val commentedOut = statement is AbstractNode && statement.commentedOut
if (commentedOut) p.print("/*")
accept(statement)
if (commentedOut) p.print("*/")
if (stmtIsGlobalBlock)
{
globalBlocks.remove(statement)
}
if (needSemi)
{
/*
* Special treatment of function declarations: If they are the only item in a
* statement (i.e. not part of an assignment operation), just give them
* a newline instead of a semi.
*/
val functionStmt = statement is JsExpressionStatement && (statement as JsExpressionStatement).getExpression() is JsFunction
/*
* Special treatment of the last statement in a block: only a few
* statements at the end of a block require semicolons.
*/
val lastStatement = !iterator.hasNext() && needBraces && !JsRequiresSemiVisitor.exec(statement)
if (functionStmt)
{
if (lastStatement)
{
newlineOpt()
}
else
{
p.newline()
}
}
else
{
if (lastStatement)
{
p.printOpt(';')
}
else
{
semi()
}
newlineOpt()
}
}
}
if (needBraces)
{
// _blockClose() modified
p.indentOut()
p.print('}')
if (finalNewline)
{
newlineOpt()
}
}
needSemi = false
}
private fun assignment(byRef: Boolean) {
p.print('=')
if (byRef) p.print('&')
}
private fun blockClose() {
p.indentOut()
p.print('}')
newlineOpt()
}
private fun blockOpen() {
p.print('{')
p.indentIn()
newlineOpt()
}
private fun _colon() {
p.print(':')
}
private fun _for() {
p.print(CHARS_FOR)
}
private fun _if() {
p.print(CHARS_IF)
}
private fun leftParen() {
p.print('(')
}
private fun leftSquare() {
p.print('[')
}
private fun nameDef(name: JsName) {
// printDebugTag(name)
p.print(escapeIdent(name.ident))
}
private fun nameOf(hasName: HasName) {
nameDef(hasName.name)
}
private fun nestedPop(statement:JsStatement):Boolean {
val pop = !(statement is JsBlock)
if (pop)
{
p.indentOut()
}
return pop
}
private fun nestedPush(statement:JsStatement):Boolean {
val push = !(statement is JsBlock)
if (push)
{
newlineOpt()
p.indentIn()
}
else
{
spaceOpt()
}
return push
}
private fun _parenPopOrSpace(parent:JsExpression, child:JsExpression, wrongAssoc:Boolean):Boolean {
val doPop = parenCalc(parent, child, wrongAssoc)
if (doPop)
{
rightParen()
}
else
{
space()
}
return doPop
}
private fun parenPush(parent:JsExpression, child:JsExpression, wrongAssoc:Boolean):Boolean {
val doPush = parenCalc(parent, child, wrongAssoc)
if (doPush)
{
leftParen()
}
return doPush
}
private fun parenPushIfCommaExpression(x:JsExpression):Boolean {
val doPush = x is JsBinaryOperation && (x as JsBinaryOperation).getOperator() === JsBinaryOperator.COMMA
if (doPush)
{
leftParen()
}
return doPush
}
private fun _parenPushOrSpace(parent:JsExpression, child:JsExpression, wrongAssoc:Boolean):Boolean {
val doPush = parenCalc(parent, child, wrongAssoc)
if (doPush)
{
leftParen()
}
else
{
space()
}
return doPush
}
private fun rightParen() {
p.print(')')
}
private fun rightSquare() {
p.print(']')
}
private fun semi() {
p.print(';')
}
private fun sepCommaOptSpace(sep:Boolean):Boolean {
if (sep)
{
p.print(',')
spaceOpt()
}
return true
}
private fun slash() {
p.print('/')
}
private fun space() {
p.print(' ')
}
private fun spaceOpt() {
p.printOpt(' ')
}
private fun printVar() {
p.print(CHARS_VAR)
}
private fun _while() {
p.print(CHARS_WHILE)
}
companion object {
private val CHARS_BREAK = "break".toCharArray()
private val CHARS_CASE = "case".toCharArray()
private val CHARS_CATCH = "catch".toCharArray()
private val CHARS_CONTINUE = "continue".toCharArray()
private val CHARS_DEBUGGER = "debugger".toCharArray()
private val CHARS_DEFAULT = "default".toCharArray()
private val CHARS_DO = "do".toCharArray()
private val CHARS_ELSE = "else".toCharArray()
private val CHARS_FALSE = "false".toCharArray()
private val CHARS_FINALLY = "finally".toCharArray()
private val CHARS_FOR = "for".toCharArray()
private val CHARS_FUNCTION = "function".toCharArray()
private val CHARS_IF = "if".toCharArray()
private val CHARS_IN = "in".toCharArray()
private val CHARS_NEW = "new".toCharArray()
private val CHARS_NULL = "NULL".toCharArray()
private val CHARS_RETURN = "return".toCharArray()
private val CHARS_SWITCH = "switch".toCharArray()
private val CHARS_THIS = "this".toCharArray()
private val CHARS_THROW = "throw".toCharArray()
private val CHARS_TRUE = "true".toCharArray()
private val CHARS_TRY = "try".toCharArray()
private val CHARS_VAR = "var".toCharArray()
private val CHARS_WHILE = "while".toCharArray()
private val HEX_DIGITS = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F')
fun javaScriptString(value:String):CharSequence {
return phpString(value, false)
}
/**
* Generate JavaScript code that evaluates to the supplied string. Adapted
* from {@link org.mozilla.javascript.ScriptRuntime#escapeString(String)}
* . The difference is that we quote with either " or ' depending on
* which one is used less inside the string.
*/
fun phpString(chars: CharSequence, forceDoubleQuote: Boolean = false):CharSequence {
val n = chars.length
var quoteCount = 0
var aposCount = 0
for (i in 0..n - 1)
{
when (chars.get(i)) {
'"' -> ++quoteCount
'\'' -> ++aposCount
}
}
val result = StringBuilder(n + 16)
val quoteChar = if ((quoteCount < aposCount || forceDoubleQuote)) '"' else '\''
result.append(quoteChar)
for (i in 0..n - 1)
{
val c = chars.get(i)
if (' ' <= c && c <= '~' && c != quoteChar && c != '\\' && c != '$')
{
// an ordinary print character (like C isprint())
result.append(c)
continue
}
var escape = -1
when (c) {
'\b' -> escape = 'b'.toInt()
// '\f' -> escape = 'f'
'\n' -> escape = 'n'.toInt()
'\r' -> escape = 'r'.toInt()
'\t' -> escape = 't'.toInt()
'"' -> escape = '"'.toInt()
'\'' -> escape = '\''.toInt()
'\\' -> escape = '\\'.toInt()
'$' -> escape = '$'.toInt()
}// only reach here if == quoteChar
// only reach here if == quoteChar
if (escape >= 0)
{
// an \escaped sort of character
result.append('\\')
result.append(escape.toChar())
}
else
{
val hexSize:Int
if (c.toInt() < 256)
{
// 2-digit hex
result.append("\\x")
hexSize = 2
}
else
{
// Unicode.
result.append("\\u")
hexSize = 4
}
// append hexadecimal form of ch left-padded with 0
var shift = (hexSize - 1) * 4
while (shift >= 0)
{
val digit = 0xf and (c.toInt() shr shift)
result.append(HEX_DIGITS[digit])
shift -= 4
}
}
}
result.append(quoteChar)
escapeClosingTags(result)
return result
}
/**
* Escapes any closing XML tags embedded in <code>str</code>, which could
* potentially cause a parse failure in a browser, for example, embedding a
* closing <code><script></code> tag.
*
* @param str an unescaped literal; May be null
*/
private fun escapeClosingTags(str:StringBuilder) {
if (str == null)
{
return
}
var index = 0
while (true) {
index = str.indexOf("</", index)
if (index == -1) break
str.insert(index + 1, '\\')
}
}
private fun parenCalc(parent:JsExpression, child:JsExpression, wrongAssoc:Boolean):Boolean {
val parentPrec = JsPrecedenceVisitor.exec(parent)
val childPrec = JsPrecedenceVisitor.exec(child)
return parentPrec > childPrec || parentPrec == childPrec && wrongAssoc
}
/**
* Decide whether, if <code>op</code> is printed followed by <code>arg</code>,
* there needs to be a space between the operator and expression.
*
* @return <code>true</code> if a space needs to be printed
*/
private fun spaceCalc(op:JsOperator, arg:JsExpression):Boolean {
if (op.isKeyword())
{
return true
}
if (arg is JsBinaryOperation)
{
val binary = arg as JsBinaryOperation
/*
* If the binary operation has a higher precedence than op, then it won't
* be parenthesized, so check the first argument of the binary operation.
*/
return binary.getOperator().getPrecedence() > op.getPrecedence() && spaceCalc(op, binary.getArg1())
}
if (arg is JsPrefixOperation)
{
val op2 = (arg as JsPrefixOperation).getOperator()
return (op === JsBinaryOperator.SUB || op === JsUnaryOperator.NEG) && (op2 === JsUnaryOperator.DEC || op2 === JsUnaryOperator.NEG) || (op === JsBinaryOperator.ADD && op2 === JsUnaryOperator.INC)
}
if (arg is JsNumberLiteral && (op === JsBinaryOperator.SUB || op === JsUnaryOperator.NEG))
{
if (arg is JsIntLiteral)
{
return (arg as JsIntLiteral).value < 0
}
else
{
assert(arg is JsDoubleLiteral)
return (arg as JsDoubleLiteral).value < 0
}
}
return false
}
}
}
| apache-2.0 | 79e53e08ca6de6a2a00038da0dc5aa5b | 29.983439 | 210 | 0.483718 | 4.641603 | false | false | false | false |
GunoH/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/r/inlays/dataframe/columns/ColumnType.kt | 7 | 4103 | /*
* 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.notebooks.visualization.r.inlays.dataframe.columns
sealed class Type<out T> {
open fun mkNullable(): Type<T?> = this
fun isNullable(): Boolean = mkNullable() == this
open fun isArray(): Boolean = false
/** Upgrade method is used in loading csv data from Zeppelin. */
open fun upgrade(type: Type<*>? ) : Type<*>? {
return null
}
open fun createDataArray() : ArrayList<*> {
return ArrayList<T>()
}
abstract fun createDataColumn(name: String,data: ArrayList<*>) : Column<*>
abstract fun appendToDataArray(array: ArrayList<*>, data: String)
}
object IntArrayType : Type<ArrayList<Int>>() {
override fun isArray(): Boolean = true
@Suppress("UNCHECKED_CAST")
override fun createDataColumn(name: String, data: ArrayList<*>) : Column<*> {
return IntArrayColumn(name, data as ArrayList<ArrayList<Int>>)
}
override fun appendToDataArray(array: ArrayList<*>, data: String) {
throw Exception("Should not be called")
}
}
object DoubleArrayType : Type<ArrayList<Double>>() {
override fun isArray(): Boolean = true
@Suppress("UNCHECKED_CAST")
/** data should be ArrayList<ArrayList<Double>> */
override fun createDataColumn(name: String, data: ArrayList<*>) : Column<*> {
return DoubleArrayColumn(name, data as ArrayList<ArrayList<Double>>)
}
override fun appendToDataArray(array: ArrayList<*>, data: String) {
throw Exception("Should not be called")
}
}
object StringArrayType : Type<ArrayList<String?>>() {
override fun isArray(): Boolean = true
@Suppress("UNCHECKED_CAST")
/** data should be ArrayList<ArrayList<String?>> */
override fun createDataColumn(name: String, data: ArrayList<*>) : Column<*> {
return StringArrayColumn(name, data as ArrayList<ArrayList<String?>>)
}
override fun appendToDataArray(array: ArrayList<*>, data: String) {
throw Exception("Should not be called")
}
}
object IntType : Type<Int>() {
/** IntType could be upgraded to
* DoubleType if incoming type is DoubleType
* StringType if incoming type is any other. */
override fun upgrade(type: Type<*>? ) : Type<*> {
return when(type) {
null -> IntType
IntType -> IntType
DoubleType -> DoubleType
else -> StringType
}
}
@Suppress("UNCHECKED_CAST")
/** data should be ArrayList<Int> */
override fun createDataColumn(name: String, data: ArrayList<*>) : Column<*> {
return IntColumn(name, data as ArrayList<Int>)
}
@Suppress("UNCHECKED_CAST")
/** data should be ArrayList<Int> */
override fun appendToDataArray(array: ArrayList<*>, data: String) {
(array as ArrayList<Int>).add(if( data.isEmpty() || data == "null") Int.MIN_VALUE else data.toInt())
}
}
object DoubleType : Type<Double>() {
override fun upgrade(type: Type<*>? ) : Type<*> {
return when(type) {
null -> DoubleType
IntType -> DoubleType
DoubleType ->DoubleType
else -> StringType
}
}
@Suppress("UNCHECKED_CAST")
/** data should be ArrayList<Double> */
override fun createDataColumn(name: String, data: ArrayList<*>) : Column<*> {
return DoubleColumn(name, data as ArrayList<Double>)
}
@Suppress("UNCHECKED_CAST")
/** data should be ArrayList<Double> */
override fun appendToDataArray(array: ArrayList<*>, data: String) {
(array as ArrayList<Double>).add(if( data.isEmpty() || data == "null") Double.NaN else data.toDouble())
}
}
object StringType : Type<String?>() {
override fun upgrade(type: Type<*>? ) : Type<*> {
return StringType
}
@Suppress("UNCHECKED_CAST")
/** data should be ArrayList<String?> */
override fun createDataColumn(name: String, data: ArrayList<*>) : Column<*> {
return StringColumn(name, data as ArrayList<String?>)
}
@Suppress("UNCHECKED_CAST")
/** data should be ArrayList<String?> */
override fun appendToDataArray(array: ArrayList<*>, data: String) {
(array as ArrayList<String?>).add(data)
}
}
| apache-2.0 | 631132c46fc160079c772f066bb49f94 | 29.392593 | 140 | 0.672679 | 4.136089 | false | false | false | false |
fossasia/rp15 | app/src/main/java/org/fossasia/openevent/general/feedback/FeedbackViewHolder.kt | 2 | 739 | package org.fossasia.openevent.general.feedback
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_feedback.view.commentTv
import kotlinx.android.synthetic.main.item_feedback.view.ratingBar
const val MAX_COMMENT_LINE = 3
class FeedbackViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(feedback: Feedback) {
itemView.commentTv.text = feedback.comment
itemView.ratingBar.rating = feedback.rating?.toFloat() ?: 0f
itemView.commentTv.setOnClickListener {
itemView.commentTv.maxLines =
if (itemView.commentTv.maxLines == MAX_COMMENT_LINE) Int.MAX_VALUE else MAX_COMMENT_LINE
}
}
}
| apache-2.0 | c94fa1f3879688ce6ad32d19f1f343db | 34.190476 | 104 | 0.738836 | 4.175141 | false | false | false | false |
matthieucoisne/LeagueChampions | libraries/core/src/main/java/com/leaguechampions/libraries/core/data/repository/NetworkBoundResource.kt | 1 | 2173 | package com.leaguechampions.libraries.core.data.repository
import androidx.annotation.MainThread
import androidx.annotation.WorkerThread
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.leaguechampions.libraries.core.utils.Resource
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlin.coroutines.coroutineContext
abstract class NetworkBoundResource<RequestType, ResultType> {
private val result = MutableLiveData<Resource<ResultType>>()
private val supervisorJob = SupervisorJob()
suspend fun build(): NetworkBoundResource<RequestType, ResultType> {
setValue(Resource.Loading())
CoroutineScope(coroutineContext).launch(Dispatchers.IO + supervisorJob) {
val dbResult = loadFromDb()
if (shouldFetch(dbResult)) {
try {
fetchFromNetwork(dbResult)
} catch (e: Exception) {
setValue(Resource.Error(e.toString(), loadFromDb()))
}
} else {
setValue(Resource.Success(dbResult!!))
}
}
return this
}
fun asLiveData() = result as LiveData<Resource<ResultType>>
private suspend fun fetchFromNetwork(dbResult: ResultType?) {
setValue(Resource.Loading(dbResult))
val apiResponse = createCall()
saveCallResults(processResponse(apiResponse))
setValue(Resource.Success(loadFromDb()!!))
}
@MainThread
private fun setValue(newValue: Resource<ResultType>) {
if (result.value != newValue) {
result.postValue(newValue)
}
}
@MainThread
protected abstract fun shouldFetch(data: ResultType?): Boolean
@MainThread
protected abstract suspend fun createCall(): RequestType
@WorkerThread
protected abstract fun processResponse(response: RequestType): RequestType
@WorkerThread
protected abstract suspend fun saveCallResults(data: RequestType)
@MainThread
protected abstract suspend fun loadFromDb(): ResultType?
}
| apache-2.0 | 4b1fcedb83686e82fe6c8ed1de242a5a | 31.432836 | 81 | 0.695812 | 5.236145 | false | false | false | false |
OpenConference/OpenConference-android | app/src/main/java/com/openconference/model/database/dao/SessionDaoSqlite.kt | 1 | 7520 | package com.openconference.model.database.dao
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import com.hannesdorfmann.sqlbrite.dao.Dao
import com.openconference.model.Session
import com.openconference.model.database.SessionDateTimeComparator
import com.openconference.util.putOrNull
import com.squareup.sqlbrite.BriteDatabase
import rx.Observable
/**
* Data-Access-Object for [com.droidcon.model.Session]
*
* @author Hannes Dorfmann
*/
open class SessionDaoSqlite : SessionDao, Dao() {
companion object {
const val TABLE = "Session"
const val COL_ID = "id"
const val COL_TITLE = "title"
const val COL_DESCRIPTION = "description"
const val COL_TAGS = "tags"
const val COL_START_TIME = "startTime"
const val COL_END_TIME = "endTime"
const val COL_FAVORITE = "favorite"
const val COL_LOCATION_ID = "locationId"
const val COL_LOCATION_NAME = "locationName"
const val COL_SPEAKER_ID = "speakerId"
const val COL_SPEAKER_NAME = "speakerName"
const val COL_SPEAKER_PIC = "speakerPicture"
const val COL_SPEAKER_COMPANY = "speakerCompany"
const val COL_SPEAKER_JOBTITLE = "speakerJobTitle"
}
/**
* Internal sql table for n:m relation between speaker and session
*/
private object GiveTalk {
const val TABLE = "GiveTalk"
const val COL_SESSION_ID = "sessionId"
const val COL_SPEAKER_ID = "speakerId"
}
private val sortByStartDate = SessionDateTimeComparator()
override fun createTable(database: SQLiteDatabase) {
CREATE_TABLE(TABLE,
"${COL_ID} VARCHAR(40) PRIMARY KEY NOT NULL",
"${COL_TITLE} TEXT NOT NULL",
"${COL_DESCRIPTION} TEXT",
"${COL_START_TIME} BIGINTEGER",
"${COL_END_TIME} BIGINTEGER",
"${COL_TAGS} TEXT",
"$COL_LOCATION_ID VARCHAR(20)",
"$COL_FAVORITE BOOLEAN DEFAULT FALSE",
"FOREIGN KEY($COL_LOCATION_ID) REFERENCES ${LocationDaoSqlite.TABLE}(${LocationDaoSqlite.COL_ID}) ON DELETE SET NULL"
).execute(database)
CREATE_TABLE(GiveTalk.TABLE,
"${GiveTalk.COL_SESSION_ID} VARCHAR(40) NOT NULL",
"${GiveTalk.COL_SPEAKER_ID} VARCHAR(20) NOT NULL",
"PRIMARY KEY(${GiveTalk.COL_SESSION_ID}, ${GiveTalk.COL_SPEAKER_ID})",
"FOREIGN KEY(${GiveTalk.COL_SESSION_ID}) REFERENCES ${TABLE}($COL_ID) ON DELETE CASCADE",
"FOREIGN KEY(${GiveTalk.COL_SPEAKER_ID}) REFERENCES ${SpeakerDaoSqlite.TABLE}(${SpeakerDaoSqlite.COL_ID}) ON DELETE CASCADE"
).execute(database)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
}
private inline fun selectAll() = SELECT(
"$TABLE.$COL_ID AS $COL_ID",
COL_TITLE,
COL_DESCRIPTION,
COL_START_TIME,
COL_END_TIME,
COL_TAGS,
COL_FAVORITE,
"${LocationDaoSqlite.TABLE}.${LocationDaoSqlite.COL_ID} AS $COL_LOCATION_ID",
"${LocationDaoSqlite.TABLE}.${LocationDaoSqlite.COL_NAME} AS $COL_LOCATION_NAME",
"${SpeakerDaoSqlite.TABLE}.${SpeakerDaoSqlite.COL_ID} AS $COL_SPEAKER_ID",
"${SpeakerDaoSqlite.TABLE}.${SpeakerDaoSqlite.COL_NAME} AS $COL_SPEAKER_NAME",
"${SpeakerDaoSqlite.TABLE}.${SpeakerDaoSqlite.COL_PICTURE} AS $COL_SPEAKER_PIC",
"${SpeakerDaoSqlite.TABLE}.${SpeakerDaoSqlite.COL_COMPANY} AS $COL_SPEAKER_COMPANY",
"${SpeakerDaoSqlite.TABLE}.${SpeakerDaoSqlite.COL_JOB_TITLE} AS $COL_SPEAKER_JOBTITLE"
)
.FROM(TABLE)
.LEFT_OUTER_JOIN(LocationDaoSqlite.TABLE)
.ON("$TABLE.$COL_LOCATION_ID = ${LocationDaoSqlite.TABLE}.${LocationDaoSqlite.COL_ID}")
.LEFT_OUTER_JOIN(GiveTalk.TABLE)
.ON("$TABLE.$COL_ID = ${GiveTalk.TABLE}.${GiveTalk.COL_SESSION_ID}")
.LEFT_OUTER_JOIN(SpeakerDaoSqlite.TABLE)
.ON("${GiveTalk.TABLE}.${GiveTalk.COL_SPEAKER_ID} = ${SpeakerDaoSqlite.TABLE}.${SpeakerDaoSqlite.COL_ID}")
override fun getSessions(): Observable<List<Session>> =
query(selectAll())
.run()
.mapToList(SessionJoinResult.mapper())
.map(::mapJoinResultToSessions)
.map { it.sortedWith(sortByStartDate) }
override fun insertOrUpdate(session: Session, favorite: Boolean): Observable<Long> {
val cv = ContentValues()
cv.put(COL_ID, session.id())
cv.putOrNull(COL_TITLE, session.title())
cv.putOrNull(COL_DESCRIPTION, session.description())
cv.putOrNull(COL_TAGS, session.tags())
cv.putOrNull(COL_LOCATION_ID, session.locationId())
cv.putOrNull(COL_START_TIME, session.startTime())
cv.putOrNull(COL_END_TIME, session.endTime())
cv.put(COL_FAVORITE, favorite)
return insert(TABLE, cv, SQLiteDatabase.CONFLICT_REPLACE)
.flatMap { delete(GiveTalk.TABLE, "${GiveTalk.COL_SESSION_ID} = ?", session.id()) }
.map {
session.speakers().forEach {
// Insert blocking
val cv = ContentValues()
cv.put(GiveTalk.COL_SESSION_ID, session.id())
cv.put(GiveTalk.COL_SPEAKER_ID, it.id())
getBriteDatabase().insert(GiveTalk.TABLE, cv)
}
1L // Everything was ok
}
}
override fun remove(id: String): Observable<Int> = delete(TABLE, "$COL_ID = ?",
id).flatMap { deleted ->
delete(GiveTalk.TABLE, "${GiveTalk.COL_SESSION_ID} = ?", id).map { deleted }
}
override fun removeAll(): Observable<Int> = delete(TABLE)
override fun setFavorite(sessionId: String, favorite: Boolean): Observable<Int> {
val cv = ContentValues()
cv.put(COL_FAVORITE, favorite)
return update(TABLE, cv, "$COL_ID = ?", sessionId)
}
override fun getById(id: String): Observable<Session> =
query(selectAll().WHERE("$TABLE.$COL_ID = ?"))
.args(id)
.run()
.mapToList(SessionJoinResult.mapper())
.map(::mapJoinResultToSessions)
.map {
when (it.size) {
0 -> null
1 -> it[0]
else -> throw Exception("Expected a single result but got ${it.size}")
}
}
override fun getFavoriteSessions(): Observable<List<Session>> =
query(selectAll().WHERE("$COL_FAVORITE = 1"))
.run()
.mapToList(SessionJoinResult.mapper())
.map(::mapJoinResultToSessions)
.map { it.sortedWith(sortByStartDate) }
// TODO test
override fun getSessionsOfSpeaker(speakerId: String): Observable<List<Session>> =
query(selectAll().WHERE("$COL_SPEAKER_ID = ?"))
.args(speakerId)
.run()
.mapToList(SessionJoinResult.mapper())
.map(::mapJoinResultToSessions)
.map { it.sortedWith(sortByStartDate) }
// TODO test
override fun findSessionsWith(query: String): Observable<List<Session>> {
val split = query.split(" ")
val whereClauseBuilder = StringBuilder()
val args = Array<String>(split.size * 3, { "" })
var argsIndex = 0
split.forEachIndexed { i, searchTerm ->
if (i > 0) {
whereClauseBuilder.append(" OR ")
}
whereClauseBuilder.append("$COL_TITLE LIKE ? OR $COL_DESCRIPTION LIKE ? OR $COL_TAGS LIKE ?")
args[argsIndex++] = "%$searchTerm%"
args[argsIndex++] = "%$searchTerm%"
args[argsIndex++] = "%$searchTerm%"
}
return query(selectAll().WHERE(whereClauseBuilder.toString()))
.args(*args)
.run()
.mapToList(SessionJoinResult.mapper())
.map(::mapJoinResultToSessions)
.map { it.sortedWith(sortByStartDate) }
}
override fun getBriteDatabase(): BriteDatabase = db
} | apache-2.0 | 636925d8902c5c5f6cee4ccbb8453720 | 35.687805 | 132 | 0.647606 | 3.884298 | false | false | false | false |
tonyofrancis/Fetch | fetch2/src/main/java/com/tonyodev/fetch2/database/DownloadInfo.kt | 1 | 11610 | package com.tonyodev.fetch2.database
import android.arch.persistence.room.*
import android.net.Uri
import android.os.Parcel
import android.os.Parcelable
import com.tonyodev.fetch2.*
import com.tonyodev.fetch2.util.*
import com.tonyodev.fetch2.NetworkType
import com.tonyodev.fetch2.Priority
import com.tonyodev.fetch2.Status
import com.tonyodev.fetch2core.Extras
import com.tonyodev.fetch2core.calculateProgress
import com.tonyodev.fetch2core.getFileUri
import java.util.*
@Entity(tableName = DownloadDatabase.TABLE_NAME,
indices = [(Index(value = [DownloadDatabase.COLUMN_FILE], unique = true)),
(Index(value = [DownloadDatabase.COLUMN_GROUP, DownloadDatabase.COLUMN_STATUS], unique = false))])
open class DownloadInfo : Download {
@PrimaryKey
@ColumnInfo(name = DownloadDatabase.COLUMN_ID, typeAffinity = ColumnInfo.INTEGER)
override var id: Int = 0
@ColumnInfo(name = DownloadDatabase.COLUMN_NAMESPACE, typeAffinity = ColumnInfo.TEXT)
override var namespace: String = ""
@ColumnInfo(name = DownloadDatabase.COLUMN_URL, typeAffinity = ColumnInfo.TEXT)
override var url: String = ""
@ColumnInfo(name = DownloadDatabase.COLUMN_FILE, typeAffinity = ColumnInfo.TEXT)
override var file: String = ""
@ColumnInfo(name = DownloadDatabase.COLUMN_GROUP, typeAffinity = ColumnInfo.INTEGER)
override var group: Int = 0
@ColumnInfo(name = DownloadDatabase.COLUMN_PRIORITY, typeAffinity = ColumnInfo.INTEGER)
override var priority: Priority = defaultPriority
@ColumnInfo(name = DownloadDatabase.COLUMN_HEADERS, typeAffinity = ColumnInfo.TEXT)
override var headers: Map<String, String> = mutableMapOf()
@ColumnInfo(name = DownloadDatabase.COLUMN_DOWNLOADED, typeAffinity = ColumnInfo.INTEGER)
override var downloaded: Long = 0L
@ColumnInfo(name = DownloadDatabase.COLUMN_TOTAL, typeAffinity = ColumnInfo.INTEGER)
override var total: Long = -1L
@ColumnInfo(name = DownloadDatabase.COLUMN_STATUS, typeAffinity = ColumnInfo.INTEGER)
override var status: Status = defaultStatus
@ColumnInfo(name = DownloadDatabase.COLUMN_ERROR, typeAffinity = ColumnInfo.INTEGER)
override var error: Error = defaultNoError
@ColumnInfo(name = DownloadDatabase.COLUMN_NETWORK_TYPE, typeAffinity = ColumnInfo.INTEGER)
override var networkType: NetworkType = defaultNetworkType
@ColumnInfo(name = DownloadDatabase.COLUMN_CREATED, typeAffinity = ColumnInfo.INTEGER)
override var created: Long = Calendar.getInstance().timeInMillis
@ColumnInfo(name = DownloadDatabase.COLUMN_TAG, typeAffinity = ColumnInfo.TEXT)
override var tag: String? = null
@ColumnInfo(name = DownloadDatabase.COLUMN_ENQUEUE_ACTION, typeAffinity = ColumnInfo.INTEGER)
override var enqueueAction: EnqueueAction = EnqueueAction.REPLACE_EXISTING
@ColumnInfo(name = DownloadDatabase.COLUMN_IDENTIFIER, typeAffinity = ColumnInfo.INTEGER)
override var identifier: Long = DEFAULT_UNIQUE_IDENTIFIER
@ColumnInfo(name = DownloadDatabase.COLUMN_DOWNLOAD_ON_ENQUEUE, typeAffinity = ColumnInfo.INTEGER)
override var downloadOnEnqueue: Boolean = DEFAULT_DOWNLOAD_ON_ENQUEUE
@ColumnInfo(name = DownloadDatabase.COLUMN_EXTRAS, typeAffinity = ColumnInfo.TEXT)
override var extras: Extras = Extras.emptyExtras
@ColumnInfo(name = DownloadDatabase.COLUMN_AUTO_RETRY_MAX_ATTEMPTS, typeAffinity = ColumnInfo.INTEGER)
override var autoRetryMaxAttempts: Int = DEFAULT_AUTO_RETRY_ATTEMPTS
@ColumnInfo(name = DownloadDatabase.COLUMN_AUTO_RETRY_ATTEMPTS, typeAffinity = ColumnInfo.INTEGER)
override var autoRetryAttempts: Int = DEFAULT_AUTO_RETRY_ATTEMPTS
@Ignore
override var etaInMilliSeconds: Long = -1L
@Ignore
override var downloadedBytesPerSecond: Long = -1L
override val progress: Int
get() {
return calculateProgress(downloaded, total)
}
override val fileUri: Uri
get() {
return getFileUri(file)
}
override val request: Request
get() {
val request = Request(url, file)
request.groupId = group
request.headers.putAll(headers)
request.networkType = networkType
request.priority = priority
request.enqueueAction = enqueueAction
request.identifier = identifier
request.downloadOnEnqueue = downloadOnEnqueue
request.extras = extras
request.autoRetryMaxAttempts = autoRetryMaxAttempts
return request
}
override fun copy(): Download {
return this.toDownloadInfo(DownloadInfo())
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as DownloadInfo
if (id != other.id) return false
if (namespace != other.namespace) return false
if (url != other.url) return false
if (file != other.file) return false
if (group != other.group) return false
if (priority != other.priority) return false
if (headers != other.headers) return false
if (downloaded != other.downloaded) return false
if (total != other.total) return false
if (status != other.status) return false
if (error != other.error) return false
if (networkType != other.networkType) return false
if (created != other.created) return false
if (tag != other.tag) return false
if (enqueueAction != other.enqueueAction) return false
if (identifier != other.identifier) return false
if (downloadOnEnqueue != other.downloadOnEnqueue) return false
if (extras != other.extras) return false
if (etaInMilliSeconds != other.etaInMilliSeconds) return false
if (downloadedBytesPerSecond != other.downloadedBytesPerSecond) return false
if (autoRetryMaxAttempts != other.autoRetryMaxAttempts) return false
if (autoRetryAttempts != other.autoRetryAttempts) return false
return true
}
override fun hashCode(): Int {
var result = id
result = 31 * result + namespace.hashCode()
result = 31 * result + url.hashCode()
result = 31 * result + file.hashCode()
result = 31 * result + group
result = 31 * result + priority.hashCode()
result = 31 * result + headers.hashCode()
result = 31 * result + downloaded.hashCode()
result = 31 * result + total.hashCode()
result = 31 * result + status.hashCode()
result = 31 * result + error.hashCode()
result = 31 * result + networkType.hashCode()
result = 31 * result + created.hashCode()
result = 31 * result + (tag?.hashCode() ?: 0)
result = 31 * result + enqueueAction.hashCode()
result = 31 * result + identifier.hashCode()
result = 31 * result + downloadOnEnqueue.hashCode()
result = 31 * result + extras.hashCode()
result = 31 * result + etaInMilliSeconds.hashCode()
result = 31 * result + downloadedBytesPerSecond.hashCode()
result = 31 * result + autoRetryMaxAttempts.hashCode()
result = 31 * result + autoRetryAttempts.hashCode()
return result
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(id)
dest.writeString(namespace)
dest.writeString(url)
dest.writeString(file)
dest.writeInt(group)
dest.writeInt(priority.value)
dest.writeSerializable(HashMap(headers))
dest.writeLong(downloaded)
dest.writeLong(total)
dest.writeInt(status.value)
dest.writeInt(error.value)
dest.writeInt(networkType.value)
dest.writeLong(created)
dest.writeString(tag)
dest.writeInt(enqueueAction.value)
dest.writeLong(identifier)
dest.writeInt(if (downloadOnEnqueue) 1 else 0)
dest.writeLong(etaInMilliSeconds)
dest.writeLong(downloadedBytesPerSecond)
dest.writeSerializable(HashMap(extras.map))
dest.writeInt(autoRetryMaxAttempts)
dest.writeInt(autoRetryAttempts)
}
override fun describeContents(): Int {
return 0
}
override fun toString(): String {
return "DownloadInfo(id=$id, namespace='$namespace', url='$url', file='$file', " +
"group=$group, priority=$priority, headers=$headers, downloaded=$downloaded," +
" total=$total, status=$status, error=$error, networkType=$networkType, " +
"created=$created, tag=$tag, enqueueAction=$enqueueAction, identifier=$identifier," +
" downloadOnEnqueue=$downloadOnEnqueue, extras=$extras, " +
"autoRetryMaxAttempts=$autoRetryMaxAttempts, autoRetryAttempts=$autoRetryAttempts," +
" etaInMilliSeconds=$etaInMilliSeconds, downloadedBytesPerSecond=$downloadedBytesPerSecond)"
}
companion object CREATOR : Parcelable.Creator<DownloadInfo> {
@Suppress("UNCHECKED_CAST")
override fun createFromParcel(source: Parcel): DownloadInfo {
val id = source.readInt()
val namespace = source.readString() ?: ""
val url = source.readString() ?: ""
val file = source.readString() ?: ""
val group = source.readInt()
val priority = Priority.valueOf(source.readInt())
val headers = source.readSerializable() as Map<String, String>
val downloaded = source.readLong()
val total = source.readLong()
val status = Status.valueOf(source.readInt())
val error = Error.valueOf(source.readInt())
val networkType = NetworkType.valueOf(source.readInt())
val created = source.readLong()
val tag = source.readString()
val enqueueAction = EnqueueAction.valueOf(source.readInt())
val identifier = source.readLong()
val downloadOnEnqueue = source.readInt() == 1
val etaInMilliSeconds = source.readLong()
val downloadedBytesPerSecond = source.readLong()
val extras = source.readSerializable() as Map<String, String>
val autoRetryMaxAttempts = source.readInt()
val autoRetryAttempts = source.readInt()
val downloadInfo = DownloadInfo()
downloadInfo.id = id
downloadInfo.namespace = namespace
downloadInfo.url = url
downloadInfo.file = file
downloadInfo.group = group
downloadInfo.priority = priority
downloadInfo.headers = headers
downloadInfo.downloaded = downloaded
downloadInfo.total = total
downloadInfo.status = status
downloadInfo.error = error
downloadInfo.networkType = networkType
downloadInfo.created = created
downloadInfo.tag = tag
downloadInfo.enqueueAction = enqueueAction
downloadInfo.identifier = identifier
downloadInfo.downloadOnEnqueue = downloadOnEnqueue
downloadInfo.etaInMilliSeconds = etaInMilliSeconds
downloadInfo.downloadedBytesPerSecond = downloadedBytesPerSecond
downloadInfo.extras = Extras(extras)
downloadInfo.autoRetryMaxAttempts = autoRetryMaxAttempts
downloadInfo.autoRetryAttempts = autoRetryAttempts
return downloadInfo
}
override fun newArray(size: Int): Array<DownloadInfo?> {
return arrayOfNulls(size)
}
}
} | apache-2.0 | 3536fafb62f3cdadedacaae7fc42ae43 | 41.375912 | 110 | 0.669681 | 4.793559 | false | false | false | false |
kunickiaj/vault-kotlin | src/main/kotlin/com/adamkunicki/vault/api/Logical.kt | 1 | 2768 | /*
* Copyright 2016 Adam Kunicki
*
* 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.adamkunicki.vault.api
import com.adamkunicki.vault.VaultConfiguration
import com.adamkunicki.vault.VaultError
import com.adamkunicki.vault.VaultException
import com.github.kittinunf.fuel.httpDelete
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.fuel.httpPut
import com.github.salomonbrys.kotson.jsonObject
import com.google.gson.Gson
@Suppress("UNUSED_VARIABLE")
class Logical(private val conf: VaultConfiguration) {
@Throws(VaultException::class)
fun list(path: String): Secret {
val (request, response, result) = (conf.adddress + "/v1/" + path.trim('/'))
.httpGet(listOf(Pair("list", true)))
.header(Pair("X-Vault-Token", conf.token))
.responseObject(Secret.Deserializer())
val (secret, error) = result
if (secret != null) {
return secret
}
val errorMessage = if (error != null) {
Gson().fromJson(String(error.errorData), VaultError::class.java).errors.joinToString()
} else {
""
}
throw VaultException(errorMessage)
}
@Throws(VaultException::class)
fun read(path: String): Secret {
val (request, response, result) = (conf.adddress + "/v1/" + path.trim('/'))
.httpGet()
.header(Pair("X-Vault-Token", conf.token))
.responseObject(Secret.Deserializer())
val (secret, error) = result
if (secret != null) {
return secret
}
val errorMessage = if (error != null) {
Gson().fromJson(String(error.errorData), VaultError::class.java).errors.joinToString()
} else {
""
}
throw VaultException(errorMessage)
}
fun write(path: String, data: List<Pair<String, Any?>>): Boolean {
val (request, response, result) = (conf.adddress + "/v1/" + path.trim('/'))
.httpPut()
.body(jsonObject(*data.toTypedArray()).toString(), Charsets.UTF_8)
.header(Pair("X-Vault-Token", conf.token))
.response()
return true
}
fun delete(path: String): Boolean {
val (request, response, result) = (conf.adddress + "/v1/" + path.trim('/'))
.httpDelete()
.header(Pair("X-Vault-Token", conf.token))
.response()
return true
}
} | apache-2.0 | 21b3fe103731163f170c8357ffa1485e | 30.11236 | 92 | 0.666185 | 3.796982 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/listener/AsyncPlayerChatListener.kt | 1 | 6204 | /*
* Copyright 2021 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.chat.bukkit.listener
import com.rpkit.chat.bukkit.RPKChatBukkit
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannel
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannelMessageCallback
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannelService
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.RPKThinProfile
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.AsyncPlayerChatEvent
/**
* Player chat listener.
* Cancels normal message processing and passes the message to the appropriate chat channel.
*/
class AsyncPlayerChatListener(private val plugin: RPKChatBukkit) : Listener {
@EventHandler
fun onAsyncPlayerChat(event: AsyncPlayerChatEvent) {
event.isCancelled = true
val chatChannelService = Services[RPKChatChannelService::class.java] ?: return
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(event.player)
if (minecraftProfile != null) {
val profile = minecraftProfile.profile
chatChannelService.getMinecraftProfileChannel(minecraftProfile).thenAcceptAsync { chatChannel ->
val queuedMessages = mutableListOf<QueuedMessage>()
val message = event.message
var readMessageIndex = 0
chatChannelService.matchPatterns
.map { matchPattern ->
val matches = matchPattern.regex.let(::Regex).findAll(message).toList()
matches to matchPattern
}
.flatMap { (matches, matchPattern) -> matches.associateWith { matchPattern }.toList() }
.sortedBy { (match, _) -> match.range.first }
.forEach { (match, matchPattern) ->
queuedMessages.add(QueuedMessage(
chatChannel,
message.substring(readMessageIndex, match.range.first),
event.player,
profile,
minecraftProfile
))
match.groupValues.forEachIndexed { index, value ->
val otherChatChannel = matchPattern.groups[index]
if (otherChatChannel != null) {
queuedMessages.add(QueuedMessage(
otherChatChannel,
value,
event.player,
profile,
minecraftProfile
))
}
}
readMessageIndex = match.range.last + 1
}
if (readMessageIndex < message.length) {
queuedMessages.add(QueuedMessage(
chatChannel,
message.substring(readMessageIndex, message.length),
event.player,
profile,
minecraftProfile
))
}
sendMessages(queuedMessages)
}
} else {
event.player.sendMessage(plugin.messages["no-minecraft-profile"])
}
}
private fun sendMessages(queue: List<QueuedMessage>) {
if (queue.isNotEmpty()) {
sendMessage(queue.first()) { sendMessages(queue.drop(1)) }
}
}
private fun sendMessage(message: QueuedMessage, callback: RPKChatChannelMessageCallback? = null) {
sendMessage(message.chatChannel, message.message, message.bukkitPlayer, message.profile, message.minecraftProfile, callback)
}
private fun sendMessage(
chatChannel: RPKChatChannel?,
message: String,
bukkitPlayer: Player,
profile: RPKThinProfile,
minecraftProfile: RPKMinecraftProfile,
callback: RPKChatChannelMessageCallback? = null
) {
if (chatChannel != null) {
plugin.server.scheduler.runTask(plugin, Runnable {
chatChannel.listeners.thenAcceptAsync { listeners ->
if (!listeners.any { listenerMinecraftProfile ->
listenerMinecraftProfile.id == minecraftProfile.id
}) {
chatChannel.addListener(minecraftProfile).join()
}
if (message.isNotBlank()) {
chatChannel.sendMessage(
profile,
minecraftProfile,
message.trim(),
true,
callback
)
} else {
callback?.invoke()
}
}
})
} else {
bukkitPlayer.sendMessage(plugin.messages["no-chat-channel"])
}
}
private data class QueuedMessage(
val chatChannel: RPKChatChannel?,
val message: String,
val bukkitPlayer: Player,
val profile: RPKThinProfile,
val minecraftProfile: RPKMinecraftProfile
)
}
| apache-2.0 | fb60679ae97f3a6fff357275c58d0b29 | 41.493151 | 132 | 0.568827 | 5.891738 | false | false | false | false |
androidx/constraintlayout | projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/MotionFlowDemo.kt | 2 | 11244 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.constraintlayout
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.MotionLayout
import androidx.constraintlayout.compose.MotionScene
@Preview(group = "motion")
@Composable
public fun MotionFlowDemo() {
var animateToEnd by remember { mutableStateOf(false) }
val progress = remember { Animatable(0f) }
LaunchedEffect(animateToEnd) {
progress.animateTo(if (animateToEnd) 1f else 0f,
animationSpec = tween(3000))
}
Column(modifier = Modifier.background(Color.White)) {
val scene1 = MotionScene("""
{
Header: {
name: 'flowDemo1'
},
ConstraintSets: {
start: {
flow1: {
width: 'parent',
height: 'parent',
type: 'hFlow',
vGap: 20,
hGap: 20,
contains: ['1', '2', '3', '4'],
}
},
end: {
flow2: {
width: 'match_parent',
height: 'match_parent',
type: 'vFlow',
wrap: 'none',
vGap: 20,
hGap: 20,
contains: ['1', '2', '3', '4'],
}
}
},
Transitions: {
default: {
from: 'start', to: 'end',
}
}
}
""")
MotionLayout(
modifier = Modifier
.fillMaxWidth()
.height(400.dp),
motionScene = scene1,
progress = progress.value) {
val numArray = arrayOf("1", "2", "3", "4")
for (num in numArray) {
Button(
modifier = Modifier.layoutId(num),
onClick = {},
) {
Text(text = num)
}
}
}
Button(onClick = { animateToEnd = !animateToEnd },
modifier = Modifier
.fillMaxWidth()
.padding(3.dp)) {
Text(text = "Run")
}
}
}
@Preview(group = "motion")
@Composable
public fun MotionFlowDemo2() {
var animateToEnd by remember { mutableStateOf(false) }
val progress = remember { Animatable(0f) }
LaunchedEffect(animateToEnd) {
progress.animateTo(if (animateToEnd) 1f else 0f,
animationSpec = tween(3000))
}
Column(modifier = Modifier.background(Color.White)) {
val scene1 = MotionScene("""
{
Header: {
name: 'flowDemo2'
},
ConstraintSets: {
start: {
flow1: {
width: 'parent',
height: 'parent',
type: 'hFlow',
vGap: 20,
hGap: 20,
contains: ['1', '2', '3', '4', '5'],
}
},
end: {
flow2: {
width: 300,
height: 300,
type: 'vFlow',
wrap: 'aligned',
maxElement: 3,
vGap: 20,
hGap: 20,
contains: ['1', '2', '3', '4', '5'],
}
}
},
Transitions: {
default: {
from: 'start', to: 'end',
}
}
}
""")
MotionLayout(
modifier = Modifier
.fillMaxWidth()
.height(400.dp),
motionScene = scene1,
progress = progress.value) {
val numArray = arrayOf("1", "2", "3", "4", "5")
for (num in numArray) {
Button(
modifier = Modifier.layoutId(num),
onClick = {},
) {
Text(text = num)
}
}
}
Button(onClick = { animateToEnd = !animateToEnd },
modifier = Modifier
.fillMaxWidth()
.padding(3.dp)) {
Text(text = "Run")
}
}
}
@Preview(group = "motion")
@Composable
public fun MotionFlowDemo3() {
var animateToEnd by remember { mutableStateOf(false) }
val progress = remember { Animatable(0f) }
LaunchedEffect(animateToEnd) {
progress.animateTo(if (animateToEnd) 1f else 0f,
animationSpec = tween(3000))
}
Column(modifier = Modifier.background(Color.White)) {
val scene1 = MotionScene("""
{
Header: {
name: 'flowDemo3'
},
ConstraintSets: {
start: {
flow1: {
width: 'parent',
height: 'parent',
type: 'vFlow',
wrap: 'chain',
maxElement: 3,
vStyle: ['spread', 'packed', 'spread_inside'],
vGap: 20,
hGap: 20,
contains: ['1', '2', '3', '4', '5', '6', '7', '8'],
}
},
end: {
flow2: {
width: 'wrap',
height: 'wrap',
type: 'hFlow',
wrap: 'chain',
maxElement: 3,
vGap: 20,
hGap: 20,
contains: ['1', '2', '3', '4', '5', '6', '7', '8'],
}
}
},
Transitions: {
default: {
from: 'start', to: 'end',
}
}
}
""")
MotionLayout(
modifier = Modifier
.fillMaxWidth()
.height(500.dp),
motionScene = scene1,
progress = progress.value) {
val numArray = arrayOf("1", "2", "3", "4", "5", "6", "7", "8")
for (num in numArray) {
Button(
modifier = Modifier.layoutId(num),
onClick = {},
) {
Text(text = num)
}
}
}
Button(onClick = { animateToEnd = !animateToEnd },
modifier = Modifier
.fillMaxWidth()
.padding(3.dp)) {
Text(text = "Run")
}
}
}
@Preview(group = "motion")
@Composable
public fun MotionFlowDemo4() {
var animateToEnd by remember { mutableStateOf(false) }
val progress = remember { Animatable(0f) }
LaunchedEffect(animateToEnd) {
progress.animateTo(if (animateToEnd) 1f else 0f,
animationSpec = tween(3000))
}
Column(modifier = Modifier.background(Color.White)) {
val scene1 = MotionScene("""
{
Header: {
name: 'flowDemo4'
},
ConstraintSets: {
start: {
flow1: {
width: 'parent',
height: 'parent',
type: 'hFlow',
wrap: 'chain',
maxElement: 3,
padding: 20,
hStyle: ['spread', 'packed', 'spread_inside'],
contains: ['1', '2', '3', '4', '5', '6', '7', '8'],
}
},
end: {
flow2: {
width: 'wrap',
height: 'wrap',
type: 'vFlow',
wrap: 'chain',
vGap: 10,
hGap: 10,
vBias: 0.1,
hBias: 0.9,
maxElement: 3,
contains: ['1', '2', '3', '4', '5', '6', '7', '8'],
start: ['parent', 'start', 20],
top: ['parent', 'top', 20],
end: ['parent', 'end', 20],
bottom: ['parent', 'bottom', 20]
}
}
},
Transitions: {
default: {
from: 'start', to: 'end',
}
}
}
""")
MotionLayout(
modifier = Modifier
.fillMaxWidth()
.height(500.dp),
motionScene = scene1,
progress = progress.value) {
val numArray = arrayOf("1", "2", "3", "4", "5", "6", "7", "8")
for (num in numArray) {
Button(
modifier = Modifier.layoutId(num),
onClick = {},
) {
Text(text = num)
}
}
}
Button(onClick = { animateToEnd = !animateToEnd },
modifier = Modifier
.fillMaxWidth()
.padding(3.dp)) {
Text(text = "Run")
}
}
} | apache-2.0 | 6f9e64a8f73cc33f2d86ba624bdcb91f | 29.391892 | 75 | 0.396656 | 5.136592 | false | false | false | false |
luxons/seven-wonders | sw-server/src/main/kotlin/org/luxons/sevenwonders/server/config/TopicSubscriptionInterceptor.kt | 1 | 1520 | package org.luxons.sevenwonders.server.config
import org.luxons.sevenwonders.server.validation.DestinationAccessValidator
import org.slf4j.LoggerFactory
import org.springframework.messaging.Message
import org.springframework.messaging.MessageChannel
import org.springframework.messaging.simp.stomp.StompCommand
import org.springframework.messaging.simp.stomp.StompHeaderAccessor
import org.springframework.messaging.support.ChannelInterceptor
import org.springframework.stereotype.Component
@Component
class TopicSubscriptionInterceptor(
private val destinationAccessValidator: DestinationAccessValidator,
) : ChannelInterceptor {
override fun preSend(message: Message<*>, channel: MessageChannel): Message<*>? {
val headerAccessor = StompHeaderAccessor.wrap(message)
if (StompCommand.SUBSCRIBE == headerAccessor.command) {
val username = headerAccessor.user!!.name
val destination = headerAccessor.destination!!
if (!destinationAccessValidator.hasAccess(username, destination)) {
sendForbiddenSubscriptionError(username, destination)
return null
}
}
return message
}
private fun sendForbiddenSubscriptionError(username: String, destination: String?) {
logger.error(String.format("Player '%s' is not allowed to access %s", username, destination))
}
companion object {
private val logger = LoggerFactory.getLogger(TopicSubscriptionInterceptor::class.java)
}
}
| mit | 6e18e7ed83d2a22f32bedd6106b32924 | 40.081081 | 101 | 0.751974 | 5.033113 | false | false | false | false |
LorittaBot/Loritta | web/showtime/backend/src/main/kotlin/net/perfectdreams/loritta/cinnamon/showtime/backend/views/StaffView.kt | 1 | 22455 | package net.perfectdreams.loritta.cinnamon.showtime.backend.views
import com.mrpowergamerbr.loritta.utils.locale.BaseLocale
import dev.kord.common.entity.Snowflake
import kotlinx.html.DIV
import kotlinx.html.a
import kotlinx.html.br
import kotlinx.html.classes
import kotlinx.html.div
import kotlinx.html.h1
import kotlinx.html.h2
import kotlinx.html.img
import kotlinx.html.p
import kotlinx.html.style
import kotlinx.html.title
import net.perfectdreams.dokyo.WebsiteTheme
import net.perfectdreams.i18nhelper.core.I18nContext
import net.perfectdreams.i18nhelper.core.keydata.ListI18nData
import net.perfectdreams.i18nhelper.core.keydata.StringI18nData
import net.perfectdreams.loritta.i18n.I18nKeysData
import net.perfectdreams.loritta.cinnamon.discord.utils.DiscordRegexes
import net.perfectdreams.loritta.cinnamon.showtime.backend.ShowtimeBackend
import net.perfectdreams.loritta.cinnamon.showtime.backend.utils.WebEmotes
import net.perfectdreams.loritta.cinnamon.showtime.backend.utils.imgSrcSetFromResourcesOrFallbackToImgIfNotPresent
import net.perfectdreams.loritta.cinnamon.showtime.backend.utils.innerContent
class StaffView(
showtimeBackend: ShowtimeBackend,
websiteTheme: WebsiteTheme,
locale: BaseLocale,
i18nContext: I18nContext,
path: String,
val discordAvatars: Map<Snowflake, String>,
val aboutMe: Map<Snowflake, String?>
) : NavbarView(
showtimeBackend,
websiteTheme,
locale,
i18nContext,
path
) {
companion object {
/**
* List of staff groups and staff members that should be shown in the list
*/
val staffList = staffList {
group(I18nKeysData.Website.Staff.LorittaCreator.Title, null) {
user("MrPowerGamerBR") {
socialNetworks.add(DiscordSocialNetwork(Snowflake(123170274651668480)))
socialNetworks.add(TwitterSocialNetwork("MrPowerGamerBR"))
socialNetworks.add(LastFmSocialNetwork("MrPowerGamerBR"))
socialNetworks.add(GitHubSocialNetwork("MrPowerGamerBR"))
socialNetworks.add(WebsiteSocialNetwork("https://mrpowergamerbr.com/"))
socialNetworks.add(YouTubeSocialNetwork("UC-eeXSRZ8cO-i2NZYrWGDnQ"))
socialNetworks.add(RedditSocialNetwork("MrPowerGamerBR"))
}
}
group(I18nKeysData.Website.Staff.LorittaBodyguard.Title, I18nKeysData.Website.Staff.LorittaBodyguard.Description) {
user("Arth") {
socialNetworks.add(DiscordSocialNetwork(Snowflake(351760430991147010)))
socialNetworks.add(TwitterSocialNetwork("souarth"))
socialNetworks.add(LastFmSocialNetwork("souarth"))
}
user("Nightdavisao") {
socialNetworks.add(DiscordSocialNetwork(Snowflake(272031079001620490)))
socialNetworks.add(TwitterSocialNetwork("Nightdavisao"))
socialNetworks.add(LastFmSocialNetwork("Nightdavisao"))
socialNetworks.add(GitHubSocialNetwork("Nightdavisao"))
}
user("Stéphany") {
socialNetworks.add(DiscordSocialNetwork(Snowflake(400683515873591296)))
socialNetworks.add(TwitterSocialNetwork("dittom_"))
socialNetworks.add(GitHubSocialNetwork("dittom20"))
}
user("DanielaGC_") {
socialNetworks.add(DiscordSocialNetwork(Snowflake(395788326835322882)))
socialNetworks.add(TwitterSocialNetwork("DanielaGC_0"))
socialNetworks.add(LastFmSocialNetwork("DanielaGC_0"))
socialNetworks.add(GitHubSocialNetwork("DanielaGC"))
}
user("joaoesteves10") {
socialNetworks.add(DiscordSocialNetwork(Snowflake(214486492909666305)))
socialNetworks.add(TwitterSocialNetwork("joaoesteves10a5"))
socialNetworks.add(GitHubSocialNetwork("joaoesteves10"))
}
user("PeterStark000") {
socialNetworks.add(DiscordSocialNetwork(Snowflake(361977144445763585)))
socialNetworks.add(GitHubSocialNetwork("PeterStark000"))
socialNetworks.add(TwitterSocialNetwork("PeterStark000"))
socialNetworks.add(YouTubeSocialNetwork("UCcTTEVAyQ_xnfopzewr-5MA"))
socialNetworks.add(RedditSocialNetwork("PeterStark000"))
socialNetworks.add(LastFmSocialNetwork("PeterStark000"))
}
user("Kaike Carlos") {
socialNetworks.add(DiscordSocialNetwork(Snowflake(123231508625489920)))
}
user("nathaan") {
socialNetworks.add(DiscordSocialNetwork(Snowflake(437731723350900739)))
socialNetworks.add(TwitterSocialNetwork("oRafa_e"))
}
user("JvGm45") {
socialNetworks.add(DiscordSocialNetwork(Snowflake(197308318119755776)))
socialNetworks.add(TwitterSocialNetwork("JvGm45"))
socialNetworks.add(GitHubSocialNetwork("JvGm45"))
}
user("victor.") {
socialNetworks.add(DiscordSocialNetwork(Snowflake(236167700777271297)))
socialNetworks.add(TwitterSocialNetwork("brviictoor"))
socialNetworks.add(GitHubSocialNetwork("hechfx"))
socialNetworks.add(LastFmSocialNetwork("brviictoor"))
}
}
group(I18nKeysData.Website.Staff.LorittaSupport.Title, I18nKeysData.Website.Staff.LorittaSupport.Description) {
// No one here... yet :(
}
}
sealed class StaffSocialNetwork
class DiscordSocialNetwork(
val userId: Snowflake
) : StaffSocialNetwork()
class TwitterSocialNetwork(
val handle: String
) : StaffSocialNetwork()
class LastFmSocialNetwork(
val handle: String
) : StaffSocialNetwork()
class GitHubSocialNetwork(
val handle: String
) : StaffSocialNetwork()
class WebsiteSocialNetwork(
val url: String
) : StaffSocialNetwork()
class YouTubeSocialNetwork(
val handle: String
) : StaffSocialNetwork()
class RedditSocialNetwork(
val handle: String
) : StaffSocialNetwork()
private val socialNetworkSortOrder = listOf(
DiscordSocialNetwork::class,
WebsiteSocialNetwork::class,
TwitterSocialNetwork::class,
RedditSocialNetwork::class,
YouTubeSocialNetwork::class,
GitHubSocialNetwork::class,
LastFmSocialNetwork::class,
)
private fun staffList(group: StaffListBuilder.() -> (Unit)): StaffListBuilder {
return StaffListBuilder().apply(group)
}
class StaffListBuilder {
val groups = mutableListOf<GroupBuilder>()
fun group(name: StringI18nData, description: ListI18nData?, builder: GroupBuilder.() -> (Unit)) {
groups.add(GroupBuilder(name, description).apply(builder))
}
}
class GroupBuilder(val name: StringI18nData, val description: ListI18nData?) {
val users = mutableListOf<StaffUserBuilder>()
fun user(name: String, builder: StaffUserBuilder.() -> (Unit)) {
users.add(StaffUserBuilder(name).apply(builder))
}
}
class StaffUserBuilder(val name: String) {
var socialNetworks = mutableListOf<StaffSocialNetwork>()
}
}
override fun getTitle() = i18nContext.get(I18nKeysData.Website.Staff.Title)
override fun DIV.generateContent() {
innerContent {
div(classes = "odd-wrapper") {
div(classes = "media") {
div(classes = "media-body") {
div {
style = "text-align: center;"
h1 {
+ i18nContext.get(I18nKeysData.Website.Staff.Title)
}
for (text in i18nContext.get(I18nKeysData.Website.Staff.Description)) {
p {
+ text
}
}
}
}
}
}
var index = 0
for (group in staffList.groups) {
if (group.users.isNotEmpty()) {
div(classes = if (index % 2 == 0) "even-wrapper" else "odd-wrapper") {
classes = classes + "wobbly-bg"
div(classes = "staff-content") {
div {
style = "text-align: center;"
h2 {
+i18nContext.get(group.name)
}
if (group.description != null) {
for (text in i18nContext.get(group.description)) {
p {
+text
}
}
}
}
div(classes = "staff-section") {
// Sort staff members by their name
for (user in group.users.sortedBy { it.name }) {
val discordSocialNetwork = user.socialNetworks.filterIsInstance<DiscordSocialNetwork>()
.firstOrNull()
val discordUserId = discordSocialNetwork?.userId
val discordAvatarUrl = if (discordUserId != null) discordAvatars[discordUserId] else null
val avatarUrl = discordAvatarUrl ?: "/v3/assets/img/emotes/lori-lick.gif"
div(classes = "staff-info") {
img(
src = avatarUrl,
classes = "staff-avatar"
)
div(classes = "staff-title") {
+user.name
}
if (user.socialNetworks.isNotEmpty()) {
div(classes = "staff-social-networks") {
for (socialNetwork in user.socialNetworks.sortedBy { socialNetworkSortOrder.indexOf(it::class) }) {
when (socialNetwork) {
is DiscordSocialNetwork -> {
a(href = "discord://-/users/${socialNetwork.userId}") {
title = "Discord"
iconManager.discord.apply(this)
}
}
is WebsiteSocialNetwork -> {
a(href = socialNetwork.url, target = "_blank") {
title = i18nContext.get(I18nKeysData.Website.Staff.SocialNetworks.PersonalWebsite)
iconManager.globe.apply(this)
}
}
is YouTubeSocialNetwork -> {
a(href = "https://youtube.com/user/${socialNetwork.handle}", target = "_blank") {
title = "YouTube"
iconManager.youtube.apply(this)
}
}
is TwitterSocialNetwork -> {
a(href = "https://twitter.com/${socialNetwork.handle}", target = "_blank") {
title = "Twitter"
iconManager.twitter.apply(this)
}
}
is LastFmSocialNetwork -> {
a(href = "https://last.fm/user/${socialNetwork.handle}", target = "_blank") {
title = "last.fm"
iconManager.lastfm.apply(this)
}
}
is GitHubSocialNetwork -> {
a(href = "https://github.com/${socialNetwork.handle}", target = "_blank") {
title = "GitHub"
iconManager.github.apply(this)
}
}
is RedditSocialNetwork -> {
a(href = "https://www.reddit.com/u/${socialNetwork.handle}", target = "_blank") {
title = "Reddit"
iconManager.reddit.apply(this)
}
}
}
}
}
}
val lastFmSocialNetwork = user.socialNetworks.filterIsInstance<LastFmSocialNetwork>()
.firstOrNull()
if (lastFmSocialNetwork != null) {
val lastFmInfo = showtimeBackend.lastFmStaffData?.get(lastFmSocialNetwork.handle)
val topSongInTheLast7Days = lastFmInfo?.topSongInTheLast7Days
val nowListening = lastFmInfo?.nowListening
if (nowListening != null) {
div(classes = "staff-song") {
title = i18nContext.get(I18nKeysData.Website.Staff.SocialNetworks.CurrentlyListening)
iconManager.headphones.apply(this)
+ " ${nowListening.artist} - ${nowListening.name}"
}
}
if (topSongInTheLast7Days != null) {
div(classes = "staff-song") {
title = i18nContext.get(I18nKeysData.Website.Staff.SocialNetworks.TopSongInTheLast7Days)
iconManager.music.apply(this)
+ " ${topSongInTheLast7Days.artist} - ${topSongInTheLast7Days.name}"
}
}
}
if (discordSocialNetwork != null) {
val rawAboutMe = aboutMe[discordSocialNetwork.userId]
if (rawAboutMe != null) {
// It says that it is unneeded but everytime that I remove it, it complains, smh
val splitAboutMe = rawAboutMe.split("\n")
div(classes = "staff-description") {
for (aboutMe in splitAboutMe) {
// We will split the string into two sections:
// - String
// - Discord Emote
val sections = mutableListOf<AboutMeSection>()
val matches = DiscordRegexes.DiscordEmote.findAll(aboutMe).toList()
var firstMatchedCharacterIndex = 0
var lastMatchedCharacterIndex = 0
for (match in matches) {
sections.add(AboutMeText(aboutMe.substring(firstMatchedCharacterIndex until match.range.first)))
val animated = match.groupValues[1] == "a"
val emoteName = match.groupValues[2]
val emoteId = match.groupValues[3]
// TODO: Fix this! Because we migrated the emotes to Ethereal, this won't work correctly anymore
if (false && WebEmotes.emotes.contains(emoteName)) {
sections.add(AboutMeLorittaWebsiteEmote(emoteName))
} else {
sections.add(AboutMeDiscordEmote(emoteId, animated))
}
lastMatchedCharacterIndex = match.range.last + 1
firstMatchedCharacterIndex = lastMatchedCharacterIndex
}
sections.add(
AboutMeText(
aboutMe.substring(
lastMatchedCharacterIndex until aboutMe.length
)
)
)
for (section in sections) {
when (section) {
is AboutMeLorittaWebsiteEmote -> {
imgSrcSetFromResourcesOrFallbackToImgIfNotPresent(
"/v3/assets/img/emotes/${WebEmotes.emotes[section.emoteFile]}",
"1.5em"
) {
classes = setOf("inline-emoji")
}
}
is AboutMeDiscordEmote -> {
img(src = "https://cdn.discordapp.com/emojis/${section.emoteId}.${if (section.animated) "gif" else "webp"}?size=48&quality=lossless", classes = "inline-emoji")
}
is AboutMeText -> +section.text
}
}
br {}
}
}
}
}
}
}
}
}
}
index++
}
}
}
}
sealed class AboutMeSection
data class AboutMeText(val text: String) : AboutMeSection()
data class AboutMeLorittaWebsiteEmote(val emoteFile: String) : AboutMeSection()
data class AboutMeDiscordEmote(val emoteId: String, val animated: Boolean) : AboutMeSection()
}
| agpl-3.0 | 6978c4809f715718ef2cc985e1c656be | 52.589499 | 227 | 0.406832 | 6.517852 | false | false | false | false |
signed/intellij-community | uast/uast-tests/test/org/jetbrains/uast/test/java/SimpleJavaRenderLogTest.kt | 1 | 1360 | /*
* Copyright 2000-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.uast.test.java
import org.junit.Test
class SimpleJavaRenderLogTest : AbstractJavaRenderLogTest() {
@Test fun testDataClass() = doTest("DataClass/DataClass.java")
@Test fun testEnumSwitch() = doTest("Simple/EnumSwitch.java")
@Test fun testLocalClass() = doTest("Simple/LocalClass.java")
@Test fun testReturnX() = doTest("Simple/ReturnX.java")
@Test fun testJava() = doTest("Simple/Simple.java")
@Test fun testClass() = doTest("Simple/SuperTypes.java")
@Test fun testTryWithResources() = doTest("Simple/TryWithResources.java")
@Test fun testEnumValueMembers() = doTest("Simple/EnumValueMembers.java")
@Test fun testQualifiedConstructorCall() = doTest("Simple/QualifiedConstructorCall.java")
}
| apache-2.0 | cb0c6ad5e979b49085840a0f38147b65 | 34.789474 | 93 | 0.736765 | 4.171779 | false | true | false | false |
kohesive/keplin | keplin-jsr223-kotlin-engine/src/main/kotlin/uy/kohesive/keplin/kotlin/script/jsr223/core/AbstractInvocableReplScriptEngine.kt | 1 | 5476 | package uy.kohesive.keplin.kotlin.script.jsr223.core
import org.jetbrains.kotlin.cli.common.repl.EvalClassWithInstanceAndLoader
import org.jetbrains.kotlin.com.google.common.base.Throwables
import org.jetbrains.kotlin.script.tryCreateCallableMapping
import uy.kohesive.keplin.util.assertNotEmpty
import java.lang.reflect.Proxy
import javax.script.Invocable
import javax.script.ScriptEngineFactory
import javax.script.ScriptException
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.KParameter
import kotlin.reflect.full.functions
import kotlin.reflect.full.safeCast
abstract class AbstractInvocableReplScriptEngine(factory: ScriptEngineFactory,
defaultImports: List<String>)
: AbstractReplScriptEngine(factory, defaultImports), Invocable {
override fun invokeFunction(name: String?, vararg args: Any?): Any? {
if (name == null) throw java.lang.NullPointerException("function name cannot be null")
return invokeImpl(prioritizedHistory(null, null), name, args)
}
override fun invokeMethod(thiz: Any?, name: String?, vararg args: Any?): Any? {
if (name == null) throw java.lang.NullPointerException("method name cannot be null")
if (thiz == null) throw IllegalArgumentException("cannot invoke method on the null object")
return invokeImpl(prioritizedHistory(thiz.javaClass.kotlin, thiz), name, args)
}
private fun invokeImpl(prioritizedCallOrder: List<EvalClassWithInstanceAndLoader>, name: String, args: Array<out Any?>): Any? {
// TODO: cache the method lookups?
val (fn, mapping, invokeWrapper) = prioritizedCallOrder.asSequence().map { attempt ->
val candidates = attempt.klass.functions.filter { it.name == name }
candidates.findMapping(listOf<Any?>(attempt.instance) + args)?.let {
Triple(it.first, it.second, attempt.invokeWrapper)
}
}.filterNotNull().firstOrNull() ?: throw NoSuchMethodException("no suitable function '$name' found")
val res = try {
if (invokeWrapper != null) {
invokeWrapper.invoke {
fn.callBy(mapping)
}
} else {
fn.callBy(mapping)
}
} catch (e: Throwable) {
// ignore everything in the stack trace until this constructor call
throw ScriptException(renderReplStackTrace(e.cause!!, startFromMethodName = fn.name))
}
return if (fn.returnType.classifier == Unit::class) Unit else res
}
override fun <T : Any> getInterface(clasz: Class<T>?): T? {
return proxyInterface(null, clasz)
}
override fun <T : Any> getInterface(thiz: Any?, clasz: Class<T>?): T? {
if (thiz == null) throw IllegalArgumentException("object cannot be null")
return proxyInterface(thiz, clasz)
}
private fun <T : Any> proxyInterface(thiz: Any?, clasz: Class<T>?): T? {
engine.lastEvaluatedScripts.assertNotEmpty("no script ")
val priority = prioritizedHistory(thiz?.javaClass?.kotlin, thiz)
if (clasz == null) throw IllegalArgumentException("class object cannot be null")
if (!clasz.isInterface) throw IllegalArgumentException("expecting interface")
// TODO: cache the method lookups?
val proxy = Proxy.newProxyInstance(Thread.currentThread().contextClassLoader, arrayOf(clasz)) { _, method, args ->
invokeImpl(priority, method.name, args ?: emptyArray())
}
return clasz.kotlin.safeCast(proxy)
}
private fun prioritizedHistory(receiverClass: KClass<*>?, receiverInstance: Any?): List<EvalClassWithInstanceAndLoader> {
return engine.lastEvaluatedScripts.map { it.item }.filter { it.instance != null }.reversed().assertNotEmpty("no script ").let { history ->
if (receiverInstance != null) {
val receiverKlass = receiverClass ?: receiverInstance.javaClass.kotlin
val receiverInHistory = history.find { it.instance == receiverInstance } ?:
EvalClassWithInstanceAndLoader(receiverKlass, receiverInstance, receiverKlass.java.classLoader, history.first().invokeWrapper)
listOf(receiverInHistory) + history.filterNot { it == receiverInHistory }
} else {
history
}
}
}
private fun Iterable<KFunction<*>>.findMapping(args: List<Any?>): Pair<KFunction<*>, Map<KParameter, Any?>>? {
for (fn in this) {
val mapping = tryCreateCallableMapping(fn, args)
if (mapping != null) return fn to mapping
}
return null
}
protected fun renderReplStackTrace(cause: Throwable, startFromMethodName: String): String {
val newTrace = arrayListOf<StackTraceElement>()
var skip = true
for ((_, element) in cause.stackTrace.withIndex().reversed()) {
if ("${element.className}.${element.methodName}" == startFromMethodName) {
skip = false
}
if (!skip) {
newTrace.add(element)
}
}
val resultingTrace = newTrace.reversed().dropLast(1)
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN", "UsePropertyAccessSyntax")
(cause as java.lang.Throwable).setStackTrace(resultingTrace.toTypedArray())
return Throwables.getStackTraceAsString(cause)
}
}
| mit | 20b477d4bb5cf2db8ed6d150c2cc0130 | 43.885246 | 150 | 0.656866 | 4.648557 | false | false | false | false |
ericberman/MyFlightbookAndroid | app/src/main/java/com/myflightbook/android/ActTimeCalc.kt | 1 | 5763 | /*
MyFlightbook for Android - provides native access to MyFlightbook
pilot's logbook
Copyright (C) 2017-2022 MyFlightbook, LLC
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.myflightbook.android
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import model.DecimalEdit
import model.DecimalEdit.Companion.stringForMode
import model.DecimalEdit.EditMode
/**
* Created by ericberman on 2/12/17.
*
* Implements a time calculator, which allows adding of multiple time periods together
*
*/
class ActTimeCalc : AppCompatActivity(), View.OnClickListener {
private val mValues = ArrayList<Double>()
private var initialTime = 0.0
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.calctime)
(findViewById<View>(R.id.decSegmentStart) as DecimalEdit).forceHHMM = true
(findViewById<View>(R.id.decSegmentEnd) as DecimalEdit).forceHHMM = true
(findViewById<View>(R.id.decSegmentStart) as DecimalEdit).setMode(EditMode.HHMM)
(findViewById<View>(R.id.decSegmentEnd) as DecimalEdit).setMode(EditMode.HHMM)
findViewById<View>(R.id.btnCopySegement).setOnClickListener(this)
findViewById<View>(R.id.btnAddSegment).setOnClickListener(this)
findViewById<View>(R.id.btnAddAndUpdate).setOnClickListener(this)
val dInit = intent.getDoubleExtra(INITIAL_TIME, 0.0)
if (dInit > 0) {
initialTime = dInit
mValues.add(dInit)
updateEquationString()
}
}
override fun onClick(v: View) {
when (v.id) {
R.id.btnCopySegement -> {
val clipboard = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
val s = stringForMode(
computedTotal(),
if (DecimalEdit.DefaultHHMM) EditMode.HHMM else EditMode.DECIMAL
)
clipboard.setPrimaryClip(ClipData.newPlainText("total", s))
}
R.id.btnAddSegment -> {
addSpecifiedTime()
updateEquationString()
}
R.id.btnAddAndUpdate -> {
addSpecifiedTime()
returnValue(computedTotal())
super.onBackPressed()
}
}
}
private fun returnValue(d: Double) {
val bundle = Bundle()
bundle.putDouble(COMPUTED_TIME, d)
hideKeyboard()
val mIntent = Intent()
mIntent.putExtras(bundle)
setResult(RESULT_OK, mIntent)
}
override fun onBackPressed() {
returnValue(initialTime)
super.onBackPressed()
}
//region Time calculation math
private fun computedTotal(): Double {
var result = 0.0
for (d in mValues) result += d
return result
}
private val specifiedTimeRange: Double
get() {
val dStart = (findViewById<View>(R.id.decSegmentStart) as DecimalEdit).doubleValue
var dEnd = (findViewById<View>(R.id.decSegmentEnd) as DecimalEdit).doubleValue
if (dEnd < 0 || dStart < 0 || dEnd > 24 || dStart > 24) {
(findViewById<View>(R.id.errTimeCalc) as TextView).setText(R.string.tcErrBadTime)
return 0.0
} else {
(findViewById<View>(R.id.errTimeCalc) as TextView).setText(R.string.strEmpty)
clearTime()
}
while (dEnd < dStart) dEnd += 24.0
return dEnd - dStart
}
private fun addSpecifiedTime() {
val d = specifiedTimeRange
if (d > 0.0) mValues.add(d)
}
private val equationString: String
get() {
val sb = StringBuilder()
val mode = if (DecimalEdit.DefaultHHMM) EditMode.HHMM else EditMode.DECIMAL
for (d in mValues) {
if (sb.isNotEmpty()) sb.append(" + ")
sb.append(stringForMode(d, mode))
}
if (mValues.size > 0) sb.append(" = ").append(stringForMode(computedTotal(), mode))
return sb.toString()
}
private fun updateEquationString() {
(findViewById<View>(R.id.txtTimeCalcEquation) as TextView).text = equationString
}
private fun clearTime() {
val deStart = findViewById<DecimalEdit>(R.id.decSegmentStart)
deStart.doubleValue = 0.0
(findViewById<View>(R.id.decSegmentEnd) as DecimalEdit).doubleValue = 0.0
deStart.requestFocus()
}
private fun hideKeyboard() {
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
val v = currentFocus
if (v != null) imm.hideSoftInputFromWindow(v.windowToken, 0)
} //endregion
companion object {
const val INITIAL_TIME = "com.myflightbook.android.initialTime"
const val COMPUTED_TIME = "com.myflightbook.android.computedTime"
}
} | gpl-3.0 | 65b78bea5957da7db01d4a4bd7d3e8d6 | 35.948718 | 97 | 0.641506 | 4.395881 | false | false | false | false |
ohmae/CdsExtractor | src/main/java/net/mm2d/android/upnp/cds/CdsObjectXmlConverter.kt | 2 | 3402 | /*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.android.upnp.cds
import net.mm2d.upnp.util.XmlUtils
import org.w3c.dom.Document
import org.w3c.dom.Element
import java.io.StringWriter
import javax.xml.parsers.ParserConfigurationException
import javax.xml.transform.OutputKeys
import javax.xml.transform.TransformerException
import javax.xml.transform.TransformerFactory
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult
/**
* AVTransport#SetAVTransportURIのCurrentURIMetaDataとして送信するXMLを作成するクラス。
*
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
object CdsObjectXmlConverter {
/**
* CdsObjectの情報からXMLを作成する。
*
* @param cdsObject CdsObject
* @return XML
*/
fun convert(cdsObject: CdsObject): String? {
if (!cdsObject.isItem) {
return null
}
try {
val document = XmlUtils.newDocument(false)
val didl = makeRootElement(document, cdsObject)
document.appendChild(didl)
val item = makeItemElement(document, cdsObject)
didl.appendChild(item)
(cdsObject as CdsObjectImpl).tagMap.map
.filter { it.key.isNotEmpty() }
.forEach {
it.value.forEach { tag ->
item.appendChild(makeElement(document, it.key, tag))
}
}
return formatXmlString(document)
} catch (ignored: ParserConfigurationException) {
} catch (ignored: TransformerException) {
} catch (ignored: IllegalArgumentException) {
}
return null
}
private fun makeElement(
document: Document,
tagName: String,
tag: Tag
): Element {
val element = document.createElement(tagName)
val value = tag.value
if (value.isNotEmpty()) {
element.textContent = value
}
tag.attributes.forEach {
element.setAttribute(it.key, it.value)
}
return element
}
private fun makeRootElement(
document: Document,
cdsObject: CdsObject
): Element {
val element = document.createElement(CdsObject.DIDL_LITE)
cdsObject.rootTag.attributes.forEach {
element.setAttribute(it.key, it.value)
}
return element
}
private fun makeItemElement(
document: Document,
cdsObject: CdsObject
): Element {
val tag = cdsObject.getTag("") ?: throw IllegalArgumentException()
return makeElement(document, CdsObject.ITEM, tag)
}
/**
* XML Documentを文字列に変換する
*
* @param document 変換するXML Document
* @return 変換された文字列
* @throws TransformerException 変換処理に問題が発生した場合
*/
@Throws(TransformerException::class)
private fun formatXmlString(document: Document): String = StringWriter().also {
val transformer = TransformerFactory.newInstance().newTransformer()
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes")
transformer.transform(DOMSource(document), StreamResult(it))
}.toString()
}
| mit | 2802029fc923229a1d1e3bd5e6178c51 | 29.754717 | 83 | 0.63681 | 4.295125 | false | false | false | false |
f-droid/fdroidclient | libs/index/src/androidMain/kotlin/org/fdroid/UpdateChecker.kt | 1 | 7777 | package org.fdroid
import android.content.pm.PackageInfo
import android.content.pm.PackageManager.GET_SIGNING_CERTIFICATES
import org.fdroid.index.IndexUtils.getPackageSignature
import org.fdroid.index.IndexUtils.getVersionCode
import org.fdroid.index.v2.PackageVersion
public interface PackagePreference {
public val ignoreVersionCodeUpdate: Long
public val releaseChannels: List<String>
}
public class UpdateChecker(
private val compatibilityChecker: CompatibilityChecker,
) {
/**
* Returns a [PackageVersion] for the given [packageInfo] that is the suggested update
* or null if there is no suitable update in [versions].
*
* Special case: A version with the [PackageInfo.getLongVersionCode] will be returned
* if [PackageVersion.hasKnownVulnerability] is true, even if there is no update.
*
* @param versions a **sorted** list of [PackageVersion] with highest version code first.
* @param packageInfo needs to be retrieved with [GET_SIGNING_CERTIFICATES]
* @param releaseChannels optional list of release channels to consider on top of stable.
* If this is null or empty, only versions without channel (stable) will be considered.
* @param preferencesGetter an optional way to consider additional per app preferences
*/
public fun <T : PackageVersion> getUpdate(
versions: List<T>,
packageInfo: PackageInfo,
releaseChannels: List<String>? = null,
preferencesGetter: (() -> PackagePreference?)? = null,
): T? = getUpdate(
versions = versions,
allowedSignersGetter = {
// always gives us the oldest signer, even if they rotated certs by now
@Suppress("DEPRECATION")
packageInfo.signatures.map { getPackageSignature(it.toByteArray()) }.toSet()
},
installedVersionCode = packageInfo.getVersionCode(),
allowedReleaseChannels = releaseChannels,
preferencesGetter = preferencesGetter,
)
/**
* Returns the [PackageVersion] that is suggested for a new installation
* or null if there is no suitable candidate in [versions].
*
* @param versions a **sorted** list of [PackageVersion] with highest version code first.
* @param preferredSigner The SHA-256 hash of the signing certificate in lower-case hex.
* Only versions from this signer will be considered for installation.
* @param releaseChannels optional list of release channels to consider on top of stable.
* If this is null or empty, only versions without channel (stable) will be considered.
* @param preferencesGetter an optional way to consider additional per app preferences
*/
public fun <T : PackageVersion> getSuggestedVersion(
versions: List<T>,
preferredSigner: String?,
releaseChannels: List<String>? = null,
preferencesGetter: (() -> PackagePreference?)? = null,
): T? = getUpdate(
versions = versions,
allowedSignersGetter = preferredSigner?.let { { setOf(it) } },
allowedReleaseChannels = releaseChannels,
preferencesGetter = preferencesGetter,
)
/**
* Returns the [PackageVersion] that is the suggested update
* for the given [installedVersionCode] or suggested for new installed if the given code is 0,
* or null if there is no suitable candidate in [versions].
*
* Special case: A version with the [installedVersionCode] will be returned
* if [PackageVersion.hasKnownVulnerability] is true, even if there is no update.
*
* @param versions a **sorted** list of [PackageVersion] with highest version code first.
* @param allowedSignersGetter should return set of SHA-256 hashes of the signing certificates
* in lower-case hex. Only versions from these signers will be considered for installation.
* This is is null or returns null, all signers will be allowed.
* If the set of signers is empty, no signers will be allowed, i.e. only apps without signer.
* @param allowedReleaseChannels optional list of release channels to consider on top of stable.
* If this is null or empty, only versions without channel (stable) will be considered.
* @param preferencesGetter an optional way to consider additional per app preferences
*/
public fun <T : PackageVersion> getUpdate(
versions: List<T>,
allowedSignersGetter: (() -> Set<String>?)? = null,
installedVersionCode: Long = 0,
allowedReleaseChannels: List<String>? = null,
preferencesGetter: (() -> PackagePreference?)? = null,
): T? {
// getting signatures is rather expensive, so we only do that when there's update candidates
val allowedSigners by lazy { allowedSignersGetter?.let { it() } }
versions.iterator().forEach versions@{ version ->
// if the installed version has a known vulnerability, we return it as well
if (version.versionCode == installedVersionCode && version.hasKnownVulnerability) {
return version
}
// if version code is not higher than installed skip package as list is sorted
if (version.versionCode <= installedVersionCode) return null
// we don't support versions that have multiple signers
if (version.signer?.hasMultipleSigners == true) return@versions
// skip incompatible versions
if (!compatibilityChecker.isCompatible(version.packageManifest)) return@versions
// check if we should ignore this version code
val packagePreference = preferencesGetter?.let { it() }
val ignoreVersionCode = packagePreference?.ignoreVersionCodeUpdate ?: 0
if (ignoreVersionCode >= version.versionCode) return@versions
// check if release channel of version is allowed
val hasAllowedReleaseChannel = hasAllowedReleaseChannel(
allowedReleaseChannels = allowedReleaseChannels?.toMutableSet() ?: LinkedHashSet(),
versionReleaseChannels = version.releaseChannels,
packagePreference = packagePreference,
)
if (!hasAllowedReleaseChannel) return@versions
// check if this version's signer is allowed
val versionSigners = version.signer?.sha256?.toSet()
// F-Droid allows versions without signature 🤦, allow those and if no allowed signers
if (versionSigners != null && allowedSigners != null) {
if (versionSigners.intersect(allowedSigners!!).isEmpty()) return@versions
}
// no need to see other versions, we got the highest version code per sorting
return version
}
return null
}
private fun hasAllowedReleaseChannel(
allowedReleaseChannels: MutableSet<String>,
versionReleaseChannels: List<String>?,
packagePreference: PackagePreference?,
): Boolean {
// no channels (aka stable version) is always allowed
if (versionReleaseChannels.isNullOrEmpty()) return true
// add release channels from package preferences into the ones we allow
val extraChannels = packagePreference?.releaseChannels
if (!extraChannels.isNullOrEmpty()) {
allowedReleaseChannels.addAll(extraChannels)
}
// if allowed releases channels are empty (only stable) don't consider this version
if (allowedReleaseChannels.isEmpty()) return false
// don't consider version with non-matching release channel
if (allowedReleaseChannels.intersect(versionReleaseChannels).isEmpty()) return false
// one of the allowed channels is present in this version
return true
}
}
| gpl-3.0 | c814f05c26c61b3b63c9de181d4a8fdb | 50.144737 | 100 | 0.68459 | 5.044776 | false | false | false | false |
youlookwhat/CloudReader | app/src/main/java/com/example/jingbin/cloudreader/utils/UpdateUtil.kt | 1 | 3758 | package com.example.jingbin.cloudreader.utils
import android.content.DialogInterface
import androidx.appcompat.app.AlertDialog
import com.example.jingbin.cloudreader.BuildConfig
import com.example.jingbin.cloudreader.app.Constants
import com.example.jingbin.cloudreader.bean.UpdateBean
import com.example.jingbin.cloudreader.http.HttpClient
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import me.jingbin.bymvvm.base.BaseActivity
/**
* Created by jingbin on 2020/12/3.
*/
class UpdateUtil {
companion object {
/**
* 检查更新
*
* @param isShowToast 是否弹出更新框
*/
@JvmStatic
fun check(activity: BaseActivity<*, *>?, isShowToast: Boolean) {
if (activity == null) {
return
}
val subscribe = HttpClient.Builder.getGiteeServer().checkUpdate()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Consumer<UpdateBean?> {
override fun accept(updateBean: UpdateBean?) { // 检查更新
if (updateBean != null && Integer.valueOf(updateBean.version) <= BuildConfig.VERSION_CODE) {
if (isShowToast) {
ToastUtil.showToastLong("已是最新版本~")
}
return
}
// 进入应用体提示更新
if (updateBean != null && "1" == updateBean.isShow && !updateBean.installUrl.isNullOrEmpty()) {
val builder = AlertDialog.Builder(activity)
// 返回无效
builder.setCancelable(false)
builder.setTitle("发现新版本")
.setMessage(String.format("版本号: %s\n更新时间: %s\n更新内容:\n%s",
updateBean.versionShort,
TimeUtil.formatDataTime((updateBean.updated_at.toString() + "000").toLong()),
updateBean.changelog))
builder.setNegativeButton("取消", null)
builder.setPositiveButton("立即下载") { _: DialogInterface?, i: Int ->
when {
// isJumpMarket == 1 跳应用市场
updateBean.isJumpMarket == 1
&& BaseTools.hasPackage(activity, Constants.COOLAPK_PACKAGE)
&& BaseTools.launchAppDetail(activity, activity.packageName, Constants.COOLAPK_PACKAGE) -> {
}
else -> {
BaseTools.openLink(activity, updateBean.installUrl)
}
}
}
builder.show()
}
}
}, Consumer<Throwable?> {
if (isShowToast) {
ToastUtil.showToastLong("抱歉,检查失败,请进入链接查看或联系作者~")
}
})
activity.addSubscription(subscribe)
}
}
} | apache-2.0 | ef4c1bed5f6d5d2b3301bd337b2df4d4 | 46.96 | 140 | 0.451613 | 5.772071 | false | false | false | false |
google/horologist | media-ui/src/debug/java/com/google/android/horologist/media/ui/components/controls/SeekBackButtonPreview.kt | 1 | 2343 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalHorologistMediaUiApi::class)
package com.google.android.horologist.media.ui.components.controls
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
@Preview(
name = "5 seconds increment - Enabled",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun SeekBackButtonPreview5() {
SeekBackButton(
onClick = {},
seekButtonIncrement = SeekButtonIncrement.Five
)
}
@Preview(
name = "10 seconds increment - Disabled",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun SeekBackButtonPreview10() {
SeekBackButton(
onClick = {},
seekButtonIncrement = SeekButtonIncrement.Ten,
enabled = false
)
}
@Preview(
name = "30 seconds increment - Enabled",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun SeekBackButtonPreview30() {
SeekBackButton(
onClick = {},
seekButtonIncrement = SeekButtonIncrement.Thirty
)
}
@Preview(
name = "Other amount of seconds increment - Disabled",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun SeekBackButtonPreviewOther() {
SeekBackButton(
onClick = {},
seekButtonIncrement = SeekButtonIncrement.Known(15),
enabled = false
)
}
@Preview(
name = "Unknown amount of seconds increment - Enabled",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun SeekBackButtonPreviewUnknown() {
SeekBackButton(
onClick = {},
seekButtonIncrement = SeekButtonIncrement.Unknown
)
}
| apache-2.0 | ec2e00d1fbd167184900648095035f59 | 25.033333 | 78 | 0.711481 | 4.488506 | false | false | false | false |
jdinkla/groovy-java-ray-tracer | src/test/kotlin/net/dinkla/raytracer/objects/CompoundTest.kt | 1 | 635 | package net.dinkla.raytracer.objects
import net.dinkla.raytracer.math.MathUtils
import net.dinkla.raytracer.objects.compound.Compound
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.assertEquals
class CompoundTest {
@Test
@Throws(Exception::class)
fun testGetBoundingBox() {
val s = Sphere(radius = 1.0)
val c = Compound()
c.add(s)
val bboxC = c.boundingBox
val bboxS = s.boundingBox
assertEquals(bboxC.p, bboxS.p.minus(MathUtils.K_EPSILON))
assertEquals(bboxC.q, bboxS.q.plus(MathUtils.K_EPSILON))
}
}
| apache-2.0 | b6420b4628119e29e0eb53fe6464cf12 | 22.423077 | 65 | 0.658268 | 3.69186 | false | true | false | false |
DenverM80/ds3_autogen | ds3-autogen-go/src/main/kotlin/com/spectralogic/ds3autogen/go/generators/parser/BaseTypeParserGenerator.kt | 1 | 8994 | /*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.spectralogic.ds3autogen.go.generators.parser
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableMap
import com.spectralogic.ds3autogen.api.models.apispec.Ds3Element
import com.spectralogic.ds3autogen.api.models.apispec.Ds3Type
import com.spectralogic.ds3autogen.go.models.parser.*
import com.spectralogic.ds3autogen.go.utils.toGoType
import com.spectralogic.ds3autogen.utils.ConverterUtil
import com.spectralogic.ds3autogen.utils.Ds3ElementUtil
import com.spectralogic.ds3autogen.utils.NormalizingContractNamesUtil
import com.spectralogic.ds3autogen.utils.collections.GuavaCollectors
open class BaseTypeParserGenerator : TypeParserModelGenerator<TypeParser>, TypeParserGeneratorUtil {
override fun generate(ds3Type: Ds3Type, typeMap: ImmutableMap<String, Ds3Type>): TypeParser {
val modelName = NormalizingContractNamesUtil.removePath(ds3Type.name)
val name = modelName + "Parser"
val attributes = toAttributeList(ds3Type.elements, modelName)
val childNodes = toChildNodeList(ds3Type.elements, modelName, typeMap)
return TypeParser(name, modelName, attributes, childNodes)
}
/**
* Converts all non-attribute elements within a Ds3Element list into ParsingElements, which
* contain the Go code for parsing the Ds3Elements as child nodes.
*/
override fun toChildNodeList(
ds3Elements: ImmutableList<Ds3Element>?,
typeName: String,
typeMap: ImmutableMap<String, Ds3Type>): ImmutableList<ParseElement> {
if (ConverterUtil.isEmpty(ds3Elements)) {
return ImmutableList.of()
}
return ds3Elements!!.stream()
.filter { ds3Element -> !Ds3ElementUtil.isAttribute(ds3Element.ds3Annotations) }
.map { ds3Element -> toChildNode(ds3Element, typeName, typeMap) }
.collect(GuavaCollectors.immutableList())
}
/**
* Converts a Ds3Element into a ParsingElements.There are no special-cased Ds3Elements within
* the BaseTypeParserGenerator.
*/
override fun toChildNode(ds3Element: Ds3Element, typeName: String, typeMap: ImmutableMap<String, Ds3Type>): ParseElement {
return toStandardChildNode(ds3Element, typeName, typeMap)
}
/**
* Converts a Ds3Element into a ParsingElement, which contains the Go code for parsing the
* specified Ds3Element as a child node. This assumes that the specified Ds3Element is not an attribute.
*/
fun toStandardChildNode(ds3Element: Ds3Element, typeName: String, typeMap: ImmutableMap<String, Ds3Type>): ParseElement {
val xmlTag = getXmlTagName(ds3Element)
val modelName = typeName.decapitalize()
val paramName = ds3Element.name.capitalize()
// Handle case if there is an encapsulating tag around a list of elements
if (Ds3ElementUtil.hasWrapperAnnotations(ds3Element.ds3Annotations)) {
val encapsulatingTag = Ds3ElementUtil.getEncapsulatingTagAnnotations(ds3Element.ds3Annotations).capitalize()
val childType = NormalizingContractNamesUtil.removePath(ds3Element.componentType)
// Handle if the slice is common prefixes
if (encapsulatingTag == "CommonPrefixes") {
return ParseChildNodeAsCommonPrefix(modelName, paramName)
}
return ParseChildNodeAsSlice(encapsulatingTag, xmlTag, modelName, paramName, childType)
}
// Handle case if there is a slice to be parsed (no encapsulating tag)
if (ds3Element.type.equals("array")) {
val childType = toGoType(ds3Element.componentType!!)
// Handle if the slice is a Ds3Type defined enum
if (isElementEnum(ds3Element.componentType!!, typeMap)) {
return ParseChildNodeAddEnumToSlice(xmlTag, modelName, paramName, childType)
}
return ParseChildNodeAddToSlice(xmlTag, modelName, paramName, childType)
}
// Handle case if the element is an enum
if (isElementEnum(ds3Element.type!!, typeMap)) {
if (ds3Element.nullable) {
return ParseChildNodeAsNullableEnum(xmlTag, modelName, paramName)
}
return ParseChildNodeAsEnum(xmlTag, modelName, paramName)
}
val goType = toGoType(ds3Element.type, ds3Element.componentType, ds3Element.nullable)
val parserNamespace = getPrimitiveTypeParserNamespace(ds3Element.type!!, ds3Element.nullable)
when (goType) {
"bool", "*bool", "int", "*int", "int64", "*int64", "float64", "*float64" ->
return ParseChildNodeAsPrimitiveType(xmlTag, modelName, paramName, parserNamespace)
"string", "*string" ->
return ParseChildNodeAsString(xmlTag, modelName, paramName, parserNamespace)
else -> {
// All remaining elements represent Ds3Types
if (goType.first() == '*') {
return ParseChildNodeAsNullableDs3Type(xmlTag, modelName, paramName, goType.drop(1))
}
return ParseChildNodeAsDs3Type(xmlTag, modelName, paramName)
}
}
}
/**
* Determines if the specified type is an enum.
*/
fun isElementEnum(elementType: String, typeMap: ImmutableMap<String, Ds3Type>): Boolean {
if (ConverterUtil.isEmpty(typeMap)) {
return false
}
val ds3Type = typeMap[elementType] ?: return false
return ConverterUtil.isEnum(ds3Type)
}
/**
* Converts all attributes within a Ds3Element list into ParsingElements which contain the
* Go code for parsing the attributes.
*/
fun toAttributeList(ds3Elements: ImmutableList<Ds3Element>?, typeName: String): ImmutableList<ParseElement> {
if (ConverterUtil.isEmpty(ds3Elements)) {
return ImmutableList.of()
}
return ds3Elements!!.stream()
.filter { ds3Element -> Ds3ElementUtil.isAttribute(ds3Element.ds3Annotations) }
.map { ds3Element -> toAttribute(ds3Element, typeName) }
.collect(GuavaCollectors.immutableList())
}
/**
* Converts a Ds3Element into a ParsingElement, which contains the Go code for parsing the
* specified Ds3Element attribute. This assumes that the specified Ds3Element is an attribute.
*/
fun toAttribute(ds3Element: Ds3Element, typeName: String): ParseElement {
val xmlName = getXmlTagName(ds3Element)
val goType = toGoType(ds3Element.type, ds3Element.componentType, ds3Element.nullable)
val modelName = typeName.decapitalize()
val paramName = ds3Element.name.capitalize()
when (goType) {
"bool", "*bool", "int", "*int", "int64", "*int64", "float64", "*float64" -> {
val parserNamespace = getPrimitiveTypeParserNamespace(ds3Element.type!!, ds3Element.nullable)
return ParseSimpleAttr(xmlName, modelName, paramName, parserNamespace)
}
"string" ->
return ParseStringAttr(xmlName, modelName, paramName)
"*string" ->
return ParseNullableStringAttr(xmlName, modelName, paramName)
else -> {
if (ds3Element.nullable) {
return ParseNullableEnumAttr(xmlName, modelName, paramName)
}
return ParseEnumAttr(xmlName, modelName, paramName)
}
}
}
/**
* Retrieves the xml tag name for the specified Ds3Element. The result is capitalized.
*/
fun getXmlTagName(ds3Element: Ds3Element): String {
return Ds3ElementUtil.getXmlTagName(ds3Element).capitalize()
}
/**
* Gets the namespace of the required primitive type parser used to parse
* the specified type. Assumes that the provided type is a Go primitive, or
* a pointer to a Go primitive type.
*/
fun getPrimitiveTypeParserNamespace(type: String, nullable: Boolean): String {
val parserPrefix = toGoType(type).capitalize()
if (nullable) {
return "Nullable$parserPrefix"
}
return parserPrefix
}
} | apache-2.0 | f48ebabd83a7e8837fccaffee1e08334 | 43.975 | 126 | 0.660551 | 4.703975 | false | false | false | false |
google/chromeosnavigationdemo | app/src/main/java/com/emilieroberts/chromeosnavigationdemo/FileBrowserFragment.kt | 1 | 3009 | /*
* Copyright 2019 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.emilieroberts.chromeosnavigationdemo
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import java.lang.IllegalArgumentException
class FileBrowserFragment : Fragment(), FilesAdapter.RecyclerViewFileActionsListener {
private lateinit var fileBehaviorViewModel: AdaptableDemoViewModel
lateinit var fileActionsListener: FileActionsListener
private var imagePreview: ImageView? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val mainView: View = inflater.inflate(R.layout.file_browser, container, false)
imagePreview = mainView.findViewById(R.id.image_preview)
val recycler: RecyclerView = mainView.findViewById(R.id.recyclerview_main) as RecyclerView
val fileListAdapter = FilesAdapter(this)
recycler.layoutManager = LinearLayoutManager(requireContext())
recycler.adapter = fileListAdapter
fileBehaviorViewModel = ViewModelProviders.of(requireActivity()).get(AdaptableDemoViewModel::class.java)
fileBehaviorViewModel.getFileSource().observe(this, Observer { fileSource ->
fileListAdapter.submitList(FileStore.getFilesForSource(fileSource))
})
fileBehaviorViewModel.getCurrentPhotoId().observe(this, Observer { fileId ->
imagePreview?.setImageResource(fileId)
})
return mainView
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is FileActionsListener) {
fileActionsListener = context
} else {
throw IllegalArgumentException("Activity needs to implement the FileActionsListener interface")
}
}
override fun onListItemClick(filePosition: Int, fileId: Int) {
fileActionsListener.onFileClick(filePosition, fileId)
}
override fun onListItemFocus(imageId: Int) {
fileBehaviorViewModel.setCurrentPhotoId(imageId)
}
interface FileActionsListener {
fun onFileClick (filePosition: Int, fileId: Int)
}
} | apache-2.0 | 3ad2983d38d033f29785eec3a9ea5fc9 | 39.675676 | 115 | 0.749751 | 5.006656 | false | false | false | false |
talhacohen/android | app/src/main/java/com/etesync/syncadapter/syncadapter/ContactsSyncManager.kt | 1 | 10276 | /*
* Copyright © 2013 – 2015 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.syncadapter
import android.accounts.Account
import android.content.*
import android.os.Bundle
import android.provider.ContactsContract
import at.bitfire.ical4android.CalendarStorageException
import at.bitfire.vcard4android.BatchOperation
import at.bitfire.vcard4android.Contact
import at.bitfire.vcard4android.ContactsStorageException
import com.etesync.syncadapter.*
import com.etesync.syncadapter.journalmanager.Exceptions
import com.etesync.syncadapter.journalmanager.JournalEntryManager
import com.etesync.syncadapter.model.CollectionInfo
import com.etesync.syncadapter.model.SyncEntry
import com.etesync.syncadapter.resource.LocalAddress
import com.etesync.syncadapter.resource.LocalAddressBook
import com.etesync.syncadapter.resource.LocalContact
import com.etesync.syncadapter.resource.LocalGroup
import okhttp3.HttpUrl
import okhttp3.Request
import org.apache.commons.collections4.SetUtils
import java.io.FileNotFoundException
import java.io.IOException
import java.io.StringReader
import java.util.logging.Level
/**
*
* Synchronization manager for CardDAV collections; handles contacts and groups.
*/
class ContactsSyncManager @Throws(Exceptions.IntegrityException::class, Exceptions.GenericCryptoException::class, ContactsStorageException::class)
constructor(context: Context, account: Account, settings: AccountSettings, extras: Bundle, authority: String, private val provider: ContentProviderClient, result: SyncResult, localAddressBook: LocalAddressBook, private val remote: HttpUrl) : SyncManager<LocalAddress>(context, account, settings, extras, authority, result, localAddressBook.url, CollectionInfo.Type.ADDRESS_BOOK, localAddressBook.mainAccount.name) {
protected override val syncErrorTitle: String
get() = context.getString(R.string.sync_error_contacts, account.name)
protected override val syncSuccessfullyTitle: String
get() = context.getString(R.string.sync_successfully_contacts, account.name)
init {
localCollection = localAddressBook
}
override fun notificationId(): Int {
return Constants.NOTIFICATION_CONTACTS_SYNC
}
@Throws(ContactsStorageException::class, CalendarStorageException::class)
override fun prepare(): Boolean {
if (!super.prepare())
return false
val localAddressBook = localAddressBook()
if (LocalContact.HASH_HACK) {
// workaround for Android 7 which sets DIRTY flag when only meta-data is changed
val reallyDirty = localAddressBook.verifyDirty()
val deleted = localAddressBook.findDeleted().size
if (extras.containsKey(ContentResolver.SYNC_EXTRAS_UPLOAD) && reallyDirty == 0 && deleted == 0) {
App.log.info("This sync was called to up-sync dirty/deleted contacts, but no contacts have been changed")
return false
}
}
// set up Contacts Provider Settings
val values = ContentValues(2)
values.put(ContactsContract.Settings.SHOULD_SYNC, 1)
values.put(ContactsContract.Settings.UNGROUPED_VISIBLE, 1)
localAddressBook.settings.putAll(values)
journal = JournalEntryManager(httpClient, remote, localAddressBook.url!!)
localAddressBook.includeGroups = true
return true
}
@Throws(CalendarStorageException::class, ContactsStorageException::class)
override fun prepareDirty() {
super.prepareDirty()
val addressBook = localAddressBook()
/* groups as separate VCards: there are group contacts and individual contacts */
// mark groups with changed members as dirty
val batch = BatchOperation(addressBook.provider!!)
for (contact in addressBook.findDirtyContacts()) {
try {
App.log.fine("Looking for changed group memberships of contact " + contact.fileName)
val cachedGroups = contact.getCachedGroupMemberships()
val currentGroups = contact.getGroupMemberships()
for (groupID in SetUtils.disjunction(cachedGroups, currentGroups)) {
App.log.fine("Marking group as dirty: " + groupID!!)
batch.enqueue(BatchOperation.Operation(
ContentProviderOperation.newUpdate(addressBook.syncAdapterURI(ContentUris.withAppendedId(ContactsContract.Groups.CONTENT_URI, groupID)))
.withValue(ContactsContract.Groups.DIRTY, 1)
.withYieldAllowed(true)
))
}
} catch (ignored: FileNotFoundException) {
}
}
batch.commit()
}
@Throws(CalendarStorageException::class, ContactsStorageException::class)
override fun postProcess() {
super.postProcess()
/* VCard4 group handling: there are group contacts and individual contacts */
App.log.info("Assigning memberships of downloaded contact groups")
LocalGroup.applyPendingMemberships(localAddressBook())
}
// helpers
private fun localAddressBook(): LocalAddressBook {
return localCollection as LocalAddressBook
}
@Throws(IOException::class, ContactsStorageException::class, CalendarStorageException::class)
override fun processSyncEntry(cEntry: SyncEntry) {
val inputReader = StringReader(cEntry.content)
val downloader = ResourceDownloader(context)
val contacts = Contact.fromReader(inputReader, downloader)
if (contacts.size == 0) {
App.log.warning("Received VCard without data, ignoring")
return
} else if (contacts.size > 1)
App.log.warning("Received multiple VCards, using first one")
val contact = contacts[0]
val local = localCollection!!.findByUid(contact.uid!!)
if (cEntry.isAction(SyncEntry.Actions.ADD) || cEntry.isAction(SyncEntry.Actions.CHANGE)) {
processContact(contact, local)
} else {
if (local != null) {
App.log.info("Removing local record which has been deleted on the server")
local.delete()
} else {
App.log.warning("Tried deleting a non-existent record: " + contact.uid)
}
}
}
@Throws(IOException::class, ContactsStorageException::class)
private fun processContact(newData: Contact, _local: LocalAddress?): LocalAddress {
var local = _local
val uuid = newData.uid
// update local contact, if it exists
if (local != null) {
App.log.log(Level.INFO, "Updating $uuid in local address book")
if (local is LocalGroup && newData.group) {
// update group
val group: LocalGroup = local
group.eTag = uuid
group.update(newData)
syncResult.stats.numUpdates++
} else if (local is LocalContact && !newData.group) {
// update contact
val contact: LocalContact = local
contact.eTag = uuid
contact.update(newData)
syncResult.stats.numUpdates++
} else {
// group has become an individual contact or vice versa
try {
local.delete()
local = null
} catch (e: CalendarStorageException) {
// CalendarStorageException is not used by LocalGroup and LocalContact
}
}
}
if (local == null) {
if (newData.group) {
App.log.log(Level.INFO, "Creating local group", newData.uid)
val group = LocalGroup(localAddressBook(), newData, uuid, uuid)
group.add()
local = group
} else {
App.log.log(Level.INFO, "Creating local contact", newData.uid)
val contact = LocalContact(localAddressBook(), newData, uuid, uuid)
contact.add()
local = contact
}
syncResult.stats.numInserts++
}
if (LocalContact.HASH_HACK && local is LocalContact)
// workaround for Android 7 which sets DIRTY flag when only meta-data is changed
local.updateHashCode(null)
return local
}
// downloader helper class
class ResourceDownloader(internal var context: Context) : Contact.Downloader {
override fun download(url: String, accepts: String): ByteArray? {
val httpUrl = HttpUrl.parse(url)
if (httpUrl == null) {
App.log.log(Level.SEVERE, "Invalid external resource URL", url)
return null
}
val host = httpUrl.host()
if (host == null) {
App.log.log(Level.SEVERE, "External resource URL doesn't specify a host name", url)
return null
}
var resourceClient = HttpClient.create(context)
// authenticate only against a certain host, and only upon request
// resourceClient = HttpClient.addAuthentication(resourceClient, baseUrl.host(), settings.username(), settings.password());
// allow redirects
resourceClient = resourceClient.newBuilder()
.followRedirects(true)
.build()
try {
val response = resourceClient.newCall(Request.Builder()
.get()
.url(httpUrl)
.build()).execute()
val body = response.body()
if (body != null) {
return body.bytes()
}
} catch (e: IOException) {
App.log.log(Level.SEVERE, "Couldn't download external resource", e)
}
return null
}
}
}
| gpl-3.0 | 94b92e7e0e0da5a83c428b81740737e0 | 38.060837 | 415 | 0.634089 | 5.078102 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/icons/RsIcons.kt | 1 | 3181 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.icons
import com.intellij.icons.AllIcons
import com.intellij.openapi.util.IconLoader
import com.intellij.ui.LayeredIcon
import com.intellij.ui.RowIcon
import com.intellij.util.PlatformIcons
import javax.swing.Icon
/**
* Icons that are used by various plugin components.
*
* The order of properties matters in this class. When conflating an icon from simple elements,
* make sure that all those elements are declared above to the icon.
*/
object RsIcons {
// Logos
val RUST = IconLoader.getIcon("/icons/rust.png")
// File types
val RUST_FILE = IconLoader.getIcon("/icons/rust-file.png")
val MAIN_RS = IconLoader.getIcon("/icons/main-rs.png")
val MOD_RS = IconLoader.getIcon("/icons/mod-rs.png")
// Marks
val FINAL_MARK = AllIcons.Nodes.FinalMark!!
val STATIC_MARK = AllIcons.Nodes.StaticMark!!
val TEST_MARK = AllIcons.Nodes.JunitTestMark!!
val DOCS_MARK = IconLoader.getIcon("/icons/docsrs.png")
// Source code elements
val CRATE = AllIcons.Nodes.PpLib!!
val MODULE = AllIcons.Nodes.Package!!
val TRAIT = AllIcons.Nodes.Interface!!
val STRUCT = AllIcons.Nodes.Class!!
val TYPE = AllIcons.Nodes.Class!!
val IMPL = AllIcons.Nodes.AbstractClass!!
val ENUM = AllIcons.Nodes.Enum!!
val METHOD = AllIcons.Nodes.Method!!
val FUNCTION = IconLoader.getIcon("/icons/nodes/function.png")
val ASSOC_FUNCTION = FUNCTION.addStaticMark()
val MACRO = AllIcons.General.ExclMark!!
val ABSTRACT_METHOD = AllIcons.Nodes.AbstractMethod!!
val ABSTRACT_FUNCTION = IconLoader.getIcon("/icons/nodes/abstractFunction.png")
val ABSTRACT_ASSOC_FUNCTION = ABSTRACT_FUNCTION.addStaticMark()
val ATTRIBUTE = AllIcons.Nodes.Annotationtype!!
val MUT_ARGUMENT = AllIcons.Nodes.Parameter!!
val ARGUMENT = MUT_ARGUMENT.addFinalMark()
val FIELD = AllIcons.Nodes.Field!!
val MUT_BINDING = AllIcons.Nodes.Variable!!
val BINDING = MUT_BINDING.addFinalMark()
val GLOBAL_BINDING = IconLoader.getIcon("/icons/nodes/globalBinding.png")
val CONSTANT = GLOBAL_BINDING.addFinalMark()
val MUT_STATIC = GLOBAL_BINDING.addStaticMark()
val STATIC = MUT_STATIC.addFinalMark()
val ENUM_VARIANT = FIELD.addFinalMark().addStaticMark()
// Gutter
val IMPLEMENTED = AllIcons.Gutter.ImplementedMethod!!
val IMPLEMENTING_METHOD = AllIcons.Gutter.ImplementingMethod!!
val OVERRIDING_METHOD = AllIcons.Gutter.OverridingMethod!!
val RECURSIVE_CALL = AllIcons.Gutter.RecursiveMethod!!
}
fun Icon.addFinalMark(): Icon = LayeredIcon(this, RsIcons.FINAL_MARK)
fun Icon.addStaticMark(): Icon = LayeredIcon(this, RsIcons.STATIC_MARK)
fun Icon.addTestMark(): Icon = LayeredIcon(this, RsIcons.TEST_MARK)
fun Icon.addVisibilityIcon(pub: Boolean): RowIcon =
RowIcon(this, if (pub) PlatformIcons.PUBLIC_ICON else PlatformIcons.PRIVATE_ICON)
fun Icon.multiple(): Icon {
val compoundIcon = LayeredIcon(2)
compoundIcon.setIcon(this, 0, 2 * iconWidth / 5, 0)
compoundIcon.setIcon(this, 1, 0, 0)
return compoundIcon
}
| mit | 435ae55ca789dc1629646d2b84146d99 | 33.204301 | 95 | 0.724301 | 3.841787 | false | false | false | false |
jtransc/jtransc | jtransc-utils/src/com/jtransc/vfs/tree.kt | 2 | 1658 | package com.jtransc.vfs
import com.jtransc.vfs.node.FileNodeIO
import com.jtransc.vfs.node.FileNodeTree
import com.jtransc.vfs.node.FileNodeType
import java.util.*
open class BaseTreeVfs(val tree: FileNodeTree) : SyncVfs() {
protected val _root = tree.root
override val absolutePath: String get() = ""
override fun read(path: String): ByteArray {
return _root.access(path).io?.read()!!
}
override fun write(path: String, data: ByteArray): Unit {
val item = _root.access(path, true)
var writtenData = data
var writtenTime = Date()
item.type = FileNodeType.FILE
item.io = object : FileNodeIO() {
override fun mtime(): Date = writtenTime
override fun read(): ByteArray = writtenData
override fun write(data: ByteArray) {
writtenTime = Date()
writtenData = data
}
override fun size(): Long = writtenData.size.toLong()
override fun mode(): FileMode = FileMode.FULL_ACCESS
}
}
override fun listdir(path: String): Iterable<SyncVfsStat> {
return _root.access(path).map {
it.toSyncStat(this, "${path}/${it.name}")
}
}
override fun mkdir(path: String): Unit {
_root.access(path, true)
}
override fun rmdir(path: String): Unit {
try {
val node = _root.access(path, false)
node.remove()
} catch (e: Throwable) {
}
}
override fun exists(path: String): Boolean {
try {
_root.access(path)
return true
} catch(e: Throwable) {
return false
}
}
override fun remove(path: String): Unit = _root.access(path).remove()
override fun stat(path: String): SyncVfsStat = _root.access(path).toSyncStat(this, path)
override fun setMtime(path: String, time: Date) {
// @TODO!
}
}
| apache-2.0 | e6533962221c8bf72c4c6fe6f8b422e7 | 23.382353 | 89 | 0.681544 | 3.122411 | false | false | false | false |
Fitbit/MvRx | todomvrx/src/main/java/com/airbnb/mvrx/todomvrx/core/BaseFragment.kt | 1 | 4088 | package com.airbnb.mvrx.todomvrx.core
import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.annotation.IdRes
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.airbnb.epoxy.EpoxyRecyclerView
import com.airbnb.mvrx.Mavericks
import com.airbnb.mvrx.MvRxView
import com.airbnb.mvrx.activityViewModel
import com.airbnb.mvrx.todomvrx.TasksState
import com.airbnb.mvrx.todomvrx.TasksViewModel
import com.airbnb.mvrx.todomvrx.data.Tasks
import com.airbnb.mvrx.todomvrx.data.findTask
import com.airbnb.mvrx.todomvrx.todoapp.R
import com.airbnb.mvrx.todomvrx.util.ToDoEpoxyController
import com.airbnb.mvrx.todomvrx.util.showLongSnackbar
import com.google.android.material.floatingactionbutton.FloatingActionButton
abstract class BaseFragment : Fragment(), MvRxView {
protected val viewModel by activityViewModel(TasksViewModel::class)
protected lateinit var coordinatorLayout: CoordinatorLayout
protected lateinit var recyclerView: EpoxyRecyclerView
protected lateinit var fab: FloatingActionButton
protected val epoxyController by lazy { epoxyController() }
// Used to keep track of task changes to determine if we should show a snackbar.
private var oldTasks: Tasks? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
epoxyController.onRestoreInstanceState(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_base, container, false).apply {
coordinatorLayout = findViewById(R.id.coordinator_layout)
fab = findViewById(R.id.fab)
recyclerView = findViewById(R.id.recycler_view)
recyclerView.setController(epoxyController)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
epoxyController.onSaveInstanceState(outState)
}
@CallSuper
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
viewModel.selectSubscribe(TasksState::tasks, TasksState::lastEditedTask) { tasks, lastEditedTask ->
if (oldTasks == null) {
oldTasks = tasks
return@selectSubscribe
}
if (oldTasks?.any { it.complete } == true && !tasks.any { it.complete }) {
coordinatorLayout.showLongSnackbar(R.string.completed_tasks_cleared)
}
val oldTask = oldTasks?.findTask(lastEditedTask)
val newTask = tasks.findTask(lastEditedTask)
if (oldTask == newTask) return@selectSubscribe
val message = when {
oldTask == null -> R.string.successfully_added_task_message
newTask == null -> R.string.successfully_deleted_task_message
oldTask.title != newTask.title || oldTask.description != newTask.description ->
R.string.successfully_saved_task_message
oldTask.complete && !newTask.complete -> R.string.task_marked_active
!oldTask.complete && newTask.complete -> R.string.task_marked_complete
else -> 0
}
if (message != 0) {
coordinatorLayout.showLongSnackbar(message)
}
oldTasks = tasks
}
viewModel.asyncSubscribe(TasksState::taskRequest, onFail = {
coordinatorLayout.showLongSnackbar(R.string.loading_tasks_error)
})
}
override fun invalidate() {
recyclerView.requestModelBuild()
}
abstract fun epoxyController(): ToDoEpoxyController
protected fun navigate(@IdRes id: Int, args: Parcelable? = null) {
findNavController().navigate(id, Bundle().apply { putParcelable(Mavericks.KEY_ARG, args) })
}
}
| apache-2.0 | 0aec78b790a3aee497a653671c42b58c | 39.88 | 116 | 0.703033 | 4.843602 | false | false | false | false |
square/moshi | moshi-kotlin-codegen/src/main/java/com/squareup/moshi/kotlin/codegen/api/typeAliasUnwrapping.kt | 1 | 2575 | /*
* 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.
*/
package com.squareup.moshi.kotlin.codegen.api
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.Dynamic
import com.squareup.kotlinpoet.LambdaTypeName
import com.squareup.kotlinpoet.ParameterizedTypeName
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeVariableName
import com.squareup.kotlinpoet.WildcardTypeName
import com.squareup.kotlinpoet.tag
import com.squareup.kotlinpoet.tags.TypeAliasTag
import java.util.TreeSet
private fun TypeName.unwrapTypeAliasInternal(): TypeName? {
return tag<TypeAliasTag>()?.abbreviatedType?.let { unwrappedType ->
// Keep track of all annotations across type levels. Sort them too for consistency.
val runningAnnotations = TreeSet<AnnotationSpec>(compareBy { it.toString() }).apply {
addAll(annotations)
}
val nestedUnwrappedType = unwrappedType.unwrapTypeAlias()
runningAnnotations.addAll(nestedUnwrappedType.annotations)
// If any type is nullable, then the whole thing is nullable
val isAnyNullable = isNullable || nestedUnwrappedType.isNullable
nestedUnwrappedType.copy(nullable = isAnyNullable, annotations = runningAnnotations.toList())
}
}
internal fun TypeName.unwrapTypeAlias(): TypeName {
return when (this) {
is ClassName -> unwrapTypeAliasInternal() ?: this
is ParameterizedTypeName -> {
unwrapTypeAliasInternal() ?: deepCopy(TypeName::unwrapTypeAlias)
}
is TypeVariableName -> {
unwrapTypeAliasInternal() ?: deepCopy(transform = TypeName::unwrapTypeAlias)
}
is WildcardTypeName -> {
unwrapTypeAliasInternal() ?: deepCopy(TypeName::unwrapTypeAlias)
}
is LambdaTypeName -> {
unwrapTypeAliasInternal() ?: deepCopy(TypeName::unwrapTypeAlias)
}
Dynamic -> throw UnsupportedOperationException("Type '${javaClass.simpleName}' is illegal. Only classes, parameterized types, wildcard types, or type variables are allowed.")
}
}
| apache-2.0 | 457192b86c756813c8c1ba8212468c9a | 41.213115 | 178 | 0.761942 | 4.681818 | false | false | false | false |
square/duktape-android | zipline-gradle-plugin/src/main/kotlin/app/cash/zipline/gradle/ZiplineGradleDownloader.kt | 1 | 1704 | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.zipline.gradle
import app.cash.zipline.loader.ManifestVerifier.Companion.NO_SIGNATURE_CHECKS
import app.cash.zipline.loader.ZiplineLoader
import java.io.File
import java.util.concurrent.Executors
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.runBlocking
import okhttp3.OkHttpClient
import okio.FileSystem
import okio.Path.Companion.toOkioPath
internal class ZiplineGradleDownloader {
private val executorService = Executors.newSingleThreadExecutor { Thread(it, "Zipline") }
private val dispatcher = executorService.asCoroutineDispatcher()
private val client = OkHttpClient()
fun download(downloadDir: File, applicationName: String, manifestUrl: String) {
val ziplineLoader = ZiplineLoader(
dispatcher = dispatcher,
manifestVerifier = NO_SIGNATURE_CHECKS,
httpClient = client,
)
runBlocking {
ziplineLoader.download(
applicationName = applicationName,
downloadDir = downloadDir.toOkioPath(),
downloadFileSystem = FileSystem.SYSTEM,
manifestUrl = manifestUrl,
)
}
}
}
| apache-2.0 | 39ac53b6d13f49dc978e9b0f28081550 | 33.77551 | 91 | 0.752347 | 4.580645 | false | false | false | false |
Ingwersaft/James | src/main/kotlin/com/mkring/james/James.kt | 1 | 7331 | package com.mkring.james
import com.mkring.james.chatbackend.*
import com.mkring.james.chatbackend.rocketchat.RocketChatBackend
import com.mkring.james.chatbackend.slack.SlackBackend
import com.mkring.james.chatbackend.telegram.TelegramBackend
import com.mkring.james.mapping.Mapping
import com.mkring.james.mapping.MappingPattern
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.slf4j.LoggerFactory
import kotlin.coroutines.CoroutineContext
@DslMarker
annotation class LimitClosureScope
/**
* builds and starts a James instance
*/
fun james(init: James.() -> Unit): James = James().also(init).autoStart()
private val log = LoggerFactory.getLogger(James::class.java)
/**
* use james dsl function
*/
@LimitClosureScope
class James internal constructor(
var name: String? = null,
var autoStart: Boolean = true,
val abortKeywords: MutableList<String> = mutableListOf()
) : CoroutineScope {
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + JamesPool
internal val chatBackends: MutableList<ChatBackend> = mutableListOf()
internal val chatConfigs: MutableList<ChatConfig> = mutableListOf()
internal val mappings: MutableMap<MappingPattern, Mapping.() -> Unit> = mutableMapOf()
internal val actualChats: MutableList<Chat> = mutableListOf()
internal fun autoStart() = if (autoStart) {
start()
} else {
this
}
/**
* if you want to block after calling james{} this is for you
*/
var blockMain: Boolean = false
/**
* check if james started
*/
fun isStarted() = started
private var started: Boolean = false
/**
* start james and wire chatbackends and mappings
*/
fun start(): James {
lg("start()")
if (started) {
lg("already started")
return this
}
createChatBackends()
val mappingprefix = when (name) {
null -> ""
else -> name + " "
}
lg("mapping prefix:$mappingprefix")
val plainHelp = mappings.map { "$mappingprefix${it.key.pattern} - ${it.key.info}" }.joinToString("\n")
val helpMapping = createHelpMapping(plainHelp, "help")
val helpMappingSlash = createHelpMapping(plainHelp, "/help")
mappings[MappingPattern(helpMapping.first, "nvmd")] = helpMapping.second
mappings[MappingPattern(helpMappingSlash.first, "nvmd")] = helpMappingSlash.second
log.info("going to startup ${chatBackends.size} chatBackends")
chatBackends.forEach {
actualChats += Chat(
mappingprefix = mappingprefix,
type = it::class.java.simpleName,
mappings = mappings.map { "$mappingprefix${it.key.pattern}" to it.value }.toMap(),
abortKeywords = abortKeywords, chatBackend = it
).also {
launch {
log.info("starting ${it.type}")
it.start()
}
}
}
started = true
if (blockMain) {
runBlocking {
job.join()
}
}
return this
}
private fun createChatBackends() {
chatConfigs.map {
chatBackends += when (it) {
is RocketChat -> RocketChatBackend(
webSocketTargetUrl = it.websocketTarget,
sslVerifyHostname = it.sslVerifyHostname,
ignoreInvalidCa = it.ignoreInvalidCa,
defaultAvatar = it.defaultAvatar,
username = it.username,
password = it.password
)
is Telegram -> TelegramBackend(it.token, it.username)
is Slack -> SlackBackend(it.botOauthToken)
}
}
}
private fun createHelpMapping(
plainHelp: String,
helpCommand: String
): Pair<String, Mapping.() -> Unit> {
val lines = mutableListOf<String>()
lines += "${name ?: "James"} at yor service:"
lines += ""
if (abortKeywords.isNotEmpty()) {
lines += "abort interactions with: ${abortKeywords.joinToString(", ")}"
}
lines += "---"
lines += plainHelp
val mappingBlock: Mapping.() -> Unit = {
send(lines.joinToString("\n"))
}
return Pair(helpCommand, mappingBlock)
}
/**
* stop james and all children
*/
fun stop() {
lg("stop()")
this.actualChats.forEach { it.stop() }
this.chatBackends.forEach { it.stop() }
this.job.cancel()
}
/**
* @param block
* @param pattern The pattern to match this mapping to.
* Will be used like `text.matches(Regex("^" + pattern + ".*", RegexOption.IGNORE_CASE))`
* @param helptext Text used when help gets build and sent
*/
fun map(pattern: String, helptext: String, block: Mapping.() -> Unit) {
lg("map() for pattern=$pattern helptext=$helptext")
mappings[MappingPattern(pattern, helptext)] = block
}
/**
* create RochetChat config/chat
*/
fun rocketchat(init: RocketChat.() -> Unit) {
chatConfigs += RocketChat().also(init)
}
/**
* create Telegram config/chat
*/
fun telegram(init: Telegram.() -> Unit) {
chatConfigs += Telegram().also(init)
}
/**
* create Slack config/chat
*/
fun slack(init: Slack.() -> Unit) {
chatConfigs += Slack().also(init)
}
/**
* Use mappings of other James instance (uses only mappings, no other config )
* Hint: Create other James instances with autoStart disabled
*/
fun use(other: James) {
other.mappings.forEach { p, block ->
map(p.pattern, p.info, block)
}
}
/**
* If you need something other than the default backends, provide your own one
* !Important! You have to interact with both io-channels:
*
* [ChatBackend.backendToJamesChannel]: When your backend receives messages, you have to forward it
* to this channel. James will process them.
*
* [ChatBackend.fromJamesToBackendChannel]: You must! receive messaged on this channel. This is the channel
* for James to send something back to the backend caller. This is best handled in a backend thread or coroutine
*/
fun addCustomChatBackend(custom: ChatBackend) {
chatBackends += custom
}
/**
* If you need to initiate a conversation you can use this method (if james started already)
*
* @param uniqueChatTarget target chat for which conversation shall be started
* @param mappingLogic your logic for this conversation
*/
fun initiateConversation(uniqueChatTarget: UniqueChatTarget, mappingLogic: Mapping.() -> Unit) {
log.info("initiateConversation to $uniqueChatTarget")
if (started.not()) {
throw IllegalAccessError("james isn't started yet!")
}
actualChats.forEach {
Mapping("<initiateConversation>", uniqueChatTarget, null, "<initiateConversation>", it).apply {
mappingLogic()
}
}
}
}
| gpl-3.0 | 62acf6f4ed09cfcfe979c8f29be39195 | 31.438053 | 116 | 0.605238 | 4.459246 | false | false | false | false |
Tenkiv/Tekdaqc-Java-Library | src/main/java/com/tenkiv/tekdaqc/locator/Locator.kt | 2 | 23189 | //Need to suppress these warnings because Kotlin hasn't implemented Map.computeIfAbsent() or Map.putIfAbsent().
package com.tenkiv.tekdaqc.locator
import com.tenkiv.tekdaqc.hardware.ATekdaqc
import com.tenkiv.tekdaqc.hardware.Tekdaqc_RevD
import com.tenkiv.tekdaqc.utility.reprepare
import java.io.IOException
import java.net.*
import java.util.*
import java.util.concurrent.locks.Condition
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.collections.LinkedHashSet
import kotlin.concurrent.read
import kotlin.concurrent.withLock
import kotlin.concurrent.write
/**
* Class to locate Tekdaqcs on the Network or to connect to unknown Tekdaqcs based on IP address .
*/
class Locator private constructor(params: LocatorParams) {
private object SINGLETON_INSTANCE {
val INSTANCE = Locator(LocatorParams())
}
companion object {
val instance: Locator by lazy { SINGLETON_INSTANCE.INSTANCE }
/**
* The default delay on the [Locator] running.
*/
private const val DEFAULT_LOCATOR_DELAY: Long = 0
/**
* The default period of running the [Locator].
*/
private const val DEFAULT_LOCATOR_PERIOD: Long = 500
}
/**
* Lock ensuring thread safety of [Locator.activeTekdaqcMap]
*/
private val tekdaqcMapLock = ReentrantReadWriteLock()
/**
* Lock ensuring thread safety of binding to the locator's socket
*/
private val socketLock = ReentrantLock()
/**
* List of all active tekdaqcs
*/
private val activeTekdaqcMap = HashMap<String, ATekdaqc>()
/**
* The parameter set to use for the locator request
*/
private var params: LocatorParams = LocatorParams.Builder().build()
/**
* Lock ensuring thread safety of [Locator.tempMapLock]
*/
private val tempMapLock = ReentrantReadWriteLock()
/**
* The list of tekdaqcs currently discovered.
*/
private val tempTekdaqcMap = HashMap<String, ATekdaqc>()
/**
* The listeners associated with the locator.
*/
private val listeners = Collections.synchronizedList(ArrayList<OnTekdaqcDiscovered>())
/**
* Boolean determining if the [Locator] is running.
*/
private var isActive = false
/**
* Time remaining on the locator timer, if it is running.
*/
private var timeRemaining: Long = -1
/**
* Boolean for if the locator is on a timer.
*/
private var isTimed = false
/**
* The timer run periodically to search for tekdaqcs on the local area network.
*/
private var updateTimer = Timer("Update Timer", false)
/**
* Flag setting if Locator broadcasts will send to loopback address. Used internally for automated testing.
*/
@Volatile
var enableLoopbackBroadcast = false
/**
* The timer task run at interval, which updates the [List] of known [ATekdaqc]
*/
private val updateTask: TimerTask
get() = object : TimerTask() {
override fun run() {
updateKnownTekdaqcs()
socketLock.withLock {
val interfaces = NetworkInterface.getNetworkInterfaces()
while (interfaces.hasMoreElements()) {
val iAddrs = interfaces.nextElement().interfaceAddresses
iAddrs.forEach { addr ->
if (addr.broadcast != null) {
locate(addr.broadcast)
}
if (enableLoopbackBroadcast && addr.address.isLoopbackAddress){
locate(addr.address)
}
}
}
}
if (isTimed) {
timeRemaining -= DEFAULT_LOCATOR_PERIOD
if (timeRemaining < 1) {
isTimed = false
cancelLocator()
}
}
}
}
/**
* Sets new params for the [Locator].
* Setting new params cancels execution of the current Locator if it is running, requiring it to be restarted.
* @param params The [LocatorParams] to be set for the [Locator].
*/
fun setLocatorParams(params: LocatorParams) {
updateTimer = updateTimer.reprepare()
this.params = params
}
/**
* Creates an unsafe instance of the [Locator] class. If not properly configured, this locator will not
* function while another is active. Use [LocatorParams] to set a different port to search on, however this
* will only work if the Tekdaqc is programmed to respond to the new port.
* @param params The [LocatorParams] to be set for the [Locator].
* *
* @return An unsafe [Locator] instance.
*/
fun createUnsafeLocator(params: LocatorParams): Locator {
return Locator(params)
}
/**
* Method to add a [OnTekdaqcDiscovered] listener to be notified about [Locator] discoveries.
* @param listener The [OnTekdaqcDiscovered] locator to be added.
*/
fun addLocatorListener(listener: OnTekdaqcDiscovered) {
listeners.add(listener)
}
/**
* Method to remove a [OnTekdaqcDiscovered] listener from the [Locator] callbacks.
* @param listener The [OnTekdaqcDiscovered] listener to be removed.
*/
fun removeLocatorListener(listener: OnTekdaqcDiscovered) {
listeners.remove(listener)
}
/**
* Factory method for producing a [ATekdaqc] of the correct subclass
* based on the response from the locator service.
* @param response [LocatorResponse] The response sent by the Tekdaqc.
* *
* @param isSafeCreation If the [ATekdaqc] was found through reliable location instead of an automatically
* * assumed preexisting IP address and MAC values.
* *
* *
* @return [ATekdaqc] The constructed Tekdaqc.
*/
private fun createTekdaqc(response: LocatorResponse, isSafeCreation: Boolean): ATekdaqc {
// This is here to allow for future backwards compatibility with
// different board versions
val tekdaqc: ATekdaqc
when (response.type) {
'D', 'E' -> {
tekdaqc = Tekdaqc_RevD(response)
if (isSafeCreation) {
addTekdaqcToMap(tekdaqc)
}
}
else -> throw IllegalArgumentException("Unknown Tekdaqc Revision: " + response.type)
}
return tekdaqc
}
/**
* Method to connect to a discovered Tekdaqc of target serial number. Returns a CONNECTED [ATekdaqc].
* @param serialNumber A [String] of the target [ATekdaqc]'s serial number.
* *
* @param defaultScale The current [ATekdaqc.AnalogScale] the board is set to.
* * This should match the physical jumpers on the board.
* *
* @throws IOException
* *
* @return A [ATekdaqc] with an open connection.
*/
fun connectToTargetTekdaqc(serialNumber: String, defaultScale: ATekdaqc.AnalogScale): ATekdaqc? {
val map = getActiveTekdaqcMap()
if (map.containsKey(serialNumber)) {
val tekdaqc = map[serialNumber]
tekdaqc?.connect(defaultScale, ATekdaqc.CONNECTION_METHOD.ETHERNET)
return tekdaqc
} else {
throw IOException("No Tekdaqc Found with serial number " + serialNumber)
}
}
/**
* Method to create a [ATekdaqc] from an assumed pre-known serial number, IP address, and board revision.
* Because this does not guarantee that the [ATekdaqc] actually exists, the [ATekdaqc] created in this
* manner will not be added to the global [Locator.getActiveTekdaqcMap].
* @param serialNumber The assumed serial number of the hypothetical [ATekdaqc].
* *
* @param hostIPAdress The assumed IP address of the hypothetical [ATekdaqc].
* *
* @param tekdaqcRevision The assumed revision of the hypothetical [ATekdaqc].
* *
* @param defaultScale The current [ATekdaqc.AnalogScale] the board is set to.
* * This should match the physical jumpers on the board.
* *
* *
* @throws IOException On failed connection attempt.
* @return A [ATekdaqc] object that represents an un-located, hypothetical Tekdaqc on the network.
*/
fun connectToUnsafeTarget(serialNumber: String,
hostIPAdress: String,
tekdaqcRevision: Char,
defaultScale: ATekdaqc.AnalogScale): ATekdaqc {
val pseudoResponse = LocatorResponse()
pseudoResponse.mHostIPAddress = hostIPAdress
pseudoResponse.mType = tekdaqcRevision
pseudoResponse.mSerial = serialNumber
val tekdaqc = createTekdaqc(pseudoResponse, false)
tekdaqc.connect(defaultScale, ATekdaqc.CONNECTION_METHOD.ETHERNET)
return tekdaqc
}
/**
* Retrieves a [ATekdaqc] for the specified serial [String].
* @param serial [String] The serial number to search for.
* *
* @return [ATekdaqc] The known [ATekdaqc] for
* * `serial` or `null` if no match was found.
*/
fun getTekdaqcForSerial(serial: String): ATekdaqc? {
tekdaqcMapLock.read {
return activeTekdaqcMap[serial]
}
}
/**
* Removes a [ATekdaqc] for the specified serial [String].
* @param serial [String] The serial number to of the [ATekdaqc] to
* * remove.
*/
protected fun removeTekdaqcForSerial(serial: String) {
tekdaqcMapLock.write { activeTekdaqcMap.remove(serial) }
}
/**
* Adds a [ATekdaqc] to the global map of [Locator.getActiveTekdaqcMap], This should only be done if
* you are certain the [ATekdaqc] exists. Adding unsafe [ATekdaqc]s may cause crashes or spooky behavior.
* @param tekdaqc The [ATekdaqc] to be added.
*/
protected fun addTekdaqcToMap(tekdaqc: ATekdaqc) {
tekdaqcMapLock.write {
activeTekdaqcMap.putIfAbsent(tekdaqc.serialNumber, tekdaqc)
}
}
/**
* Gets a copy of a [Map] representing all currently located [ATekdaqc].
* @return A new [HashMap] which contains all currently located [ATekdaqc].
*/
fun getActiveTekdaqcMap(): Map<String, ATekdaqc> {
tekdaqcMapLock.read {
return HashMap(activeTekdaqcMap)
}
}
/**
* Activates the search for Tekdaqcs.
* @return True if discovery is started successfully.
* *
* @throws SocketException Thrown if there is a problem with the underlying socket.
* *
* @throws UnknownHostException Thrown if the IP address this [Locator] is pinging is
* * invalid.
*/
@Throws(SocketException::class, UnknownHostException::class)
private fun locate(address: InetAddress): Boolean {
val mSocket = DatagramSocket(params.port)
mSocket.broadcast = true
mSocket.soTimeout = params.timeout
return try {
sendDiscoveryRequest(mSocket, address)
true
} catch (e: IOException) {
false
} finally {
mSocket.close()
}
}
/**
* Sends out the discovery packet on the network.
* @param socket [DatagramSocket] to send on.
* *
* @param addr [InetAddress] to send the discovery packet to.
* *
* @throws [IOException] Thrown if there is a problem with the
* * underlying interface.
*/
@Throws(IOException::class)
private fun sendDiscoveryRequest(socket: DatagramSocket, addr: InetAddress) {
val message = params.getMessage()
val data = message.toByteArray()
var buf = ByteArray(1024)
socket.send(DatagramPacket(data, data.size, addr, params.getPort()))
while (true) {
try {
val packet = DatagramPacket(buf, buf.size)
socket.receive(packet)
val response = LocatorResponse(packet.address.hostAddress, packet.data)
if (response.isValid(params)) {
handleResponse(response)
}
} catch (e: SocketTimeoutException) {
return
}
buf = ByteArray(1024)
}
}
private fun handleResponse(response: LocatorResponse){
tempMapLock.write {
if (isKnownTekdaqc(response.serial)) {
tempTekdaqcMap.put(response.serial,
getTekdaqcForSerial(response.serial) ?:
createTekdaqc(response, true))
} else {
val tekdaqc = createTekdaqc(response, true)
tempTekdaqcMap.put(tekdaqc.serialNumber, tekdaqc)
for (listener in listeners) {
listener.onTekdaqcFirstLocated(tekdaqc)
}
}
for (listener in listeners) {
listener.onTekdaqcResponse(getTekdaqcForSerial(response.serial))
}
}
}
/**
* Method to update the current list of discovered [ATekdaqc].
*/
private fun updateKnownTekdaqcs() {
tekdaqcMapLock.read {
getActiveTekdaqcMap().entries.forEach { questionableBoard ->
tempMapLock.readLock().lock()
if (!tempTekdaqcMap.containsKey(questionableBoard.key) && !questionableBoard.value.isConnected) {
removeTekdaqcForSerial(questionableBoard.key)
listeners.forEach { listener -> listener.onTekdaqcNoLongerLocated(questionableBoard.value) }
}
tempMapLock.readLock().unlock()
}
}
tempTekdaqcMap.clear()
}
/**
* Internal method to determine if a [ATekdaqc] has been located.
* @param serialNumber The [String] of the [ATekdaqc] serial number.
* *
* @return [Boolean] of if the [ATekdaqc] has been located.
*/
private fun isKnownTekdaqc(serialNumber: String): Boolean {
tekdaqcMapLock.read {
return getActiveTekdaqcMap().containsKey(serialNumber)
}
}
/**
* Method which halts the locator.
*/
fun cancelLocator() {
isActive = false
isTimed = false
timeRemaining = -1
updateTimer = updateTimer.reprepare()
}
/**
* Method that returns if the [Locator] is active.
* @return Boolean if the [Locator] is active.
*/
fun isActive(): Boolean {
return isActive
}
/**
* Method which starts the locator at a given delay and period.
* @param delay The delay at which to start the locator in milliseconds as a [Long].
* *
* @param period The period at which to run the locator in milliseconds as a [Long].
*/
fun searchForTekdaqcs(delay: Long, period: Long) {
isActive = true
updateTimer = updateTimer.reprepare()
updateTimer.scheduleAtFixedRate(updateTask, delay, period)
}
/**
* Method that activates the locator for a given duration
* @param totalTimeMillis Total time in milliseconds.
*/
fun searchForTekdaqcsForDuration(totalTimeMillis: Long) {
timeRemaining = totalTimeMillis
isTimed = true
if (isActive()) {
cancelLocator()
isActive = true
}
searchForTekdaqcs()
}
/**
* Method which starts the locator at the default delay and period.
*/
fun searchForTekdaqcs() {
isActive = true
updateTimer.scheduleAtFixedRate(updateTask, DEFAULT_LOCATOR_DELAY, DEFAULT_LOCATOR_PERIOD)
}
/**
* Convenience method to search for specific [ATekdaqc]s on the network.
* Note: this method will start the [Locator]'s default method ([Locator.searchForTekdaqcs]), so other classes
* may also be notified of discovered [ATekdaqc]s. Contains the option to automatically connect to the [ATekdaqc]
* so that the boards returned will not be taken by other listeners and will not need the [ATekdaqc.connect]
* method called on them.
* @param listener The [OnTargetTekdaqcFound] listener to be notified.
* *
* @param timeoutMillis The maximum time to run before returning [OnTargetTekdaqcFound.onTargetFailure]
* *
* @param autoConnect If the [Locator] should automatically connect to the [ATekdaqc] for you.
* *
* @param autoConnectDefaultScale The current [ATekdaqc.AnalogScale] the board is set to.
* * This should match the physical jumpers on the board.
* *
* @param serials Variable arguments of the serial numbers of the [ATekdaqc] to find.
*/
fun searchForSpecificTekdaqcs(listener: OnTargetTekdaqcFound, timeoutMillis: Long,
autoConnect: Boolean = false,
autoConnectDefaultScale: ATekdaqc.AnalogScale
= ATekdaqc.AnalogScale.ANALOG_SCALE_5V,
vararg serials: String) {
val previouslyLocated = getActiveTekdaqcMap()
val serialList = ArrayList(Arrays.asList(*serials))
previouslyLocated.forEach { k, v ->
if (serialList.contains(k)) {
listener.onTargetFound(v)
serialList.remove(k)
}
}
val searchTimer = Timer("Specific Tekdaqc Search Timer", false)
searchTimer.schedule(AwaitSpecificTekdaqcTask(
serialList,
listener,
autoConnect,
autoConnectDefaultScale),
timeoutMillis)
}
/**
* Method which runs the locator while blocking the current thread to look for specific Tekdaqcs.
* @param timeoutMillis The maximum time to search for [ATekdaqc]s.
* *
* @param lock Optional lock to be used. This should be implemented where custom threading libraries or
* concurrency is being used.
* *
* @param autoConnect If [ATekdaqc]s should be automatically connected to.
* *
* @param autoConnectDefaultScale The optional scale of the [ATekdaqc]s that are auto-connected to.
* * THIS MUST BE NON-NULL IN ORDER TO AUTOMATICALLY CONNECT.
* *
* @param serials The serial numbers of [ATekdaqc]s to search for.
*
* @throws IOException
* *
* @return A list of [ATekdaqc]s found during the timeout with the listed serial numbers.
*/
fun blockingSearchForSpecificTekdaqcs(timeoutMillis: Long,
lock: Lock = ReentrantLock(),
autoConnect: Boolean = false,
autoConnectDefaultScale: ATekdaqc.AnalogScale? = null,
vararg serials: String): List<ATekdaqc> {
val discoveredTekdaqcs = ArrayList<ATekdaqc>()
val condition = lock.newCondition()
val timer = Timer("Blocking Search for Specific Tekdaqcs", false)
timer.schedule(BlockingWakeTask(lock, condition), timeoutMillis)
addLocatorListener(object : OnTekdaqcDiscovered {
override fun onTekdaqcResponse(board: ATekdaqc) {
for (serial in serials) {
if (serial == board.serialNumber && !discoveredTekdaqcs.contains(board)) {
if (autoConnect && autoConnectDefaultScale != null) {
board.connect(autoConnectDefaultScale, ATekdaqc.CONNECTION_METHOD.ETHERNET)
}
discoveredTekdaqcs.add(board)
if (discoveredTekdaqcs.size == serials.size) {
timer.purge()
timer.cancel()
lock.withLock { condition.signalAll() }
}
}
}
}
override fun onTekdaqcFirstLocated(board: ATekdaqc) {
}
override fun onTekdaqcNoLongerLocated(board: ATekdaqc) {
}
})
searchForTekdaqcs()
lock.withLock {
condition.await()
}
timer.purge()
timer.cancel()
cancelLocator()
return discoveredTekdaqcs
}
/**
* Internal class used for [Locator.blockingSearchForSpecificTekdaqcs]
* and similar methods.
*/
private inner class BlockingWakeTask internal constructor(private val mLock: Lock,
private val mCondition: Condition) : TimerTask() {
override fun run() {
mLock.withLock { mCondition.signalAll() }
}
}
/**
* Internal class to handle waiting for the location of specific [ATekdaqc]s
*/
private inner class AwaitSpecificTekdaqcTask
/**
* Constructor for the [AwaitSpecificTekdaqcTask].
* @param serialList The [List] of serial numbers.
* *
* @param listener The [OnTargetTekdaqcFound] listener to be notified.
* *
* @param autoConnect If the program should automatically connect.
*
* @param defaultScale The default scale to connect at.
*/
internal constructor(
private val serialList: MutableList<String>,
private val listener: OnTargetTekdaqcFound,
private val autoConnect: Boolean,
private val defaultScale: ATekdaqc.AnalogScale) : TimerTask(), OnTekdaqcDiscovered {
/**
* The list of [ATekdaqc]s which have been found.
*/
private val tekdaqcList = ArrayList<ATekdaqc>()
init {
instance.addLocatorListener(this)
if (!instance.isActive) {
instance.searchForTekdaqcs()
}
}
override fun onTekdaqcResponse(board: ATekdaqc) {
}
override fun onTekdaqcFirstLocated(board: ATekdaqc) {
if (serialList.contains(board.serialNumber)) {
if (autoConnect) {
board.connect(defaultScale, ATekdaqc.CONNECTION_METHOD.ETHERNET)
}
listener.onTargetFound(board)
serialList.remove(board.serialNumber)
tekdaqcList.add(board)
if (serialList.size == 0) {
listener.onAllTargetsFound(LinkedHashSet(tekdaqcList))
}
}
}
override fun onTekdaqcNoLongerLocated(board: ATekdaqc) {
}
override fun run() {
instance.removeLocatorListener(this)
serialList.forEach { serial -> listener.onTargetFailure(serial,
OnTargetTekdaqcFound.FailureFlag.TEKDAQC_NOT_LOCATED) }
}
}
} | apache-2.0 | e6bd28e215ee6a68355d5d8c27249326 | 31.661972 | 117 | 0.598862 | 4.93383 | false | false | false | false |
yamamotoj/workshop-jb | src/ii_conventions/MyDate.kt | 1 | 1450 | package ii_conventions
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> {
override fun compareTo(other: MyDate): Int =
if (year != other.year) year - other.year
else if (month != other.month) month - other.month
else if (dayOfMonth != other.dayOfMonth) dayOfMonth - other.dayOfMonth
else 0
fun rangeTo(to:MyDate) : DateRange = DateRange(this, to)
fun plus(interval: RepeatedTimeInterval) :MyDate = addTimeIntervals(interval.ti, interval.n)
fun plus(interval: TimeInterval) :MyDate = addTimeIntervals(interval, 1)
}
class RepeatedTimeInterval(val ti: TimeInterval, val n: Int){}
enum class TimeInterval {
DAY,
WEEK,
YEAR;
fun times(times : Int) :RepeatedTimeInterval = RepeatedTimeInterval(this, times)
}
class DateRange(public override val start: MyDate, public override val end: MyDate) : Iterable<MyDate>, Range<MyDate> {
override fun iterator(): Iterator<MyDate> {
var current: MyDate = start
return object : Iterator<MyDate> {
override fun hasNext(): Boolean = current.compareTo(end) <= 0
override fun next(): MyDate {
val prev = current
current = prev.nextDay()
return prev
}
}
}
override fun contains(item: MyDate) : Boolean =
start.compareTo(item) <= 0 && item.compareTo(end) <= 0
}
| mit | 0f349c5b3016beaed0f82f1e03970f1b | 32.72093 | 119 | 0.635862 | 4.420732 | false | false | false | false |
icanit/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/download/model/DownloadQueue.kt | 1 | 2175 | package eu.kanade.tachiyomi.data.download.model
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.source.model.Page
import rx.Observable
import rx.subjects.PublishSubject
import java.util.*
class DownloadQueue : ArrayList<Download>() {
private val statusSubject = PublishSubject.create<Download>()
override fun add(download: Download): Boolean {
download.setStatusSubject(statusSubject)
download.status = Download.QUEUE
return super.add(download)
}
fun del(download: Download) {
super.remove(download)
download.setStatusSubject(null)
}
fun del(chapter: Chapter) {
for (download in this) {
if (download.chapter.id == chapter.id) {
del(download)
break
}
}
}
fun getActiveDownloads() =
Observable.from(this).filter { download -> download.status == Download.DOWNLOADING }
fun getStatusObservable() = statusSubject.onBackpressureBuffer()
fun getProgressObservable(): Observable<Download> {
return statusSubject.onBackpressureBuffer()
.startWith(getActiveDownloads())
.flatMap { download ->
if (download.status == Download.DOWNLOADING) {
val pageStatusSubject = PublishSubject.create<Int>()
setPagesSubject(download.pages, pageStatusSubject)
return@flatMap pageStatusSubject
.filter { it == Page.READY }
.map { download }
} else if (download.status == Download.DOWNLOADED || download.status == Download.ERROR) {
setPagesSubject(download.pages, null)
}
Observable.just(download)
}
.filter { it.status == Download.DOWNLOADING }
}
private fun setPagesSubject(pages: List<Page>?, subject: PublishSubject<Int>?) {
if (pages != null) {
for (page in pages) {
page.setStatusSubject(subject)
}
}
}
}
| apache-2.0 | 6b01fb145e02840fd667bae875291ac2 | 32.461538 | 109 | 0.58069 | 5.081776 | false | false | false | false |
ShevaBrothers/easylib | src/core/fifo/main/Deque.kt | 1 | 6111 | /**
* Created by akise on 27.05.2017.
* Double-ended queue is an abstract data type that generalizes a queue,
* for which elements can be added to or removed from either
* the front (head) or back (tail).
*
* @author Volodymyr Semenovych (@akisemenovych).
* @since 0.1
* @param E the type of elements which are consists in this data structure.
* @see Node .
*/
class Deque<E> (private var dequeHead : Node<E>? = null, private var dequeTail : Node<E>? = null) : AbstractQueue<E> {
init {
dequeHead?.setNext(dequeTail)
dequeTail?.setPrev(dequeHead)
}
/**
* Inner misc class for representation of container with data and next element reference.
*
* @author Volodymyr Semenovych (@akisemenovych).
* @since 0.1
* @param el valuable data object
* @see Deque .
* @constructor creates object with data and temporary null reference for next block.
*/
class Node<E> (private var el: E) : AbstractQueue.QueueNode<E>(el) {
private var next : Node<E>? = null
private var prev : Node<E>? = null
/**
* Unpack element from object Node
*/
override fun getElement() : E = el
/**
* Pack element to object Node
*/
override fun setElement(el : E) {
this.el = el
}
/**
* Get link on next Node
*/
override fun next() : Node<E>? = next
/**
* Get link on prev Node
*/
fun prev() : Node<E>? = prev
/**
* Set link to next Node
*/
fun setNext(nextEl : Node<E>?) {
this.next = nextEl
}
/**
* Set link to prev Node
*/
fun setPrev(prevEl : Node<E>?) {
this.prev = prevEl
}
/**
* Remove current Node
*/
override fun remove() {
if (el != null) {
this.el = next!!.getElement()
if (next!!.next()?.equals(null) as Boolean)
this.next = next!!.next
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as Node<*>
if (el != other.el) return false
return true
}
override fun hashCode(): Int {
var result = el?.hashCode() ?: 0
result = 31 * result + (next!!.hashCode() ?: 0)
return result
}
}
/**
* Retrieves, but does not remove, the head of this queue.
*/
override fun head(): Node<E>? = this.dequeHead
/**
* Retrieves, but does not remove, the tail of this queue.
*/
override fun tail(): Node<E>? = this.dequeTail
/**
* Retrieves, but does not remove, the next node of this queue.
*/
fun next(selectedNode : Node<E>) : Node<E>? = selectedNode?.next()
/**
* Retrieves, but does not remove, the prev node of this queue.
*/
fun prev(selectedNode : Node<E>) : Node<E>? = selectedNode?.prev()
private var queueSize = 0
/**
* @author Volodymyr Semenovych (@akisemenovych).
* @since 0.1
* @return Queue size
*/
override val size: Int
get() = this.queueSize
/**
* Inserts the specified element into this queue (to Tail).
*
* @author Volodymyr Semenovych (@akisemenovych).
* @since 0.1
* @param element
* @return flag of action status
*/
override fun add(element : E): Boolean {
var current = Node(element)
if (dequeHead == null) {
dequeHead = current
queueSize += 1
return true
} else if (dequeTail == null) {
dequeTail = current
dequeHead?.setNext(dequeTail)
queueSize += 1
return true
} else {
dequeTail?.setNext(current)
dequeTail = current
queueSize += 1
return true
}
return false
}
/**
* Inserts the specified element into this queue to Head.
*
* @author Volodymyr Semenovych (@akisemenovych).
* @since 0.1
* @param element
* @return flag of action status
*/
fun addToHead(element : E): Boolean {
var current : Node<E>? = null
current?.setElement(element)
if (dequeHead == null) {
dequeHead = current
queueSize += 1
return true
} else {
dequeHead?.setPrev(current)
current?.setNext(dequeHead)
dequeHead = current
queueSize += 1
return true
}
return false
}
/**
* Retrieves, but does not remove, the head element of this queue.
*
* @author Volodymyr Semenovych (@akisemenovych).
* @since 0.1
* @return head element from Queue
*/
override fun element() : E? {
return dequeHead?.getElement()
}
/**
* Retrieves, but does not remove, the tail element of this queue.
*
* @author Volodymyr Semenovych (@akisemenovych).
* @since 0.1
* @return tail element from Queue
*/
fun elementFromTail() : E? {
return dequeTail?.getElement()
}
/**
* Retrieves and removes, the head element of this queue,
* or returns null if this queue is empty.
*
* @author Volodymyr Semenovych (@akisemenovych).
* @since 0.1
* @return head element from Queue
*/
override fun poll() : E? {
var element : E? = dequeHead?.getElement()
dequeHead = dequeHead?.next()
return element
}
/**
* Retrieves and removes, the tail element of this queue,
* or returns null if this queue is empty.
*
* @author Volodymyr Semenovych (@akisemenovych).
* @since 0.1
* @return tail element from Queue
*/
fun pollFromTail() : E? {
var element : E? = dequeTail?.getElement()
dequeTail = dequeTail?.prev()
return element
}
} | mit | a692c2445813cdac260b584dfb786730 | 26.408072 | 118 | 0.535428 | 4.060465 | false | false | false | false |
magnusja/libaums | libaums/src/main/java/me/jahnen/libaums/core/driver/scsi/commands/ScsiWrite10.kt | 2 | 3238 | /*
* (C) Copyright 2014 mjahnen <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package me.jahnen.libaums.core.driver.scsi.commands
import java.nio.ByteBuffer
import java.nio.ByteOrder
/**
* SCSI command to write to the mass storage device. The 10 means that the
* transfer length is two byte and the logical block address field is four byte.
* Thus the hole command takes 10 byte when serialized.
*
*
* The actual data is transferred in the data phase.
*
* @author mjahnen
*/
class ScsiWrite10 : CommandBlockWrapper {
private var blockAddress: Int = 0
private var transferBytes: Int = 0
private var blockSize: Int = 0
private var transferBlocks: Short = 0
/**
* Constructs a new write command without any information.
* Be sure to call [.init] before transfering command to device.
*/
constructor(lun: Byte) : super(0, Direction.OUT, lun, LENGTH)
/**
* Constructs a new write command with the given information.
*
* @param blockAddress
* The logical block address the write should start.
* @param transferBytes
* The bytes which should be transferred.
* @param blockSize
* The block size of the mass storage device.
*/
constructor(blockAddress: Int, transferBytes: Int, blockSize: Int) : super(transferBytes, Direction.OUT, 0.toByte(), LENGTH) {
init(blockAddress, transferBytes, blockSize)
}
fun init(blockAddress: Int, transferBytes: Int, blockSize: Int) {
super.dCbwDataTransferLength = transferBytes
this.blockAddress = blockAddress
this.transferBytes = transferBytes
this.blockSize = blockSize
val transferBlocks = (transferBytes / blockSize).toShort()
require(transferBytes % blockSize == 0) { "transfer bytes is not a multiple of block size" }
this.transferBlocks = transferBlocks
}
override fun serialize(buffer: ByteBuffer) {
super.serialize(buffer)
buffer.apply {
order(ByteOrder.BIG_ENDIAN)
put(OPCODE)
put(0.toByte())
putInt(blockAddress)
put(0.toByte())
putShort(transferBlocks)
}
}
override fun toString(): String {
return ("ScsiWrite10 [blockAddress=" + blockAddress + ", transferBytes=" + transferBytes
+ ", blockSize=" + blockSize + ", transferBlocks=" + transferBlocks
+ ", getdCbwDataTransferLength()=" + dCbwDataTransferLength + "]")
}
companion object {
// private static final String TAG = ScsiWrite10.class.getSimpleName();
private const val LENGTH: Byte = 10
private const val OPCODE: Byte = 0x2a
}
}
| apache-2.0 | 6ade4bf699396baa97d0b5e58c287f53 | 32.729167 | 130 | 0.668314 | 4.334672 | false | false | false | false |
pdvrieze/ProcessManager | ProcessEngine/core/src/jvmTest/kotlin/nl/adaptivity/process/engine/test/loanOrigination/LoanActivityContext.kt | 1 | 4930 | /*
* Copyright (c) 2019.
*
* 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.test.loanOrigination
import nl.adaptivity.process.engine.ActivityInstanceContext
import nl.adaptivity.process.engine.test.loanOrigination.auth.*
import nl.adaptivity.process.engine.test.loanOrigination.systems.Browser
import nl.adaptivity.process.engine.test.loanOrigination.systems.TaskList
import java.security.Principal
import java.util.*
class LoanActivityContext(override val processContext:LoanProcessContext, private val baseContext: ActivityInstanceContext): ActivityInstanceContext by baseContext {
override var owner: Principal = baseContext.owner
private set
private val pendingPermissions = ArrayDeque<PendingPermission>()
inline fun <R> acceptBrowserActivity(browser: Browser, action: TaskList.Context.() -> R): R {
acceptActivityImpl(browser) // This will initialise the task list and then delegate to it
return taskList.contextImpl(browser).action()
}
@PublishedApi
internal fun acceptActivityImpl(browser: Browser) {
ensureTaskList(browser)
processContext.engineService.registerActivityToTaskList(taskList, handle)
val authorizationCode= taskList.acceptActivity(browser.loginToService(taskList), browser.user, pendingPermissions, handle)
browser.addToken(processContext.authService, authorizationCode)
/*
val hNodeInstance = handle
while (pendingPermissions.isNotEmpty()) {
val pendingPermission = pendingPermissions.removeFirst()
processContext.authService.grantPermission(
engineServiceAuth,
taskIdentityToken,
processContext.authService,
LoanPermissions.GRANT_PERMISSION.invoke(pendingPermission.service, pendingPermission.scope))
}
browser.addToken(taskIdentityToken)
*/
}
private fun ensureTaskList(browser: Browser) {
val taskUser = browser.user
if (::taskList.isInitialized) {
if (taskList.principal != taskUser) {
throw UnsupportedOperationException("Attempting to change the user for an activity after it has already been set")
}
} else {
taskList = processContext.taskList(taskUser)
owner = taskUser
}
}
fun serviceTask(): AuthorizationCode {
if (::taskList.isInitialized) {
throw UnsupportedOperationException("Attempting to mark as service task an activity that has already been marked for users")
}
val clientServiceId = processContext.generalClientService.serviceId
val serviceAuthorization = with(processContext) {
authService.createAuthorizationCode(engineServiceAuth,
clientServiceId, [email protected], authService, LoanPermissions.IDENTIFY)
}
while(pendingPermissions.isNotEmpty()) {
val pendingPermission = pendingPermissions.removeFirst()
processContext.authService.grantPermission(engineServiceAuth, serviceAuthorization, processContext.authService, LoanPermissions.GRANT_ACTIVITY_PERMISSION.restrictTo(
handle, pendingPermission.clientId ?: clientServiceId, pendingPermission.service, pendingPermission.scope))
}
return serviceAuthorization
}
/**
* TODO Function that registers permissions for the task. This should be done based upon task definition
* and in acceptActivity.
*/
fun registerTaskPermission(service: Service, scope: PermissionScope) {
pendingPermissions.add(PendingPermission(null, service, scope))
}
/**
* TODO Function that registers permissions for the task. This should be done based upon task definition
* and in acceptActivity.
*/
fun registerTaskPermission(clientId: String, service: Service, scope: PermissionScope) {
pendingPermissions.add(PendingPermission(clientId, service, scope))
}
lateinit var taskList: TaskList
private val engineServiceAuth: IdSecretAuthInfo get() = processContext.loanContextFactory.engineClientAuth
class PendingPermission(val clientId: String? = null, val service: Service, val scope: PermissionScope)
}
| lgpl-3.0 | 78ef71c06ac3370152e5f846bec3cee8 | 42.628319 | 177 | 0.72069 | 5.178571 | false | false | false | false |
asamm/locus-api | locus-api-android-sample/src/main/java/com/asamm/locus/api/sample/utils/SampleCalls.kt | 1 | 25817 | /*
* Copyright 2011, Asamm soft, s.r.o.
*
* This file is part of LocusAddonPublicLibSample.
*
* LocusAddonPublicLibSample 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.
*
* LocusAddonPublicLibSample 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 LocusAddonPublicLibSample. If not, see <http://www.gnu.org/licenses/>.
*/
package com.asamm.locus.api.sample.utils
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Color
import android.widget.EditText
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.fragment.app.FragmentActivity
import com.asamm.locus.api.sample.R
import locus.api.android.ActionBasics
import locus.api.android.ActionDisplayPoints
import locus.api.android.ActionDisplayVarious
import locus.api.android.ActionFiles
import locus.api.android.features.sendToApp.SendMode
import locus.api.android.features.sendToApp.SendToAppHelper
import locus.api.android.features.sendToApp.tracks.SendTrack
import locus.api.android.features.sendToApp.tracks.SendTracks
import locus.api.android.objects.LocusVersion
import locus.api.android.objects.PackPoints
import locus.api.android.objects.VersionCode
import locus.api.android.utils.LocusUtils
import locus.api.android.utils.exceptions.RequiredVersionMissingException
import locus.api.objects.extra.GeoDataExtra
import locus.api.objects.extra.Location
import locus.api.objects.geoData.Circle
import locus.api.objects.geoData.Point
import locus.api.objects.geoData.Track
import locus.api.objects.geocaching.GeocachingData
import locus.api.objects.geocaching.GeocachingWaypoint
import locus.api.objects.styles.GeoDataStyle
import locus.api.utils.Logger
import java.io.File
import java.util.*
object SampleCalls {
// tag for logger
private const val TAG = "SampleCalls"
// ID for "onDisplay" event
const val EXTRA_ON_DISPLAY_ACTION_ID = "myOnDisplayExtraActionId"
const val EXTRA_CALLBACK_ID = "extraCallbackId"
/**
* Temporary file used for testing of import feature.
*/
private fun getTempGpxFile(ctx: Context, content: String): File {
return File(ctx.externalCacheDir, "temporary_path.gpx").apply {
writeText(content)
}
}
//*************************************************
// BASIC CHECKS
//*************************************************
/**
* Write stats about app into log.
*
* @param ctx current context
*/
fun callDisplayLocusMapInfo(ctx: Context) {
// iterate over versions
Logger.logI(TAG, "Locus versions:")
for (version in LocusUtils.getAvailableVersions(ctx)) {
Logger.logI(TAG, " version: $version")
}
// active version
Logger.logI(TAG, "Active version:")
Logger.logI(TAG, " version: " + LocusUtils.getActiveVersion(ctx))
// notify
Toast.makeText(ctx, "Check log for result", Toast.LENGTH_SHORT).show()
}
fun getRootDirectory(ctx: Context, lv: LocusVersion): String? {
return try {
ActionBasics.getLocusInfo(ctx, lv)!!.rootDir
} catch (e: RequiredVersionMissingException) {
e.printStackTrace()
null
}
}
/**
* Check if found version is running.
*
* @param ctx current context
* @param lv received Locus version
* @return `true` if app is running
*/
fun isRunning(ctx: Context, lv: LocusVersion): Boolean {
return try {
ActionBasics.getLocusInfo(ctx, lv)!!.isRunning
} catch (e: RequiredVersionMissingException) {
e.printStackTrace()
false
}
}
/**
* Check if periodic updates are enabled.
*
* @param ctx current context
* @param lv received Locus version
* @return `true` if updates are enabled
*/
fun isPeriodicUpdateEnabled(ctx: Context, lv: LocusVersion): Boolean {
return try {
ActionBasics.getLocusInfo(ctx, lv)!!.isPeriodicUpdatesEnabled
} catch (e: RequiredVersionMissingException) {
e.printStackTrace()
false
}
}
//*************************************************
// DISPLAY POINTS
//*************************************************
/**
* Send single point into Locus application.
*
* @param ctx current context
* @throws RequiredVersionMissingException exception in case of missing required app version
*/
@Throws(RequiredVersionMissingException::class)
fun callSendOnePoint(ctx: Context) {
// generate pack
val pw = PackPoints("callSendOnePoint")
pw.addPoint(generateWaypoint(0))
// send data
val send = ActionDisplayPoints.sendPack(ctx, pw, ActionDisplayVarious.ExtraAction.IMPORT)
Logger.logD(TAG, "callSendOnePoint(), " +
"send:" + send)
}
/**
* Send more points - LIMIT DATA TO MAX 1000 (really max 1500), more cause troubles. It easy and fast method,
* but depend on data size, so intent with lot of geocaches will be really limited.
*
* @param ctx current context
* @throws RequiredVersionMissingException exception in case of missing required app version
*/
@Throws(RequiredVersionMissingException::class)
fun callSendMorePoints(ctx: Context) {
// generate pack with points
val pw = PackPoints("callSendMorePoints")
for (i in 0..999) {
pw.addPoint(generateWaypoint(i))
}
// send data
val send = ActionDisplayPoints.sendPack(ctx, pw, ActionDisplayVarious.ExtraAction.IMPORT)
Logger.logD(TAG, "callSendMorePoints(), " +
"send:" + send)
}
/**
* Send single point that will be immediately visible on a map. Point will also contains an icon.
*
* @param ctx current context
* @throws RequiredVersionMissingException exception in case of missing required app version
*/
@Throws(RequiredVersionMissingException::class)
fun callSendOnePointWithIcon(ctx: Context) {
// prepare pack with point (with icon)
val pw = PackPoints("callSendOnePointWithIcon")
pw.bitmap = BitmapFactory.decodeResource(
ctx.resources, R.drawable.ic_launcher)
pw.addPoint(generateWaypoint(0))
// send data
val send = ActionDisplayPoints.sendPack(ctx, pw, ActionDisplayVarious.ExtraAction.CENTER)
Logger.logD(TAG, "callSendOnePointWithIcon(), " +
"send:" + send)
}
/**
* Similar to previous method. Every PackPoints object have defined icon that is applied on
* every points. So if you want to send more points with various icons, you have to define for
* every pack specific PackPoints object
*
* @param ctx current context
*/
@Throws(RequiredVersionMissingException::class)
fun callSendMorePointsWithIcons(ctx: Context) {
// container for pack of points
val data = ArrayList<PackPoints>()
// prepare first pack
val pd1 = PackPoints("test01")
val es1 = GeoDataStyle()
es1.setIconStyle("http://www.googlemapsmarkers.com/v1/009900/", 1.0f)
pd1.extraStyle = es1
for (i in 0..99) {
pd1.addPoint(generateWaypoint(i))
}
data.add(pd1)
// prepare second pack with different icon
val pd2 = PackPoints("test02")
val es2 = GeoDataStyle()
es2.setIconStyle("http://www.googlemapsmarkers.com/v1/990000/", 1.0f)
pd2.extraStyle = es2
for (i in 0..99) {
pd2.addPoint(generateWaypoint(i))
}
data.add(pd2)
// send data
val send = ActionDisplayPoints.sendPacks(ctx, data, ActionDisplayVarious.ExtraAction.CENTER)
Logger.logD(TAG, "callSendMorePointsWithIcons(), " +
"send:" + send)
}
/**
* Display single geocache point on the map.
*
* @param ctx current context
* @throws RequiredVersionMissingException exception in case of missing required app version
*/
@Throws(RequiredVersionMissingException::class)
fun callSendOnePointGeocache(ctx: Context) {
// prepare geocache
val pd = PackPoints("callSendOnePointGeocache")
pd.addPoint(generateGeocache(0))
// send data
val send = ActionDisplayPoints.sendPack(ctx, pd, ActionDisplayVarious.ExtraAction.CENTER)
Logger.logD(TAG, "callSendOnePointGeocache(), " +
"send:" + send)
}
/**
* Send and display more geocaches on the screen at once. Limit here is much more tight! Intent have limit on
* data size (around 2MB, so if you want to send more geocaches, don't rather use this method.
*
* @param ctx current context
* @throws RequiredVersionMissingException exception in case of missing required app version
*/
@Throws(RequiredVersionMissingException::class)
fun callSendMorePointsGeocacheIntentMethod(ctx: Context) {
// prepare geocaches
val pw = PackPoints("test6")
for (i in 0..99) {
pw.addPoint(generateGeocache(i))
}
// send data
val send = ActionDisplayPoints.sendPack(ctx, pw, ActionDisplayVarious.ExtraAction.CENTER)
Logger.logD(TAG, "callSendMorePointsGeocacheIntentMethod(), " +
"send:" + send)
}
/**
* Send more geocaches with method, that store byte[] data in raw file and send locus link to this file.
* This method is useful in case of bigger number of caches that already has some troubles with
* method over intent.
*
* @param ctx current context
*/
@Throws(RequiredVersionMissingException::class)
fun callSendMorePointsGeocacheFileMethod(ctx: Context) {
val version = LocusUtils.getActiveVersion(ctx) ?: return
// get file to share
val file = SendToAppHelper.getCacheFile(ctx)
// prepare data
val pw = PackPoints("test07")
for (i in 0..999) {
pw.addPoint(generateGeocache(i))
}
val data = ArrayList<PackPoints>()
data.add(pw)
// send data
val send = if (version.isVersionValid(VersionCode.UPDATE_15)) {
// send file via FileProvider, you don't need WRITE_EXTERNAL_STORAGE permission for this
val uri = FileProvider.getUriForFile(ctx, ctx.getString(R.string.file_provider_authority), file)
ActionDisplayPoints.sendPacksFile(ctx, version, data, file, uri)
} else {
// send file old way, you need WRITE_EXTERNAL_STORAGE permission for this
ActionDisplayPoints.sendPacksFile(ctx, version, data, file)
}
Logger.logD(TAG, "callSendMorePointsGeocacheFileMethod(), send: $send")
}
/**
* Display single point with special "onClick" event. Such point when shown, will call back to this application.
* You may use this for loading extra data. So you send simple point and when show, you display extra information.
*
* @param ctx current context
* @throws RequiredVersionMissingException exception in case of missing required app version
*/
@Throws(RequiredVersionMissingException::class)
fun callSendOnePointWithCallbackOnDisplay(ctx: Context) {
// prepare data
val pd = PackPoints("test2")
val p = generateWaypoint(0)
p.setExtraOnDisplay(
"com.asamm.locus.api.sample",
"com.asamm.locus.api.sample.MainActivity",
EXTRA_ON_DISPLAY_ACTION_ID,
"id01")
pd.addPoint(p)
// send point
val send = ActionDisplayPoints.sendPack(ctx, pd, ActionDisplayVarious.ExtraAction.CENTER)
Logger.logD(TAG, "callSendOnePointWithCallbackOnDisplay(), " +
"send:" + send)
}
/**
* Display single point with special "onClick" event. Such point when shown, will call back to this application.
* You may use this for loading extra data. So you send simple point and when show, you display extra information.
*
* @param ctx current context
* @throws RequiredVersionMissingException exception in case of missing required app version
*/
@Throws(RequiredVersionMissingException::class)
fun callSendOnePointWithExtraCallback(ctx: Context) {
// prepare data
val pd = PackPoints("test3")
val p = generateWaypoint(0)
p.setExtraCallback("My button",
"com.asamm.locus.api.sample",
"com.asamm.locus.api.sample.MainActivity",
EXTRA_CALLBACK_ID,
"id01")
pd.addPoint(p)
// send point
val send = ActionDisplayPoints.sendPack(ctx, pd, ActionDisplayVarious.ExtraAction.CENTER)
Logger.logD(TAG, "callSendOnePointWithExtraCallback(), " +
"send:" + send)
}
/**
* Allows to search for waypoint in Locus database, based on the waypoint's ID.
*
* @param ctx current context
* @param activeLocus current active Locus
*/
fun callRequestPointIdByName(ctx: Context, activeLocus: LocusVersion) {
// reference to field
val etName = EditText(ctx)
// display dialog
AlertDialog.Builder(ctx)
.setTitle("Search for waypoints")
.setView(etName)
.setMessage("Write name of waypoint you want to find. You may use '%' before or after " + "name as wildcards. \n\n" +
"Read more at description of \'ActionTools.getLocusWaypointId\'")
.setPositiveButton("Search") { _, _ ->
// get defined name of point
val name = etName.text.toString()
if (name.isEmpty()) {
Toast.makeText(ctx, "Invalid text to search", Toast.LENGTH_LONG).show()
return@setPositiveButton
}
// start search
try {
val pts = ActionBasics.getPointsId(ctx, activeLocus, name)
Toast.makeText(ctx, "Found pts: \'" + pts.contentToString() + "\'",
Toast.LENGTH_LONG)
.show()
} catch (e: RequiredVersionMissingException) {
Toast.makeText(ctx, "Invalid Locus version", Toast.LENGTH_LONG).show()
e.printStackTrace()
}
}
.show()
}
/**
* Allows to display main 'Point screen' for a waypoint, defined by it's ID value.
*
* @param ctx current context
* @param activeLocus current active Locus
* @param pointId ID of point from Locus database
*/
@Throws(RequiredVersionMissingException::class)
fun callRequestDisplayPointScreen(ctx: Context, activeLocus: LocusVersion,
pointId: Long) {
// call special intent with request to return back
ActionBasics.displayPointScreen(ctx, activeLocus, pointId,
"com.asamm.locus.api.sample",
"com.asamm.locus.api.sample.MainActivity",
"myKey",
"myValue")
}
//*************************************************
// DISPLAY TRACKS
//*************************************************
/**
* Send (display) single track on the Locus Map map.
*
* @param ctx current context
* @throws RequiredVersionMissingException exception in case of missing required app version
*/
@Throws(RequiredVersionMissingException::class)
fun callSendOneTrack(ctx: Context) {
// prepare data. Create a huge track that may be send only over fileUri (over-limit of
// basic intent 1MB)
val track = generateTrack(50.0, 15.0, 100000)
// get file to share
val file = SendToAppHelper.getCacheFile(ctx)
// prepare file Uri: share via FileProvider. You don't need WRITE_EXTERNAL_STORAGE permission for this!
val uri = FileProvider.getUriForFile(ctx, ctx.getString(R.string.file_provider_authority), file)
// send data the app. 'SendMode' define core behavior how Locus app handle received data
val sendResult = SendTrack(SendMode.Basic(), track)
.sendOverFile(ctx, cacheFile = file, cacheFileUri = uri)
Logger.logD(TAG, "callSendOneTrack(), " +
"send:" + sendResult)
}
/**
* Send multiple tracks at once to Locus.
*
* @param ctx current context
*/
@Throws(RequiredVersionMissingException::class)
fun callSendMultipleTracks(ctx: Context) {
// prepare data
val tracks = ArrayList<Track>()
for (i in 0..4) {
val track = generateTrack(50 - i * 0.1, 15.0)
tracks.add(track)
}
// send data
val send = SendTracks(SendMode.Basic(centerOnData = true), tracks)
.send(ctx)
//ActionDisplayTracks.sendTracks(ctx, tracks, ActionDisplayVarious.ExtraAction.CENTER)
Logger.logD(TAG, "callSendMultipleTracks(" + ctx + "), " +
"send:" + send)
}
//*************************************************
// GUIDANCE / NAVIGATION
//*************************************************
/**
* Start guidance on point closest to certain coordinates. Useful in case, we know name and coordinates
* of points we previously send to app, but do not know it's real ID (which is common case if point
* was send into app with one of 'ActionDisplayPoints' method.
*/
fun startGuidanceToNearestPoint(ctx: Context, lv: LocusVersion) {
val pointsId = ActionBasics.getPointsId(ctx, lv,
Location(14.5, 50.6),
1000)
if (pointsId.isEmpty()) {
Logger.logD(TAG, "startGuidanceToNearestPoint(" + ctx + "), " +
"no valid point in range")
} else {
// search for specific point
for (pointId in pointsId) {
val pt = ActionBasics.getPoint(ctx, lv, pointId)
if (pt?.name?.equals("It is my point") == true) {
ActionBasics.actionStartGuiding(ctx, pt.id)
return
}
}
Logger.logD(TAG, "startGuidanceToNearestPoint(" + ctx + "), " +
"required points not found")
}
}
//*************************************************
// VARIOUS TOOLS
//*************************************************
fun callSendFileToSystem(ctx: Context) {
val file = getTempGpxFile(ctx, "<xml></xml>")
// generate Uri over FileProvider
val uri = FileProvider.getUriForFile(ctx, ctx.getString(R.string.file_provider_authority), file)
// send request for "display"
val send = ActionFiles.importFileSystem(ctx, uri, ActionFiles.getMimeType(file))
Logger.logD(TAG, "callSendFileToSystem($ctx), " +
"send: $send, file: $file, uri: $uri")
}
/**
* Send certain file directly to Locus Map application for handling.
*/
fun callSendFileToLocus(ctx: Context, lv: LocusVersion) {
val file = getTempGpxFile(ctx, "<xml></xml>")
// generate Uri over FileProvider
val uri = FileProvider.getUriForFile(ctx, ctx.getString(R.string.file_provider_authority), file)
// send request for "display"
val send = ActionFiles.importFileLocus(ctx, uri, ActionFiles.getMimeType(file), lv, false)
Logger.logD(TAG, "callSendFileToLocus($ctx, $lv), " +
"send: $send, file: $file, uri: $uri")
}
/**
* Send request on a location. This open Locus "Location picker" and allow to choose
* location from supported sources. Result will be delivered to activity as response
*
* @param act current activity
* @throws RequiredVersionMissingException exception in case of missing required app version
*/
@Throws(RequiredVersionMissingException::class)
fun pickLocation(act: Activity) {
ActionBasics.actionPickLocation(act)
}
@Throws(Exception::class)
fun showCircles(activity: FragmentActivity) {
val circles = ArrayList<Circle>()
val c0 = Circle(Location(50.15, 15.0), 10000000f, true)
c0.styleNormal = GeoDataStyle()
c0.styleNormal!!.setPolyStyle(Color.argb(50, Color.red(Color.RED),
Color.green(Color.RED), Color.blue(Color.RED)))
circles.add(c0)
val c1 = Circle(Location(50.0, 15.0), 1000f, false)
c1.styleNormal = GeoDataStyle()
c1.styleNormal!!.setLineStyle(Color.BLUE, 2f)
circles.add(c1)
val c2 = Circle(Location(50.1, 15.0), 1500f, false)
c2.styleNormal = GeoDataStyle()
c2.styleNormal!!.setLineStyle(Color.RED, 3f)
circles.add(c2)
val c3 = Circle(Location(50.2, 15.0), 2000f, false)
c3.styleNormal = GeoDataStyle()
c3.styleNormal!!.setLineStyle(Color.GREEN, 4f)
c3.styleNormal!!.setPolyStyle(Color.LTGRAY)
circles.add(c3)
val c4 = Circle(Location(50.3, 15.0), 1500f, false)
c4.styleNormal = GeoDataStyle()
c4.styleNormal!!.setLineStyle(Color.MAGENTA, 0f)
c4.styleNormal!!.setPolyStyle(
Color.argb(100, Color.red(Color.MAGENTA),
Color.green(Color.MAGENTA), Color.blue(Color.MAGENTA)))
circles.add(c4)
// send data
val send = ActionDisplayVarious.sendCirclesSilent(activity, circles, true)
Logger.logD(TAG, "showCircles(), " +
"send:" + send)
}
//*************************************************
// PRIVATE TOOLS
//*************************************************
/**
* Generate random point.
*
* @param id ID of point we wants to generate
* @return generated point
*/
fun generateWaypoint(id: Int): Point {
// create one simple point with location
val loc = Location()
loc.latitude = Math.random() + 50.0
loc.longitude = Math.random() + 14.0
return Point("Testing point - $id", loc)
}
/**
* Generate geocache point.
*
* @param id ID of point we wants to generate
* @return generated geocache
*/
private fun generateGeocache(id: Int): Point {
// generate basic point
val wpt = generateWaypoint(id)
// generate new geocaching data
val gcData = GeocachingData()
// fill data with variables
gcData.cacheID = "GC2Y0RJ" // REQUIRED
gcData.name = "Kokotín" // REQUIRED
// rest is optional so fill as you want - should work
gcData.type = (Math.random() * 13).toInt()
gcData.owner = "Menion1"
gcData.placedBy = "Menion2"
gcData.difficulty = 3.5f
gcData.terrain = 3.5f
gcData.container = GeocachingData.CACHE_SIZE_LARGE
var longDesc = ""
for (i in 0..4) {
longDesc += "Oh, what a looooooooooooooooooooooooong description, never imagine it could be sooo<i>oooo</i>long!<br /><br />Oh, what a looooooooooooooooooooooooong description, never imagine it could be sooo<i>oooo</i>long!"
}
gcData.setDescriptions(
"bla bla, this is some short description also with <b>HTML tags</b>", true,
longDesc, false)
// add one waypoint
val gcWpt = GeocachingWaypoint()
gcWpt.name = "Just an waypoint"
gcWpt.desc = "Description of waypoint"
gcWpt.lon = Math.random() + 14.0
gcWpt.lat = Math.random() + 50.0
gcWpt.type = GeocachingWaypoint.CACHE_WAYPOINT_TYPE_PARKING
gcData.waypoints.add(gcWpt)
// set data and return point
wpt.gcData = gcData
return wpt
}
/**
* Generate fictive track from defined start location.
*
* @param startLat start latitude
* @param startLon start longitude
* @return generated track
*/
private fun generateTrack(startLat: Double, startLon: Double, numOfPoints: Int = 1000): Track {
val track = Track()
track.name = "track from API ($startLat|$startLon)"
track.addParameter(GeoDataExtra.PAR_DESCRIPTION, "simple track bla bla bla ...")
// set style
val style = GeoDataStyle()
style.setLineStyle(Color.CYAN, 7.0f)
track.styleNormal = style
// generate points
var lat = startLat
var lon = startLon
val locs = ArrayList<Location>()
for (i in 0 until numOfPoints) {
lat += (Math.random() - 0.5) * 0.01
lon += Math.random() * 0.001
val loc = Location()
loc.latitude = lat
loc.longitude = lon
locs.add(loc)
}
track.points = locs
// set some points as highlighted wpts
val pts = ArrayList<Point>()
pts.add(Point("p1", locs[100]))
pts.add(Point("p2", locs[300]))
pts.add(Point("p3", locs[800]))
track.waypoints = pts
return track
}
}
| mit | 322566207635bcc7690fcbf066efad0e | 36.577875 | 236 | 0.609196 | 4.304819 | false | false | false | false |
asamm/locus-api | locus-api-android/src/main/java/locus/api/android/ActionDisplayVarious.kt | 1 | 6718 | package locus.api.android
import android.content.Context
import android.content.Intent
import android.os.Parcelable
import locus.api.android.objects.LocusVersion
import locus.api.android.objects.PackPoints
import locus.api.android.objects.VersionCode
import locus.api.android.utils.LocusConst
import locus.api.android.utils.LocusUtils
import locus.api.android.utils.exceptions.RequiredVersionMissingException
import locus.api.objects.Storable
import locus.api.objects.geoData.Circle
import locus.api.utils.Logger
object ActionDisplayVarious {
// tag for logger
private const val TAG = "ActionDisplayVarious"
enum class ExtraAction {
NONE, CENTER, IMPORT
}
// PRIVATE CALLS
@Throws(RequiredVersionMissingException::class)
internal fun sendData(action: String, context: Context, intent: Intent,
callImport: Boolean, center: Boolean): Boolean {
return sendData(action, context, intent,
callImport, center, VersionCode.UPDATE_01)
}
@Throws(RequiredVersionMissingException::class)
internal fun sendData(action: String, ctx: Context, intent: Intent,
callImport: Boolean, center: Boolean, vc: VersionCode): Boolean {
// get valid version
val lv = LocusUtils.getActiveVersion(ctx, vc)
?: throw RequiredVersionMissingException(vc.vcFree)
// send data with valid active version
return sendData(action, ctx, intent, callImport, center, lv)
}
@Throws(RequiredVersionMissingException::class)
internal fun sendData(action: String, ctx: Context, intent: Intent,
callImport: Boolean, center: Boolean, lv: LocusVersion): Boolean {
// check intent firstly
if (!hasData(intent)) {
Logger.logW(TAG, "Intent 'null' or not contain any data")
return false
}
// create intent with right calling method
intent.action = action
// set centering tag
intent.putExtra(LocusConst.INTENT_EXTRA_CENTER_ON_DATA, center)
// set import tag
if (action == LocusConst.ACTION_DISPLAY_DATA_SILENTLY) {
// send broadcast
LocusUtils.sendBroadcast(ctx, intent, lv)
} else {
// set import tag
intent.putExtra(LocusConst.INTENT_EXTRA_CALL_IMPORT, callImport)
// finally start activity
ctx.startActivity(intent)
}
return true
}
/**
* Method used for removing special objects from Locus map. Currently this method
* is used only for removing circles. If you want to remove any visible points or
* tracks you already send by this API, send simply new same intent (as the one
* with your data), but with empty list of data. So for example send again
* [PackPoints] that has same name!, but contain no data
*
* @param ctx current context
* @param extraName name of items to remove
* @param itemsId ID of item
* @return `true` if item was correctly send
* @throws RequiredVersionMissingException exception in case of missing required app version
*/
@Throws(RequiredVersionMissingException::class)
internal fun removeSpecialDataSilently(ctx: Context, lv: LocusVersion,
extraName: String, itemsId: LongArray?): Boolean {
// check Locus version
if (!lv.isVersionValid(VersionCode.UPDATE_02)) {
throw RequiredVersionMissingException(VersionCode.UPDATE_02)
}
// check intent firstly
if (itemsId == null || itemsId.isEmpty()) {
Logger.logW(TAG, "Intent 'null' or not contain any data")
return false
}
// create intent with right calling method
val intent = Intent(LocusConst.ACTION_REMOVE_DATA_SILENTLY)
intent.setPackage(lv.packageName)
intent.putExtra(extraName, itemsId)
// set import tag
LocusUtils.sendBroadcast(ctx, intent, lv)
return true
}
//*************************************************
// CIRCLES
//*************************************************
/**
* Simple way how to send circles over intent to Locus.
*
* @return true if success
*/
@Throws(RequiredVersionMissingException::class)
fun sendCirclesSilent(ctx: Context, circles: List<Circle>, centerOnData: Boolean): Boolean {
return sendCirclesSilent(LocusConst.ACTION_DISPLAY_DATA_SILENTLY,
ctx, circles, false, centerOnData)
}
@Throws(RequiredVersionMissingException::class)
private fun sendCirclesSilent(action: String, ctx: Context,
circles: List<Circle>, callImport: Boolean, centerOnData: Boolean): Boolean {
// check data
if (circles.isEmpty()) {
return false
}
// create and start intent
val intent = Intent()
intent.putExtra(LocusConst.INTENT_EXTRA_CIRCLES_MULTI,
Storable.getAsBytes(circles))
return sendData(action, ctx, intent, callImport, centerOnData,
VersionCode.UPDATE_02)
}
/**
* Allow to remove visible circles defined by it's ID value
*
* @param ctx current context that send broadcast
* @param itemsId list of circles IDs that should be removed from map
*/
@Throws(RequiredVersionMissingException::class)
fun removeCirclesSilent(ctx: Context, lv: LocusVersion, itemsId: LongArray) {
removeSpecialDataSilently(ctx, lv, LocusConst.INTENT_EXTRA_CIRCLES_MULTI, itemsId)
}
//*************************************************
// TOOLS
//*************************************************
/**
* Test if intent is valid and contains any data to display.
*
* @param intent intent to test
* @return `true` if intent is valid and contains data
*/
fun hasData(intent: Intent): Boolean {
// check intent object
return !(intent.getByteArrayExtra(LocusConst.INTENT_EXTRA_POINTS_DATA) == null
&& intent.getByteArrayExtra(LocusConst.INTENT_EXTRA_POINTS_DATA_ARRAY) == null
&& intent.getStringExtra(LocusConst.INTENT_EXTRA_POINTS_FILE_PATH) == null
&& intent.getParcelableExtra<Parcelable>(LocusConst.INTENT_EXTRA_POINTS_FILE_URI) == null
&& intent.getByteArrayExtra(LocusConst.INTENT_EXTRA_TRACKS_SINGLE) == null
&& intent.getByteArrayExtra(LocusConst.INTENT_EXTRA_TRACKS_MULTI) == null
&& intent.getParcelableExtra<Parcelable>(LocusConst.INTENT_EXTRA_TRACKS_FILE_URI) == null
&& intent.getByteArrayExtra(LocusConst.INTENT_EXTRA_CIRCLES_MULTI) == null)
}
}
| mit | d5e08da4a5bce7d990254d4b96fa4f16 | 37.83237 | 105 | 0.639476 | 4.626722 | false | false | false | false |
misaochan/apps-android-commons | app/src/main/java/fr/free/nrw/commons/upload/structure/depictions/DepictedItem.kt | 2 | 3763 | package fr.free.nrw.commons.upload.structure.depictions
import android.os.Parcelable
import fr.free.nrw.commons.nearby.Place
import fr.free.nrw.commons.upload.WikidataItem
import fr.free.nrw.commons.wikidata.WikidataProperties
import fr.free.nrw.commons.wikidata.WikidataProperties.*
import kotlinx.android.parcel.Parcelize
import org.wikipedia.wikidata.DataValue
import org.wikipedia.wikidata.Entities
import org.wikipedia.wikidata.Statement_partial
import java.math.BigInteger
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*
const val THUMB_IMAGE_SIZE = "70px"
/**
* Model class for Depicted Item in Upload and Explore
*/
@Parcelize
data class DepictedItem constructor(
override val name: String,
val description: String?,
val imageUrl: String?,
val instanceOfs: List<String>,
val commonsCategories: List<String>,
var isSelected: Boolean,
override val id: String
) : WikidataItem, Parcelable {
constructor(entity: Entities.Entity) : this(
entity,
entity.labels().byLanguageOrFirstOrEmpty(),
entity.descriptions().byLanguageOrFirstOrEmpty()
)
constructor(entity: Entities.Entity, place: Place) : this(
entity,
place.name,
place.longDescription
)
private constructor(entity: Entities.Entity, name: String, description: String) : this(
name,
description,
entity[IMAGE].primaryImageValue?.let {
getImageUrl(it.value, THUMB_IMAGE_SIZE)
},
entity[INSTANCE_OF].toIds(),
entity[COMMONS_CATEGORY]?.map { (it.mainSnak.dataValue as DataValue.ValueString).value }
?: emptyList(),
false,
entity.id()
)
override fun equals(other: Any?) = when {
this === other -> true
other is DepictedItem -> name == other.name
else -> false
}
override fun hashCode(): Int {
return name.hashCode()
}
}
private fun List<Statement_partial>?.toIds(): List<String> {
return this?.map { it.mainSnak.dataValue }
?.filterIsInstance<DataValue.EntityId>()
?.map { it.value.id }
?: emptyList()
}
private val List<Statement_partial>?.primaryImageValue: DataValue.ValueString?
get() = this?.firstOrNull()?.mainSnak?.dataValue as? DataValue.ValueString
operator fun Entities.Entity.get(property: WikidataProperties) =
statements?.get(property.propertyName)
private fun Map<String, Entities.Label>.byLanguageOrFirstOrEmpty() =
let { it[Locale.getDefault().language] ?: it.values.firstOrNull() }?.value() ?: ""
private fun getImageUrl(title: String, size: String): String {
return title.substringAfter(":")
.replace(" ", "_")
.let {
val MD5Hash = getMd5(it)
"https://upload.wikimedia.org/wikipedia/commons/thumb/${MD5Hash[0]}/${MD5Hash[0]}${MD5Hash[1]}/$it/$size-$it"
}
}
/**
* Generates MD5 hash for the filename
*/
private fun getMd5(input: String): String {
return try {
// Static getInstance method is called with hashing MD5
val md = MessageDigest.getInstance("MD5")
// digest() method is called to calculate message digest
// of an input digest() return array of byte
val messageDigest = md.digest(input.toByteArray())
// Convert byte array into signum representation
val no = BigInteger(1, messageDigest)
// Convert message digest into hex value
var hashtext = no.toString(16)
while (hashtext.length < 32) {
hashtext = "0$hashtext"
}
hashtext
} // For specifying wrong message digest algorithms
catch (e: NoSuchAlgorithmException) {
throw RuntimeException(e)
}
}
| apache-2.0 | 509ddeb9409068a9ab531aaa2c781174 | 30.099174 | 121 | 0.669678 | 4.21861 | false | false | false | false |
GeoffreyMetais/vlc-android | application/moviepedia/src/main/java/org/videolan/moviepedia/ui/MediaScrapingResultAdapter.kt | 1 | 2921 | /*
* ************************************************************************
* NextResultAdapter.kt
* *************************************************************************
* Copyright © 2019 VLC authors and VideoLAN
* Author: Nicolas POMEPUY
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* **************************************************************************
*
*
*/
package org.videolan.moviepedia.ui
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.ObsoleteCoroutinesApi
import org.videolan.moviepedia.databinding.MoviepediaItemBinding
import org.videolan.moviepedia.models.resolver.ResolverMedia
import org.videolan.tools.getLocaleLanguages
import org.videolan.vlc.gui.helpers.SelectorViewHolder
class MediaScrapingResultAdapter internal constructor(private val layoutInflater: LayoutInflater) : RecyclerView.Adapter<MediaScrapingResultAdapter.ViewHolder>() {
private var dataList: List<ResolverMedia>? = null
internal lateinit var clickHandler: MediaScrapingActivity.ClickHandler
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(MoviepediaItemBinding.inflate(layoutInflater, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val mediaResult = dataList!![position]
holder.binding.item = mediaResult
holder.binding.imageUrl = mediaResult.imageUri(layoutInflater.context.getLocaleLanguages())
}
fun setItems(newList: List<ResolverMedia>) {
dataList = newList
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return if (dataList == null) 0 else dataList!!.size
}
inner class ViewHolder(binding: MoviepediaItemBinding) : SelectorViewHolder<MoviepediaItemBinding>(binding) {
init {
binding.handler = clickHandler
}
}
}
@ExperimentalCoroutinesApi
@ObsoleteCoroutinesApi
@BindingAdapter("year")
fun showYear(view: TextView, item: ResolverMedia) {
view.text = item.year()
}
| gpl-2.0 | 94b6f4aba1d25da117d29e543febc489 | 36.922078 | 163 | 0.703425 | 5.104895 | false | false | false | false |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/gui/helpers/AudioUtil.kt | 1 | 7500 | /*****************************************************************************
* AudioUtil.java
*
* Copyright © 2011-2012 VLC authors and VideoLAN
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*/
package org.videolan.vlc.gui.helpers
import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Bitmap.CompressFormat
import android.graphics.BitmapFactory
import android.media.RingtoneManager
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.annotation.WorkerThread
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.ObsoleteCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.videolan.libvlc.util.AndroidUtil
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.tools.BitmapCache
import org.videolan.tools.CloseableUtils
import org.videolan.tools.HttpImageLoader
import org.videolan.vlc.R
import org.videolan.vlc.gui.helpers.UiTools.snackerConfirm
import org.videolan.vlc.util.Permissions
import java.io.*
import java.lang.Runnable
@ExperimentalCoroutinesApi
@ObsoleteCoroutinesApi
object AudioUtil {
const val TAG = "VLC/AudioUtil"
fun FragmentActivity.setRingtone(song: MediaWrapper) {
if (AndroidUtil.isOOrLater && !Permissions.canWriteStorage(this)) {
Permissions.askWriteStoragePermission(this, false, Runnable { setRingtone(song) })
return
}
if (!Permissions.canWriteSettings(this)) {
Permissions.checkWriteSettingsPermission(this, Permissions.PERMISSION_SYSTEM_RINGTONE)
return
}
lifecycleScope.snackerConfirm(window.decorView, getString(R.string.set_song_question, song.title)) {
val newRingtone = AndroidUtil.UriToFile(song.uri)
if (!withContext(Dispatchers.IO) { newRingtone.exists() }) {
Toast.makeText(applicationContext, getString(R.string.ringtone_error), Toast.LENGTH_SHORT).show()
return@snackerConfirm
}
val values = ContentValues().apply {
put(MediaStore.MediaColumns.DATA, newRingtone.absolutePath)
put(MediaStore.MediaColumns.TITLE, song.title)
put(MediaStore.MediaColumns.MIME_TYPE, "audio/*")
put(MediaStore.Audio.Media.ARTIST, song.artist)
put(MediaStore.Audio.Media.IS_RINGTONE, true)
put(MediaStore.Audio.Media.IS_NOTIFICATION, false)
put(MediaStore.Audio.Media.IS_ALARM, false)
put(MediaStore.Audio.Media.IS_MUSIC, false)
}
try {
val uri = withContext(Dispatchers.IO) {
val tmpUri = MediaStore.Audio.Media.getContentUriForPath(newRingtone.absolutePath)
contentResolver.delete(tmpUri, MediaStore.MediaColumns.DATA + "=\"" + newRingtone.absolutePath + "\"", null)
contentResolver.insert(tmpUri, values)
}
RingtoneManager.setActualDefaultRingtoneUri(
applicationContext,
RingtoneManager.TYPE_RINGTONE,
uri
)
} catch (e: Exception) {
Log.e(TAG, "error setting ringtone", e)
Toast.makeText(applicationContext,
getString(R.string.ringtone_error),
Toast.LENGTH_SHORT).show()
return@snackerConfirm
}
Toast.makeText(
applicationContext,
getString(R.string.ringtone_set, song.title),
Toast.LENGTH_SHORT)
.show()
}
}
private fun getCoverFromMediaStore(context: Context, media: MediaWrapper): String? {
val album = media.album ?: return null
val contentResolver = context.contentResolver
val uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI
val cursor = contentResolver.query(uri, arrayOf(MediaStore.Audio.Albums.ALBUM, MediaStore.Audio.Albums.ALBUM_ART),
MediaStore.Audio.Albums.ALBUM + " LIKE ?",
arrayOf(album), null)
if (cursor == null) {
// do nothing
} else if (!cursor.moveToFirst()) {
// do nothing
cursor.close()
} else {
val titleColumn = cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART)
val albumArt = cursor.getString(titleColumn)
cursor.close()
return albumArt
}
return null
}
@Throws(IOException::class)
private fun writeBitmap(bitmap: Bitmap?, path: String) {
var out: OutputStream? = null
try {
val file = File(path)
if (file.exists() && file.length() > 0)
return
out = BufferedOutputStream(FileOutputStream(file), 4096)
bitmap?.compress(CompressFormat.JPEG, 90, out)
} catch (e: Exception) {
Log.e(TAG, "writeBitmap failed : " + e.message)
} finally {
CloseableUtils.close(out)
}
}
//TODO Make it a suspend function to get rid of runBlocking {... }
@WorkerThread
fun readCoverBitmap(path: String?, width: Int): Bitmap? {
val path = path ?: return null
if (path.startsWith("http")) return runBlocking(Dispatchers.Main) {
HttpImageLoader.downloadBitmap(path)
}
return BitmapCache.getBitmapFromMemCache(path.substringAfter("file://")) ?: fetchCoverBitmap(path, width)
}
@WorkerThread
fun fetchCoverBitmap(path: String, width: Int): Bitmap? {
val path = path.substringAfter("file://")
var cover: Bitmap? = null
val options = BitmapFactory.Options()
/* Get the resolution of the bitmap without allocating the memory */
options.inJustDecodeBounds = true
BitmapFactory.decodeFile(path, options)
if (options.outWidth > 0 && options.outHeight > 0) {
options.inJustDecodeBounds = false
options.inSampleSize = 1
// Find the best decoding scale for the bitmap
if (width > 0) {
while (options.outWidth / options.inSampleSize > width)
options.inSampleSize = options.inSampleSize * 2
}
// Decode the file (with memory allocation this time)
cover = BitmapFactory.decodeFile(path, options)
BitmapCache.addBitmapToMemCache(path, cover)
}
return cover
}
}
| gpl-2.0 | 5cb6d11a016f1a158d3b3984dca8769a | 40.430939 | 128 | 0.635818 | 4.894909 | false | false | false | false |
chrislo27/Baristron | src/chrislo27/discordbot/impl/baristron/goat/Goat.kt | 1 | 3936 | /*
* 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 chrislo27.discordbot.impl.baristron.goat
import chrislo27.discordbot.BotManager
import chrislo27.discordbot.Userdata
import chrislo27.discordbot.util.builder
import chrislo27.discordbot.util.sendMessage
import chrislo27.oldbot.bots.baristabot2.goat.Backgrounds
import chrislo27.oldbot.bots.baristabot2.goat.Faces
import org.apache.commons.lang3.builder.HashCodeBuilder
import sx.blah.discord.handle.obj.IPrivateChannel
import sx.blah.discord.handle.obj.IUser
import sx.blah.discord.util.EmbedBuilder
import sx.blah.discord.util.RequestBuffer
class Goat {
val DEFAULT_NAME = "Goat"
val UPGRADE_COOLDOWN = "goatCooldownUpgrades"
val UPGRADE_INCOME = "goatIncomeUpgrades"
val UPGRADE_EFFECT_MULTIPLIER = 1.1
val UPGRADE_BASE_COST_INCOME: Long = 15000
val UPGRADE_BASE_COST_COOLDOWN: Long = 15000
val UPGRADE_COST_EXP_INCREASE = 1.5
/**
* Goat's name.
*/
var name: String? = DEFAULT_NAME
/**
* How many times the goat has been fed in its lifetime.
*/
var totalFeedings: Long = 0
/**
* The current level.
*/
var currentLevel: Long = 0
/**
* The current food for this level.
*/
var currentFoodForLevel: Long = 0
/**
* The millisecond time until the goat can be fed again.
*/
var timeUntilNextFeed: Long = 0
/**
* If notifications (like your goat is ready) should be sent.
*/
var shouldSendNotifications = false
@Volatile
var alreadySentNotification = false
var inventory: Inventory = Inventory()
var lastUrl: String? = null
set(value) {
field = value
lastUrlHash = hashCode()
}
var lastUrlHash: Int = 0
var profileData: ProfileData = ProfileData()
companion object {
fun getRequiredFoodToLevel(nextLevel: Long): Long {
return nextLevel - 1 + 1
}
fun getMsDelayTime(): Long {
return (1000 * 60 * 10).toLong()
}
}
fun sendNotification(user: IUser) {
val time = timeUntilNextFeed - System.currentTimeMillis()
if (time < 100) return
BotManager.bots.find {
it.client == user.client
}?.tickManager?.queueInMs(time) {
if (!shouldSendNotifications) return@queueInMs
val channel: IPrivateChannel = RequestBuffer.request<IPrivateChannel> { user.orCreatePMChannel }.get()
sendMessage(builder(channel).withEmbed(
EmbedBuilder().withColor(25, 200, 25).withTitle("Your goat is ready to be fed again!")
.appendField("To disable", "Use the command `goat notifications` to toggle notifications", false)
.build()))
}
}
fun invalidateImage() {
lastUrl = null
}
fun isImageStillValid(): Boolean = lastUrl != null && lastUrlHash == hashCode()
fun persist(user: IUser) {
Userdata.setGson("goat_" + user.id, this)
Userdata.instance().save()
}
override fun hashCode(): Int {
return HashCodeBuilder().append(name).append(currentLevel).append(totalFeedings).append(profileData.hashCode()).build()
}
}
class Inventory {
var hats: List<String> = arrayListOf()
var faces: List<String> = arrayListOf()
var backgrounds: List<String> = arrayListOf()
}
class ProfileData {
var hat: String? = null
var face: String? = Faces.DEFAULT.name
var background: String? = Backgrounds.DEFAULT.name
override fun hashCode(): Int {
return HashCodeBuilder().append(hat).append(face).append(background).build()
}
} | gpl-3.0 | 3251f5231c2a6c0c266071d3613f570d | 25.601351 | 121 | 0.71875 | 3.565217 | false | false | false | false |
soniccat/android-taskmanager | taskmanager/src/main/java/com/example/alexeyglushkov/taskmanager/file/FileLoadTask.kt | 1 | 1226 | package com.example.alexeyglushkov.taskmanager.file
import java.io.File
import android.content.Context
import com.example.alexeyglushkov.streamlib.data_readers_and_writers.InputStreamDataReader
import com.example.alexeyglushkov.streamlib.data_readers_and_writers.InputStreamDataReaders
import com.example.alexeyglushkov.taskmanager.task.TaskImpl
class FileLoadTask(protected var fileName: String,
protected var reader: InputStreamDataReader<*>,
context: Context) : TaskImpl() {
val context: Context
init {
this.context = context.applicationContext
}
protected val fileSize: Long
get() {
val file = File(context.filesDir, fileName)
return file.length()
}
override suspend fun startTask() {
val name = this.fileName
try {
reader.setProgressUpdater(private.createProgressUpdater(fileSize.toFloat()))
val fis = this.context.openFileInput(name)
val data = InputStreamDataReaders.readOnce(reader, fis)
taskResult = data
} catch (e: Exception) {
private.taskError = Exception("FileLoadTask exception: " + e.message)
}
}
}
| mit | 937b005be7016bdded19d07f1a66173e | 30.435897 | 91 | 0.670473 | 4.733591 | false | false | false | false |
06needhamt/Neuroph-Intellij-Plugin | neuroph-plugin/src/com/thomas/needham/neurophidea/settings/AutoGenerateCodeSetting.kt | 1 | 6754 | /*
The MIT License (MIT)
neuroph-plugin Copyright (c) 2016 thoma
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.thomas.needham.neurophidea.settings
import com.intellij.ide.DataManager
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.actionSystem.DataConstants
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.project.Project
import com.thomas.needham.neurophidea.Constants.GENERATE_CODE_KEY
import com.thomas.needham.neurophidea.Constants.GENERATE_GROOVY_KEY
import com.thomas.needham.neurophidea.Constants.GENERATE_JAVA_KEY
import com.thomas.needham.neurophidea.Constants.GENERATE_KOTLIN_KEY
import com.thomas.needham.neurophidea.Constants.GENERATE_SCALA_KEY
import java.awt.event.ItemEvent
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JPanel
/**
* Created by thoma on 13/09/2016.
*/
class AutoGenerateCodeSetting : Configurable {
var generate: Boolean = false
var generateJava: Boolean = false
var generateGroovy: Boolean = false
var generateScala: Boolean = false
var generateKotlin: Boolean = false
var properties: PropertiesComponent = PropertiesComponent.getInstance(getProject.invoke())
companion object Interface {
var modified: Boolean = true
val panel: JPanel = JPanel(null)
val insets = panel.insets
val generateCheckBox: JCheckBox = JCheckBox("Regenerate Code On Change")
val javaCheckBox: JCheckBox = JCheckBox("Generate Java Code")
val groovyCheckBox: JCheckBox = JCheckBox("Generate Groovy Code")
val scalaCheckBox: JCheckBox = JCheckBox("Generate Scala Code")
val kotlinCheckBox: JCheckBox = JCheckBox("Generate Kotlin Code")
//val checkBoxGroupName : String = "CodeGenerationGroup"
@JvmStatic
val getProject: () -> Project? = {
val dataContext: DataContext = DataManager.getInstance().getDataContext()
val project: Project? = dataContext.getData(DataConstants.PROJECT) as Project?
project
}
}
override fun isModified(): Boolean {
return modified
}
override fun getDisplayName(): String {
return "Code Generator Settings"
}
override fun apply() {
generate = generateCheckBox.isSelected
generateJava = javaCheckBox.isSelected
generateGroovy = groovyCheckBox.isSelected
generateScala = scalaCheckBox.isSelected
generateKotlin = kotlinCheckBox.isSelected
properties.setValue(GENERATE_CODE_KEY, generate)
properties.setValue(GENERATE_JAVA_KEY, generateJava)
properties.setValue(GENERATE_GROOVY_KEY, generateGroovy)
properties.setValue(GENERATE_SCALA_KEY, generateScala)
properties.setValue(GENERATE_KOTLIN_KEY, generateKotlin)
}
override fun createComponent(): JComponent {
generateCheckBox.setBounds(insets.left + 50, insets.top + 30, 200, 25)
panel.add(generateCheckBox)
javaCheckBox.setBounds(generateCheckBox.bounds.x + 50, generateCheckBox.bounds.y + 30, 200, 25)
panel.add(javaCheckBox)
groovyCheckBox.setBounds(javaCheckBox.bounds.x, javaCheckBox.bounds.y + 30, 200, 25)
panel.add(groovyCheckBox)
scalaCheckBox.setBounds(groovyCheckBox.bounds.x, groovyCheckBox.bounds.y + 30, 200, 25)
panel.add(scalaCheckBox)
kotlinCheckBox.setBounds(scalaCheckBox.bounds.x, scalaCheckBox.bounds.y + 30, 200, 25)
panel.add(kotlinCheckBox)
generateCheckBox.addItemListener { e ->
modified = true
if (e.stateChange.and(ItemEvent.SELECTED) != 0) {
generate = true
javaCheckBox.isEnabled = true
groovyCheckBox.isEnabled = true
scalaCheckBox.isEnabled = true
kotlinCheckBox.isEnabled = true
} else if (e.stateChange.and(ItemEvent.DESELECTED) != 0) {
generate = false
generateJava = false
generateGroovy = false
generateScala = false
generateKotlin = false
javaCheckBox.isEnabled = false
groovyCheckBox.isEnabled = false
scalaCheckBox.isEnabled = false
kotlinCheckBox.isEnabled = false
}
}
javaCheckBox.addItemListener { e ->
modified = true
if (e.stateChange.and(ItemEvent.SELECTED) != 0) {
if (generate)
generateJava = true
} else if (e.stateChange.and(ItemEvent.DESELECTED) != 0) {
if (generate)
generateJava = false
}
}
groovyCheckBox.addItemListener { e ->
modified = true
if (e.stateChange.and(ItemEvent.SELECTED) != 0) {
if (generate)
generateGroovy = true
} else if (e.stateChange.and(ItemEvent.DESELECTED) != 0) {
if (generate)
generateGroovy = false
}
}
scalaCheckBox.addItemListener { e ->
modified = true
if (e.stateChange.and(ItemEvent.SELECTED) != 0) {
if (generate)
generateScala = true
} else if (e.stateChange.and(ItemEvent.DESELECTED) != 0) {
if (generate)
generateScala = false
}
}
kotlinCheckBox.addItemListener { e ->
modified = true
if (e.stateChange.and(ItemEvent.SELECTED) != 0) {
if (generate)
generateKotlin = true
} else if (e.stateChange.and(ItemEvent.DESELECTED) != 0) {
if (generate)
generateKotlin = false
}
}
return panel
}
override fun reset() {
modified = false
generate = properties.getBoolean(GENERATE_CODE_KEY, false)
generateJava = properties.getBoolean(GENERATE_JAVA_KEY, false)
generateGroovy = properties.getBoolean(GENERATE_GROOVY_KEY, false)
generateScala = properties.getBoolean(GENERATE_SCALA_KEY, false)
generateKotlin = properties.getBoolean(GENERATE_KOTLIN_KEY, false)
}
override fun getHelpTopic(): String {
return ""
}
override fun disposeUIResources() {
super.disposeUIResources()
panel.remove(kotlinCheckBox)
panel.remove(scalaCheckBox)
panel.remove(groovyCheckBox)
panel.remove(javaCheckBox)
panel.remove(generateCheckBox)
}
} | mit | 586a65451de5e82997391ad346eae090 | 34.740741 | 97 | 0.747113 | 3.947399 | false | false | false | false |
rsiebert/TVHClient | data/src/main/java/org/tvheadend/data/dao/ProgramDao.kt | 1 | 5780 | package org.tvheadend.data.dao
import androidx.lifecycle.LiveData
import androidx.room.*
import org.tvheadend.data.entity.EpgProgramEntity
import org.tvheadend.data.entity.ProgramEntity
@Dao
internal interface ProgramDao {
@get:Query("SELECT COUNT (*) FROM programs AS p " +
" WHERE $CONNECTION_IS_ACTIVE")
val itemCount: LiveData<Int>
@get:Query("SELECT COUNT (*) FROM programs AS p " +
" WHERE $CONNECTION_IS_ACTIVE")
val itemCountSync: Int
@Transaction
@Query(PROGRAM_BASE_QUERY +
" WHERE $CONNECTION_IS_ACTIVE" +
" AND ((p.start >= :time) " +
" OR (p.start <= :time AND p.stop >= :time)) " +
" GROUP BY p.id " +
" ORDER BY p.start, p.channel_name ASC")
fun loadProgramsFromTime(time: Long): LiveData<List<ProgramEntity>>
@Transaction
@Query(PROGRAM_BASE_QUERY +
" WHERE $CONNECTION_IS_ACTIVE" +
" AND p.channel_id = :channelId " +
" AND ((p.start >= :time) " +
" OR (p.start <= :time AND p.stop >= :time)) " +
" GROUP BY p.id " +
" ORDER BY p.start ASC")
fun loadProgramsFromChannelFromTime(channelId: Int, time: Long): LiveData<List<ProgramEntity>>
@Transaction
@Query(EPG_PROGRAM_BASE_QUERY +
" WHERE $CONNECTION_IS_ACTIVE" +
" AND channel_id = :channelId " +
// Program is within time slot
" AND ((start >= :startTime AND stop <= :endTime) " +
// Program is at the beginning of time slot
" OR (start <= :startTime AND stop > :startTime) " +
// Program is at the end of the time slot
" OR (start < :endTime AND stop >= :endTime)) " +
" GROUP BY p.id " +
" ORDER BY start ASC")
fun loadEpgProgramsFromChannelBetweenTimeSync(channelId: Int, startTime: Long, endTime: Long): List<EpgProgramEntity>
@Transaction
@Query(PROGRAM_BASE_QUERY +
" WHERE $CONNECTION_IS_ACTIVE" +
" AND channel_id = :channelId " +
// Program is within time slot
" AND ((start >= :startTime AND stop <= :endTime) " +
// Program is at the beginning of time slot
" OR (start <= :startTime AND stop > :startTime) " +
// Program is at the end of the time slot
" OR (start < :endTime AND stop >= :endTime)) " +
" GROUP BY p.id " +
" ORDER BY start ASC")
fun loadProgramsFromChannelBetweenTimeSync(channelId: Int, startTime: Long, endTime: Long): List<ProgramEntity>
@Transaction
@Query(PROGRAM_BASE_QUERY +
" WHERE $CONNECTION_IS_ACTIVE" +
" GROUP BY p.id " +
" ORDER BY p.start, p.channel_name ASC")
fun loadPrograms(): LiveData<List<ProgramEntity>>
@Transaction
@Query(PROGRAM_BASE_QUERY +
" WHERE $CONNECTION_IS_ACTIVE" +
" GROUP BY p.id " +
" ORDER BY p.start, p.channel_name ASC")
fun loadProgramsSync(): List<ProgramEntity>
@Transaction
@Query(PROGRAM_BASE_QUERY +
" WHERE $CONNECTION_IS_ACTIVE" +
" AND p.id = :id")
fun loadProgramById(id: Int): LiveData<ProgramEntity>
@Transaction
@Query(PROGRAM_BASE_QUERY +
" WHERE $CONNECTION_IS_ACTIVE" +
" AND p.id = :id")
fun loadProgramByIdSync(id: Int): ProgramEntity?
@Query(PROGRAM_BASE_QUERY +
" WHERE $CONNECTION_IS_ACTIVE" +
" AND p.channel_id = :channelId " +
" ORDER BY start DESC")
fun loadProgramsFromChannelSync(channelId: Int): List<ProgramEntity>
@Query(PROGRAM_BASE_QUERY +
" WHERE $CONNECTION_IS_ACTIVE" +
" AND p.channel_id = :channelId " +
" ORDER BY start DESC LIMIT 1")
fun loadLastProgramFromChannelSync(channelId: Int): ProgramEntity?
@Query(EPG_PROGRAM_BASE_QUERY +
" WHERE $CONNECTION_IS_ACTIVE" +
" AND p.channel_id = :channelId " +
" GROUP BY title, subtitle" +
" ORDER BY title, start DESC")
fun loadDuplicateProgramsSync(channelId: Int): List<EpgProgramEntity>
@Query("DELETE FROM programs " + "WHERE stop < :time")
fun deleteProgramsByTime(time: Long)
@Transaction
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(programs: List<ProgramEntity>)
@Transaction
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(program: ProgramEntity)
@Update
fun update(programs: List<ProgramEntity>)
@Update
fun update(program: ProgramEntity)
@Delete
fun delete(programs: List<ProgramEntity>)
@Delete
fun delete(program: ProgramEntity)
@Query("DELETE FROM programs " +
"WHERE connection_id IN (SELECT id FROM connections WHERE active = 1) " +
" AND id = :id")
fun deleteById(id: Int)
@Query("DELETE FROM programs")
fun deleteAll()
companion object {
const val PROGRAM_BASE_QUERY = "SELECT p.*," +
"c.name AS channel_name, " +
"c.icon AS channel_icon " +
"FROM programs AS p " +
"LEFT JOIN channels AS c ON c.id = p.channel_id "
const val EPG_PROGRAM_BASE_QUERY = "SELECT p.id, " +
"p.title, " +
"p.subtitle, " +
"p.channel_id, " +
"p.connection_id, " +
"p.start, " +
"p.stop, " +
"p.content_type " +
"FROM programs AS p " +
"LEFT JOIN channels AS c ON c.id = channel_id "
const val CONNECTION_IS_ACTIVE = " p.connection_id IN (SELECT id FROM connections WHERE active = 1) "
}
}
| gpl-3.0 | d04e46b554c45d90d0a8fc8518dd6ab1 | 34.460123 | 121 | 0.571972 | 4.013889 | false | false | false | false |
06needhamt/Neuroph-Intellij-Plugin | neuroph-plugin/src/com/thomas/needham/neurophidea/actions/ShowCreateNetworkFormAction.kt | 1 | 2127 | /*
The MIT License (MIT)
Copyright (c) 2016 Tom Needham
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.thomas.needham.neurophidea.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
import com.thomas.needham.neurophidea.forms.create.CreateNetworkForm
/**
* Created by Thomas Needham on 25/05/2016.
*/
class ShowCreateNetworkFormAction : AnAction() {
var form: CreateNetworkForm? = null
var itr: Long = 0L
companion object ProjectInfo {
var project: Project? = null
var projectDirectory: String? = ""
var isOpen: Boolean? = false
}
override fun actionPerformed(e: AnActionEvent) {
InitialisationAction.project = e.project
InitialisationAction.projectDirectory = InitialisationAction.project?.basePath
InitialisationAction.isOpen = InitialisationAction.project?.isOpen
form = CreateNetworkForm()
}
override fun update(e: AnActionEvent) {
super.update(e)
if (form != null) {
form?.repaint(itr, 0, 0, form?.width!!, form?.height!!)
itr++
}
e.presentation.isEnabledAndVisible = true
}
}
| mit | 70bf82515a80bbe1abc1319905629427 | 35.050847 | 80 | 0.779031 | 4.262525 | false | false | false | false |
nextcloud/android | app/src/main/java/com/owncloud/android/authentication/PassCodeManager.kt | 1 | 6079 | /*
* ownCloud Android client application
*
* @author David A. Velasco
* Copyright (C) 2015 ownCloud Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.owncloud.android.authentication
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.PowerManager
import android.view.View
import android.view.WindowManager
import com.nextcloud.client.core.Clock
import com.nextcloud.client.preferences.AppPreferences
import com.owncloud.android.MainApp
import com.owncloud.android.ui.activity.PassCodeActivity
import com.owncloud.android.ui.activity.RequestCredentialsActivity
import com.owncloud.android.ui.activity.SettingsActivity
import com.owncloud.android.utils.DeviceCredentialUtils
import kotlin.math.abs
@Suppress("TooManyFunctions")
class PassCodeManager(private val preferences: AppPreferences, private val clock: Clock) {
companion object {
private val exemptOfPasscodeActivities = setOf(
PassCodeActivity::class.java,
RequestCredentialsActivity::class.java
)
const val PASSCODE_ACTIVITY = 9999
/**
* Keeping a "low" positive value is the easiest way to prevent
* the pass code being requested on screen rotations.
*/
private const val PASS_CODE_TIMEOUT = 5000
}
private var visibleActivitiesCounter = 0
private fun isExemptActivity(activity: Activity): Boolean {
return exemptOfPasscodeActivities.contains(activity.javaClass)
}
fun onActivityResumed(activity: Activity): Boolean {
var askedForPin = false
val timestamp = preferences.lockTimestamp
setSecureFlag(activity)
if (!isExemptActivity(activity)) {
val passcodeRequested = passCodeShouldBeRequested(timestamp)
val credentialsRequested = deviceCredentialsShouldBeRequested(timestamp, activity)
if (passcodeRequested || credentialsRequested) {
getActivityRootView(activity)?.visibility = View.GONE
} else {
getActivityRootView(activity)?.visibility = View.VISIBLE
}
if (passcodeRequested) {
askedForPin = true
preferences.lockTimestamp = 0
requestPasscode(activity)
}
if (credentialsRequested) {
askedForPin = true
preferences.lockTimestamp = 0
requestCredentials(activity)
}
}
if (!askedForPin && preferences.lockTimestamp != 0L) {
updateLockTimestamp()
}
if (!isExemptActivity(activity)) {
visibleActivitiesCounter++ // keep it AFTER passCodeShouldBeRequested was checked
}
return askedForPin
}
private fun setSecureFlag(activity: Activity) {
val window = activity.window
if (window != null) {
if (isPassCodeEnabled() || deviceCredentialsAreEnabled(activity)) {
window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
}
}
}
private fun requestPasscode(activity: Activity) {
val i = Intent(MainApp.getAppContext(), PassCodeActivity::class.java)
i.action = PassCodeActivity.ACTION_CHECK
i.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
activity.startActivityForResult(i, PASSCODE_ACTIVITY)
}
private fun requestCredentials(activity: Activity) {
val i = Intent(MainApp.getAppContext(), RequestCredentialsActivity::class.java)
i.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
activity.startActivityForResult(i, PASSCODE_ACTIVITY)
}
fun onActivityStopped(activity: Activity) {
if (visibleActivitiesCounter > 0 && !isExemptActivity(activity)) {
visibleActivitiesCounter--
}
val powerMgr = activity.getSystemService(Context.POWER_SERVICE) as PowerManager
if ((isPassCodeEnabled() || deviceCredentialsAreEnabled(activity)) && !powerMgr.isScreenOn) {
activity.moveTaskToBack(true)
}
}
fun updateLockTimestamp() {
preferences.lockTimestamp = clock.millisSinceBoot
}
/**
* `true` if the time elapsed since last unlock is longer than [PASS_CODE_TIMEOUT] and no activities are visible
*/
private fun shouldBeLocked(timestamp: Long) =
abs(clock.millisSinceBoot - timestamp) > PASS_CODE_TIMEOUT &&
visibleActivitiesCounter <= 0
private fun passCodeShouldBeRequested(timestamp: Long): Boolean {
return shouldBeLocked(timestamp) && isPassCodeEnabled()
}
private fun isPassCodeEnabled(): Boolean = SettingsActivity.LOCK_PASSCODE == preferences.lockPreference
private fun deviceCredentialsShouldBeRequested(timestamp: Long, activity: Activity): Boolean {
return shouldBeLocked(timestamp) && deviceCredentialsAreEnabled(activity)
}
private fun deviceCredentialsAreEnabled(activity: Activity): Boolean {
return SettingsActivity.LOCK_DEVICE_CREDENTIALS == preferences.lockPreference ||
(preferences.isFingerprintUnlockEnabled && DeviceCredentialUtils.areCredentialsAvailable(activity))
}
private fun getActivityRootView(activity: Activity): View? {
return activity.window.findViewById(android.R.id.content)
?: activity.window.decorView.findViewById(android.R.id.content)
}
}
| gpl-2.0 | b566505cb32fe7934b9fe8d72458727e | 37.232704 | 116 | 0.687284 | 4.813143 | false | false | false | false |
xiaojinzi123/Component | ComponentImpl/src/main/java/com/xiaojinzi/component/ComponentActivityStack.kt | 1 | 3090 | package com.xiaojinzi.component
import android.app.Activity
import com.xiaojinzi.component.support.Utils
import java.util.*
/**
* Component 的 Activity 栈
*
* @author xiaojinzi
*/
object ComponentActivityStack {
/**
* the stack will be save all reference of Activity
*/
private val activityStack: Stack<Activity> = Stack()
/**
* 是否是空的
*/
val isEmpty: Boolean
@Synchronized
get() = activityStack.isEmpty()
/**
* 返回顶层的 Activity
*/
val topActivity: Activity?
@Synchronized
get() = if (isEmpty) null else activityStack[activityStack.lastIndex]
/**
* 返回顶层第二个的 Activity
*/
val secondTopActivity: Activity?
@Synchronized
get() = if (isEmpty || activityStack.size < 2) null else activityStack[activityStack.lastIndex - 1]
/**
* 返回底层的 Activity
*/
val bottomActivity: Activity?
@Synchronized
get() = if (isEmpty || activityStack.size < 1) null else activityStack[0]
/**
* 返回顶层的活着的 Activity
*/
val topAliveActivity: Activity?
@Synchronized
get() {
var result: Activity? = null
if (!isEmpty) {
val size = activityStack.size
for (i in size - 1 downTo 0) {
val activity = activityStack[i]
// 如果已经销毁, 就下一个
if (!Utils.isActivityDestoryed(activity)) {
result = activity
break
}
}
}
return result
}
/**
* 进入栈
*/
@Synchronized
fun pushActivity(activity: Activity) {
if (activityStack.contains(activity)) {
return
}
activityStack.add(activity)
}
/**
* remove the reference of Activity
*
* @author xiaojinzi
*/
@Synchronized
fun removeActivity(activity: Activity) {
activityStack.remove(activity)
}
/**
* 返回顶层的 Activity除了某一个
*/
@Synchronized
fun getTopActivityExcept(clazz: Class<out Activity?>): Activity? {
val size = activityStack.size
for (i in size - 1 downTo 0) {
val itemActivity = activityStack[i]
if (itemActivity.javaClass != clazz) {
return itemActivity
}
}
return null
}
/**
* 是否存在某一个 Activity
*/
@Synchronized
fun isExistActivity(clazz: Class<out Activity>): Boolean {
for (activity in activityStack) {
if (activity.javaClass == clazz) {
return true
}
}
return false
}
@Synchronized
fun isExistOtherActivityExcept(clazz: Class<out Activity>): Boolean {
for (activity in activityStack) {
if (activity.javaClass != clazz) {
return true
}
}
return false
}
} | apache-2.0 | da6d21b8f47ed275d773d6c5dd5998d7 | 22.346457 | 107 | 0.534413 | 4.727273 | false | false | false | false |
candalo/rss-reader | app/src/main/java/com/github/rssreader/features/feed/data/entity/FeedItemEntity.kt | 1 | 838 | package com.github.rssreader.features.feed.data.entity
import org.simpleframework.xml.Element
import org.simpleframework.xml.ElementList
import org.simpleframework.xml.Root
@Root(name = "item", strict = false)
data class FeedItemEntity(
@field:Element(name = "title", required = false)
var title: String = "",
@field:Element(name = "link", required = false)
var link: String = "",
@field:Element(name = "description", required = false)
var description: String = "",
@field:Element(name = "author", required = false)
var authorEmail: String = "",
@field:ElementList(entry = "category", inline = true, required = false)
var categories: List<String> = ArrayList(),
@field:Element(name = "pubDate", required = false)
var pubDate: String = ""
) | mit | 1ad73a61c9b17ac6f4a8b62cc086ebd2 | 37.136364 | 79 | 0.645585 | 4.107843 | false | false | false | false |
hewking/HUILibrary | app/src/main/java/com/hewking/custom/util/ViewGroupEx.kt | 1 | 6908 | package com.hewking.custom.util
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import androidx.annotation.LayoutRes
/**
* Kotlin ViewGroup的扩展
* Created by angcyo on 2017-07-26.
*/
/**
* 计算child在parent中的位置坐标, 请确保child在parent中.
* */
public fun ViewGroup.getLocationInParent(child: View, location: Rect) {
var x = 0
var y = 0
var view = child
while (view.parent != this) {
x += view.left
y += view.top
view = view.parent as View
}
x += view.left
y += view.top
location.set(x, y, x + child.measuredWidth, y + child.measuredHeight)
}
public fun ViewGroup.findView(targetView: View /*判断需要结果的View*/, touchRawX: Float, touchRawY: Float, offsetTop: Int = 0): View? {
/**键盘的高度*/
var touchView: View? = targetView
val rect = Rect()
for (i in childCount - 1 downTo 0) {
val childAt = getChildAt(i)
if (childAt.visibility != View.VISIBLE) {
continue
}
// childAt.getWindowVisibleDisplayFrame(rect)
// L.e("${this}:1 ->$i $rect")
childAt.getGlobalVisibleRect(rect)
// L.e("${this}:2 ->$i $rect")
// L.e("call: ------------------end -> ")
rect.offset(0, -offsetTop)
fun check(view: View): View? {
if (view.visibility == View.VISIBLE &&
view.measuredHeight != 0 &&
view.measuredWidth != 0 &&
(view.left != view.right) &&
(view.top != view.bottom) &&
rect.contains(touchRawX.toInt(), touchRawY.toInt())) {
return view
}
return null
}
if (childAt is ViewGroup && childAt.childCount > 0) {
val resultView = childAt.findView(targetView, touchRawX, touchRawY, offsetTop)
if (resultView != null && resultView != targetView) {
touchView = resultView
break
} else {
val check = check(childAt)
if (check != null) {
touchView = childAt
break
}
}
} else {
val check = check(childAt)
if (check != null) {
touchView = childAt
break
}
}
}
return touchView
}
/**将子View的数量, 重置到指定的数量*/
public fun ViewGroup.resetChildCount(newSize: Int, onAddView: () -> View) {
val oldSize = childCount
val count = newSize - oldSize
if (count > 0) {
//需要补充子View
for (i in 0 until count) {
addView(onAddView.invoke())
}
} else if (count < 0) {
//需要移除子View
for (i in 0 until count.abs()) {
removeViewAt(oldSize - 1 - i)
}
}
}
public fun <T> ViewGroup.addView(size: Int, datas: List<T>, onAddViewCallback: OnAddViewCallback<T>) {
this.resetChildCount(size) {
val layoutId = onAddViewCallback.getLayoutId()
val childView = if (layoutId > 0) {
LayoutInflater.from(context).inflate(layoutId, this, false)
} else onAddViewCallback.getView()!!
onAddViewCallback.onCreateView(childView)
childView
}
for (i in 0 until size) {
onAddViewCallback.onInitView(getChildAt(i), if (i < datas.size) datas[i] else null, i)
}
}
/**动态添加View, 并初始化 (做了性能优化)*/
public fun <T> ViewGroup.addView(datas: List<T>, onAddViewCallback: OnAddViewCallback<T>) {
addView(datas.size, datas, onAddViewCallback)
}
/**枚举所有child view*/
public fun ViewGroup.childs(map: (Int, View) -> Unit) {
for (i in 0 until childCount) {
val childAt = getChildAt(i)
map.invoke(i, childAt)
}
}
public fun ViewGroup.show(@LayoutRes layoutId: Int): View {
return show(layoutId, null, null)
}
public fun ViewGroup.show(@LayoutRes layoutId: Int, enterAnimation: Animation?, otherExitAnimation: Animation?): View {
val viewWithTag = findViewWithTag<View>(layoutId)
if (viewWithTag == null) {
//之前的view
val preView = if (childCount > 0) {
getChildAt(childCount - 1)
} else {
null
}
LayoutInflater.from(context).inflate(layoutId, this)
val newView = getChildAt(childCount - 1)
newView.tag = layoutId
newView?.let { view ->
enterAnimation?.let {
view.startAnimation(it)
}
}
preView?.let { view ->
otherExitAnimation?.let {
view.startAnimation(it)
}
}
return newView
}
return viewWithTag
}
public fun ViewGroup.hide(@LayoutRes layoutId: Int): View? {
return hide(layoutId, null, null)
}
public fun ViewGroup.hide(@LayoutRes layoutId: Int, exitAnimation: Animation?, otherEnterAnimation: Animation?): View? {
val viewWithTag = findViewWithTag<View>(layoutId)
if (viewWithTag == null || viewWithTag.parent == null) {
} else {
//之前的view
val preView = if (childCount > 1) {
getChildAt(childCount - 2)
} else {
null
}
val parent = viewWithTag.parent
if (parent is ViewGroup) {
viewWithTag.let { view ->
exitAnimation?.let {
it.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(animation: Animation?) {
}
override fun onAnimationRepeat(animation: Animation?) {
}
override fun onAnimationEnd(animation: Animation?) {
parent.removeView(viewWithTag)
}
})
view.startAnimation(it)
}
if (exitAnimation == null) {
parent.removeView(viewWithTag)
}
}
preView?.let { view ->
otherEnterAnimation?.let {
view.startAnimation(it)
}
}
}
}
return viewWithTag
}
abstract class OnAddViewCallback<T> {
open fun getLayoutId(): Int = -1
open fun getView(): View? = null
/**当首次创建View时, 回调*/
open fun onCreateView(child: View) {
}
open fun onInitView(view: View, data: T?, index: Int) {
}
} | mit | db7b9000c1bf7c23f9e34a1089eddfea | 26.209205 | 128 | 0.525668 | 4.382315 | false | false | false | false |
REBOOTERS/AndroidAnimationExercise | imitate/src/main/java/com/engineer/imitate/model/School.kt | 1 | 1397 | package com.engineer.imitate.model
import android.os.Parcel
import android.os.Parcelable
import androidx.room.Ignore
class School @Ignore constructor() : Parcelable {
class Location {
var lat = 0f
var lng = 0f
override fun toString(): String {
return "Location{" +
"lat=" + lat +
", lng=" + lng +
'}'
}
}
var name: String? = null
var province: String? = null
var city: String? = null
var area: String? = null
var address: String? = null
var location: Location? = null
override fun toString(): String {
return "School{" +
"name='" + name + '\'' +
", province='" + province + '\'' +
", city='" + city + '\'' +
", area='" + area + '\'' +
", address='" + address + '\'' +
", location=" + location +
'}'
}
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<School> = object : Parcelable.Creator<School> {
override fun createFromParcel(source: Parcel): School = School()
override fun newArray(size: Int): Array<School?> = arrayOfNulls(size)
}
}
} | apache-2.0 | 8c381218043365dce7a5b368d392a718 | 24.418182 | 87 | 0.506084 | 4.703704 | false | false | false | false |
langara/MyIntent | myintent/src/main/java/pl/mareklangiewicz/myintent/RecentCommandsRVService.kt | 1 | 1693 | package pl.mareklangiewicz.myintent
import android.content.Context
import android.content.Intent
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import pl.mareklangiewicz.myutils.EX_COMMAND
import java.util.*
/**
* Created by Marek Langiewicz on 24.11.15.
*/
class RecentCommandsRVService : RemoteViewsService() {
override fun onGetViewFactory(intent: Intent): RemoteViewsService.RemoteViewsFactory = RVFactory(this.applicationContext)
internal inner class RVFactory(private val context: Context) : RemoteViewsService.RemoteViewsFactory {
private val MAX = 64
private val commands = ArrayList<String>(MAX)
private fun reload() {
commands.clear()
MIContract.CmdRecent.load(context, commands, MAX)
}
override fun onCreate() = reload()
override fun onDataSetChanged() = reload()
override fun onDestroy() { }
override fun getCount(): Int = commands.size
override fun getLoadingView(): RemoteViews? = null
override fun getViewTypeCount(): Int = 1
override fun getItemId(position: Int): Long = position.toLong()
override fun hasStableIds(): Boolean = true
override fun getViewAt(position: Int): RemoteViews {
val rv = RemoteViews(context.packageName, R.layout.mi_recent_commands_appwidget_item)
rv.setTextViewText(R.id.cmd_recent_app_widget_item, commands[position])
val fillInIntent = Intent()
fillInIntent.putExtra(EX_COMMAND, commands[position])
rv.setOnClickFillInIntent(R.id.cmd_recent_app_widget_item, fillInIntent)
return rv
}
}
}
| apache-2.0 | 26ecce20b80345995e2020c2a1c5b861 | 33.55102 | 125 | 0.6899 | 4.921512 | false | false | false | false |
codeka/weather | app/src/main/java/au/com/codeka/weather/location/LocationProvider.kt | 1 | 7343 | package au.com.codeka.weather.location
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.location.Criteria
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.Handler
import android.os.SystemClock
import android.util.Log
import androidx.core.app.ActivityCompat
import au.com.codeka.weather.DebugLog
import java.util.concurrent.TimeUnit
/**
* Provider for fetching our current location. We do some fancy tricks to ensure we don't query
* the expensive sensor too often.
*/
class LocationProvider(private val context: Context) {
interface LocationFetchedListener {
fun onLocationFetched(loc: Location)
}
private val locationManager: LocationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
private val prefs: SharedPreferences = context.getSharedPreferences("au.com.codeka.weather", Context.MODE_PRIVATE)
/** Gets your current location as a lat/long */
fun getLocation(force: Boolean, locationFetcherListener: LocationFetchedListener) {
val now = System.currentTimeMillis()
// we'll use the PASSIVE_PROVIDER most of the time, but occasionally use GPS_PROVIDER for
// more accurate updates.
val timeSinceLastGpsRequest = prefs.getLong("TimeSinceLastGpsRequest", 0)
var doGpsRequest = force
if (now - timeSinceLastGpsRequest > LOCATION_UPDATE_TIME_MS) {
doGpsRequest = true
}
if (doGpsRequest) {
prefs.edit().putLong("TimeSinceLastGpsRequest", now).apply()
}
val criteria = Criteria()
var provider: String = LocationManager.PASSIVE_PROVIDER
if (doGpsRequest) {
provider = locationManager.getBestProvider(criteria, true) ?: LocationManager.NETWORK_PROVIDER
}
val haveFineLocation = ActivityCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
val haveCoarseLocation = ActivityCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
if (!haveCoarseLocation || !haveFineLocation) {
// We'll only do this if we're called in the context of an activity. If it's the worker
// receiver calling us, then don't bother.
if (context is Activity) {
ActivityCompat.requestPermissions(context, arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
), 1)
}
DebugLog.current().log("No location permission, cannot get current location")
return
}
val myLocationListener = MyLocationListener(locationManager.getLastKnownLocation(provider))
if (myLocationListener.isLocationGoodEnough) {
// if lastKnownLocation is good enough, just use it.
locationFetcherListener.onLocationFetched(myLocationListener.bestLocation!!)
return
}
DebugLog.current().log("Using location provider: $provider")
if (provider == LocationManager.GPS_PROVIDER) {
// if we're getting GPS location, also listen for network locations in case we don't have
// GPS lock and we're inside or whatever.
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0f,
myLocationListener)
}
locationManager.requestLocationUpdates(provider, 0, 0f, myLocationListener)
// check back in 10 seconds for the best location we've received in that time.
DebugLog.current().log("Waiting for location fix.")
Handler().postDelayed(Runnable {
val loc = myLocationListener.bestLocation
try {
locationManager.removeUpdates(myLocationListener)
} catch (e: SecurityException) {
// Should never happen because we check for the permission above, but if we do get this,
// just ignore it.
return@Runnable
}
if (loc != null) {
locationFetcherListener.onLocationFetched(loc)
} else {
DebugLog.current().log("No location found after 10 seconds, giving up.")
}
}, 10000)
}
private inner class MyLocationListener(var bestLocation: Location?) : LocationListener {
val isLocationGoodEnough: Boolean
get() {
if (bestLocation == null) {
return false
}
val nanos = SystemClock.elapsedRealtimeNanos() - bestLocation!!.elapsedRealtimeNanos
return nanos < TimeUnit.MINUTES.toNanos(10)
}
override fun onLocationChanged(location: Location) {
if (isBetterLocation(location, bestLocation)) {
bestLocation = location
}
}
override fun onProviderDisabled(provider: String) {}
override fun onProviderEnabled(provider: String) {}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
/** Determines whether one Location reading is better than the current Location fix
* @param location The new Location that you want to evaluate
* @param currentBestLocation The current Location fix, to which you want to compare the new one
*/
private fun isBetterLocation(location: Location, currentBestLocation: Location?): Boolean {
if (currentBestLocation == null) {
// A new location is always better than no location
return true
}
// Check whether the new location fix is newer or older
val timeDelta = location.time - currentBestLocation.time
val isSignificantlyNewer = timeDelta > Companion.TWO_MINUTES
val isSignificantlyOlder = timeDelta < -Companion.TWO_MINUTES
val isNewer = timeDelta > 0
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
return false
}
// Check whether the new location fix is more or less accurate
val accuracyDelta = (location.accuracy - currentBestLocation.accuracy).toInt()
val isLessAccurate = accuracyDelta > 0
val isMoreAccurate = accuracyDelta < 0
val isSignificantlyLessAccurate = accuracyDelta > 200
// Check if the old and new location are from the same provider
val isFromSameProvider = isSameProvider(location.provider,
currentBestLocation.provider)
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true
} else if (isNewer && !isLessAccurate) {
return true
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true
}
return false
}
/** Checks whether two providers are the same */
private fun isSameProvider(provider1: String?, provider2: String?): Boolean {
return if (provider1 == null) {
provider2 == null
} else provider1 == provider2
}
}
companion object {
private const val TWO_MINUTES = 1000 * 60 * 2
private const val TAG = "codeka.weather"
private const val LOCATION_UPDATE_TIME_MS = 3 * 60 * 60 * 1000 // every 3 hours
.toLong()
}
} | apache-2.0 | c3b3086613fe8b95c6f55f5dfef9305d | 39.574586 | 118 | 0.710064 | 4.87907 | false | false | false | false |
alexmonthy/libdelorean-java | libdelorean/src/main/kotlin/ca/polymtl/dorsal/libdelorean/interval/StateInterval.kt | 2 | 1727 | /*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package ca.polymtl.dorsal.libdelorean.interval
import ca.polymtl.dorsal.libdelorean.exceptions.TimeRangeException
import ca.polymtl.dorsal.libdelorean.statevalue.StateValue
import com.google.common.base.MoreObjects
import java.util.*
open class StateInterval(val start: Long,
val end: Long,
val attribute: Int,
val stateValue: StateValue) {
init {
if (start > end) throw TimeRangeException("Start:$start, End:$end")
}
fun intersects(timestamp: Long) = ((start <= timestamp) && (timestamp <= end))
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as StateInterval
if (start != other.start) return false
if (end != other.end) return false
if (attribute != other.attribute) return false
if (stateValue != other.stateValue) return false
return true
}
override fun hashCode(): Int {
return Objects.hash(start, end, attribute, stateValue)
}
override fun toString(): String {
return MoreObjects.toStringHelper(this)
.add("start", start)
.add("end", end)
.add("attribute", attribute)
.add("value", stateValue.toString())
.toString()
}
} | epl-1.0 | 4cf9a3aeb73cffad9d062dc3d20018d9 | 29.857143 | 84 | 0.634627 | 4.28536 | false | false | false | false |
digammas/damas | solutions.digamma.damas.jcr/src/test/kotlin/solutions/digamma/damas/jcr/auth/JcrPermissionManagerTest.kt | 1 | 6821 | package solutions.digamma.damas.jcr.auth
import org.junit.After
import org.junit.Before
import org.junit.Test
import solutions.digamma.damas.auth.AccessRight
import solutions.digamma.damas.common.WorkspaceException
import solutions.digamma.damas.content.DocumentManager
import solutions.digamma.damas.content.FolderManager
import solutions.digamma.damas.jcr.Mocks
import solutions.digamma.damas.jcr.RepositoryTest
import solutions.digamma.damas.session.Token
import solutions.digamma.damas.user.GroupManager
import solutions.digamma.damas.user.UserManager
import java.util.Arrays
class JcrPermissionManagerTest: RepositoryTest() {
private val userManager = inject(UserManager::class.java)
private val groupManager = inject(GroupManager::class.java)
private val folderManager = inject(FolderManager::class.java)
private val documentManager = inject(DocumentManager::class.java)
private val manager = inject(JcrPermissionManager::class.java)
private lateinit var username: String
private lateinit var userToken: Token
private lateinit var folderId: String
private lateinit var subfolderId: String
private lateinit var docId: String
private lateinit var groupId: String
@Before
fun setUp() {
this.login()
val group = Mocks.group("testers")
this.groupId = this.groupManager.create(group).id
val user = Mocks.user("tester", Arrays.asList(this.groupId))
this.username = this.userManager.create(user).login
val password = "P@55w0rd"
this.userManager.updatePassword(this.username, password)
this.commit()
this.userToken = this.login.login(this.username, password)
val rootId = this.folderManager
.find("/").id
this.folderId = folderManager.create(
Mocks.folder(rootId, "folder")).id
this.subfolderId = folderManager.create(
Mocks.folder(folderId, "subfolder")).id
this.docId = documentManager.create(
Mocks.document(folderId, "doc-um.ent")).id
}
@After
fun tearDown() {
this.manager.delete(this.folderId, this.username)
this.folderManager.delete(this.folderId)
this.login.logout(this.userToken)
this.userManager.delete(this.username)
this.groupManager.delete(this.groupId)
this.logout()
}
@Test
fun retrieve() {
val permission = this.manager.retrieve(folderId, username)
assert(permission.accessRights == AccessRight.NONE) {
"Error retrieving permission."
}
}
@Test
fun update() {
this.use(this.userToken){
folderManager.retrieve(folderId)
assert(false) { "Expecting access rights denial." }
}
assert(manager.update(
Mocks.permission(folderId, username, AccessRight.READ)
).accessRights == AccessRight.READ) {
"Error creating permission."
}
this.use(this.userToken) {
folderManager.retrieve(folderId)
folderManager.update(folderId, Mocks.folder(null, "new_name"))
assert(false) { "Expecting access rights denial." }
}
assert(manager.update(
Mocks.permission(folderId, username, AccessRight.WRITE)
).accessRights == AccessRight.WRITE) { "Error updating permission." }
this.use(this.userToken) {
folderManager.update(folderId, Mocks.folder(null, "new_name"))
}
}
@Test
fun updateForGroup() {
this.use(this.userToken) {
folderManager.retrieve(folderId)
assert(false) { "Expecting access rights denial." }
}
assert(manager.update(
Mocks.permission(folderId, groupId, AccessRight.READ)
).accessRights == AccessRight.READ) { "Error creating permission." }
this.use(this.userToken) {
folderManager.retrieve(folderId)
folderManager.update(folderId, Mocks.folder(null, "new_name"))
assert(false) { "Expecting access rights denial." }
}
assert(manager.update(
Mocks.permission(folderId, groupId, AccessRight.WRITE)
).accessRights == AccessRight.WRITE) {
"Error updating permission."
}
this.use(this.userToken) {
folderManager.update(folderId, Mocks.folder(null, "new_name"))
}
}
@Test
fun updateRecursive() {
this.use(this.userToken) {
folderManager.retrieve(subfolderId)
assert(false) { "Expecting access rights denial." }
}
/* Try with no recursion */
manager.update(folderId, Arrays.asList(
Mocks.permission(null, username, AccessRight.READ)))
/* It won't work */
this.use(this.userToken) {
folderManager.retrieve(subfolderId)
assert(false) { "Expecting access rights denial." }
}
/* Grand access on folder, recursively */
manager.update(folderId, Arrays.asList(
Mocks.permission(null, username, AccessRight.READ)), true)
this.use(this.userToken) {
/* Also works on sub-folder */
folderManager.retrieve(subfolderId)
/* Not for write, yet */
folderManager.update(subfolderId, Mocks.folder(null, "new_name")
)
assert(false) { "Expecting access rights denial." }
}
/* Grant write access, recursively */
manager.update(folderId, Arrays.asList(
Mocks.permission(null, username, AccessRight.WRITE)), true)
this.use(this.userToken) {
/* And watch it apply to children */
folderManager.update(folderId, Mocks.folder(null, "new_name"))
}
/* Revoke all */
manager.update(folderId, Arrays.asList(
Mocks.permission(null, username, AccessRight.NONE)), true)
this.use(this.userToken) {
/* Back to square one */
folderManager.retrieve(subfolderId)
assert(false) { "Expecting access rights denial." }
}
}
@Test
fun delete() {
manager.update(Mocks.permission(folderId, username, AccessRight.READ))
this.use(this.userToken) {
folderManager.retrieve(folderId)
}
manager.delete(folderId, username)
this.use(this.userToken) {
folderManager.retrieve(folderId)
assert(false) { "Expecting access rights denial." }
}
}
private fun <R> use(token: Token, block: () -> R): R? {
this.authenticator.connect(token).use {
try {
return block()
} catch (_: WorkspaceException) {
return null
}
}
}
}
| mit | d56a9bd31e1e17729e37d31a496958d5 | 35.672043 | 78 | 0.621903 | 4.437866 | false | true | false | false |
vondear/RxTools | RxUI/src/main/java/com/tamsiree/rxui/view/colorpicker/CircleColorDrawable.kt | 1 | 1362 | package com.tamsiree.rxui.view.colorpicker
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.drawable.ColorDrawable
import com.tamsiree.rxui.view.colorpicker.builder.PaintBuilder
/**
* @author tamsiree
* @date 2018/6/11 11:36:40 整合修改
*/
class CircleColorDrawable : ColorDrawable {
private var strokeWidth = 0f
private val strokePaint = PaintBuilder.newPaint().style(Paint.Style.STROKE).stroke(strokeWidth).color(-0x1).build()
private val fillPaint = PaintBuilder.newPaint().style(Paint.Style.FILL).color(0).build()
private val fillBackPaint = PaintBuilder.newPaint().shader(PaintBuilder.createAlphaPatternShader(16)).build()
constructor() : super()
constructor(color: Int) : super(color)
override fun draw(canvas: Canvas) {
canvas.drawColor(0)
val width = canvas.width
val radius = width / 2f
strokeWidth = radius / 12f
strokePaint.strokeWidth = strokeWidth
fillPaint.color = color
canvas.drawCircle(radius, radius, radius - strokeWidth * 1.5f, fillBackPaint)
canvas.drawCircle(radius, radius, radius - strokeWidth * 1.5f, fillPaint)
canvas.drawCircle(radius, radius, radius - strokeWidth, strokePaint)
}
override fun setColor(color: Int) {
super.setColor(color)
invalidateSelf()
}
} | apache-2.0 | 4bf20bd6042f7dc575b91a0cc8e8e2ac | 35.621622 | 119 | 0.711226 | 4.10303 | false | false | false | false |
stripe/stripe-android | identity/src/main/java/com/stripe/android/identity/networking/IdentityHeaderFactory.kt | 1 | 1694 | package com.stripe.android.identity.networking
import com.stripe.android.core.networking.ApiRequest
import com.stripe.android.core.networking.HEADER_CONTENT_TYPE
import com.stripe.android.core.networking.RequestHeadersFactory
import com.stripe.android.core.networking.StripeRequest
/**
* Factory to to create headers for Identity requests.
* Encapsulates a [RequestHeadersFactory.BaseApiHeadersFactory] instance to mutable ephemeral key
* attached each time.
*/
internal object IdentityHeaderFactory {
// Mutable internal instances to change the ephemeralKeys attached to header.
private var ephemeralKey: String? = null
set(value) {
field = value
apiOptions = ApiRequest.Options(
apiKey = requireNotNull(value),
stripeAccount = null,
idempotencyKey = null
)
}
private var apiOptions: ApiRequest.Options? = null
private val baseApiHeaderFactory = object : RequestHeadersFactory.BaseApiHeadersFactory(
optionsProvider = { requireNotNull(apiOptions) },
apiVersion = IDENTITY_STRIPE_API_VERSION_WITH_BETA_HEADER
) {
override var postHeaders = mapOf(
HEADER_CONTENT_TYPE to StripeRequest.MimeType.Form.toString()
)
}
/**
* Create header with [ephemeralKey] attached as Bearer token.
*/
fun createHeaderWithEphemeralKey(ephemeralKey: String): Map<String, String> {
this.ephemeralKey = ephemeralKey
return baseApiHeaderFactory.create()
}
/**
* Create post header with multipart/form-data.
*/
fun createPostHeader() =
baseApiHeaderFactory.createPostHeader()
}
| mit | 29325e42e35fd8877135a22b2f1ef8fb | 34.291667 | 97 | 0.693625 | 4.705556 | false | false | false | false |
Xenoage/Zong | utils-kotlin/src/com/xenoage/utils/collections/SortedList.kt | 1 | 3877 | package com.xenoage.utils.collections
import kotlin.properties.Delegates
/**
* Mutable sorted list.
* The list may contain duplicate entries or not.
*/
class SortedList<T : Comparable<T>> private constructor(
val list: MutableList<T> = mutableListOf(),
/** True, when this list may contain duplicates. When false,
* duplicate entries are removed. */
val duplicates: Boolean = true
) : List<T> by list {
/**
* Creates a new sorted list from presorted elements.
* If they are not sorted, an [IllegalArgumentException] is thown.
*-/
constructor(entries: Array<T>, duplicates: Boolean) {
this.duplicates = duplicates
listOf<>()
var last: T? = null
for (e in entries) {
if (last != null) {
if (duplicates && last.compareTo(e) > 0 || !duplicates && last.compareTo(e) >= 0) {
throw IllegalArgumentException("Elements are not presorted!")
}
}
linkedList.addLast(e)
last = e
}
}
/**
* Merges this list with the given list and returns the result.
*/
fun merge(sortedList: SortedList<T>, duplicates: Boolean): SortedList<T> {
val ret = SortedList<T>(duplicates)
val l1 = this.linkedList.iterator()
val l2 = sortedList.linkedList.iterator()
var e1 = if (l1.hasNext()) l1.next() else null
var e2 = if (l2.hasNext()) l2.next() else null
while (e1 != null || e2 != null) {
if (e1 == null)
//l1 queue is empty
{
ret.addLast(e2)
e2 = if (l2.hasNext()) l2.next() else null
} else if (e2 == null)
//l2 queue is empty
{
ret.addLast(e1)
e1 = if (l1.hasNext()) l1.next() else null
} else {
//both queues are non-empty, choose the lower one
if (e1!!.compareTo(e2) <= 0) {
//e1 first
ret.addLast(e1)
e1 = if (l1.hasNext()) l1.next() else null
} else {
//e2 first
ret.addLast(e2)
e2 = if (l2.hasNext()) l2.next() else null
}
}
}
return ret
} */
/** Merges the given list into this list. */
fun addAll(sortedList: SortedList<T>) {
sortedList.forEach { add(it) }
}
/**
* Adds the given entry at the correct position.
* If duplicates are not allowed but the given entry is a duplicate,
* it is not inserted.
*
* Runtime: O(n)
*/
fun add(entry: T) = add(entry, false)
/**
* Adds the given entry at the correct position.
* If duplicates are not allowed but the given entry is a duplicate,
* it is not replaced.
*
* Runtime: O(n)
*/
fun addOrReplace(entry: T) = add(entry, true)
/**
* Adds the given entry at the correct position.
* If duplicates are not allowed but the given entry is a duplicate,
* it is not inserted if `replace` is false, otherwise
* it is replaced.
*
* Runtime: O(n)
*/
private fun add(entry: T, replace: Boolean) {
for (i in indices) {
if (this[i] > entry) {
//add before this entry
list.add(i, entry)
return
}
else if (this[i] == entry) {
if (replace)
list[i] = entry
else if (duplicates)
list.add(i, entry)
return
}
}
list.add(entry)
}
companion object {
operator fun <T : Comparable<T>> invoke(duplicates: Boolean = true) =
SortedList<T>(mutableListOf<T>(), duplicates = duplicates)
operator fun <T : Comparable<T>> invoke(duplicates: Boolean = true, vararg initialValues: T): SortedList<T> {
val ret = SortedList<T>(duplicates = duplicates)
initialValues.forEach { ret.add(it) }
return ret
}
}
}
fun <T : Comparable<T>> sortedListOf(vararg items: T): SortedList<T> {
val ret = SortedList<T>()
items.forEach { ret.add(it) }
return ret;
}
fun <T : Comparable<T>> sortedListOf(items: Collection<T>): SortedList<T> {
val ret = SortedList<T>()
items.forEach { ret.add(it) }
return ret;
}
//TEST
class Positive(value: Int) {
var value: Int by Delegates.vetoable(0) { prop, old, new -> new > old }
}
fun main(vararg args: String) {
val n = Positive(5)
println(n.value)
}
| agpl-3.0 | d489979af4a4a03874444281ad8ae648 | 23.694268 | 111 | 0.635801 | 3.109062 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/SequenceInsert.kt | 1 | 3521 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations
import org.nd4j.autodiff.samediff.SDVariable
import org.nd4j.autodiff.samediff.SameDiff
import org.nd4j.autodiff.samediff.internal.SameDiffOp
import org.nd4j.linalg.api.ops.impl.shape.tensorops.TensorArray
import org.nd4j.samediff.frameworkimport.ImportGraph
import org.nd4j.samediff.frameworkimport.hooks.PreImportHook
import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule
import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
/**
* A port of sequence_insert.py from onnx tensorflow for samediff:
* https://github.com/onnx/onnx-tensorflow/blob/master/onnx_tf/handlers/backend/sequence_insert.py
*
* @author Adam Gibson
*/
@PreHookRule(nodeNames = [],opNames = ["SequenceInsert"],frameworkName = "onnx")
class SequenceInsert : PreImportHook {
override fun doImport(
sd: SameDiff,
attributes: Map<String, Any>,
outputNames: List<String>,
op: SameDiffOp,
mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>,
importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>,
dynamicVariables: Map<String, GeneratedMessageV3>
): Map<String, List<SDVariable>> {
val input = sd.getVariable(op.inputsToOp[0])
val tensorToInsert = sd.getVariable(op.inputsToOp[1])
val position = if(op.inputsToOp.size < 3) sd.constant(-1) else {
sd.getVariable(op.inputsToOp[2])
}
val tensorArrayOp = sd.tensorArray(input)
val written = tensorArrayOp.write(input,position,tensorToInsert)
written.addControlDependency(position)
written.addControlDependency(input)
var outputVars = written
outputVars = sd.updateVariableNameAndReference(outputVars,outputNames[0])
val ret = mutableMapOf<String,List<SDVariable>>()
ret[outputNames[0]] = listOf(outputVars)
return ret
}
fun checkPositionInBounds(sd: SameDiff,inputSequence: SDVariable,position: SDVariable): SDVariable {
val seqLength = inputSequence.shape().prod(0).castTo(position.dataType())
val cond1 = sd.gte(position,sd.math().neg(seqLength))
val cond2 = sd.lte(position,seqLength)
return sd.all(sd.bitwise().and(cond1,cond2),0)
}
} | apache-2.0 | aa7c198b5c47f3af9b5669eaa5140ef7 | 44.74026 | 184 | 0.704629 | 4.137485 | false | false | false | false |
noud02/Akatsuki | src/main/kotlin/moe/kyubey/akatsuki/commands/Danbooru.kt | 1 | 3254 | /*
* Copyright (c) 2017-2019 Yui
*
* 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 moe.kyubey.akatsuki.commands
import io.sentry.Sentry
import moe.kyubey.akatsuki.annotations.Argument
import moe.kyubey.akatsuki.annotations.Load
import moe.kyubey.akatsuki.entities.Command
import moe.kyubey.akatsuki.entities.Context
import moe.kyubey.akatsuki.utils.Http
import moe.kyubey.akatsuki.utils.I18n
import net.dv8tion.jda.core.EmbedBuilder
import okhttp3.HttpUrl
import org.json.JSONArray
@Load
@Argument("tags", "string")
class Danbooru : Command() {
override val desc = "Search for images on danbooru."
override val nsfw = true
override fun run(ctx: Context) {
val query = ctx.args["tags"] as String
if (query.indexOf("loli") > -1) {
return ctx.send(I18n.parse(ctx.lang.getString("loli_is_illegal"), mapOf("username" to ctx.author.name)))
}
Http.get(HttpUrl.Builder().apply {
scheme("https")
host("danbooru.donmai.us")
addPathSegment("posts.json")
addQueryParameter("limit", "100")
addQueryParameter("random", "true")
addQueryParameter("tags", query)
}.build()).thenAccept { res ->
val jsonArr = JSONArray(res.body()!!.string())
if (jsonArr.count() == 0)
return@thenAccept ctx.send(I18n.parse(ctx.lang.getString("no_images_found"), mapOf("username" to ctx.author.name)))
val json = jsonArr.getJSONObject(Math.floor(Math.random() * jsonArr.count()).toInt())
if (json.getString("tag_string").indexOf("loli") > -1) {
return@thenAccept ctx.send(I18n.parse(ctx.lang.getString("loli_is_illegal"), mapOf("username" to ctx.author.name)))
}
val embed = EmbedBuilder().apply {
setImage("https://danbooru.donmai.us${json.getString("file_url")}")
}
ctx.send(embed.build())
res.close()
}.thenApply {}.exceptionally {
ctx.logger.error("Error while trying to get post from danbooru", it)
ctx.sendError(it)
Sentry.capture(it)
}
}
} | mit | c03de52cd15dc7bca6fb43b6e0bbd043 | 38.216867 | 131 | 0.660418 | 4.02225 | false | false | false | false |
noud02/Akatsuki | src/main/kotlin/moe/kyubey/akatsuki/commands/Mute.kt | 1 | 3981 | /*
* Copyright (c) 2017-2019 Yui
*
* 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 moe.kyubey.akatsuki.commands
import moe.kyubey.akatsuki.annotations.Argument
import moe.kyubey.akatsuki.annotations.Arguments
import moe.kyubey.akatsuki.annotations.Load
import moe.kyubey.akatsuki.annotations.Perm
import moe.kyubey.akatsuki.entities.Command
import moe.kyubey.akatsuki.entities.Context
import moe.kyubey.akatsuki.utils.I18n
import net.dv8tion.jda.core.Permission
import net.dv8tion.jda.core.entities.Member
import net.dv8tion.jda.core.exceptions.PermissionException
@Load
@Perm(Permission.KICK_MEMBERS)
@Arguments(
Argument("user", "user"),
Argument("reason", "string", true)
)
class Mute : Command() {
override val guildOnly = true
override val desc = "Mute people."
override fun run(ctx: Context) {
if (ctx.storedGuild!!.mutedRole == null) {
return ctx.send(
I18n.parse(
ctx.lang.getString("no_muted_role"),
mapOf(
"username" to ctx.author.name
)
)
)
}
val user = ctx.args["user"] as Member
val role = ctx.guild!!.getRoleById(ctx.storedGuild.mutedRole!!)
?: return ctx.send(
I18n.parse(
ctx.lang.getString("muted_role_deleted"),
mapOf(
"username" to ctx.author.name
)
)
)
ctx.guild.controller
.addSingleRoleToMember(user, role)
.reason("[ ${ctx.author.name}#${ctx.author.discriminator} ] ${ctx.args.getOrDefault("reason", "none")}")
.queue({
ctx.send(
I18n.parse(
ctx.lang.getString("muted_user"),
mapOf(
"username" to user.user.name
)
)
)
}) {
if (it is PermissionException) {
ctx.send(
I18n.parse(
ctx.lang.getString("perm_cant_mute"),
mapOf(
"username" to user.user.name,
"permission" to I18n.permission(ctx.lang, it.permission.name)
)
)
)
} else {
ctx.sendError(it)
}
}
}
} | mit | baca28b0a677410f1f3eabad7f9342be | 38.82 | 120 | 0.5157 | 4.982478 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/hints/parameter/RsAsyncParameterInfoHandler.kt | 3 | 2843 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.hints.parameter
import com.intellij.lang.parameterInfo.CreateParameterInfoContext
import com.intellij.lang.parameterInfo.ParameterInfoHandler
import com.intellij.lang.parameterInfo.UpdateParameterInfoContext
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ReadAction
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.util.concurrency.AppExecutorUtil
import org.rust.lang.core.psi.ext.startOffset
import org.rust.openapiext.isUnitTestMode
import java.util.concurrent.Callable
import java.util.concurrent.Executor
/**
* This is a hack to make [ParameterInfoHandler] asynchronous. Usual [ParameterInfoHandler] is called from the EDT
* and so complex computations inside it (e.g. name resolution) can freeze the UI.
*/
abstract class RsAsyncParameterInfoHandler<ParameterOwner : PsiElement, ParameterType : Any>
: ParameterInfoHandler<ParameterOwner, ParameterType> {
abstract fun findTargetElement(file: PsiFile, offset: Int): ParameterOwner?
/**
* Ran in background thread
*/
abstract fun calculateParameterInfo(element: ParameterOwner): Array<ParameterType>?
final override fun findElementForParameterInfo(context: CreateParameterInfoContext): ParameterOwner? {
val element = findTargetElement(context.file, context.offset) ?: return null
return if (isUnitTestMode) {
context.itemsToShow = calculateParameterInfo(element) ?: return null
element
} else {
ReadAction.nonBlocking(Callable {
calculateParameterInfo(element)
}).finishOnUiThread(ModalityState.defaultModalityState()) { paramInfo ->
if (paramInfo != null) {
context.itemsToShow = paramInfo
showParameterInfo(element, context)
}
}.expireWhen { !element.isValid }.submit(executor)
null
}
}
final override fun findElementForUpdatingParameterInfo(context: UpdateParameterInfoContext): ParameterOwner? {
return findTargetElement(context.file, context.offset)
}
/**
* This method is not called by the platform b/c we always return null from [findElementForParameterInfo].
* We call it manually from [findElementForParameterInfo] and from unit tests.
*/
override fun showParameterInfo(element: ParameterOwner, context: CreateParameterInfoContext) {
context.showHint(element, element.startOffset, this)
}
private companion object {
private val executor: Executor =
AppExecutorUtil.createBoundedApplicationPoolExecutor("Rust async parameter info handler", 1)
}
}
| mit | 971da83806d8c2eca084388d9feb3fc4 | 39.042254 | 114 | 0.728456 | 5.113309 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.