repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
openhab/openhab.android | mobile/src/full/java/org/openhab/habdroid/core/CloudMessagingHelper.kt | 1 | 5365 | /*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.core
import android.content.Context
import android.content.Intent
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import org.openhab.habdroid.R
import org.openhab.habdroid.core.connection.CloudConnection
import org.openhab.habdroid.core.connection.ConnectionFactory
import org.openhab.habdroid.core.connection.NotACloudServerException
import org.openhab.habdroid.ui.PushNotificationStatus
import org.openhab.habdroid.util.HttpClient
import org.openhab.habdroid.util.getHumanReadableErrorMessage
import org.openhab.habdroid.util.getPrefs
import org.openhab.habdroid.util.getPrimaryServerId
import org.openhab.habdroid.util.getRemoteUrl
object CloudMessagingHelper {
internal var registrationDone: Boolean = false
internal var registrationFailureReason: Throwable? = null
private val TAG = CloudMessagingHelper::class.java.simpleName
fun onConnectionUpdated(context: Context, connection: CloudConnection?) {
registrationDone = false
if (connection != null) {
FcmRegistrationWorker.scheduleRegistration(context)
}
}
fun onNotificationSelected(context: Context, intent: Intent) {
val notificationId = intent.getIntExtra(
NotificationHelper.EXTRA_NOTIFICATION_ID, -1)
if (notificationId >= 0) {
FcmRegistrationWorker.scheduleHideNotification(context, notificationId)
}
}
fun isPollingBuild() = false
fun needsPollingForNotifications(@Suppress("UNUSED_PARAMETER") context: Context) = false
fun pollForNotifications(@Suppress("UNUSED_PARAMETER") context: Context) {
// Used in foss flavor
}
suspend fun getPushNotificationStatus(context: Context): PushNotificationStatus {
ConnectionFactory.waitForInitialization()
val prefs = context.getPrefs()
val cloudFailure = ConnectionFactory.primaryCloudConnection?.failureReason
return when {
// No remote server is configured
prefs.getRemoteUrl(prefs.getPrimaryServerId()).isEmpty() ->
PushNotificationStatus(
context.getString(R.string.push_notification_status_no_remote_configured),
R.drawable.ic_bell_off_outline_grey_24dp,
false
)
// Cloud connection failed
cloudFailure != null && cloudFailure !is NotACloudServerException -> {
val message = context.getString(R.string.push_notification_status_http_error,
context.getHumanReadableErrorMessage(
if (cloudFailure is HttpClient.HttpException) cloudFailure.originalUrl else "",
if (cloudFailure is HttpClient.HttpException) cloudFailure.statusCode else 0,
cloudFailure,
true
)
)
PushNotificationStatus(message, R.drawable.ic_bell_off_outline_grey_24dp, true)
}
// Remote server is configured, but it's not a cloud instance
ConnectionFactory.primaryCloudConnection?.connection == null && ConnectionFactory.primaryRemoteConnection != null ->
PushNotificationStatus(
context.getString(R.string.push_notification_status_remote_no_cloud),
R.drawable.ic_bell_off_outline_grey_24dp,
false
)
// Registration isn't done yet
!registrationDone ->
PushNotificationStatus(
context.getString(R.string.info_openhab_gcm_in_progress),
R.drawable.ic_bell_outline_grey_24dp,
false
)
// Registration failed
registrationFailureReason != null -> {
val gaa = GoogleApiAvailability.getInstance()
val errorCode = gaa.isGooglePlayServicesAvailable(context)
if (errorCode != ConnectionResult.SUCCESS) {
val message = context.getString(
R.string.info_openhab_gcm_failed_play_services,
gaa.getErrorString(errorCode)
)
PushNotificationStatus(message, R.drawable.ic_bell_off_outline_grey_24dp, true)
} else {
PushNotificationStatus(
context.getString(R.string.info_openhab_gcm_failed),
R.drawable.ic_bell_off_outline_grey_24dp,
true
)
}
}
// Push notifications are working
else ->
PushNotificationStatus(
context.getString(R.string.info_openhab_gcm_connected),
R.drawable.ic_bell_ring_outline_grey_24dp,
false
)
}
}
}
| epl-1.0 | ce48e84db932ca9a70e51448490cf86c | 42.266129 | 128 | 0.629264 | 5.203686 | false | false | false | false |
tipsy/javalin | javalin/src/main/java/io/javalin/http/JavalinServletHandler.kt | 1 | 8142 | package io.javalin.http
import io.javalin.core.JavalinConfig
import io.javalin.core.util.LogUtil
import java.io.InputStream
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletableFuture.completedFuture
import java.util.concurrent.atomic.AtomicBoolean
import java.util.function.Consumer
import javax.servlet.AsyncContext
import javax.servlet.AsyncEvent
import javax.servlet.AsyncListener
interface StageName
enum class DefaultName : StageName { BEFORE, HTTP, ERROR, AFTER }
data class Stage(
val name: StageName,
val haltsOnError: Boolean = true, // tasks in this scope should be executed even if some previous stage ended up with exception
val initializer: StageInitializer // DSL method to add task to the stage's queue
)
internal data class Result(
val previous: InputStream? = null,
val future: CompletableFuture<*> = completedFuture(null),
val callback: Consumer<Any?>? = null,
)
internal data class Task(
val stage: Stage,
val handler: TaskHandler
)
typealias TaskHandler = (JavalinServletHandler) -> Unit
typealias SubmitTask = (TaskHandler) -> Unit
typealias StageInitializer = JavalinServletHandler.(submitTask: SubmitTask) -> Unit
/**
* Executes request lifecycle.
* The lifecycle consists of multiple [stages] (before/http/etc), each of which
* can have one or more [tasks]. The default lifecycle is defined in [JavalinServlet].
* [JavalinServletHandler] is called only once per request, and has a mutable state.
*/
class JavalinServletHandler(
private val stages: ArrayDeque<Stage>,
private val config: JavalinConfig,
private val errorMapper: ErrorMapper,
private val exceptionMapper: ExceptionMapper,
val ctx: Context,
val requestType: HandlerType = HandlerType.fromServletRequest(ctx.req),
val requestUri: String = ctx.req.requestURI.removePrefix(ctx.req.contextPath),
) {
/** Queue of tasks to execute within the current [Stage] */
private val tasks = ArrayDeque<Task>(4)
/** Future representing currently queued task */
private var currentTaskFuture: CompletableFuture<InputStream?> = completedFuture(null)
/** InputStream representing previous result */
private var previousResult: InputStream? = null
/** Indicates if exception occurred during execution of a tasks chain */
private var errored = false
/** Indicates if [JavalinServletHandler] already wrote response to client, requires support for atomic switch */
private val finished = AtomicBoolean(false)
/**
* This method starts execution process of all stages in a given lifecycle.
* Execution is based on recursive calls of this method,
* because we need a lazy evaluation of next tasks in a chain to support multiple concurrent stages.
*/
internal fun queueNextTaskOrFinish() {
while (tasks.isEmpty() && stages.isNotEmpty()) { // refill tasks from next stage, if the current queue is empty
val stage = stages.poll()
stage.initializer.invoke(this) { taskHandler -> tasks.offer(Task(stage, taskHandler)) } // add tasks from stage to task queue
}
if (tasks.isEmpty())
finishResponse() // we looked but didn't find any more tasks, time to write the response
else
currentTaskFuture = currentTaskFuture
.thenAccept { inputStream -> previousResult = inputStream }
.thenCompose { executeNextTask() } // chain next task into current future
.exceptionally { throwable -> exceptionMapper.handleUnexpectedThrowable(ctx.res, throwable) } // default catch-all for whole scope, might occur when e.g. finishResponse() will fail
}
/** Executes the given task with proper error handling and returns next task to execute as future */
private fun executeNextTask(): CompletableFuture<InputStream> {
val task = tasks.poll()
if (errored && task.stage.haltsOnError) {
queueNextTaskOrFinish() // each subsequent task for this stage will be queued and skipped
return completedFuture(previousResult)
}
val wasAsync = ctx.isAsync() // necessary to detect if user called startAsync() manually
try {
/** run code added through submitTask in [JavalinServlet]. This mutates [ctx] */
task.handler(this)
} catch (exception: Exception) {
errored = true
ctx.resultReference.getAndSet(Result(previousResult)).future.cancel(true)
exceptionMapper.handle(exception, ctx)
}
return ctx.resultReference.getAndSet(Result(previousResult))
.let { result ->
when { // we need to check if the user has called startAsync manually, and keep the connection open if so
ctx.isAsync() && !wasAsync -> result.copy(future = CompletableFuture<Void>()) // GH-1560: freeze JavalinServletHandler infinitely, TODO: Remove it in Javalin 5.x
else -> result
}
}
.also { result -> if (!ctx.isAsync() && !result.future.isDone) startAsyncAndAddDefaultTimeoutListeners() } // start async context only if the future is not already completed
.also { result -> if (ctx.isAsync()) ctx.req.asyncContext.addListener(onTimeout = { result.future.cancel(true) }) }
.let { result ->
result.future
.thenAccept { any -> (result.callback?.accept(any) ?: ctx.contextResolver().defaultFutureCallback(ctx, any)) } // callback after future resolves - modifies ctx result, status, etc
.thenApply { ctx.resultStream() ?: previousResult } // set value of future to be resultStream (or previous stream)
.exceptionally { throwable -> exceptionMapper.handleFutureException(ctx, throwable) } // standard exception handler
.thenApply { inputStream -> inputStream.also { queueNextTaskOrFinish() } } // we have to attach the "also" to the input stream to avoid mapping a void
}
}
private fun startAsyncAndAddDefaultTimeoutListeners() = ctx.req.startAsync()
.addListener(onTimeout = { // a timeout avoids the pipeline - we need to handle it manually
currentTaskFuture.cancel(true) // cancel current task
ctx.status(500).result("Request timed out") // default error handling
errorMapper.handle(ctx.status(), ctx) // user defined error handling
finishResponse() // write response
})
.also { asyncCtx -> asyncCtx.timeout = config.asyncRequestTimeout }
/** Writes response to the client and frees resources */
private fun finishResponse() {
if (finished.getAndSet(true)) return // prevent writing more than once (ex. both async requests+errors) [it's required because timeout listener can terminate the flow at any tim]
try {
JavalinResponseWrapper(ctx, config, requestType).write(ctx.resultStream())
config.inner.requestLogger?.handle(ctx, LogUtil.executionTimeMs(ctx))
} catch (throwable: Throwable) {
exceptionMapper.handleUnexpectedThrowable(ctx.res, throwable) // handle any unexpected error, e.g. write failure
} finally {
if (ctx.isAsync()) ctx.req.asyncContext.complete() // guarantee completion of async context to eliminate the possibility of hanging connections
}
}
}
/** Checks if request is executed asynchronously */
private fun Context.isAsync(): Boolean = req.isAsyncStarted
internal fun AsyncContext.addListener(
onComplete: (AsyncEvent) -> Unit = {},
onError: (AsyncEvent) -> Unit = {},
onStartAsync: (AsyncEvent) -> Unit = {},
onTimeout: (AsyncEvent) -> Unit = {},
) : AsyncContext = apply {
addListener(object : AsyncListener {
override fun onComplete(event: AsyncEvent) = onComplete(event)
override fun onError(event: AsyncEvent) = onError(event)
override fun onStartAsync(event: AsyncEvent) = onStartAsync(event)
override fun onTimeout(event: AsyncEvent) = onTimeout(event)
})
}
| apache-2.0 | 580fd534be2a903be6bf2997a41d788c | 49.259259 | 199 | 0.687792 | 4.829181 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/editor/LatexParagraphFillHandler.kt | 1 | 6720 | package nl.hannahsten.texifyidea.editor
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.editorActions.fillParagraph.ParagraphFillHandler
import com.intellij.formatting.FormatterTagHandler
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.util.EditorFacade
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.UnfairTextRange
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.nextLeaf
import com.intellij.psi.util.prevLeaf
import com.intellij.refactoring.suggested.startOffset
import nl.hannahsten.texifyidea.file.LatexFile
import nl.hannahsten.texifyidea.psi.LatexBeginCommand
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.psi.LatexDisplayMath
import nl.hannahsten.texifyidea.psi.LatexEndCommand
import nl.hannahsten.texifyidea.util.endOffset
import nl.hannahsten.texifyidea.util.hasParent
import nl.hannahsten.texifyidea.util.magic.CommandMagic
import nl.hannahsten.texifyidea.util.parentOfType
/**
* Implements the paragraph fill handler action.
*
* @author Abby Berkers
*/
class LatexParagraphFillHandler : ParagraphFillHandler() {
override fun isAvailableForFile(psiFile: PsiFile?): Boolean {
return psiFile is LatexFile
}
/**
* Given the leaf [element] at the caret at the time of invoking the fill paragraph action, replace the text of the
* current paragraph with the same text such that the new text fills the editor evenly.
*
* Based on the super implementation, which wasn't custom enough. We now have finer control over when an element ends.
*/
override fun performOnElement(element: PsiElement, editor: Editor) {
val document = editor.document
val (textRange, preFix, postFix) = getParagraphTextRange(element)
if (textRange.isEmpty) return
val text = textRange.substring(element.containingFile.text)
val subStrings = StringUtil.split(text, "\n", true)
// Join the paragraph text to a single line, so it can be wrapped later.
val replacementText = preFix + subStrings.joinToString(" ") { it.trim() } + postFix
CommandProcessor.getInstance().executeCommand(element.project, {
document.replaceString(
textRange.startOffset, textRange.endOffset,
replacementText
)
val file = element.containingFile
val formatterTagHandler = FormatterTagHandler(CodeStyle.getSettings(file))
val enabledRanges = formatterTagHandler.getEnabledRanges(file.node, TextRange.create(0, document.textLength))
// Deprecated ("a temporary solution") but there doesn't seem anything to replace it yet. Used all over by IJ as well.
EditorFacade.getInstance().doWrapLongLinesIfNecessary(
editor, element.project, document,
textRange.startOffset,
textRange.startOffset + replacementText.length + 1,
enabledRanges,
CodeStyle.getSettings(file).getRightMargin(element.language)
)
}, null, document)
}
/**
* Get the text range of the paragraph of the current element, along with a prefix and postfix.
*
* Note that these paragraphs are different from the paragraphs as outputted by TeX. The paragraphs we are dealing
* with here are the walls of text as they appear in the editor. E.g., these paragraphs are separated by a display
* math environment, while for TeX a display math environment is part of the paragraph.
*/
private fun getParagraphTextRange(element: PsiElement): Triple<TextRange, String, String> {
// The final element of the paragraph.
var endElement = element
// The last element is the last element we checked. At the end the last element will be the first element that
// is not part of the current paragraph.
var lastElement = element.nextLeaf(true)
while (lastElement != null && !separatesParagraph(lastElement)) {
endElement = lastElement
lastElement = lastElement.nextLeaf(true)
}
val postFix = if (endElement.isPostOrPreFix()) endElement.text else ""
// The first element of the paragraph.
var startElement = element
// The last element that we checked. At the end the first element will be the last element that is not part of
// the current paragraph, i.e., the paragraph starts at the next element after firstElement.
var firstElement = element.prevLeaf(true)
while (firstElement != null && !separatesParagraph(firstElement)) {
startElement = firstElement
firstElement = firstElement.prevLeaf(true)
}
val preFix = if (startElement.isPostOrPreFix()) startElement.text else ""
return Triple(UnfairTextRange(startElement.startOffset, endElement.endOffset()), preFix, postFix)
}
/**
* A paragraph ends when we encounter
* - multiple new lines, or
* - the begin of an environment (display math counts for this as well, inline math does not), or
* - the end of the file.
* In that case the current element is the first element that is not part of the paragraph anymore. If the last
* element before the current element is a white space, that white space is still part of the paragraph.
*/
private fun separatesParagraph(element: PsiElement): Boolean {
return when {
element is PsiWhiteSpace -> element.text.count { it == '\n' } >= 2
element.hasParent(LatexBeginCommand::class) -> true
element.hasParent(LatexEndCommand::class) -> true
element.hasParent(LatexDisplayMath::class) -> true
element.hasParent(LatexCommands::class) -> {
CommandMagic.sectionMarkers.contains(element.parentOfType(LatexCommands::class)?.commandToken?.text)
}
else -> false
}
}
/**
* If the first or last element of a paragraph is a white space, this white space should be preserved.
*
* For example, when the paragraph is ended by an environment, the `\begin{env}` is the element that separates this
* paragraph. The last element of the paragraph then is the new line before the `\begin{env}`. White spaces are
* trimmed when creating the replacement text, but this white space should be preserved.
*/
private fun PsiElement.isPostOrPreFix() = this is PsiWhiteSpace
} | mit | 8c71b5d9a24b23227fc9ef256c8b4829 | 48.058394 | 130 | 0.70625 | 4.824121 | false | false | false | false |
RoverPlatform/rover-android | core/src/main/kotlin/io/rover/sdk/core/platform/DeviceName.kt | 1 | 66406 | /*
* Copyright (C) 2017 Jared Rummler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.rover.sdk.core.platform
import android.os.Build
/**
* Uses Jared Rummler's library to get the marketing/consumer name of the device. Otherwise,
* returns [Build.MODEL].
*/
fun getDeviceName(): String {
return getDeviceName(Build.DEVICE, Build.MODEL, Build.MODEL.capitalize())
}
/**
* Get the consumer friendly name of a device.
*
* Borrowed from https://github.com/jaredrummler/AndroidDeviceNames by Jared Rummler.
*
* (getDeviceName() method copied, specifically, and transformed into Kotlin)
*
* @param codename
* the value of the system property "ro.product.device" ([Build.DEVICE]).
* @param model
* the value of the system property "ro.product.model" ([Build.MODEL]).
* @param fallback
* the fallback name if the device is unknown. Usually the value of the system property
* "ro.product.model" ([Build.MODEL])
* @return the market name of a device or `fallback` if the device is unknown.
*/
fun getDeviceName(codename: String?, model: String?, fallback: String): String {
// ----------------------------------------------------------------------------
// Acer
if (codename != null && codename == "acer_S57" || model != null && model == "S57") {
return "Liquid Jade Z"
}
if (codename != null && codename == "acer_t08" || model != null && model == "T08") {
return "Liquid Zest Plus"
}
// ----------------------------------------------------------------------------
// Asus
if (codename != null && (codename == "grouper" || codename == "tilapia")) {
return "Nexus 7 (2012)"
}
if (codename != null && (codename == "deb" || codename == "flo")) {
return "Nexus 7 (2013)"
}
// ----------------------------------------------------------------------------
// Google
if (codename != null && codename == "sailfish") {
return "Pixel"
}
if (codename != null && codename == "marlin") {
return "Pixel XL"
}
if (codename != null && codename == "dragon") {
return "Pixel C"
}
if (codename != null && codename == "walleye") {
return "Pixel 2"
}
if (codename != null && codename == "taimen") {
return "Pixel 2 XL"
}
if (codename != null && codename == "blueline") {
return "Pixel 3"
}
if (codename != null && codename == "crosshatch") {
return "Pixel 3 XL"
}
if (codename != null && codename == "sargo") {
return "Pixel 3a"
}
if (codename != null && codename == "bonito") {
return "Pixel 3a XL"
}
if (codename != null && codename == "flame") {
return "Pixel 4"
}
if (codename != null && codename == "coral") {
return "Pixel 4 XL"
}
if (codename != null && codename == "flounder") {
return "Nexus 9"
}
// ----------------------------------------------------------------------------
// Huawei
if (codename != null && codename == "HWBND-H"
|| model != null && (model == "BND-L21" || model == "BND-L24" || model == "BND-L31")
) {
return "Honor 7X"
}
if (codename != null && codename == "HWBKL"
|| model != null && (model == "BKL-L04" || model == "BKL-L09")
) {
return "Honor View 10"
}
if (codename != null && codename == "HWALP"
|| model != null && (model == "ALP-AL00" || model == "ALP-L09" || model == "ALP-L29" ||
model == "ALP-TL00")
) {
return "Mate 10"
}
if (codename != null && codename == "HWMHA"
|| model != null && (model == "MHA-AL00" || model == "MHA-L09" || model == "MHA-L29" ||
model == "MHA-TL00")
) {
return "Mate 9"
}
if (codename != null && codename == "angler") {
return "Nexus 6P"
}
// ----------------------------------------------------------------------------
// LGE
if (codename != null && codename == "g2" || model != null && (model == "LG-D800" ||
model == "LG-D801" ||
model == "LG-D802" ||
model == "LG-D802T" ||
model == "LG-D802TR" ||
model == "LG-D803" ||
model == "LG-D805" ||
model == "LG-D806" ||
model == "LG-F320K" ||
model == "LG-F320L" ||
model == "LG-F320S" ||
model == "LG-LS980" ||
model == "VS980 4G")
) {
return "LG G2"
}
if (codename != null && codename == "g3" || model != null && (model == "AS985" ||
model == "LG-AS990" ||
model == "LG-D850" ||
model == "LG-D851" ||
model == "LG-D852" ||
model == "LG-D852G" ||
model == "LG-D855" ||
model == "LG-D856" ||
model == "LG-D857" ||
model == "LG-D858" ||
model == "LG-D858HK" ||
model == "LG-D859" ||
model == "LG-F400K" ||
model == "LG-F400L" ||
model == "LG-F400S" ||
model == "LGL24" ||
model == "LGLS990" ||
model == "LGUS990" ||
model == "LGV31" ||
model == "VS985 4G")
) {
return "LG G3"
}
if (codename != null && codename == "p1" || model != null && (model == "AS986" ||
model == "LG-AS811" ||
model == "LG-AS991" ||
model == "LG-F500K" ||
model == "LG-F500L" ||
model == "LG-F500S" ||
model == "LG-H810" ||
model == "LG-H811" ||
model == "LG-H812" ||
model == "LG-H815" ||
model == "LG-H818" ||
model == "LG-H819" ||
model == "LGLS991" ||
model == "LGUS991" ||
model == "LGV32" ||
model == "VS986")
) {
return "LG G4"
}
if (codename != null && codename == "h1" ||
model != null && (
model == "LG-F700K" ||
model == "LG-F700L" ||
model == "LG-F700S" ||
model == "LG-H820" ||
model == "LG-H820PR" ||
model == "LG-H830" ||
model == "LG-H831" ||
model == "LG-H850" ||
model == "LG-H858" ||
model == "LG-H860" ||
model == "LG-H868" ||
model == "LGAS992" ||
model == "LGLS992" ||
model == "LGUS992" ||
model == "RS988" ||
model == "VS987")
) {
return "LG G5"
}
if (codename != null && codename == "lucye" || model != null && (model == "LG-AS993" ||
model == "LG-H870" || model == "LG-H870AR" || model == "LG-H870DS" ||
model == "LG-H870I" || model == "LG-H870S" || model == "LG-H871" ||
model == "LG-H871S" || model == "LG-H872" ||
model == "LG-H872PR" || model == "LG-H873" || model == "LG-LS993" ||
model == "LGM-G600K" || model == "LGM-G600L" || model == "LGM-G600S" ||
model == "LGUS997" || model == "VS988")
) {
return "LG G6"
}
if (codename != null && codename == "flashlmdd"
|| model != null && (model == "LM-V500" || model == "LM-V500N")
) {
return "LG V50 ThinQ"
}
if (codename != null && codename == "mako") {
return "Nexus 4"
}
if (codename != null && codename == "hammerhead") {
return "Nexus 5"
}
if (codename != null && codename == "bullhead") {
return "Nexus 5X"
}
// ----------------------------------------------------------------------------
// Motorola
if (codename != null && codename == "griffin"
|| model != null && (model == "XT1650" || model == "XT1650-05")
) {
return "Moto Z"
}
if (codename != null && codename == "shamu") {
return "Nexus 6"
}
// ----------------------------------------------------------------------------
// Nokia
if (codename != null && (codename == "RHD" || codename == "ROO" || codename == "ROON_sprout" ||
codename == "ROO_sprout")
) {
return "Nokia 3.1 Plus"
}
if (codename != null && codename == "CTL_sprout") {
return "Nokia 7.1"
}
// ----------------------------------------------------------------------------
// OnePlus
if (codename != null && codename == "OnePlus3" || model != null && model == "ONEPLUS A3000") {
return "OnePlus3"
}
if (codename != null && codename == "OnePlus3T" || model != null && model == "ONEPLUS A3000") {
return "OnePlus3T"
}
if (codename != null && codename == "OnePlus5" || model != null && model == "ONEPLUS A5000") {
return "OnePlus5"
}
if (codename != null && codename == "OnePlus5T" || model != null && model == "ONEPLUS A5010") {
return "OnePlus5T"
}
if (codename != null && codename == "OnePlus6"
|| model != null && (model == "ONEPLUS A6000" || model == "ONEPLUS A6003")
) {
return "OnePlus 6"
}
if (codename != null && (codename == "OnePlus6T" || codename == "OnePlus6TSingle")
|| model != null && model == "ONEPLUS A6013"
) {
return "OnePlus 6T"
}
if (codename != null && codename == "OnePlus7"
|| model != null && model == "GM1905"
) {
return "OnePlus 7"
}
if (codename != null && (codename == "OP7ProNRSpr" || codename == "OnePlus7Pro" ||
codename == "OnePlus7ProTMO") || model != null && (model == "GM1915" ||
model == "GM1917" || model == "GM1925")
) {
return "OnePlus 7 Pro"
}
// ----------------------------------------------------------------------------
// Samsung
if (codename != null && (codename == "a53g" ||
codename == "a5lte" ||
codename == "a5ltechn" ||
codename == "a5ltectc" ||
codename == "a5ltezh" ||
codename == "a5ltezt" ||
codename == "a5ulte" ||
codename == "a5ultebmc" ||
codename == "a5ultektt" ||
codename == "a5ultelgt" ||
codename == "a5ulteskt") || model != null && (model == "SM-A5000" ||
model == "SM-A5009" ||
model == "SM-A500F" ||
model == "SM-A500F1" ||
model == "SM-A500FU" ||
model == "SM-A500G" ||
model == "SM-A500H" ||
model == "SM-A500K" ||
model == "SM-A500L" ||
model == "SM-A500M" ||
model == "SM-A500S" ||
model == "SM-A500W" ||
model == "SM-A500X" ||
model == "SM-A500XZ" ||
model == "SM-A500Y" ||
model == "SM-A500YZ")
) {
return "Galaxy A5"
}
if (codename != null && codename == "vivaltods5m" || model != null && (model == "SM-G313HU" ||
model == "SM-G313HY" ||
model == "SM-G313M" ||
model == "SM-G313MY")
) {
return "Galaxy Ace 4"
}
if (codename != null && (codename == "GT-S6352" ||
codename == "GT-S6802" ||
codename == "GT-S6802B" ||
codename == "SCH-I579" ||
codename == "SCH-I589" ||
codename == "SCH-i579" ||
codename == "SCH-i589") || model != null && (model == "GT-S6352" ||
model == "GT-S6802" ||
model == "GT-S6802B" ||
model == "SCH-I589" ||
model == "SCH-i579" ||
model == "SCH-i589")
) {
return "Galaxy Ace Duos"
}
if (codename != null && (codename == "GT-S7500" ||
codename == "GT-S7500L" ||
codename == "GT-S7500T" ||
codename == "GT-S7500W" ||
codename == "GT-S7508") || model != null && (model == "GT-S7500" ||
model == "GT-S7500L" ||
model == "GT-S7500T" ||
model == "GT-S7500W" ||
model == "GT-S7508")
) {
return "Galaxy Ace Plus"
}
if (codename != null && (codename == "heat3gtfnvzw" ||
codename == "heatnfc3g" ||
codename == "heatqlte") || model != null && (model == "SM-G310HN" ||
model == "SM-G357FZ" ||
model == "SM-S765C" ||
model == "SM-S766C")
) {
return "Galaxy Ace Style"
}
if (codename != null && (codename == "vivalto3g" ||
codename == "vivalto3mve3g" ||
codename == "vivalto5mve3g" ||
codename == "vivaltolte" ||
codename == "vivaltonfc3g") || model != null && (model == "SM-G313F" ||
model == "SM-G313HN" ||
model == "SM-G313ML" ||
model == "SM-G313MU" ||
model == "SM-G316H" ||
model == "SM-G316HU" ||
model == "SM-G316M" ||
model == "SM-G316MY")
) {
return "Galaxy Ace4"
}
if (codename != null && (codename == "core33g" ||
codename == "coreprimelte" ||
codename == "coreprimelteaio" ||
codename == "coreprimeltelra" ||
codename == "coreprimeltespr" ||
codename == "coreprimeltetfnvzw" ||
codename == "coreprimeltevzw" ||
codename == "coreprimeve3g" ||
codename == "coreprimevelte" ||
codename == "cprimeltemtr" ||
codename == "cprimeltetmo" ||
codename == "rossalte" ||
codename == "rossaltectc" ||
codename == "rossaltexsa") || model != null && (model == "SAMSUNG-SM-G360AZ" ||
model == "SM-G3606" ||
model == "SM-G3608" ||
model == "SM-G3609" ||
model == "SM-G360F" ||
model == "SM-G360FY" ||
model == "SM-G360GY" ||
model == "SM-G360H" ||
model == "SM-G360HU" ||
model == "SM-G360M" ||
model == "SM-G360P" ||
model == "SM-G360R6" ||
model == "SM-G360T" ||
model == "SM-G360T1" ||
model == "SM-G360V" ||
model == "SM-G361F" ||
model == "SM-G361H" ||
model == "SM-G361HU" ||
model == "SM-G361M" ||
model == "SM-S820L")
) {
return "Galaxy Core Prime"
}
if (codename != null && (codename == "kanas" ||
codename == "kanas3g" ||
codename == "kanas3gcmcc" ||
codename == "kanas3gctc" ||
codename == "kanas3gnfc") || model != null && (model == "SM-G3556D" ||
model == "SM-G3558" ||
model == "SM-G3559" ||
model == "SM-G355H" ||
model == "SM-G355HN" ||
model == "SM-G355HQ" ||
model == "SM-G355M")
) {
return "Galaxy Core2"
}
if (codename != null && (codename == "e53g" ||
codename == "e5lte" ||
codename == "e5ltetfnvzw" ||
codename == "e5ltetw") || model != null && (model == "SM-E500F" ||
model == "SM-E500H" ||
model == "SM-E500M" ||
model == "SM-E500YZ" ||
model == "SM-S978L")
) {
return "Galaxy E5"
}
if (codename != null && (codename == "e73g" ||
codename == "e7lte" ||
codename == "e7ltechn" ||
codename == "e7ltectc" ||
codename == "e7ltehktw") || model != null && (model == "SM-E7000" ||
model == "SM-E7009" ||
model == "SM-E700F" ||
model == "SM-E700H" ||
model == "SM-E700M")
) {
return "Galaxy E7"
}
if (codename != null && (codename == "SCH-I629" ||
codename == "nevis" ||
codename == "nevis3g" ||
codename == "nevis3gcmcc" ||
codename == "nevisds" ||
codename == "nevisnvess" ||
codename == "nevisp" ||
codename == "nevisvess" ||
codename == "nevisw") || model != null && (model == "GT-S6790" ||
model == "GT-S6790E" ||
model == "GT-S6790L" ||
model == "GT-S6790N" ||
model == "GT-S6810" ||
model == "GT-S6810B" ||
model == "GT-S6810E" ||
model == "GT-S6810L" ||
model == "GT-S6810M" ||
model == "GT-S6810P" ||
model == "GT-S6812" ||
model == "GT-S6812B" ||
model == "GT-S6812C" ||
model == "GT-S6812i" ||
model == "GT-S6818" ||
model == "GT-S6818V" ||
model == "SCH-I629")
) {
return "Galaxy Fame"
}
if (codename != null && codename == "grandprimelteatt" || model != null && model == "SAMSUNG-SM-G530A") {
return "Galaxy Go Prime"
}
if (codename != null && (codename == "baffinlite" ||
codename == "baffinlitedtv" ||
codename == "baffinq3g") || model != null && (model == "GT-I9060" ||
model == "GT-I9060L" ||
model == "GT-I9063T" ||
model == "GT-I9082C" ||
model == "GT-I9168" ||
model == "GT-I9168I")
) {
return "Galaxy Grand Neo"
}
if (codename != null && (codename == "fortuna3g" ||
codename == "fortuna3gdtv" ||
codename == "fortunalte" ||
codename == "fortunaltectc" ||
codename == "fortunaltezh" ||
codename == "fortunaltezt" ||
codename == "fortunave3g" ||
codename == "gprimelteacg" ||
codename == "gprimeltecan" ||
codename == "gprimeltemtr" ||
codename == "gprimeltespr" ||
codename == "gprimeltetfnvzw" ||
codename == "gprimeltetmo" ||
codename == "gprimelteusc" ||
codename == "grandprimelte" ||
codename == "grandprimelteaio" ||
codename == "grandprimeve3g" ||
codename == "grandprimeve3gdtv" ||
codename == "grandprimevelte" ||
codename == "grandprimevelteltn" ||
codename == "grandprimeveltezt") || model != null && (model == "SAMSUNG-SM-G530AZ" ||
model == "SM-G5306W" ||
model == "SM-G5308W" ||
model == "SM-G5309W" ||
model == "SM-G530BT" ||
model == "SM-G530F" ||
model == "SM-G530FZ" ||
model == "SM-G530H" ||
model == "SM-G530M" ||
model == "SM-G530MU" ||
model == "SM-G530P" ||
model == "SM-G530R4" ||
model == "SM-G530R7" ||
model == "SM-G530T" ||
model == "SM-G530T1" ||
model == "SM-G530W" ||
model == "SM-G530Y" ||
model == "SM-G531BT" ||
model == "SM-G531F" ||
model == "SM-G531H" ||
model == "SM-G531M" ||
model == "SM-G531Y" ||
model == "SM-S920L" ||
model == "gprimelteacg")
) {
return "Galaxy Grand Prime"
}
if (codename != null && (codename == "ms013g" ||
codename == "ms013gdtv" ||
codename == "ms013gss" ||
codename == "ms01lte" ||
codename == "ms01ltektt" ||
codename == "ms01ltelgt" ||
codename == "ms01lteskt") || model != null && (model == "SM-G710" ||
model == "SM-G7102" ||
model == "SM-G7102T" ||
model == "SM-G7105" ||
model == "SM-G7105H" ||
model == "SM-G7105L" ||
model == "SM-G7106" ||
model == "SM-G7108" ||
model == "SM-G7109" ||
model == "SM-G710K" ||
model == "SM-G710L" ||
model == "SM-G710S")
) {
return "Galaxy Grand2"
}
if (codename != null && (codename == "j13g" ||
codename == "j13gtfnvzw" ||
codename == "j1lte" ||
codename == "j1nlte" ||
codename == "j1qltevzw" ||
codename == "j1xlte" ||
codename == "j1xlteaio" ||
codename == "j1xlteatt" ||
codename == "j1xltecan" ||
codename == "j1xqltespr" ||
codename == "j1xqltetfnvzw") || model != null && (model == "SAMSUNG-SM-J120A" ||
model == "SAMSUNG-SM-J120AZ" ||
model == "SM-J100F" ||
model == "SM-J100FN" ||
model == "SM-J100G" ||
model == "SM-J100H" ||
model == "SM-J100M" ||
model == "SM-J100ML" ||
model == "SM-J100MU" ||
model == "SM-J100VPP" ||
model == "SM-J100Y" ||
model == "SM-J120F" ||
model == "SM-J120FN" ||
model == "SM-J120M" ||
model == "SM-J120P" ||
model == "SM-J120W" ||
model == "SM-S120VL" ||
model == "SM-S777C")
) {
return "Galaxy J1"
}
if (codename != null && (codename == "j1acelte" ||
codename == "j1acelteltn" ||
codename == "j1acevelte" ||
codename == "j1pop3g") || model != null && (model == "SM-J110F" ||
model == "SM-J110G" ||
model == "SM-J110H" ||
model == "SM-J110L" ||
model == "SM-J110M" ||
model == "SM-J111F" ||
model == "SM-J111M")
) {
return "Galaxy J1 Ace"
}
if (codename != null && (codename == "j53g" ||
codename == "j5lte" ||
codename == "j5ltechn" ||
codename == "j5ltekx" ||
codename == "j5nlte" ||
codename == "j5ylte") || model != null && (model == "SM-J5007" ||
model == "SM-J5008" ||
model == "SM-J500F" ||
model == "SM-J500FN" ||
model == "SM-J500G" ||
model == "SM-J500H" ||
model == "SM-J500M" ||
model == "SM-J500N0" ||
model == "SM-J500Y")
) {
return "Galaxy J5"
}
if (codename != null && (codename == "j75ltektt" ||
codename == "j7e3g" ||
codename == "j7elte" ||
codename == "j7ltechn") || model != null && (model == "SM-J7008" ||
model == "SM-J700F" ||
model == "SM-J700H" ||
model == "SM-J700K" ||
model == "SM-J700M")
) {
return "Galaxy J7"
}
if (codename != null && codename == "a50"
|| model != null && (model == "SM-A505F" || model == "SM-A505FM" || model == "SM-A505FN" ||
model == "SM-A505G" || model == "SM-A505GN" || model == "SM-A505GT" ||
model == "SM-A505N" || model == "SM-A505U" || model == "SM-A505U1" ||
model == "SM-A505W" || model == "SM-A505YN" || model == "SM-S506DL")
) {
return "Galaxy A50"
}
if (codename != null && (codename == "a6elteaio" || codename == "a6elteatt"
|| codename == "a6eltemtr" || codename == "a6eltespr" || codename == "a6eltetmo"
|| codename == "a6elteue" || codename == "a6lte" || codename == "a6lteks")
|| model != null && (model == "SM-A600A" || model == "SM-A600AZ" || model == "SM-A600F"
|| model == "SM-A600FN" || model == "SM-A600G" || model == "SM-A600GN" ||
model == "SM-A600N" || model == "SM-A600P" || model == "SM-A600T" ||
model == "SM-A600T1" || model == "SM-A600U")
) {
return "Galaxy A6"
}
if (codename != null && (codename == "SC-01J" || codename == "SCV34" ||
codename == "gracelte" || codename == "graceltektt" || codename == "graceltelgt" ||
codename == "gracelteskt" || codename == "graceqlteacg" || codename == "graceqlteatt" ||
codename == "graceqltebmc" || codename == "graceqltechn" || codename == "graceqltedcm" ||
codename == "graceqltelra" || codename == "graceqltespr" ||
codename == "graceqltetfnvzw" || codename == "graceqltetmo" ||
codename == "graceqlteue" || codename == "graceqlteusc" ||
codename == "graceqltevzw")
|| model != null && (model == "SAMSUNG-SM-N930A" || model == "SC-01J" || model == "SCV34" ||
model == "SGH-N037" || model == "SM-N9300" || model == "SM-N930F" ||
model == "SM-N930K" || model == "SM-N930L" || model == "SM-N930P" ||
model == "SM-N930R4" || model == "SM-N930R6" || model == "SM-N930R7" ||
model == "SM-N930S" || model == "SM-N930T" || model == "SM-N930U" ||
model == "SM-N930V" || model == "SM-N930VL" || model == "SM-N930W8" ||
model == "SM-N930X")
) {
return "Galaxy Note7"
}
if (codename != null && (codename == "maguro" ||
codename == "toro" ||
codename == "toroplus") || model != null && model == "Galaxy X"
) {
return "Galaxy Nexus"
}
if (codename != null && (codename == "lt033g" ||
codename == "lt03ltektt" ||
codename == "lt03ltelgt" ||
codename == "lt03lteskt" ||
codename == "p4notelte" ||
codename == "p4noteltektt" ||
codename == "p4noteltelgt" ||
codename == "p4notelteskt" ||
codename == "p4noteltespr" ||
codename == "p4notelteusc" ||
codename == "p4noteltevzw" ||
codename == "p4noterf" ||
codename == "p4noterfktt" ||
codename == "p4notewifi" ||
codename == "p4notewifi43241any" ||
codename == "p4notewifiany" ||
codename == "p4notewifiktt" ||
codename == "p4notewifiww") || model != null && (model == "GT-N8000" ||
model == "GT-N8005" ||
model == "GT-N8010" ||
model == "GT-N8013" ||
model == "GT-N8020" ||
model == "SCH-I925" ||
model == "SCH-I925U" ||
model == "SHV-E230K" ||
model == "SHV-E230L" ||
model == "SHV-E230S" ||
model == "SHW-M480K" ||
model == "SHW-M480W" ||
model == "SHW-M485W" ||
model == "SHW-M486W" ||
model == "SM-P601" ||
model == "SM-P602" ||
model == "SM-P605K" ||
model == "SM-P605L" ||
model == "SM-P605S" ||
model == "SPH-P600")
) {
return "Galaxy Note 10.1"
}
if (codename != null && (codename == "SC-01G" ||
codename == "SCL24" ||
codename == "tbeltektt" ||
codename == "tbeltelgt" ||
codename == "tbelteskt" ||
codename == "tblte" ||
codename == "tblteatt" ||
codename == "tbltecan" ||
codename == "tbltechn" ||
codename == "tbltespr" ||
codename == "tbltetmo" ||
codename == "tblteusc" ||
codename == "tbltevzw") || model != null && (model == "SAMSUNG-SM-N915A" ||
model == "SC-01G" ||
model == "SCL24" ||
model == "SM-N9150" ||
model == "SM-N915F" ||
model == "SM-N915FY" ||
model == "SM-N915G" ||
model == "SM-N915K" ||
model == "SM-N915L" ||
model == "SM-N915P" ||
model == "SM-N915R4" ||
model == "SM-N915S" ||
model == "SM-N915T" ||
model == "SM-N915T3" ||
model == "SM-N915V" ||
model == "SM-N915W8" ||
model == "SM-N915X")
) {
return "Galaxy Note Edge"
}
if (codename != null && (codename == "v1a3g" ||
codename == "v1awifi" ||
codename == "v1awifikx" ||
codename == "viennalte" ||
codename == "viennalteatt" ||
codename == "viennaltekx" ||
codename == "viennaltevzw") || model != null && (model == "SAMSUNG-SM-P907A" ||
model == "SM-P900" ||
model == "SM-P901" ||
model == "SM-P905" ||
model == "SM-P905F0" ||
model == "SM-P905M" ||
model == "SM-P905V")
) {
return "Galaxy Note Pro 12.2"
}
if (codename != null && (codename == "tre3caltektt" ||
codename == "tre3caltelgt" ||
codename == "tre3calteskt" ||
codename == "tre3g" ||
codename == "trelte" ||
codename == "treltektt" ||
codename == "treltelgt" ||
codename == "trelteskt" ||
codename == "trhplte" ||
codename == "trlte" ||
codename == "trlteatt" ||
codename == "trltecan" ||
codename == "trltechn" ||
codename == "trltechnzh" ||
codename == "trltespr" ||
codename == "trltetmo" ||
codename == "trlteusc" ||
codename == "trltevzw") || model != null && (model == "SAMSUNG-SM-N910A" ||
model == "SM-N9100" ||
model == "SM-N9106W" ||
model == "SM-N9108V" ||
model == "SM-N9109W" ||
model == "SM-N910C" ||
model == "SM-N910F" ||
model == "SM-N910G" ||
model == "SM-N910H" ||
model == "SM-N910K" ||
model == "SM-N910L" ||
model == "SM-N910P" ||
model == "SM-N910R4" ||
model == "SM-N910S" ||
model == "SM-N910T" ||
model == "SM-N910T2" ||
model == "SM-N910T3" ||
model == "SM-N910U" ||
model == "SM-N910V" ||
model == "SM-N910W8" ||
model == "SM-N910X" ||
model == "SM-N916K" ||
model == "SM-N916L" ||
model == "SM-N916S")
) {
return "Galaxy Note4"
}
if (codename != null && (codename == "noblelte" ||
codename == "noblelteacg" ||
codename == "noblelteatt" ||
codename == "nobleltebmc" ||
codename == "nobleltechn" ||
codename == "nobleltecmcc" ||
codename == "nobleltehk" ||
codename == "nobleltektt" ||
codename == "nobleltelgt" ||
codename == "nobleltelra" ||
codename == "noblelteskt" ||
codename == "nobleltespr" ||
codename == "nobleltetmo" ||
codename == "noblelteusc" ||
codename == "nobleltevzw") || model != null && (model == "SAMSUNG-SM-N920A" ||
model == "SM-N9200" ||
model == "SM-N9208" ||
model == "SM-N920C" ||
model == "SM-N920F" ||
model == "SM-N920G" ||
model == "SM-N920I" ||
model == "SM-N920K" ||
model == "SM-N920L" ||
model == "SM-N920P" ||
model == "SM-N920R4" ||
model == "SM-N920R6" ||
model == "SM-N920R7" ||
model == "SM-N920S" ||
model == "SM-N920T" ||
model == "SM-N920V" ||
model == "SM-N920W8" ||
model == "SM-N920X")
) {
return "Galaxy Note5"
}
if (codename != null && (codename == "SC-01J" ||
codename == "SCV34" ||
codename == "gracelte" ||
codename == "graceltektt" ||
codename == "graceltelgt" ||
codename == "gracelteskt" ||
codename == "graceqlteacg" ||
codename == "graceqlteatt" ||
codename == "graceqltebmc" ||
codename == "graceqltechn" ||
codename == "graceqltedcm" ||
codename == "graceqltelra" ||
codename == "graceqltespr" ||
codename == "graceqltetfnvzw" ||
codename == "graceqltetmo" ||
codename == "graceqlteue" ||
codename == "graceqlteusc" ||
codename == "graceqltevzw") || model != null && (model == "SAMSUNG-SM-N930A" ||
model == "SC-01J" ||
model == "SCV34" ||
model == "SGH-N037" ||
model == "SM-N9300" ||
model == "SM-N930F" ||
model == "SM-N930K" ||
model == "SM-N930L" ||
model == "SM-N930P" ||
model == "SM-N930R4" ||
model == "SM-N930R6" ||
model == "SM-N930R7" ||
model == "SM-N930S" ||
model == "SM-N930T" ||
model == "SM-N930U" ||
model == "SM-N930V" ||
model == "SM-N930VL" ||
model == "SM-N930W8" ||
model == "SM-N930X")
) {
return "Galaxy Note7"
}
if (codename != null && (codename == "SC-01K" || codename == "SCV37" ||
codename == "greatlte" || codename == "greatlteks" || codename == "greatqlte" ||
codename == "greatqltechn" || codename == "greatqltecmcc" ||
codename == "greatqltecs" || codename == "greatqlteue")
|| model != null && (model == "SC-01K" || model == "SCV37" || model == "SM-N9500" ||
model == "SM-N9508" || model == "SM-N950F" || model == "SM-N950N" ||
model == "SM-N950U" || model == "SM-N950U1" || model == "SM-N950W" ||
model == "SM-N950XN")
) {
return "Galaxy Note8"
}
if (codename != null && (codename == "o5lte" ||
codename == "o5ltechn" ||
codename == "o5prolte" ||
codename == "on5ltemtr" ||
codename == "on5ltetfntmo" ||
codename == "on5ltetmo") || model != null && (model == "SM-G5500" ||
model == "SM-G550FY" ||
model == "SM-G550T" ||
model == "SM-G550T1" ||
model == "SM-G550T2" ||
model == "SM-S550TL")
) {
return "Galaxy On5"
}
if (codename != null && (codename == "o7lte" ||
codename == "o7ltechn" ||
codename == "on7elte") || model != null && (model == "SM-G6000" ||
model == "SM-G600F" ||
model == "SM-G600FY")
) {
return "Galaxy On7"
}
if (codename != null && (codename == "GT-I9000" ||
codename == "GT-I9000B" ||
codename == "GT-I9000M" ||
codename == "GT-I9000T" ||
codename == "GT-I9003" ||
codename == "GT-I9003L" ||
codename == "GT-I9008L" ||
codename == "GT-I9010" ||
codename == "GT-I9018" ||
codename == "GT-I9050" ||
codename == "SC-02B" ||
codename == "SCH-I500" ||
codename == "SCH-S950C" ||
codename == "SCH-i909" ||
codename == "SGH-I897" ||
codename == "SGH-T959V" ||
codename == "SGH-T959W" ||
codename == "SHW-M110S" ||
codename == "SHW-M190S" ||
codename == "SPH-D700" ||
codename == "loganlte") || model != null && (model == "GT-I9000" ||
model == "GT-I9000B" ||
model == "GT-I9000M" ||
model == "GT-I9000T" ||
model == "GT-I9003" ||
model == "GT-I9003L" ||
model == "GT-I9008L" ||
model == "GT-I9010" ||
model == "GT-I9018" ||
model == "GT-I9050" ||
model == "GT-S7275" ||
model == "SAMSUNG-SGH-I897" ||
model == "SC-02B" ||
model == "SCH-I500" ||
model == "SCH-S950C" ||
model == "SCH-i909" ||
model == "SGH-T959V" ||
model == "SGH-T959W" ||
model == "SHW-M110S" ||
model == "SHW-M190S" ||
model == "SPH-D700")
) {
return "Galaxy S"
}
if (codename != null && (codename == "kylechn" ||
codename == "kyleopen" ||
codename == "kyletdcmcc") || model != null && (model == "GT-S7562" || model == "GT-S7568")
) {
return "Galaxy S Duos"
}
if (codename != null && codename == "kyleprods" || model != null && (model == "GT-S7582" || model == "GT-S7582L")) {
return "Galaxy S Duos2"
}
if (codename != null && codename == "vivalto3gvn" || model != null && model == "SM-G313HZ") {
return "Galaxy S Duos3"
}
if (codename != null && (codename == "SC-03E" ||
codename == "c1att" ||
codename == "c1ktt" ||
codename == "c1lgt" ||
codename == "c1skt" ||
codename == "d2att" ||
codename == "d2can" ||
codename == "d2cri" ||
codename == "d2dcm" ||
codename == "d2lteMetroPCS" ||
codename == "d2lterefreshspr" ||
codename == "d2ltetmo" ||
codename == "d2mtr" ||
codename == "d2spi" ||
codename == "d2spr" ||
codename == "d2tfnspr" ||
codename == "d2tfnvzw" ||
codename == "d2tmo" ||
codename == "d2usc" ||
codename == "d2vmu" ||
codename == "d2vzw" ||
codename == "d2xar" ||
codename == "m0" ||
codename == "m0apt" ||
codename == "m0chn" ||
codename == "m0cmcc" ||
codename == "m0ctc" ||
codename == "m0ctcduos" ||
codename == "m0skt" ||
codename == "m3" ||
codename == "m3dcm") || model != null && (model == "GT-I9300" ||
model == "GT-I9300T" ||
model == "GT-I9305" ||
model == "GT-I9305N" ||
model == "GT-I9305T" ||
model == "GT-I9308" ||
model == "Gravity" ||
model == "GravityQuad" ||
model == "SAMSUNG-SGH-I747" ||
model == "SC-03E" ||
model == "SC-06D" ||
model == "SCH-I535" ||
model == "SCH-I535PP" ||
model == "SCH-I939" ||
model == "SCH-I939D" ||
model == "SCH-L710" ||
model == "SCH-R530C" ||
model == "SCH-R530M" ||
model == "SCH-R530U" ||
model == "SCH-R530X" ||
model == "SCH-S960L" ||
model == "SCH-S968C" ||
model == "SGH-I747M" ||
model == "SGH-I748" ||
model == "SGH-T999" ||
model == "SGH-T999L" ||
model == "SGH-T999N" ||
model == "SGH-T999V" ||
model == "SHV-E210K" ||
model == "SHV-E210L" ||
model == "SHV-E210S" ||
model == "SHW-M440S" ||
model == "SPH-L710" ||
model == "SPH-L710T")
) {
return "Galaxy S3"
}
if (codename != null && (codename == "golden" ||
codename == "goldenlteatt" ||
codename == "goldenltebmc" ||
codename == "goldenltevzw" ||
codename == "goldenve3g") || model != null && (model == "GT-I8190" ||
model == "GT-I8190L" ||
model == "GT-I8190N" ||
model == "GT-I8190T" ||
model == "GT-I8200L" ||
model == "SAMSUNG-SM-G730A" ||
model == "SM-G730V" ||
model == "SM-G730W8")
) {
return "Galaxy S3 Mini"
}
if (codename != null && (codename == "goldenve3g" || codename == "goldenvess3g") || model != null && (model == "GT-I8200" ||
model == "GT-I8200N" ||
model == "GT-I8200Q")
) {
return "Galaxy S3 Mini Value Edition"
}
if (codename != null && (codename == "s3ve3g" ||
codename == "s3ve3gdd" ||
codename == "s3ve3gds" ||
codename == "s3ve3gdsdd") || model != null && (model == "GT-I9300I" ||
model == "GT-I9301I" ||
model == "GT-I9301Q")
) {
return "Galaxy S3 Neo"
}
if (codename != null && (codename == "SC-04E" ||
codename == "ja3g" ||
codename == "ja3gduosctc" ||
codename == "jaltektt" ||
codename == "jaltelgt" ||
codename == "jalteskt" ||
codename == "jflte" ||
codename == "jflteMetroPCS" ||
codename == "jflteaio" ||
codename == "jflteatt" ||
codename == "jfltecan" ||
codename == "jfltecri" ||
codename == "jfltecsp" ||
codename == "jfltelra" ||
codename == "jflterefreshspr" ||
codename == "jfltespr" ||
codename == "jfltetfnatt" ||
codename == "jfltetfntmo" ||
codename == "jfltetmo" ||
codename == "jflteusc" ||
codename == "jfltevzw" ||
codename == "jfltevzwpp" ||
codename == "jftdd" ||
codename == "jfvelte" ||
codename == "jfwifi" ||
codename == "jsglte" ||
codename == "ks01lte" ||
codename == "ks01ltektt" ||
codename == "ks01ltelgt") || model != null && (model == "GT-I9500" ||
model == "GT-I9505" ||
model == "GT-I9505X" ||
model == "GT-I9506" ||
model == "GT-I9507" ||
model == "GT-I9507V" ||
model == "GT-I9508" ||
model == "GT-I9508C" ||
model == "GT-I9508V" ||
model == "GT-I9515" ||
model == "GT-I9515L" ||
model == "SAMSUNG-SGH-I337" ||
model == "SAMSUNG-SGH-I337Z" ||
model == "SC-04E" ||
model == "SCH-I545" ||
model == "SCH-I545L" ||
model == "SCH-I545PP" ||
model == "SCH-I959" ||
model == "SCH-R970" ||
model == "SCH-R970C" ||
model == "SCH-R970X" ||
model == "SGH-I337M" ||
model == "SGH-M919" ||
model == "SGH-M919N" ||
model == "SGH-M919V" ||
model == "SGH-S970G" ||
model == "SHV-E300K" ||
model == "SHV-E300L" ||
model == "SHV-E300S" ||
model == "SHV-E330K" ||
model == "SHV-E330L" ||
model == "SM-S975L" ||
model == "SPH-L720" ||
model == "SPH-L720T")
) {
return "Galaxy S4"
}
if (codename != null && (codename == "serrano3g" ||
codename == "serranods" ||
codename == "serranolte" ||
codename == "serranoltebmc" ||
codename == "serranoltektt" ||
codename == "serranoltekx" ||
codename == "serranoltelra" ||
codename == "serranoltespr" ||
codename == "serranolteusc" ||
codename == "serranoltevzw" ||
codename == "serranove3g" ||
codename == "serranovelte" ||
codename == "serranovolteatt") || model != null && (model == "GT-I9190" ||
model == "GT-I9192" ||
model == "GT-I9192I" ||
model == "GT-I9195" ||
model == "GT-I9195I" ||
model == "GT-I9195L" ||
model == "GT-I9195T" ||
model == "GT-I9195X" ||
model == "GT-I9197" ||
model == "SAMSUNG-SGH-I257" ||
model == "SCH-I435" ||
model == "SCH-I435L" ||
model == "SCH-R890" ||
model == "SGH-I257M" ||
model == "SHV-E370D" ||
model == "SHV-E370K" ||
model == "SPH-L520")
) {
return "Galaxy S4 Mini"
}
if (codename != null && (codename == "SC-01L" || codename == "SCV40" ||
codename == "crownlte" || codename == "crownlteks" || codename == "crownqltechn" ||
codename == "crownqltecs" || codename == "crownqltesq" || codename == "crownqlteue")
|| model != null && (model == "SC-01L" || model == "SCV40" || model == "SM-N9600" ||
model == "SM-N960F" || model == "SM-N960N" || model == "SM-N960U" ||
model == "SM-N960U1" || model == "SM-N960W")
) {
return "Galaxy Note9"
}
if (codename != null && (codename == "SC-03L" || codename == "SCV41" || codename == "beyond1" ||
codename == "beyond1q")
|| model != null && (model == "SC-03L" || model == "SCV41" || model == "SM-G9730" ||
model == "SM-G9738" || model == "SM-G973C" || model == "SM-G973F" ||
model == "SM-G973N" || model == "SM-G973U" || model == "SM-G973U1" || model == "SM-G973W")
) {
return "Galaxy S10"
}
if (codename != null && (codename == "SC-04L" || codename == "SCV42" || codename == "beyond2" ||
codename == "beyond2q") || model != null && (model == "SC-04L" || model == "SCV42" ||
model == "SM-G9750" || model == "SM-G9758" || model == "SM-G975F" ||
model == "SM-G975N" || model == "SM-G975U" || model == "SM-G975U1" || model == "SM-G975W")
) {
return "Galaxy S10+"
}
if (codename != null && (codename == "beyond0" || codename == "beyond0q")
|| model != null && (model == "SM-G9700" || model == "SM-G9708" || model == "SM-G970F" ||
model == "SM-G970N" || model == "SM-G970U" || model == "SM-G970U1" ||
model == "SM-G970W")
) {
return "Galaxy S10e"
}
if (codename != null && (codename == "SC-04F" || codename == "SCL23" || codename == "k3g" ||
codename == "klte" || codename == "klteMetroPCS" || codename == "klteacg" ||
codename == "klteaio" || codename == "klteatt" || codename == "kltecan" ||
codename == "klteduoszn" || codename == "kltektt" || codename == "kltelgt" ||
codename == "kltelra" || codename == "klteskt" || codename == "kltespr" ||
codename == "kltetfnvzw" || codename == "kltetmo" || codename == "klteusc" ||
codename == "kltevzw" || codename == "kwifi" || codename == "lentisltektt" ||
codename == "lentisltelgt" || codename == "lentislteskt")
|| model != null && (model == "SAMSUNG-SM-G900A" || model == "SAMSUNG-SM-G900AZ" ||
model == "SC-04F" || model == "SCL23" || model == "SM-G9006W" || model == "SM-G9008W" ||
model == "SM-G9009W" || model == "SM-G900F" || model == "SM-G900FQ" ||
model == "SM-G900H" || model == "SM-G900I" || model == "SM-G900K" ||
model == "SM-G900L" || model == "SM-G900M" || model == "SM-G900MD" ||
model == "SM-G900P" || model == "SM-G900R4" || model == "SM-G900R6" ||
model == "SM-G900R7" || model == "SM-G900S" || model == "SM-G900T" ||
model == "SM-G900T1" || model == "SM-G900T3" || model == "SM-G900T4" ||
model == "SM-G900V" || model == "SM-G900W8" || model == "SM-G900X" ||
model == "SM-G906K" || model == "SM-G906L" || model == "SM-G906S" || model == "SM-S903VL")
) {
return "Galaxy S5"
}
if (codename != null && (codename == "s5neolte" || codename == "s5neoltecan")
|| model != null && (model == "SM-G903F" || model == "SM-G903M" || model == "SM-G903W")
) {
return "Galaxy S5 Neo"
}
if (codename != null && (codename == "SC-05G" || codename == "zeroflte" ||
codename == "zeroflteacg" || codename == "zeroflteaio" || codename == "zeroflteatt" ||
codename == "zerofltebmc" || codename == "zerofltechn" || codename == "zerofltectc" ||
codename == "zerofltektt" || codename == "zerofltelgt" || codename == "zerofltelra" ||
codename == "zerofltemtr" || codename == "zeroflteskt" || codename == "zerofltespr" ||
codename == "zerofltetfnvzw" || codename == "zerofltetmo" ||
codename == "zeroflteusc" || codename == "zerofltevzw")
|| model != null && (model == "SAMSUNG-SM-G920A" || model == "SAMSUNG-SM-G920AZ" ||
model == "SC-05G" || model == "SM-G9200" || model == "SM-G9208" ||
model == "SM-G9209" || model == "SM-G920F" || model == "SM-G920I" ||
model == "SM-G920K" || model == "SM-G920L" || model == "SM-G920P" ||
model == "SM-G920R4" || model == "SM-G920R6" || model == "SM-G920R7" ||
model == "SM-G920S" || model == "SM-G920T" || model == "SM-G920T1" ||
model == "SM-G920V" || model == "SM-G920W8" || model == "SM-G920X" ||
model == "SM-S906L" || model == "SM-S907VL")
) {
return "Galaxy S6"
}
if (codename != null && (codename == "404SC" || codename == "SC-04G" || codename == "SCV31" ||
codename == "zerolte" || codename == "zerolteacg" || codename == "zerolteatt" ||
codename == "zeroltebmc" || codename == "zeroltechn" || codename == "zeroltektt" ||
codename == "zeroltelra" || codename == "zerolteskt" || codename == "zeroltespr" ||
codename == "zeroltetmo" || codename == "zerolteusc" || codename == "zeroltevzw")
|| model != null && (model == "404SC" || model == "SAMSUNG-SM-G925A" || model == "SC-04G" ||
model == "SCV31" || model == "SM-G9250" || model == "SM-G925I" || model == "SM-G925K" ||
model == "SM-G925P" || model == "SM-G925R4" || model == "SM-G925R6" ||
model == "SM-G925R7" || model == "SM-G925S" || model == "SM-G925T" ||
model == "SM-G925V" || model == "SM-G925W8" || model == "SM-G925X")
) {
return "Galaxy S6 Edge"
}
if (codename != null && (codename == "zenlte" || codename == "zenlteatt" ||
codename == "zenltebmc" || codename == "zenltechn" || codename == "zenltektt" ||
codename == "zenltekx" || codename == "zenltelgt" || codename == "zenlteskt" ||
codename == "zenltespr" || codename == "zenltetmo" || codename == "zenlteusc" ||
codename == "zenltevzw")
|| model != null && (model == "SAMSUNG-SM-G928A" || model == "SM-G9280" ||
model == "SM-G9287C" || model == "SM-G928C" || model == "SM-G928G" ||
model == "SM-G928I" || model == "SM-G928K" || model == "SM-G928L" ||
model == "SM-G928N0" || model == "SM-G928P" || model == "SM-G928R4" ||
model == "SM-G928S" || model == "SM-G928T" || model == "SM-G928V" ||
model == "SM-G928W8" || model == "SM-G928X")
) {
return "Galaxy S6 Edge+"
}
if (codename != null && (codename == "herolte" || codename == "heroltebmc" ||
codename == "heroltektt" || codename == "heroltelgt" || codename == "herolteskt" ||
codename == "heroqlteacg" || codename == "heroqlteaio" || codename == "heroqlteatt" ||
codename == "heroqltecctvzw" || codename == "heroqltechn" || codename == "heroqltelra" ||
codename == "heroqltemtr" || codename == "heroqltespr" || codename == "heroqltetfnvzw" ||
codename == "heroqltetmo" || codename == "heroqlteue" || codename == "heroqlteusc" ||
codename == "heroqltevzw")
|| model != null && (model == "SAMSUNG-SM-G930A" || model == "SAMSUNG-SM-G930AZ" ||
model == "SM-G9300" || model == "SM-G9308" || model == "SM-G930F" || model == "SM-G930K" ||
model == "SM-G930L" || model == "SM-G930P" || model == "SM-G930R4" || model == "SM-G930R6" ||
model == "SM-G930R7" || model == "SM-G930S" || model == "SM-G930T" || model == "SM-G930T1" ||
model == "SM-G930U" || model == "SM-G930V" || model == "SM-G930VC" || model == "SM-G930VL" ||
model == "SM-G930W8" || model == "SM-G930X")
) {
return "Galaxy S7"
}
if (codename != null && (codename == "SC-02H" || codename == "SCV33" ||
codename == "hero2lte" || codename == "hero2ltebmc" || codename == "hero2ltektt" ||
codename == "hero2lteskt" || codename == "hero2qlteatt" ||
codename == "hero2qltecctvzw" || codename == "hero2qltespr" ||
codename == "hero2qltetmo" || codename == "hero2qlteusc" || codename == "hero2qltevzw")
|| model != null && (model == "SAMSUNG-SM-G935A" || model == "SC-02H" ||
model == "SCV33" || model == "SM-G935K" || model == "SM-G935P" ||
model == "SM-G935R4" || model == "SM-G935S" || model == "SM-G935T" ||
model == "SM-G935V" || model == "SM-G935VC" || model == "SM-G935W8" ||
model == "SM-G935X")
) {
return "Galaxy S7 Edge"
}
if (codename != null && (codename == "SC-02J" || codename == "SCV36" ||
codename == "dreamlte" || codename == "dreamlteks" || codename == "dreamqltecan" ||
codename == "dreamqltechn" || codename == "dreamqltecmcc" || codename == "dreamqltesq" ||
codename == "dreamqlteue")
|| model != null && (model == "SC-02J" || model == "SCV36" || model == "SM-G9500" ||
model == "SM-G9508" || model == "SM-G950F" || model == "SM-G950N" ||
model == "SM-G950U" || model == "SM-G950U1" || model == "SM-G950W")
) {
return "Galaxy S8"
}
if (codename != null && (codename == "SC-03J" || codename == "SCV35" ||
codename == "dream2lte" || codename == "dream2lteks" || codename == "dream2qltecan" ||
codename == "dream2qltechn" || codename == "dream2qltesq" || codename == "dream2qlteue")
|| model != null && (model == "SC-03J" || model == "SCV35" || model == "SM-G9550" ||
model == "SM-G955F" || model == "SM-G955N" || model == "SM-G955U" ||
model == "SM-G955U1" || model == "SM-G955W")
) {
return "Galaxy S8+"
}
if (codename != null && (codename == "SC-02K" || codename == "SCV38" ||
codename == "starlte" || codename == "starlteks" || codename == "starqltechn" ||
codename == "starqltecmcc" || codename == "starqltecs" || codename == "starqltesq" ||
codename == "starqlteue")
|| model != null && (model == "SC-02K" || model == "SCV38" || model == "SM-G9600" ||
model == "SM-G9608" || model == "SM-G960F" || model == "SM-G960N" ||
model == "SM-G960U" || model == "SM-G960U1" || model == "SM-G960W")
) {
return "Galaxy S9"
}
if (codename != null && (codename == "SC-03K" || codename == "SCV39" ||
codename == "star2lte" || codename == "star2lteks" || codename == "star2qltechn" ||
codename == "star2qltecs" || codename == "star2qltesq" || codename == "star2qlteue")
|| model != null && (model == "SC-03K" || model == "SCV39" || model == "SM-G9650" ||
model == "SM-G965F" || model == "SM-G965N" || model == "SM-G965U" ||
model == "SM-G965U1" || model == "SM-G965W")
) {
return "Galaxy S9+"
}
if (codename != null && (codename == "GT-P7500" ||
codename == "GT-P7500D" ||
codename == "GT-P7503" ||
codename == "GT-P7510" ||
codename == "SC-01D" ||
codename == "SCH-I905" ||
codename == "SGH-T859" ||
codename == "SHW-M300W" ||
codename == "SHW-M380K" ||
codename == "SHW-M380S" ||
codename == "SHW-M380W") || model != null && (model == "GT-P7500" ||
model == "GT-P7500D" ||
model == "GT-P7503" ||
model == "GT-P7510" ||
model == "SC-01D" ||
model == "SCH-I905" ||
model == "SGH-T859" ||
model == "SHW-M300W" ||
model == "SHW-M380K" ||
model == "SHW-M380S" ||
model == "SHW-M380W")
) {
return "Galaxy Tab 10.1"
}
if (codename != null && (codename == "GT-P6200" ||
codename == "GT-P6200L" ||
codename == "GT-P6201" ||
codename == "GT-P6210" ||
codename == "GT-P6211" ||
codename == "SC-02D" ||
codename == "SGH-T869" ||
codename == "SHW-M430W") || model != null && (model == "GT-P6200" ||
model == "GT-P6200L" ||
model == "GT-P6201" ||
model == "GT-P6210" ||
model == "GT-P6211" ||
model == "SC-02D" ||
model == "SGH-T869" ||
model == "SHW-M430W")
) {
return "Galaxy Tab 7.0 Plus"
}
if (codename != null && (codename == "gteslteatt" ||
codename == "gtesltebmc" ||
codename == "gtesltelgt" ||
codename == "gteslteskt" ||
codename == "gtesltetmo" ||
codename == "gtesltetw" ||
codename == "gtesltevzw" ||
codename == "gtesqltespr" ||
codename == "gtesqlteusc") || model != null && (model == "SAMSUNG-SM-T377A" ||
model == "SM-T375L" ||
model == "SM-T375S" ||
model == "SM-T3777" ||
model == "SM-T377P" ||
model == "SM-T377R4" ||
model == "SM-T377T" ||
model == "SM-T377V" ||
model == "SM-T377W")
) {
return "Galaxy Tab E 8.0"
}
if (codename != null && (codename == "gtel3g" ||
codename == "gtelltevzw" ||
codename == "gtelwifi" ||
codename == "gtelwifichn" ||
codename == "gtelwifiue") || model != null && (model == "SM-T560" ||
model == "SM-T560NU" ||
model == "SM-T561" ||
model == "SM-T561M" ||
model == "SM-T561Y" ||
model == "SM-T562" ||
model == "SM-T567V")
) {
return "Galaxy Tab E 9.6"
}
if (codename != null && (codename == "403SC" ||
codename == "degas2wifi" ||
codename == "degas2wifibmwchn" ||
codename == "degas3g" ||
codename == "degaslte" ||
codename == "degasltespr" ||
codename == "degasltevzw" ||
codename == "degasvelte" ||
codename == "degasveltechn" ||
codename == "degaswifi" ||
codename == "degaswifibmwzc" ||
codename == "degaswifidtv" ||
codename == "degaswifiopenbnn" ||
codename == "degaswifiue") || model != null && (model == "403SC" ||
model == "SM-T230" ||
model == "SM-T230NT" ||
model == "SM-T230NU" ||
model == "SM-T230NW" ||
model == "SM-T230NY" ||
model == "SM-T230X" ||
model == "SM-T231" ||
model == "SM-T232" ||
model == "SM-T235" ||
model == "SM-T235Y" ||
model == "SM-T237P" ||
model == "SM-T237V" ||
model == "SM-T239" ||
model == "SM-T2397" ||
model == "SM-T239C" ||
model == "SM-T239M")
) {
return "Galaxy Tab4 7.0"
}
if (codename != null && (codename == "gvlte" ||
codename == "gvlteatt" ||
codename == "gvltevzw" ||
codename == "gvltexsp" ||
codename == "gvwifijpn" ||
codename == "gvwifiue") || model != null && (model == "SAMSUNG-SM-T677A" ||
model == "SM-T670" ||
model == "SM-T677" ||
model == "SM-T677V")
) {
return "Galaxy View"
}
if (codename != null && codename == "manta") {
return "Nexus 10"
}
// ----------------------------------------------------------------------------
// Sony
if (codename != null && (codename == "D2104" || codename == "D2105") || model != null && (model == "D2104" || model == "D2105")) {
return "Xperia E1 dual"
}
if (codename != null && (codename == "D2202" ||
codename == "D2203" ||
codename == "D2206" ||
codename == "D2243") || model != null && (model == "D2202" ||
model == "D2203" ||
model == "D2206" ||
model == "D2243")
) {
return "Xperia E3"
}
if (codename != null && (codename == "E5603" ||
codename == "E5606" ||
codename == "E5653") || model != null && (model == "E5603" ||
model == "E5606" ||
model == "E5653")
) {
return "Xperia M5"
}
if (codename != null && (codename == "E5633" ||
codename == "E5643" ||
codename == "E5663") || model != null && (model == "E5633" ||
model == "E5643" ||
model == "E5663")
) {
return "Xperia M5 Dual"
}
if (codename != null && codename == "LT26i" || model != null && model == "LT26i") {
return "Xperia S"
}
if (codename != null && (codename == "D5303" ||
codename == "D5306" ||
codename == "D5316" ||
codename == "D5316N" ||
codename == "D5322") || model != null && (model == "D5303" ||
model == "D5306" ||
model == "D5316" ||
model == "D5316N" ||
model == "D5322")
) {
return "Xperia T2 Ultra"
}
if (codename != null && codename == "txs03" || model != null && (model == "SGPT12" || model == "SGPT13")) {
return "Xperia Tablet S"
}
if (codename != null && (codename == "SGP311" ||
codename == "SGP312" ||
codename == "SGP321" ||
codename == "SGP351") || model != null && (model == "SGP311" ||
model == "SGP312" ||
model == "SGP321" ||
model == "SGP351")
) {
return "Xperia Tablet Z"
}
if (codename != null && (codename == "D6502" ||
codename == "D6503" ||
codename == "D6543" ||
codename == "SO-03F") || model != null && (model == "D6502" ||
model == "D6503" ||
model == "D6543" ||
model == "SO-03F")
) {
return "Xperia Z2"
}
if (codename != null && (codename == "802SO" || codename == "J8110" || codename == "J8170" ||
codename == "J9110" || codename == "J9180" || codename == "SO-03L" || codename == "SOV40")
|| model != null && (model == "802SO" || model == "J8110" || model == "J8170" ||
model == "J9110" || model == "J9180" || model == "SO-03L" || model == "SOV40")
) {
return "Xperia 1"
}
if (codename != null && (codename == "I3113" || codename == "I3123" || codename == "I4113" ||
codename == "I4193")
|| model != null && (model == "I3113" || model == "I3123" || model == "I4113" ||
model == "I4193")
) {
return "Xperia 10"
}
if (codename != null && (codename == "I3213" || codename == "I3223" || codename == "I4213" ||
codename == "I4293")
|| model != null && (model == "I3213" || model == "I3223" || model == "I4213" ||
model == "I4293")
) {
return "Xperia 10 Plus"
}
if (codename != null && (codename == "702SO" || codename == "H8216" || codename == "H8266" ||
codename == "H8276" || codename == "H8296" || codename == "SO-03K" || codename == "SOV37")
|| model != null && (model == "702SO" || model == "H8216" || model == "H8266" ||
model == "H8276" || model == "H8296" || model == "SO-03K" || model == "SOV37")
) {
return "Xperia XZ2"
}
if (codename != null && (codename == "SGP311" ||
codename == "SGP312" ||
codename == "SGP321" ||
codename == "SGP351") || model != null && (model == "SGP311" ||
model == "SGP312" ||
model == "SGP321" ||
model == "SGP351")
) {
return "Xperia Tablet Z"
}
if (codename != null && codename == "txs03" || model != null && (model == "SGPT12" || model == "SGPT13")) {
return "Xperia Tablet S"
}
if (codename != null && (codename == "H8116" || codename == "H8166" || codename == "SO-04K" ||
codename == "SOV38")
|| model != null && (model == "H8116" || model == "H8166" || model == "SO-04K" || model == "SOV38")
) {
return "Xperia XZ2 Premium"
}
if (codename != null && (codename == "401SO" ||
codename == "D6603" ||
codename == "D6616" ||
codename == "D6643" ||
codename == "D6646" ||
codename == "D6653" ||
codename == "SO-01G" ||
codename == "SOL26" ||
codename == "leo") || model != null && (model == "401SO" ||
model == "D6603" ||
model == "D6616" ||
model == "D6643" ||
model == "D6646" ||
model == "D6653" ||
model == "SO-01G" ||
model == "SOL26")
) {
return "Xperia Z3"
}
if (codename != null && (codename == "402SO" ||
codename == "SO-03G" ||
codename == "SOV31") || model != null && (model == "402SO" ||
model == "SO-03G" ||
model == "SOV31")
) {
return "Xperia Z4"
}
if (codename != null && (codename == "E5803" ||
codename == "E5823" ||
codename == "SO-02H") || model != null && (model == "E5803" ||
model == "E5823" ||
model == "SO-02H")
) {
return "Xperia Z5 Compact"
}
if (codename != null && (codename == "801SO" || codename == "H8416" ||
codename == "H9436" || codename == "H9493" || codename == "SO-01L" || codename == "SOV39")
|| model != null && (model == "801SO" || model == "H8416" || model == "H9436" ||
model == "H9493" || model == "SO-01L" || model == "SOV39")
) {
return "Xperia XZ3"
}
// ----------------------------------------------------------------------------
// Sony Ericsson
if (codename != null && (codename == "LT26i" || codename == "SO-02D") || model != null && (model == "LT26i" || model == "SO-02D")) {
return "Xperia S"
}
return if (codename != null && (codename == "SGP311" ||
codename == "SGP321" ||
codename == "SGP341" ||
codename == "SO-03E") || model != null && (model == "SGP311" ||
model == "SGP321" ||
model == "SGP341" ||
model == "SO-03E")) {
"Xperia Tablet Z"
} else fallback
} | apache-2.0 | f70946cad6e5906ca71d981808f73542 | 39.790541 | 136 | 0.435247 | 3.473662 | false | false | false | false |
SimonVT/cathode | cathode-provider/src/main/java/net/simonvt/cathode/provider/helper/SeasonDatabaseHelper.kt | 1 | 7348 | /*
* Copyright (C) 2017 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.provider.helper
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import net.simonvt.cathode.api.entity.Season
import net.simonvt.cathode.common.database.getBoolean
import net.simonvt.cathode.common.database.getInt
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.common.util.guava.Preconditions
import net.simonvt.cathode.provider.DatabaseContract.EpisodeColumns
import net.simonvt.cathode.provider.DatabaseContract.SeasonColumns
import net.simonvt.cathode.provider.ProviderSchematic.Episodes
import net.simonvt.cathode.provider.ProviderSchematic.Seasons
import net.simonvt.cathode.provider.query
import net.simonvt.cathode.provider.update
import net.simonvt.cathode.settings.FirstAiredOffsetPreference
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class SeasonDatabaseHelper @Inject constructor(
private val context: Context,
private val showHelper: ShowDatabaseHelper
) {
fun getId(showId: Long, season: Int): Long {
synchronized(LOCK_ID) {
var c: Cursor? = null
try {
c = context.contentResolver.query(
Seasons.SEASONS,
arrayOf(SeasonColumns.ID),
SeasonColumns.SHOW_ID + "=? AND " + SeasonColumns.SEASON + "=?",
arrayOf(showId.toString(), season.toString())
)
return if (!c.moveToFirst()) -1L else c.getLong(SeasonColumns.ID)
} finally {
c?.close()
}
}
}
fun getTmdbId(seasonId: Long): Int {
synchronized(LOCK_ID) {
var c: Cursor? = null
try {
c = context.contentResolver.query(Seasons.withId(seasonId), arrayOf(SeasonColumns.TMDB_ID))
return if (!c.moveToFirst()) -1 else c.getInt(SeasonColumns.TMDB_ID)
} finally {
c?.close()
}
}
}
fun getNumber(seasonId: Long): Int {
var c: Cursor? = null
try {
c = context.contentResolver.query(
Seasons.withId(seasonId),
arrayOf(SeasonColumns.SEASON)
)
return if (c.moveToFirst()) c.getInt(0) else -1
} finally {
c?.close()
}
}
fun getShowId(seasonId: Long): Long {
var c: Cursor? = null
try {
c = context.contentResolver.query(
Seasons.withId(seasonId),
arrayOf(SeasonColumns.SHOW_ID)
)
return if (c.moveToFirst()) c.getLong(0) else -1L
} finally {
c?.close()
}
}
class IdResult(var id: Long, var didCreate: Boolean)
fun getIdOrCreate(showId: Long, season: Int): IdResult {
Preconditions.checkArgument(showId >= 0, "showId must be >=0, was %d", showId)
synchronized(LOCK_ID) {
var id = getId(showId, season)
if (id == -1L) {
id = create(showId, season)
return IdResult(id, true)
} else {
return IdResult(id, false)
}
}
}
private fun create(showId: Long, season: Int): Long {
val values = ContentValues()
values.put(SeasonColumns.SHOW_ID, showId)
values.put(SeasonColumns.SEASON, season)
val uri = context.contentResolver.insert(Seasons.SEASONS, values)
return Seasons.getId(uri!!)
}
fun updateSeason(showId: Long, season: Season): Long {
val result = getIdOrCreate(showId, season.number)
val seasonId = result.id
val values = getValues(season)
context.contentResolver.update(Seasons.withId(seasonId), values, null, null)
return seasonId
}
fun addToHistory(seasonId: Long, watchedAt: Long) {
val values = ContentValues()
values.put(EpisodeColumns.WATCHED, true)
val firstAiredOffset = FirstAiredOffsetPreference.getInstance().offsetMillis
val millis = System.currentTimeMillis() - firstAiredOffset
context.contentResolver.update(
Episodes.fromSeason(seasonId), values, EpisodeColumns.FIRST_AIRED + "<?",
arrayOf(millis.toString())
)
if (watchedAt == WATCHED_RELEASE) {
values.clear()
val episodes = context.contentResolver.query(
Episodes.fromSeason(seasonId),
arrayOf(EpisodeColumns.ID, EpisodeColumns.FIRST_AIRED),
EpisodeColumns.WATCHED + " AND " + EpisodeColumns.FIRST_AIRED + ">" + EpisodeColumns.LAST_WATCHED_AT
)
while (episodes.moveToNext()) {
val episodeId = episodes.getLong(EpisodeColumns.ID)
val firstAired = episodes.getLong(EpisodeColumns.FIRST_AIRED)
values.put(EpisodeColumns.LAST_WATCHED_AT, firstAired)
context.contentResolver.update(Episodes.withId(episodeId), values, null, null)
}
episodes.close()
} else {
values.clear()
values.put(EpisodeColumns.LAST_WATCHED_AT, watchedAt)
context.contentResolver.update(
Episodes.fromSeason(seasonId),
values,
EpisodeColumns.WATCHED + " AND " + EpisodeColumns.LAST_WATCHED_AT + "<?",
arrayOf(watchedAt.toString())
)
}
}
fun removeFromHistory(seasonId: Long) {
val values = ContentValues()
values.put(EpisodeColumns.WATCHED, false)
values.put(EpisodeColumns.LAST_WATCHED_AT, 0L)
context.contentResolver.update(Episodes.fromSeason(seasonId), values, null, null)
}
fun setIsInCollection(
showTraktId: Long,
seasonNumber: Int,
collected: Boolean,
collectedAt: Long
) {
val showId = showHelper.getId(showTraktId)
val seasonId = getId(showId, seasonNumber)
setIsInCollection(seasonId, collected, collectedAt)
}
fun setIsInCollection(seasonId: Long, collected: Boolean, collectedAt: Long) {
val episodes = context.contentResolver.query(
Episodes.fromSeason(seasonId),
arrayOf(EpisodeColumns.ID, EpisodeColumns.IN_COLLECTION)
)
val values = ContentValues()
values.put(EpisodeColumns.IN_COLLECTION, collected)
values.put(EpisodeColumns.COLLECTED_AT, collectedAt)
while (episodes.moveToNext()) {
val isCollected = episodes.getBoolean(EpisodeColumns.IN_COLLECTION)
if (isCollected != collected) {
val episodeId = episodes.getLong(EpisodeColumns.ID)
context.contentResolver.update(Episodes.withId(episodeId), values)
}
}
episodes.close()
}
private fun getValues(season: Season): ContentValues {
val values = ContentValues()
values.put(SeasonColumns.SEASON, season.number)
values.put(SeasonColumns.FIRST_AIRED, season.first_aired?.timeInMillis)
values.put(SeasonColumns.TVDB_ID, season.ids.tvdb)
values.put(SeasonColumns.TMDB_ID, season.ids.tmdb)
values.put(SeasonColumns.TVRAGE_ID, season.ids.tvrage)
values.put(SeasonColumns.RATING, season.rating)
values.put(SeasonColumns.VOTES, season.votes)
return values
}
companion object {
const val WATCHED_RELEASE = -1L
private val LOCK_ID = Any()
}
}
| apache-2.0 | 6bd106d22b64d24746e10dc0a426401f | 30.401709 | 108 | 0.692569 | 4.242494 | false | false | false | false |
TeamAmaze/AmazeFileManager | app/src/main/java/com/amaze/filemanager/ui/fragments/preferencefragments/PrefsFragment.kt | 1 | 3615 | /*
* Copyright (C) 2014-2020 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.ui.fragments.preferencefragments
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Toast
import androidx.preference.Preference
import com.amaze.filemanager.R
import com.amaze.filemanager.ui.activities.AboutActivity
import com.amaze.filemanager.utils.Utils
class PrefsFragment : BasePrefsFragment() {
override val title = R.string.setting
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences, rootKey)
findPreference<Preference>("appearance")?.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
activity.pushFragment(AppearancePrefsFragment())
true
}
findPreference<Preference>("ui")?.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
activity.pushFragment(UiPrefsFragment())
true
}
findPreference<Preference>("behavior")?.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
activity.pushFragment(BehaviorPrefsFragment())
true
}
findPreference<Preference>("security")?.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
activity.pushFragment(SecurityPrefsFragment())
true
}
findPreference<Preference>("about")?.onPreferenceClickListener =
Preference.OnPreferenceClickListener {
startActivity(Intent(activity, AboutActivity::class.java))
false
}
findPreference<Preference>("feedback")
?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val emailIntent = Utils.buildEmailIntent(requireContext(), null, Utils.EMAIL_SUPPORT)
val activities = activity.packageManager.queryIntentActivities(
emailIntent,
PackageManager.MATCH_DEFAULT_ONLY
)
if (activities.isNotEmpty()) {
startActivity(
Intent.createChooser(
emailIntent,
resources.getString(R.string.feedback)
)
)
} else {
Toast.makeText(
getActivity(),
resources.getString(R.string.send_email_to) + " " + Utils.EMAIL_SUPPORT,
Toast.LENGTH_LONG
)
.show()
}
false
}
}
}
| gpl-3.0 | 4fd065e121349ab850c77c3d4a16525b | 36.65625 | 107 | 0.642047 | 5.622084 | false | false | false | false |
QuickBlox/quickblox-android-sdk | sample-videochat-kotlin/app/src/main/java/com/quickblox/sample/videochat/kotlin/activities/LoginActivity.kt | 1 | 6809 | package com.quickblox.sample.videochat.kotlin.activities
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Menu
import android.view.MenuItem
import android.widget.EditText
import com.quickblox.core.QBEntityCallback
import com.quickblox.core.exception.QBResponseException
import com.quickblox.sample.videochat.kotlin.DEFAULT_USER_PASSWORD
import com.quickblox.sample.videochat.kotlin.R
import com.quickblox.sample.videochat.kotlin.services.LoginService
import com.quickblox.sample.videochat.kotlin.utils.*
import com.quickblox.users.QBUsers
import com.quickblox.users.model.QBUser
const val ERROR_LOGIN_ALREADY_TAKEN_HTTP_STATUS = 422
class LoginActivity : BaseActivity() {
private lateinit var userLoginEditText: EditText
private lateinit var userDisplayNameEditText: EditText
private lateinit var user: QBUser
companion object {
fun start(context: Context) =
context.startActivity(Intent(context, LoginActivity::class.java))
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
initUI()
}
private fun initUI() {
supportActionBar?.title = getString(R.string.title_login_activity)
userLoginEditText = findViewById(R.id.userLoginEditText)
userLoginEditText.addTextChangedListener(LoginEditTextWatcher(userLoginEditText))
userDisplayNameEditText = findViewById(R.id.userDisplayNameEditText)
userDisplayNameEditText.addTextChangedListener(LoginEditTextWatcher(userDisplayNameEditText))
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.activity_login, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_login_user_done -> {
val isNotValidLogin = !isLoginValid(userLoginEditText.text.toString())
if (isNotValidLogin) {
userLoginEditText.error = getString(R.string.error_login)
return false
}
val isNotValidDisplayName = !isDisplayNameValid(userDisplayNameEditText.text.toString())
if (isNotValidDisplayName) {
userDisplayNameEditText.error = getString(R.string.error_display_name)
return false
}
hideKeyboard(userDisplayNameEditText)
val user = createUser()
signUp(user)
return true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun signUp(user: QBUser) {
showProgressDialog(R.string.dlg_creating_new_user)
QBUsers.signUp(user).performAsync(object : QBEntityCallback<QBUser> {
override fun onSuccess(result: QBUser, params: Bundle) {
SharedPrefsHelper.saveCurrentUser(user)
loginToChat(result)
}
override fun onError(e: QBResponseException) {
if (e.httpStatusCode == ERROR_LOGIN_ALREADY_TAKEN_HTTP_STATUS) {
loginToRest(user)
} else {
hideProgressDialog()
longToast(R.string.sign_up_error)
}
}
})
}
private fun loginToChat(user: QBUser) {
user.password = DEFAULT_USER_PASSWORD
this.user = user
startLoginService(user)
}
private fun createUser(): QBUser {
val user = QBUser()
val userLogin = userLoginEditText.text.toString()
val userFullName = userDisplayNameEditText.text.toString()
user.login = userLogin
user.fullName = userFullName
user.password = DEFAULT_USER_PASSWORD
return user
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == EXTRA_LOGIN_RESULT_CODE) {
hideProgressDialog()
var isLoginSuccessInChat = false
data?.let {
isLoginSuccessInChat = it.getBooleanExtra(EXTRA_LOGIN_RESULT, false)
}
if (isLoginSuccessInChat) {
SharedPrefsHelper.saveCurrentUser(user)
loginToRest(user)
} else {
var errorMessage: String? = getString(R.string.unknown_error)
data?.let {
errorMessage = it.getStringExtra(EXTRA_LOGIN_ERROR_MESSAGE)
}
longToast(getString(R.string.login_chat_login_error) + errorMessage)
userLoginEditText.setText(user.login)
userDisplayNameEditText.setText(user.fullName)
}
}
}
private fun loginToRest(user: QBUser) {
QBUsers.signIn(user).performAsync(object : QBEntityCallback<QBUser> {
override fun onSuccess(result: QBUser, params: Bundle) {
SharedPrefsHelper.saveCurrentUser(user)
updateUserOnServer(user)
}
override fun onError(responseException: QBResponseException) {
hideProgressDialog()
longToast(R.string.sign_in_error)
}
})
}
private fun updateUserOnServer(user: QBUser) {
user.password = null
QBUsers.updateUser(user).performAsync(object : QBEntityCallback<QBUser> {
override fun onSuccess(user: QBUser?, params: Bundle?) {
hideProgressDialog()
OpponentsActivity.start(this@LoginActivity)
finish()
}
override fun onError(responseException: QBResponseException?) {
hideProgressDialog()
longToast(R.string.update_user_error)
}
})
}
override fun onBackPressed() {
finish()
}
private fun startLoginService(qbUser: QBUser) {
val tempIntent = Intent(this, LoginService::class.java)
val pendingIntent = createPendingResult(EXTRA_LOGIN_RESULT_CODE, tempIntent, 0)
LoginService.loginToChatAndInitRTCClient(this, qbUser, pendingIntent)
}
private inner class LoginEditTextWatcher internal constructor(private val editText: EditText) :
TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
editText.error = null
}
override fun afterTextChanged(s: Editable) {
}
}
} | bsd-3-clause | abfdbfbd32fc61d5502574f589f0e0e4 | 34.46875 | 104 | 0.634601 | 5.085138 | false | false | false | false |
dszopa/Spark-Message-Router | src/test/kotlin/io/github/dszopa/message_router/router/MessageRouterTest.kt | 1 | 5206 | package io.github.dszopa.message_router.router
import io.github.dszopa.message_router.MessageRouter
import io.github.dszopa.message_router.exception.DuplicateRouteException
import io.github.dszopa.message_router.exception.ParameterMismatchException
import io.github.dszopa.message_router.helper.no_type.nonTypedMessageHandlerCalled
import io.github.dszopa.message_router.helper.no_type.nonTypedMessageHandlerMessage
import io.github.dszopa.message_router.helper.non_null.NonNullableGreeting
import io.github.dszopa.message_router.helper.non_null.nonNullableGreetingHandlerCalled
import io.github.dszopa.message_router.helper.non_null.nonNullableGreetingHandlerGreeting
import io.github.dszopa.message_router.helper.with_null.Greeting
import io.github.dszopa.message_router.helper.with_null.nullableGreetingHandlerCalled
import io.github.dszopa.message_router.helper.with_null.nullableGreetingHandlerGreeting
import org.eclipse.jetty.websocket.api.Session
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.mock
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
class MessageRouterTest {
private val packagePath: String = "io.github.dszopa.message_router.helper"
private val packagePathError: String = "io.github.dszopa.message_router.exception"
private var mockSession: Session? = null
@Before
fun setup() {
mockSession = mock(Session::class.java)
nonTypedMessageHandlerCalled = false
nonTypedMessageHandlerMessage = ""
nonNullableGreetingHandlerCalled = false
nonNullableGreetingHandlerGreeting = null
nullableGreetingHandlerCalled = false
nullableGreetingHandlerGreeting = null
}
@Test(expected = ParameterMismatchException::class) fun messageRouterInvalidFunctionParams() {
MessageRouter(packagePathError + ".param_mismatch")
}
@Test(expected = DuplicateRouteException::class) fun messageRouterDuplicateRoute() {
MessageRouter(packagePathError + ".duplicate_route")
}
@Test fun handleNonCustom() {
assertFalse(nonTypedMessageHandlerCalled)
assertEquals(nonTypedMessageHandlerMessage, "")
val messageRouter = MessageRouter(packagePath + ".no_type")
messageRouter.handle(mockSession!!, "{ route: 'nonTypedMessageHandler' }")
assertTrue(nonTypedMessageHandlerCalled)
assertEquals(nonTypedMessageHandlerMessage, "{ route: 'nonTypedMessageHandler' }")
}
@Test fun handleNonNullableNoData() {
assertFalse(nonNullableGreetingHandlerCalled)
assertNull(nonNullableGreetingHandlerGreeting)
val messageRouter = MessageRouter(packagePath + ".non_null")
messageRouter.handle(mockSession!!, "{ route: 'nonNullableGreetingHandler' }")
assertFalse(nonNullableGreetingHandlerCalled)
assertNull(nonNullableGreetingHandlerGreeting)
}
@Test fun handleNonNullableInvalidData() {
assertFalse(nonNullableGreetingHandlerCalled)
assertNull(nonNullableGreetingHandlerGreeting)
val messageRouter = MessageRouter(packagePath + ".non_null")
messageRouter.handle(mockSession!!, "{ route: 'nonNullableGreetingHandler', data: {} }")
assertFalse(nonNullableGreetingHandlerCalled)
assertNull(nonNullableGreetingHandlerGreeting)
}
@Test fun handleNonNullableMessageObject() {
assertFalse(nonNullableGreetingHandlerCalled)
assertNull(nonNullableGreetingHandlerGreeting)
val messageRouter = MessageRouter(packagePath + ".non_null")
messageRouter.handle(mockSession!!, "{ route: 'nonNullableGreetingHandler', data: { name: 'nameo', exclamation: false } }")
assertTrue(nonNullableGreetingHandlerCalled)
assertEquals(NonNullableGreeting("nameo", false), nonNullableGreetingHandlerGreeting)
}
@Test fun handleNullableMessageObject() {
assertFalse(nullableGreetingHandlerCalled)
assertNull(nullableGreetingHandlerGreeting)
val messageRouter = MessageRouter(packagePath + ".with_null")
messageRouter.handle(mockSession!!, "{ route: 'nullableGreetingHandler', data: { name: 'nameo', exclamation: false } }")
assertTrue(nullableGreetingHandlerCalled)
assertEquals(Greeting("nameo", false), nullableGreetingHandlerGreeting)
}
@Test fun handleNullableMessageObjectEmptyMessage() {
assertFalse(nullableGreetingHandlerCalled)
assertNull(nullableGreetingHandlerGreeting)
val messageRouter = MessageRouter(packagePath + ".with_null")
messageRouter.handle(mockSession!!, "{ route: 'nullableGreetingHandler', data: {} }")
assertTrue(nullableGreetingHandlerCalled)
assertEquals(Greeting(null, null), nullableGreetingHandlerGreeting)
}
@Test fun handleNoRoute() {
assertFalse(nullableGreetingHandlerCalled)
assertNull(nullableGreetingHandlerGreeting)
val messageRouter = MessageRouter(packagePath + ".with_null")
messageRouter.handle(mockSession!!, "{}")
assertFalse(nullableGreetingHandlerCalled)
assertNull(nullableGreetingHandlerGreeting)
}
}
| mit | 785814a3dcdf30516585a5e1e7b61f83 | 46.327273 | 131 | 0.757779 | 5.609914 | false | true | false | false |
michaelgallacher/intellij-community | plugins/settings-repository/testSrc/IcsTestCase.kt | 3 | 2242 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository.test
import com.intellij.testFramework.InMemoryFsRule
import com.intellij.testFramework.TemporaryDirectory
import com.intellij.util.io.writeChild
import org.eclipse.jgit.lib.Repository
import org.jetbrains.settingsRepository.IcsManager
import org.jetbrains.settingsRepository.git.AddLoadedFile
import org.jetbrains.settingsRepository.git.createGitRepository
import org.jetbrains.settingsRepository.git.edit
import org.junit.Rule
import java.nio.file.FileSystem
import java.nio.file.Path
fun Repository.add(path: String, data: String) = add(path, data.toByteArray())
fun Repository.add(path: String, data: ByteArray): Repository {
workTreePath.writeChild(path, data)
edit(AddLoadedFile(path, data))
return this
}
val Repository.workTreePath: Path
get() = workTree.toPath()
val SAMPLE_FILE_NAME = "file.xml"
val SAMPLE_FILE_CONTENT = """<application>
<component name="Encoding" default_encoding="UTF-8" />
</application>"""
abstract class IcsTestCase {
val tempDirManager = TemporaryDirectory()
@Rule fun getTemporaryFolder() = tempDirManager
@JvmField
@Rule
val fsRule = InMemoryFsRule()
val fs: FileSystem
get() = fsRule.fs
val icsManager by lazy(LazyThreadSafetyMode.NONE) {
val icsManager = IcsManager(tempDirManager.newPath())
icsManager.repositoryManager.createRepositoryIfNeed()
icsManager.repositoryActive = true
icsManager
}
val provider by lazy(LazyThreadSafetyMode.NONE) { icsManager.ApplicationLevelProvider() }
}
fun TemporaryDirectory.createRepository(directoryName: String? = null) = createGitRepository(newPath(directoryName))
| apache-2.0 | 5286eb5c5a2860967cd9433c0279c1db | 32.462687 | 116 | 0.776985 | 4.286807 | false | true | false | false |
nemerosa/ontrack | ontrack-extension-git/src/main/java/net/nemerosa/ontrack/extension/git/branching/BranchingModelPropertyType.kt | 1 | 2572 | package net.nemerosa.ontrack.extension.git.branching
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.extension.git.GitExtensionFeature
import net.nemerosa.ontrack.extension.support.AbstractPropertyType
import net.nemerosa.ontrack.json.JsonUtils
import net.nemerosa.ontrack.model.form.Form
import net.nemerosa.ontrack.model.form.NamedEntries
import net.nemerosa.ontrack.model.security.ProjectConfig
import net.nemerosa.ontrack.model.security.SecurityService
import net.nemerosa.ontrack.model.structure.ProjectEntity
import net.nemerosa.ontrack.model.structure.ProjectEntityType
import net.nemerosa.ontrack.model.support.NameValue
import org.springframework.stereotype.Component
import java.util.function.Function
@Component
class BranchingModelPropertyType(
extensionFeature: GitExtensionFeature
) : AbstractPropertyType<BranchingModelProperty>(extensionFeature) {
override fun getName(): String = "Branching Model"
override fun getDescription(): String =
"Defines the branching model used by a project"
override fun getSupportedEntityTypes() =
setOf(ProjectEntityType.PROJECT)
override fun canEdit(entity: ProjectEntity, securityService: SecurityService): Boolean =
securityService.isProjectFunctionGranted(entity, ProjectConfig::class.java)
override fun canView(entity: ProjectEntity, securityService: SecurityService): Boolean =
true
override fun getEditionForm(entity: ProjectEntity, value: BranchingModelProperty?): Form {
val patterns: List<NameValue> = value?.patterns
?: BranchingModel.DEFAULT.patterns.map { (type, regex) -> NameValue(type, regex) }
return Form.create()
.with(
NamedEntries.of("patterns")
.label("List of branches")
.nameLabel("Type")
.valueLabel("Branches")
.addText("Add a branch type")
.help("Regular expressions to associate with branch types")
.value(patterns)
)
}
override fun fromClient(node: JsonNode): BranchingModelProperty {
return fromStorage(node)
}
override fun fromStorage(node: JsonNode): BranchingModelProperty {
return JsonUtils.parse(node, BranchingModelProperty::class.java)
}
override fun replaceValue(value: BranchingModelProperty, replacementFunction: Function<String, String>) = value
} | mit | 283eb33d14d7041f36ff6a8e78584ce5 | 42.610169 | 115 | 0.6979 | 5.31405 | false | false | false | false |
06needhamt/Neuroph-Intellij-Plugin | neuroph-plugin/src/com/thomas/needham/neurophidea/forms/output/NetworkOutputFormImplementation.kt | 1 | 2792 | /*
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.
*/
@file:JvmName("NetworkOutputForm\$Ext") // Do Some Kotlin Sorcery!
@file:JvmMultifileClass()
// Do Some Kotlin Sorcery!
package com.thomas.needham.neurophidea.forms.output
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import javax.swing.ListModel
/**
* Created by Thomas Needham on 09/06/2016.
*/
fun NetworkOutputForm.PopulateLists(path: String) {
val file: File = File(path)
val fr: FileReader? = FileReader(file)
val br: BufferedReader? = BufferedReader(fr)
for (line: String in br?.lines()!!) {
if (line.startsWith("Caculated Output: ")) {
val temp: String?
temp = line.replace("Caculated Output: ", "", true)
this.actualItems.addElement(temp.toDouble())
} else if (line.startsWith("Expected Output: ")) {
val temp: String?
temp = line.replace("Expected Output: ", "")
this.expectedItems.addElement(temp.toDouble())
} else if (line.startsWith("Devience: ")) {
val temp: String?
temp = line.replace("Devience: ", "")
this.differenceItems.addElement(temp.toDouble())
} else {
continue
}
}
br?.close()
this.lstActual?.model = this.differenceItems as ListModel<Any>
this.lstExpected.model = this.expectedItems as ListModel<Any>
this.lstDifference.model = this.differenceItems as ListModel<Any>
}
fun NetworkOutputForm.AddOnClickListeners() {
val browseListener: ResultsOutputBrowseButtonActionListener? = ResultsOutputBrowseButtonActionListener()
browseListener?.formInstance = this
this.btnBrowseSaveLocation.addActionListener(browseListener)
val saveListener: SaveOutputButtonActionListener? = SaveOutputButtonActionListener()
saveListener?.formInstance = this
this.btnSaveOutput.addActionListener(saveListener)
} | mit | 78a9419ac2223bc2b1a0eefd7ae77acb | 37.260274 | 105 | 0.770057 | 3.965909 | false | false | false | false |
nemerosa/ontrack | ontrack-model/src/main/java/net/nemerosa/ontrack/model/annotations/APIUtils.kt | 1 | 2010 | package net.nemerosa.ontrack.model.annotations
import com.fasterxml.jackson.annotation.JsonProperty
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
import kotlin.reflect.full.findAnnotation
@Deprecated("Use getPropertyDescription")
fun getDescription(property: KProperty<*>, defaultDescription: String? = null): String =
defaultDescription
?: property.findAnnotation<APIDescription>()?.value
?: "${property.name} property"
/**
* Getting the description for a property.
*
* Will use first the provided [description], then any [APIDescription] attached to the property
* and as a fallback, a generated string based on the property name.
*/
fun getPropertyDescription(property: KProperty<*>, description: String? = null): String =
description
?: property.findAnnotation<APIDescription>()?.value
?: "${getPropertyName(property)} field"
/**
* Getting the label for a property.
*
* Will use first the provided [label], then any [APILabel] attached to the property
* and as a fallback, a generated string based on the property name.
*/
fun getPropertyLabel(property: KProperty<*>, label: String? = null): String =
label
?: property.findAnnotation<APILabel>()?.value
?: getPropertyName(property)
/**
* Getting the name for a property.
*
* Will use in order:
*
* # any [APIName] annotation
* # any [JsonProperty] annotation on the property
* # any [JsonProperty] annotation on the getter
* # the property name
*/
fun getPropertyName(property: KProperty<*>): String =
property.findAnnotation<APIName>()?.value
?: property.findAnnotation<JsonProperty>()?.value
?: property.getter.findAnnotation<JsonProperty>()?.value
?: property.name
/**
* Getting the name for a class
*
* Will use in order:
*
* # any [APIName] annotation
* # the simple Java class name
*/
fun <T : Any> getAPITypeName(type: KClass<T>): String =
type.findAnnotation<APIName>()?.value
?: type.java.simpleName
| mit | 34ad4c0f4250d6eba151d3256c9c93f7 | 31.419355 | 96 | 0.705473 | 4.466667 | false | false | false | false |
hewking/HUILibrary | app/src/main/java/com/hewking/custom/TagRectView.kt | 1 | 2012 | package com.hewking.custom
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.View
import com.hewking.custom.util.dp2px
/**
* 项目名称:FlowChat
* 类的描述:
* 创建人员:hewking
* 创建时间:2018/10/24 0024
* 修改人员:hewking
* 修改时间:2018/10/24 0024
* 修改备注:
* Version: 1.0.0
*/
class TagRectView(ctx : Context,attrs : AttributeSet) : View(ctx,attrs) {
private val mPaint by lazy {
Paint().apply {
isAntiAlias = true
style = Paint.Style.FILL
color = Color.RED
strokeWidth = dp2px(1f).toFloat()
}
}
init {
val typedArray = ctx.obtainStyledAttributes(attrs, R.styleable.CalendarView)
typedArray.recycle()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val wMode = MeasureSpec.getMode(widthMeasureSpec)
var width = MeasureSpec.getSize(widthMeasureSpec)
val hMode = MeasureSpec.getMode(heightMeasureSpec)
var height = MeasureSpec.getSize(heightMeasureSpec)
if (wMode == MeasureSpec.AT_MOST) {
width = dp2px(15f)
}
if (hMode == MeasureSpec.AT_MOST) {
height = dp2px(30f)
}
setMeasuredDimension(width,height)
if (isInEditMode) {
setMeasuredDimension(100,200)
}
}
private val path : Path by lazy {
Path()
}
override fun onDraw(canvas: Canvas?) {
canvas?:return
val smallH = height / 3f
val biggerH = height / 3f * 2
path.moveTo(0f,smallH)
path.rLineTo(0f,biggerH)
path.rLineTo(width.toFloat(),-smallH)
path.rLineTo(0f,-biggerH)
path.close()
canvas.drawPath(path,mPaint)
}
} | mit | 91d37501538fa976b194064998915e8b | 23.246753 | 84 | 0.599897 | 4.079832 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-Coroutines/src/main/kotlin/core/select/04_SelectingDeferredValues.kt | 2 | 1414 | package core.select
import kotlinx.coroutines.*
import kotlinx.coroutines.selects.select
import java.util.*
//延迟值可以使用 onAwait 子句查询。 让我们启动一个异步函数,它在随机的延迟后会延迟返回字符串:
fun CoroutineScope.asyncString(time: Int) = async {
delay(time.toLong())
"Waited for $time ms"
}
//让我们随机启动十余个异步函数,每个都延迟随机的时间。
fun CoroutineScope.asyncStringsList(): List<Deferred<String>> {
val random = Random(3)
return List(12) { asyncString(random.nextInt(1000)) }
}
/*
现在 main 函数在等待第一个函数完成,并统计仍处于激活状态的延迟值的数量。注意,我们在这里使用 select 表达式事实上是作为一种 Kotlin DSL,
所以我们可以用任意代码为它提供子句。在这种情况下,我们遍历一个延迟值的队列,并为每个延迟值提供 onAwait 子句的调用。
*/
fun main() = runBlocking<Unit> {
//sampleStart
val list = asyncStringsList()
val result = select<String> {
list.withIndex().forEach { (index, deferred) ->
deferred.onAwait { answer ->
"Deferred $index produced answer '$answer'"
}
}
}
println("result = $result ----")
val countActive = list.count { it.isActive }
println("$countActive coroutines are still active")
//sampleEnd
} | apache-2.0 | 1b388e5c6e9888bf246c529b92e71db0 | 27.026316 | 80 | 0.68515 | 3.084058 | false | false | false | false |
matejdro/WearMusicCenter | common/src/main/java/com/matejdro/wearmusiccenter/common/actions/StandardActions.kt | 1 | 974 | package com.matejdro.wearmusiccenter.common.actions
object StandardActions {
const val ACTION_PLAY = "com.matejdro.wearmusiccenter.actions.playback.PlayAction"
const val ACTION_PAUSE = "com.matejdro.wearmusiccenter.actions.playback.PauseAction"
const val ACTION_SKIP_TO_PREV = "com.matejdro.wearmusiccenter.actions.playback.SkipToPrevAction"
const val ACTION_SKIP_TO_NEXT = "com.matejdro.wearmusiccenter.actions.playback.SkipToNextAction"
const val ACTION_VOLUME_UP = "com.matejdro.wearmusiccenter.actions.volume.IncreaseVolumeAction"
const val ACTION_VOLUME_DOWN = "com.matejdro.wearmusiccenter.actions.volume.DecreaseVolumeAction"
const val ACTION_OPEN_MENU = "com.matejdro.wearmusiccenter.actions.OpenMenuAction"
const val ACTION_SKIP_30_SECONDS = "com.matejdro.wearmusiccenter.actions.playback.SkipThirtySecondsAction"
const val ACTION_REVERSE_30_SECONDS = "com.matejdro.wearmusiccenter.actions.playback.ReverseThirtySecondsAction"
} | gpl-3.0 | 1f1c7406fbcc6372f512ac14f2fe4eb7 | 74 | 116 | 0.811088 | 4.198276 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/userlists/BaseUserListsLoader.kt | 1 | 4946 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.loader.userlists
import android.accounts.AccountManager
import android.content.Context
import android.content.SharedPreferences
import android.support.v4.content.FixedAsyncTaskLoader
import android.util.Log
import org.mariotaku.kpreferences.get
import de.vanita5.microblog.library.MicroBlog
import de.vanita5.microblog.library.MicroBlogException
import de.vanita5.microblog.library.twitter.model.PageableResponseList
import de.vanita5.microblog.library.twitter.model.Paging
import de.vanita5.microblog.library.twitter.model.UserList
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.TwittnukerConstants.LOGTAG
import de.vanita5.twittnuker.constant.loadItemLimitKey
import de.vanita5.twittnuker.extension.model.api.microblog.toParcelable
import de.vanita5.twittnuker.extension.model.newMicroBlogInstance
import de.vanita5.twittnuker.loader.iface.IPaginationLoader
import de.vanita5.twittnuker.model.ParcelableUserList
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.pagination.CursorPagination
import de.vanita5.twittnuker.model.pagination.Pagination
import de.vanita5.twittnuker.model.util.AccountUtils
import de.vanita5.twittnuker.util.collection.NoDuplicatesArrayList
import de.vanita5.twittnuker.util.dagger.GeneralComponent
import java.util.*
import javax.inject.Inject
abstract class BaseUserListsLoader(
context: Context,
protected val accountKey: UserKey?,
data: List<ParcelableUserList>?
) : FixedAsyncTaskLoader<List<ParcelableUserList>>(context), IPaginationLoader {
@Inject
lateinit var preferences: SharedPreferences
protected val data = NoDuplicatesArrayList<ParcelableUserList>()
private val profileImageSize = context.getString(R.string.profile_image_size)
override var pagination: Pagination? = null
override var nextPagination: Pagination? = null
protected set
override var prevPagination: Pagination? = null
protected set
init {
GeneralComponent.get(context).inject(this)
if (data != null) {
this.data.addAll(data)
}
}
@Throws(MicroBlogException::class)
abstract fun getUserLists(twitter: MicroBlog, paging: Paging): List<UserList>
override fun loadInBackground(): List<ParcelableUserList> {
if (accountKey == null) return emptyList()
var listLoaded: List<UserList>? = null
try {
val am = AccountManager.get(context)
val details = AccountUtils.getAccountDetails(am, accountKey, true) ?: return data
val twitter = details.newMicroBlogInstance(context, MicroBlog::class.java)
val paging = Paging()
paging.count(preferences[loadItemLimitKey].coerceIn(0, 100))
pagination?.applyTo(paging)
listLoaded = getUserLists(twitter, paging)
} catch (e: MicroBlogException) {
Log.w(LOGTAG, e)
}
if (listLoaded != null) {
val listSize = listLoaded.size
if (listLoaded is PageableResponseList<*>) {
nextPagination = CursorPagination.valueOf(listLoaded.nextCursor)
prevPagination = CursorPagination.valueOf(listLoaded.previousCursor)
val dataSize = data.size
for (i in 0 until listSize) {
val list = listLoaded[i]
data.add(list.toParcelable(accountKey, (dataSize + i).toLong(),
isFollowing(list), profileImageSize))
}
} else {
for (i in 0 until listSize) {
val list = listLoaded[i]
data.add(listLoaded[i].toParcelable(accountKey, i.toLong(),
isFollowing(list), profileImageSize))
}
}
}
Collections.sort(data)
return data
}
override fun onStartLoading() {
forceLoad()
}
protected open fun isFollowing(list: UserList): Boolean {
return list.isFollowing
}
} | gpl-3.0 | 8010167791dba0c7580f2082395c37df | 37.952756 | 93 | 0.700768 | 4.652869 | false | false | false | false |
BitPrepared/login-app | app/src/main/java/it/bitprepared/loginapp/ResultActivity.kt | 1 | 1038 | package it.bitprepared.loginapp
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_result.*
const val KEY_RESULT_SQ = "result_sq"
class ResultActivity : AppCompatActivity() {
private var resultSq: String? = null
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_result)
resultSq = if (savedInstanceState == null) {
intent.extras.getString(KEY_RESULT_SQ)
} else {
savedInstanceState.getSerializable(KEY_RESULT_SQ) as String
}
if (resultSq == null) return
when (resultSq) {
WHITE -> result_image.setImageResource(R.drawable.rad2)
YELLOW -> result_image.setImageResource(R.drawable.rad5)
RED -> result_image.setImageResource(R.drawable.rad3)
GREEN -> result_image.setImageResource(R.drawable.rad4)
}
result_sq.text = resultSq
}
}
| gpl-2.0 | 1113ca8441ecad621372d1acaaaa0565 | 30.454545 | 71 | 0.67052 | 4.307054 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/task/AddUserListMembersTask.kt | 1 | 3069 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.task
import android.content.Context
import android.widget.Toast
import org.mariotaku.kpreferences.get
import org.mariotaku.ktextension.mapToArray
import de.vanita5.microblog.library.MicroBlog
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.constant.nameFirstKey
import de.vanita5.twittnuker.extension.model.api.microblog.toParcelable
import de.vanita5.twittnuker.extension.model.newMicroBlogInstance
import de.vanita5.twittnuker.model.AccountDetails
import de.vanita5.twittnuker.model.ParcelableUser
import de.vanita5.twittnuker.model.ParcelableUserList
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.event.UserListMembersChangedEvent
class AddUserListMembersTask(
context: Context,
accountKey: UserKey,
private val listId: String,
private val users: Array<out ParcelableUser>
) : AbsAccountRequestTask<Any?, ParcelableUserList, Any?>(context, accountKey) {
override fun onExecute(account: AccountDetails, params: Any?): ParcelableUserList {
val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java)
val userIds = users.mapToArray(ParcelableUser::key)
val result = microBlog.addUserListMembers(listId, UserKey.getIds(userIds))
return result.toParcelable(account.key)
}
override fun onSucceed(callback: Any?, result: ParcelableUserList) {
val message: String
if (users.size == 1) {
val user = users.first()
val nameFirst = preferences[nameFirstKey]
val displayName = userColorNameManager.getDisplayName(user.key, user.name,
user.screen_name, nameFirst)
message = context.getString(R.string.message_toast_added_user_to_list, displayName, result.name)
} else {
val res = context.resources
message = res.getQuantityString(R.plurals.added_N_users_to_list, users.size, users.size,
result.name)
}
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
bus.post(UserListMembersChangedEvent(UserListMembersChangedEvent.Action.ADDED, result, users))
}
} | gpl-3.0 | 6ee9719b80c0c044571c16f2b5165c0e | 42.239437 | 108 | 0.735745 | 4.384286 | false | false | false | false |
matejdro/WearMusicCenter | mobile/src/main/java/com/matejdro/wearmusiccenter/actions/tasker/TaskerTaskPickerAction.kt | 1 | 1875 | package com.matejdro.wearmusiccenter.actions.tasker
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.PersistableBundle
import androidx.appcompat.content.res.AppCompatResources
import com.matejdro.wearmusiccenter.R
import com.matejdro.wearmusiccenter.actions.PhoneAction
import com.matejdro.wearmusiccenter.view.ActivityResultReceiver
import com.matejdro.wearmusiccenter.view.buttonconfig.ActionPickerViewModel
import com.matejdro.wearutils.tasker.TaskerIntent
class TaskerTaskPickerAction : PhoneAction, ActivityResultReceiver {
constructor(context: Context) : super(context)
constructor(context: Context, bundle: PersistableBundle) : super(context, bundle)
private var prevActionPicker: ActionPickerViewModel? = null
override fun retrieveTitle(): String = context.getString(R.string.tasker_task)
override val defaultIcon: Drawable
get() {
return try {
context.packageManager.getApplicationIcon(TaskerIntent.TASKER_PACKAGE_MARKET)
} catch (ignored: PackageManager.NameNotFoundException) {
AppCompatResources.getDrawable(context, android.R.drawable.sym_def_app_icon)!!
}
}
override fun onActionPicked(actionPicker: ActionPickerViewModel) {
prevActionPicker = actionPicker
actionPicker.startActivityForResult(TaskerIntent.getTaskSelectIntent(), this)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode != Activity.RESULT_OK) {
return
}
val taskName = data?.dataString ?: return
val taskerAction = TaskerTaskAction(context, taskName)
prevActionPicker?.selectedAction?.value = taskerAction
}
}
| gpl-3.0 | 3b1f82706cd87ec51b1d02fe63d29849 | 38.893617 | 94 | 0.752533 | 4.960317 | false | false | false | false |
SapuSeven/BetterUntis | app/src/main/java/com/sapuseven/untis/models/untis/masterdata/Holiday.kt | 1 | 1541 | package com.sapuseven.untis.models.untis.masterdata
import android.content.ContentValues
import android.database.Cursor
import com.sapuseven.untis.annotations.Table
import com.sapuseven.untis.annotations.TableColumn
import com.sapuseven.untis.data.databases.TABLE_NAME_HOLIDAYS
import com.sapuseven.untis.interfaces.TableModel
import kotlinx.serialization.Serializable
@Serializable
@Table(TABLE_NAME_HOLIDAYS)
data class Holiday(
@field:TableColumn("INTEGER NOT NULL") val id: Int = 0,
@field:TableColumn("VARCHAR(255) NOT NULL") val name: String = "",
@field:TableColumn("VARCHAR(255) NOT NULL") val longName: String = "",
@field:TableColumn("VARCHAR(255) NOT NULL") val startDate: String = "",
@field:TableColumn("VARCHAR(255) NOT NULL") val endDate: String = ""
) : TableModel {
companion object {
const val TABLE_NAME = TABLE_NAME_HOLIDAYS
}
override val tableName = TABLE_NAME
override val elementId = id
override fun generateValues(): ContentValues {
val values = ContentValues()
values.put("id", id)
values.put("name", name)
values.put("longName", longName)
values.put("startDate", startDate)
values.put("endDate", endDate)
return values
}
override fun parseCursor(cursor: Cursor): TableModel {
return Holiday(
cursor.getInt(cursor.getColumnIndex("id")),
cursor.getString(cursor.getColumnIndex("name")),
cursor.getString(cursor.getColumnIndex("longName")),
cursor.getString(cursor.getColumnIndex("startDate")),
cursor.getString(cursor.getColumnIndex("endDate"))
)
}
}
| gpl-3.0 | afc8519d0e487704b5de38725a7ee3f2 | 31.104167 | 73 | 0.748864 | 3.758537 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/stubs/index/RsExternCrateReexportIndex.kt | 2 | 2313 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.stubs.index
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.IndexSink
import com.intellij.psi.stubs.StringStubIndexExtension
import com.intellij.psi.stubs.StubIndexKey
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import org.rust.lang.core.crate.impl.FakeCrate
import org.rust.lang.core.psi.RsExternCrateItem
import org.rust.lang.core.psi.ext.RsMod
import org.rust.lang.core.psi.rustStructureOrAnyPsiModificationTracker
import org.rust.lang.core.stubs.RsExternCrateItemStub
import org.rust.lang.core.stubs.RsFileStub
import org.rust.openapiext.checkCommitIsNotInProgress
import org.rust.openapiext.getElements
class RsExternCrateReexportIndex : StringStubIndexExtension<RsExternCrateItem>() {
override fun getVersion(): Int = RsFileStub.Type.stubVersion
override fun getKey(): StubIndexKey<String, RsExternCrateItem> = KEY
companion object {
val KEY: StubIndexKey<String, RsExternCrateItem> =
StubIndexKey.createIndexKey("org.rust.lang.core.stubs.index.RsExternCrateReexportIndex")
fun index(stub: RsExternCrateItemStub, sink: IndexSink) {
val externCrateItem = stub.psi
val isPublic = externCrateItem?.vis != null
if (!isPublic) return
sink.occurrence(KEY, externCrateItem.referenceName)
}
fun findReexports(project: Project, crateRoot: RsMod): List<RsExternCrateItem> {
checkCommitIsNotInProgress(project)
return CachedValuesManager.getCachedValue(crateRoot) {
val targetCrate = crateRoot.containingCrate
val reexports = if (targetCrate !is FakeCrate) {
getElements(KEY, targetCrate.normName, project, GlobalSearchScope.allScope(project))
.filter { externCrateItem -> externCrateItem.reference.resolve() == crateRoot }
} else {
emptyList()
}
CachedValueProvider.Result.create(reexports, crateRoot.rustStructureOrAnyPsiModificationTracker)
}
}
}
}
| mit | b230a584de5cf1e2fdac9a28b480787a | 41.833333 | 112 | 0.719412 | 4.869474 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/RsPsiManager.kt | 2 | 12906 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi
import com.intellij.ProjectTopics
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.service
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.ModificationTracker
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.psi.*
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.messages.MessageBusConnection
import com.intellij.util.messages.Topic
import org.rust.cargo.project.model.CargoProjectsService
import org.rust.cargo.project.model.CargoProjectsService.CargoProjectsListener
import org.rust.cargo.project.model.cargoProjects
import org.rust.cargo.project.workspace.PackageOrigin
import org.rust.lang.RsFileType
import org.rust.lang.core.crate.Crate
import org.rust.lang.core.crate.crateGraph
import org.rust.lang.core.macros.MacroExpansionFileSystem
import org.rust.lang.core.macros.MacroExpansionMode
import org.rust.lang.core.macros.macroExpansionManagerIfCreated
import org.rust.lang.core.psi.RsPsiManager.Companion.isIgnorePsiEvents
import org.rust.lang.core.psi.RsPsiTreeChangeEvent.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve2.defMapService
/** Don't subscribe directly or via plugin.xml lazy listeners. Use [RsPsiManager.subscribeRustStructureChange] */
private val RUST_STRUCTURE_CHANGE_TOPIC: Topic<RustStructureChangeListener> = Topic.create(
"RUST_STRUCTURE_CHANGE_TOPIC",
RustStructureChangeListener::class.java,
Topic.BroadcastDirection.TO_PARENT
)
/** Don't subscribe directly or via plugin.xml lazy listeners. Use [RsPsiManager.subscribeRustPsiChange] */
private val RUST_PSI_CHANGE_TOPIC: Topic<RustPsiChangeListener> = Topic.create(
"RUST_PSI_CHANGE_TOPIC",
RustPsiChangeListener::class.java,
Topic.BroadcastDirection.TO_PARENT
)
interface RsPsiManager {
/**
* A project-global modification tracker that increments on each PSI change that can affect
* name resolution or type inference. It will be incremented with a change of most types of
* PSI element excluding function bodies (expressions and statements)
*/
val rustStructureModificationTracker: ModificationTracker
/**
* Similar to [rustStructureModificationTracker], but it is not incremented by changes in
* workspace rust files.
*
* @see PackageOrigin.WORKSPACE
*/
val rustStructureModificationTrackerInDependencies: SimpleModificationTracker
fun incRustStructureModificationCount()
/** This is an instance method because [RsPsiManager] should be created prior to event subscription */
fun subscribeRustStructureChange(connection: MessageBusConnection, listener: RustStructureChangeListener) {
connection.subscribe(RUST_STRUCTURE_CHANGE_TOPIC, listener)
}
/** This is an instance method because [RsPsiManager] should be created prior to event subscription */
fun subscribeRustPsiChange(connection: MessageBusConnection, listener: RustPsiChangeListener) {
connection.subscribe(RUST_PSI_CHANGE_TOPIC, listener)
}
companion object {
private val IGNORE_PSI_EVENTS: Key<Boolean> = Key.create("IGNORE_PSI_EVENTS")
fun <T> withIgnoredPsiEvents(psi: PsiFile, f: () -> T): T {
setIgnorePsiEvents(psi, true)
try {
return f()
} finally {
setIgnorePsiEvents(psi, false)
}
}
fun isIgnorePsiEvents(psi: PsiFile): Boolean =
psi.getUserData(IGNORE_PSI_EVENTS) == true
private fun setIgnorePsiEvents(psi: PsiFile, ignore: Boolean) {
psi.putUserData(IGNORE_PSI_EVENTS, if (ignore) true else null)
}
}
}
interface RustStructureChangeListener {
fun rustStructureChanged(file: PsiFile?, changedElement: PsiElement?)
}
interface RustPsiChangeListener {
fun rustPsiChanged(file: PsiFile, element: PsiElement, isStructureModification: Boolean)
}
class RsPsiManagerImpl(val project: Project) : RsPsiManager, Disposable {
override val rustStructureModificationTracker = SimpleModificationTracker()
override val rustStructureModificationTrackerInDependencies = SimpleModificationTracker()
init {
PsiManager.getInstance(project).addPsiTreeChangeListener(CacheInvalidator(), this)
project.messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
incRustStructureModificationCount()
}
})
project.messageBus.connect().subscribe(CargoProjectsService.CARGO_PROJECTS_TOPIC, CargoProjectsListener { _, _ ->
incRustStructureModificationCount()
})
}
override fun dispose() {}
inner class CacheInvalidator : RsPsiTreeChangeAdapter() {
override fun handleEvent(event: RsPsiTreeChangeEvent) {
val element = when (event) {
is ChildRemoval.Before -> event.child
is ChildRemoval.After -> event.parent
is ChildReplacement.Before -> event.oldChild
is ChildReplacement.After -> event.newChild
is ChildAddition.After -> event.child
is ChildMovement.After -> event.child
is ChildrenChange.After -> if (!event.isGenericChange) event.parent else return
is PropertyChange.After -> {
when (event.propertyName) {
PsiTreeChangeEvent.PROP_UNLOADED_PSI, PsiTreeChangeEvent.PROP_FILE_TYPES -> {
incRustStructureModificationCount()
return
}
PsiTreeChangeEvent.PROP_WRITABLE -> return
else -> event.element ?: return
}
}
else -> return
}
val file = event.file
// if file is null, this is an event about VFS changes
if (file == null) {
val isStructureModification = element is RsFile && !isIgnorePsiEvents(element)
|| element is PsiDirectory && project.cargoProjects.findPackageForFile(element.virtualFile) != null
if (isStructureModification) {
incRustStructureModificationCount(element as? RsFile, element as? RsFile)
}
} else {
if (file.fileType != RsFileType) return
if (isIgnorePsiEvents(file)) return
val isWhitespaceOrComment = element is PsiComment || element is PsiWhiteSpace
if (isWhitespaceOrComment && !isMacroExpansionModeNew) {
// Whitespace/comment changes are meaningful if new macro expansion engine is used
return
}
// Most of events means that some element *itself* is changed, but ChildrenChange means
// that changed some of element's children, not the element itself. In this case
// we should look up for ModificationTrackerOwner a bit differently
val isChildrenChange = event is ChildrenChange || event is ChildRemoval.After
updateModificationCount(file, element, isChildrenChange, isWhitespaceOrComment)
}
}
}
private fun updateModificationCount(
file: PsiFile,
psi: PsiElement,
isChildrenChange: Boolean,
isWhitespaceOrComment: Boolean
) {
// We find the nearest parent item or macro call (because macro call can produce items)
// If found item implements RsModificationTrackerOwner, we increment its own
// modification counter. Otherwise we increment global modification counter.
//
// So, if something is changed inside a function except an item, we will only
// increment the function local modification counter.
//
// It may not be intuitive that if we change an item inside a function,
// like this struct: `fn foo() { struct Bar; }`, we will increment the
// global modification counter instead of function-local. We do not care
// about it because it is a rare case and implementing it differently
// is much more difficult.
val owner = if (DumbService.isDumb(project)) null else psi.findModificationTrackerOwner(!isChildrenChange)
// Whitespace/comment changes are meaningful for macros only
// (b/c they affect range mappings and body hashes)
if (isWhitespaceOrComment) {
if (owner !is RsMacroCall && owner !is RsMacroDefinitionBase && !RsProcMacroPsiUtil.canBeInProcMacroCallBody(psi)) return
}
val isStructureModification = owner == null || !owner.incModificationCount(psi)
if (!isStructureModification && owner is RsMacroCall &&
(!isMacroExpansionModeNew || !owner.isTopLevelExpansion)) {
return updateModificationCount(file, owner, isChildrenChange = false, isWhitespaceOrComment = false)
}
if (isStructureModification) {
incRustStructureModificationCount(file, psi)
}
project.messageBus.syncPublisher(RUST_PSI_CHANGE_TOPIC).rustPsiChanged(file, psi, isStructureModification)
}
private val isMacroExpansionModeNew
get() = project.macroExpansionManagerIfCreated?.macroExpansionMode is MacroExpansionMode.New
override fun incRustStructureModificationCount() =
incRustStructureModificationCount(null, null)
private fun incRustStructureModificationCount(file: PsiFile? = null, psi: PsiElement? = null) {
rustStructureModificationTracker.incModificationCount()
if (!isWorkspaceFile(file)) {
rustStructureModificationTrackerInDependencies.incModificationCount()
}
project.messageBus.syncPublisher(RUST_STRUCTURE_CHANGE_TOPIC).rustStructureChanged(file, psi)
}
private fun isWorkspaceFile(file: PsiFile?): Boolean {
if (file !is RsFile) return false
val virtualFile = file.virtualFile ?: return false
val crates = if (virtualFile.fileSystem is MacroExpansionFileSystem) {
val crateId = project.macroExpansionManagerIfCreated?.getCrateForExpansionFile(virtualFile) ?: return false
listOf(crateId)
} else {
project.defMapService.findCrates(file)
}
if (crates.isEmpty()) return false
val crateGraph = project.crateGraph
if (crates.any { crateGraph.findCrateById(it)?.origin != PackageOrigin.WORKSPACE }) return false
return true
}
}
val Project.rustPsiManager: RsPsiManager get() = service()
/** @see RsPsiManager.rustStructureModificationTracker */
val Project.rustStructureModificationTracker: ModificationTracker
get() = rustPsiManager.rustStructureModificationTracker
/**
* Returns [RsPsiManager.rustStructureModificationTracker] if [Crate.origin] == [PackageOrigin.WORKSPACE] or
* [RsPsiManager.rustStructureModificationTrackerInDependencies] otherwise
*/
val Crate.rustStructureModificationTracker: ModificationTracker
get() = if (origin == PackageOrigin.WORKSPACE) {
project.rustStructureModificationTracker
} else {
project.rustPsiManager.rustStructureModificationTrackerInDependencies
}
/**
* Returns [RsPsiManager.rustStructureModificationTracker] or [PsiModificationTracker.MODIFICATION_COUNT]
* if `this` element is inside language injection
*/
val RsElement.rustStructureOrAnyPsiModificationTracker: ModificationTracker
get() {
val containingFile = containingFile
return when {
// The case of injected language. Injected PSI doesn't have its own event system, so can only
// handle evens from outer PSI. For example, Rust language is injected to Kotlin's string
// literal. If a user change the literal, we can only be notified that the literal is changed.
// So we have to invalidate the cached value on any PSI change
containingFile.virtualFile is VirtualFileWindow ->
PsiManager.getInstance(containingFile.project).modificationTracker
containingFile.containingRsFileSkippingCodeFragments?.crate?.origin == PackageOrigin.WORKSPACE ->
containingFile.project.rustStructureModificationTracker
else -> containingFile.project.rustPsiManager.rustStructureModificationTrackerInDependencies
}
}
| mit | e3acf46d40a1c8745905923f879c3235 | 43.657439 | 133 | 0.699365 | 5.422689 | false | false | false | false |
Undin/intellij-rust | idea/src/main/kotlin/org/rust/ide/idea/RsProjectStructureDetector.kt | 3 | 2263 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.idea
import com.intellij.ide.util.importProject.ModuleDescriptor
import com.intellij.ide.util.importProject.ProjectDescriptor
import com.intellij.ide.util.projectWizard.ModuleWizardStep
import com.intellij.ide.util.projectWizard.importSources.DetectedProjectRoot
import com.intellij.ide.util.projectWizard.importSources.DetectedSourceRoot
import com.intellij.ide.util.projectWizard.importSources.ProjectFromSourcesBuilder
import com.intellij.ide.util.projectWizard.importSources.ProjectStructureDetector
import org.rust.cargo.CargoConstants
import org.rust.ide.module.CargoConfigurationWizardStep
import org.rust.ide.module.RsModuleType
import java.io.File
import javax.swing.Icon
class RsProjectStructureDetector : ProjectStructureDetector() {
override fun detectRoots(
dir: File,
children: Array<out File>,
base: File,
result: MutableList<DetectedProjectRoot>
): DirectoryProcessingResult {
if (children.any { it.name == CargoConstants.MANIFEST_FILE }) {
result.add(object : DetectedProjectRoot(dir) {
override fun getRootTypeName(): String = "Rust"
})
}
return DirectoryProcessingResult.SKIP_CHILDREN
}
override fun setupProjectStructure(
roots: MutableCollection<DetectedProjectRoot>,
projectDescriptor: ProjectDescriptor,
builder: ProjectFromSourcesBuilder
) {
val root = roots.singleOrNull()
if (root == null || builder.hasRootsFromOtherDetectors(this) || projectDescriptor.modules.isNotEmpty()) {
return
}
val moduleDescriptor = ModuleDescriptor(root.directory, RsModuleType.INSTANCE, emptyList<DetectedSourceRoot>())
projectDescriptor.modules = listOf(moduleDescriptor)
}
override fun createWizardSteps(
builder: ProjectFromSourcesBuilder,
projectDescriptor: ProjectDescriptor,
stepIcon: Icon?
): List<ModuleWizardStep> {
return listOf(CargoConfigurationWizardStep(builder.context) {
projectDescriptor.modules.firstOrNull()?.addConfigurationUpdater(it)
})
}
}
| mit | ce3323415560853ba4a52fafa2b52a08 | 36.716667 | 119 | 0.732656 | 4.95186 | false | false | false | false |
arcuri82/testing_security_development_enterprise_systems | advanced/graphql/news-graphql/src/main/kotlin/org/tsdes/advanced/graphql/newsgraphql/resolver/MutationResolver.kt | 1 | 2849 | package org.tsdes.advanced.graphql.newsgraphql.resolver
import com.coxautodev.graphql.tools.GraphQLMutationResolver
import com.google.common.base.Throwables
import graphql.execution.DataFetcherResult
import graphql.servlet.GenericGraphQLError
import org.springframework.stereotype.Component
import org.tsdes.advanced.examplenews.NewsRepository
import org.tsdes.advanced.graphql.newsgraphql.type.InputNewsType
import org.tsdes.advanced.graphql.newsgraphql.type.InputUpdateNewsType
import javax.validation.ConstraintViolationException
@Component
class MutationResolver(
private val crud: NewsRepository
) : GraphQLMutationResolver {
fun createNews(input: InputNewsType): DataFetcherResult<String> {
val id = try {
/*
the fields in 'input' cannot be null, because, if they were,
this code would never be reached, as validation already failed
when parsing the GraphQL request
*/
crud.createNews(input.authorId!!, input.text!!, input.country!!)
} catch (e: Exception) {
val cause = Throwables.getRootCause(e)
val msg = if (cause is ConstraintViolationException) {
"Violated constraints: ${cause.message}"
}else {
"${e.javaClass}: ${e.message}"
}
return DataFetcherResult<String>("", listOf(GenericGraphQLError(msg)))
}
return DataFetcherResult(id.toString(), listOf())
}
fun updateNewsById(pathId: String, input: InputUpdateNewsType): DataFetcherResult<Boolean> {
val id: Long
try {
id = pathId.toLong()
} catch (e: Exception) {
return DataFetcherResult<Boolean>(false, listOf(
GenericGraphQLError("No News with id $pathId exists")))
}
if (!crud.existsById(id)) {
return DataFetcherResult<Boolean>(false, listOf(
GenericGraphQLError("No News with id $id exists")))
}
try {
crud.update(id, input.text!!, input.authorId!!, input.country!!, input.creationTime!!)
} catch (e: Exception) {
val cause = Throwables.getRootCause(e)
if (cause is ConstraintViolationException) {
return DataFetcherResult<Boolean>(false, listOf(
GenericGraphQLError("Violated constraints: ${cause.message}")))
}
throw e
}
return DataFetcherResult(true, listOf())
}
fun deleteNewsById(pathId: String): Boolean {
val id: Long
try {
id = pathId.toLong()
} catch (e: Exception) {
return false
}
if (!crud.existsById(id)) {
return false
}
crud.deleteById(id)
return true
}
} | lgpl-3.0 | 09fab0ad4d211c7f9d4e0803842c0620 | 31.758621 | 98 | 0.614602 | 4.946181 | false | false | false | false |
androidx/androidx | samples/Support4Demos/src/main/java/com/example/android/supportv4/view/WindowInsetsControllerPlayground.kt | 3 | 21683 | /*
* Copyright 2020 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.
*/
@file:Suppress("DEPRECATION")
package com.example.android.supportv4.view
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.ViewGroup
import android.view.WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
import android.view.animation.LinearInterpolator
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.CheckBox
import android.widget.Spinner
import android.widget.TextView
import android.widget.ToggleButton
import androidx.annotation.RequiresApi
import androidx.core.graphics.Insets
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsAnimationCompat
import androidx.core.view.WindowInsetsAnimationControlListenerCompat
import androidx.core.view.WindowInsetsAnimationControllerCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsCompat.Type.ime
import androidx.core.view.WindowInsetsCompat.Type.navigationBars
import androidx.core.view.WindowInsetsCompat.Type.statusBars
import androidx.core.view.WindowInsetsCompat.Type.systemBars
import androidx.core.view.WindowInsetsControllerCompat
import com.example.android.supportv4.R
import java.util.ArrayList
import kotlin.concurrent.thread
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
@SuppressLint("InlinedApi")
@RequiresApi(21)
class WindowInsetsControllerPlayground : Activity() {
private val TAG: String = "WindowInsets_Playground"
val mTransitions = ArrayList<Transition>()
var currentType: Int? = null
private lateinit var mRoot: View
private lateinit var editRow: ViewGroup
private lateinit var visibility: TextView
private lateinit var buttonsRow: ViewGroup
private lateinit var buttonsRow2: ViewGroup
private lateinit var fitSystemWindow: CheckBox
private lateinit var isDecorView: CheckBox
internal lateinit var info: TextView
lateinit var graph: View
val values = mutableListOf(0f)
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_insets_controller)
setActionBar(findViewById(R.id.toolbar))
mRoot = findViewById(R.id.root)
editRow = findViewById(R.id.editRow)
visibility = findViewById(R.id.visibility)
buttonsRow = findViewById(R.id.buttonRow)
buttonsRow2 = findViewById(R.id.buttonRow2)
info = findViewById(R.id.info)
fitSystemWindow = findViewById(R.id.decorFitsSystemWindows)
isDecorView = findViewById(R.id.isDecorView)
addPlot()
WindowCompat.setDecorFitsSystemWindows(window, fitSystemWindow.isChecked)
WindowCompat.getInsetsController(window, window.decorView).systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
Log.e(
TAG,
"FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS: " + (
window.attributes.flags and
FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS != 0
)
)
fitSystemWindow.apply {
isChecked = false
setOnCheckedChangeListener { _, isChecked ->
WindowCompat.setDecorFitsSystemWindows(window, isChecked)
if (isChecked) {
mRoot.setPadding(0, 0, 0, 0)
}
}
}
mTransitions.add(Transition(findViewById(R.id.scrollView)))
mTransitions.add(Transition(editRow))
setupTypeSpinner()
setupHideShowButtons()
setupAppearanceButtons()
setupBehaviorSpinner()
setupLayoutButton()
setupIMEAnimation()
setupActionButton()
isDecorView.setOnCheckedChangeListener { _, _ ->
setupIMEAnimation()
}
}
private fun addPlot() {
val stroke = 20
val p2 = Paint()
p2.color = Color.RED
p2.strokeWidth = 1f
p2.style = Paint.Style.FILL
graph = object : View(this) {
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val mx = (values.maxOrNull() ?: 0f) + 1
val mn = values.minOrNull() ?: 0f
val ct = values.size.toFloat()
val h = height - stroke * 2
val w = width - stroke * 2
values.forEachIndexed { i, f ->
val x = (i / ct) * w + stroke
val y = ((f - mn) / (mx - mn)) * h + stroke
canvas.drawCircle(x, y, stroke.toFloat(), p2)
}
}
}
graph.minimumWidth = 300
graph.minimumHeight = 100
graph.setBackgroundColor(Color.GRAY)
findViewById<ViewGroup>(R.id.graph_container).addView(
graph,
ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 200)
)
}
private fun setupAppearanceButtons() {
mapOf<String, (Boolean) -> Unit>(
"LIGHT_NAV" to { isLight ->
WindowCompat.getInsetsController(window, mRoot).isAppearanceLightNavigationBars =
isLight
},
"LIGHT_STAT" to { isLight ->
WindowCompat.getInsetsController(window, mRoot).isAppearanceLightStatusBars =
isLight
},
).forEach { (name, callback) ->
buttonsRow.addView(
ToggleButton(this).apply {
text = name
textOn = text
textOff = text
setOnCheckedChangeListener { _, isChecked -> callback(isChecked) }
isChecked = true
callback(true)
}
)
}
}
private var visibilityThreadRunning = true
@SuppressLint("SetTextI18n")
override fun onResume() {
super.onResume()
thread {
visibilityThreadRunning = true
while (visibilityThreadRunning) {
visibility.post {
visibility.text = currentType?.let {
ViewCompat.getRootWindowInsets(mRoot)?.isVisible(it).toString()
} + " " + window.attributes.flags + " " + SystemClock.elapsedRealtime()
}
Thread.sleep(500)
}
}
}
override fun onPause() {
super.onPause()
visibilityThreadRunning = false
}
private fun setupActionButton() {
findViewById<View>(R.id.floating_action_button).setOnClickListener { v: View? ->
WindowCompat.getInsetsController(window, v!!).controlWindowInsetsAnimation(
ime(), -1, LinearInterpolator(), null /* cancellationSignal */,
object : WindowInsetsAnimationControlListenerCompat {
override fun onReady(
controller: WindowInsetsAnimationControllerCompat,
types: Int
) {
val anim =
ValueAnimator.ofFloat(0f, 1f)
anim.duration = 1500
anim.addUpdateListener { animation: ValueAnimator ->
controller.setInsetsAndAlpha(
controller.shownStateInsets,
animation.animatedValue as Float,
anim.animatedFraction
)
}
anim.addListener(
object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
super.onAnimationEnd(animation)
controller.finish(true)
}
})
anim.start()
}
override fun onCancelled(
controller: WindowInsetsAnimationControllerCompat?
) {
}
override fun onFinished(
controller: WindowInsetsAnimationControllerCompat
) {
}
}
)
}
}
private fun setupIMEAnimation() {
mRoot.setOnTouchListener(createOnTouchListener())
if (isDecorView.isChecked) {
ViewCompat.setWindowInsetsAnimationCallback(mRoot, null)
ViewCompat.setWindowInsetsAnimationCallback(window.decorView, createAnimationCallback())
// Why it doesn't work on the root view?
} else {
ViewCompat.setWindowInsetsAnimationCallback(window.decorView, null)
ViewCompat.setWindowInsetsAnimationCallback(mRoot, createAnimationCallback())
}
}
private fun createAnimationCallback(): WindowInsetsAnimationCompat.Callback {
return object : WindowInsetsAnimationCompat.Callback(DISPATCH_MODE_STOP) {
override fun onPrepare(animation: WindowInsetsAnimationCompat) {
mTransitions.forEach { it.onPrepare(animation) }
}
override fun onProgress(
insets: WindowInsetsCompat,
runningAnimations: List<WindowInsetsAnimationCompat>
): WindowInsetsCompat {
val systemInsets = insets.getInsets(systemBars())
mRoot.setPadding(
systemInsets.left, systemInsets.top, systemInsets.right,
systemInsets.bottom
)
mTransitions.forEach { it.onProgress(insets) }
return insets
}
override fun onStart(
animation: WindowInsetsAnimationCompat,
bounds: WindowInsetsAnimationCompat.BoundsCompat
): WindowInsetsAnimationCompat.BoundsCompat {
mTransitions.forEach { obj -> obj.onStart() }
return bounds
}
override fun onEnd(animation: WindowInsetsAnimationCompat) {
mTransitions.forEach { it.onFinish(animation) }
}
}
}
private fun setupHideShowButtons() {
findViewById<Button>(R.id.btn_show).apply {
setOnClickListener { view ->
currentType?.let { type ->
WindowCompat.getInsetsController(window, view).show(type)
}
}
}
findViewById<Button>(R.id.btn_hide).apply {
setOnClickListener { view ->
currentType?.let { type ->
WindowCompat.getInsetsController(window, view).hide(type)
}
}
}
}
private fun setupLayoutButton() {
arrayOf(
"STABLE" to View.SYSTEM_UI_FLAG_LAYOUT_STABLE,
"STAT" to View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN,
"NAV" to View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
).forEach { (name, flag) ->
buttonsRow2.addView(
ToggleButton(this).apply {
text = name
textOn = text
textOff = text
setOnCheckedChangeListener { _, isChecked ->
val systemUiVisibility = window.decorView.systemUiVisibility
window.decorView.systemUiVisibility =
if (isChecked) systemUiVisibility or flag
else systemUiVisibility and flag.inv()
}
isChecked = false
}
)
}
window.decorView.systemUiVisibility = window.decorView.systemUiVisibility and (
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
)
.inv()
}
private fun createOnTouchListener(): View.OnTouchListener {
return object : View.OnTouchListener {
private val mViewConfiguration =
ViewConfiguration.get(this@WindowInsetsControllerPlayground)
var mAnimationController: WindowInsetsAnimationControllerCompat? = null
var mCurrentRequest: WindowInsetsAnimationControlListenerCompat? = null
var mRequestedController = false
var mDown = 0f
var mCurrent = 0f
var mDownInsets = Insets.NONE
var mShownAtDown = false
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(
v: View,
event: MotionEvent
): Boolean {
mCurrent = event.y
when (event.action) {
MotionEvent.ACTION_DOWN -> {
mDown = event.y
val rootWindowInsets = ViewCompat.getRootWindowInsets(v)!!
mDownInsets = rootWindowInsets.getInsets(ime())
mShownAtDown = rootWindowInsets.isVisible(ime())
mRequestedController = false
mCurrentRequest = null
}
MotionEvent.ACTION_MOVE -> {
if (mAnimationController != null) {
updateInset()
} else if (abs(mDown - event.y) > mViewConfiguration.scaledTouchSlop &&
!mRequestedController
) {
mRequestedController = true
val listener = object : WindowInsetsAnimationControlListenerCompat {
override fun onReady(
controller: WindowInsetsAnimationControllerCompat,
types: Int
) {
if (mCurrentRequest === this) {
mAnimationController = controller
updateInset()
} else {
controller.finish(mShownAtDown)
}
}
override fun onFinished(
controller: WindowInsetsAnimationControllerCompat
) {
mAnimationController = null
}
override fun onCancelled(
controller: WindowInsetsAnimationControllerCompat?
) {
mAnimationController = null
}
}
mCurrentRequest = listener
WindowCompat
.getInsetsController(window, v)
.controlWindowInsetsAnimation(
ime(),
1000,
LinearInterpolator(),
null /* cancellationSignal */,
listener
)
}
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
if (mAnimationController != null) {
val isCancel =
event.action == MotionEvent.ACTION_CANCEL
mAnimationController!!.finish(
if (isCancel) mShownAtDown else !mShownAtDown
)
mAnimationController = null
}
mRequestedController = false
mCurrentRequest = null
}
}
return true
}
fun updateInset() {
var inset = (mDownInsets.bottom + (mDown - mCurrent)).toInt()
val hidden = mAnimationController!!.hiddenStateInsets.bottom
val shown = mAnimationController!!.shownStateInsets.bottom
val start = if (mShownAtDown) shown else hidden
val end = if (mShownAtDown) hidden else shown
inset = max(inset, hidden)
inset = min(inset, shown)
mAnimationController!!.setInsetsAndAlpha(
Insets.of(0, 0, 0, inset),
1f, (inset - start) / (end - start).toFloat()
)
}
}
}
private fun setupTypeSpinner() {
val types = mapOf(
"System" to systemBars(),
"IME" to ime(),
"Navigation" to navigationBars(),
"Status" to statusBars(),
"All" to (systemBars() or ime())
)
findViewById<Spinner>(R.id.spn_insets_type).apply {
adapter = ArrayAdapter(
context, android.R.layout.simple_spinner_dropdown_item,
types.keys.toTypedArray()
)
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
if (parent != null) {
currentType = types[parent.selectedItem]
}
}
}
}
}
private fun setupBehaviorSpinner() {
val types = mapOf(
"BY TOUCH" to WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_TOUCH,
"BY SWIPE" to WindowInsetsControllerCompat.BEHAVIOR_SHOW_BARS_BY_SWIPE,
"TRANSIENT" to WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE,
)
findViewById<Spinner>(R.id.spn_behavior).apply {
adapter = ArrayAdapter(
context, android.R.layout.simple_spinner_dropdown_item,
types.keys.toTypedArray()
)
onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
if (parent != null && view != null) {
WindowCompat.getInsetsController(window, view)
.systemBarsBehavior = types[selectedItem]!!
}
}
}
setSelection(0)
}
}
inner class Transition(private val view: View) {
private var mEndBottom = 0
private var mStartBottom = 0
private var mInsetsAnimation: WindowInsetsAnimationCompat? = null
private val debug = view.id == R.id.editRow
@SuppressLint("SetTextI18n")
fun onPrepare(animation: WindowInsetsAnimationCompat) {
if (animation.typeMask and ime() != 0) {
mInsetsAnimation = animation
}
mStartBottom = view.bottom
if (debug) {
values.clear()
info.text = "Prepare: start=$mStartBottom, end=$mEndBottom"
}
}
fun onProgress(insets: WindowInsetsCompat) {
view.y = (mStartBottom + insets.getInsets(ime() or systemBars()).bottom).toFloat()
if (debug) {
Log.d(TAG, view.y.toString())
values.add(view.y)
graph.invalidate()
}
}
@SuppressLint("SetTextI18n")
fun onStart() {
mEndBottom = view.bottom
if (debug) {
info.text = "${info.text}\nStart: start=$mStartBottom, end=$mEndBottom"
}
}
fun onFinish(animation: WindowInsetsAnimationCompat) {
if (mInsetsAnimation == animation) {
mInsetsAnimation = null
}
}
}
} | apache-2.0 | db1a822fa76366932568379286d381ec | 37.721429 | 100 | 0.537748 | 5.994747 | false | false | false | false |
androidx/androidx | compose/ui/ui-tooling/src/androidMain/kotlin/androidx/compose/ui/tooling/animation/clock/AnimateXAsStateClock.kt | 3 | 7218 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.tooling.animation.clock
import androidx.compose.animation.core.AnimationVector
import androidx.compose.animation.core.TargetBasedAnimation
import androidx.compose.animation.tooling.ComposeAnimatedProperty
import androidx.compose.animation.tooling.TransitionInfo
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.animation.AnimateXAsStateComposeAnimation
import androidx.compose.ui.tooling.animation.states.TargetState
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
/**
* [ComposeAnimationClock] for [AnimateXAsStateComposeAnimation].
*/
internal class AnimateXAsStateClock<T, V : AnimationVector>(
override val animation: AnimateXAsStateComposeAnimation<T, V>
) :
ComposeAnimationClock<AnimateXAsStateComposeAnimation<T, V>, TargetState<T>> {
override var state = TargetState(
animation.animationObject.value,
animation.animationObject.value
)
set(value) {
field = value
currAnimation = getCurrentAnimation()
setClockTime(0)
}
private var currentValue: T = animation.toolingState.value
private set(value) {
field = value
animation.toolingState.value = value
}
private var currAnimation: TargetBasedAnimation<T, V> = getCurrentAnimation()
@Suppress("UNCHECKED_CAST")
override fun setStateParameters(par1: Any, par2: Any?) {
fun parametersAreValid(par1: Any?, par2: Any?): Boolean {
return currentValue != null &&
par1 != null && par2 != null && par1::class == par2::class
}
fun parametersHasTheSameType(value: Any, par1: Any, par2: Any): Boolean {
return value::class == par1::class && value::class == par2::class
}
if (!parametersAreValid(par1, par2)) return
if (parametersHasTheSameType(currentValue!!, par1, par2!!)) {
state = TargetState(par1 as T, par2 as T)
return
}
if (par1 is List<*> && par2 is List<*>) {
try {
state = when (currentValue) {
is IntSize -> TargetState(
IntSize(par1[0] as Int, par1[1] as Int),
IntSize(par2[0] as Int, par2[1] as Int)
)
is IntOffset -> TargetState(
IntOffset(par1[0] as Int, par1[1] as Int),
IntOffset(par2[0] as Int, par2[1] as Int)
)
is Size -> TargetState(
Size(par1[0] as Float, par1[1] as Float),
Size(par2[0] as Float, par2[1] as Float)
)
is Offset -> TargetState(
Offset(par1[0] as Float, par1[1] as Float),
Offset(par2[0] as Float, par2[1] as Float)
)
is Rect ->
TargetState(
Rect(
par1[0] as Float,
par1[1] as Float,
par1[2] as Float,
par1[3] as Float
),
Rect(
par2[0] as Float,
par2[1] as Float,
par2[2] as Float,
par2[3] as Float
),
)
is Color -> TargetState(
Color(
par1[0] as Float,
par1[1] as Float,
par1[2] as Float,
par1[3] as Float
),
Color(
par2[0] as Float,
par2[1] as Float,
par2[2] as Float,
par2[3] as Float
),
)
is Dp -> {
if (parametersHasTheSameType(currentValue!!, par1[0]!!, par2[0]!!))
TargetState(par1[0], par2[0]) else TargetState(
(par1[0] as Float).dp, (par2[0] as Float).dp
)
}
else -> {
if (parametersAreValid(par1[0], par2[0]) &&
parametersHasTheSameType(currentValue!!, par1[0]!!, par2[0]!!)
) TargetState(par1[0], par2[0])
else return
}
} as TargetState<T>
} catch (_: IndexOutOfBoundsException) {
return
} catch (_: ClassCastException) {
return
} catch (_: IllegalArgumentException) {
return
} catch (_: NullPointerException) {
return
}
}
}
override fun getAnimatedProperties(): List<ComposeAnimatedProperty> {
return listOf(ComposeAnimatedProperty(animation.label, currentValue as Any))
}
override fun getMaxDurationPerIteration(): Long {
return nanosToMillis(currAnimation.durationNanos)
}
override fun getMaxDuration(): Long {
return nanosToMillis(currAnimation.durationNanos)
}
override fun getTransitions(stepMillis: Long): List<TransitionInfo> {
return listOf(
currAnimation.createTransitionInfo(
animation.label, animation.animationSpec, stepMillis
)
)
}
private var clockTimeNanos = 0L
set(value) {
field = value
currentValue = currAnimation.getValueFromNanos(value)
}
override fun setClockTime(animationTimeNanos: Long) {
clockTimeNanos = animationTimeNanos
}
private fun getCurrentAnimation(): TargetBasedAnimation<T, V> {
return TargetBasedAnimation(
animationSpec = animation.animationSpec,
initialValue = state.initial,
targetValue = state.target,
typeConverter = animation.animationObject.typeConverter,
initialVelocity = animation.animationObject.velocity
)
}
} | apache-2.0 | 79483753b1e2744f82de817ef5f2a52b | 35.64467 | 91 | 0.53422 | 4.9745 | false | false | false | false |
Soya93/Extract-Refactoring | platform/built-in-server/src/org/jetbrains/io/jsonRpc/JsonRpcServer.kt | 4 | 10969 | package org.jetbrains.io.jsonRpc
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.TypeAdapter
import com.google.gson.TypeAdapterFactory
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NotNullLazyValue
import com.intellij.util.ArrayUtil
import com.intellij.util.ArrayUtilRt
import com.intellij.util.Consumer
import com.intellij.util.SmartList
import gnu.trove.THashMap
import gnu.trove.TIntArrayList
import io.netty.buffer.*
import org.jetbrains.concurrency.Promise
import org.jetbrains.io.JsonReaderEx
import org.jetbrains.io.JsonUtil
import org.jetbrains.io.releaseIfError
import java.io.IOException
import java.lang.reflect.Method
import java.util.concurrent.atomic.AtomicInteger
private val LOG = Logger.getInstance(JsonRpcServer::class.java)
private val INT_LIST_TYPE_ADAPTER_FACTORY = object : TypeAdapterFactory {
private var typeAdapter: IntArrayListTypeAdapter<TIntArrayList>? = null
override fun <T> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? {
if (type.type !== TIntArrayList::class.java) {
return null
}
if (typeAdapter == null) {
typeAdapter = IntArrayListTypeAdapter<TIntArrayList>()
}
@Suppress("CAST_NEVER_SUCCEEDS")
return typeAdapter as TypeAdapter<T>?
}
}
private val gson by lazy {
GsonBuilder()
.registerTypeAdapterFactory(INT_LIST_TYPE_ADAPTER_FACTORY)
.disableHtmlEscaping()
.create()
}
class JsonRpcServer(private val clientManager: ClientManager) : MessageServer {
private val messageIdCounter = AtomicInteger()
private val domains = THashMap<String, NotNullLazyValue<*>>()
fun registerDomain(name: String, commands: NotNullLazyValue<*>, overridable: Boolean = false, disposable: Disposable? = null) {
if (domains.containsKey(name)) {
if (overridable) {
return
}
else {
throw IllegalArgumentException("$name is already registered")
}
}
domains.put(name, commands)
if (disposable != null) {
Disposer.register(disposable, Disposable { domains.remove(name) })
}
}
override fun messageReceived(client: Client, message: CharSequence) {
if (LOG.isDebugEnabled) {
LOG.debug("IN $message")
}
val reader = JsonReaderEx(message)
reader.beginArray()
val messageId = if (reader.peek() == JsonToken.NUMBER) reader.nextInt() else -1
val domainName = reader.nextString()
if (domainName.length == 1) {
val promise = client.messageCallbackMap.remove(messageId)
if (domainName[0] == 'r') {
if (promise == null) {
LOG.error("Response with id $messageId was already processed")
return
}
promise.setResult(JsonUtil.nextAny(reader))
}
else {
promise!!.setError("error")
}
return
}
val domainHolder = domains[domainName]
if (domainHolder == null) {
processClientError(client, "Cannot find domain $domainName", messageId)
return
}
val domain = domainHolder.value
val command = reader.nextString()
if (domain is JsonServiceInvocator) {
domain.invoke(command, client, reader, messageId, message)
return
}
val parameters: Array<Any>
if (reader.hasNext()) {
val list = SmartList<Any>()
JsonUtil.readListBody(reader, list)
parameters = ArrayUtil.toObjectArray(list)
}
else {
parameters = ArrayUtilRt.EMPTY_OBJECT_ARRAY
}
val isStatic = domain is Class<*>
val methods: Array<Method>
if (isStatic) {
methods = (domain as Class<*>).declaredMethods
}
else {
methods = domain.javaClass.methods
}
for (method in methods) {
if (method.name == command) {
method.isAccessible = true
val result = method.invoke(if (isStatic) null else domain, *parameters)
if (messageId != -1) {
if (result is ByteBuf) {
result.releaseIfError {
client.send(encodeMessage(client.byteBufAllocator, messageId, rawData = result))
}
}
else {
client.send(encodeMessage(client.byteBufAllocator, messageId, params = if (result == null) ArrayUtil.EMPTY_OBJECT_ARRAY else arrayOf(result)))
}
}
return
}
}
processClientError(client, "Cannot find method $domain.$command", messageId)
}
private fun processClientError(client: Client, error: String, messageId: Int) {
try {
LOG.error(error)
}
finally {
if (messageId != -1) {
sendErrorResponse(client, messageId, error)
}
}
}
fun sendResponse(client: Client, messageId: Int, rawData: ByteBuf? = null) {
client.send(encodeMessage(client.byteBufAllocator, messageId, rawData = rawData))
}
fun sendErrorResponse(client: Client, messageId: Int, message: CharSequence?) {
client.send(encodeMessage(client.byteBufAllocator, messageId, "e", params = arrayOf(message)))
}
fun sendWithRawPart(client: Client, domain: String, command: String, rawData: ByteBuf, params: Array<*>): Boolean {
return client.send(encodeMessage(client.byteBufAllocator, -1, domain, command, rawData = rawData, params = params)).cause() == null
}
fun send(client: Client, domain: String, command: String, vararg params: Any?) {
client.send(encodeMessage(client.byteBufAllocator, -1, domain, command, params = params))
}
fun <T> call(client: Client, domain: String, command: String, vararg params: Any?): Promise<T> {
val messageId = messageIdCounter.andIncrement
val message = encodeMessage(client.byteBufAllocator, messageId, domain, command, params = params)
return client.send(messageId, message)!!
}
fun send(domain: String, command: String, vararg params: Any?) {
if (clientManager.hasClients()) {
val messageId = -1
val message = encodeMessage(ByteBufAllocator.DEFAULT, messageId, domain, command, params = params)
clientManager.send<Any?>(messageId, message)
}
}
private fun encodeMessage(byteBufAllocator: ByteBufAllocator,
messageId: Int = -1,
domain: String? = null,
command: String? = null,
rawData: ByteBuf? = null,
params: Array<*> = ArrayUtil.EMPTY_OBJECT_ARRAY): ByteBuf {
val buffer = doEncodeMessage(byteBufAllocator, messageId, domain, command, params, rawData)
if (LOG.isDebugEnabled) {
LOG.debug("OUT ${buffer.toString(Charsets.UTF_8)}")
}
return buffer
}
private fun doEncodeMessage(byteBufAllocator: ByteBufAllocator,
id: Int,
domain: String?,
command: String?,
params: Array<*>,
rawData: ByteBuf?): ByteBuf {
var buffer = byteBufAllocator.ioBuffer()
buffer.writeByte('[')
var sb: StringBuilder? = null
if (id != -1) {
sb = StringBuilder()
buffer.writeAscii(sb.append(id))
sb.setLength(0)
}
if (domain != null) {
if (id != -1) {
buffer.writeByte(',')
}
buffer.writeByte('"').writeAscii(domain).writeByte('"')
if (command != null) {
buffer.writeByte(',').writeByte('"').writeAscii(command).writeByte('"')
}
}
var effectiveBuffer = buffer
if (params.isNotEmpty() || rawData != null) {
buffer.writeByte(',').writeByte('[')
encodeParameters(buffer, params, sb)
if (rawData != null) {
if (params.isNotEmpty()) {
buffer.writeByte(',')
}
effectiveBuffer = byteBufAllocator.compositeBuffer().addComponent(buffer).addComponent(rawData)
buffer = byteBufAllocator.ioBuffer()
}
buffer.writeByte(']')
}
buffer.writeByte(']')
return effectiveBuffer.addBuffer(buffer)
}
private fun encodeParameters(buffer: ByteBuf, params: Array<*>, _sb: StringBuilder?) {
var sb = _sb
var writer: JsonWriter? = null
var hasPrev = false
for (param in params) {
if (hasPrev) {
buffer.writeByte(',')
}
else {
hasPrev = true
}
// gson - SOE if param has type class com.intellij.openapi.editor.impl.DocumentImpl$MyCharArray, so, use hack
if (param is CharSequence) {
JsonUtil.escape(param, buffer)
}
else if (param == null) {
buffer.writeAscii("null")
}
else if (param is Boolean) {
buffer.writeAscii(param.toString())
}
else if (param is Number) {
if (sb == null) {
sb = StringBuilder()
}
if (param is Int) {
sb.append(param.toInt())
}
else if (param is Long) {
sb.append(param.toLong())
}
else if (param is Float) {
sb.append(param.toFloat())
}
else if (param is Double) {
sb.append(param.toDouble())
}
else {
sb.append(param.toString())
}
buffer.writeAscii(sb)
sb.setLength(0)
}
else if (param is Consumer<*>) {
if (sb == null) {
sb = StringBuilder()
}
@Suppress("UNCHECKED_CAST")
(param as Consumer<StringBuilder>).consume(sb)
ByteBufUtilEx.writeUtf8(buffer, sb)
sb.setLength(0)
}
else {
if (writer == null) {
writer = JsonWriter(ByteBufUtf8Writer(buffer))
}
(gson.getAdapter(param.javaClass) as TypeAdapter<Any>).write(writer, param)
}
}
}
}
private fun ByteBuf.writeByte(c: Char) = writeByte(c.toInt())
private fun ByteBuf.writeAscii(s: CharSequence): ByteBuf {
ByteBufUtil.writeAscii(this, s)
return this
}
private class IntArrayListTypeAdapter<T> : TypeAdapter<T>() {
override fun write(out: JsonWriter, value: T) {
var error: IOException? = null
out.beginArray()
(value as TIntArrayList).forEach { value ->
try {
out.value(value.toLong())
}
catch (e: IOException) {
error = e
}
error == null
}
error?.let { throw it }
out.endArray()
}
override fun read(`in`: com.google.gson.stream.JsonReader) = throw UnsupportedOperationException()
}
// addComponent always add sliced component, so, we must add last buffer only after all writes
private fun ByteBuf.addBuffer(buffer: ByteBuf): ByteBuf {
if (this !== buffer) {
(this as CompositeByteBuf).addComponent(buffer)
writerIndex(capacity())
}
return this
}
fun JsonRpcServer.registerFromEp() {
for (domainBean in JsonRpcDomainBean.EP_NAME.extensions) {
registerDomain(domainBean.name, domainBean.value, domainBean.overridable)
}
} | apache-2.0 | 958e85955545429038ea77b26775f5f3 | 30.076487 | 154 | 0.634789 | 4.385846 | false | false | false | false |
pedroSG94/rtmp-rtsp-stream-client-java | rtmp/src/main/java/com/pedro/rtmp/amf/v0/AmfLongString.kt | 1 | 1778 | /*
* Copyright (C) 2021 pedroSG94.
*
* 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.pedro.rtmp.amf.v0
import com.pedro.rtmp.utils.*
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import kotlin.jvm.Throws
/**
* Created by pedro on 19/07/22.
*
* A string encoded in UTF-8 where 4 first bytes indicate string size
*/
open class AmfLongString(var value: String = ""): AmfData() {
private var bodySize: Int = value.toByteArray(Charsets.UTF_8).size + 2
@Throws(IOException::class)
override fun readBody(input: InputStream) {
//read value size as UInt32
bodySize = input.readUInt32()
//read value in UTF-8
val bytes = ByteArray(bodySize)
bodySize += 2
input.readUntil(bytes)
value = String(bytes, Charsets.UTF_8)
}
@Throws(IOException::class)
override fun writeBody(output: OutputStream) {
val bytes = value.toByteArray(Charsets.UTF_8)
//write value size as UInt32. Value size not included
output.writeUInt32(bodySize - 2)
//write value bytes in UTF-8
output.write(bytes)
}
override fun getType(): AmfType = AmfType.LONG_STRING
override fun getSize(): Int = bodySize
override fun toString(): String {
return "AmfLongString value: $value"
}
} | apache-2.0 | 9fdd1f9d72a32dcda5c85e134e4a98a8 | 28.163934 | 75 | 0.715973 | 3.856833 | false | false | false | false |
EventFahrplan/EventFahrplan | app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/SessionViewColumnAdapter.kt | 1 | 1633 | package nerd.tuxmobil.fahrplan.congress.schedule
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.recyclerview.widget.RecyclerView
import nerd.tuxmobil.fahrplan.congress.R
import nerd.tuxmobil.fahrplan.congress.models.Session
internal interface SessionViewEventsHandler : View.OnCreateContextMenuListener, View.OnClickListener
internal class SessionViewColumnAdapter(
private val sessions: List<Session>,
private val layoutParamsBySession: Map<Session, LinearLayout.LayoutParams>,
private val drawer: SessionViewDrawer,
private val eventsHandler: SessionViewEventsHandler
) : RecyclerView.Adapter<SessionViewColumnAdapter.SessionViewHolder>() {
override fun onBindViewHolder(viewHolder: SessionViewHolder, position: Int) {
val session = sessions[position]
viewHolder.itemView.tag = session
viewHolder.itemView.layoutParams = layoutParamsBySession[session]
drawer.updateSessionView(viewHolder.itemView, session)
}
override fun getItemCount(): Int = sessions.size
override fun onCreateViewHolder(parent: ViewGroup, position: Int): SessionViewHolder {
val sessionLayout = LayoutInflater.from(parent.context).inflate(R.layout.session_layout, parent, false) as LinearLayout
sessionLayout.setOnCreateContextMenuListener(eventsHandler)
sessionLayout.setOnClickListener(eventsHandler)
return SessionViewHolder(sessionLayout)
}
class SessionViewHolder(sessionLayout: LinearLayout) : RecyclerView.ViewHolder(sessionLayout)
} | apache-2.0 | 519c764895b3c76513c13b40c4cd50bd | 43.162162 | 127 | 0.791182 | 5.233974 | false | false | false | false |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/notes/dto/NotesNote.kt | 1 | 2862 | /**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.notes.dto
import com.google.gson.annotations.SerializedName
import com.vk.dto.common.id.UserId
import com.vk.sdk.api.base.dto.BaseBoolInt
import kotlin.Int
import kotlin.String
import kotlin.collections.List
/**
* @param comments - Comments number
* @param date - Date when the note has been created in Unixtime
* @param id - Note ID
* @param ownerId - Note owner's ID
* @param title - Note title
* @param viewUrl - URL of the page with note preview
* @param readComments
* @param canComment - Information whether current user can comment the note
* @param text - Note text
* @param textWiki - Note text in wiki format
* @param privacyView
* @param privacyComment
*/
data class NotesNote(
@SerializedName("comments")
val comments: Int,
@SerializedName("date")
val date: Int,
@SerializedName("id")
val id: Int,
@SerializedName("owner_id")
val ownerId: UserId,
@SerializedName("title")
val title: String,
@SerializedName("view_url")
val viewUrl: String,
@SerializedName("read_comments")
val readComments: Int? = null,
@SerializedName("can_comment")
val canComment: BaseBoolInt? = null,
@SerializedName("text")
val text: String? = null,
@SerializedName("text_wiki")
val textWiki: String? = null,
@SerializedName("privacy_view")
val privacyView: List<String>? = null,
@SerializedName("privacy_comment")
val privacyComment: List<String>? = null
)
| mit | 4483c4ba9e4478ef46a121a98ddce5c3 | 36.657895 | 81 | 0.686233 | 4.290855 | false | false | false | false |
jeffgbutler/mybatis-dynamic-sql | src/test/kotlin/examples/kotlin/mybatis3/canonical/PersonWithAddressMapper.kt | 1 | 3120 | /*
* Copyright 2016-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 examples.kotlin.mybatis3.canonical
import org.apache.ibatis.annotations.Mapper
import org.apache.ibatis.annotations.Result
import org.apache.ibatis.annotations.ResultMap
import org.apache.ibatis.annotations.Results
import org.apache.ibatis.annotations.SelectProvider
import org.apache.ibatis.type.EnumOrdinalTypeHandler
import org.apache.ibatis.type.JdbcType
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider
import org.mybatis.dynamic.sql.util.SqlProviderAdapter
/**
*
* This is a mapper that shows coding a join
*
*/
@Mapper
interface PersonWithAddressMapper {
@SelectProvider(type = SqlProviderAdapter::class, method = "select")
@Results(
id = "PersonWithAddressResult",
value = [
Result(column = "A_ID", property = "id", jdbcType = JdbcType.INTEGER, id = true),
Result(column = "first_name", property = "firstName", jdbcType = JdbcType.VARCHAR),
Result(
column = "last_name",
property = "lastName",
jdbcType = JdbcType.VARCHAR,
typeHandler = LastNameTypeHandler::class
),
Result(column = "birth_date", property = "birthDate", jdbcType = JdbcType.DATE),
Result(
column = "employed",
property = "employed",
jdbcType = JdbcType.VARCHAR,
typeHandler = YesNoTypeHandler::class
),
Result(column = "occupation", property = "occupation", jdbcType = JdbcType.VARCHAR),
Result(column = "address_id", property = "address.id", jdbcType = JdbcType.INTEGER),
Result(column = "street_address", property = "address.streetAddress", jdbcType = JdbcType.VARCHAR),
Result(column = "city", property = "address.city", jdbcType = JdbcType.VARCHAR),
Result(column = "state", property = "address.state", jdbcType = JdbcType.CHAR),
Result(
column = "address_type",
property = "address.addressType",
jdbcType = JdbcType.INTEGER,
typeHandler = EnumOrdinalTypeHandler::class
)
]
)
fun selectMany(selectStatement: SelectStatementProvider): List<PersonWithAddress>
@SelectProvider(type = SqlProviderAdapter::class, method = "select")
@ResultMap("PersonWithAddressResult")
fun selectOne(selectStatement: SelectStatementProvider): PersonWithAddress?
}
| apache-2.0 | c7be915938ef480979c5aa1440880f4c | 41.739726 | 111 | 0.659295 | 4.608567 | false | false | false | false |
trife/Field-Book | app/src/main/java/com/fieldbook/tracker/database/dao/VisibleObservationVariableDao.kt | 1 | 3488 | package com.fieldbook.tracker.database.dao
import com.fieldbook.tracker.database.Migrator.Companion.sVisibleObservationVariableViewName
import com.fieldbook.tracker.database.Migrator.ObservationVariable
import com.fieldbook.tracker.database.Migrator.ObservationVariableAttribute
import com.fieldbook.tracker.database.models.ObservationVariableModel
import com.fieldbook.tracker.database.query
import com.fieldbook.tracker.database.toFirst
import com.fieldbook.tracker.database.toTable
import com.fieldbook.tracker.database.withDatabase
import com.fieldbook.tracker.objects.TraitObject
class VisibleObservationVariableDao {
companion object {
fun getVisibleTrait(): Array<String> = withDatabase { db ->
db.query(sVisibleObservationVariableViewName,
select = arrayOf("observation_variable_name"),
orderBy = "position").toTable().map { it ->
it["observation_variable_name"].toString()
}.toTypedArray()
} ?: emptyArray<String>()
// fun getVisibleTraitObjects(): Array<ObservationVariableModel> = withDatabase { db ->
//
// val rows = db.query(sVisibleObservationVariableViewName,
// orderBy = "position").toTable()
//
// val variables: Array<ObservationVariableModel?> = arrayOfNulls(rows.size)
//
// rows.forEachIndexed { index, map ->
//
// variables[index] = ObservationVariableModel(map)
//
// }
//
// variables.mapNotNull { it }.toTypedArray()
//
// } ?: emptyArray()
fun getFormat(): Array<String> = withDatabase { db ->
db.query(sVisibleObservationVariableViewName,
arrayOf(ObservationVariable.PK,
"observation_variable_field_book_format",
"position")).toTable().map { row ->
row["observation_variable_field_book_format"] as String
}.toTypedArray()
} ?: emptyArray()
// //todo switched name to 'getDetails'
// fun getDetails(trait: String): Array<ObservationVariableModel> = withDatabase { db ->
//
// arrayOf(*db.query(sVisibleObservationVariableViewName,
// where = "observation_variable_name LIKE $trait")
// .toTable().map {
// ObservationVariableModel(it)
// }.toTypedArray())
//
// } ?: arrayOf()
fun getDetail(trait: String): TraitObject? = withDatabase { db ->
//return a trait object but requires multiple queries to use the attr/values table.
ObservationVariableDao.getAllTraitObjects().first { it.trait == trait }.apply {
ObservationVariableValueDao.getVariableValues(id.toInt()).also { values ->
values?.forEach {
val attrName = ObservationVariableAttributeDao.getAttributeNameById(it[ObservationVariableAttribute.FK] as Int)
when (attrName) {
"validValuesMin" -> minimum = it["observation_variable_attribute_value"] as? String ?: ""
"validValuesMax" -> maximum = it["observation_variable_attribute_value"] as? String ?: ""
"category" -> categories = it["observation_variable_attribute_value"] as? String ?: ""
}
}
}
}
}
}
} | gpl-2.0 | 3e53a5f1c4cbd27dff894ad884d48e63 | 38.647727 | 135 | 0.603211 | 5.136966 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/codegen/propertyCallableReference/valExtension.kt | 1 | 196 | class A(y: Int) {
var x = y
}
val A.z get() = this.x
fun main(args: Array<String>) {
val p1 = A::z
println(p1.get(A(42)))
val a = A(117)
val p2 = a::z
println(p2.get())
} | apache-2.0 | c6e75d2bb5d74a7d7e6d8c5f2e7a3d64 | 14.153846 | 31 | 0.505102 | 2.305882 | false | false | false | false |
MrSugarCaney/DirtyArrows | src/main/kotlin/nl/sugcube/dirtyarrows/command/CommandVisualize.kt | 1 | 1330 | package nl.sugcube.dirtyarrows.command
import nl.sugcube.dirtyarrows.DirtyArrows
import nl.sugcube.dirtyarrows.region.showPositionMarkers
import nl.sugcube.dirtyarrows.region.showRegionMarkers
import nl.sugcube.dirtyarrows.util.sendError
import org.bukkit.command.CommandSender
/**
* @author SugarCaney
*/
open class CommandVisualize : SubCommand<DirtyArrows>(
name = "visualize",
usage = "/da visualize [region]",
argumentCount = 0,
description = "Shows the set positions, or the corners of the region."
) {
init {
addPermissions("dirtyarrows.admin")
addAutoCompleteMeta(0, AutoCompleteArgument.REGIONS)
}
override fun executeImpl(plugin: DirtyArrows, sender: CommandSender, vararg arguments: String) {
val regionName = arguments.firstOrNull()
// No region specified : show the current positions.
if (regionName == null) {
plugin.showPositionMarkers(5)
return
}
// Region specified
val region = plugin.regionManager.regionByName(regionName)
if (region == null) {
sender.sendError("There is no region with name '$regionName'")
return
}
plugin.showRegionMarkers(region, 5)
}
override fun assertSender(sender: CommandSender) = true
} | gpl-3.0 | 063393a007a7589f6c83b46899463e2d | 28.577778 | 100 | 0.675188 | 4.716312 | false | false | false | false |
MrSugarCaney/DirtyArrows | src/main/kotlin/nl/sugcube/dirtyarrows/bow/ability/AquaticBow.kt | 1 | 2674 | package nl.sugcube.dirtyarrows.bow.ability
import nl.sugcube.dirtyarrows.DirtyArrows
import nl.sugcube.dirtyarrows.bow.BowAbility
import nl.sugcube.dirtyarrows.bow.DefaultBow
import nl.sugcube.dirtyarrows.util.copyOf
import org.bukkit.Effect
import org.bukkit.GameMode
import org.bukkit.Material
import org.bukkit.entity.Arrow
import org.bukkit.entity.FallingBlock
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.entity.EntityChangeBlockEvent
import org.bukkit.event.entity.ProjectileLaunchEvent
import org.bukkit.inventory.ItemStack
import org.bukkit.material.MaterialData
/**
* Shoots a blob of water.
*
* @author SugarCaney
*/
open class AquaticBow(plugin: DirtyArrows) : BowAbility(
plugin = plugin,
type = DefaultBow.AQUATIC,
canShootInProtectedRegions = false,
protectionRange = 1.0,
costRequirements = listOf(ItemStack(Material.WATER_BUCKET, 1)),
description = "Shoot water."
) {
/**
* A particle will spawn from shot arrows every N ticks.
*/
val particleEveryNTicks = config.getInt("$node.particle-every-n-ticks")
/**
* Shot falling blocks mapped to their shooter.
*/
private val waterBlocks = HashMap<FallingBlock, Player>()
override fun launch(player: Player, arrow: Arrow, event: ProjectileLaunchEvent) {
val direction = arrow.velocity.copyOf().normalize()
// Spawn the lava block slightly in front of the player.
val spawnLocation = arrow.location.add(direction.multiply(1.5))
player.world.spawnFallingBlock(spawnLocation, MaterialData(Material.WATER)).apply {
velocity = arrow.velocity
dropItem = false
waterBlocks[this] = player
}
}
override fun particle(tickNumber: Int) {
if (tickNumber % particleEveryNTicks == 0) return
arrows.forEach {
it.world.playEffect(it.location.copyOf().add(0.5, 0.5, 0.5), Effect.STEP_SOUND, Material.WATER)
}
}
override fun Player.consumeBowItems() {
if (gameMode == GameMode.CREATIVE) return
// Empty the lava bucket.
inventory.firstOrNull { it?.type == Material.WATER_BUCKET }
?.let { it.type = Material.BUCKET }
}
@EventHandler
fun lavaBlockProtection(event: EntityChangeBlockEvent) {
val waterBlock = event.entity as? FallingBlock ?: return
val shooter = waterBlocks[waterBlock] ?: return
if (waterBlock.location.isInProtectedRegion(shooter)) {
event.isCancelled = true
waterBlocks.remove(waterBlock)
waterBlock.remove()
}
}
} | gpl-3.0 | 51b1e56fbb9093cd566c385de1232c2f | 32.024691 | 107 | 0.684742 | 4.251192 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/speech/SpeechOptions.kt | 2 | 1340 | package abi44_0_0.expo.modules.speech
import abi44_0_0.expo.modules.core.Promise
import java.util.*
data class SpeechOptions(
val language: String?,
val pitch: Float?,
val rate: Float?,
val voice: String?
) {
companion object {
fun optionsFromMap(options: Map<String, Any?>?, promise: Promise): SpeechOptions? {
if (options == null) {
return SpeechOptions(null, null, null, null)
}
val language = options["language"]?.let {
if (it is String) {
return@let it
}
promise.reject("ERR_INVALID_OPTION", "Language must be a string")
return null
}
val pitch = options["pitch"]?.let {
if (it is Number) {
return@let it.toFloat()
}
promise.reject("ERR_INVALID_OPTION", "Pitch must be a number")
return null
}
val rate = options["rate"]?.let {
if (it is Number) {
return@let it.toFloat()
}
promise.reject("ERR_INVALID_OPTION", "Rate must be a number")
return null
}
val voice = options["voice"]?.let {
if (it is String) {
return@let it
}
promise.reject("ERR_INVALID_OPTION", "Voice name must be a string")
return null
}
return SpeechOptions(language, pitch, rate, voice)
}
}
}
| bsd-3-clause | 386afd37b5d03e40caef2f132a4bdca5 | 22.103448 | 87 | 0.56791 | 4.024024 | false | false | false | false |
maurocchi/chesslave | backend/src/test/java/io/chesslave/eyes/PositionRecogniserTest.kt | 2 | 1539 | package io.chesslave.eyes
import io.chesslave.eyes.sikuli.SikuliVision
import io.chesslave.model.*
import io.chesslave.visual.rendering.BoardRenderer
import io.chesslave.visual.rendering.ChessSet
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
class PositionRecogniserTest(chessSet: ChessSet) : SinglePieceRecognitionTest(chessSet) {
lateinit var recogniser: PositionRecogniser
@Before
fun setUp() {
val initialPosition = Game.initialPosition().position()
val initialBoard = BoardRenderer(chessSet).withPosition(initialPosition).render()
val config = analyzeBoardImage(initialBoard.image)
this.recogniser = PositionRecogniser(SikuliVision(), config)
}
@Test
fun recognisePosition() {
val position = positionFromText(
"r|n|b|q|k|b|n|r",
"p|p| | |p|p|p|p",
" | | |p| | | | ",
" | | | | | | | ",
" | | |p|P| | | ",
" | | | | |N| | ",
"P|P|P| | |P|P|P",
"R|N|B|Q|K|B| |R")
val board = BoardRenderer(chessSet).withPosition(position).render()
val got = recogniser.position(board)
assertEquals(position, got)
}
override fun withPieceOnSquare(square: Square, piece: Piece) {
val position = Position.Builder().withPiece(square, piece).build()
val board = BoardRenderer(chessSet).withPosition(position).render()
val got = recogniser.position(board)
assertEquals(position, got)
}
} | gpl-2.0 | 31e4184e97fc7f463d3f8d4e1a0b2cd0 | 33.222222 | 89 | 0.631579 | 3.866834 | false | true | false | false |
PolymerLabs/arcs | java/arcs/sdk/EdgeHandles.kt | 1 | 4281 | package arcs.sdk
import arcs.core.entity.Handle
import arcs.core.entity.ReadCollectionHandle
import arcs.core.entity.ReadSingletonHandle
import arcs.core.entity.Storable
import arcs.core.entity.WriteCollectionHandle
import arcs.core.entity.WriteSingletonHandle
import kotlinx.coroutines.Job
import kotlinx.coroutines.withContext
/*
* To facilitate safe read/write access to data handles in running arcs, particles can be
* annotated with '@edge' in the manifest. This will cause the following set of changes to
* the code generation output:
* - The generated class will be concrete and final instead of an abstract base class.
* - The particle lifecycle will be managed internally to this class; clients will not have
* any access to lifecycle events.
* - Handles will be exposed via the Edge*Handle interfaces given below. All edge handle methods
* are asynchronous and may be invoked at any time after the particle has been created.
* - All read operations will suspend as required to await handle synchronization.
* - All write operations will be applied immediately to the local handle data model. They will
* return a Job that will be completed once the operation has been sent to the backing store
* for this handle; it is not required that join() is called on these jobs.
*
* Query handles are not supported at this time.
*/
interface EdgeReadSingletonHandle<E> {
suspend fun fetch(): E?
}
interface EdgeWriteSingletonHandle<I> {
suspend fun store(element: I): Job
suspend fun clear(): Job
}
interface EdgeReadWriteSingletonHandle<E, I> :
EdgeReadSingletonHandle<E>, EdgeWriteSingletonHandle<I>
interface EdgeReadCollectionHandle<E> {
suspend fun size(): Int
suspend fun isEmpty(): Boolean
suspend fun fetchAll(): Set<E>
suspend fun fetchById(entityId: String): E?
}
interface EdgeWriteCollectionHandle<I> {
suspend fun store(element: I): Job
suspend fun storeAll(elements: Collection<I>): Job
suspend fun clear(): Job
suspend fun remove(element: I): Job
suspend fun removeById(id: String): Job
}
interface EdgeReadWriteCollectionHandle<E, I> :
EdgeReadCollectionHandle<E>, EdgeWriteCollectionHandle<I>
/** Base class for the edge handle implementations. */
abstract class EdgeHandle {
// The "real" arc handle; assigned by setHandles() in the generated particle implementation.
lateinit var handle: Handle
private var ready = Job()
suspend fun <T> readOp(op: () -> T): T = withContext(handle.dispatcher) {
ready.join()
op()
}
suspend fun <T> writeOp(op: () -> T): T = withContext(handle.dispatcher) { op() }
// Invoked by onReady in the generated particle implementation.
fun moveToReady() {
ready.complete()
}
}
@Suppress("UNCHECKED_CAST")
class EdgeSingletonHandle<E : Storable, I : Storable> :
EdgeHandle(), EdgeReadWriteSingletonHandle<E, I> {
override suspend fun fetch() = readOp {
(handle as ReadSingletonHandle<E>).fetch()
}
override suspend fun store(element: I) = writeOp {
(handle as WriteSingletonHandle<I>).store(element)
}
override suspend fun clear() = writeOp {
(handle as WriteSingletonHandle<I>).clear()
}
}
@Suppress("UNCHECKED_CAST")
class EdgeCollectionHandle<E : Storable, I : Storable> :
EdgeHandle(), EdgeReadWriteCollectionHandle<E, I> {
private val readHandle: ReadCollectionHandle<E>
get() = handle as ReadCollectionHandle<E>
private val writeHandle: WriteCollectionHandle<I>
get() = handle as WriteCollectionHandle<I>
override suspend fun size() = readOp {
readHandle.size()
}
override suspend fun isEmpty() = readOp {
readHandle.isEmpty()
}
override suspend fun fetchAll() = readOp {
readHandle.fetchAll()
}
override suspend fun fetchById(entityId: String) = readOp {
readHandle.fetchById(entityId)
}
override suspend fun store(element: I) = writeOp {
writeHandle.store(element)
}
override suspend fun storeAll(elements: Collection<I>) = writeOp {
writeHandle.storeAll(elements)
}
override suspend fun clear() = writeOp {
writeHandle.clear()
}
override suspend fun remove(element: I) = writeOp {
writeHandle.remove(element)
}
override suspend fun removeById(id: String) = writeOp {
writeHandle.removeById(id)
}
}
| bsd-3-clause | b4bf9d2dd221b40d5bfa97c754928f0b | 29.361702 | 97 | 0.732773 | 4.255467 | false | false | false | false |
SourceUtils/hl2-toolkit | src/main/kotlin/com/timepath/hl2/io/demo/UserMessage.kt | 1 | 9755 | package com.timepath.hl2.io.demo
import com.timepath.io.BitBuffer
import com.timepath.toUnsigned
import java.awt.Color
import java.awt.Point
import java.util.LinkedList
/**
* @see [https://forums.alliedmods.net/showthread.php?t=163224](null)
* @see [https://github.com/LestaD/SourceEngine2007/blob/master/src_main/game/server/util.cpp.L1115](null)
* @see [https://github.com/LestaD/SourceEngine2007/blob/master/se2007/game/shared/hl2/hl2_usermessages.cpp](null)
* HookMessage, HOOK_HUD_MESSAGE, MsgFunc_
*/
public abstract class UserMessage(private val size: Int = -1) : PacketHandler {
override fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM, lengthBits: Int): Boolean = size == -1
object Geiger : UserMessage(1) {
override fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM, lengthBits: Int): Boolean {
l["Range"] = bb.getByte().toUnsigned() * 2
return true
}
}
object Train : UserMessage(1) {
override fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM, lengthBits: Int): Boolean {
l["Pos"] = bb.getByte()
return true
}
}
object HudText : UserMessage() {
override fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM, lengthBits: Int): Boolean {
l["Text"] = bb.getString()
return true
}
}
object SayText : UserMessage()
object SayText2 : UserMessage() {
override fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM, lengthBits: Int): Boolean {
val endBit = bb.positionBits() + lengthBits
val client = bb.getBits(8)
l["Client"] = client
// 0 - raw text, 1 - sets CHAT_FILTER_PUBLICCHAT
val isRaw = bb.getBits(8) != 0L
l["Raw"] = isRaw
// \x03 in the message for the team color of the specified clientid
val kind = bb.getString()
l["Kind"] = kind
val from = bb.getString()
l["From"] = from
val msg = bb.getString()
l["Text"] = msg
// This message can have two optional string parameters.
val args = LinkedList<String>()
while (bb.positionBits() < endBit) {
val arg = bb.getString()
args.add(arg)
}
l["Args"] = args
return true
}
}
object TextMsg : UserMessage() {
override fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM, lengthBits: Int): Boolean {
val destination = arrayOf("HUD_PRINTCONSOLE", "HUD_PRINTNOTIFY", "HUD_PRINTTALK", "HUD_PRINTCENTER")
val msgDest = bb.getByte()
l["Destination"] = destination[msgDest.toInt()]
l["Message"] = bb.getString()
// These seem to be disabled in TF2
// l.add(new Pair<Object, Object>("args[0]", bb.getString()));
// l.add(new Pair<Object, Object>("args[1]", bb.getString()));
// l.add(new Pair<Object, Object>("args[2]", bb.getString()));
// l.add(new Pair<Object, Object>("args[3]", bb.getString()));
return true
}
}
object ResetHUD : UserMessage(1)
object GameTitle : UserMessage(0)
object ItemPickup : UserMessage()
object ShowMenu : UserMessage()
object Shake : UserMessage(13)
object Fade : UserMessage(10)
object VGUIMenu : UserMessage()
object Rumble : UserMessage(3)
object CloseCaption : UserMessage()
object SendAudio : UserMessage()
object VoiceMask : UserMessage(17)
object RequestState : UserMessage(0)
object Damage : UserMessage()
object HintText : UserMessage()
object KeyHintText : UserMessage()
/**
* Position command $position x y
* x & y are from 0 to 1 to be screen resolution independent
* -1 means center in each dimension
* Effect command $effect
* effect 0 is fade in/fade out
* effect 1 is flickery credits
* effect 2 is write out (training room)
* Text color r g b command $color
* Text color r g b command $color2
* fadein time fadeout time / hold time
* $fadein (message fade in time - per character in effect 2)
* $fadeout (message fade out time)
* $holdtime (stay on the screen for this long)
*/
object HudMsg : UserMessage() {
override fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM, lengthBits: Int): Boolean {
val pos = Point(bb.getByte().toInt(), bb.getByte().toInt())
val color = Color(bb.getByte().toInt(), bb.getByte().toInt(), bb.getByte().toInt(), bb.getByte().toInt())
val color2 = Color(bb.getByte().toInt(), bb.getByte().toInt(), bb.getByte().toInt(), bb.getByte().toInt())
val effect = bb.getByte().toFloat()
val fadein = bb.getFloat()
val fadeout = bb.getFloat()
val holdtime = bb.getFloat()
val fxtime = bb.getFloat()
l["Text"] = bb.getString()
return true
}
private val MAX_NETMESSAGE = 6
}
object AmmoDenied : UserMessage(2) {
override fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM, lengthBits: Int): Boolean {
l["Ammo"] = bb.getShort().toUnsigned()
return true
}
}
object AchievementEvent : UserMessage()
object UpdateRadar : UserMessage()
object VoiceSubtitle : UserMessage(3)
object HudNotify : UserMessage(1)
object HudNotifyCustom : UserMessage()
object PlayerStatsUpdate : UserMessage()
object PlayerIgnited : UserMessage(3)
object PlayerIgnitedInv : UserMessage(3)
object HudArenaNotify : UserMessage(2)
object UpdateAchievement : UserMessage()
object TrainingMsg : UserMessage()
object TrainingObjective : UserMessage()
object DamageDodged : UserMessage()
object PlayerJarated : UserMessage(2)
object PlayerExtinguished : UserMessage(2)
object PlayerJaratedFade : UserMessage(2)
object PlayerShieldBlocked : UserMessage(2)
object BreakModel : UserMessage()
object CheapBreakModel : UserMessage()
object BreakModel_Pumpkin : UserMessage()
object BreakModelRocketDud : UserMessage()
object CallVoteFailed : UserMessage()
object VoteStart : UserMessage()
object VotePass : UserMessage()
object VoteFailed : UserMessage(2)
object VoteSetup : UserMessage()
object PlayerBonusPoints : UserMessage(3)
object SpawnFlyingBird : UserMessage()
object PlayerGodRayEffect : UserMessage()
object SPHapWeapEvent : UserMessage(4)
object HapDmg : UserMessage()
object HapPunch : UserMessage()
object HapSetDrag : UserMessage()
object HapSetConst : UserMessage()
object HapMeleeContact : UserMessage(0)
companion object {
fun read(bb: BitBuffer, l: TupleMap<Any, Any>, demo: HL2DEM): Boolean {
val msgType = bb.getByte().toInt()
val m = UserMessage[msgType]
l["Message"] = m?.let { "${it.javaClass.getSimpleName()}(${msgType})" } ?: "Unknown($msgType)"
val length = bb.getBits(11).toInt()
l["Length"] = length
l["Range"] = bb.positionBits() to bb.positionBits() + length
m?.let {
if (it.read(bb, l, demo, length)) return true
l["Status"] = "Error"
return false
}
l["Status"] = "TODO"
bb.getBits(length) // Skip
return true
}
fun get(i: Int): UserMessage? = values[i]
private val values = mapOf(
0 to Geiger,
1 to Train,
2 to HudText,
3 to SayText,
4 to SayText2,
5 to TextMsg,
6 to ResetHUD,
7 to GameTitle,
8 to ItemPickup,
9 to ShowMenu,
10 to Shake,
11 to Fade,
12 to VGUIMenu,
13 to Rumble,
14 to CloseCaption,
15 to SendAudio,
16 to VoiceMask,
17 to RequestState,
18 to Damage,
19 to HintText,
20 to KeyHintText,
21 to HudMsg,
22 to AmmoDenied,
23 to AchievementEvent,
24 to UpdateRadar,
25 to VoiceSubtitle,
26 to HudNotify,
27 to HudNotifyCustom,
28 to PlayerStatsUpdate,
29 to PlayerIgnited,
30 to PlayerIgnitedInv,
31 to HudArenaNotify,
32 to UpdateAchievement,
33 to TrainingMsg,
34 to TrainingObjective,
35 to DamageDodged,
36 to PlayerJarated,
37 to PlayerExtinguished,
38 to PlayerJaratedFade,
39 to PlayerShieldBlocked,
40 to BreakModel,
41 to CheapBreakModel,
42 to BreakModel_Pumpkin,
43 to BreakModelRocketDud,
44 to CallVoteFailed,
45 to VoteStart,
46 to VotePass,
47 to VoteFailed,
48 to VoteSetup,
49 to PlayerBonusPoints,
50 to SpawnFlyingBird,
51 to PlayerGodRayEffect,
52 to SPHapWeapEvent,
53 to HapDmg,
54 to HapPunch,
55 to HapSetDrag,
56 to HapSetConst,
57 to HapMeleeContact
)
}
}
| artistic-2.0 | 7c65e4120014e43046d0f93edb6aab5e | 31.194719 | 118 | 0.566786 | 4.374439 | false | false | false | false |
NCBSinfo/NCBSinfo | app/src/main/java/com/rohitsuratekar/NCBSinfo/database/CheckRoutes.kt | 1 | 7023 | package com.rohitsuratekar.NCBSinfo.database
import android.os.AsyncTask
import android.util.Log
import com.rohitsuratekar.NCBSinfo.R
import com.rohitsuratekar.NCBSinfo.common.Constants
import com.rohitsuratekar.NCBSinfo.common.convertToList
import com.rohitsuratekar.NCBSinfo.common.serverTimestamp
import com.rohitsuratekar.NCBSinfo.di.Repository
import com.rohitsuratekar.NCBSinfo.models.Route
import java.text.SimpleDateFormat
import java.util.*
private const val TAG = "CheckRoute"
class CheckRoutes(private val repository: Repository, private val listener: OnFinishRetrieving) :
AsyncTask<Void?, Void?, Void?>() {
override fun doInBackground(vararg params: Void?): Void? {
val routes = repository.data().getAllRoutes()
if (routes.isEmpty()) {
makeDefaultRoutes()
} else {
listener.dataLoadFinished()
}
return null
}
private fun makeDefaultRoutes() {
Log.i(TAG, "Making default routes.")
listener.changeStatus(repository.app().getString(R.string.making_default))
val creationString = "2018-07-21 00:00:00"
val modifiedString = "2020-10-08 00:00:00"
val readableFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
val creationDate = Calendar.getInstance()
val modifiedDate = Calendar.getInstance()
creationDate.timeInMillis = readableFormat.parse(creationString)?.time!!
modifiedDate.timeInMillis = readableFormat.parse(modifiedString)?.time!!
//NCBS - IISC Shuttle
val r1 = makeRoute("ncbs", "iisc", "shuttle", creationDate, modifiedDate)
makeTrips(
r1, Calendar.MONDAY,
convertToList(repository.app().getString(R.string.def_ncbs_iisc_week))
)
makeTrips(
r1, Calendar.SUNDAY,
convertToList(repository.app().getString(R.string.def_ncbs_iisc_sunday))
)
// IISC - NCBS Shuttle
val r2 = makeRoute("iisc", "ncbs", "shuttle", creationDate, modifiedDate)
makeTrips(
r2, Calendar.MONDAY,
convertToList(repository.app().getString(R.string.def_iisc_ncbs_week))
)
makeTrips(
r2, Calendar.SUNDAY,
convertToList(repository.app().getString(R.string.def_iisc_ncbs_sunday))
)
//NCBS - Mandara Shuttle
val r3 = makeRoute("ncbs", "mandara", "shuttle", creationDate, modifiedDate)
makeTrips(
r3, Calendar.MONDAY,
convertToList(repository.app().getString(R.string.def_ncbs_mandara_week))
)
makeTrips(
r3, Calendar.SUNDAY,
convertToList(repository.app().getString(R.string.def_ncbs_mandara_sunday))
)
//Mandara - NCBS Shuttle
val r4 = makeRoute("mandara", "ncbs", "shuttle", creationDate, modifiedDate)
makeTrips(
r4, Calendar.MONDAY,
convertToList(repository.app().getString(R.string.def_mandara_ncbs_week))
)
makeTrips(
r4, Calendar.SUNDAY,
convertToList(repository.app().getString(R.string.def_mandara_ncbs_sunday))
)
//NCBS - Mandara Buggy
val r5 = makeRoute("ncbs", "mandara", "buggy", creationDate, modifiedDate)
makeTrips(
r5, Calendar.MONDAY,
convertToList(repository.app().getString(R.string.def_buggy_from_ncbs))
)
//Mandara - NCBS Buggy
val r6 = makeRoute("mandara", "ncbs", "buggy", creationDate, modifiedDate)
makeTrips(
r6, Calendar.MONDAY,
convertToList(repository.app().getString(R.string.def_buggy_from_mandara))
)
//NCBS - ICTS Shuttle
val r7 = makeRoute("ncbs", "icts", "shuttle", creationDate, modifiedDate)
makeTrips(
r7, Calendar.MONDAY,
convertToList(repository.app().getString(R.string.def_ncbs_icts_week))
)
makeTrips(
r7, Calendar.SUNDAY,
convertToList(repository.app().getString(R.string.def_ncbs_icts_sunday))
)
//ICTS-NCBS Shuttle
val r8 = makeRoute("icts", "ncbs", "shuttle", creationDate, modifiedDate)
makeTrips(
r8, Calendar.MONDAY,
convertToList(repository.app().getString(R.string.def_icts_ncbs_week))
)
makeTrips(
r8, Calendar.SUNDAY,
convertToList(repository.app().getString(R.string.def_icts_ncbs_sunday))
)
//NCBS-CBL TTC
val r9 = makeRoute("ncbs", "cbl", "ttc", creationDate, modifiedDate)
makeTrips(
r9, Calendar.MONDAY,
convertToList(repository.app().getString(R.string.def_ncbs_cbl))
)
val routeList = repository.data().getAllRoutes()
val returnList = mutableListOf<Route>()
for (r in routeList) {
val tps = repository.data().getTrips(r)
if (tps.isNotEmpty()) {
returnList.add(Route(r, repository.data().getTrips(r)))
} else {
repository.data().deleteRoute(r)
}
}
listener.returnRoutes(returnList)
// If default data is reset, no need to check database update, hence update the "UPDATE_VERSION"
repository.prefs().updateVersion(Constants.UPDATE_VERSION)
// Finish database loading
listener.dataLoadFinished()
}
private fun makeRoute(
originString: String,
destinationString: String,
typeString: String,
creation: Calendar,
modified: Calendar
): RouteData {
val route = RouteData().apply {
origin = originString.toLowerCase(Locale.getDefault())
destination = destinationString.toLowerCase(Locale.getDefault())
type = typeString.toLowerCase(Locale.getDefault())
createdOn = creation.serverTimestamp()
modifiedOn = modified.serverTimestamp()
syncedOn = modified.serverTimestamp()
favorite = "no"
author = Constants.DEFAULT_AUTHOR
}
val no = repository.data().addRoute(route)
route.routeID = no.toInt()
Log.i(TAG, "New route $originString - $destinationString $typeString is made")
return route
}
private fun makeTrips(route: RouteData, tripDay: Int, tripsList: List<String>) {
val tripData = TripData().apply {
routeID = route.routeID
trips = tripsList
day = tripDay
}
tripData.trips?.let {
if (it.isNotEmpty()) {
repository.data().addTrips(tripData)
}
}
}
}
interface OnFinishRetrieving {
fun dataLoadFinished()
fun changeStatus(statusNote: String)
fun returnRoutes(routeList: List<Route>)
} | mit | 67440a4808346a94ec83e6ab9d4709d1 | 34.398964 | 104 | 0.599032 | 4.590196 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/sitecreation/previews/SiteCreationPreviewFragment.kt | 1 | 18988 | package org.wordpress.android.ui.sitecreation.previews
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.content.res.Configuration
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.View.OnLayoutChangeListener
import android.view.animation.DecelerateInterpolator
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.viewModels
import dagger.hilt.android.AndroidEntryPoint
import org.wordpress.android.R
import org.wordpress.android.WordPress
import org.wordpress.android.databinding.FullscreenErrorWithRetryBinding
import org.wordpress.android.databinding.SiteCreationFormScreenBinding
import org.wordpress.android.databinding.SiteCreationPreviewScreenBinding
import org.wordpress.android.databinding.SiteCreationPreviewScreenDefaultBinding
import org.wordpress.android.databinding.SiteCreationProgressCreatingSiteBinding
import org.wordpress.android.ui.accounts.HelpActivity
import org.wordpress.android.ui.sitecreation.SiteCreationBaseFormFragment
import org.wordpress.android.ui.sitecreation.SiteCreationState
import org.wordpress.android.ui.sitecreation.misc.OnHelpClickedListener
import org.wordpress.android.ui.sitecreation.previews.SitePreviewViewModel.SitePreviewData
import org.wordpress.android.ui.sitecreation.previews.SitePreviewViewModel.SitePreviewUiState.SitePreviewContentUiState
import org.wordpress.android.ui.sitecreation.previews.SitePreviewViewModel.SitePreviewUiState.SitePreviewFullscreenErrorUiState
import org.wordpress.android.ui.sitecreation.previews.SitePreviewViewModel.SitePreviewUiState.SitePreviewFullscreenProgressUiState
import org.wordpress.android.ui.sitecreation.previews.SitePreviewViewModel.SitePreviewUiState.SitePreviewLoadingShimmerState
import org.wordpress.android.ui.sitecreation.previews.SitePreviewViewModel.SitePreviewUiState.SitePreviewWebErrorUiState
import org.wordpress.android.ui.sitecreation.services.SiteCreationService
import org.wordpress.android.ui.utils.UiHelpers
import org.wordpress.android.util.AniUtils
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AutoForeground.ServiceEventConnection
import org.wordpress.android.util.ErrorManagedWebViewClient.ErrorManagedWebViewClientListener
import org.wordpress.android.util.URLFilteredWebViewClient
import javax.inject.Inject
private const val ARG_DATA = "arg_site_creation_data"
private const val SLIDE_IN_ANIMATION_DURATION = 450L
@AndroidEntryPoint
class SiteCreationPreviewFragment : SiteCreationBaseFormFragment(),
ErrorManagedWebViewClientListener {
/**
* We need to connect to the service, so the service knows when the app is in the background. The service
* automatically shows system notifications when site creation is in progress and the app is in the background.
*/
private var serviceEventConnection: ServiceEventConnection? = null
private val viewModel: SitePreviewViewModel by viewModels()
private var animatorSet: AnimatorSet? = null
private val isLandscape: Boolean
get() = resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE
@Inject internal lateinit var uiHelpers: UiHelpers
private var binding: SiteCreationPreviewScreenBinding? = null
@Suppress("UseCheckOrError")
override fun onAttach(context: Context) {
super.onAttach(context)
if (context !is SitePreviewScreenListener) {
throw IllegalStateException("Parent activity must implement SitePreviewScreenListener.")
}
if (context !is OnHelpClickedListener) {
throw IllegalStateException("Parent activity must implement OnHelpClickedListener.")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
// we need to manually clear the SiteCreationService state so we don't for example receive sticky events
// from the previous run of the SiteCreation flow.
SiteCreationService.clearSiteCreationServiceState()
}
}
@Suppress("DEPRECATION")
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
(requireActivity() as AppCompatActivity).supportActionBar?.hide()
viewModel.start(requireArguments()[ARG_DATA] as SiteCreationState, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(requireActivity() as AppCompatActivity).supportActionBar?.hide()
viewModel.start(requireArguments()[ARG_DATA] as SiteCreationState, savedInstanceState)
}
override fun getContentLayout(): Int {
return R.layout.site_creation_preview_screen
}
@Suppress("UseCheckOrError") override val screenTitle: String
get() = arguments?.getString(EXTRA_SCREEN_TITLE)
?: throw IllegalStateException("Required argument screen title is missing.")
override fun setBindingViewStubListener(parentBinding: SiteCreationFormScreenBinding) {
parentBinding.siteCreationFormContentStub.setOnInflateListener { _, inflated ->
binding = SiteCreationPreviewScreenBinding.bind(inflated)
}
}
override fun setupContent() {
binding?.siteCreationPreviewScreenDefault?.initViewModel()
binding?.siteCreationPreviewScreenDefault?.fullscreenErrorWithRetry?.initRetryButton()
binding?.siteCreationPreviewScreenDefault?.initOkButton()
binding?.siteCreationPreviewScreenDefault?.fullscreenErrorWithRetry?.initCancelWizardButton()
binding?.siteCreationPreviewScreenDefault?.fullscreenErrorWithRetry?.initContactSupportButton()
}
private fun SiteCreationPreviewScreenDefaultBinding.initViewModel() {
viewModel.uiState.observe(this@SiteCreationPreviewFragment, { uiState ->
uiState?.let {
when (uiState) {
is SitePreviewContentUiState -> updateContentLayout(uiState.data)
is SitePreviewWebErrorUiState -> updateContentLayout(uiState.data)
is SitePreviewLoadingShimmerState -> updateContentLayout(uiState.data)
is SitePreviewFullscreenProgressUiState ->
siteCreationProgressCreatingSite.updateLoadingLayout(uiState)
is SitePreviewFullscreenErrorUiState ->
fullscreenErrorWithRetry.updateErrorLayout(uiState)
}
uiHelpers.updateVisibility(
siteCreationProgressCreatingSite.progressLayout,
uiState.fullscreenProgressLayoutVisibility
)
uiHelpers.updateVisibility(contentLayout, uiState.contentLayoutVisibility)
uiHelpers.updateVisibility(
siteCreationPreviewWebViewContainer.sitePreviewWebView,
uiState.webViewVisibility
)
uiHelpers.updateVisibility(
siteCreationPreviewWebViewContainer.sitePreviewWebError,
uiState.webViewErrorVisibility
)
uiHelpers.updateVisibility(
siteCreationPreviewWebViewContainer.sitePreviewWebViewShimmerLayout,
uiState.shimmerVisibility
)
uiHelpers.updateVisibility(
fullscreenErrorWithRetry.errorLayout,
uiState.fullscreenErrorLayoutVisibility
)
}
})
viewModel.preloadPreview.observe(this@SiteCreationPreviewFragment, { url ->
url?.let { urlString ->
siteCreationPreviewWebViewContainer.sitePreviewWebView.webViewClient =
URLFilteredWebViewClient(urlString, this@SiteCreationPreviewFragment)
siteCreationPreviewWebViewContainer.sitePreviewWebView.settings.userAgentString =
WordPress.getUserAgent()
siteCreationPreviewWebViewContainer.sitePreviewWebView.loadUrl(urlString)
}
})
viewModel.startCreateSiteService.observe(this@SiteCreationPreviewFragment, { startServiceData ->
startServiceData?.let {
SiteCreationService.createSite(
requireNotNull(activity),
startServiceData.previousState,
startServiceData.serviceData
)
}
})
initClickObservers()
}
private fun initClickObservers() {
viewModel.onHelpClicked.observe(this, {
(requireActivity() as OnHelpClickedListener).onHelpClicked(HelpActivity.Origin.SITE_CREATION_CREATING)
})
viewModel.onSiteCreationCompleted.observe(this, {
(requireActivity() as SitePreviewScreenListener).onSiteCreationCompleted()
})
viewModel.onOkButtonClicked.observe(this, { createSiteState ->
createSiteState?.let {
(requireActivity() as SitePreviewScreenListener).onSitePreviewScreenDismissed(createSiteState)
}
})
viewModel.onCancelWizardClicked.observe(this, { createSiteState ->
createSiteState?.let {
(requireActivity() as SitePreviewScreenListener).onSitePreviewScreenDismissed(createSiteState)
}
})
}
private fun FullscreenErrorWithRetryBinding.initRetryButton() {
errorRetry.setOnClickListener { viewModel.retry() }
}
private fun SiteCreationPreviewScreenDefaultBinding.initOkButton() {
okButton.setOnClickListener { viewModel.onOkButtonClicked() }
}
private fun FullscreenErrorWithRetryBinding.initCancelWizardButton() {
cancelWizardButton.setOnClickListener { viewModel.onCancelWizardClicked() }
}
private fun FullscreenErrorWithRetryBinding.initContactSupportButton() {
contactSupport.setOnClickListener { viewModel.onHelpClicked() }
}
private fun SiteCreationPreviewScreenDefaultBinding.updateContentLayout(sitePreviewData: SitePreviewData) {
sitePreviewData.apply {
siteCreationPreviewWebViewContainer.sitePreviewWebUrlTitle.text = createSpannableUrl(
requireNotNull(activity),
shortUrl,
subDomainIndices,
domainIndices
)
}
if (contentLayout.visibility == View.GONE) {
animateContentTransition()
view?.announceForAccessibility(
getString(R.string.new_site_creation_preview_title) +
getString(R.string.new_site_creation_site_preview_content_description)
)
}
}
private fun SiteCreationProgressCreatingSiteBinding.updateLoadingLayout(
progressUiState: SitePreviewFullscreenProgressUiState
) {
progressUiState.apply {
val newText = uiHelpers.getTextOfUiString(progressText.context, loadingTextResId)
AppLog.d(AppLog.T.MAIN, "Changing text - animation: $animate")
if (animate) {
updateLoadingTextWithFadeAnimation(newText)
} else {
progressText.text = newText
}
}
}
private fun SiteCreationProgressCreatingSiteBinding.updateLoadingTextWithFadeAnimation(newText: CharSequence) {
val animationDuration = AniUtils.Duration.SHORT
val fadeOut = AniUtils.getFadeOutAnim(
progressTextLayout,
animationDuration,
View.VISIBLE
)
val fadeIn = AniUtils.getFadeInAnim(
progressTextLayout,
animationDuration
)
// update the text when the view isn't visible
fadeIn.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator) {
progressText.text = newText
}
override fun onAnimationEnd(animation: Animator?) {
super.onAnimationEnd(animation)
animatorSet = null
}
})
// Start the fade-in animation right after the view fades out
fadeIn.startDelay = animationDuration.toMillis(progressTextLayout.context)
animatorSet = AnimatorSet().apply {
playSequentially(fadeOut, fadeIn)
start()
}
}
private fun FullscreenErrorWithRetryBinding.updateErrorLayout(
errorUiStateState: SitePreviewFullscreenErrorUiState
) {
errorUiStateState.apply {
uiHelpers.setTextOrHide(errorTitle, titleResId)
uiHelpers.setTextOrHide(errorSubtitle, subtitleResId)
uiHelpers.updateVisibility(contactSupport, errorUiStateState.showContactSupport)
uiHelpers.updateVisibility(cancelWizardButton, errorUiStateState.showCancelWizardButton)
}
}
/**
* Creates a spannable url with 2 different text colors for the subdomain and domain.
*
* @param context Context to get the color resources
* @param url The url to be used to created the spannable from
* @param subdomainSpan The subdomain index pair for the start and end positions
* @param domainSpan The domain index pair for the start and end positions
*
* @return [Spannable] styled with two different colors for the subdomain and domain parts
*/
private fun createSpannableUrl(
context: Context,
url: String,
subdomainSpan: Pair<Int, Int>,
domainSpan: Pair<Int, Int>
): Spannable {
val spannableTitle = SpannableString(url)
spannableTitle.setSpan(
ForegroundColorSpan(ContextCompat.getColor(context, R.color.neutral_80)),
subdomainSpan.first,
subdomainSpan.second,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
spannableTitle.setSpan(
ForegroundColorSpan(ContextCompat.getColor(context, R.color.neutral_40)),
domainSpan.first,
domainSpan.second,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
return spannableTitle
}
override fun onWebViewPageLoaded() {
viewModel.onUrlLoaded()
}
override fun onWebViewReceivedError() {
viewModel.onWebViewError()
}
override fun onHelp() {
viewModel.onHelpClicked()
}
private fun SiteCreationPreviewScreenDefaultBinding.animateContentTransition() {
contentLayout.addOnLayoutChangeListener(
object : OnLayoutChangeListener {
override fun onLayoutChange(
v: View?,
left: Int,
top: Int,
right: Int,
bottom: Int,
oldLeft: Int,
oldTop: Int,
oldRight: Int,
oldBottom: Int
) {
if (meetsHeightWidthForAnimation()) {
contentLayout.removeOnLayoutChangeListener(this)
val contentHeight = contentLayout.measuredHeight.toFloat()
val titleAnim = createFadeInAnimator(siteCreationPreviewHeaderItem.sitePreviewTitle)
val webViewAnim = createSlideInFromBottomAnimator(
siteCreationPreviewWebViewContainer.webViewContainer,
contentHeight
)
// OK button should slide in if the container exists and fade in otherwise
// difference between land & portrait
val okAnim = if (isLandscape) {
createFadeInAnimator(okButton)
} else {
createSlideInFromBottomAnimator(sitePreviewOkButtonContainer as View, contentHeight)
}
// There is a chance that either of the following fields can be null,
// so to avoid a NPE, we only execute playTogether if they are both not null
if (titleAnim != null && okAnim != null) {
AnimatorSet().apply {
interpolator = DecelerateInterpolator()
duration = SLIDE_IN_ANIMATION_DURATION
playTogether(titleAnim, webViewAnim, okAnim)
start()
}
}
}
}
})
}
private fun SiteCreationPreviewScreenDefaultBinding.meetsHeightWidthForAnimation() =
contentLayout.measuredWidth > 0 && contentLayout.measuredHeight > 0
private fun createSlideInFromBottomAnimator(view: View, contentHeight: Float): ObjectAnimator {
return ObjectAnimator.ofFloat(
view,
"translationY",
// start below the bottom edge of the display
(contentHeight - view.top),
0f
)
}
private fun createFadeInAnimator(view: View) = ObjectAnimator.ofFloat(view, "alpha", 0f, 1f)
override fun onResume() {
super.onResume()
serviceEventConnection = ServiceEventConnection(context, SiteCreationService::class.java, viewModel)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
viewModel.writeToBundle(outState)
}
override fun onPause() {
super.onPause()
serviceEventConnection?.disconnect(context, viewModel)
}
override fun onStop() {
super.onStop()
if (animatorSet?.isRunning == true) {
animatorSet?.cancel()
}
}
companion object {
const val TAG = "site_creation_preview_fragment_tag"
fun newInstance(
screenTitle: String,
siteCreationData: SiteCreationState
): SiteCreationPreviewFragment {
val fragment = SiteCreationPreviewFragment()
val bundle = Bundle()
bundle.putString(EXTRA_SCREEN_TITLE, screenTitle)
bundle.putParcelable(ARG_DATA, siteCreationData)
fragment.arguments = bundle
return fragment
}
}
}
| gpl-2.0 | 925047718dca4364e7bb908a61935e2b | 42.550459 | 130 | 0.65968 | 6.10743 | false | false | false | false |
trustin/armeria | kotlin/src/test/kotlin/com/linecorp/armeria/internal/server/annotation/DataClassDefaultNameTypeInfoProviderTest.kt | 3 | 4869 | /*
* Copyright 2022 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* 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.linecorp.armeria.internal.server.annotation
import com.fasterxml.jackson.annotation.JsonProperty
import com.linecorp.armeria.internal.server.annotation.AnnotatedDocServicePlugin.STRING
import com.linecorp.armeria.server.annotation.Description
import com.linecorp.armeria.server.docs.DescriptionInfo
import com.linecorp.armeria.server.docs.EnumInfo
import com.linecorp.armeria.server.docs.EnumValueInfo
import com.linecorp.armeria.server.docs.FieldInfo
import com.linecorp.armeria.server.docs.FieldRequirement
import com.linecorp.armeria.server.docs.StructInfo
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
class DataClassDefaultNameTypeInfoProviderTest {
@CsvSource(value = ["true", "false"])
@ParameterizedTest
fun dataClass(request: Boolean) {
val provider = DefaultNamedTypeInfoProvider(request)
val struct: StructInfo = (provider.newNamedTypeInfo(DescriptionResult::class.java) as StructInfo)
assertThat(struct.name()).isEqualTo(DescriptionResult::class.java.name)
assertThat(struct.descriptionInfo()).isEqualTo(DescriptionInfo.of("Class description"))
assertThat(struct.fields()).containsExactlyInAnyOrder(
FieldInfo.builder("required", STRING)
.requirement(FieldRequirement.REQUIRED)
.descriptionInfo(DescriptionInfo.of("required description"))
.build(),
FieldInfo.builder("optional", STRING)
.requirement(FieldRequirement.OPTIONAL)
.descriptionInfo(DescriptionInfo.of("optional description"))
.build(),
FieldInfo.builder("defaultValue", STRING)
.requirement(FieldRequirement.REQUIRED)
.descriptionInfo(DescriptionInfo.of("default value description"))
.build(),
FieldInfo.builder("defaultValue2", STRING)
.requirement(FieldRequirement.REQUIRED)
.descriptionInfo(DescriptionInfo.of("default value 2 description"))
.build(),
FieldInfo.builder("renamedNonnull", STRING)
.requirement(FieldRequirement.REQUIRED)
.descriptionInfo(DescriptionInfo.of("renamed nonnull description"))
.build(),
FieldInfo.builder("renamedNullable", STRING)
.requirement(FieldRequirement.OPTIONAL)
.descriptionInfo(DescriptionInfo.of("renamed nullable description"))
.build()
)
}
@CsvSource(value = ["true", "false"])
@ParameterizedTest
fun enumClass(request: Boolean) {
val requestProvider = DefaultNamedTypeInfoProvider(request)
val enumInfo: EnumInfo =
(requestProvider.newNamedTypeInfo(EnumParam::class.java) as EnumInfo)
assertThat(enumInfo.name()).isEqualTo(EnumParam::class.java.name)
assertThat(enumInfo.descriptionInfo()).isEqualTo(DescriptionInfo.of("Enum description"))
assertThat(enumInfo.values()).containsExactlyInAnyOrder(
EnumValueInfo("ENUM_1", null, DescriptionInfo.of("ENUM_1 description")),
EnumValueInfo("ENUM_2", null, DescriptionInfo.of("ENUM_2 description"))
)
}
@Description(value = "Class description")
data class DescriptionResult(
@Description(value = "required description")
val required: String,
@Description(value = "optional description")
val optional: String?,
@Description(value = "default value description")
val defaultValue: String = "Hello",
@Description(value = "default value 2 description")
val defaultValue2: String = "Hello2",
@JsonProperty("renamedNonnull")
@Description("renamed nonnull description")
val nonnullName: String,
@JsonProperty("renamedNullable")
@Description("renamed nullable description")
val nullableName: String?
)
@Description("Enum description")
enum class EnumParam {
@Description(value = "ENUM_1 description")
ENUM_1,
@Description(value = "ENUM_2 description")
ENUM_2
}
}
| apache-2.0 | 4735cbc0f4b3e3dc8652a2147b80a980 | 42.864865 | 105 | 0.689053 | 4.953204 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinMemberInfo.kt | 1 | 4083 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.memberInfo
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiField
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiMethod
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.classMembers.MemberInfoBase
import com.intellij.refactoring.util.classMembers.MemberInfo
import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.renderer.DescriptorRendererModifier
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
class KotlinMemberInfo @JvmOverloads constructor(
member: KtNamedDeclaration,
val isSuperClass: Boolean = false,
val isCompanionMember: Boolean = false
) : MemberInfoBase<KtNamedDeclaration>(member) {
companion object {
private val RENDERER = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withOptions {
modifiers = setOf(DescriptorRendererModifier.INNER)
}
}
init {
val memberDescriptor = member.resolveToDescriptorWrapperAware()
isStatic = member.parent is KtFile
if ((member is KtClass || member is KtPsiClassWrapper) && isSuperClass) {
if (member.isInterfaceClass()) {
displayName = RefactoringBundle.message("member.info.implements.0", member.name)
overrides = false
} else {
displayName = RefactoringBundle.message("member.info.extends.0", member.name)
overrides = true
}
} else {
displayName = RENDERER.render(memberDescriptor)
if (member.hasModifier(KtTokens.ABSTRACT_KEYWORD)) {
displayName = KotlinBundle.message("member.info.abstract.0", displayName)
}
if (isCompanionMember) {
displayName = KotlinBundle.message("member.info.companion.0", displayName)
}
val overriddenDescriptors = (memberDescriptor as? CallableMemberDescriptor)?.overriddenDescriptors ?: emptySet()
if (overriddenDescriptors.isNotEmpty()) {
overrides = overriddenDescriptors.any { it.modality != Modality.ABSTRACT }
}
}
}
}
fun lightElementForMemberInfo(declaration: KtNamedDeclaration?): PsiMember? {
return when (declaration) {
is KtNamedFunction -> declaration.getRepresentativeLightMethod()
is KtProperty, is KtParameter -> declaration.toLightElements().let {
it.firstIsInstanceOrNull<PsiMethod>() ?: it.firstIsInstanceOrNull<PsiField>()
} as PsiMember?
is KtClassOrObject -> declaration.toLightClass()
is KtPsiClassWrapper -> declaration.psiClass
else -> null
}
}
fun MemberInfoBase<out KtNamedDeclaration>.toJavaMemberInfo(): MemberInfo? {
val declaration = member
val psiMember: PsiMember? = lightElementForMemberInfo(declaration)
val info = MemberInfo(psiMember ?: return null, psiMember is PsiClass && overrides != null, null)
info.isToAbstract = isToAbstract
info.isChecked = isChecked
return info
}
fun MemberInfo.toKotlinMemberInfo(): KotlinMemberInfo? {
val declaration = member.unwrapped as? KtNamedDeclaration ?: return null
return KotlinMemberInfo(declaration, declaration is KtClass && overrides != null).apply {
this.isToAbstract = [email protected]
}
}
| apache-2.0 | 5fe08c32807a6bed0f0264f027095369 | 43.380435 | 158 | 0.729121 | 5.268387 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/commands/model/UpdateLyrics.kt | 1 | 751 | package com.kelsos.mbrc.commands.model
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.kelsos.mbrc.data.LyricsPayload
import com.kelsos.mbrc.interfaces.ICommand
import com.kelsos.mbrc.interfaces.IEvent
import com.kelsos.mbrc.model.LyricsModel
import javax.inject.Inject
class UpdateLyrics
@Inject
constructor(
private val model: LyricsModel,
private val mapper: ObjectMapper
) : ICommand {
override fun execute(e: IEvent) {
val payload = mapper.treeToValue((e.data as JsonNode), LyricsPayload::class.java)
model.status = payload.status
if (payload.status == LyricsPayload.SUCCESS) {
model.lyrics = payload.lyrics
} else {
model.lyrics = ""
}
}
}
| gpl-3.0 | b9caf1c1eba627daba1dc68e4e256b88 | 25.821429 | 85 | 0.756325 | 3.812183 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/conventionNameCalls/ReplaceCallWithUnaryOperatorIntention.kt | 1 | 2492 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions.conventionNameCalls
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.intentions.calleeName
import org.jetbrains.kotlin.idea.intentions.isReceiverExpressionWithValue
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.types.expressions.OperatorConventions
class ReplaceCallWithUnaryOperatorIntention : SelfTargetingRangeIntention<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java,
KotlinBundle.lazyMessage("replace.call.with.unary.operator")
), HighPriorityAction {
override fun applicabilityRange(element: KtDotQualifiedExpression): TextRange? {
val operation = operation(element.calleeName) ?: return null
if (!isApplicableOperation(operation)) return null
val call = element.callExpression ?: return null
if (call.typeArgumentList != null) return null
if (call.valueArguments.isNotEmpty()) return null
if (!element.isReceiverExpressionWithValue()) return null
setTextGetter(KotlinBundle.lazyMessage("replace.with.0.operator", operation.value))
return call.calleeExpression?.textRange
}
override fun applyTo(element: KtDotQualifiedExpression, editor: Editor?) {
val operation = operation(element.calleeName)?.value ?: return
val receiver = element.receiverExpression
element.replace(KtPsiFactory(element).createExpressionByPattern("$0$1", operation, receiver))
}
private fun isApplicableOperation(operation: KtSingleValueToken): Boolean = operation !in OperatorConventions.INCREMENT_OPERATIONS
private fun operation(functionName: String?): KtSingleValueToken? = functionName?.let {
OperatorConventions.UNARY_OPERATION_NAMES.inverse()[Name.identifier(it)]
}
}
| apache-2.0 | 5e2280ef981ec250b1803e9d73f6266f | 49.857143 | 158 | 0.796148 | 5.170124 | false | false | false | false |
team401/SnakeSkin | SnakeSkin-Core/src/main/kotlin/org/snakeskin/utility/value/HistoryByte.kt | 1 | 780 | package org.snakeskin.utility.value
class HistoryByte(initialValue: Byte = Byte.MIN_VALUE) {
var last = initialValue
@Synchronized get
private set
var current = initialValue
@Synchronized get
private set
@Synchronized
fun update(newValue: Byte) {
last = current
current = newValue
}
/**
* Returns true if the value changed from its previous value since the last call to "update"
*/
fun changed(): Boolean {
return current != last
}
//Numeric operations
/**
* Returns the difference between the current value and the last value
* Returns an Int, as byte subtraction in Kotlin returns an Int
*/
fun delta(): Int {
return current - last
}
} | gpl-3.0 | 6ddf4d8ac7aef8d6e3e8f353ab2210c0 | 21.970588 | 96 | 0.617949 | 4.936709 | false | false | false | false |
WhisperSystems/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/webrtc/CallParticipantsState.kt | 1 | 15173 | package org.thoughtcrime.securesms.components.webrtc
import android.content.Context
import androidx.annotation.PluralsRes
import androidx.annotation.StringRes
import com.annimon.stream.OptionalLong
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.webrtc.WebRtcControls.FoldableState
import org.thoughtcrime.securesms.events.CallParticipant
import org.thoughtcrime.securesms.events.CallParticipant.Companion.createLocal
import org.thoughtcrime.securesms.events.WebRtcViewModel
import org.thoughtcrime.securesms.groups.ui.GroupMemberEntry
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.ringrtc.CameraState
import org.thoughtcrime.securesms.service.webrtc.collections.ParticipantCollection
import java.util.concurrent.TimeUnit
/**
* Represents the state of all participants, remote and local, combined with view state
* needed to properly render the participants. The view state primarily consists of
* if we are in System PIP mode and if we should show our video for an outgoing call.
*/
data class CallParticipantsState(
val callState: WebRtcViewModel.State = WebRtcViewModel.State.CALL_DISCONNECTED,
val groupCallState: WebRtcViewModel.GroupCallState = WebRtcViewModel.GroupCallState.IDLE,
private val remoteParticipants: ParticipantCollection = ParticipantCollection(SMALL_GROUP_MAX),
val localParticipant: CallParticipant = createLocal(CameraState.UNKNOWN, BroadcastVideoSink(), false),
val focusedParticipant: CallParticipant = CallParticipant.EMPTY,
val localRenderState: WebRtcLocalRenderState = WebRtcLocalRenderState.GONE,
val isInPipMode: Boolean = false,
private val showVideoForOutgoing: Boolean = false,
val isViewingFocusedParticipant: Boolean = false,
val remoteDevicesCount: OptionalLong = OptionalLong.empty(),
private val foldableState: FoldableState = FoldableState.flat(),
val isInOutgoingRingingMode: Boolean = false,
val ringGroup: Boolean = false,
val ringerRecipient: Recipient = Recipient.UNKNOWN,
val groupMembers: List<GroupMemberEntry.FullMember> = emptyList()
) {
val allRemoteParticipants: List<CallParticipant> = remoteParticipants.allParticipants
val isFolded: Boolean = foldableState.isFolded
val isLargeVideoGroup: Boolean = allRemoteParticipants.size > SMALL_GROUP_MAX
val isIncomingRing: Boolean = callState == WebRtcViewModel.State.CALL_INCOMING
val gridParticipants: List<CallParticipant>
get() {
return remoteParticipants.gridParticipants
}
val listParticipants: List<CallParticipant>
get() {
val listParticipants: MutableList<CallParticipant> = mutableListOf()
if (isViewingFocusedParticipant && allRemoteParticipants.size > 1) {
listParticipants.addAll(allRemoteParticipants)
listParticipants.remove(focusedParticipant)
} else {
listParticipants.addAll(remoteParticipants.listParticipants)
}
if (foldableState.isFlat) {
listParticipants.add(CallParticipant.EMPTY)
}
listParticipants.reverse()
return listParticipants
}
val participantCount: OptionalLong
get() {
val includeSelf = groupCallState == WebRtcViewModel.GroupCallState.CONNECTED_AND_JOINED
return remoteDevicesCount.map { l: Long -> l + if (includeSelf) 1L else 0L }
.or { if (includeSelf) OptionalLong.of(1L) else OptionalLong.empty() }
}
fun getPreJoinGroupDescription(context: Context): String? {
if (callState != WebRtcViewModel.State.CALL_PRE_JOIN || groupCallState.isIdle) {
return null
}
return if (remoteParticipants.isEmpty) {
describeGroupMembers(
context = context,
oneParticipant = if (ringGroup) R.string.WebRtcCallView__signal_will_ring_s else R.string.WebRtcCallView__s_will_be_notified,
twoParticipants = if (ringGroup) R.string.WebRtcCallView__signal_will_ring_s_and_s else R.string.WebRtcCallView__s_and_s_will_be_notified,
multipleParticipants = if (ringGroup) R.plurals.WebRtcCallView__signal_will_ring_s_s_and_d_others else R.plurals.WebRtcCallView__s_s_and_d_others_will_be_notified,
members = groupMembers
)
} else {
when (remoteParticipants.size()) {
0 -> context.getString(R.string.WebRtcCallView__no_one_else_is_here)
1 -> context.getString(if (remoteParticipants[0].isSelf) R.string.WebRtcCallView__s_are_in_this_call else R.string.WebRtcCallView__s_is_in_this_call, remoteParticipants[0].getShortRecipientDisplayName(context))
2 -> context.getString(
R.string.WebRtcCallView__s_and_s_are_in_this_call,
remoteParticipants[0].getShortRecipientDisplayName(context),
remoteParticipants[1].getShortRecipientDisplayName(context)
)
else -> {
val others = remoteParticipants.size() - 2
context.resources.getQuantityString(
R.plurals.WebRtcCallView__s_s_and_d_others_are_in_this_call,
others,
remoteParticipants[0].getShortRecipientDisplayName(context),
remoteParticipants[1].getShortRecipientDisplayName(context),
others
)
}
}
}
}
fun getOutgoingRingingGroupDescription(context: Context): String? {
if (callState == WebRtcViewModel.State.CALL_CONNECTED &&
groupCallState == WebRtcViewModel.GroupCallState.CONNECTED_AND_JOINED &&
isInOutgoingRingingMode
) {
return describeGroupMembers(
context = context,
oneParticipant = R.string.WebRtcCallView__ringing_s,
twoParticipants = R.string.WebRtcCallView__ringing_s_and_s,
multipleParticipants = R.plurals.WebRtcCallView__ringing_s_s_and_d_others,
members = groupMembers
)
}
return null
}
fun getIncomingRingingGroupDescription(context: Context): String? {
if (callState == WebRtcViewModel.State.CALL_INCOMING &&
groupCallState == WebRtcViewModel.GroupCallState.RINGING &&
ringerRecipient.hasUuid()
) {
val ringerName = ringerRecipient.getShortDisplayName(context)
val membersWithoutYouOrRinger: List<GroupMemberEntry.FullMember> = groupMembers.filterNot { it.member.isSelf || ringerRecipient.requireUuid() == it.member.uuid.orNull() }
return when (membersWithoutYouOrRinger.size) {
0 -> context.getString(R.string.WebRtcCallView__s_is_calling_you, ringerName)
1 -> context.getString(
R.string.WebRtcCallView__s_is_calling_you_and_s,
ringerName,
membersWithoutYouOrRinger[0].member.getShortDisplayName(context)
)
2 -> context.getString(
R.string.WebRtcCallView__s_is_calling_you_s_and_s,
ringerName,
membersWithoutYouOrRinger[0].member.getShortDisplayName(context),
membersWithoutYouOrRinger[1].member.getShortDisplayName(context)
)
else -> {
val others = membersWithoutYouOrRinger.size - 2
context.resources.getQuantityString(
R.plurals.WebRtcCallView__s_is_calling_you_s_s_and_d_others,
others,
ringerName,
membersWithoutYouOrRinger[0].member.getShortDisplayName(context),
membersWithoutYouOrRinger[1].member.getShortDisplayName(context),
others
)
}
}
}
return null
}
fun needsNewRequestSizes(): Boolean {
return if (groupCallState.isNotIdle) {
allRemoteParticipants.any { it.videoSink.needsNewRequestingSize() }
} else {
false
}
}
companion object {
private const val SMALL_GROUP_MAX = 6
@JvmField
val MAX_OUTGOING_GROUP_RING_DURATION = TimeUnit.MINUTES.toMillis(1)
@JvmField
val STARTING_STATE = CallParticipantsState()
@JvmStatic
fun update(
oldState: CallParticipantsState,
webRtcViewModel: WebRtcViewModel,
enableVideo: Boolean
): CallParticipantsState {
var newShowVideoForOutgoing: Boolean = oldState.showVideoForOutgoing
if (enableVideo) {
newShowVideoForOutgoing = webRtcViewModel.state == WebRtcViewModel.State.CALL_OUTGOING
} else if (webRtcViewModel.state != WebRtcViewModel.State.CALL_OUTGOING) {
newShowVideoForOutgoing = false
}
val isInOutgoingRingingMode = if (oldState.isInOutgoingRingingMode) {
webRtcViewModel.callConnectedTime + MAX_OUTGOING_GROUP_RING_DURATION > System.currentTimeMillis() && webRtcViewModel.remoteParticipants.size == 0
} else {
oldState.ringGroup &&
webRtcViewModel.callConnectedTime + MAX_OUTGOING_GROUP_RING_DURATION > System.currentTimeMillis() &&
webRtcViewModel.remoteParticipants.size == 0 &&
oldState.callState == WebRtcViewModel.State.CALL_OUTGOING &&
webRtcViewModel.state == WebRtcViewModel.State.CALL_CONNECTED
}
val localRenderState: WebRtcLocalRenderState = determineLocalRenderMode(
oldState = oldState,
localParticipant = webRtcViewModel.localParticipant,
showVideoForOutgoing = newShowVideoForOutgoing,
isNonIdleGroupCall = webRtcViewModel.groupState.isNotIdle,
callState = webRtcViewModel.state,
numberOfRemoteParticipants = webRtcViewModel.remoteParticipants.size
)
return oldState.copy(
callState = webRtcViewModel.state,
groupCallState = webRtcViewModel.groupState,
remoteParticipants = oldState.remoteParticipants.getNext(webRtcViewModel.remoteParticipants),
localParticipant = webRtcViewModel.localParticipant,
focusedParticipant = getFocusedParticipant(webRtcViewModel.remoteParticipants),
localRenderState = localRenderState,
showVideoForOutgoing = newShowVideoForOutgoing,
remoteDevicesCount = webRtcViewModel.remoteDevicesCount,
ringGroup = webRtcViewModel.shouldRingGroup(),
isInOutgoingRingingMode = isInOutgoingRingingMode,
ringerRecipient = webRtcViewModel.ringerRecipient
)
}
@JvmStatic
fun update(oldState: CallParticipantsState, isInPip: Boolean): CallParticipantsState {
val localRenderState: WebRtcLocalRenderState = determineLocalRenderMode(oldState = oldState, isInPip = isInPip)
return oldState.copy(localRenderState = localRenderState, isInPipMode = isInPip)
}
@JvmStatic
fun setExpanded(oldState: CallParticipantsState, expanded: Boolean): CallParticipantsState {
val localRenderState: WebRtcLocalRenderState = determineLocalRenderMode(oldState = oldState, isExpanded = expanded)
return oldState.copy(localRenderState = localRenderState)
}
@JvmStatic
fun update(oldState: CallParticipantsState, selectedPage: SelectedPage): CallParticipantsState {
val localRenderState: WebRtcLocalRenderState = determineLocalRenderMode(oldState = oldState, isViewingFocusedParticipant = selectedPage == SelectedPage.FOCUSED)
return oldState.copy(localRenderState = localRenderState, isViewingFocusedParticipant = selectedPage == SelectedPage.FOCUSED)
}
@JvmStatic
fun update(oldState: CallParticipantsState, foldableState: FoldableState): CallParticipantsState {
val localRenderState: WebRtcLocalRenderState = determineLocalRenderMode(oldState = oldState)
return oldState.copy(localRenderState = localRenderState, foldableState = foldableState)
}
@JvmStatic
fun update(oldState: CallParticipantsState, groupMembers: List<GroupMemberEntry.FullMember>): CallParticipantsState {
return oldState.copy(groupMembers = groupMembers)
}
private fun determineLocalRenderMode(
oldState: CallParticipantsState,
localParticipant: CallParticipant = oldState.localParticipant,
isInPip: Boolean = oldState.isInPipMode,
showVideoForOutgoing: Boolean = oldState.showVideoForOutgoing,
isNonIdleGroupCall: Boolean = oldState.groupCallState.isNotIdle,
callState: WebRtcViewModel.State = oldState.callState,
numberOfRemoteParticipants: Int = oldState.allRemoteParticipants.size,
isViewingFocusedParticipant: Boolean = oldState.isViewingFocusedParticipant,
isExpanded: Boolean = oldState.localRenderState == WebRtcLocalRenderState.EXPANDED
): WebRtcLocalRenderState {
val displayLocal: Boolean = (numberOfRemoteParticipants == 0 || !isInPip) && (isNonIdleGroupCall || localParticipant.isVideoEnabled)
var localRenderState: WebRtcLocalRenderState = WebRtcLocalRenderState.GONE
if (isExpanded && (localParticipant.isVideoEnabled || isNonIdleGroupCall)) {
return WebRtcLocalRenderState.EXPANDED
} else if (displayLocal || showVideoForOutgoing) {
if (callState == WebRtcViewModel.State.CALL_CONNECTED) {
localRenderState = if (isViewingFocusedParticipant || numberOfRemoteParticipants > 1) {
WebRtcLocalRenderState.SMALLER_RECTANGLE
} else if (numberOfRemoteParticipants == 1) {
WebRtcLocalRenderState.SMALL_RECTANGLE
} else {
if (localParticipant.isVideoEnabled) WebRtcLocalRenderState.LARGE else WebRtcLocalRenderState.LARGE_NO_VIDEO
}
} else if (callState != WebRtcViewModel.State.CALL_INCOMING && callState != WebRtcViewModel.State.CALL_DISCONNECTED) {
localRenderState = if (localParticipant.isVideoEnabled) WebRtcLocalRenderState.LARGE else WebRtcLocalRenderState.LARGE_NO_VIDEO
}
} else if (callState == WebRtcViewModel.State.CALL_PRE_JOIN) {
localRenderState = WebRtcLocalRenderState.LARGE_NO_VIDEO
}
return localRenderState
}
private fun getFocusedParticipant(participants: List<CallParticipant>): CallParticipant {
val participantsByLastSpoke: List<CallParticipant> = participants.sortedByDescending(CallParticipant::lastSpoke)
return if (participantsByLastSpoke.isEmpty()) {
CallParticipant.EMPTY
} else {
participantsByLastSpoke.firstOrNull(CallParticipant::isScreenSharing) ?: participantsByLastSpoke[0]
}
}
private fun describeGroupMembers(
context: Context,
@StringRes oneParticipant: Int,
@StringRes twoParticipants: Int,
@PluralsRes multipleParticipants: Int,
members: List<GroupMemberEntry.FullMember>
): String {
val membersWithoutYou: List<GroupMemberEntry.FullMember> = members.filterNot { it.member.isSelf }
return when (membersWithoutYou.size) {
0 -> ""
1 -> context.getString(
oneParticipant,
membersWithoutYou[0].member.getShortDisplayName(context)
)
2 -> context.getString(
twoParticipants,
membersWithoutYou[0].member.getShortDisplayName(context),
membersWithoutYou[1].member.getShortDisplayName(context)
)
else -> {
val others = membersWithoutYou.size - 2
context.resources.getQuantityString(
multipleParticipants,
others,
membersWithoutYou[0].member.getShortDisplayName(context),
membersWithoutYou[1].member.getShortDisplayName(context),
others
)
}
}
}
}
enum class SelectedPage {
GRID, FOCUSED
}
}
| gpl-3.0 | 184bd4fee5e5237fc23bc85d0db20b82 | 42.97971 | 218 | 0.726422 | 5.344487 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/multi/Localizer.kt | 1 | 2221 | /*
* Localizer.kt
*
* Copyright 2019 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.multi
expect class StringResource
expect class PluralsResource
expect class DrawableResource
internal fun stripTts(input: String): String {
val b = StringBuilder()
// Find the TTS-exclusive bits
// They are wrapped in parentheses: ( )
var x = 0
while (x < input.length) {
val start = input.indexOf("(", x)
if (start == -1) break
val end = input.indexOf(")", start)
if (end == -1) break
// Delete those characters
b.append(input, x, start)
x = end + 1
}
if (x < input.length)
b.append(input, x, input.length)
val c = StringBuilder()
// Find the display-exclusive bits.
// They are wrapped in square brackets: [ ]
x = 0
while (x < b.length) {
val start = b.indexOf("[", x)
if (start == -1) break
val end = b.indexOf("]", start)
if (end == -1) break
c.append(b, x, start).append(b, start + 1, end)
x = end + 1
}
if (x < b.length)
c.append(b, x, b.length)
return c.toString()
}
interface LocalizerInterface {
fun localizeString(res: StringResource, vararg v: Any?): String
fun localizeFormatted(res: StringResource, vararg v: Any?): FormattedString = FormattedString(localizeString(res, *v))
fun localizeTts(res: StringResource, vararg v: Any?): FormattedString
fun localizePlural(res: PluralsResource, count: Int, vararg v: Any?): String
}
expect object Localizer : LocalizerInterface
| gpl-3.0 | 6378dd0d1c1d3ead8f86883bfbf1f886 | 30.728571 | 122 | 0.65466 | 3.944938 | false | false | false | false |
GunoH/intellij-community | json/src/com/intellij/jsonpath/ui/JsonPathEvaluateView.kt | 2 | 15650 | // 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.jsonpath.ui
import com.intellij.codeInsight.actions.ReformatCodeProcessor
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.find.FindBundle
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.util.PropertiesComponent
import com.intellij.json.JsonBundle
import com.intellij.json.JsonFileType
import com.intellij.json.psi.JsonFile
import com.intellij.jsonpath.JsonPathFileType
import com.intellij.jsonpath.ui.JsonPathEvaluateManager.Companion.JSON_PATH_EVALUATE_EXPRESSION_KEY
import com.intellij.jsonpath.ui.JsonPathEvaluateManager.Companion.JSON_PATH_EVALUATE_HISTORY
import com.intellij.jsonpath.ui.JsonPathEvaluateManager.Companion.JSON_PATH_EVALUATE_RESULT_KEY
import com.intellij.jsonpath.ui.JsonPathEvaluateManager.Companion.JSON_PATH_EVALUATE_SOURCE_KEY
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionButtonLook
import com.intellij.openapi.actionSystem.ex.ComboBoxAction
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.EditorKind
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.SimpleToolWindowPanel
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.PopupChooserBuilder
import com.intellij.openapi.util.NlsActions
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiManager
import com.intellij.testFramework.LightVirtualFile
import com.intellij.ui.EditorTextField
import com.intellij.ui.JBColor
import com.intellij.ui.components.*
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.popup.PopupState
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.jayway.jsonpath.Configuration
import com.jayway.jsonpath.Option
import com.jayway.jsonpath.spi.json.JacksonJsonProvider
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider
import java.awt.BorderLayout
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.event.KeyEvent
import java.util.*
import java.util.function.Supplier
import javax.swing.*
import kotlin.collections.ArrayDeque
internal abstract class JsonPathEvaluateView(protected val project: Project) : SimpleToolWindowPanel(true, true), Disposable {
companion object {
init {
Configuration.setDefaults(object : Configuration.Defaults {
private val jsonProvider = JacksonJsonProvider()
private val mappingProvider = JacksonMappingProvider()
override fun jsonProvider() = jsonProvider
override fun mappingProvider() = mappingProvider
override fun options() = EnumSet.noneOf(Option::class.java)
})
}
}
protected val searchTextField: EditorTextField = object : EditorTextField(project, JsonPathFileType.INSTANCE) {
override fun processKeyBinding(ks: KeyStroke?, e: KeyEvent?, condition: Int, pressed: Boolean): Boolean {
if (e?.keyCode == KeyEvent.VK_ENTER && pressed) {
evaluate()
return true
}
return super.processKeyBinding(ks, e, condition, pressed)
}
override fun createEditor(): EditorEx {
val editor = super.createEditor()
editor.setBorder(JBUI.Borders.empty())
editor.component.border = JBUI.Borders.empty(4, 0, 3, 6)
editor.component.isOpaque = false
editor.backgroundColor = UIUtil.getTextFieldBackground()
val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document)
if (psiFile != null) {
psiFile.putUserData(JSON_PATH_EVALUATE_EXPRESSION_KEY, true)
psiFile.putUserData(JSON_PATH_EVALUATE_SOURCE_KEY, Supplier(::getJsonFile))
}
return editor
}
}
protected val searchWrapper: JPanel = object : NonOpaquePanel(BorderLayout()) {
override fun updateUI() {
super.updateUI()
this.background = UIUtil.getTextFieldBackground()
}
}
val searchComponent: JComponent
get() = searchTextField
protected val resultWrapper: JBPanelWithEmptyText = JBPanelWithEmptyText(BorderLayout())
private val resultLabel = JBLabel(JsonBundle.message("jsonpath.evaluate.result"))
private val resultEditor: Editor = initJsonEditor("result.json", true, EditorKind.PREVIEW)
private val errorOutputArea: JBTextArea = JBTextArea()
private val errorOutputContainer: JScrollPane = JBScrollPane(errorOutputArea)
private val evalOptions: MutableSet<Option> = mutableSetOf()
init {
resultEditor.putUserData(JSON_PATH_EVALUATE_RESULT_KEY, true)
resultEditor.setBorder(JBUI.Borders.customLine(JBColor.border(), 1, 0, 0, 0))
resultLabel.border = JBUI.Borders.empty(3, 6)
resultWrapper.emptyText.text = JsonBundle.message("jsonpath.evaluate.no.result")
errorOutputContainer.border = JBUI.Borders.customLine(JBColor.border(), 1, 0, 0, 0)
val historyButton = SearchHistoryButton(ShowHistoryAction(), false)
val historyButtonWrapper = NonOpaquePanel(BorderLayout())
historyButtonWrapper.border = JBUI.Borders.empty(3, 6, 3, 6)
historyButtonWrapper.add(historyButton, BorderLayout.NORTH)
searchTextField.setFontInheritedFromLAF(false) // use font as in regular editor
searchWrapper.add(historyButtonWrapper, BorderLayout.WEST)
searchWrapper.add(searchTextField, BorderLayout.CENTER)
searchWrapper.border = JBUI.Borders.customLine(JBColor.border(), 0, 0, 1, 0)
searchWrapper.isOpaque = true
errorOutputArea.isEditable = false
errorOutputArea.wrapStyleWord = true
errorOutputArea.lineWrap = true
errorOutputArea.border = JBUI.Borders.empty(10)
setExpression("$..*")
}
protected fun initToolbar() {
val actionGroup = DefaultActionGroup()
fillToolbarOptions(actionGroup)
val toolbar = ActionManager.getInstance().createActionToolbar("JsonPathEvaluateToolbar", actionGroup, true)
toolbar.targetComponent = this
setToolbar(toolbar.component)
}
protected abstract fun getJsonFile(): JsonFile?
protected fun resetExpressionHighlighting() {
val jsonPathFile = PsiDocumentManager.getInstance(project).getPsiFile(searchTextField.document)
if (jsonPathFile != null) {
// reset inspections in expression
DaemonCodeAnalyzer.getInstance(project).restart(jsonPathFile)
}
}
private fun fillToolbarOptions(group: DefaultActionGroup) {
val outputComboBox = object : ComboBoxAction() {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
override fun createPopupActionGroup(button: JComponent, context: DataContext): DefaultActionGroup {
val outputItems = DefaultActionGroup()
outputItems.add(OutputOptionAction(false, JsonBundle.message("jsonpath.evaluate.output.values")))
outputItems.add(OutputOptionAction(true, JsonBundle.message("jsonpath.evaluate.output.paths")))
return outputItems
}
override fun update(e: AnActionEvent) {
val presentation = e.presentation
if (e.project == null) return
presentation.text = if (evalOptions.contains(Option.AS_PATH_LIST)) {
JsonBundle.message("jsonpath.evaluate.output.paths")
}
else {
JsonBundle.message("jsonpath.evaluate.output.values")
}
}
override fun createCustomComponent(presentation: Presentation, place: String): JComponent {
val panel = JPanel(GridBagLayout())
panel.add(JLabel(JsonBundle.message("jsonpath.evaluate.output.option")),
GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, JBUI.insetsLeft(5), 0, 0))
panel.add(super.createCustomComponent(presentation, place),
GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, JBInsets.emptyInsets(), 0, 0))
return panel
}
}
group.add(outputComboBox)
group.add(DefaultActionGroup(JsonBundle.message("jsonpath.evaluate.options"), true).apply {
templatePresentation.icon = AllIcons.General.Settings
add(OptionToggleAction(Option.SUPPRESS_EXCEPTIONS, JsonBundle.message("jsonpath.evaluate.suppress.exceptions")))
add(OptionToggleAction(Option.ALWAYS_RETURN_LIST, JsonBundle.message("jsonpath.evaluate.return.list")))
add(OptionToggleAction(Option.DEFAULT_PATH_LEAF_TO_NULL, JsonBundle.message("jsonpath.evaluate.nullize.missing.leaf")))
add(OptionToggleAction(Option.REQUIRE_PROPERTIES, JsonBundle.message("jsonpath.evaluate.require.all.properties")))
})
}
protected fun initJsonEditor(fileName: String, isViewer: Boolean, kind: EditorKind): Editor {
val sourceVirtualFile = LightVirtualFile(fileName, JsonFileType.INSTANCE, "") // require strict JSON with quotes
val sourceFile = PsiManager.getInstance(project).findFile(sourceVirtualFile)!!
val document = PsiDocumentManager.getInstance(project).getDocument(sourceFile)!!
val editor = EditorFactory.getInstance().createEditor(document, project, sourceVirtualFile, isViewer, kind)
editor.settings.isLineNumbersShown = false
return editor
}
fun setExpression(jsonPathExpr: String) {
searchTextField.text = jsonPathExpr
}
private fun setResult(result: String) {
WriteAction.run<Throwable> {
resultEditor.document.setText(result)
PsiDocumentManager.getInstance(project).commitDocument(resultEditor.document)
val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(resultEditor.document)!!
ReformatCodeProcessor(psiFile, false).run()
}
if (!resultWrapper.components.contains(resultEditor.component)) {
resultWrapper.removeAll()
resultWrapper.add(resultLabel, BorderLayout.NORTH)
resultWrapper.add(resultEditor.component, BorderLayout.CENTER)
resultWrapper.revalidate()
resultWrapper.repaint()
}
resultEditor.caretModel.moveToOffset(0)
}
private fun setError(error: String) {
errorOutputArea.text = error
if (!resultWrapper.components.contains(errorOutputArea)) {
resultWrapper.removeAll()
resultWrapper.add(resultLabel, BorderLayout.NORTH)
resultWrapper.add(errorOutputContainer, BorderLayout.CENTER)
resultWrapper.revalidate()
resultWrapper.repaint()
}
}
private fun evaluate() {
val evaluator = JsonPathEvaluator(getJsonFile(), searchTextField.text, evalOptions)
val result = evaluator.evaluate()
when (result) {
is IncorrectExpression -> setError(result.message)
is IncorrectDocument -> setError(result.message)
is ResultNotFound -> setError(result.message)
is ResultString -> setResult(result.value)
else -> {}
}
if (result != null && result !is IncorrectExpression) {
addJSONPathToHistory(searchTextField.text.trim())
}
}
override fun dispose() {
EditorFactory.getInstance().releaseEditor(resultEditor)
}
private inner class OutputOptionAction(private val enablePaths: Boolean, @NlsActions.ActionText message: String)
: DumbAwareAction(message) {
override fun actionPerformed(e: AnActionEvent) {
if (enablePaths) {
evalOptions.add(Option.AS_PATH_LIST)
}
else {
evalOptions.remove(Option.AS_PATH_LIST)
}
evaluate()
}
}
private inner class OptionToggleAction(private val option: Option, @NlsActions.ActionText message: String) : ToggleAction(message) {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
override fun isSelected(e: AnActionEvent): Boolean {
return evalOptions.contains(option)
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
if (state) {
evalOptions.add(option)
}
else {
evalOptions.remove(option)
}
evaluate()
}
}
private class SearchHistoryButton constructor(action: AnAction, focusable: Boolean) :
ActionButton(action, action.templatePresentation.clone(), ActionPlaces.UNKNOWN, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) {
override fun getDataContext(): DataContext {
return DataManager.getInstance().getDataContext(this)
}
override fun getPopState(): Int {
return if (isSelected) SELECTED else super.getPopState()
}
override fun getIcon(): Icon {
if (isEnabled && isSelected) {
val selectedIcon = myPresentation.selectedIcon
if (selectedIcon != null) return selectedIcon
}
return super.getIcon()
}
init {
setLook(ActionButtonLook.INPLACE_LOOK)
isFocusable = focusable
updateIcon()
}
}
private fun getExpressionHistory(): List<String> {
return PropertiesComponent.getInstance().getValue(JSON_PATH_EVALUATE_HISTORY)?.split('\n') ?: emptyList()
}
private fun setExpressionHistory(history: Collection<String>) {
PropertiesComponent.getInstance().setValue(JSON_PATH_EVALUATE_HISTORY, history.joinToString("\n"))
}
private fun addJSONPathToHistory(path: String) {
if (path.isBlank()) return
val history = ArrayDeque(getExpressionHistory())
if (!history.contains(path)) {
history.addFirst(path)
if (history.size > 10) {
history.removeLast()
}
setExpressionHistory(history)
}
else {
if (history.firstOrNull() == path) {
return
}
history.remove(path)
history.addFirst(path)
setExpressionHistory(history)
}
}
private inner class ShowHistoryAction : DumbAwareAction(FindBundle.message("find.search.history"), null,
AllIcons.Actions.SearchWithHistory) {
private val popupState: PopupState<JBPopup?> = PopupState.forPopup()
override fun actionPerformed(e: AnActionEvent) {
if (popupState.isRecentlyHidden) return
val historyList = JBList(getExpressionHistory())
showCompletionPopup(searchWrapper, historyList, searchTextField, popupState)
}
init {
registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("ShowSearchHistory"), searchTextField)
}
private fun showCompletionPopup(toolbarComponent: JComponent?,
list: JList<String>,
textField: EditorTextField,
popupState: PopupState<JBPopup?>) {
val builder: PopupChooserBuilder<*> = JBPopupFactory.getInstance().createListPopupBuilder(list)
val popup = builder
.setMovable(false)
.setResizable(false)
.setRequestFocus(true)
.setItemChoosenCallback(Runnable {
val selectedValue = list.selectedValue
if (selectedValue != null) {
textField.text = selectedValue
IdeFocusManager.getGlobalInstance().requestFocus(textField, false)
}
})
.createPopup()
popupState.prepareToShow(popup)
if (toolbarComponent != null) {
popup.showUnderneathOf(toolbarComponent)
}
else {
popup.showUnderneathOf(textField)
}
}
}
} | apache-2.0 | 2a68c793362141f6f746e98366a8de4b | 36.987864 | 139 | 0.730607 | 4.830247 | false | false | false | false |
GunoH/intellij-community | platform/feedback/src/com/intellij/feedback/common/state/DontShowAgainFeedbackService.kt | 8 | 950 | // 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.feedback.common.state
import com.intellij.openapi.components.*
import kotlinx.serialization.Serializable
@Service(Service.Level.APP)
@State(name = "DontShowAgainFeedbackService", storages = [Storage("DontShowAgainFeedbackService.xml")])
class DontShowAgainFeedbackService : PersistentStateComponent<DontShowAgainFeedbackState> {
companion object {
@JvmStatic
fun getInstance(): DontShowAgainFeedbackService = service()
}
private var state: DontShowAgainFeedbackState = DontShowAgainFeedbackState()
override fun getState(): DontShowAgainFeedbackState {
return state
}
override fun loadState(state: DontShowAgainFeedbackState) {
this.state = state
}
}
@Serializable
data class DontShowAgainFeedbackState(
val dontShowAgainIdeVersions: MutableSet<String> = mutableSetOf()
) | apache-2.0 | f5d262c5bae2b5c4da34397d62254ec7 | 31.793103 | 120 | 0.792632 | 4.92228 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/internal/InternalSettingsViewModel.kt | 1 | 5678 | package org.thoughtcrime.securesms.components.settings.app.internal
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import org.signal.ringrtc.CallManager
import org.thoughtcrime.securesms.keyvalue.InternalValues
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.util.livedata.Store
class InternalSettingsViewModel(private val repository: InternalSettingsRepository) : ViewModel() {
private val preferenceDataStore = SignalStore.getPreferenceDataStore()
private val store = Store(getState())
init {
repository.getEmojiVersionInfo { version ->
store.update { it.copy(emojiVersion = version) }
}
}
val state: LiveData<InternalSettingsState> = store.stateLiveData
fun setSeeMoreUserDetails(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.RECIPIENT_DETAILS, enabled)
refresh()
}
fun setShakeToReport(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.SHAKE_TO_REPORT, enabled)
refresh()
}
fun setDisableStorageService(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.DISABLE_STORAGE_SERVICE, enabled)
refresh()
}
fun setGv2DoNotCreateGv2Groups(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.GV2_DO_NOT_CREATE_GV2, enabled)
refresh()
}
fun setGv2ForceInvites(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.GV2_FORCE_INVITES, enabled)
refresh()
}
fun setGv2IgnoreServerChanges(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.GV2_IGNORE_SERVER_CHANGES, enabled)
refresh()
}
fun setGv2IgnoreP2PChanges(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.GV2_IGNORE_P2P_CHANGES, enabled)
refresh()
}
fun setDisableAutoMigrationInitiation(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.GV2_DISABLE_AUTOMIGRATE_INITIATION, enabled)
refresh()
}
fun setDisableAutoMigrationNotification(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.GV2_DISABLE_AUTOMIGRATE_NOTIFICATION, enabled)
refresh()
}
fun setAllowCensorshipSetting(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.ALLOW_CENSORSHIP_SETTING, enabled)
refresh()
}
fun setUseBuiltInEmoji(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.FORCE_BUILT_IN_EMOJI, enabled)
refresh()
}
fun setRemoveSenderKeyMinimum(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.REMOVE_SENDER_KEY_MINIMUM, enabled)
refresh()
}
fun setDelayResends(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.DELAY_RESENDS, enabled)
refresh()
}
fun setInternalGroupCallingServer(server: String?) {
preferenceDataStore.putString(InternalValues.CALLING_SERVER, server)
refresh()
}
fun setInternalCallingAudioProcessingMethod(method: CallManager.AudioProcessingMethod) {
preferenceDataStore.putInt(InternalValues.CALLING_AUDIO_PROCESSING_METHOD, method.ordinal)
refresh()
}
fun setInternalCallingBandwidthMode(bandwidthMode: CallManager.BandwidthMode) {
preferenceDataStore.putInt(InternalValues.CALLING_BANDWIDTH_MODE, bandwidthMode.ordinal)
refresh()
}
fun setInternalCallingDisableTelecom(enabled: Boolean) {
preferenceDataStore.putBoolean(InternalValues.CALLING_DISABLE_TELECOM, enabled)
refresh()
}
fun toggleStories() {
val newState = !SignalStore.storyValues().isFeatureDisabled
SignalStore.storyValues().isFeatureDisabled = newState
store.update { getState().copy(disableStories = newState) }
}
fun addSampleReleaseNote() {
repository.addSampleReleaseNote()
}
private fun refresh() {
store.update { getState().copy(emojiVersion = it.emojiVersion) }
}
private fun getState() = InternalSettingsState(
seeMoreUserDetails = SignalStore.internalValues().recipientDetails(),
shakeToReport = SignalStore.internalValues().shakeToReport(),
gv2doNotCreateGv2Groups = SignalStore.internalValues().gv2DoNotCreateGv2Groups(),
gv2forceInvites = SignalStore.internalValues().gv2ForceInvites(),
gv2ignoreServerChanges = SignalStore.internalValues().gv2IgnoreServerChanges(),
gv2ignoreP2PChanges = SignalStore.internalValues().gv2IgnoreP2PChanges(),
disableAutoMigrationInitiation = SignalStore.internalValues().disableGv1AutoMigrateInitiation(),
disableAutoMigrationNotification = SignalStore.internalValues().disableGv1AutoMigrateNotification(),
allowCensorshipSetting = SignalStore.internalValues().allowChangingCensorshipSetting(),
callingServer = SignalStore.internalValues().groupCallingServer(),
callingAudioProcessingMethod = SignalStore.internalValues().callingAudioProcessingMethod(),
callingBandwidthMode = SignalStore.internalValues().callingBandwidthMode(),
callingDisableTelecom = SignalStore.internalValues().callingDisableTelecom(),
useBuiltInEmojiSet = SignalStore.internalValues().forceBuiltInEmoji(),
emojiVersion = null,
removeSenderKeyMinimium = SignalStore.internalValues().removeSenderKeyMinimum(),
delayResends = SignalStore.internalValues().delayResends(),
disableStorageService = SignalStore.internalValues().storageServiceDisabled(),
disableStories = SignalStore.storyValues().isFeatureDisabled
)
class Factory(private val repository: InternalSettingsRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return requireNotNull(modelClass.cast(InternalSettingsViewModel(repository)))
}
}
}
| gpl-3.0 | dd1f3355cad66459bbb83310199c9037 | 36.853333 | 104 | 0.784607 | 4.916017 | false | false | false | false |
chaojimiaomiao/colorful_wechat | src/main/kotlin/com/rarnu/tophighlight/xposed/HookTopHighlight.kt | 1 | 3431 | package com.rarnu.tophighlight.xposed
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.StateListDrawable
import android.view.View
import android.view.ViewGroup
import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XposedHelpers
/**
* Created by rarnu on 1/11/17.
*/
object HookTopHighlight {
/**
* 此处是hook置顶的群和普通的群
*/
fun hookTopHighlight(classLoader: ClassLoader?, ver: Versions) {
XposedHelpers.findAndHookMethod(ver.conversationAdapter, classLoader, "getView", Integer.TYPE, View::class.java, ViewGroup::class.java, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun afterHookedMethod(pmethod: MethodHookParam) {
val ad = XposedHelpers.callMethod(pmethod.thisObject, ver.userInfoMethod, pmethod.args[0])
val j = XposedHelpers.callMethod(pmethod.thisObject, ver.topInfoMethod, ad)
val oLH = XposedHelpers.getBooleanField(j, ver.topInfoField)
(pmethod.result as View?)?.background = if (oLH) createTopHighlightSelectorDrawable(pmethod.args[0] as Int) else createNormalSelectorDrawable()
}
})
}
fun hookTopReaderAndMac(classLoader: ClassLoader?, ver: Versions) {
XposedHelpers.findAndHookMethod(ver.topMacActivity, classLoader, ver.topMacMethod, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun afterHookedMethod(pmethod: MethodHookParam) {
val v = XposedHelpers.getObjectField(pmethod.thisObject, ver.topMacField) as View?
v?.background = createTopReaderAndMacSelectorDrawable()
}
})
XposedHelpers.findAndHookMethod(ver.topReaderActivity, classLoader, ver.topReaderMethod, Integer.TYPE, object : XC_MethodHook() {
@Throws(Throwable::class)
override fun afterHookedMethod(pmethod: MethodHookParam) {
val view = XposedHelpers.getObjectField(pmethod.thisObject, ver.topReaderField) as View?
view?.findViewById(ver.topReaderViewId)?.background = createTopReaderAndMacSelectorDrawable(1)
}
})
}
private fun createTopHighlightSelectorDrawable(idx: Int): StateListDrawable? {
return createSelectorDrawable(XpConfig.topColors[idx], XpConfig.topPressColors[idx])
}
private fun createNormalSelectorDrawable(): StateListDrawable? {
return createSelectorDrawable(XpConfig.normalColor, XpConfig.normalPressColor)
}
private fun createTopReaderAndMacSelectorDrawable(type: Int = 0): StateListDrawable? {
return when (type) {
0 -> createSelectorDrawable(XpConfig.macColor, XpConfig.macPressColor)
1 -> createSelectorDrawable(XpConfig.readerColor, XpConfig.readerPressColor)
else -> null
}
}
private fun createSelectorDrawable(defaultColor: Int, pressColor: Int): StateListDrawable? {
val stateList = StateListDrawable()
stateList.addState(intArrayOf(android.R.attr.state_selected), ColorDrawable(pressColor))
stateList.addState(intArrayOf(android.R.attr.state_focused), ColorDrawable(pressColor))
stateList.addState(intArrayOf(android.R.attr.state_pressed), ColorDrawable(pressColor))
stateList.addState(intArrayOf(), ColorDrawable(defaultColor))
return stateList
}
} | gpl-3.0 | 635612fce4e273add9335367f0e66e79 | 47 | 170 | 0.7059 | 4.725381 | false | true | false | false |
oldergod/android-architecture | app/src/main/java/com/example/android/architecture/blueprints/todoapp/taskdetail/TaskDetailViewModel.kt | 1 | 8886 | /*
* Copyright 2016, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp.taskdetail
import android.arch.lifecycle.ViewModel
import com.example.android.architecture.blueprints.todoapp.mvibase.MviAction
import com.example.android.architecture.blueprints.todoapp.mvibase.MviIntent
import com.example.android.architecture.blueprints.todoapp.mvibase.MviResult
import com.example.android.architecture.blueprints.todoapp.mvibase.MviView
import com.example.android.architecture.blueprints.todoapp.mvibase.MviViewModel
import com.example.android.architecture.blueprints.todoapp.mvibase.MviViewState
import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailAction.ActivateTaskAction
import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailAction.CompleteTaskAction
import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailAction.DeleteTaskAction
import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailAction.PopulateTaskAction
import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailResult.ActivateTaskResult
import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailResult.CompleteTaskResult
import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailResult.DeleteTaskResult
import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailResult.PopulateTaskResult
import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailViewState.UiNotification.TASK_ACTIVATED
import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailViewState.UiNotification.TASK_COMPLETE
import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailViewState.UiNotification.TASK_DELETED
import com.example.android.architecture.blueprints.todoapp.util.notOfType
import io.reactivex.Observable
import io.reactivex.ObservableTransformer
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.functions.BiFunction
import io.reactivex.subjects.PublishSubject
/**
* Listens to user actions from the UI ([TaskDetailFragment]), retrieves the data and updates
* the UI as required.
*
* @property actionProcessorHolder Contains and executes the business logic of all emitted actions.
*/
class TaskDetailViewModel(
private val actionProcessorHolder: TaskDetailActionProcessorHolder
) : ViewModel(), MviViewModel<TaskDetailIntent, TaskDetailViewState> {
/**
* Proxy subject used to keep the stream alive even after the UI gets recycled.
* This is basically used to keep ongoing events and the last cached State alive
* while the UI disconnects and reconnects on config changes.
*/
private val intentsSubject: PublishSubject<TaskDetailIntent> = PublishSubject.create()
private val statesObservable: Observable<TaskDetailViewState> = compose()
private val disposables = CompositeDisposable()
/**
* take only the first ever InitialIntent and all intents of other types
* to avoid reloading data on config changes
*/
private val intentFilter: ObservableTransformer<TaskDetailIntent, TaskDetailIntent>
get() = ObservableTransformer { intents ->
intents.publish { shared ->
Observable.merge<TaskDetailIntent>(
shared.ofType(TaskDetailIntent.InitialIntent::class.java).take(1),
shared.notOfType(TaskDetailIntent.InitialIntent::class.java)
)
}
}
override fun processIntents(intents: Observable<TaskDetailIntent>) {
disposables.add(intents.subscribe(intentsSubject::onNext))
}
override fun states(): Observable<TaskDetailViewState> = statesObservable
/**
* Compose all components to create the stream logic
*/
private fun compose(): Observable<TaskDetailViewState> {
return intentsSubject
.compose<TaskDetailIntent>(intentFilter)
.map(this::actionFromIntent)
.compose(actionProcessorHolder.actionProcessor)
// Cache each state and pass it to the reducer to create a new state from
// the previous cached one and the latest Result emitted from the action processor.
// The Scan operator is used here for the caching.
.scan(TaskDetailViewState.idle(), reducer)
// When a reducer just emits previousState, there's no reason to call render. In fact,
// redrawing the UI in cases like this can cause jank (e.g. messing up snackbar animations
// by showing the same snackbar twice in rapid succession).
.distinctUntilChanged()
// Emit the last one event of the stream on subscription
// Useful when a View rebinds to the ViewModel after rotation.
.replay(1)
// Create the stream on creation without waiting for anyone to subscribe
// This allows the stream to stay alive even when the UI disconnects and
// match the stream's lifecycle to the ViewModel's one.
.autoConnect(0)
}
/**
* Translate an [MviIntent] to an [MviAction].
* Used to decouple the UI and the business logic to allow easy testings and reusability.
*/
private fun actionFromIntent(intent: TaskDetailIntent): TaskDetailAction {
return when (intent) {
is TaskDetailIntent.InitialIntent -> PopulateTaskAction(intent.taskId)
is TaskDetailIntent.DeleteTask -> DeleteTaskAction(intent.taskId)
is TaskDetailIntent.ActivateTaskIntent -> ActivateTaskAction(intent.taskId)
is TaskDetailIntent.CompleteTaskIntent -> CompleteTaskAction(intent.taskId)
}
}
override fun onCleared() {
disposables.dispose()
}
companion object {
/**
* The Reducer is where [MviViewState], that the [MviView] will use to
* render itself, are created.
* It takes the last cached [MviViewState], the latest [MviResult] and
* creates a new [MviViewState] by only updating the related fields.
* This is basically like a big switch statement of all possible types for the [MviResult]
*/
private val reducer =
BiFunction { previousState: TaskDetailViewState, result: TaskDetailResult ->
when (result) {
is PopulateTaskResult -> when (result) {
is PopulateTaskResult.Success -> previousState.copy(
loading = false,
title = result.task.title!!,
description = result.task.description!!,
active = result.task.active
)
is PopulateTaskResult.Failure -> previousState.copy(
loading = false, error = result.error
)
is PopulateTaskResult.InFlight -> previousState.copy(loading = true)
}
is ActivateTaskResult -> when (result) {
is ActivateTaskResult.Success -> previousState.copy(
uiNotification = TASK_ACTIVATED,
active = true
)
is ActivateTaskResult.Failure -> previousState.copy(error = result.error)
is ActivateTaskResult.InFlight -> previousState
is ActivateTaskResult.HideUiNotification ->
if (previousState.uiNotification == TASK_ACTIVATED) {
previousState.copy(
uiNotification = null
)
} else {
previousState
}
}
is CompleteTaskResult -> when (result) {
is CompleteTaskResult.Success -> previousState.copy(
uiNotification = TASK_COMPLETE,
active = false
)
is CompleteTaskResult.Failure -> previousState.copy(error = result.error)
is CompleteTaskResult.InFlight -> previousState
is CompleteTaskResult.HideUiNotification ->
if (previousState.uiNotification == TASK_COMPLETE) {
previousState.copy(
uiNotification = null
)
} else {
previousState
}
}
is DeleteTaskResult -> when (result) {
is DeleteTaskResult.Success -> previousState.copy(uiNotification = TASK_DELETED)
is DeleteTaskResult.Failure -> previousState.copy(error = result.error)
is DeleteTaskResult.InFlight -> previousState
}
}
}
}
}
| apache-2.0 | dc01d855715c1da712bb26de5d3a114d | 46.015873 | 119 | 0.716408 | 5.175306 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/EXT_external_objects_win32.kt | 4 | 4528 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengles.templates
import org.lwjgl.generator.*
import opengles.*
val EXT_memory_object_win32 = "EXTMemoryObjectWin32".nativeClassGLES("EXT_memory_object_win32", postfix = EXT) {
documentation =
"""
Native bindings to the ${registryLink("EXT_external_objects_win32")} extension.
Building upon the OpenGL memory object and semaphore framework defined in ${registryLinkTo("EXT", "external_objects")}, this extension enables an
OpenGL application to import a memory object or semaphore from a Win32 NT handle or a KMT share handle.
"""
IntConstant(
"""
Accepted by the {@code handleType} parameter of #ImportMemoryWin32HandleEXT(), #ImportMemoryWin32NameEXT(), #ImportSemaphoreWin32HandleEXT(), and
#ImportSemaphoreWin32NameEXT().
""",
"HANDLE_TYPE_OPAQUE_WIN32_EXT"..0x9587
)
IntConstant(
"Accepted by the {@code handleType} parameter of #ImportMemoryWin32HandleEXT() and #ImportSemaphoreWin32HandleEXT().",
"HANDLE_TYPE_OPAQUE_WIN32_KMT_EXT"..0x9588
)
IntConstant(
"""
Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetFloatv, GetIntegerv, GetInteger64v, GetBooleani_v, GetIntegeri_v, GetFloati_v,
GetDoublei_v, and GetInteger64i_v.
""",
"DEVICE_LUID_EXT"..0x9599,
"DEVICE_NODE_MASK_EXT"..0x959A
)
IntConstant(
"Constant values.",
"LUID_SIZE_EXT".."8"
)
IntConstant(
"Accepted by the {@code handleType} parameter of #ImportMemoryWin32HandleEXT() and #ImportMemoryWin32NameEXT().",
"HANDLE_TYPE_D3D12_TILEPOOL_EXT"..0x9589,
"HANDLE_TYPE_D3D12_RESOURCE_EXT"..0x958A,
"HANDLE_TYPE_D3D11_IMAGE_EXT"..0x958B
)
IntConstant(
"Accepted by the {@code handleType} parameter of #ImportMemoryWin32HandleEXT().",
"HANDLE_TYPE_D3D11_IMAGE_KMT_EXT"..0x958C
)
void(
"ImportMemoryWin32HandleEXT",
"",
GLuint("memory", ""),
GLuint64("size", ""),
GLenum("handleType", ""),
opaque_p("handle", "")
)
void(
"ImportMemoryWin32NameEXT",
"",
GLuint("memory", ""),
GLuint64("size", ""),
GLenum("handleType", ""),
opaque_const_p("name", "")
)
}
val EXT_semaphore_win32 = "EXTSemaphoreWin32".nativeClassGLES("EXT_semaphore_win32", postfix = EXT) {
documentation =
"""
Native bindings to the ${registryLink("EXT_external_objects_win32")} extension.
Building upon the OpenGL memory object and semaphore framework defined in ${registryLinkTo("EXT", "external_objects")}, this extension enables an
OpenGL application to import a memory object or semaphore from a Win32 NT handle or a KMT share handle.
"""
IntConstant(
"""
Accepted by the {@code handleType} parameter of #ImportMemoryWin32HandleEXT(), #ImportMemoryWin32NameEXT(), #ImportSemaphoreWin32HandleEXT(), and
#ImportSemaphoreWin32NameEXT().
""",
"HANDLE_TYPE_OPAQUE_WIN32_EXT"..0x9587
)
IntConstant(
"Accepted by the {@code handleType} parameter of #ImportMemoryWin32HandleEXT() and #ImportSemaphoreWin32HandleEXT().",
"HANDLE_TYPE_OPAQUE_WIN32_KMT_EXT"..0x9588
)
IntConstant(
"""
Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetFloatv, GetIntegerv, GetInteger64v, GetBooleani_v, GetIntegeri_v, GetFloati_v,
GetDoublei_v, and GetInteger64i_v.
""",
"DEVICE_LUID_EXT"..0x9599,
"DEVICE_NODE_MASK_EXT"..0x959A
)
IntConstant(
"Constant values.",
"LUID_SIZE_EXT".."8"
)
IntConstant(
"Accepted by the {@code handleType} parameter of #ImportSemaphoreWin32HandleEXT().",
"HANDLE_TYPE_D3D12_FENCE_EXT"..0x9594
)
IntConstant(
"Accepted by the {@code pname} parameter of #SemaphoreParameterui64vEXT() and #GetSemaphoreParameterui64vEXT().",
"D3D12_FENCE_VALUE_EXT"..0x9595
)
void(
"ImportSemaphoreWin32HandleEXT",
"",
GLuint("semaphore", ""),
GLenum("handleType", ""),
opaque_p("handle", "")
)
void(
"ImportSemaphoreWin32NameEXT",
"",
GLuint("semaphore", ""),
GLenum("handleType", ""),
opaque_const_p("name", "")
)
} | bsd-3-clause | 202fcc4af21dd00d2de85c7810875cec | 28.409091 | 157 | 0.626988 | 4.328872 | false | false | false | false |
AshishKayastha/Movie-Guide | app/src/main/kotlin/com/ashish/movieguide/utils/extensions/ButterKnife.kt | 1 | 2426 | @file:Suppress("unused")
package com.ashish.movieguide.utils.extensions
import android.app.Activity
import android.support.v4.app.Fragment
import android.support.v7.widget.RecyclerView.ViewHolder
import android.view.View
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
// Required Views
fun <V : View> View.bindView(id: Int): ReadOnlyProperty<View, V> = required(id, viewFinder)
fun <V : View> Activity.bindView(id: Int): ReadOnlyProperty<Activity, V> = required(id, viewFinder)
fun <V : View> Fragment.bindView(id: Int): ReadOnlyProperty<Fragment, V> = required(id, viewFinder)
fun <V : View> ViewHolder.bindView(id: Int): ReadOnlyProperty<ViewHolder, V> = required(id, viewFinder)
// Optional Views
fun <V : View> Activity.bindOptionalView(id: Int): ReadOnlyProperty<Activity, V?> = optional(id, viewFinder)
fun <V : View> Fragment.bindOptionalView(id: Int): ReadOnlyProperty<Fragment, V?> = optional(id, viewFinder)
fun <V : View> ViewHolder.bindOptionalView(id: Int)
: ReadOnlyProperty<ViewHolder, V?> = optional(id, viewFinder)
// Getters
private val View.viewFinder: View.(Int) -> View?
get() = { findViewById(it) }
private val Activity.viewFinder: Activity.(Int) -> View?
get() = { findViewById(it) }
private val Fragment.viewFinder: Fragment.(Int) -> View?
get() = { view?.findViewById(it) }
private val ViewHolder.viewFinder: ViewHolder.(Int) -> View?
get() = { itemView.findViewById(it) }
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> required(id: Int, finder: T.(Int) -> View?)
= Lazy { t: T, desc -> t.finder(id) as V? ?: viewNotFound(id, desc) }
private fun viewNotFound(id: Int, desc: KProperty<*>): Nothing =
throw IllegalStateException("View ID $id for '${desc.name}' not found.")
@Suppress("UNCHECKED_CAST")
private fun <T, V : View> optional(id: Int, finder: T.(Int) -> View?)
= Lazy { t: T, _ -> t.finder(id) as V? }
// Like Kotlin's lazy delegate but the initializer gets the target and metadata passed to it
private class Lazy<in T, out V>(private val initializer: (T, KProperty<*>) -> V) : ReadOnlyProperty<T, V> {
private object EMPTY
private var value: Any? = EMPTY
override fun getValue(thisRef: T, property: KProperty<*>): V {
if (value == EMPTY) {
value = initializer(thisRef, property)
}
@Suppress("UNCHECKED_CAST")
return value as V
}
} | apache-2.0 | d873d172ae8f576b880383f321b7151c | 35.772727 | 108 | 0.689613 | 3.698171 | false | false | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/dalatlaptop/ux/adapters/DrawerRecyclerAdapter.kt | 1 | 1961 | package com.tungnui.dalatlaptop.ux.adapters
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.tungnui.dalatlaptop.models.Category
import java.util.ArrayList
import com.tungnui.dalatlaptop.R
import com.tungnui.dalatlaptop.utils.inflate
import kotlinx.android.synthetic.main.list_item_drawer_category.view.*
class DrawerRecyclerAdapter(val listener: (Category) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val listCategory = ArrayList<Category>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
ViewHolderItemCategory(parent.inflate(R.layout.list_item_drawer_category))
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
(holder as ViewHolderItemCategory).blind(listCategory[position],listener)
}
override fun getItemCount(): Int {
return listCategory.size
}
fun changeDrawerItems(categories: List<Category>) {
listCategory.clear()
listCategory.addAll(categories)
notifyDataSetChanged()
}
class ViewHolderItemCategory(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun blind(item:Category,listener: (Category) -> Unit)=with(itemView){
drawer_list_item_text.text = item.name
drawer_list_item_text.setTextColor(ContextCompat.getColor(context, R.color.textPrimary))
drawer_list_item_text.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
drawer_list_item_divider.visibility = View.GONE
if (item.display == "subcategories") {
drawer_list_item_indicator.visibility = View.VISIBLE
} else {
drawer_list_item_indicator.visibility = View.INVISIBLE
}
setOnClickListener { listener(item) }
}
}
}
| mit | baa71673df6d5cc392599a36718678d8 | 36 | 113 | 0.713412 | 4.549884 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/internal/ui/uiDslShowcase/UiDslShowcaseAction.kt | 3 | 4159 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.ui.uiDslShowcase
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.components.JBTabbedPane
import com.intellij.ui.dsl.builder.BottomGap
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.ui.dsl.gridLayout.VerticalAlign
import com.intellij.util.ui.JBEmptyBorder
import java.awt.Dimension
import javax.swing.JComponent
import kotlin.reflect.KFunction
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.jvm.javaMethod
const val BASE_URL = "https://github.com/JetBrains/intellij-community/blob/master/platform/platform-impl/"
val DEMOS = arrayOf(
::demoBasics,
::demoRowLayout,
::demoComponentLabels,
::demoComments,
::demoComponents,
::demoGaps,
::demoGroups,
::demoAvailability,
::demoBinding,
::demoTips
)
internal class UiDslShowcaseAction : DumbAwareAction() {
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun actionPerformed(e: AnActionEvent) {
UiDslShowcaseDialog(e.project, templatePresentation.text).show()
}
}
private class UiDslShowcaseDialog(val project: Project?, dialogTitle: String) :
DialogWrapper(project, null, true, IdeModalityType.MODELESS, false) {
init {
title = dialogTitle
init()
}
override fun createCenterPanel(): JComponent {
val result = JBTabbedPane()
result.minimumSize = Dimension(400, 300)
result.preferredSize = Dimension(800, 600)
for (demo in DEMOS) {
addDemo(demo, result)
}
return result
}
private fun addDemo(demo: KFunction<DialogPanel>, tabbedPane: JBTabbedPane) {
val annotation = demo.findAnnotation<Demo>()
if (annotation == null) {
throw Exception("Demo annotation is missed for ${demo.name}")
}
val content = panel {
row {
label("<html>Description: ${annotation.description}")
}
val simpleName = "src/${demo.javaMethod!!.declaringClass.name}".replace('.', '/')
val fileName = (simpleName.substring(0..simpleName.length - 3) + ".kt")
row {
link("View source") {
if (!openInIdeaProject(fileName)) {
BrowserUtil.browse(BASE_URL + fileName)
}
}
}.bottomGap(BottomGap.MEDIUM)
val args = demo.parameters.associateBy(
{ it },
{
when (it.name) {
"parentDisposable" -> myDisposable
else -> null
}
}
)
val dialogPanel = demo.callBy(args)
if (annotation.scrollbar) {
row {
dialogPanel.border = JBEmptyBorder(10)
scrollCell(dialogPanel)
.horizontalAlign(HorizontalAlign.FILL)
.verticalAlign(VerticalAlign.FILL)
.resizableColumn()
}.resizableRow()
}
else {
row {
cell(dialogPanel)
.horizontalAlign(HorizontalAlign.FILL)
.resizableColumn()
}
}
}
tabbedPane.add(annotation.title, content)
}
private fun openInIdeaProject(fileName: String): Boolean {
if (project == null) {
return false
}
val moduleManager = ModuleManager.getInstance(project)
val module = moduleManager.findModuleByName("intellij.platform.ide.impl")
if (module == null) {
return false
}
for (contentRoot in module.rootManager.contentRoots) {
val file = contentRoot.findFileByRelativePath(fileName)
if (file?.isValid == true) {
OpenFileDescriptor(project, file).navigate(true)
return true
}
}
return false
}
}
| apache-2.0 | d4e40c71d396451d9d9c9bcadf4653f7 | 28.496454 | 120 | 0.688146 | 4.424468 | false | false | false | false |
orauyeu/SimYukkuri | subprojects/messageutil/src/main/kotlin/shitarabatogit/ParseMessage.kt | 1 | 4225 | package shitarabatogit
import messageutil.*
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.Path
/**
* したらば版形式のメッセージを読み込み, アクション名 -> (コメント, ゆっくりタイプ) -> セリフリスト) の形式のマップを返す.
*
* "<"と">"はセットになっていることを前提とする.
*
* @param strict falseのときタグの閉じ忘れや閉じすぎを無視する.
*/
fun parseShitarabaMessage(path: Path, strict: Boolean = true): CommentedMessageCollection =
Files.newInputStream(path).use { parseShitarabaMessage(it, strict) }
/**
* したらば版形式のメッセージを読み込み, アクション名 -> (コメント, ゆっくりタイプ -> (コメント, セリフリスト)) の形式のマップを返す.
*
* @param strict falseのときタグの閉じ忘れや閉じすぎを無視する.
*/
fun parseShitarabaMessage(input: InputStream, strict: Boolean = true): CommentedMessageCollection {
val msgData = mutableCommentedMessageCollection()
// 現在の行における状態
var lineNumber = 0
var actionName = ""
val comments = mutableListOf<String>()
var cond = emptyCondition
input.bufferedReader().forEachLine {
lineNumber += 1
val line = it.trim { it <= ' ' }
if (line.isEmpty()) return@forEachLine
val first = line[0]
if (first == '#') {
comments.add(line.substring(1))
return@forEachLine
}
// アクション
if (first == '[') {
// 閉じタグの場合
if (line[1] == '/') {
if (actionName.isEmpty()) {
if (strict)
throw RuntimeException("対応する開始タグがありません at $lineNumber")
else {
val openPos = 2
val closePos = line.indexOf(']')
actionName = line.substring(openPos, closePos)
}
}
msgData.getOrPut(actionName) { MutableCommented(linkedMapOf()) }.commentLines.addAll(comments)
comments.clear()
actionName = ""
if (cond != emptyCondition)
if (strict)
throw RuntimeException("閉じられていない属性があります at $lineNumber: ${cond.toSimpleString()}")
cond = emptyCondition
return@forEachLine
}
// 開始タグの場合
else {
if (actionName.isNotEmpty())
throw RuntimeException("閉じられていないアクションがあります at $lineNumber: $actionName")
val openPos = 1
val closePos = line.indexOf(']')
actionName = line.substring(openPos, closePos)
return@forEachLine
}
}
// タイプ
else if (first == '<') {
// 閉じタグの場合
if (line[1] == '/') {
val openPos = 2
val closePos = line.indexOf('>')
val attr = line.substring(openPos, closePos)
if (!cond.contains(attr))
if (strict)
throw Exception("対応する開始タグがありません at $lineNumber: $attr")
cond = cond.removed(attr)
return@forEachLine
}
// 開始タグの場合
else {
val openPos = 1
val closePos = line.indexOf('>')
val attr = line.substring(openPos, closePos)
cond = cond.added(attr)
return@forEachLine
}
}
// メッセージ本文
else {
msgData.getOrPut(actionName) { MutableCommented(linkedMapOf()) }
.body.getOrPut(cond) { mutableListOf<String>() }
.add(line)
}
}
if (actionName.isNotEmpty())
throw RuntimeException("閉じられていないアクションがあります at $lineNumber: $actionName")
return msgData
} | apache-2.0 | eca533f5ecba0e221ceac5d1ec70e300 | 31.428571 | 110 | 0.52217 | 4.261737 | false | false | false | false |
LookitheFirst/redditlive | src/main/java/io/looki/redditlive/LiveMessageObservable.kt | 1 | 2469 | package io.looki.redditlive
import com.google.gson.Gson
import com.google.gson.internal.LinkedTreeMap
import com.google.gson.reflect.TypeToken
import io.reactivex.ObservableEmitter
import io.reactivex.ObservableOnSubscribe
import okhttp3.*
class LiveMessageObservable(private val gson: Gson, okHttpClient: OkHttpClient, websocketUrl: String) : ObservableOnSubscribe<LiveMessage<LiveMessage.GenericPayload>>, WebSocketListener() {
private val emitterList = mutableListOf<ObservableEmitter<LiveMessage<LiveMessage.GenericPayload>>>()
private val request = Request.Builder().url(websocketUrl).build()
init { okHttpClient.newWebSocket(request, this) }
override fun subscribe(observableEmitter: ObservableEmitter<LiveMessage<LiveMessage.GenericPayload>>) { emitterList += observableEmitter }
override fun onOpen(webSocket: WebSocket, response: Response) { println("Opened Websocket") }
override fun onMessage(webSocket: WebSocket, text: String) {
//Get the payload from the sent data to find out what kind of message we received
val rawMessage = gson.fromJson<LiveMessage<Any>>(text)
//Check if content of Payload is String or Object (String means Delete or Strike Event)
val messageContent = when (rawMessage.payload) {
//If Object it should be a LinkedTreeMap. In this case find the Event in the LiveEvent.PayloadType enum and parse the JSON to the corresponding POJO schema
is LinkedTreeMap<*,*> -> gson.fromJson(gson.toJsonTree(rawMessage.payload), rawMessage.type.payload)
is String -> rawMessage.type.payload.getDeclaredConstructor(String::class.java).newInstance(rawMessage.payload)
else -> throw Exception("Corrupt Payload")
}
//Create a new LiveMessage POJO with the correct child type
val processedMessage = LiveMessage(rawMessage.type, messageContent)
emitterList.forEach { it.onNext(processedMessage) }
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
emitterList.forEach { it.onComplete() }
println("Closing Websocket ($code: $reason)")
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
emitterList.forEach { it.onError(t) }
println("Websocket Error")
t.printStackTrace()
}
private inline fun <reified T> Gson.fromJson(json: String) = this.fromJson<T>(json, object: TypeToken<T>() {}.type)
} | gpl-3.0 | 5c91bd91cd3831987107416a6c96a7d9 | 51.553191 | 189 | 0.73228 | 4.748077 | false | false | false | false |
sachil/Essence | app/src/main/java/xyz/sachil/essence/model/cache/dao/TypeDataDao.kt | 1 | 1047 | package xyz.sachil.essence.model.cache.dao
import androidx.paging.DataSource
import androidx.room.*
import xyz.sachil.essence.model.net.bean.TypeData
import xyz.sachil.essence.util.Utils
@Dao
interface TypeDataDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertTypeData(typeDataList: List<TypeData>)
@Query("SELECT * FROM type_data_table WHERE category=:category AND type=:type ORDER BY published_date DESC ")
fun getTypeData(category: String, type: String): DataSource.Factory<Int, TypeData>
@Update(onConflict = OnConflictStrategy.REPLACE)
fun updateTypeData(vararg typeData: TypeData)
@Query("SELECT COUNT(id) FROM type_data_table WHERE category=:category AND type=:type")
fun getCount(category: String, type: String): Int
@Delete
fun deleteTypeData(vararg typeData: TypeData)
@Query("DELETE FROM type_data_table WHERE category=:category AND type=:type")
fun deleteTypeData(category: String, type: String)
@Query("DELETE FROM type_data_table")
fun deleteAllData()
} | apache-2.0 | 2dbedb9204fbca2c826fc1a64bc0701e | 32.806452 | 113 | 0.751671 | 4.105882 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/insight/ColorUtil.kt | 1 | 3301 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.insight
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.util.runWriteAction
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.JavaTokenType
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiExpressionList
import com.intellij.psi.PsiLiteralExpression
import com.intellij.psi.PsiReferenceExpression
import java.awt.Color
fun <T> PsiElement.findColor(function: (Map<String, Color>, Map.Entry<String, Color>) -> T): T? {
if (this !is PsiReferenceExpression) {
return null
}
val module = ModuleUtilCore.findModuleForPsiElement(this) ?: return null
val facet = MinecraftFacet.getInstance(module) ?: return null
val expression = this
val type = expression.type ?: return null
for (abstractModuleType in facet.types) {
val map = abstractModuleType.classToColorMappings
for (entry in map.entries) {
// This is such a hack
// Okay, type will be the fully-qualified class, but it will exclude the actual enum
// the expression will be the non-fully-qualified class with the enum
// So we combine those checks and get this
if (entry.key.startsWith(type.canonicalText) && entry.key.endsWith(expression.canonicalText)) {
return function(map, entry)
}
}
}
return null
}
fun PsiElement.setColor(color: String) {
this.containingFile.runWriteAction {
val split = color.split(".").dropLastWhile(String::isEmpty).toTypedArray()
val newColorBase = split.last()
val node = this.node
val child = node.findChildByType(JavaTokenType.IDENTIFIER) ?: return@runWriteAction
val identifier = JavaPsiFacade.getElementFactory(this.project).createIdentifier(newColorBase)
child.psi.replace(identifier)
}
}
fun PsiLiteralExpression.setColor(value: Int) {
this.containingFile.runWriteAction {
val node = this.node
val literalExpression = JavaPsiFacade.getElementFactory(this.project)
.createExpressionFromText("0x" + Integer.toHexString(value).toUpperCase(), null) as PsiLiteralExpression
node.psi.replace(literalExpression)
}
}
fun PsiExpressionList.setColor(red: Int, green: Int, blue: Int) {
this.containingFile.runWriteAction {
val expressionOne = this.expressions[0]
val expressionTwo = this.expressions[1]
val expressionThree = this.expressions[2]
val nodeOne = expressionOne.node
val nodeTwo = expressionTwo.node
val nodeThree = expressionThree.node
val facade = JavaPsiFacade.getElementFactory(this.project)
val literalExpressionOne = facade.createExpressionFromText(red.toString(), null)
val literalExpressionTwo = facade.createExpressionFromText(green.toString(), null)
val literalExpressionThree = facade.createExpressionFromText(blue.toString(), null)
nodeOne.psi.replace(literalExpressionOne)
nodeTwo.psi.replace(literalExpressionTwo)
nodeThree.psi.replace(literalExpressionThree)
}
}
| mit | c7ab245e37beb82b09dd556cada4a49d | 33.385417 | 116 | 0.708876 | 4.649296 | false | false | false | false |
nibarius/opera-park-android | app/src/main/java/se/barsk/park/storage/ParkContract.kt | 1 | 988 | package se.barsk.park.storage
import android.provider.BaseColumns
object ParkContract {
const val SQL_CREATE_ENTRIES =
"CREATE TABLE " + CarCollectionTable.TABLE_NAME + " (" +
CarCollectionTable.COLUMN_NAME_UUID + " TEXT PRIMARY KEY," +
CarCollectionTable.COLUMN_NAME_POSITION + " INTEGER," +
CarCollectionTable.COLUMN_NAME_REGNO + " TEXT," +
CarCollectionTable.COLUMN_NAME_OWNER + " TEXT," +
CarCollectionTable.COLUMN_NAME_NICKNAME + " TEXT)"
class CarCollectionTable private constructor() : BaseColumns {
companion object {
const val TABLE_NAME = "car_collection"
const val COLUMN_NAME_UUID = "uuid"
const val COLUMN_NAME_POSITION = "position"
const val COLUMN_NAME_REGNO = "regno"
const val COLUMN_NAME_OWNER = "owner"
const val COLUMN_NAME_NICKNAME = "nickname"
}
}
} | mit | 495534db4f70ee4690ddfbf3b0e81d01 | 37.038462 | 80 | 0.59413 | 4.796117 | false | false | false | false |
apoi/quickbeer-next | app/src/main/java/quickbeer/android/domain/stylelist/network/StyleJson.kt | 2 | 414 | package quickbeer.android.domain.stylelist.network
import com.squareup.moshi.Json
data class StyleJson(
@field:Json(name = "BeerStyleID") val id: Int,
@field:Json(name = "BeerStyleName") val name: String,
@field:Json(name = "BeerStyleDescription") val description: String?,
@field:Json(name = "BeerStyleParent") val parent: Int?,
@field:Json(name = "BeerStyleCategory") val category: Int?,
)
| gpl-3.0 | 1fcbd5f50a72dfe2e2d8a9cf8d3e53bf | 36.636364 | 72 | 0.717391 | 3.568966 | false | false | false | false |
google/intellij-community | platform/diff-impl/src/com/intellij/openapi/vcs/ex/RangesBuilder.kt | 5 | 10148 | /*
* 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:JvmName("RangesBuilder")
package com.intellij.openapi.vcs.ex
import com.intellij.diff.comparison.*
import com.intellij.diff.comparison.iterables.DiffIterableUtil
import com.intellij.diff.comparison.iterables.DiffIterableUtil.fair
import com.intellij.diff.comparison.iterables.FairDiffIterable
import com.intellij.diff.tools.util.text.LineOffsets
import com.intellij.diff.tools.util.text.LineOffsetsUtil
import com.intellij.diff.util.DiffRangeUtil
import com.intellij.diff.util.Range
import com.intellij.diff.util.Side
import com.intellij.openapi.editor.Document
import com.intellij.openapi.progress.DumbProgressIndicator
import kotlin.math.max
fun createRanges(current: List<String>,
vcs: List<String>,
currentShift: Int,
vcsShift: Int,
innerWhitespaceChanges: Boolean): List<LstRange> {
val iterable = compareLines(vcs, current)
return iterable.iterateChanges().map {
val inner = if (innerWhitespaceChanges) createInnerRanges(vcs.subList(it.start1, it.end1), current.subList(it.start2, it.end2)) else null
LstRange(it.start2 + currentShift, it.end2 + currentShift, it.start1 + vcsShift, it.end1 + vcsShift, inner)
}
}
fun createRanges(current: Document, vcs: Document): List<LstRange> {
return createRanges(current.immutableCharSequence, vcs.immutableCharSequence, current.lineOffsets, vcs.lineOffsets)
}
fun createRanges(current: CharSequence, vcs: CharSequence): List<LstRange> {
return createRanges(current, vcs, current.lineOffsets, vcs.lineOffsets)
}
private fun createRanges(current: CharSequence,
vcs: CharSequence,
currentLineOffsets: LineOffsets,
vcsLineOffsets: LineOffsets): List<LstRange> {
val iterable = compareLines(vcs, current, vcsLineOffsets, currentLineOffsets)
return iterable.iterateChanges().map { LstRange(it.start2, it.end2, it.start1, it.end1) }
}
fun compareLines(text1: CharSequence,
text2: CharSequence,
lineOffsets1: LineOffsets,
lineOffsets2: LineOffsets): FairDiffIterable {
val range = expand(text1, text2, 0, 0, text1.length, text2.length)
if (range.isEmpty) return fair(DiffIterableUtil.create(emptyList(), lineOffsets1.lineCount, lineOffsets2.lineCount))
val contextLines = 5
val start = max(lineOffsets1.getLineNumber(range.start1) - contextLines, 0)
val tail = max(lineOffsets1.lineCount - lineOffsets1.getLineNumber(range.end1) - 1 - contextLines, 0)
val lineRange = Range(start, lineOffsets1.lineCount - tail, start, lineOffsets2.lineCount - tail)
val iterable = compareLines(lineRange, text1, text2, lineOffsets1, lineOffsets2)
return fair(DiffIterableUtil.expandedIterable(iterable, start, start, lineOffsets1.lineCount, lineOffsets2.lineCount))
}
fun compareLines(lineRange: Range,
text1: CharSequence,
text2: CharSequence,
lineOffsets1: LineOffsets,
lineOffsets2: LineOffsets): FairDiffIterable {
val lines1 = DiffRangeUtil.getLines(text1, lineOffsets1, lineRange.start1, lineRange.end1)
val lines2 = DiffRangeUtil.getLines(text2, lineOffsets2, lineRange.start2, lineRange.end2)
return compareLines(lines1, lines2)
}
fun tryCompareLines(lineRange: Range,
text1: CharSequence,
text2: CharSequence,
lineOffsets1: LineOffsets,
lineOffsets2: LineOffsets): FairDiffIterable? {
val lines1 = DiffRangeUtil.getLines(text1, lineOffsets1, lineRange.start1, lineRange.end1)
val lines2 = DiffRangeUtil.getLines(text2, lineOffsets2, lineRange.start2, lineRange.end2)
return tryCompareLines(lines1, lines2)
}
fun fastCompareLines(lineRange: Range,
text1: CharSequence,
text2: CharSequence,
lineOffsets1: LineOffsets,
lineOffsets2: LineOffsets): FairDiffIterable {
val lines1 = DiffRangeUtil.getLines(text1, lineOffsets1, lineRange.start1, lineRange.end1)
val lines2 = DiffRangeUtil.getLines(text2, lineOffsets2, lineRange.start2, lineRange.end2)
return fastCompareLines(lines1, lines2)
}
fun createInnerRanges(lineRange: Range,
text1: CharSequence,
text2: CharSequence,
lineOffsets1: LineOffsets,
lineOffsets2: LineOffsets): List<LstInnerRange> {
val lines1 = DiffRangeUtil.getLines(text1, lineOffsets1, lineRange.start1, lineRange.end1)
val lines2 = DiffRangeUtil.getLines(text2, lineOffsets2, lineRange.start2, lineRange.end2)
return createInnerRanges(lines1, lines2)
}
private fun compareLines(lines1: List<String>,
lines2: List<String>): FairDiffIterable {
val iwIterable: FairDiffIterable = safeCompareLines(lines1, lines2, ComparisonPolicy.IGNORE_WHITESPACES)
return processLines(lines1, lines2, iwIterable)
}
private fun tryCompareLines(lines1: List<String>,
lines2: List<String>): FairDiffIterable? {
val iwIterable: FairDiffIterable = tryCompareLines(lines1, lines2, ComparisonPolicy.IGNORE_WHITESPACES) ?: return null
return processLines(lines1, lines2, iwIterable)
}
private fun fastCompareLines(lines1: List<String>,
lines2: List<String>): FairDiffIterable {
val iwIterable: FairDiffIterable = fastCompareLines(lines1, lines2, ComparisonPolicy.IGNORE_WHITESPACES)
return processLines(lines1, lines2, iwIterable)
}
/**
* Compare lines, preferring non-optimal but less confusing results for whitespace-only changed lines
* Ex: "X\n\nY\nZ" vs " X\n Y\n\n Z" should be a single big change, rather than 2 changes separated by "matched" empty line.
*/
private fun processLines(lines1: List<String>,
lines2: List<String>,
iwIterable: FairDiffIterable): FairDiffIterable {
val builder = DiffIterableUtil.ExpandChangeBuilder(lines1, lines2)
for (range in iwIterable.unchanged()) {
val count = range.end1 - range.start1
for (i in 0 until count) {
val index1 = range.start1 + i
val index2 = range.start2 + i
if (lines1[index1] == lines2[index2]) {
builder.markEqual(index1, index2)
}
}
}
return fair(builder.finish())
}
private fun createInnerRanges(lines1: List<String>,
lines2: List<String>): List<LstInnerRange> {
val iwIterable: FairDiffIterable = safeCompareLines(lines1, lines2, ComparisonPolicy.IGNORE_WHITESPACES)
val result = ArrayList<LstInnerRange>()
for (pair in DiffIterableUtil.iterateAll(iwIterable)) {
val range = pair.first
val equals = pair.second
result.add(LstInnerRange(range.start2, range.end2, getChangeType(range, equals)))
}
result.trimToSize()
return result
}
private fun getChangeType(range: Range, equals: Boolean): Byte {
if (equals) return LstRange.EQUAL
val deleted = range.end1 - range.start1
val inserted = range.end2 - range.start2
if (deleted > 0 && inserted > 0) return LstRange.MODIFIED
if (deleted > 0) return LstRange.DELETED
if (inserted > 0) return LstRange.INSERTED
return LstRange.EQUAL
}
private fun safeCompareLines(lines1: List<String>, lines2: List<String>, comparisonPolicy: ComparisonPolicy): FairDiffIterable {
return tryCompareLines(lines1, lines2, comparisonPolicy) ?: fastCompareLines(lines1, lines2, comparisonPolicy)
}
private fun tryCompareLines(lines1: List<String>, lines2: List<String>, comparisonPolicy: ComparisonPolicy): FairDiffIterable? {
try {
return ByLine.compare(lines1, lines2, comparisonPolicy, DumbProgressIndicator.INSTANCE)
}
catch (e: DiffTooBigException) {
return null
}
}
private fun fastCompareLines(lines1: List<String>, lines2: List<String>, comparisonPolicy: ComparisonPolicy): FairDiffIterable {
val range = expand(lines1, lines2, 0, 0, lines1.size, lines2.size,
{ line1, line2 -> ComparisonUtil.isEquals(line1, line2, comparisonPolicy) })
val ranges = if (range.isEmpty) emptyList() else listOf(range)
return fair(DiffIterableUtil.create(ranges, lines1.size, lines2.size))
}
fun isValidRanges(content1: CharSequence,
content2: CharSequence,
lineOffsets1: LineOffsets,
lineOffsets2: LineOffsets,
lineRanges: List<Range>): Boolean {
val allRangesValid = lineRanges.all {
isValidLineRange(lineOffsets1, it.start1, it.end1) &&
isValidLineRange(lineOffsets2, it.start2, it.end2)
}
if (!allRangesValid) return false
val iterable = DiffIterableUtil.create(lineRanges, lineOffsets1.lineCount, lineOffsets2.lineCount)
for (range in iterable.iterateUnchanged()) {
val lines1 = DiffRangeUtil.getLines(content1, lineOffsets1, range.start1, range.end1)
val lines2 = DiffRangeUtil.getLines(content2, lineOffsets2, range.start2, range.end2)
if (lines1 != lines2) {
return false
}
}
return true
}
private fun isValidLineRange(lineOffsets: LineOffsets, start: Int, end: Int): Boolean {
return start in 0..end && end <= lineOffsets.lineCount
}
internal operator fun <T> Side.get(v1: T, v2: T): T = if (isLeft) v1 else v2
internal fun Range.start(side: Side) = side[start1, start2]
internal fun Range.end(side: Side) = side[end1, end2]
internal val Document.lineOffsets: LineOffsets get() = LineOffsetsUtil.create(this)
internal val CharSequence.lineOffsets: LineOffsets get() = LineOffsetsUtil.create(this) | apache-2.0 | edfdc9612fea891473f1162652259b62 | 41.822785 | 141 | 0.714229 | 4.207297 | false | false | false | false |
google/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/Expressions.kt | 2 | 10270 | // 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.j2k.ast
import com.intellij.psi.JavaTokenType
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.j2k.CodeBuilder
import org.jetbrains.kotlin.j2k.append
import org.jetbrains.kotlin.lexer.KtTokens
import java.util.*
class ArrayAccessExpression(val expression: Expression, val index: Expression, val lvalue: Boolean) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, expression)
if (!lvalue && expression.isNullable) builder.append("!!")
builder append "[" append index append "]"
}
}
open class AssignmentExpression(val left: Expression, val right: Expression, val op: Operator) : Expression() {
fun isMultiAssignment() = right is AssignmentExpression
fun appendAssignment(builder: CodeBuilder, left: Expression, right: Expression) {
builder.appendOperand(this, left).append(" ").append(op).append(" ").appendOperand(this, right)
}
override fun generateCode(builder: CodeBuilder) {
if (right !is AssignmentExpression)
appendAssignment(builder, left, right)
else {
right.generateCode(builder)
builder.append("\n")
appendAssignment(builder, left, right.left)
}
}
}
class BangBangExpression(val expr: Expression) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, expr).append("!!")
}
companion object {
fun surroundIfNullable(expression: Expression): Expression {
return if (expression.isNullable)
BangBangExpression(expression).assignNoPrototype()
else
expression
}
}
}
class BinaryExpression(val left: Expression, val right: Expression, val op: Operator) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, left, false).append(" ").append(op).append(" ").appendOperand(this, right, true)
}
}
class IsOperator(val expression: Expression, val type: Type) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, expression).append(" is ").append(type)
}
}
class TypeCastExpression(val type: Type, val expression: Expression) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, expression).append(" as ").append(type)
}
override val isNullable: Boolean
get() = type.isNullable
}
open class LiteralExpression(val literalText: String) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.append(literalText)
}
object NullLiteral : LiteralExpression("null"){
override val isNullable: Boolean
get() = true
}
}
class ArrayLiteralExpression(val expressions: List<Expression>) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.append("[")
builder.append(expressions, ", ")
builder.append("]")
}
}
class ParenthesizedExpression(val expression: Expression) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder append "(" append expression append ")"
}
}
class PrefixExpression(val op: Operator, val expression: Expression) : Expression() {
override fun generateCode(builder: CodeBuilder){
builder.append(op).appendOperand(this, expression)
}
override val isNullable: Boolean
get() = expression.isNullable
}
class PostfixExpression(val op: Operator, val expression: Expression) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, expression) append op
}
}
class ThisExpression(val identifier: Identifier) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.append("this").appendWithPrefix(identifier, "@")
}
}
class SuperExpression(val identifier: Identifier) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.append("super").appendWithPrefix(identifier, "@")
}
}
class QualifiedExpression(val qualifier: Expression, val identifier: Expression, dotPrototype: PsiElement?) : Expression() {
private val dot = Dot().assignPrototype(dotPrototype, CommentsAndSpacesInheritance.LINE_BREAKS)
override val isNullable: Boolean
get() = identifier.isNullable
override fun generateCode(builder: CodeBuilder) {
if (!qualifier.isEmpty) {
builder.appendOperand(this, qualifier).append(if (qualifier.isNullable) "!!" else "")
builder.append(dot)
}
builder.append(identifier)
}
private class Dot : Element() {
override fun generateCode(builder: CodeBuilder) {
builder.append(".")
}
}
}
open class Operator(val operatorType: IElementType): Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.append(asString(operatorType))
}
fun asString() = asString(operatorType)
fun acceptLineBreakBefore(): Boolean {
return when(operatorType) {
JavaTokenType.ANDAND,
JavaTokenType.OROR,
JavaTokenType.PLUS,
JavaTokenType.MINUS -> true
else -> false
}
}
val precedence: Int
get() = when (this.operatorType) {
JavaTokenType.ASTERISK, JavaTokenType.DIV, JavaTokenType.PERC -> 3
JavaTokenType.PLUS, JavaTokenType.MINUS -> 4
KtTokens.ELVIS -> 7
JavaTokenType.GT, JavaTokenType.LT, JavaTokenType.GE, JavaTokenType.LE -> 9
JavaTokenType.EQEQ, JavaTokenType.NE, KtTokens.EQEQEQ, KtTokens.EXCLEQEQEQ -> 10
JavaTokenType.ANDAND -> 11
JavaTokenType.OROR -> 12
JavaTokenType.GTGTGT, JavaTokenType.GTGT, JavaTokenType.LTLT -> 7
else -> 6 /* simple name */
}
private fun asString(tokenType: IElementType): String {
return when (tokenType) {
JavaTokenType.EQ -> "="
JavaTokenType.EQEQ -> "=="
JavaTokenType.NE -> "!="
JavaTokenType.ANDAND -> "&&"
JavaTokenType.OROR -> "||"
JavaTokenType.GT -> ">"
JavaTokenType.LT -> "<"
JavaTokenType.GE -> ">="
JavaTokenType.LE -> "<="
JavaTokenType.EXCL -> "!"
JavaTokenType.PLUS -> "+"
JavaTokenType.MINUS -> "-"
JavaTokenType.ASTERISK -> "*"
JavaTokenType.DIV -> "/"
JavaTokenType.PERC -> "%"
JavaTokenType.PLUSEQ -> "+="
JavaTokenType.MINUSEQ -> "-="
JavaTokenType.ASTERISKEQ -> "*="
JavaTokenType.DIVEQ -> "/="
JavaTokenType.PERCEQ -> "%="
JavaTokenType.GTGT -> "shr"
JavaTokenType.LTLT -> "shl"
JavaTokenType.XOR -> "xor"
JavaTokenType.AND -> "and"
JavaTokenType.OR -> "or"
JavaTokenType.GTGTGT -> "ushr"
JavaTokenType.GTGTEQ -> "shr"
JavaTokenType.LTLTEQ -> "shl"
JavaTokenType.XOREQ -> "xor"
JavaTokenType.ANDEQ -> "and"
JavaTokenType.OREQ -> "or"
JavaTokenType.GTGTGTEQ -> "ushr"
JavaTokenType.PLUSPLUS -> "++"
JavaTokenType.MINUSMINUS -> "--"
KtTokens.EQEQEQ -> "==="
KtTokens.EXCLEQEQEQ -> "!=="
else -> "" //System.out.println("UNSUPPORTED TOKEN TYPE: " + tokenType?.toString())
}
}
companion object {
val EQEQ = Operator(JavaTokenType.EQEQ).assignNoPrototype()
val EQ = Operator(JavaTokenType.EQ).assignNoPrototype()
}
}
class LambdaExpression(val parameterList: ParameterList?, val block: Block) : Expression() {
init {
assignPrototypesFrom(block)
}
override fun generateCode(builder: CodeBuilder) {
builder append block.lBrace append " "
if (parameterList != null && !parameterList.parameters.isEmpty()) {
builder.append(parameterList)
.append("->")
.append(if (block.statements.size > 1) "\n" else " ")
.append(block.statements, "\n")
}
else {
builder.append(block.statements, "\n")
}
builder append " " append block.rBrace
}
}
class StarExpression(val operand: Expression) : Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.append("*").appendOperand(this, operand)
}
}
class RangeExpression(val start: Expression, val end: Expression): Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, start).append("..").appendOperand(this, end)
}
}
class UntilExpression(val start: Expression, val end: Expression): Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, start).append(" until ").appendOperand(this, end)
}
}
class DownToExpression(val start: Expression, val end: Expression): Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.appendOperand(this, start).append(" downTo ").appendOperand(this, end)
}
}
class ClassLiteralExpression(val type: Type): Expression() {
override fun generateCode(builder: CodeBuilder) {
builder.append(type).append("::class")
}
}
fun createArrayInitializerExpression(arrayType: ArrayType, initializers: List<Expression>, needExplicitType: Boolean = true) : MethodCallExpression {
val elementType = arrayType.elementType
val createArrayFunction = when {
elementType is PrimitiveType -> (elementType.toNotNullType().canonicalCode() + "ArrayOf").decapitalize(Locale.US)
needExplicitType -> "arrayOf<" + arrayType.elementType.canonicalCode() + ">"
else -> "arrayOf"
}
return MethodCallExpression.buildNonNull(null, createArrayFunction, ArgumentList.withNoPrototype(initializers))
}
| apache-2.0 | 98f30ca32a796c87a36482a50abba272 | 34.536332 | 158 | 0.64372 | 4.867299 | false | false | false | false |
JetBrains/intellij-community | plugins/gitlab/src/org/jetbrains/plugins/gitlab/mergerequest/ui/list/GitLabMergeRequestsPanelFactory.kt | 1 | 4153 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gitlab.mergerequest.ui.list
import com.intellij.collaboration.async.nestedDisposable
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.openapi.project.Project
import com.intellij.ui.CollectionListModel
import com.intellij.ui.ScrollPaneFactory
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.scroll.BoundedRangeModelThresholdListener
import com.intellij.vcs.log.ui.frame.ProgressStripe
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.jetbrains.plugins.gitlab.mergerequest.api.dto.GitLabMergeRequestShortDTO
import org.jetbrains.plugins.gitlab.mergerequest.ui.GitLabMergeRequestsListViewModel
import org.jetbrains.plugins.gitlab.mergerequest.ui.filters.GitLabFiltersPanelFactory
import javax.swing.JComponent
import javax.swing.ScrollPaneConstants
import javax.swing.event.ChangeEvent
internal class GitLabMergeRequestsPanelFactory {
fun create(project: Project, scope: CoroutineScope, listVm: GitLabMergeRequestsListViewModel): JComponent {
val listModel = collectMergeRequests(scope, listVm)
val listMergeRequests = GitLabMergeRequestsListComponentFactory.create(listModel, listVm.avatarIconsProvider)
val listLoaderPanel = createListLoaderPanel(scope, listVm, listMergeRequests)
val progressStripe = ProgressStripe(
listLoaderPanel,
scope.nestedDisposable(),
ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS
).apply {
scope.launch {
listVm.loadingState.collect {
if (it) startLoadingImmediately() else stopLoading()
}
}
}
val searchPanel = createSearchPanel(scope, listVm)
GitLabMergeRequestsListController(project, scope, listVm, listMergeRequests.emptyText, listLoaderPanel, progressStripe)
return JBUI.Panels.simplePanel(progressStripe)
.addToTop(searchPanel)
.andTransparent()
}
private fun collectMergeRequests(scope: CoroutineScope,
listVm: GitLabMergeRequestsListViewModel): CollectionListModel<GitLabMergeRequestShortDTO> {
val listModel = CollectionListModel<GitLabMergeRequestShortDTO>()
scope.launch {
var firstEvent = true
listVm.listDataFlow.collect {
when (it) {
is GitLabMergeRequestsListViewModel.ListDataUpdate.NewBatch -> {
if (firstEvent) listModel.add(it.newList)
else listModel.add(it.batch)
}
GitLabMergeRequestsListViewModel.ListDataUpdate.Clear -> listModel.removeAll()
}
firstEvent = false
}
}
return listModel
}
private fun createListLoaderPanel(scope: CoroutineScope, listVm: GitLabMergeRequestsListViewModel, list: JComponent): JComponent {
return ScrollPaneFactory.createScrollPane(list, true).apply {
isOpaque = false
viewport.isOpaque = false
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
val model = verticalScrollBar.model
val listener = object : BoundedRangeModelThresholdListener(model, 0.7f) {
override fun onThresholdReached() {
if (listVm.canLoadMoreState.value) {
listVm.requestMore()
}
}
}
model.addChangeListener(listener)
scope.launch {
listVm.listDataFlow.collect {
when (it) {
is GitLabMergeRequestsListViewModel.ListDataUpdate.NewBatch -> {
if (isShowing) {
listener.stateChanged(ChangeEvent(listVm))
}
}
GitLabMergeRequestsListViewModel.ListDataUpdate.Clear -> {
if (isShowing) {
listVm.requestMore()
}
}
}
}
}
}
}
private fun createSearchPanel(scope: CoroutineScope, listVm: GitLabMergeRequestsListViewModel): JComponent {
return GitLabFiltersPanelFactory(listVm.filterVm).create(scope)
}
} | apache-2.0 | c9f3f074c5ac01721818968608136c3c | 37.462963 | 132 | 0.724055 | 5.243687 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddFileAnnotationFix.kt | 1 | 5360 | // 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.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.SmartPsiElementPointer
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.replaceFileAnnotationList
import org.jetbrains.kotlin.renderer.render
/**
* A quick fix to add file-level annotations, e.g. `@file:OptIn(SomeExperimentalAnnotation::class)`.
*
* The fix either creates a new annotation or adds the argument to the existing annotation entry.
* It does not check whether the annotation class allows duplicating annotations; it is the caller responsibility.
* For example, only one `@file:OptIn(...)` annotation is allowed, so if this annotation entry already exists,
* the caller should pass the non-null smart pointer to it as the `existingAnnotationEntry` argument.
*
* @param file the file where the annotation should be added
* @param annotationFqName the fully qualified name of the annotation class (e.g., `kotlin.OptIn`)
* @param argumentClassFqName the fully qualified name of the argument class (e.g., `SomeExperimentalAnnotation`) (optional)
* @param existingAnnotationEntry a smart pointer to the existing annotation entry with the same annotation class (optional)
*/
open class AddFileAnnotationFix(
file: KtFile,
private val annotationFqName: FqName,
private val argumentClassFqName: FqName? = null,
private val existingAnnotationEntry: SmartPsiElementPointer<KtAnnotationEntry>? = null
) : KotlinQuickFixAction<KtFile>(file) {
override fun getText(): String {
val annotationName = annotationFqName.shortName().asString()
val innerText = argumentClassFqName?.shortName()?.asString()?.let { "$it::class" } ?: ""
val annotationText = "$annotationName($innerText)"
return KotlinBundle.message("fix.add.annotation.text.containing.file", annotationText, element?.name ?: "")
}
override fun getFamilyName(): String = KotlinBundle.message("fix.add.annotation.family")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val fileToAnnotate = element ?: return
val innerText = argumentClassFqName?.render()?.let { "$it::class"}
val annotationText = when (innerText) {
null -> annotationFqName.render()
else -> "${annotationFqName.render()}($innerText)"
}
val psiFactory = KtPsiFactory(project)
if (fileToAnnotate.fileAnnotationList == null) {
// If there are no existing file-level annotations, create an annotation list with the new annotation
val newAnnotationList = psiFactory.createFileAnnotationListWithAnnotation(annotationText)
val createdAnnotationList = replaceFileAnnotationList(fileToAnnotate, newAnnotationList)
fileToAnnotate.addAfter(psiFactory.createWhiteSpace("\n"), createdAnnotationList)
ShortenReferences.DEFAULT.process(createdAnnotationList)
} else {
val annotationList = fileToAnnotate.fileAnnotationList ?: return
if (existingAnnotationEntry == null) {
// There are file-level annotations, but the fix is expected to add a new entry
val newAnnotation = psiFactory.createFileAnnotation(annotationText)
annotationList.add(psiFactory.createWhiteSpace("\n"))
annotationList.add(newAnnotation)
ShortenReferences.DEFAULT.process(annotationList)
} else if (innerText != null) {
// There is an existing annotation and the non-null argument that should be added to it
addArgumentToExistingAnnotation(existingAnnotationEntry, innerText)
}
}
}
/**
* Add an argument to the existing annotation.
*
* @param annotationEntry a smart pointer to the existing annotation entry
* @param argumentText the argument text
*/
private fun addArgumentToExistingAnnotation(annotationEntry: SmartPsiElementPointer<KtAnnotationEntry>, argumentText: String) {
val entry = annotationEntry.element ?: return
val existingArgumentList = entry.valueArgumentList
val psiFactory = KtPsiFactory(entry.project)
val newArgumentList = psiFactory.createCallArguments("($argumentText)")
when {
existingArgumentList == null -> // use the new argument list
entry.addAfter(newArgumentList, entry.lastChild)
existingArgumentList.arguments.isEmpty() -> // replace '()' with the new argument list
existingArgumentList.replace(newArgumentList)
else -> // add the new argument to the existing list
existingArgumentList.addArgument(newArgumentList.arguments[0])
}
ShortenReferences.DEFAULT.process(entry)
}
}
| apache-2.0 | 5b9db75bc64408cbb0ca5d85ddd26ca0 | 54.257732 | 158 | 0.720896 | 5.280788 | false | false | false | false |
JetBrains/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/impl/WindowsDistributionBuilder.kt | 1 | 20770 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("BlockingMethodInNonBlockingContext")
package org.jetbrains.intellij.build.impl
import com.intellij.diagnostic.telemetry.useWithScope2
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.NioFiles
import com.intellij.openapi.util.text.StringUtilRt
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.trace.Span
import kotlinx.coroutines.*
import org.jetbrains.intellij.build.*
import org.jetbrains.intellij.build.TraceManager.spanBuilder
import org.jetbrains.intellij.build.impl.productInfo.*
import org.jetbrains.intellij.build.impl.support.RepairUtilityBuilder
import org.jetbrains.intellij.build.io.*
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.nio.file.attribute.FileTime
import java.util.concurrent.TimeUnit
import java.util.function.BiPredicate
import kotlin.io.path.setLastModifiedTime
internal class WindowsDistributionBuilder(
override val context: BuildContext,
private val customizer: WindowsDistributionCustomizer,
private val ideaProperties: Path?,
) : OsSpecificDistributionBuilder {
private val icoFile: Path?
init {
val icoPath = (if (context.applicationInfo.isEAP) customizer.icoPathForEAP else null) ?: customizer.icoPath
icoFile = icoPath?.let { Path.of(icoPath) }
}
override val targetOs: OsFamily
get() = OsFamily.WINDOWS
override suspend fun copyFilesForOsDistribution(targetPath: Path, arch: JvmArchitecture) {
val distBinDir = targetPath.resolve("bin")
withContext(Dispatchers.IO) {
Files.createDirectories(distBinDir)
val sourceBinDir = context.paths.communityHomeDir.resolve("bin/win")
FileSet(sourceBinDir.resolve(arch.dirName))
.includeAll()
.copyToDir(distBinDir)
if (context.includeBreakGenLibraries()) {
// There's near zero chance that on x64 hardware arm64 library will be needed, but it's only 70 KiB.
// Contrary on arm64 hardware all three library versions could be used, so we copy them all.
@Suppress("SpellCheckingInspection")
FileSet(sourceBinDir)
.include("breakgen*.dll")
.copyToDir(distBinDir)
}
generateBuildTxt(context, targetPath)
copyDistFiles(context = context, newDir = targetPath, os = OsFamily.WINDOWS, arch = arch)
Files.writeString(distBinDir.resolve(ideaProperties!!.fileName),
StringUtilRt.convertLineSeparators(Files.readString(ideaProperties), "\r\n"))
if (icoFile != null) {
Files.copy(icoFile, distBinDir.resolve("${context.productProperties.baseFileName}.ico"), StandardCopyOption.REPLACE_EXISTING)
}
if (customizer.includeBatchLaunchers) {
generateScripts(distBinDir, arch)
}
generateVMOptions(distBinDir)
buildWinLauncher(targetPath, arch)
customizer.copyAdditionalFiles(context, targetPath.toString(), arch)
}
context.executeStep(spanBuilder = spanBuilder("sign windows"), stepId = BuildOptions.WIN_SIGN_STEP) {
val nativeFiles = ArrayList<Path>()
withContext(Dispatchers.IO) {
Files.find(distBinDir, Integer.MAX_VALUE, BiPredicate { file, attributes ->
if (attributes.isRegularFile) {
val path = file.toString()
path.endsWith(".exe") || path.endsWith(".dll")
}
else {
false
}
}).use { stream ->
stream.forEach(nativeFiles::add)
}
}
Span.current().setAttribute(AttributeKey.stringArrayKey("files"), nativeFiles.map(Path::toString))
customizer.getBinariesToSign(context).mapTo(nativeFiles) { targetPath.resolve(it) }
if (nativeFiles.isNotEmpty()) {
withContext(Dispatchers.IO) {
context.signFiles(nativeFiles, BuildOptions.WIN_SIGN_OPTIONS)
}
}
}
}
override suspend fun buildArtifacts(osAndArchSpecificDistPath: Path, arch: JvmArchitecture) {
copyFilesForOsDistribution(osAndArchSpecificDistPath, arch)
val suffix = if (arch == JvmArchitecture.x64) "" else "-${arch.fileSuffix}"
val runtimeDir = context.bundledRuntime.extract(BundledRuntimeImpl.getProductPrefix(context), OsFamily.WINDOWS, arch)
@Suppress("SpellCheckingInspection")
val vcRtDll = runtimeDir.resolve("jbr/bin/msvcp140.dll")
check(Files.exists(vcRtDll)) {
"VS C++ Runtime DLL (${vcRtDll.fileName}) not found in ${vcRtDll.parent}.\n" +
"If JBR uses a newer version, please correct the path in this code and update Windows Launcher build configuration.\n" +
"If DLL was relocated to another place, please correct the path in this code."
}
copyFileToDir(vcRtDll, osAndArchSpecificDistPath.resolve("bin"))
var exePath: Path? = null
val zipWithJbrPath = coroutineScope {
Files.walk(osAndArchSpecificDistPath).use { tree ->
val fileTime = FileTime.from(context.options.buildDateInSeconds, TimeUnit.SECONDS)
tree.forEach {
it.setLastModifiedTime(fileTime)
}
}
val zipWithJbrPathTask = if (customizer.buildZipArchiveWithBundledJre) {
createBuildWinZipTask(runtimeDir = runtimeDir,
zipNameSuffix = suffix + customizer.zipArchiveWithBundledJreSuffix,
winDistPath = osAndArchSpecificDistPath,
arch = arch,
customizer = customizer,
context = context)
}
else {
null
}
if (customizer.buildZipArchiveWithoutBundledJre) {
createBuildWinZipTask(runtimeDir = null,
zipNameSuffix = suffix + customizer.zipArchiveWithoutBundledJreSuffix,
winDistPath = osAndArchSpecificDistPath,
arch = arch,
customizer = customizer,
context = context)
}
context.executeStep(spanBuilder("build Windows installer")
.setAttribute("arch", arch.dirName), BuildOptions.WINDOWS_EXE_INSTALLER_STEP) {
val productJsonDir = Files.createTempDirectory(context.paths.tempDir, "win-product-info")
validateProductJson(jsonText = generateProductJson(targetDir = productJsonDir, arch = arch, isRuntimeIncluded = true, context = context),
relativePathToProductJson = "",
installationDirectories = listOf(context.paths.distAllDir, osAndArchSpecificDistPath, runtimeDir),
installationArchives = emptyList(),
context = context)
exePath = buildNsisInstaller(winDistPath = osAndArchSpecificDistPath,
additionalDirectoryToInclude = productJsonDir,
suffix = suffix,
customizer = customizer,
runtimeDir = runtimeDir,
context = context)
}
zipWithJbrPathTask?.await()
}
if (zipWithJbrPath != null && exePath != null) {
if (context.options.isInDevelopmentMode) {
Span.current().addEvent("comparing .zip and .exe skipped in development mode")
}
else if (!SystemInfoRt.isLinux) {
Span.current().addEvent("comparing .zip and .exe is not supported on ${SystemInfoRt.OS_NAME}")
}
else {
checkThatExeInstallerAndZipWithJbrAreTheSame(zipPath = zipWithJbrPath,
exePath = exePath!!,
arch = arch,
tempDir = context.paths.tempDir,
context = context)
}
return
}
}
private fun generateScripts(distBinDir: Path, arch: JvmArchitecture) {
val fullName = context.applicationInfo.productName
val baseName = context.productProperties.baseFileName
val scriptName = "${baseName}.bat"
val vmOptionsFileName = "${baseName}64.exe"
val classPathJars = context.bootClassPathJarNames
var classPath = "SET \"CLASS_PATH=%IDE_HOME%\\lib\\${classPathJars[0]}\""
for (i in 1 until classPathJars.size) {
classPath += "\nSET \"CLASS_PATH=%CLASS_PATH%;%IDE_HOME%\\lib\\${classPathJars[i]}\""
}
var additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.WINDOWS, arch, isScript = true)
if (!context.xBootClassPathJarNames.isEmpty()) {
additionalJvmArguments = additionalJvmArguments.toMutableList()
val bootCp = context.xBootClassPathJarNames.joinToString(separator = ";") { "%IDE_HOME%\\lib\\${it}" }
additionalJvmArguments.add("\"-Xbootclasspath/a:$bootCp\"")
}
val winScripts = context.paths.communityHomeDir.resolve("platform/build-scripts/resources/win/scripts")
val actualScriptNames = Files.newDirectoryStream(winScripts).use { dirStream -> dirStream.map { it.fileName.toString() }.sorted() }
@Suppress("SpellCheckingInspection")
val expectedScriptNames = listOf("executable-template.bat", "format.bat", "inspect.bat", "ltedit.bat")
check(actualScriptNames == expectedScriptNames) {
"Expected script names '${expectedScriptNames.joinToString(separator = " ")}', " +
"but got '${actualScriptNames.joinToString(separator = " ")}' " +
"in $winScripts. Please review ${WindowsDistributionBuilder::class.java.name} and update accordingly"
}
substituteTemplatePlaceholders(
inputFile = winScripts.resolve("executable-template.bat"),
outputFile = distBinDir.resolve(scriptName),
placeholder = "@@",
values = listOf(
Pair("product_full", fullName),
Pair("product_uc", context.productProperties.getEnvironmentVariableBaseName(context.applicationInfo)),
Pair("product_vendor", context.applicationInfo.shortCompanyName),
Pair("vm_options", vmOptionsFileName),
Pair("system_selector", context.systemSelector),
Pair("ide_jvm_args", additionalJvmArguments.joinToString(separator = " ")),
Pair("class_path", classPath),
Pair("base_name", baseName),
Pair("main_class_name", context.productProperties.mainClassName),
)
)
val inspectScript = context.productProperties.inspectCommandName
@Suppress("SpellCheckingInspection")
for (fileName in listOf("format.bat", "inspect.bat", "ltedit.bat")) {
val sourceFile = winScripts.resolve(fileName)
val targetFile = distBinDir.resolve(fileName)
substituteTemplatePlaceholders(
inputFile = sourceFile,
outputFile = targetFile,
placeholder = "@@",
values = listOf(
Pair("product_full", fullName),
Pair("script_name", scriptName),
)
)
}
if (inspectScript != "inspect") {
val targetPath = distBinDir.resolve("${inspectScript}.bat")
Files.move(distBinDir.resolve("inspect.bat"), targetPath)
context.patchInspectScript(targetPath)
}
FileSet(distBinDir)
.include("*.bat")
.enumerate()
.forEach { file ->
transformFile(file) { target ->
@Suppress("BlockingMethodInNonBlockingContext")
Files.writeString(target, toDosLineEndings(Files.readString(file)))
}
}
}
private fun generateVMOptions(distBinDir: Path) {
val productProperties = context.productProperties
val fileName = "${productProperties.baseFileName}64.exe.vmoptions"
val vmOptions = VmOptionsGenerator.computeVmOptions(context.applicationInfo.isEAP, productProperties)
VmOptionsGenerator.writeVmOptions(distBinDir.resolve(fileName), vmOptions, "\r\n")
}
private suspend fun buildWinLauncher(winDistPath: Path, arch: JvmArchitecture) {
spanBuilder("build Windows executable").useWithScope2 {
val executableBaseName = "${context.productProperties.baseFileName}64"
val launcherPropertiesPath = context.paths.tempDir.resolve("launcher-${arch.dirName}.properties")
@Suppress("SpellCheckingInspection")
val vmOptions = context.getAdditionalJvmArguments(OsFamily.WINDOWS, arch) + listOf("-Dide.native.launcher=true")
val productName = context.applicationInfo.shortProductName
val classPath = context.bootClassPathJarNames.joinToString(separator = ";") { "%IDE_HOME%\\\\lib\\\\${it}" }
val bootClassPath = context.xBootClassPathJarNames.joinToString(separator = ";") { "%IDE_HOME%\\\\lib\\\\${it}" }
val envVarBaseName = context.productProperties.getEnvironmentVariableBaseName(context.applicationInfo)
val icoFilesDirectory = context.paths.tempDir.resolve("win-launcher-ico-${arch.dirName}")
val appInfoForLauncher = generateApplicationInfoForLauncher(context.applicationInfo.appInfoXml, icoFilesDirectory)
@Suppress("SpellCheckingInspection")
Files.writeString(launcherPropertiesPath, """
IDS_JDK_ONLY=${context.productProperties.toolsJarRequired}
IDS_JDK_ENV_VAR=${envVarBaseName}_JDK
IDS_VM_OPTIONS_PATH=%APPDATA%\\\\${context.applicationInfo.shortCompanyName}\\\\${context.systemSelector}
IDS_VM_OPTION_ERRORFILE=-XX:ErrorFile=%USERPROFILE%\\\\java_error_in_${executableBaseName}_%p.log
IDS_VM_OPTION_HEAPDUMPPATH=-XX:HeapDumpPath=%USERPROFILE%\\\\java_error_in_${executableBaseName}.hprof
IDS_PROPS_ENV_VAR=${envVarBaseName}_PROPERTIES
IDS_VM_OPTIONS_ENV_VAR=${envVarBaseName}_VM_OPTIONS
IDS_ERROR_LAUNCHING_APP=Error launching $productName
IDS_VM_OPTIONS=${vmOptions.joinToString(separator = " ")}
IDS_CLASSPATH_LIBS=${classPath}
IDS_BOOTCLASSPATH_LIBS=${bootClassPath}
IDS_INSTANCE_ACTIVATION=${context.productProperties.fastInstanceActivation}
IDS_MAIN_CLASS=${context.productProperties.mainClassName.replace('.', '/')}
""".trimIndent().trim())
val communityHome = context.paths.communityHome
val inputPath = "${communityHome}/platform/build-scripts/resources/win/launcher/${arch.dirName}/WinLauncher.exe"
val outputPath = winDistPath.resolve("bin/${executableBaseName}.exe")
val classpath = ArrayList<String>()
val generatorClasspath = context.getModuleRuntimeClasspath(module = context.findRequiredModule("intellij.tools.launcherGenerator"),
forTests = false)
classpath.addAll(generatorClasspath)
sequenceOf(context.findApplicationInfoModule(), context.findRequiredModule("intellij.platform.icons"))
.flatMap { it.sourceRoots }
.forEach { root ->
classpath.add(root.file.absolutePath)
}
for (p in context.productProperties.brandingResourcePaths) {
classpath.add(p.toString())
}
classpath.add(icoFilesDirectory.toString())
runIdea(
context = context,
mainClass = "com.pme.launcher.LauncherGeneratorMain",
args = listOf(
inputPath,
appInfoForLauncher.toString(),
"$communityHome/native/WinLauncher/resource.h",
launcherPropertiesPath.toString(),
icoFile?.fileName?.toString() ?: " ",
outputPath.toString(),
),
jvmArgs = listOf("-Djava.awt.headless=true"),
classPath = classpath
)
}
}
/**
* Generates ApplicationInfo.xml file for launcher generator which contains link to proper *.ico file.
* todo pass path to ico file to LauncherGeneratorMain directly (probably after IDEA-196705 is fixed).
*/
private fun generateApplicationInfoForLauncher(appInfo: String, icoFilesDirectory: Path): Path {
Files.createDirectories(icoFilesDirectory)
if (icoFile != null) {
Files.copy(icoFile, icoFilesDirectory.resolve(icoFile.fileName), StandardCopyOption.REPLACE_EXISTING)
}
val patchedFile = icoFilesDirectory.resolve("win-launcher-application-info.xml")
Files.writeString(patchedFile, appInfo)
return patchedFile
}
}
private suspend fun checkThatExeInstallerAndZipWithJbrAreTheSame(zipPath: Path,
exePath: Path,
arch: JvmArchitecture,
tempDir: Path,
context: BuildContext) {
Span.current().addEvent("compare ${zipPath.fileName} vs. ${exePath.fileName}")
val tempZip = withContext(Dispatchers.IO) { Files.createTempDirectory(tempDir, "zip-${arch.dirName}") }
val tempExe = withContext(Dispatchers.IO) { Files.createTempDirectory(tempDir, "exe-${arch.dirName}") }
try {
withContext(Dispatchers.IO) {
runProcess(args = listOf("7z", "x", "-bd", exePath.toString()), workingDir = tempExe)
runProcess(args = listOf("unzip", "-q", zipPath.toString()), workingDir = tempZip)
@Suppress("SpellCheckingInspection")
NioFiles.deleteRecursively(tempExe.resolve("\$PLUGINSDIR"))
runProcess(args = listOf("diff", "-q", "-r", tempZip.toString(), tempExe.toString()))
}
if (!context.options.buildStepsToSkip.contains(BuildOptions.REPAIR_UTILITY_BUNDLE_STEP)) {
RepairUtilityBuilder.generateManifest(context, tempExe, OsFamily.WINDOWS, arch)
}
}
finally {
withContext(Dispatchers.IO + NonCancellable) {
NioFiles.deleteRecursively(tempZip)
NioFiles.deleteRecursively(tempExe)
}
}
}
private fun CoroutineScope.createBuildWinZipTask(runtimeDir: Path?,
zipNameSuffix: String,
winDistPath: Path,
arch: JvmArchitecture,
customizer: WindowsDistributionCustomizer,
context: BuildContext): Deferred<Path> {
return async(Dispatchers.IO) {
val baseName = context.productProperties.getBaseArtifactName(context.applicationInfo, context.buildNumber)
val targetFile = context.paths.artifactDir.resolve("${baseName}${zipNameSuffix}.zip")
spanBuilder("build Windows ${zipNameSuffix}.zip distribution")
.setAttribute("targetFile", targetFile.toString())
.setAttribute("arch", arch.dirName)
.useWithScope2 {
val productJsonDir = context.paths.tempDir.resolve("win.dist.product-info.json.zip$zipNameSuffix")
generateProductJson(targetDir = productJsonDir, arch = arch, isRuntimeIncluded = runtimeDir != null, context = context)
val zipPrefix = customizer.getRootDirectoryName(context.applicationInfo, context.buildNumber)
val dirs = listOfNotNull(context.paths.distAllDir, winDistPath, productJsonDir, runtimeDir)
val dirMap = dirs.associateWithTo(LinkedHashMap(dirs.size)) { zipPrefix }
if (context.options.compressZipFiles) {
zipWithCompression(targetFile = targetFile, dirs = dirMap)
}
else {
zip(targetFile = targetFile, dirs = dirMap, addDirEntriesMode = AddDirEntriesMode.NONE)
}
checkInArchive(archiveFile = targetFile, pathInArchive = zipPrefix, context = context)
context.notifyArtifactWasBuilt(targetFile)
targetFile
}
}
}
private fun generateProductJson(targetDir: Path, isRuntimeIncluded: Boolean, arch: JvmArchitecture, context: BuildContext): String {
val launcherPath = "bin/${context.productProperties.baseFileName}64.exe"
val vmOptionsPath = "bin/${context.productProperties.baseFileName}64.exe.vmoptions"
val javaExecutablePath = if (isRuntimeIncluded) "jbr/bin/java.exe" else null
val file = targetDir.resolve(PRODUCT_INFO_FILE_NAME)
Files.createDirectories(targetDir)
val json = generateMultiPlatformProductJson(
"bin",
context.builtinModule,
listOf(ProductInfoLaunchData(
os = OsFamily.WINDOWS.osName,
arch = arch.dirName,
launcherPath = launcherPath,
javaExecutablePath = javaExecutablePath,
vmOptionsFilePath = vmOptionsPath,
startupWmClass = null,
bootClassPathJarNames = context.bootClassPathJarNames,
additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.WINDOWS, arch))),
context)
Files.writeString(file, json)
file.setLastModifiedTime(FileTime.from(context.options.buildDateInSeconds, TimeUnit.SECONDS))
return json
}
private fun toDosLineEndings(x: String): String =
x.replace("\r", "").replace("\n", "\r\n")
| apache-2.0 | 5d348d324ced622a61d224dd4db25825 | 45.569507 | 145 | 0.666731 | 5.176969 | false | false | false | false |
ursjoss/sipamato | public/public-persistence-jooq/src/main/kotlin/ch/difty/scipamato/publ/persistence/paper/PublicPaperFilterConditionMapper.kt | 1 | 5374 | package ch.difty.scipamato.publ.persistence.paper
import ch.difty.scipamato.common.persistence.AbstractFilterConditionMapper
import ch.difty.scipamato.common.persistence.FilterConditionMapper
import ch.difty.scipamato.publ.db.tables.Paper
import ch.difty.scipamato.publ.db.tables.records.PaperRecord
import ch.difty.scipamato.publ.entity.Code
import ch.difty.scipamato.publ.entity.filter.PublicPaperFilter
import org.jooq.Condition
import org.jooq.TableField
import org.jooq.impl.DSL
import org.jooq.impl.SQLDataType
import java.util.regex.Matcher
import java.util.regex.Pattern
private const val RE_QUOTE = "\""
private val QUOTED = Pattern.compile("$RE_QUOTE([^$RE_QUOTE]+)$RE_QUOTE")
private const val QUOTED_GROUP_INDEX = 1
@FilterConditionMapper
class PublicPaperFilterConditionMapper : AbstractFilterConditionMapper<PublicPaperFilter>() {
override fun internalMap(filter: PublicPaperFilter): List<Condition> {
val conditions = mutableListOf<Condition>()
filter.number?.let { conditions.add(Paper.PAPER.NUMBER.eq(it)) }
filter.authorMask?.let { conditions.addAll(Paper.PAPER.AUTHORS.tokenize(it)) }
filter.titleMask?.let { conditions.addAll(Paper.PAPER.TITLE.tokenize(it)) }
filter.methodsMask?.let { conditions.addAll(Paper.PAPER.METHODS.tokenize(it)) }
if (filter.publicationYearFrom != null) {
if (hasNoOrIdenticalPubYearUntil(filter)) {
conditions.add(Paper.PAPER.PUBLICATION_YEAR.eq(filter.publicationYearFrom))
} else {
conditions.add(
Paper.PAPER.PUBLICATION_YEAR.between(filter.publicationYearFrom, filter.publicationYearUntil))
}
} else if (filter.publicationYearUntil != null) {
conditions.add(Paper.PAPER.PUBLICATION_YEAR.le(filter.publicationYearUntil))
}
filter.populationCodes?.let { codes ->
val ids = codes.map { it.id }.toTypedArray()
conditions.add(Paper.PAPER.CODES_POPULATION.contains(ids))
}
filter.studyDesignCodes?.let { codes ->
val ids = codes.map { it.id }.toTypedArray()
conditions.add(Paper.PAPER.CODES_STUDY_DESIGN.contains(ids))
}
if (filter.codesOfClass1 != null || filter.codesOfClass2 != null || filter.codesOfClass3 != null || filter.codesOfClass4 != null || filter.codesOfClass5 != null || filter.codesOfClass6 != null || filter.codesOfClass7 != null || filter.codesOfClass8 != null) {
val allCodes = filter.allCodes()
if (allCodes.isNotEmpty()) conditions.add(allCodes.toCondition())
}
return conditions
}
private fun hasNoOrIdenticalPubYearUntil(filter: PublicPaperFilter) =
filter.publicationYearUntil == null ||
filter.publicationYearFrom == filter.publicationYearUntil
/*
* Currently does not allow to mix quoted and unquoted terms. If this will
* become necessary we might have to implement a proper tokenization of the
* search term, as was done in core with the SearchTerm hierarchy.
*/
private fun TableField<PaperRecord, String>.tokenize(mask: String): List<Condition> {
val m = QUOTED.matcher(mask)
val (conditions, done) = tokenizeQuoted(m)
return conditions + if (!done) tokenizeUnquoted(mask) else emptyList()
}
private fun TableField<PaperRecord, String>.tokenizeQuoted(m: Matcher): Pair<List<Condition>, Boolean> {
val conditions = mutableListOf<Condition>()
var term: String? = null
while (m.find()) {
term = m.group(QUOTED_GROUP_INDEX)
conditions.add(likeIgnoreCase("%$term%"))
}
return Pair(conditions, term != null)
}
private fun TableField<PaperRecord, String>.tokenizeUnquoted(mask: String): List<Condition> {
val conditions = mutableListOf<Condition>()
if (!mask.contains(" "))
conditions.add(likeIgnoreCase("%$mask%"))
else
for (t in mask.split(" ").toTypedArray()) {
val token = t.trim { it <= ' ' }
if (token.isNotEmpty()) conditions.add(likeIgnoreCase("%$token%"))
}
return conditions
}
private fun PublicPaperFilter.allCodes() = with(this) {
codesOfClass1.codesNullSafe() +
codesOfClass2.codesNullSafe() +
codesOfClass3.codesNullSafe() +
codesOfClass4.codesNullSafe() +
codesOfClass5.codesNullSafe() +
codesOfClass6.codesNullSafe() +
codesOfClass7.codesNullSafe() +
codesOfClass8.codesNullSafe()
}
private fun List<Code>?.codesNullSafe() = this?.mapNotNull { it.code } ?: emptyList()
/**
* Due to bug https://github.com/jOOQ/jOOQ/issues/4754, the straightforward way
* of mapping the codes to the array of type text does not work:
*
* <pre>
* return PAPER.CODES.contains(codeCollection.toArray(new String[0]));
* </pre>
*
* While I originally casted to PostgresDataType.TEXT, I now need to cast to SQLDataType.CLOB
* due to https://github.com/jOOQ/jOOQ/issues/7375
*/
private fun List<String>.toCondition(): Condition =
Paper.PAPER.CODES.contains(
DSL.array(
mapNotNull { DSL.`val`(it).cast(SQLDataType.CLOB) }
)
)
}
| gpl-3.0 | 1ada70dd44652e1df95f03bd074e5421 | 43.413223 | 267 | 0.660402 | 4.523569 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/internal/retype/RetypeSession.kt | 2 | 23274 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.retype
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.CodeInsightWorkspaceSettings
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementPresentation
import com.intellij.codeInsight.lookup.LookupFocusDegree
import com.intellij.codeInsight.lookup.LookupManager
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.codeInsight.template.TemplateManager
import com.intellij.codeInsight.template.impl.LiveTemplateLookupElement
import com.intellij.diagnostic.ThreadDumper
import com.intellij.ide.DataManager
import com.intellij.ide.IdeEventQueue
import com.intellij.internal.performance.LatencyDistributionRecordKey
import com.intellij.internal.performance.TypingLatencyReportDialog
import com.intellij.internal.performance.currentLatencyRecordKey
import com.intellij.internal.performance.latencyRecorderProperties
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.actionSystem.ex.ActionManagerEx
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.actionSystem.LatencyRecorder
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileEditor.impl.text.PsiAwareTextEditorImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.ui.playback.commands.ActionCommand
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import com.intellij.ui.LightColors
import com.intellij.util.Alarm
import org.intellij.lang.annotations.Language
import java.awt.event.KeyEvent
import java.io.File
import java.util.*
fun String.toReadable() = replace(" ", "<Space>").replace("\n", "<Enter>").replace("\t", "<Tab>")
class RetypeLog {
val LOG = Logger.getInstance(RetypeLog::class.java)
private val log = arrayListOf<String>()
private var currentTyping: String? = null
private var currentCompletion: String? = null
var typedChars = 0
private set
var completedChars = 0
private set
fun recordTyping(c: Char) {
if (currentTyping == null) {
flushCompletion()
currentTyping = ""
}
currentTyping += c.toString().toReadable()
typedChars++
}
fun recordCompletion(c: Char) {
if (currentCompletion == null) {
flushTyping()
currentCompletion = ""
}
currentCompletion += c.toString().toReadable()
completedChars++
}
fun recordDesync(message: String) {
flush()
log.add("Desync: $message")
}
fun flush() {
flushTyping()
flushCompletion()
}
private fun flushTyping() {
if (currentTyping != null) {
log.add("Type: $currentTyping")
currentTyping = null
}
}
private fun flushCompletion() {
if (currentCompletion != null) {
log.add("Complete: $currentCompletion")
currentCompletion = null
}
}
fun printToStdout() {
for (s in log) {
if (ApplicationManager.getApplication().isUnitTestMode) {
LOG.debug(s)
}
else {
println(s)
}
}
}
}
class RetypeSession(
private val project: Project,
private val editor: EditorImpl,
private val delayMillis: Int,
private val scriptBuilder: StringBuilder?,
private val threadDumpDelay: Int,
private val threadDumps: MutableList<String> = mutableListOf(),
private val filesForIndexCount: Int = -1,
private val restoreText: Boolean = !ApplicationManager.getApplication().isUnitTestMode
) : Disposable {
private val document = editor.document
// -- Alarms
private val threadDumpAlarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, this)
private val originalText = document.text
@Volatile
private var pos = 0
private val endPos: Int
private val tailLength: Int
private val log = RetypeLog()
private val oldSelectAutopopup = CodeInsightSettings.getInstance().SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS
private val oldAddUnambiguous = CodeInsightSettings.getInstance().ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY
private val oldOptimize = CodeInsightWorkspaceSettings.getInstance(project).isOptimizeImportsOnTheFly
var startNextCallback: (() -> Unit)? = null
private val disposeLock = Any()
private var typedRightBefore = false
private var skipLookupSuggestion = false
private var textBeforeLookupSelection: String? = null
@Volatile
private var waitingForTimerInvokeLater: Boolean = false
private var lastTimerTick = -1L
private var threadPoolTimerLag = 0L
private var totalTimerLag = 0L
// This stack will contain autocompletion elements
// E.g. "}", "]", "*/", "* @return"
private val completionStack = ArrayDeque<String>()
private var stopInterfereFileChanger = false
var retypePaused: Boolean = false
private val timerThread = Thread(::runLoop, "RetypeSession loop")
private var stopTimer = false
init {
if (editor.selectionModel.hasSelection()) {
pos = editor.selectionModel.selectionStart
endPos = editor.selectionModel.selectionEnd
}
else {
pos = editor.caretModel.offset
endPos = document.textLength
}
tailLength = document.textLength - endPos
}
fun start() {
editor.putUserData(RETYPE_SESSION_KEY, this)
val vFile = FileDocumentManager.getInstance().getFile(document)
val keyName = "${vFile?.name ?: "Unknown file"} (${document.textLength} chars)"
currentLatencyRecordKey = LatencyDistributionRecordKey(keyName)
latencyRecorderProperties.putAll(mapOf("Delay" to "$delayMillis ms",
"Thread dump delay" to "$threadDumpDelay ms"
))
scriptBuilder?.let {
if (vFile != null) {
val contentRoot = ProjectRootManager.getInstance(project).fileIndex.getContentRootForFile(vFile) ?: return@let
it.append("%openFile ${VfsUtil.getRelativePath(vFile, contentRoot)}\n")
}
it.append(correctText(originalText.substring(0, pos) + originalText.substring(endPos)))
val line = editor.document.getLineNumber(pos)
it.append("%goto ${line + 1} ${pos - editor.document.getLineStartOffset(line) + 1}\n")
}
WriteCommandAction.runWriteCommandAction(project) { document.deleteString(pos, endPos) }
CodeInsightSettings.getInstance().apply {
SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS = false
ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = false
}
CodeInsightWorkspaceSettings.getInstance(project).isOptimizeImportsOnTheFly = false
EditorNotifications.getInstance(project).updateNotifications(editor.virtualFile)
retypePaused = false
startLargeIndexing()
timerThread.start()
checkStop()
}
private fun correctText(text: String) = "%replaceText ${text.replace('\n', '\u32E1')}\n"
fun stop(startNext: Boolean) {
stopTimer = true
timerThread.join()
for (retypeFileAssistant in RetypeFileAssistant.EP_NAME.extensions) {
retypeFileAssistant.retypeDone(editor)
}
if (restoreText) {
WriteCommandAction.runWriteCommandAction(project) { document.replaceString(0, document.textLength, originalText) }
}
synchronized(disposeLock) {
Disposer.dispose(this)
}
editor.putUserData(RETYPE_SESSION_KEY, null)
CodeInsightSettings.getInstance().apply {
SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS = oldSelectAutopopup
ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY = oldAddUnambiguous
}
CodeInsightWorkspaceSettings.getInstance(project).isOptimizeImportsOnTheFly = oldOptimize
currentLatencyRecordKey?.details = "typed ${log.typedChars} chars, completed ${log.completedChars} chars"
log.flush()
log.printToStdout()
currentLatencyRecordKey = null
if (startNext) {
startNextCallback?.invoke()
}
removeLargeIndexing()
stopInterfereFileChanger = true
EditorNotifications.getInstance(project).updateAllNotifications()
}
override fun dispose() {
}
private fun inFocus(): Boolean =
editor.contentComponent == IdeFocusManager.findInstance().focusOwner && ApplicationManager.getApplication().isActive || ApplicationManager.getApplication().isUnitTestMode
private fun runLoop() {
while (pos != endPos && !stopTimer) {
Thread.sleep(delayMillis.toLong())
if (stopTimer) break
typeNext()
}
}
private fun typeNext() {
if (!ApplicationManager.getApplication().isUnitTestMode) {
threadDumpAlarm.addRequest({ logThreadDump() }, threadDumpDelay)
}
val timerTick = System.currentTimeMillis()
waitingForTimerInvokeLater = true
val expectedTimerTick = if (lastTimerTick != -1L) lastTimerTick + delayMillis else -1L
if (lastTimerTick != -1L) {
threadPoolTimerLag += (timerTick - expectedTimerTick)
}
lastTimerTick = timerTick
ApplicationManager.getApplication().invokeLater {
if (stopTimer) return@invokeLater
typeNextInEDT(timerTick, expectedTimerTick)
}
}
private fun typeNextInEDT(timerTick: Long, expectedTimerTick: Long) {
if (retypePaused) {
if (inFocus()) {
// Resume retyping on editor focus
retypePaused = false
}
else {
checkStop()
return
}
}
if (expectedTimerTick != -1L) {
totalTimerLag += (System.currentTimeMillis() - expectedTimerTick)
}
EditorNotifications.getInstance(project).updateAllNotifications()
waitingForTimerInvokeLater = false
val processNextEvent = handleIdeaIntelligence()
if (processNextEvent) return
if (TemplateManager.getInstance(project).getActiveTemplate(editor) != null) {
TemplateManager.getInstance(project).finishTemplate(editor)
checkStop()
return
}
val lookup = LookupManager.getActiveLookup(editor) as LookupImpl?
if (lookup != null && !skipLookupSuggestion) {
val currentLookupElement = lookup.currentItem
if (currentLookupElement?.shouldAccept(lookup.lookupStart) == true) {
lookup.lookupFocusDegree = LookupFocusDegree.FOCUSED
scriptBuilder?.append("${ActionCommand.PREFIX} ${IdeActions.ACTION_CHOOSE_LOOKUP_ITEM}\n")
typedRightBefore = false
textBeforeLookupSelection = document.text
executeEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM, timerTick)
checkStop()
return
}
}
// Do not perform typing if editor is not in focus
if (!inFocus()) retypePaused = true
if (retypePaused) {
checkStop()
return
}
// Restore caret position (E.g. user clicks accidentally on another position)
if (editor.caretModel.offset != pos) editor.caretModel.moveToOffset(pos)
val c = originalText[pos++]
log.recordTyping(c)
// Reset lookup related variables
textBeforeLookupSelection = null
if (c == ' ') skipLookupSuggestion = false // We expecting new lookup suggestions
if (c == '\n') {
scriptBuilder?.append("${ActionCommand.PREFIX} ${IdeActions.ACTION_EDITOR_ENTER}\n")
executeEditorAction(IdeActions.ACTION_EDITOR_ENTER, timerTick)
typedRightBefore = false
}
else {
scriptBuilder?.let {
if (typedRightBefore) {
it.deleteCharAt(it.length - 1)
it.append("$c\n")
}
else {
it.append("%delayType $delayMillis|$c\n")
}
}
if (ApplicationManager.getApplication().isUnitTestMode) {
editor.type(c.toString())
}
else {
IdeEventQueue.getInstance().postEvent(
KeyEvent(editor.component, KeyEvent.KEY_PRESSED, timerTick, 0, KeyEvent.VK_UNDEFINED, c))
IdeEventQueue.getInstance().postEvent(
KeyEvent(editor.component, KeyEvent.KEY_TYPED, timerTick, 0, KeyEvent.VK_UNDEFINED, c))
}
typedRightBefore = true
}
checkStop()
}
/**
* @return if next queue event should be processed
*/
private fun handleIdeaIntelligence(): Boolean {
val actualBeforeCaret = document.text.take(pos)
val expectedBeforeCaret = originalText.take(pos)
if (actualBeforeCaret != expectedBeforeCaret) {
// Unexpected changes before current cursor position
// (may be unwanted import)
if (textBeforeLookupSelection != null) {
log.recordDesync("Restoring text before lookup (expected ...${expectedBeforeCaret.takeLast(
5).toReadable()}, actual ...${actualBeforeCaret.takeLast(5).toReadable()} ")
// Unexpected changes was made by lookup.
// Restore previous text state and set flag to skip further suggestions until whitespace will be typed
WriteCommandAction.runWriteCommandAction(project) {
document.replaceText(textBeforeLookupSelection ?: return@runWriteCommandAction, document.modificationStamp + 1)
}
skipLookupSuggestion = true
}
else {
log.recordDesync(
"Restoring text before caret (expected ...${expectedBeforeCaret.takeLast(5).toReadable()}, actual ...${actualBeforeCaret.takeLast(
5).toReadable()} | pos: $pos, caretOffset: ${editor.caretModel.offset}")
// There changes wasn't made by lookup, so we don't know how to handle them
// Restore text before caret as it should be at this point without any intelligence
WriteCommandAction.runWriteCommandAction(project) {
document.replaceString(0, editor.caretModel.offset, expectedBeforeCaret)
}
}
}
if (editor.caretModel.offset > pos) {
// Caret movement has been preformed
// Move the caret forward until the characters match
while (pos < document.textLength - tailLength
&& originalText[pos] == document.text[pos]
&& document.text[pos] !in listOf('\n') // Don't count line breakers because we want to enter "enter" explicitly
) {
log.recordCompletion(document.text[pos])
pos++
}
if (editor.caretModel.offset > pos) {
log.recordDesync("Deleting extra characters: ${document.text.substring(pos, editor.caretModel.offset).toReadable()}")
WriteCommandAction.runWriteCommandAction(project) {
// Delete symbols not from original text and move caret
document.deleteString(pos, editor.caretModel.offset)
}
}
editor.caretModel.moveToOffset(pos)
}
if (document.textLength > pos + tailLength) {
updateStack(completionStack)
val firstCompletion = completionStack.peekLast()
if (firstCompletion != null) {
val origIndexOfFirstCompletion = originalText.substring(pos, endPos).trim().indexOf(firstCompletion)
if (origIndexOfFirstCompletion == 0) {
// Next non-whitespace chars from original tests are from completion stack
val origIndexOfFirstComp = originalText.substring(pos, endPos).indexOf(firstCompletion)
val docIndexOfFirstComp = document.text.substring(pos).indexOf(firstCompletion)
if (originalText.substring(pos).take(origIndexOfFirstComp) != document.text.substring(pos).take(origIndexOfFirstComp)) {
// We have some unexpected chars before completion. Remove them
WriteCommandAction.runWriteCommandAction(project) {
val replacement = originalText.substring(pos, pos + origIndexOfFirstComp)
log.recordDesync("Replacing extra characters before completion: ${document.text.substring(pos,
pos + docIndexOfFirstComp).toReadable()} -> ${replacement.toReadable()}")
document.replaceString(pos, pos + docIndexOfFirstComp, replacement)
}
}
(pos until pos + origIndexOfFirstComp + firstCompletion.length).forEach { log.recordCompletion(document.text[it]) }
pos += origIndexOfFirstComp + firstCompletion.length
editor.caretModel.moveToOffset(pos)
completionStack.removeLast()
checkStop()
return true
}
else if (origIndexOfFirstCompletion < 0) {
// Completion is wrong and original text doesn't contain it
// Remove this completion
val docIndexOfFirstComp = document.text.substring(pos).indexOf(firstCompletion)
log.recordDesync("Removing wrong completion: ${document.text.substring(pos, pos + docIndexOfFirstComp).toReadable()}")
WriteCommandAction.runWriteCommandAction(project) {
document.replaceString(pos, pos + docIndexOfFirstComp + firstCompletion.length, "")
}
completionStack.removeLast()
checkStop()
return true
}
}
}
else if (document.textLength == pos + tailLength && completionStack.isNotEmpty()) {
// Text is as expected, but we have some extra completions in stack
completionStack.clear()
}
return false
}
private fun updateStack(completionStack: Deque<String>) {
val unexpectedCharsDoc = document.text.substring(pos, document.textLength - tailLength)
var endPosDoc = unexpectedCharsDoc.length
val completionIterator = completionStack.iterator()
while (completionIterator.hasNext()) {
// Validate all existing completions and add new completions if they are
val completion = completionIterator.next()
val lastIndexOfCompletion = unexpectedCharsDoc.substring(0, endPosDoc).lastIndexOf(completion)
if (lastIndexOfCompletion < 0) {
completionIterator.remove()
continue
}
endPosDoc = lastIndexOfCompletion
}
// Add new completion in stack
unexpectedCharsDoc.substring(0, endPosDoc).trim().split("\\s+".toRegex()).map { it.trim() }.reversed().forEach {
if (it.isNotEmpty()) {
completionStack.add(it)
}
}
}
private fun checkStop() {
if (pos == endPos) {
stop(true)
if (startNextCallback == null && !ApplicationManager.getApplication().isUnitTestMode) {
if (scriptBuilder != null) {
scriptBuilder.append(correctText(originalText))
val file = File.createTempFile("perf", ".test")
val vFile = VfsUtil.findFileByIoFile(file, false)!!
WriteCommandAction.runWriteCommandAction(project) {
VfsUtil.saveText(vFile, scriptBuilder.toString())
}
OpenFileDescriptor(project, vFile).navigate(true)
}
latencyRecorderProperties["Thread pool timer lag"] = "$threadPoolTimerLag ms"
latencyRecorderProperties["Total timer lag"] = "$totalTimerLag ms"
TypingLatencyReportDialog(project, threadDumps).show()
}
}
}
private fun LookupElement.shouldAccept(lookupStartOffset: Int): Boolean {
for (retypeFileAssistant in RetypeFileAssistant.EP_NAME.extensionList) {
if (!retypeFileAssistant.acceptLookupElement(this)) {
return false
}
}
if (this is LiveTemplateLookupElement) {
return false
}
val lookupString = try {
LookupElementPresentation.renderElement(this).itemText ?: return false
}
catch (e: Exception) {
return false
}
val textAtLookup = originalText.substring(lookupStartOffset)
if (textAtLookup.take(lookupString.length) != lookupString) {
return false
}
return textAtLookup.length == lookupString.length ||
!Character.isJavaIdentifierPart(textAtLookup[lookupString.length] + 1)
}
private fun executeEditorAction(actionId: String, timerTick: Long) {
val actionManager = ActionManagerEx.getInstanceEx()
val action = actionManager.getAction(actionId)
val event = AnActionEvent.createFromAnAction(action, null, "",
DataManager.getInstance().getDataContext(
editor.component))
action.beforeActionPerformedUpdate(event)
actionManager.fireBeforeActionPerformed(action, event.dataContext, event)
LatencyRecorder.getInstance().recordLatencyAwareAction(editor, actionId, timerTick)
action.actionPerformed(event)
actionManager.fireAfterActionPerformed(action, event.dataContext, event)
}
private fun logThreadDump() {
if (editor.isProcessingTypedAction || waitingForTimerInvokeLater) {
threadDumps.add(ThreadDumper.dumpThreadsToString())
if (threadDumps.size > 200) {
threadDumps.subList(0, 100).clear()
}
synchronized(disposeLock) {
if (!threadDumpAlarm.isDisposed) {
threadDumpAlarm.addRequest({ logThreadDump() }, threadDumpDelay)
}
}
}
}
private fun startLargeIndexing() {
if (filesForIndexCount <= 0) return
val dir = File(editor.virtualFile.parent.path, LARGE_INDEX_DIR_NAME)
dir.mkdir()
for (i in 0..filesForIndexCount) {
val file = File(dir, "MyClass$i.java")
file.createNewFile()
file.writeText(code.repeat(500))
}
}
private fun removeLargeIndexing() {
if (filesForIndexCount <= 0) return
val dir = File(editor.virtualFile.parent.path, LARGE_INDEX_DIR_NAME)
dir.deleteRecursively()
}
@Language("JAVA")
val code = """
final class MyClass {
public static void main1(String[] args) {
int x = 5;
}
}
""".trimIndent()
companion object {
val LOG = Logger.getInstance(RetypeSession::class.java)
const val INTERFERE_FILE_NAME = "IdeaRetypeBackgroundChanges.java"
const val LARGE_INDEX_DIR_NAME = "_indexDir_"
}
}
val RETYPE_SESSION_KEY = Key.create<RetypeSession>("com.intellij.internal.retype.RetypeSession")
val RETYPE_SESSION_NOTIFICATION_KEY = Key.create<EditorNotificationPanel>("com.intellij.internal.retype.RetypeSessionNotification")
class RetypeEditorNotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>() {
override fun getKey(): Key<EditorNotificationPanel> = RETYPE_SESSION_NOTIFICATION_KEY
override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? {
if (fileEditor !is PsiAwareTextEditorImpl) return null
val retypeSession = fileEditor.editor.getUserData(RETYPE_SESSION_KEY)
if (retypeSession == null) return null
val panel: EditorNotificationPanel
if (retypeSession.retypePaused) {
panel = EditorNotificationPanel(fileEditor)
panel.setText("Pause retyping. Click on editor to resume")
}
else {
panel = EditorNotificationPanel(LightColors.SLIGHTLY_GREEN)
panel.setText("Retyping")
}
panel.createActionLabel("Stop without report") {
retypeSession.stop(false)
}
return panel
}
}
| apache-2.0 | 8bc07943715218b2df26cf903c2735ec | 36.298077 | 177 | 0.700524 | 4.788889 | false | false | false | false |
ursjoss/sipamato | core/core-web/src/main/java/ch/difty/scipamato/core/config/ScipamatoProperties.kt | 2 | 3086 | package ch.difty.scipamato.core.config
import ch.difty.scipamato.common.config.ScipamatoBaseProperties
import ch.difty.scipamato.core.logic.exporting.RisExporterStrategy
import ch.difty.scipamato.core.logic.parsing.AuthorParserStrategy
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.stereotype.Component
@Component
@ConfigurationProperties(prefix = "scipamato")
data class ScipamatoProperties(
/**
* Brand name of the application. Appears e.g. in the Navbar.
*/
override var brand: String = "SciPaMaTo-Core",
/**
* Page Title of the application. Appears in the browser tab.
*/
override var pageTitle: String? = null,
/**
* Default localization. Normally the browser locale is used.
*/
override var defaultLocalization: String = "en",
/**
* The base url used to access the Pubmed API.
*/
override var pubmedBaseUrl: String = "https://www.ncbi.nlm.nih.gov/pubmed/",
/**
* The author parser used for parsing Author Strings. Currently only
* DEFAULT is implemented.
*/
var authorParser: String = "DEFAULT",
/**
* The ris export adapter used for exporting studies into RIS format. Currently only
* DEFAULT and DISTILLERSR is implemented.
*/
var risExporter: String = "DEFAULT",
/**
* Any free number below this threshold will not be reused.
*/
var paperNumberMinimumToBeRecycled: Int = 0,
/**
* DB Schema.
*/
var dbSchema: String = "public",
/**
* Port from where an unsecured http connection is forwarded to the secured
* https port (@literal server.port}. Only has an effect if https is configured.
*/
override var redirectFromPort: Int? = null,
/**
* The URL of the CMS page that points to the paper search page
*/
override var cmsUrlSearchPage: String? = null,
/**
* @return the author parser strategy used for interpreting the authors string.
*/
var authorParserStrategy: AuthorParserStrategy = AuthorParserStrategy.fromProperty(authorParser, AUTHOR_PARSER_PROPERTY_KEY),
/**
* @return the strategy for exporting studies into RIS file format.
*/
var risExporterStrategy: RisExporterStrategy = RisExporterStrategy.fromProperty(risExporter, RIS_EXPORTER_PROPERTY_KEY),
/**
* The threshold above which the multi-select box may (if configured) show the
* action box providing the select all/select none buttons
*/
override var multiSelectBoxActionBoxWithMoreEntriesThan: Int = 4,
/**
* The API Key used for accessing pubmed papers.
*
*
* https://ncbiinsights.ncbi.nlm.nih.gov/2017/11/02/new-api-keys-for-the-e-utilities/
*/
var pubmedApiKey: String? = null,
) : ScipamatoBaseProperties {
companion object {
private const val serialVersionUID = 1L
private const val AUTHOR_PARSER_PROPERTY_KEY = "scipamato.author-parser"
private const val RIS_EXPORTER_PROPERTY_KEY = "scipamato.ris-exporter"
}
}
| gpl-3.0 | 9835daa03d3cf4ae0c6de81a43c8a127 | 31.145833 | 129 | 0.68827 | 4.322129 | false | true | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/jvm/src/Executors.kt | 1 | 8876 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.internal.*
import java.io.*
import java.util.concurrent.*
import kotlin.coroutines.*
/**
* [CoroutineDispatcher] that has underlying [Executor] for dispatching tasks.
* Instances of [ExecutorCoroutineDispatcher] should be closed by the owner of the dispatcher.
*
* This class is generally used as a bridge between coroutine-based API and
* asynchronous API that requires an instance of the [Executor].
*/
public abstract class ExecutorCoroutineDispatcher: CoroutineDispatcher(), Closeable {
/** @suppress */
@ExperimentalStdlibApi
public companion object Key : AbstractCoroutineContextKey<CoroutineDispatcher, ExecutorCoroutineDispatcher>(
CoroutineDispatcher,
{ it as? ExecutorCoroutineDispatcher })
/**
* Underlying executor of current [CoroutineDispatcher].
*/
public abstract val executor: Executor
/**
* Closes this coroutine dispatcher and shuts down its executor.
*
* It may throw an exception if this dispatcher is global and cannot be closed.
*/
public abstract override fun close()
}
@ExperimentalCoroutinesApi
public actual typealias CloseableCoroutineDispatcher = ExecutorCoroutineDispatcher
/**
* Converts an instance of [ExecutorService] to an implementation of [ExecutorCoroutineDispatcher].
*
* ## Interaction with [delay] and time-based coroutines.
*
* If the given [ExecutorService] is an instance of [ScheduledExecutorService], then all time-related
* coroutine operations such as [delay], [withTimeout] and time-based [Flow] operators will be scheduled
* on this executor using [schedule][ScheduledExecutorService.schedule] method. If the corresponding
* coroutine is cancelled, [ScheduledFuture.cancel] will be invoked on the corresponding future.
*
* If the given [ExecutorService] is an instance of [ScheduledThreadPoolExecutor], then prior to any scheduling,
* remove on cancel policy will be set via [ScheduledThreadPoolExecutor.setRemoveOnCancelPolicy] in order
* to reduce the memory pressure of cancelled coroutines.
*
* If the executor service is neither of this types, the separate internal thread will be used to
* _track_ the delay and time-related executions, but the coroutine itself will still be executed
* on top of the given executor.
*
* ## Rejected execution
* If the underlying executor throws [RejectedExecutionException] on
* attempt to submit a continuation task (it happens when [closing][ExecutorCoroutineDispatcher.close] the
* resulting dispatcher, on underlying executor [shutdown][ExecutorService.shutdown], or when it uses limited queues),
* then the [Job] of the affected task is [cancelled][Job.cancel] and the task is submitted to the
* [Dispatchers.IO], so that the affected coroutine can cleanup its resources and promptly complete.
*/
@JvmName("from") // this is for a nice Java API, see issue #255
public fun ExecutorService.asCoroutineDispatcher(): ExecutorCoroutineDispatcher =
ExecutorCoroutineDispatcherImpl(this)
/**
* Converts an instance of [Executor] to an implementation of [CoroutineDispatcher].
*
* ## Interaction with [delay] and time-based coroutines.
*
* If the given [Executor] is an instance of [ScheduledExecutorService], then all time-related
* coroutine operations such as [delay], [withTimeout] and time-based [Flow] operators will be scheduled
* on this executor using [schedule][ScheduledExecutorService.schedule] method. If the corresponding
* coroutine is cancelled, [ScheduledFuture.cancel] will be invoked on the corresponding future.
*
* If the given [Executor] is an instance of [ScheduledThreadPoolExecutor], then prior to any scheduling,
* remove on cancel policy will be set via [ScheduledThreadPoolExecutor.setRemoveOnCancelPolicy] in order
* to reduce the memory pressure of cancelled coroutines.
*
* If the executor is neither of this types, the separate internal thread will be used to
* _track_ the delay and time-related executions, but the coroutine itself will still be executed
* on top of the given executor.
*
* ## Rejected execution
*
* If the underlying executor throws [RejectedExecutionException] on
* attempt to submit a continuation task (it happens when [closing][ExecutorCoroutineDispatcher.close] the
* resulting dispatcher, on underlying executor [shutdown][ExecutorService.shutdown], or when it uses limited queues),
* then the [Job] of the affected task is [cancelled][Job.cancel] and the task is submitted to the
* [Dispatchers.IO], so that the affected coroutine can cleanup its resources and promptly complete.
*/
@JvmName("from") // this is for a nice Java API, see issue #255
public fun Executor.asCoroutineDispatcher(): CoroutineDispatcher =
(this as? DispatcherExecutor)?.dispatcher ?: ExecutorCoroutineDispatcherImpl(this)
/**
* Converts an instance of [CoroutineDispatcher] to an implementation of [Executor].
*
* It returns the original executor when used on the result of [Executor.asCoroutineDispatcher] extensions.
*/
public fun CoroutineDispatcher.asExecutor(): Executor =
(this as? ExecutorCoroutineDispatcher)?.executor ?: DispatcherExecutor(this)
private class DispatcherExecutor(@JvmField val dispatcher: CoroutineDispatcher) : Executor {
override fun execute(block: Runnable) = dispatcher.dispatch(EmptyCoroutineContext, block)
override fun toString(): String = dispatcher.toString()
}
internal class ExecutorCoroutineDispatcherImpl(override val executor: Executor) : ExecutorCoroutineDispatcher(), Delay {
/*
* Attempts to reflectively (to be Java 6 compatible) invoke
* ScheduledThreadPoolExecutor.setRemoveOnCancelPolicy in order to cleanup
* internal scheduler queue on cancellation.
*/
init {
removeFutureOnCancel(executor)
}
override fun dispatch(context: CoroutineContext, block: Runnable) {
try {
executor.execute(wrapTask(block))
} catch (e: RejectedExecutionException) {
unTrackTask()
cancelJobOnRejection(context, e)
Dispatchers.IO.dispatch(context, block)
}
}
override fun scheduleResumeAfterDelay(timeMillis: Long, continuation: CancellableContinuation<Unit>) {
val future = (executor as? ScheduledExecutorService)?.scheduleBlock(
ResumeUndispatchedRunnable(this, continuation),
continuation.context,
timeMillis
)
// If everything went fine and the scheduling attempt was not rejected -- use it
if (future != null) {
continuation.cancelFutureOnCancellation(future)
return
}
// Otherwise fallback to default executor
DefaultExecutor.scheduleResumeAfterDelay(timeMillis, continuation)
}
override fun invokeOnTimeout(timeMillis: Long, block: Runnable, context: CoroutineContext): DisposableHandle {
val future = (executor as? ScheduledExecutorService)?.scheduleBlock(block, context, timeMillis)
return when {
future != null -> DisposableFutureHandle(future)
else -> DefaultExecutor.invokeOnTimeout(timeMillis, block, context)
}
}
private fun ScheduledExecutorService.scheduleBlock(block: Runnable, context: CoroutineContext, timeMillis: Long): ScheduledFuture<*>? {
return try {
schedule(block, timeMillis, TimeUnit.MILLISECONDS)
} catch (e: RejectedExecutionException) {
cancelJobOnRejection(context, e)
null
}
}
private fun cancelJobOnRejection(context: CoroutineContext, exception: RejectedExecutionException) {
context.cancel(CancellationException("The task was rejected", exception))
}
override fun close() {
(executor as? ExecutorService)?.shutdown()
}
override fun toString(): String = executor.toString()
override fun equals(other: Any?): Boolean = other is ExecutorCoroutineDispatcherImpl && other.executor === executor
override fun hashCode(): Int = System.identityHashCode(executor)
}
private class ResumeUndispatchedRunnable(
private val dispatcher: CoroutineDispatcher,
private val continuation: CancellableContinuation<Unit>
) : Runnable {
override fun run() {
with(continuation) { dispatcher.resumeUndispatched(Unit) }
}
}
/**
* An implementation of [DisposableHandle] that cancels the specified future on dispose.
* @suppress **This is unstable API and it is subject to change.**
*/
private class DisposableFutureHandle(private val future: Future<*>) : DisposableHandle {
override fun dispose() {
future.cancel(false)
}
override fun toString(): String = "DisposableFutureHandle[$future]"
}
| apache-2.0 | 633b97ef6c8f453ca722833b237f926e | 43.603015 | 139 | 0.739973 | 5.133603 | false | false | false | false |
martinlau/fixture | src/main/kotlin/io/fixture/repository/PersistentLoginRepository.kt | 1 | 1721 | /*
* #%L
* fixture
* %%
* Copyright (C) 2013 Martin Lau
* %%
* 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.
* #L%
*/
package io.fixture.repository
import io.fixture.domain.PersistentLogin
import java.util.UUID
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param
import javax.persistence.QueryHint
import org.springframework.data.jpa.repository.QueryHints
trait PersistentLoginRepository: JpaRepository<PersistentLogin, UUID> {
[Modifying]
[Query(value = "DELETE FROM PersistentLogin pl WHERE pl.user = (SELECT u FROM User u WHERE u.username = :username)")]
[QueryHints(value = array(
QueryHint(name = "org.hibernate.cacheable", value = "true")
))]
fun deleteAllForUsername([Param(value = "username")] username: String)
[Query(value = "SELECT pl FROM PersistentLogin pl WHERE pl.series = :series")]
[QueryHints(value = array(
QueryHint(name = "org.hibernate.cacheable", value = "true")
))]
fun findOne([Param(value = "series")] series: String): PersistentLogin?
}
| apache-2.0 | 68df25bfedc2202e23d38eed6e96365a | 35.617021 | 121 | 0.730389 | 3.974596 | false | false | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/openapi/observable/properties/PropertyGraph.kt | 1 | 2901 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.observable.properties
import org.jetbrains.annotations.TestOnly
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.atomic.AtomicBoolean
class PropertyGraph {
private val inPropagation = AtomicBoolean(false)
private val propagationListeners = CopyOnWriteArrayList<() -> Unit>()
private val properties = ConcurrentHashMap<ObservableClearableProperty<*>, PropertyNode>()
private val dependencies = ConcurrentHashMap<PropertyNode, CopyOnWriteArrayList<Dependency<*>>>()
fun <T> dependsOn(child: ObservableClearableProperty<T>, parent: ObservableClearableProperty<*>, update: () -> T) {
val childNode = properties[child] ?: throw IllegalArgumentException("Unregistered child property")
val parentNode = properties[parent] ?: throw IllegalArgumentException("Unregistered parent property")
dependencies.putIfAbsent(parentNode, CopyOnWriteArrayList())
val children = dependencies.getValue(parentNode)
children.add(Dependency(childNode, child, update))
}
fun afterPropagation(listener: () -> Unit) {
propagationListeners.add(listener)
}
fun register(property: ObservableClearableProperty<*>) {
val node = PropertyNode()
properties[property] = node
property.afterChange {
if (!inPropagation.get()) {
node.isPropagationBlocked = true
}
}
property.afterReset {
node.isPropagationBlocked = false
}
property.afterChange {
inPropagation.withLockIfCan {
node.inPropagation.withLockIfCan {
propagateChange(node)
}
propagationListeners.forEach { it() }
}
}
}
private fun propagateChange(parent: PropertyNode) {
val dependencies = dependencies[parent] ?: return
for (dependency in dependencies) {
val child = dependency.node
if (child.isPropagationBlocked) continue
child.inPropagation.withLockIfCan {
dependency.applyUpdate()
propagateChange(child)
}
}
}
@TestOnly
fun isPropagationBlocked(property: ObservableClearableProperty<*>) =
properties.getValue(property).isPropagationBlocked
private inner class PropertyNode {
@Volatile
var isPropagationBlocked = false
val inPropagation = AtomicBoolean(false)
}
private class Dependency<T>(val node: PropertyNode, private val property: ObservableClearableProperty<T>, private val update: () -> T) {
fun applyUpdate() {
property.set(update())
}
}
companion object {
private inline fun AtomicBoolean.withLockIfCan(action: () -> Unit) {
if (!compareAndSet(false, true)) return
try {
action()
}
finally {
set(false)
}
}
}
} | apache-2.0 | c90b133243544baa119f7bcdcf85ff54 | 32.356322 | 140 | 0.711479 | 5.045217 | false | false | false | false |
benoitletondor/EasyBudget | Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/db/impl/ExpenseDao.kt | 1 | 4093 | /*
* Copyright 2022 Benoit LETONDOR
*
* 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.benoitletondor.easybudgetapp.db.impl
import androidx.room.*
import com.benoitletondor.easybudgetapp.db.impl.entity.ExpenseEntity
import com.benoitletondor.easybudgetapp.db.impl.entity.RecurringExpenseEntity
import androidx.sqlite.db.SupportSQLiteQuery
import androidx.room.RawQuery
import java.time.LocalDate
@Dao
interface ExpenseDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun persistExpense(expenseEntity: ExpenseEntity): Long
@Query("SELECT COUNT(*) FROM expense WHERE date = :dayDate LIMIT 1")
suspend fun hasExpenseForDay(dayDate: LocalDate): Int
@Query("SELECT * FROM expense WHERE date = :dayDate")
suspend fun getExpensesForDay(dayDate: LocalDate): List<ExpenseEntity>
@Query("SELECT * FROM expense WHERE date >= :monthStartDate AND date <= :monthEndDate")
suspend fun getExpensesForMonth(monthStartDate: LocalDate, monthEndDate: LocalDate): List<ExpenseEntity>
@Query("SELECT SUM(amount) FROM expense WHERE date <= :dayDate")
suspend fun getBalanceForDay(dayDate: LocalDate): Long?
@Query("SELECT SUM(amount) FROM expense WHERE date <= :dayDate AND checked")
suspend fun getCheckedBalanceForDay(dayDate: LocalDate): Long?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun persistRecurringExpense(recurringExpenseEntity: RecurringExpenseEntity): Long
@Delete
suspend fun deleteRecurringExpense(recurringExpenseEntity: RecurringExpenseEntity)
@Delete
suspend fun deleteExpense(expenseEntity: ExpenseEntity)
@Query("DELETE FROM expense WHERE monthly_id = :recurringExpenseId")
suspend fun deleteAllExpenseForRecurringExpense(recurringExpenseId: Long)
@Query("SELECT * FROM expense WHERE monthly_id = :recurringExpenseId")
suspend fun getAllExpenseForRecurringExpense(recurringExpenseId: Long): List<ExpenseEntity>
@Query("DELETE FROM expense WHERE monthly_id = :recurringExpenseId AND date > :afterDate")
suspend fun deleteAllExpenseForRecurringExpenseAfterDate(recurringExpenseId: Long, afterDate: LocalDate)
@Query("SELECT * FROM expense WHERE monthly_id = :recurringExpenseId AND date > :afterDate")
suspend fun getAllExpensesForRecurringExpenseAfterDate(recurringExpenseId: Long, afterDate: LocalDate): List<ExpenseEntity>
@Query("DELETE FROM expense WHERE monthly_id = :recurringExpenseId AND date < :beforeDate")
suspend fun deleteAllExpenseForRecurringExpenseBeforeDate(recurringExpenseId: Long, beforeDate: LocalDate)
@Query("SELECT * FROM expense WHERE monthly_id = :recurringExpenseId AND date < :beforeDate")
suspend fun getAllExpensesForRecurringExpenseBeforeDate(recurringExpenseId: Long, beforeDate: LocalDate): List<ExpenseEntity>
@Query("SELECT count(*) FROM expense WHERE monthly_id = :recurringExpenseId AND date < :beforeDate LIMIT 1")
suspend fun hasExpensesForRecurringExpenseBeforeDate(recurringExpenseId: Long, beforeDate: LocalDate): Int
@Query("SELECT * FROM monthlyexpense WHERE _expense_id = :recurringExpenseId LIMIT 1")
suspend fun findRecurringExpenseForId(recurringExpenseId: Long): RecurringExpenseEntity?
@RawQuery
suspend fun checkpoint(supportSQLiteQuery: SupportSQLiteQuery): Int
@Query("SELECT * FROM expense ORDER BY date LIMIT 1")
suspend fun getOldestExpense(): ExpenseEntity?
@Query("UPDATE expense SET checked = 1 WHERE date < :beforeDate")
suspend fun markAllEntriesAsChecked(beforeDate: LocalDate)
} | apache-2.0 | 477482fdb2caf3c2cea554705578fc14 | 45.522727 | 129 | 0.773027 | 4.931325 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/statics/incInClassObject.kt | 5 | 1486 | class A {
companion object {
private var r: Int = 1;
fun test(): Int {
r++
++r
return r
}
var holder: String = ""
var r2: Int = 1
get() {
holder += "getR2"
return field
}
fun test2() : Int {
r2++
++r2
return r2
}
var r3: Int = 1
set(p: Int) {
holder += "setR3"
field = p
}
fun test3() : Int {
r3++
++r3
return r3
}
var r4: Int = 1
get() {
holder += "getR4"
return field
}
set(p: Int) {
holder += "setR4"
field = p
}
fun test4() : Int {
r4++
holder += ":"
++r4
return r4
}
}
}
fun box() : String {
val p = A.test()
if (p != 3) return "fail 1: $p"
val p2 = A.test2()
var holderValue = A.holder
if (p2 != 3 || holderValue != "getR2getR2getR2getR2") return "fail 2: $p2 ${holderValue}"
A.holder = ""
val p3 = A.test3()
if (p3 != 3 || A.holder != "setR3setR3") return "fail 3: $p3 ${A.holder}"
A.holder = ""
val p4 = A.test4()
if (p4 != 3 || A.holder != "getR4setR4:getR4setR4getR4getR4") return "fail 4: $p4 ${A.holder}"
return "OK"
} | apache-2.0 | 0c531a33c175b7749f97bf00f28055fe | 19.369863 | 99 | 0.368102 | 3.651106 | false | true | false | false |
android/compose-samples | Jetsnack/app/src/main/java/com/example/jetsnack/ui/home/cart/CartViewModel.kt | 1 | 3432 | /*
* Copyright 2020 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.
*/
package com.example.jetsnack.ui.home.cart
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.jetsnack.R
import com.example.jetsnack.model.OrderLine
import com.example.jetsnack.model.SnackRepo
import com.example.jetsnack.model.SnackbarManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/**
* Holds the contents of the cart and allows changes to it.
*
* TODO: Move data to Repository so it can be displayed and changed consistently throughout the app.
*/
class CartViewModel(
private val snackbarManager: SnackbarManager,
snackRepository: SnackRepo
) : ViewModel() {
private val _orderLines: MutableStateFlow<List<OrderLine>> =
MutableStateFlow(snackRepository.getCart())
val orderLines: StateFlow<List<OrderLine>> get() = _orderLines
// Logic to show errors every few requests
private var requestCount = 0
private fun shouldRandomlyFail(): Boolean = ++requestCount % 5 == 0
fun increaseSnackCount(snackId: Long) {
if (!shouldRandomlyFail()) {
val currentCount = _orderLines.value.first { it.snack.id == snackId }.count
updateSnackCount(snackId, currentCount + 1)
} else {
snackbarManager.showMessage(R.string.cart_increase_error)
}
}
fun decreaseSnackCount(snackId: Long) {
if (!shouldRandomlyFail()) {
val currentCount = _orderLines.value.first { it.snack.id == snackId }.count
if (currentCount == 1) {
// remove snack from cart
removeSnack(snackId)
} else {
// update quantity in cart
updateSnackCount(snackId, currentCount - 1)
}
} else {
snackbarManager.showMessage(R.string.cart_decrease_error)
}
}
fun removeSnack(snackId: Long) {
_orderLines.value = _orderLines.value.filter { it.snack.id != snackId }
}
private fun updateSnackCount(snackId: Long, count: Int) {
_orderLines.value = _orderLines.value.map {
if (it.snack.id == snackId) {
it.copy(count = count)
} else {
it
}
}
}
/**
* Factory for CartViewModel that takes SnackbarManager as a dependency
*/
companion object {
fun provideFactory(
snackbarManager: SnackbarManager = SnackbarManager,
snackRepository: SnackRepo = SnackRepo
): ViewModelProvider.Factory = object : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return CartViewModel(snackbarManager, snackRepository) as T
}
}
}
}
| apache-2.0 | 889d480962038e68272c47e9560f3605 | 34.020408 | 100 | 0.656177 | 4.760055 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/inventory/QuestColors.kt | 1 | 810 | package com.habitrpg.android.habitica.models.inventory
import android.graphics.Color
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
/**
* Created by phillip on 31.01.18.
*/
open class QuestColors : RealmObject() {
@PrimaryKey
var key: String? = null
var dark: String? = null
var medium: String? = null
var light: String? = null
var extralight: String? = null
var darkColor: Int = 0
get() {
return Color.parseColor(dark)
}
var mediumColor: Int = 0
get() {
return Color.parseColor(medium)
}
var lightColor: Int = 0
get() {
return Color.parseColor(light)
}
var extraLightColor: Int = 0
get() {
return Color.parseColor(extralight)
}
}
| gpl-3.0 | 45bd469516de099e39227434ae1e0177 | 21.5 | 54 | 0.597531 | 4.05 | false | false | false | false |
jillesvangurp/jsonj | src/main/kotlin/com/github/jsonj/JsonJExtensions.kt | 1 | 8654 | package com.github.jsonj
import com.github.jsonj.tools.JsonBuilder
import com.github.jsonj.tools.JsonBuilder.array
import com.github.jsonj.tools.JsonBuilder.nullValue
import com.github.jsonj.tools.JsonBuilder.primitive
import org.apache.commons.lang3.StringUtils
import java.lang.IllegalStateException
import java.math.BigDecimal
import java.math.BigInteger
import java.util.Locale
import kotlin.reflect.KClass
import kotlin.reflect.KParameter
import kotlin.reflect.KType
import kotlin.reflect.full.cast
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.full.isSubtypeOf
import kotlin.reflect.full.primaryConstructor
import kotlin.reflect.full.starProjectedType
import kotlin.reflect.full.withNullability
import kotlin.reflect.jvm.jvmErasure
fun obj(init: JsonObject.() -> Unit): JsonObject {
val newObject = JsonObject()
newObject.init()
return newObject
}
fun arr(init: JsonArray.() -> Unit): JsonArray {
val newObject = JsonArray()
newObject.init()
return newObject
}
fun JsonObject.field(key: String, vararg values: Any) {
when (values.size) {
0 -> put(key, JsonBuilder.nullValue())
1 -> put(key, values[0])
else -> put(key, JsonBuilder.array(*values))
}
}
fun JsonObject.arrayField(key: String, vararg values: Any) {
put(key, JsonBuilder.array(*values))
}
/**
* @param property name
* @param ignoreCase if true ignore case
* @param ignoreUnderscores if true ignore underscores
* @return the value of the first field matching the name or null
*/
fun JsonObject.flexGet(name: String, ignoreCase: Boolean = true, ignoreUnderscores: Boolean = true): JsonElement? {
val key =
keys.filter { normalize(it, ignoreCase, ignoreUnderscores) == normalize(name, ignoreCase, ignoreUnderscores) }
.firstOrNull()
return if (key != null) {
val value = get(key)
if (value?.isNull() == true) {
// handle json null as null
null
} else {
value
}
} else {
null
}
}
fun <T : Enum<*>> enumVal(clazz: KClass<T>, value: String): T? {
val enumConstants = clazz.java.enumConstants
return enumConstants.filter { value == it.name }.first()
}
/**
* @param clazz a kotlin class
* @return a new instance of clazz populated with values from the json object matched on the property names (ignoring case and underscores).
*/
fun <T : Any> JsonObject.construct(clazz: KClass<T>): T {
val primaryConstructor = clazz.primaryConstructor
val paramz: MutableMap<KParameter, Any?> = mutableMapOf()
if (primaryConstructor != null) {
primaryConstructor.parameters.forEach {
val name = it.name.orEmpty()
val nonNullableType = it.type.withNullability(false)
if (nonNullableType.isSubtypeOf(Int::class.starProjectedType)) {
paramz.put(it, flexGet(name)?.asInt())
} else if (nonNullableType.isSubtypeOf(Long::class.starProjectedType.withNullability(true))) {
paramz.put(it, flexGet(name)?.asLong())
} else if (nonNullableType.isSubtypeOf(Float::class.starProjectedType.withNullability(true))) {
paramz.put(it, flexGet(name)?.asFloat())
} else if (nonNullableType.isSubtypeOf(Double::class.starProjectedType.withNullability(true))) {
paramz.put(it, flexGet(name)?.asDouble())
} else if (nonNullableType.isSubtypeOf(BigInteger::class.starProjectedType.withNullability(true))) {
paramz.put(it, flexGet(name)?.asNumber())
} else if (nonNullableType.isSubtypeOf(BigDecimal::class.starProjectedType.withNullability(true))) {
paramz.put(it, flexGet(name)?.asNumber())
} else if (nonNullableType.isSubtypeOf(Long::class.starProjectedType.withNullability(true))) {
paramz.put(it, flexGet(name)?.asLong())
} else if (nonNullableType.isSubtypeOf(String::class.starProjectedType.withNullability(true))) {
paramz.put(it, flexGet(name)?.asString())
} else if (nonNullableType.isSubtypeOf(Boolean::class.starProjectedType.withNullability(true))) {
paramz.put(it, flexGet(name)?.asBoolean())
} else if (nonNullableType.isSubtypeOf(Enum::class.starProjectedType.withNullability(true))) {
val enumName = flexGet(name)?.asString()
if (enumName != null) {
@Suppress("UNCHECKED_CAST") // we already checked but too hard for Kotlin to figure out
paramz.put(it, enumVal(it.type.jvmErasure as KClass<Enum<*>>, enumName))
}
} else if (nonNullableType.isSubtypeOf(JsonElement::class.starProjectedType.withNullability(true))) {
paramz.put(it, flexGet(name))
} else {
paramz.put(it, flexGet(name)?.asObject()?.construct(it.type.jvmErasure))
}
}
return primaryConstructor.callBy(paramz)
} else {
throw IllegalStateException("no primary constructor for ${clazz.qualifiedName}")
}
}
/**
* Attempt to populate the json object using the properties of the provided object. Field names are lower cased and underscored.
* @param obj an object
*/
fun <T : Any> JsonObject.fill(obj: T): JsonObject {
val clazz = obj::class
for (memberProperty in clazz.declaredMemberProperties) {
val propertyName = memberProperty.name
val jsonName = toUnderscore(propertyName)
try {
val value = memberProperty.getter.call(obj)
if (memberProperty.returnType.isSubtypeOf(Enum::class.starProjectedType)) {
val enumValue = value as Enum<*>
put(jsonName, enumValue.name)
} else {
val returnType = memberProperty.returnType
val jsonElement: JsonElement = jsonElement(returnType, value)
put(jsonName, jsonElement)
}
} catch (e: UnsupportedOperationException) {
// function properties fail, skip those
if (!(e.message?.contains("internal synthetic class") ?: false)) {
throw e
} else {
@Suppress("UNCHECKED_CAST") // this seems to work ;-), ugly though
val fn = (memberProperty.call(obj) ?: throw e) as Function0<Any>
put(jsonName, fn.invoke())
}
}
}
return this
}
private fun normalize(input: String, lower: Boolean = true, ignoreUnderscores: Boolean = true): String {
val normalized = if (ignoreUnderscores) input.replace("_", "") else input
return if (lower) normalized.toLowerCase(Locale.ROOT) else normalized
}
private fun toUnderscore(propertyName: String): String {
return StringUtils.splitByCharacterTypeCamelCase(propertyName)
.filter { !it.equals("_") } // avoid getting ___
.map { it.toLowerCase(Locale.ROOT) }
.joinToString("_")
}
private fun jsonElement(returnType: KType, value: Any?): JsonElement {
val jsonElement: JsonElement
if (value == null) {
return nullValue()
}
val nonNullableReturnType = returnType.withNullability(false)
if (nonNullableReturnType.isSubtypeOf(JsonElement::class.starProjectedType)) {
jsonElement = value as JsonElement
} else if (nonNullableReturnType.isSubtypeOf(JsonDataObject::class.starProjectedType)) {
jsonElement = (value as JsonDataObject).jsonObject
} else if (nonNullableReturnType.isSubtypeOf(Number::class.starProjectedType) ||
nonNullableReturnType.isSubtypeOf(String::class.starProjectedType) ||
nonNullableReturnType.isSubtypeOf(Boolean::class.starProjectedType)
) {
jsonElement = primitive(value)
} else if (nonNullableReturnType.isSubtypeOf(Collection::class.starProjectedType)) {
val arr = array()
Collection::class.cast(value).forEach {
if (it != null) {
arr.add(jsonElement(it::class.starProjectedType, it))
}
}
jsonElement = arr
} else if (nonNullableReturnType.isSubtypeOf(Map::class.starProjectedType)) {
val newObj = JsonObject()
Map::class.cast(value).forEach {
if (it.key != null) {
if (it.value != null) {
newObj.put(toUnderscore(it.key.toString()), jsonElement(it::class.starProjectedType, it.value))
}
}
}
jsonElement = newObj
} else {
val newObj = JsonObject()
newObj.fill(value)
jsonElement = newObj
}
return jsonElement
}
| mit | 54499fc776c857fc0a8d849594025982 | 40.014218 | 140 | 0.651028 | 4.721222 | false | false | false | false |
siosio/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/autoimport/ProjectAware.kt | 1 | 4095 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project.autoimport
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.externalSystem.ExternalSystemAutoImportAware
import com.intellij.openapi.externalSystem.autoimport.*
import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType.RESOLVE_PROJECT
import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode
import com.intellij.openapi.externalSystem.service.internal.ExternalSystemProcessingManager
import com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask
import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import java.io.File
import java.util.concurrent.atomic.AtomicReference
class ProjectAware(
private val project: Project,
override val projectId: ExternalSystemProjectId,
private val autoImportAware: ExternalSystemAutoImportAware
) : ExternalSystemProjectAware {
private val systemId = projectId.systemId
private val projectPath = projectId.externalProjectPath
override val settingsFiles: Set<String>
get() = externalProjectFiles.map { FileUtil.toCanonicalPath(it.path) }.toSet()
private val externalProjectFiles: List<File>
get() = autoImportAware.getAffectedExternalProjectFiles(projectPath, project)
override fun subscribe(listener: ExternalSystemProjectRefreshListener, parentDisposable: Disposable) {
val progressManager = ExternalSystemProgressNotificationManager.getInstance()
progressManager.addNotificationListener(TaskNotificationListener(listener), parentDisposable)
}
override fun reloadProject(context: ExternalSystemProjectReloadContext) {
val importSpec = ImportSpecBuilder(project, systemId)
if (!context.isExplicitReload) {
importSpec.dontReportRefreshErrors()
importSpec.dontNavigateToError()
}
if (!ExternalSystemUtil.isTrusted(project, systemId)) {
importSpec.usePreviewMode()
}
ExternalSystemUtil.refreshProject(projectPath, importSpec)
}
private inner class TaskNotificationListener(
val delegate: ExternalSystemProjectRefreshListener
) : ExternalSystemTaskNotificationListenerAdapter() {
var externalSystemTaskId = AtomicReference<ExternalSystemTaskId?>(null)
override fun onStart(id: ExternalSystemTaskId, workingDir: String?) {
if (id.type != RESOLVE_PROJECT) return
if (!FileUtil.pathsEqual(workingDir, projectPath)) return
val task = ApplicationManager.getApplication().getService(ExternalSystemProcessingManager::class.java).findTask(id)
if (task is ExternalSystemResolveProjectTask) {
if (!autoImportAware.isApplicable(task.resolverPolicy)) {
return
}
}
externalSystemTaskId.set(id)
delegate.beforeProjectRefresh()
}
private fun afterProjectRefresh(id: ExternalSystemTaskId, status: ExternalSystemRefreshStatus) {
if (id.type != RESOLVE_PROJECT) return
if (!externalSystemTaskId.compareAndSet(id, null)) return
delegate.afterProjectRefresh(status)
}
override fun onSuccess(id: ExternalSystemTaskId) {
afterProjectRefresh(id, ExternalSystemRefreshStatus.SUCCESS)
}
override fun onFailure(id: ExternalSystemTaskId, e: Exception) {
afterProjectRefresh(id, ExternalSystemRefreshStatus.FAILURE)
}
override fun onCancel(id: ExternalSystemTaskId) {
afterProjectRefresh(id, ExternalSystemRefreshStatus.CANCEL)
}
}
} | apache-2.0 | 7c47fb88e4538e462df483a35d08fba4 | 44.010989 | 140 | 0.803419 | 5.489276 | false | false | false | false |
idea4bsd/idea4bsd | platform/script-debugger/backend/src/ValueModifierUtil.kt | 3 | 2567 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.thenAsyncAccept
import org.jetbrains.debugger.values.Value
import org.jetbrains.io.JsonUtil
import java.util.*
import java.util.regex.Pattern
private val KEY_NOTATION_PROPERTY_NAME_PATTERN = Pattern.compile("[\\p{L}_$]+[\\d\\p{L}_$]*")
object ValueModifierUtil {
fun setValue(variable: Variable,
newValue: String,
evaluateContext: EvaluateContext,
modifier: ValueModifier) = evaluateContext.evaluate(newValue)
.thenAsyncAccept { modifier.setValue(variable, it.value, evaluateContext) }
fun evaluateGet(variable: Variable,
host: Any,
evaluateContext: EvaluateContext,
selfName: String): Promise<Value> {
val builder = StringBuilder(selfName)
appendUnquotedName(builder, variable.name)
return evaluateContext.evaluate(builder.toString(), Collections.singletonMap(selfName, host), false)
.then {
variable.value = it.value
it.value
}
}
fun propertyNamesToString(list: List<String>, quotedAware: Boolean): String {
val builder = StringBuilder()
for (i in list.indices.reversed()) {
val name = list[i]
doAppendName(builder, name, quotedAware && (name[0] == '"' || name[0] == '\''))
}
return builder.toString()
}
fun appendUnquotedName(builder: StringBuilder, name: String) {
doAppendName(builder, name, false)
}
}
private fun doAppendName(builder: StringBuilder, name: String, quoted: Boolean) {
val useKeyNotation = !quoted && KEY_NOTATION_PROPERTY_NAME_PATTERN.matcher(name).matches()
if (builder.length != 0) {
builder.append(if (useKeyNotation) '.' else '[')
}
if (useKeyNotation) {
builder.append(name)
}
else {
if (quoted) {
builder.append(name)
}
else {
JsonUtil.escape(name, builder)
}
builder.append(']')
}
} | apache-2.0 | e7b0924283f12463568e0c5f5f69390a | 31.923077 | 104 | 0.683288 | 4.180782 | false | false | false | false |
ncoe/rosetta | Zumkeller_numbers/Kotlin/src/ZumkellerNumbers.kt | 1 | 3296 | import java.util.ArrayList
import kotlin.math.sqrt
object ZumkellerNumbers {
@JvmStatic
fun main(args: Array<String>) {
var n = 1
println("First 220 Zumkeller numbers:")
run {
var count = 1
while (count <= 220) {
if (isZumkeller(n)) {
print("%3d ".format(n))
if (count % 20 == 0) {
println()
}
count++
}
n += 1
}
}
n = 1
println("\nFirst 40 odd Zumkeller numbers:")
run {
var count = 1
while (count <= 40) {
if (isZumkeller(n)) {
print("%6d".format(n))
if (count % 10 == 0) {
println()
}
count++
}
n += 2
}
}
n = 1
println("\nFirst 40 odd Zumkeller numbers that do not end in a 5:")
var count = 1
while (count <= 40) {
if (n % 5 != 0 && isZumkeller(n)) {
print("%8d".format(n))
if (count % 10 == 0) {
println()
}
count++
}
n += 2
}
}
private fun isZumkeller(n: Int): Boolean { // numbers congruent to 6 or 12 modulo 18 are Zumkeller numbers
if (n % 18 == 6 || n % 18 == 12) {
return true
}
val divisors = getDivisors(n)
val divisorSum = divisors.stream().mapToInt { i: Int? -> i!! }.sum()
// divisor sum cannot be odd
if (divisorSum % 2 == 1) {
return false
}
// numbers where n is odd and the abundance is even are Zumkeller numbers
val abundance = divisorSum - 2 * n
if (n % 2 == 1 && abundance > 0 && abundance % 2 == 0) {
return true
}
divisors.sort()
val j = divisors.size - 1
val sum = divisorSum / 2
// Largest divisor larger than sum - then cannot partition and not Zumkeller number
return if (divisors[j] > sum) false else canPartition(j, divisors, sum, IntArray(2))
}
private fun canPartition(j: Int, divisors: List<Int>, sum: Int, buckets: IntArray): Boolean {
if (j < 0) {
return true
}
for (i in 0..1) {
if (buckets[i] + divisors[j] <= sum) {
buckets[i] += divisors[j]
if (canPartition(j - 1, divisors, sum, buckets)) {
return true
}
buckets[i] -= divisors[j]
}
if (buckets[i] == 0) {
break
}
}
return false
}
private fun getDivisors(number: Int): MutableList<Int> {
val divisors: MutableList<Int> = ArrayList()
val sqrt = sqrt(number.toDouble()).toLong()
for (i in 1..sqrt) {
if (number % i == 0L) {
divisors.add(i.toInt())
val div = (number / i).toInt()
if (div.toLong() != i) {
divisors.add(div)
}
}
}
return divisors
}
}
| mit | 5bfafe47eca4431880539f7cd8c46931 | 29.238532 | 111 | 0.418993 | 4.388815 | false | false | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/roots/standardContributors.kt | 1 | 6266 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.indexing.roots
import com.intellij.ide.lightEdit.LightEdit
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.*
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.addIfNotNull
import com.intellij.util.indexing.AdditionalIndexableFileSet
import com.intellij.util.indexing.IndexableSetContributor
import com.intellij.util.indexing.roots.builders.IndexableIteratorBuilders
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import java.util.function.Predicate
internal class DefaultProjectIndexableFilesContributor : IndexableFilesContributor {
override fun getIndexableFiles(project: Project): List<IndexableFilesIterator> {
@Suppress("DEPRECATION")
if (indexProjectBasedOnIndexableEntityProviders()) {
val builders: MutableList<IndexableEntityProvider.IndexableIteratorBuilder> = mutableListOf()
val entityStorage = WorkspaceModel.getInstance(project).entityStorage.current
for (provider in IndexableEntityProvider.EP_NAME.extensionList) {
if (provider is IndexableEntityProvider.Existing) {
addIteratorBuildersFromProvider(provider, entityStorage, project, builders)
ProgressManager.checkCanceled()
}
}
return IndexableIteratorBuilders.instantiateBuilders(builders, project, entityStorage)
}
else {
val seenLibraries: MutableSet<Library> = HashSet()
val seenSdks: MutableSet<Sdk> = HashSet()
val modules = ModuleManager.getInstance(project).sortedModules
val providers: MutableList<IndexableFilesIterator> = mutableListOf()
for (module in modules) {
providers.addAll(ModuleIndexableFilesIteratorImpl.getModuleIterators(module))
val orderEntries = ModuleRootManager.getInstance(module).orderEntries
for (orderEntry in orderEntries) {
when (orderEntry) {
is LibraryOrderEntry -> {
val library = orderEntry.library
if (library != null && seenLibraries.add(library)) {
@Suppress("DEPRECATION")
providers.addIfNotNull(LibraryIndexableFilesIteratorImpl.createIterator(library))
}
}
is JdkOrderEntry -> {
val sdk = orderEntry.jdk
if (sdk != null && seenSdks.add(sdk)) {
providers.add(SdkIndexableFilesIteratorImpl(sdk))
}
}
}
}
}
return providers
}
}
override fun getOwnFilePredicate(project: Project): Predicate<VirtualFile> {
val projectFileIndex: ProjectFileIndex = ProjectFileIndex.getInstance(project)
return Predicate {
if (LightEdit.owns(project)) {
return@Predicate false
}
if (projectFileIndex.isInContent(it) || projectFileIndex.isInLibrary(it)) {
!FileTypeManager.getInstance().isFileIgnored(it)
}
else false
}
}
companion object {
private fun <E : WorkspaceEntity> addIteratorBuildersFromProvider(provider: IndexableEntityProvider.Existing<E>,
entityStorage: WorkspaceEntityStorage,
project: Project,
iterators: MutableList<IndexableEntityProvider.IndexableIteratorBuilder>) {
val entityClass = provider.entityClass
for (entity in entityStorage.entities(entityClass)) {
iterators.addAll(provider.getExistingEntityIteratorBuilder(entity, project))
}
}
/**
* Registry property introduced to provide quick workaround for possible performance issues.
* Should be removed when the feature becomes stable
*/
@ApiStatus.ScheduledForRemoval
@Deprecated("Registry property introduced to provide quick workaround for possible performance issues. " +
"Should be removed when the feature is proved to be stable", ReplaceWith("true"))
@JvmStatic
fun indexProjectBasedOnIndexableEntityProviders(): Boolean = Registry.`is`("indexing.enable.entity.provider.based.indexing")
}
}
internal class AdditionalFilesContributor : IndexableFilesContributor {
override fun getIndexableFiles(project: Project): List<IndexableFilesIterator> {
return IndexableSetContributor.EP_NAME.extensionList.flatMap {
listOf(IndexableSetContributorFilesIterator(it, true),
IndexableSetContributorFilesIterator(it, false))
}
}
override fun getOwnFilePredicate(project: Project): Predicate<VirtualFile> {
val additionalFilesContributor = AdditionalIndexableFileSet(project)
return Predicate(additionalFilesContributor::isInSet)
}
}
internal class AdditionalLibraryRootsContributor : IndexableFilesContributor {
override fun getIndexableFiles(project: Project): List<IndexableFilesIterator> {
return AdditionalLibraryRootsProvider.EP_NAME
.extensionList
.flatMap { it.getAdditionalProjectLibraries(project) }
.map { SyntheticLibraryIndexableFilesIteratorImpl(it) }
}
override fun getOwnFilePredicate(project: Project): Predicate<VirtualFile> {
return Predicate { false }
// todo: synthetic library changes are served in DefaultProjectIndexableFilesContributor
}
companion object {
@JvmStatic
fun createIndexingIterator(presentableLibraryName: @Nls String?, rootsToIndex: List<VirtualFile>, libraryNameForDebug: String): IndexableFilesIterator =
AdditionalLibraryIndexableAddedFilesIterator(presentableLibraryName, rootsToIndex, libraryNameForDebug)
}
} | apache-2.0 | dba0cdae98ff78fcd19539f0ded7f727 | 43.764286 | 156 | 0.725981 | 5.53045 | false | false | false | false |
dowenliu-xyz/ketcd | ketcd-core/src/main/kotlin/xyz/dowenliu/ketcd/kv/Cmp.kt | 1 | 1849 | package xyz.dowenliu.ketcd.kv
import com.google.protobuf.ByteString
import xyz.dowenliu.ketcd.api.Compare
/**
* The compare predicate
*
* create at 2017/4/15
* @author liufl
* @since 0.1.0
*
* @property key Compare key
* @property op CmpOp
* @property target Compare target.
*/
class Cmp(private val key: ByteString,
private val op: CmpOp,
private val target: CmpTarget<*>) {
/**
* Predicate a [Compare] using in deeper gRPC APIs.
*
* @return A [Compare] predicated.
*/
fun toCompare(): Compare {
val builder = Compare.newBuilder().setKey(key)
.setResult(op.result)
.setTarget(target.target)
when (target) {
is CmpTarget.VersionCmpTarget -> builder.version = target.targetValue
is CmpTarget.ValueCmpTarget -> builder.value = target.targetValue
is CmpTarget.ModRevisionCmpTarget -> builder.modRevision = target.targetValue
is CmpTarget.CreateRevisionCmpTarget -> builder.createRevision = target.targetValue
else -> throw IllegalArgumentException("Unexpected target type ($target)")
}
return builder.build()
}
/**
* A sub collection of [Compare.CompareResult].
*
* In a Txn operation, we only do EQUAL, GREATER and LESS compare.
*
* @property result The [Compare.CompareResult] wrapping.
*/
enum class CmpOp(val result: Compare.CompareResult) {
/**
* A wrapper for [Compare.CompareResult.EQUAL]
*/
EQUAL(Compare.CompareResult.EQUAL),
/**
* A wrapper for [Compare.CompareResult.GREATER]
*/
GREATER(Compare.CompareResult.GREATER),
/**
* A wrapper for [Compare.CompareResult.LESS]
*/
LESS(Compare.CompareResult.LESS)
}
} | apache-2.0 | 8e33f3115b5022b27303e773255ad22f | 29.327869 | 95 | 0.619254 | 4.455422 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnsafeCastFromDynamicInspection.kt | 2 | 2688 | // 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.inspections
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.psi.expressionVisitor
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.isDynamic
import org.jetbrains.kotlin.types.typeUtil.isNullableAny
class UnsafeCastFromDynamicInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor =
expressionVisitor(fun(expression) {
val context = expression.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
val expectedType = context[BindingContext.EXPECTED_EXPRESSION_TYPE, expression] ?: return
val actualType = expression.getType(context) ?: return
if (actualType.isDynamic() && !expectedType.isDynamic() && !expectedType.isNullableAny() &&
!TypeUtils.noExpectedType(expectedType)
) {
holder.registerProblem(
expression,
KotlinBundle.message("implicit.unsafe.cast.from.dynamic.to.0", expectedType),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
CastExplicitlyFix(expectedType)
)
}
})
}
private class CastExplicitlyFix(private val type: KotlinType) : LocalQuickFix {
override fun getName() = KotlinBundle.message("cast.explicitly.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expression = descriptor.psiElement as? KtExpression ?: return
val typeName = type.constructor.declarationDescriptor?.name ?: return
val pattern = if (type.isMarkedNullable) "$0 as? $1" else "$0 as $1"
val newExpression = KtPsiFactory(expression).createExpressionByPattern(pattern, expression, typeName)
expression.replace(newExpression)
}
} | apache-2.0 | 95f7b64daae0e03faf2b88784913a3fc | 48.796296 | 158 | 0.74256 | 5.024299 | false | false | false | false |
nadraliev/DsrWeatherApp | app/src/main/java/soutvoid/com/DsrWeatherApp/ui/util/Extensions.kt | 1 | 8419 | package soutvoid.com.DsrWeatherApp.ui.util
import android.animation.Animator
import android.annotation.TargetApi
import android.content.Context
import android.content.SharedPreferences
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.support.annotation.StringRes
import android.support.v4.app.FragmentManager
import android.support.v4.content.ContextCompat
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewAnimationUtils
import android.view.ViewGroup
import io.realm.*
import soutvoid.com.DsrWeatherApp.R
import soutvoid.com.DsrWeatherApp.domain.triggers.SavedTrigger
import soutvoid.com.DsrWeatherApp.domain.triggers.condition.ConditionExpression
import soutvoid.com.DsrWeatherApp.domain.triggers.condition.ConditionName
import soutvoid.com.DsrWeatherApp.ui.receivers.RequestCode
import soutvoid.com.DsrWeatherApp.ui.screen.main.settings.SettingsFragment
import io.realm.RealmObject.deleteFromRealm
import io.realm.RealmObject
import io.realm.RealmList
import soutvoid.com.DsrWeatherApp.domain.location.SavedLocation
import java.math.BigInteger
import java.security.SecureRandom
import java.util.*
fun ViewGroup.inflate(resId: Int): View {
return LayoutInflater.from(context).inflate(resId, this, false)
}
/**
* позволяет получить цвет из текущей темы
* @param [attr] имя аттрибута из темы
* @return цвет, полученный из темы
*/
fun Context.getThemeColor(attr: Int): Int {
val typedValue: TypedValue = TypedValue()
this.theme.resolveAttribute(attr, typedValue, true)
return typedValue.data
}
fun Context.getThemedDrawable(attr: Int): Drawable {
val typedValue = TypedValue()
theme.resolveAttribute(attr, typedValue, true)
return ContextCompat.getDrawable(this, typedValue.data)
}
/**
* @return общий SharedPreferences для любого контекста
*/
fun Context.getDefaultPreferences(): SharedPreferences {
return this.getSharedPreferences(SettingsFragment.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
}
/**
* чтобы добавить тему, напиши стиль в res-main styles, добавь записи в res-settings strings для экрана настроек, добавь опцию сюда
* @return id текущей темы
*/
fun SharedPreferences.getPreferredThemeId(): Int {
var themeNumber = getString(SettingsFragment.SHARED_PREFERENCES_THEME, "0").toInt()
val preferDark = isDarkThemePreferred()
if (preferDark)
themeNumber += 100 //dark themes "zone" is 1xx
when(themeNumber) {
0 -> return R.style.AppTheme_Light
1 -> return R.style.AppTheme_PurpleLight
2 -> return R.style.AppTheme_GreenLight
3 -> return R.style.AppTheme_RedLight
4 -> return R.style.AppTheme_BlueLight
5 -> return R.style.AppTheme_PinkLight
6 -> return R.style.AppTheme_DeepPurpleLight
7 -> return R.style.AppTheme_CyanLight
8 -> return R.style.AppTheme_TealLight
9 -> return R.style.AppTheme_YellowLight
10 -> return R.style.AppTheme_OrangeLight
11 -> return R.style.AppTheme_BrownLight
100 -> return R.style.AppTheme_Dark
101 -> return R.style.AppTheme_PurpleDark
102 -> return R.style.AppTheme_GreenDark
103 -> return R.style.AppTheme_RedDark
104 -> return R.style.AppTheme_BlueDark
105 -> return R.style.AppTheme_PinkDark
106 -> return R.style.AppTheme_Deep_purpleDark
107 -> return R.style.AppTheme_CyanDark
108 -> return R.style.AppTheme_TealDark
109 -> return R.style.AppTheme_YellowDark
110 -> return R.style.AppTheme_OrangeDark
111 -> return R.style.AppTheme_BrownDark
else -> return R.style.AppTheme_Light
}
}
fun SharedPreferences.isDarkThemePreferred(): Boolean {
return getBoolean(SettingsFragment.SHARED_PREFERENCES_DARK_THEME, false)
}
fun View.dpToPx(dp: Double): Double {
val scale = context.resources.displayMetrics.density
return dp * scale + 0.5f
}
fun View.spToPx(sp: Float): Int {
val px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.resources.displayMetrics).toInt()
return px
}
@TargetApi(21)
fun View.createFullScreenCircularReveal(startX: Int, startY: Int): Animator {
return ViewAnimationUtils.createCircularReveal(
this,
startX,
startY,
0f,
maxOf(this.measuredHeight, this.measuredWidth).toFloat()
)
}
fun ConditionName.getNiceNameStringId(): Int {
when(this) {
ConditionName.temp -> return R.string.temperature
ConditionName.humidity -> return R.string.humidity
ConditionName.clouds -> return R.string.clouds
ConditionName.pressure -> return R.string.pressure
ConditionName.wind_direction -> return R.string.wind_direction
ConditionName.wind_speed -> return R.string.wind_speed
}
}
fun ConditionExpression.getNiceStringId(): Int {
when(this) {
ConditionExpression.gt -> return R.string.more_than
ConditionExpression.lt -> return R.string.less_than
else -> return R.string.equals
}
}
/**
* возвращает @param [alt], если this == null
*/
fun <T> T?.ifNotNullOr(alt: T): T {
if (this == null)
return alt
else
return this
}
fun <T> T?.ifNotNullOr(alt: () -> T): T {
if (this == null)
return alt()
else
return this
}
fun <T> List<T>.plusElementFront(element: T) : List<T> {
val newList = this.toMutableList()
newList.add(0, element)
return newList.toList()
}
fun <T> realmListOf(elements: Iterable<T>): RealmList<T> where T: RealmModel{
val list = RealmList<T>()
list.addAll(elements)
return list
}
/**
* получить сохраненные в бд триггеры по списку id
*/
fun getSavedTriggers(triggersIds: IntArray = intArrayOf()): List<SavedTrigger> {
val realm = Realm.getDefaultInstance()
var realmResults: RealmResults<SavedTrigger>?
var list = emptyList<SavedTrigger>()
if (triggersIds.isEmpty())
realmResults = realm.where(SavedTrigger::class.java).findAll()
else
realmResults = realm.where(SavedTrigger::class.java).`in`("id", triggersIds.toTypedArray()).findAll()
if (realmResults != null)
list = realm.copyFromRealm(realmResults)
realm.close()
return list
}
/**
* сохранить внесенные изменения в бд
*/
private fun updateDbTriggers(triggers: List<SavedTrigger>) {
val realm = Realm.getDefaultInstance()
realm.executeTransaction { it.copyToRealmOrUpdate(triggers) }
realm.close()
}
fun getNewRequestCode(): Int {
val realm = Realm.getDefaultInstance()
val requestCode = RequestCode()
realm.executeTransaction { it.copyToRealm(requestCode) }
realm.close()
return requestCode.value
}
fun getAllRequestCodes(): List<Int> {
val realm = Realm.getDefaultInstance()
val realmResults = realm.where(RequestCode::class.java).findAll()
var results = emptyList<Int>()
realmResults?.let { results = realm.copyFromRealm(realmResults).map { it.value } }
realm.close()
return results
}
fun deleteAllRequestCodes() {
val realm = Realm.getDefaultInstance()
realm.executeTransaction { realm.where(RequestCode::class.java).findAll().deleteAllFromRealm() }
realm.close()
}
fun getAllSavedLocations(): List<SavedLocation> {
val realm = Realm.getDefaultInstance()
val realmResults = realm.where(SavedLocation::class.java).findAll()
var results: List<SavedLocation> = emptyList()
realmResults?.let { results = realm.copyFromRealm(realmResults) }
realm.close()
return results
}
fun getRandomString(): String {
val secureRandom = SecureRandom()
return BigInteger(130, secureRandom).toString(32)
}
fun FragmentManager.clearBackStack() {
kotlin.repeat(backStackEntryCount) {popBackStack()}
}
fun secondsToHours(seconds: Long): Long =
seconds / 60 / 60
fun secondsToDays(seconds: Long): Long =
secondsToHours(seconds) / 24
fun getHourOfDay(seconds: Long): Int {
val calendar = Calendar.getInstance()
calendar.timeInMillis = seconds * 1000
return calendar.get(Calendar.HOUR_OF_DAY)
}
| apache-2.0 | a291c5d3c5329c68cdd9931c7aa3269a | 31.114173 | 131 | 0.716072 | 4.040119 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceGuardClauseWithFunctionCallInspection.kt | 2 | 8225 | // 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.inspections
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.idea.util.textRangeIn
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.parentOrNull
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ReplaceGuardClauseWithFunctionCallInspection : AbstractApplicabilityBasedInspection<KtIfExpression>(
KtIfExpression::class.java
) {
companion object {
private const val ILLEGAL_STATE_EXCEPTION = "IllegalStateException"
private const val ILLEGAL_ARGUMENT_EXCEPTION = "IllegalArgumentException"
}
private enum class KotlinFunction(val functionName: String) {
CHECK("check"), CHECK_NOT_NULL("checkNotNull"), REQUIRE("require"), REQUIRE_NOT_NULL("requireNotNull");
val fqName: String
get() = "kotlin.$functionName"
}
override fun inspectionText(element: KtIfExpression) = KotlinBundle.message("replace.guard.clause.with.kotlin.s.function.call")
override val defaultFixText get() = KotlinBundle.message("replace.with.kotlin.s.function.call")
override fun fixText(element: KtIfExpression) =
element.getKotlinFunction()?.let { KotlinBundle.message("replace.with.0.call", it.functionName) } ?: defaultFixText
override fun inspectionHighlightRangeInElement(element: KtIfExpression) = element.ifKeyword.textRangeIn(element)
override fun isApplicable(element: KtIfExpression): Boolean {
val languageVersionSettings = element.languageVersionSettings
if (!languageVersionSettings.supportsFeature(LanguageFeature.UseReturnsEffect)) return false
if (element.condition == null) return false
val call = element.getCallExpression() ?: return false
val calleeText = call.calleeExpression?.text ?: return false
val valueArguments = call.valueArguments
if (valueArguments.size > 1) return false
if (calleeText != ILLEGAL_STATE_EXCEPTION && calleeText != ILLEGAL_ARGUMENT_EXCEPTION) return false
val context = call.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
val argumentType = valueArguments.firstOrNull()?.getArgumentExpression()?.getType(context)
if (argumentType != null && !KotlinBuiltIns.isStringOrNullableString(argumentType)) return false
if (element.isUsedAsExpression(context)) return false
val fqName = call.getResolvedCall(context)?.resultingDescriptor?.fqNameSafe?.parentOrNull()
return fqName == FqName("kotlin.$calleeText") || fqName == FqName("java.lang.$calleeText")
}
override fun applyTo(element: KtIfExpression, project: Project, editor: Editor?) {
val condition = element.condition ?: return
val call = element.getCallExpression() ?: return
val argument = call.valueArguments.firstOrNull()?.getArgumentExpression()
val commentSaver = CommentSaver(element)
val psiFactory = KtPsiFactory(element)
val replaced = when (val kotlinFunction = element.getKotlinFunction(call)) {
KotlinFunction.CHECK, KotlinFunction.REQUIRE -> {
val (excl, newCondition) = if (condition is KtPrefixExpression && condition.operationToken == KtTokens.EXCL) {
"" to (condition.baseExpression ?: return)
} else {
"!" to condition
}
val newExpression = if (argument == null) {
psiFactory.createExpressionByPattern("${kotlinFunction.fqName}($excl$0)", newCondition)
} else {
psiFactory.createExpressionByPattern("${kotlinFunction.fqName}($excl$0) { $1 }", newCondition, argument)
}
val replaced = element.replaceWith(newExpression, psiFactory)
val newCall = (replaced as? KtDotQualifiedExpression)?.callExpression
val negatedExpression = newCall?.valueArguments?.firstOrNull()?.getArgumentExpression() as? KtPrefixExpression
if (negatedExpression != null) {
SimplifyNegatedBinaryExpressionInspection.simplifyNegatedBinaryExpressionIfNeeded(negatedExpression)
}
replaced
}
KotlinFunction.CHECK_NOT_NULL, KotlinFunction.REQUIRE_NOT_NULL -> {
val nullCheckedExpression = condition.notNullCheckExpression() ?: return
val newExpression = if (argument == null) {
psiFactory.createExpressionByPattern("${kotlinFunction.fqName}($0)", nullCheckedExpression)
} else {
psiFactory.createExpressionByPattern("${kotlinFunction.fqName}($0) { $1 }", nullCheckedExpression, argument)
}
element.replaceWith(newExpression, psiFactory)
}
else -> return
}
commentSaver.restore(replaced)
editor?.caretModel?.moveToOffset(replaced.startOffset)
ShortenReferences.DEFAULT.process(replaced)
}
private fun KtIfExpression.replaceWith(newExpression: KtExpression, psiFactory: KtPsiFactory): KtExpression {
val parent = parent
val elseBranch = `else`
return if (elseBranch != null) {
val added = parent.addBefore(newExpression, this) as KtExpression
parent.addBefore(psiFactory.createNewLine(), this)
replaceWithBranch(elseBranch, isUsedAsExpression = false, keepBraces = false)
added
} else {
replaced(newExpression)
}
}
private fun KtIfExpression.getCallExpression(): KtCallExpression? {
val throwExpression = this.then?.let {
it as? KtThrowExpression ?: (it as? KtBlockExpression)?.statements?.singleOrNull() as? KtThrowExpression
} ?: return null
return throwExpression.thrownExpression?.let {
it as? KtCallExpression ?: (it as? KtQualifiedExpression)?.callExpression
}
}
private fun KtIfExpression.getKotlinFunction(call: KtCallExpression? = getCallExpression()): KotlinFunction? {
val calleeText = call?.calleeExpression?.text ?: return null
val isNotNullCheck = condition.notNullCheckExpression() != null
return when (calleeText) {
ILLEGAL_STATE_EXCEPTION -> if (isNotNullCheck) KotlinFunction.CHECK_NOT_NULL else KotlinFunction.CHECK
ILLEGAL_ARGUMENT_EXCEPTION -> if (isNotNullCheck) KotlinFunction.REQUIRE_NOT_NULL else KotlinFunction.REQUIRE
else -> null
}
}
private fun KtExpression?.notNullCheckExpression(): KtExpression? {
if (this == null) return null
if (this !is KtBinaryExpression) return null
if (this.operationToken != KtTokens.EQEQ) return null
val left = this.left ?: return null
val right = this.right ?: return null
return when {
right.isNullConstant() -> left
left.isNullConstant() -> right
else -> null
}
}
private fun KtExpression.isNullConstant(): Boolean {
return (this as? KtConstantExpression)?.text == KtTokens.NULL_KEYWORD.value
}
}
| apache-2.0 | a1a7453b0a87d3d7331c534c0966ac2d | 50.72956 | 158 | 0.696413 | 5.461487 | false | false | false | false |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/ui/feed/FeedFragment.kt | 1 | 10540 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.ui.feed
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.doOnLayout
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.google.common.collect.ImmutableMap
import com.google.samples.apps.iosched.databinding.FragmentFeedBinding
import com.google.samples.apps.iosched.model.SessionId
import com.google.samples.apps.iosched.shared.analytics.AnalyticsHelper
import com.google.samples.apps.iosched.ui.MainActivityViewModel
import com.google.samples.apps.iosched.ui.MainNavigationFragment
import com.google.samples.apps.iosched.ui.feed.FeedNavigationAction.NavigateAction
import com.google.samples.apps.iosched.ui.feed.FeedNavigationAction.NavigateToScheduleAction
import com.google.samples.apps.iosched.ui.feed.FeedNavigationAction.NavigateToSession
import com.google.samples.apps.iosched.ui.feed.FeedNavigationAction.OpenLiveStreamAction
import com.google.samples.apps.iosched.ui.feed.FeedNavigationAction.OpenSignInDialogAction
import com.google.samples.apps.iosched.ui.messages.SnackbarMessageManager
import com.google.samples.apps.iosched.ui.messages.setupSnackbarManager
import com.google.samples.apps.iosched.ui.signin.SignInDialogFragment
import com.google.samples.apps.iosched.ui.signin.setupProfileMenuItem
import com.google.samples.apps.iosched.util.doOnApplyWindowInsets
import com.google.samples.apps.iosched.util.launchAndRepeatWithViewLifecycle
import com.google.samples.apps.iosched.util.openWebsiteUrl
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import javax.inject.Inject
@AndroidEntryPoint
class FeedFragment : MainNavigationFragment() {
companion object {
private const val DIALOG_NEED_TO_SIGN_IN = "dialog_need_to_sign_in"
private const val BUNDLE_KEY_SESSIONS_LAYOUT_MANAGER_STATE = "sessions_layout_manager"
}
@Inject
lateinit var snackbarMessageManager: SnackbarMessageManager
@Inject
lateinit var analyticsHelper: AnalyticsHelper
private val model: FeedViewModel by viewModels()
private val mainActivityViewModel: MainActivityViewModel by activityViewModels()
private lateinit var binding: FragmentFeedBinding
private var adapter: FeedAdapter? = null
private lateinit var sessionsViewBinder: FeedSessionsViewBinder
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentFeedBinding.inflate(
inflater, container, false
).apply {
lifecycleOwner = viewLifecycleOwner
viewModel = model
}
return binding.root
}
override fun onSaveInstanceState(outState: Bundle) {
if (::sessionsViewBinder.isInitialized) {
outState.putParcelable(
BUNDLE_KEY_SESSIONS_LAYOUT_MANAGER_STATE,
sessionsViewBinder.recyclerViewManagerState
)
}
super.onSaveInstanceState(outState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
analyticsHelper.sendScreenView("Home", requireActivity())
binding.toolbar.setupProfileMenuItem(mainActivityViewModel, viewLifecycleOwner)
binding.root.doOnApplyWindowInsets { _, insets, _ ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
binding.statusBar.run {
layoutParams.height = systemBars.top
isVisible = layoutParams.height > 0
requestLayout()
}
}
if (adapter == null) {
// Initialising sessionsViewBinder here to handle config change.
sessionsViewBinder =
FeedSessionsViewBinder(
model,
savedInstanceState?.getParcelable(
BUNDLE_KEY_SESSIONS_LAYOUT_MANAGER_STATE
)
)
}
binding.recyclerView.doOnApplyWindowInsets { v, insets, padding ->
val systemInsets = insets.getInsets(
WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime()
)
v.updatePadding(bottom = padding.bottom + systemInsets.bottom)
}
binding.snackbar.doOnApplyWindowInsets { v, insets, padding ->
val systemInsets = insets.getInsets(
WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime()
)
v.updatePadding(bottom = padding.bottom + systemInsets.bottom)
}
setupSnackbarManager(snackbarMessageManager, binding.snackbar)
// Observe feed
launchAndRepeatWithViewLifecycle {
model.feed.collect {
showFeedItems(binding.recyclerView, it)
}
}
// Observe navigation events
launchAndRepeatWithViewLifecycle {
model.navigationActions.collect { action ->
when (action) {
is NavigateAction -> findNavController().navigate(action.directions)
NavigateToScheduleAction ->
findNavController().navigate(FeedFragmentDirections.toSchedule())
is NavigateToSession -> openSessionDetail(action.sessionId)
is OpenLiveStreamAction -> openLiveStreamUrl(action.url)
OpenSignInDialogAction -> openSignInDialog()
}
}
}
}
private fun openSessionDetail(id: SessionId) {
// TODO support opening a session detail
// findNavController().navigate(toSessionDetail(id))
}
private fun showFeedItems(recyclerView: RecyclerView, list: List<Any>?) {
if (adapter == null) {
val sectionHeaderViewBinder = FeedSectionHeaderViewBinder()
val countdownViewBinder = CountdownViewBinder()
val momentViewBinder = MomentViewBinder(
eventListener = model,
userInfo = model.userInfo,
theme = model.theme
)
val sessionsViewBinder = FeedSessionsViewBinder(model)
val feedAnnouncementsHeaderViewBinder =
AnnouncementsHeaderViewBinder(this, model)
val announcementViewBinder = AnnouncementViewBinder(model.timeZoneId, this)
val announcementsEmptyViewBinder = AnnouncementsEmptyViewBinder()
val announcementsLoadingViewBinder = AnnouncementsLoadingViewBinder()
val feedSustainabilitySectionViewBinder = FeedSustainabilitySectionViewBinder()
val feedSocialChannelsSectionViewBinder = FeedSocialChannelsSectionViewBinder()
@Suppress("UNCHECKED_CAST")
val viewBinders = ImmutableMap.builder<FeedItemClass, FeedItemBinder>()
.put(
sectionHeaderViewBinder.modelClass,
sectionHeaderViewBinder as FeedItemBinder
)
.put(
countdownViewBinder.modelClass,
countdownViewBinder as FeedItemBinder
)
.put(
momentViewBinder.modelClass,
momentViewBinder as FeedItemBinder
)
.put(
sessionsViewBinder.modelClass,
sessionsViewBinder as FeedItemBinder
)
.put(
feedAnnouncementsHeaderViewBinder.modelClass,
feedAnnouncementsHeaderViewBinder as FeedItemBinder
)
.put(
announcementViewBinder.modelClass,
announcementViewBinder as FeedItemBinder
)
.put(
announcementsEmptyViewBinder.modelClass,
announcementsEmptyViewBinder as FeedItemBinder
)
.put(
announcementsLoadingViewBinder.modelClass,
announcementsLoadingViewBinder as FeedItemBinder
)
.put(
feedSustainabilitySectionViewBinder.modelClass,
feedSustainabilitySectionViewBinder as FeedItemBinder
)
.put(
feedSocialChannelsSectionViewBinder.modelClass,
feedSocialChannelsSectionViewBinder as FeedItemBinder
)
.build()
adapter = FeedAdapter(viewBinders)
}
if (recyclerView.adapter == null) {
recyclerView.adapter = adapter
}
(recyclerView.adapter as FeedAdapter).submitList(list ?: emptyList())
// After submitting the list to the adapter, the recycler view starts measuring and drawing
// so let's wait for the layout to be drawn before reporting fully drawn.
binding.recyclerView.doOnLayout {
// reportFullyDrawn() prints `I/ActivityTaskManager: Fully drawn {activity} {time}`
// to logcat. The framework ensures that the statement is printed only once for the
// activity, so there is no need to add dedupping logic to the app.
activity?.reportFullyDrawn()
}
}
private fun openSignInDialog() {
SignInDialogFragment().show(
requireActivity().supportFragmentManager, DIALOG_NEED_TO_SIGN_IN
)
}
private fun openLiveStreamUrl(url: String) {
openWebsiteUrl(requireContext(), url)
}
}
| apache-2.0 | 6c7d29edcfbd27e2912481a1916a8d87 | 40.496063 | 99 | 0.661954 | 5.685005 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/gradle/gradle/src/org/jetbrains/kotlin/idea/gradle/statistics/KotlinGradleFUSLogger.kt | 1 | 3911 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradle.statistics
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.ProjectPostStartupActivity
import kotlinx.coroutines.delay
import org.jetbrains.kotlin.statistics.BuildSessionLogger
import org.jetbrains.kotlin.statistics.BuildSessionLogger.Companion.STATISTICS_FOLDER_NAME
import org.jetbrains.kotlin.statistics.fileloggers.MetricsContainer
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.io.path.Path
import kotlin.io.path.exists
import kotlin.time.Duration.Companion.minutes
class KotlinGradleFUSLogger : ProjectPostStartupActivity {
override suspend fun execute(project: Project) {
while (true) {
delay(EXECUTION_DELAY_MIN.minutes)
reportStatistics()
}
}
companion object {
/**
* Maximum amount of directories which were reported as gradle user dirs
* These directories should be monitored for reported gradle statistics.
*/
private const val MAXIMUM_USER_DIRS = 10
/**
* Delay between sequential checks of gradle statistics
*/
const val EXECUTION_DELAY_MIN = 60L
/**
* Property name used for persisting gradle user dirs
*/
private const val GRADLE_USER_DIRS_PROPERTY_NAME = "kotlin-gradle-user-dirs"
private val isRunning = AtomicBoolean(false)
fun reportStatistics() {
if (isRunning.compareAndSet(false, true)) {
try {
for (gradleUserHome in gradleUserDirs) {
BuildSessionLogger.listProfileFiles(File(gradleUserHome, STATISTICS_FOLDER_NAME))?.forEach { statisticFile ->
var fileWasRead = true
try {
var previousEvent: MetricsContainer? = null
fileWasRead = MetricsContainer.readFromFile(statisticFile) { metricContainer ->
KotlinGradleFUSCollector.reportMetrics(metricContainer, previousEvent)
previousEvent = metricContainer
}
} catch (e: Exception) {
Logger.getInstance(KotlinGradleFUSCollector::class.java)
.info("Failed to process file ${statisticFile.absolutePath}: ${e.message}", e)
} finally {
if (fileWasRead && !statisticFile.delete()) {
Logger.getInstance(KotlinGradleFUSCollector::class.java)
.warn("[FUS] Failed to delete file ${statisticFile.absolutePath}")
}
}
}
}
} finally {
isRunning.set(false)
}
}
}
private var gradleUserDirs: List<String>
set(value) = PropertiesComponent.getInstance().setList(
GRADLE_USER_DIRS_PROPERTY_NAME, value
)
get() = PropertiesComponent.getInstance().getList(GRADLE_USER_DIRS_PROPERTY_NAME) ?: emptyList()
fun populateGradleUserDir(path: String) {
val currentState = gradleUserDirs
if (path in currentState) return
val result = ArrayList<String>()
result.add(path)
result.addAll(currentState)
gradleUserDirs = result.filter { filePath -> Path(filePath).exists() }.take(MAXIMUM_USER_DIRS)
}
}
}
| apache-2.0 | 516a7193c9a3d038ac2b5bf0b52cef6c | 41.053763 | 133 | 0.587318 | 5.619253 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/checkin/GitCommitAndPushExecutor.kt | 1 | 1646 | // 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.checkin
import com.intellij.dvcs.commit.getCommitAndPushActionName
import com.intellij.dvcs.ui.DvcsBundle
import com.intellij.openapi.components.Service
import com.intellij.openapi.util.Key
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.changes.CommitExecutorWithRichDescription
import com.intellij.openapi.vcs.changes.CommitSession
import com.intellij.vcs.commit.CommitWorkflowHandlerState
import com.intellij.vcs.commit.commitProperty
import org.jetbrains.annotations.Nls
private val IS_PUSH_AFTER_COMMIT_KEY = Key.create<Boolean>("Git.Commit.IsPushAfterCommit")
internal var CommitContext.isPushAfterCommit: Boolean by commitProperty(IS_PUSH_AFTER_COMMIT_KEY)
@Service(Service.Level.PROJECT)
internal class GitCommitAndPushExecutor : CommitExecutorWithRichDescription {
@Nls
override fun getActionText(): String = DvcsBundle.message("action.commit.and.push.text")
override fun getText(state: CommitWorkflowHandlerState): String {
return getCommitAndPushActionName(state)
}
override fun useDefaultAction(): Boolean = false
override fun requiresSyncCommitChecks(): Boolean = true
override fun getId(): String = ID
override fun supportsPartialCommit(): Boolean = true
override fun createCommitSession(commitContext: CommitContext): CommitSession {
commitContext.isPushAfterCommit = true
return CommitSession.VCS_COMMIT
}
companion object {
internal const val ID = "Git.Commit.And.Push.Executor"
}
}
| apache-2.0 | 70e0a96013b589e54bde8f976850ddff | 37.27907 | 140 | 0.808019 | 4.32021 | false | false | false | false |
GunoH/intellij-community | platform/statistics/src/com/intellij/internal/statistic/eventLog/events/EventFields.kt | 2 | 17546 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.statistic.eventLog.events
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.internal.statistic.StructuredIdeActivity
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule
import com.intellij.internal.statistic.service.fus.collectors.FeatureUsageCollectorExtension
import com.intellij.internal.statistic.utils.PluginInfo
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.internal.statistic.utils.getPluginInfoByDescriptor
import com.intellij.lang.Language
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.util.Version
import org.jetbrains.annotations.NonNls
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import org.intellij.lang.annotations.Language as InjectedLanguage
@Suppress("FunctionName")
object EventFields {
/**
* Creates a field that will be validated by global regexp rule
* @param name name of the field
* @param regexpRef reference to global regexp, e.g "integer" for "{regexp#integer}"
*/
@JvmStatic
fun StringValidatedByRegexp(@NonNls name: String, @NonNls regexpRef: String): StringEventField {
return StringEventField.ValidatedByRegexp(name, regexpRef)
}
/**
* Creates a field that will be validated by global enum rule
* @param name name of the field
* @param enumRef reference to global enum, e.g "os" for "{enum#os}"
*/
@JvmStatic
fun StringValidatedByEnum(@NonNls name: String, @NonNls enumRef: String): StringEventField {
return StringEventField.ValidatedByEnum(name, enumRef)
}
/**
* Creates a field that will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule]
* @param name name of the field
* @param customRuleId ruleId that is accepted by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule.acceptRuleId],
* e.g "class_name" for "{util#class_name}"
*/
@kotlin.Deprecated("Please use EventFields.StringValidatedByCustomRule(String, Class<out CustomValidationRule>)",
ReplaceWith("EventFields.StringValidatedByCustomRule(name, customValidationRule)"))
@JvmStatic
fun StringValidatedByCustomRule(@NonNls name: String, @NonNls customRuleId: String): StringEventField {
return StringEventField.ValidatedByCustomRule(name, customRuleId)
}
/**
* Creates a field that will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule]
* @param name name of the field
* @param customValidationRule inheritor of [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule],
*/
@JvmStatic
fun StringValidatedByCustomRule(@NonNls name: String, customValidationRule: Class<out CustomValidationRule>): StringEventField =
StringEventField.ValidatedByCustomValidationRule(name, customValidationRule)
/**
* Creates a field that will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule].
* @param name name of the field
*/
inline fun <reified T : CustomValidationRule> StringValidatedByCustomRule(@NonNls name: String): StringEventField =
StringValidatedByCustomRule(name, T::class.java)
/**
* Creates a field that allows only a specific list of values
* @param name name of the field
* @param allowedValues list of allowed values, e.g [ "bool", "int", "float"]
*/
@JvmStatic
fun String(@NonNls name: String, allowedValues: List<String>): StringEventField =
StringEventField.ValidatedByAllowedValues(name, allowedValues)
@JvmStatic
fun Int(@NonNls name: String): IntEventField = IntEventField(name)
/**
* Creates an int field that will be validated by regexp rule
* @param name name of the field
* @param regexp regular expression, e.g "-?[0-9]{1,3}"
* Please choose regexp carefully to avoid reporting any sensitive data.
*/
@JvmStatic
fun RegexpInt(@NonNls name: String, @InjectedLanguage("RegExp") @NonNls regexp: String): RegexpIntEventField =
RegexpIntEventField(name, regexp)
/**
* Rounds integer value to the next power of two.
* Use it to anonymize sensitive information like the number of files in a project.
* @see com.intellij.internal.statistic.utils.StatisticsUtil.roundToPowerOfTwo
*/
@JvmStatic
fun RoundedInt(@NonNls name: String): RoundedIntEventField = RoundedIntEventField(name)
@JvmStatic
fun Long(@NonNls name: String): LongEventField = LongEventField(name)
/**
* Rounds long value to the next power of two.
* Use it to anonymize sensitive information like the number of files in a project.
* @see com.intellij.internal.statistic.utils.StatisticsUtil.roundToPowerOfTwo
*/
@JvmStatic
fun RoundedLong(@NonNls name: String): RoundedLongEventField = RoundedLongEventField(name)
@JvmStatic
fun Float(@NonNls name: String): FloatEventField = FloatEventField(name)
@JvmStatic
fun Double(@NonNls name: String): DoubleEventField = DoubleEventField(name)
@JvmStatic
fun Boolean(@NonNls name: String): BooleanEventField = BooleanEventField(name)
@JvmStatic
fun Class(@NonNls name: String): ClassEventField = ClassEventField(name)
val defaultEnumTransform: (Any) -> String = { it.toString() }
@JvmStatic
@JvmOverloads
fun <T : Enum<*>> Enum(@NonNls name: String, enumClass: Class<T>, transform: (T) -> String = defaultEnumTransform): EnumEventField<T> =
EnumEventField(name, enumClass, transform)
inline fun <reified T : Enum<*>> Enum(@NonNls name: String, noinline transform: (T) -> String = defaultEnumTransform): EnumEventField<T> =
EnumEventField(name, T::class.java, transform)
/**
* Creates a field for a list, each element of which will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule]
* @param name name of the field
* @param customRuleId ruleId that is accepted by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule.acceptRuleId],
* e.g "class_name" for "{util#class_name}"
*/
@kotlin.Deprecated("Please use EventFields.StringListValidatedByCustomRule(String, Class<out CustomValidationRule>)",
ReplaceWith("EventFields.StringListValidatedByCustomRule(name, customValidationRule)"))
@JvmStatic
fun StringListValidatedByCustomRule(@NonNls name: String, @NonNls customRuleId: String): StringListEventField =
StringListEventField.ValidatedByCustomRule(name, customRuleId)
/**
* Creates a field for a list, each element of which will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule]
* @param name name of the field
* @param customValidationRule inheritor of [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule]
*/
@JvmStatic
fun StringListValidatedByCustomRule(@NonNls name: String, customValidationRule: Class<out CustomValidationRule>): StringListEventField =
StringListEventField.ValidatedByCustomValidationRule(name, customValidationRule)
/**
* Creates a field for a list, each element of which will be validated by [com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule]
* @param name name of the field
*/
inline fun <reified T : CustomValidationRule> StringListValidatedByCustomRule(@NonNls name: String): StringListEventField =
StringListValidatedByCustomRule(name, T::class.java)
/**
* Creates a field for a list, each element of which will be validated by global enum rule
* @param name name of the field
* @param enumRef reference to global enum, e.g "os" for "{enum#os}"
*/
@JvmStatic
fun StringListValidatedByEnum(@NonNls name: String, @NonNls enumRef: String): StringListEventField =
StringListEventField.ValidatedByEnum(name, enumRef)
/**
* Creates a field for a list, each element of which will be validated by global regexp
* @param name name of the field
* @param regexpRef reference to global regexp, e.g "integer" for "{regexp#integer}"
*/
@JvmStatic
fun StringListValidatedByRegexp(@NonNls name: String, @NonNls regexpRef: String): StringListEventField =
StringListEventField.ValidatedByRegexp(name, regexpRef)
/**
* Creates a field for a list in which only a specific values are allowed
* @param name name of the field
* @param allowedValues list of allowed values, e.g [ "bool", "int", "float"]
*/
@JvmStatic
fun StringList(@NonNls name: String, allowedValues: List<String>): StringListEventField =
StringListEventField.ValidatedByAllowedValues(name, allowedValues)
@JvmStatic
fun LongList(@NonNls name: String): LongListEventField = LongListEventField(name)
@JvmStatic
fun IntList(@NonNls name: String): IntListEventField = IntListEventField(name)
/**
* Please choose regexp carefully to avoid reporting any sensitive data.
*/
@JvmStatic
fun StringValidatedByInlineRegexp(@NonNls name: String, @InjectedLanguage("RegExp") @NonNls regexp: String): StringEventField =
StringEventField.ValidatedByInlineRegexp(name, regexp)
/**
* Please choose regexp carefully to avoid reporting any sensitive data.
*/
@JvmStatic
fun StringListValidatedByInlineRegexp(@NonNls name: String, @InjectedLanguage("RegExp") @NonNls regexp: String): StringListEventField =
StringListEventField.ValidatedByInlineRegexp(name, regexp)
@JvmField
val InputEvent = object : PrimitiveEventField<FusInputEvent?>() {
override val name = "input_event"
override val validationRule: List<String>
get() = listOf("{util#shortcut}")
override fun addData(fuData: FeatureUsageData, value: FusInputEvent?) {
if (value != null) {
fuData.addInputEvent(value.inputEvent, value.place)
}
}
}
@JvmField
val InputEventByAnAction = object : PrimitiveEventField<AnActionEvent?>() {
override val name = "input_event"
override val validationRule: List<String>
get() = listOf("{util#shortcut}")
override fun addData(fuData: FeatureUsageData, value: AnActionEvent?) {
if (value != null) {
fuData.addInputEvent(value)
}
}
}
@JvmField
val InputEventByKeyEvent = object : PrimitiveEventField<KeyEvent?>() {
override val name = "input_event"
override val validationRule: List<String>
get() = listOf("{util#shortcut}")
override fun addData(fuData: FeatureUsageData, value: KeyEvent?) {
if (value != null) {
fuData.addInputEvent(value)
}
}
}
@JvmField
val InputEventByMouseEvent = object : PrimitiveEventField<MouseEvent?>() {
override val name = "input_event"
override val validationRule: List<String>
get() = listOf("{util#shortcut}")
override fun addData(fuData: FeatureUsageData, value: MouseEvent?) {
if (value != null) {
fuData.addInputEvent(value)
}
}
}
@JvmField
val ActionPlace = object : PrimitiveEventField<String?>() {
override val name: String = "place"
override val validationRule: List<String>
get() = listOf("{util#place}")
override fun addData(fuData: FeatureUsageData, value: String?) {
fuData.addPlace(value)
}
}
//will be replaced with ObjectEventField in the future
@JvmField
val PluginInfo = object : PrimitiveEventField<PluginInfo?>() {
override val name: String
get() = "plugin_type"
override val validationRule: List<String>
get() = listOf("plugin_info")
override fun addData(
fuData: FeatureUsageData,
value: PluginInfo?,
) {
fuData.addPluginInfo(value)
}
}
@JvmField
val PluginInfoByDescriptor = object : PrimitiveEventField<IdeaPluginDescriptor>() {
private val delegate
get() = PluginInfo
override val name: String
get() = delegate.name
override val validationRule: List<String>
get() = delegate.validationRule
override fun addData(
fuData: FeatureUsageData,
value: IdeaPluginDescriptor,
) {
delegate.addData(fuData, getPluginInfoByDescriptor(value))
}
}
//will be replaced with ObjectEventField in the future
@JvmField
val PluginInfoFromInstance = object : PrimitiveEventField<Any>() {
private val delegate
get() = PluginInfo
override val name: String
get() = delegate.name
override val validationRule: List<String>
get() = delegate.validationRule
override fun addData(
fuData: FeatureUsageData,
value: Any,
) {
delegate.addData(fuData, getPluginInfo(value::class.java))
}
}
@JvmField
val AnonymizedPath = object : PrimitiveEventField<String?>() {
override val validationRule: List<String>
get() = listOf("{regexp#hash}")
override val name = "file_path"
override fun addData(fuData: FeatureUsageData, value: String?) {
fuData.addAnonymizedPath(value)
}
}
@JvmField
val AnonymizedId = object : PrimitiveEventField<String?>() {
override val validationRule: List<String>
get() = listOf("{regexp#hash}")
override val name = "anonymous_id"
override fun addData(fuData: FeatureUsageData, value: String?) {
value?.let {
fuData.addAnonymizedId(value)
}
}
}
@JvmField
val CodeWithMeClientId = object : PrimitiveEventField<String?>() {
override val validationRule: List<String>
get() = listOf("{regexp#hash}")
override val name: String = "client_id"
override fun addData(fuData: FeatureUsageData, value: String?) {
fuData.addClientId(value)
}
}
@JvmField
val Language = object : PrimitiveEventField<Language?>() {
override val name = "lang"
override val validationRule: List<String>
get() = listOf("{util#lang}")
override fun addData(fuData: FeatureUsageData, value: Language?) {
fuData.addLanguage(value)
}
}
@JvmField
val LanguageById = object : PrimitiveEventField<String?>() {
override val name = "lang"
override val validationRule: List<String>
get() = listOf("{util#lang}")
override fun addData(fuData: FeatureUsageData, value: String?) {
fuData.addLanguage(value)
}
}
@JvmField
val FileType = object : PrimitiveEventField<FileType?>() {
override val name = "file_type"
override val validationRule: List<String>
get() = listOf("{util#file_type}")
override fun addData(fuData: FeatureUsageData, value: FileType?) {
value?.let {
val type = getPluginInfo(it.javaClass)
if (type.isSafeToReport()) {
fuData.addData("file_type", it.name)
}
else {
fuData.addData("file_type", "third.party")
}
}
}
}
@JvmField
val CurrentFile = object : PrimitiveEventField<Language?>() {
override val name = "current_file"
override val validationRule: List<String>
get() = listOf("{util#current_file}")
override fun addData(fuData: FeatureUsageData, value: Language?) {
fuData.addCurrentFile(value)
}
}
@JvmField
val Version = object : PrimitiveEventField<String?>() {
override val name: String = "version"
override val validationRule: List<String>
get() = listOf("{regexp#version}")
override fun addData(fuData: FeatureUsageData, value: String?) {
fuData.addVersionByString(value)
}
}
@JvmField
val VersionByObject = object : PrimitiveEventField<Version?>() {
override val name: String = "version"
override val validationRule: List<String>
get() = listOf("{regexp#version}")
override fun addData(fuData: FeatureUsageData, value: Version?) {
fuData.addVersion(value)
}
}
@JvmField
val Count = Int("count")
@JvmField
val Enabled = Boolean("enabled")
@JvmField
val DurationMs = LongEventField("duration_ms")
@JvmField
val Size = Int("size")
@JvmField
val IdeActivityIdField = object : PrimitiveEventField<StructuredIdeActivity>() {
override val name: String = "ide_activity_id"
override fun addData(fuData: FeatureUsageData, value: StructuredIdeActivity) {
fuData.addData(name, value.id)
}
override val validationRule: List<String>
get() = listOf("{regexp#integer}")
}
@JvmField
val TimeToShowMs = LongEventField("time_to_show")
@JvmField
val StartTime = LongEventField("start_time")
/**
* Logger merges successive events with identical group id, event id and event data fields except for fields listed here.
*
* @see com.intellij.internal.statistic.eventLog.StatisticsEventLoggerProvider.createEventsMergeStrategy
*/
@JvmField
val FieldsIgnoredByMerge: List<EventField<*>> = arrayListOf(StartTime)
@JvmStatic
fun createAdditionalDataField(groupId: String, eventId: String): ObjectEventField {
val additionalFields = mutableListOf<EventField<*>>()
for (ext in FeatureUsageCollectorExtension.EP_NAME.extensionsIfPointIsRegistered) {
if (ext.groupId == groupId && ext.eventId == eventId) {
for (field in ext.extensionFields) {
if (field != null) {
additionalFields.add(field)
}
}
}
}
return ObjectEventField("additional", *additionalFields.toTypedArray())
}
}
| apache-2.0 | cdd65f7556f8e20823110bb227cd370c | 34.590264 | 160 | 0.718112 | 4.682679 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInliner/ReplacementPerformer.kt | 1 | 12634 | // 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.codeInliner
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiTreeChangeAdapter
import com.intellij.psi.PsiTreeChangeEvent
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.intentions.ConvertToBlockBodyIntention
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange
import org.jetbrains.kotlin.psi.psiUtil.canPlaceAfterSimpleNameEntry
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
internal abstract class ReplacementPerformer<TElement : KtElement>(
protected val codeToInline: MutableCodeToInline,
protected var elementToBeReplaced: TElement
) {
protected val psiFactory = KtPsiFactory(elementToBeReplaced)
abstract fun doIt(postProcessing: (PsiChildRange) -> PsiChildRange): TElement?
}
internal abstract class AbstractSimpleReplacementPerformer<TElement : KtElement>(
codeToInline: MutableCodeToInline,
elementToBeReplaced: TElement
) : ReplacementPerformer<TElement>(codeToInline, elementToBeReplaced) {
protected abstract fun createDummyElement(mainExpression: KtExpression): TElement
protected open fun rangeToElement(range: PsiChildRange): TElement {
assert(range.first == range.last)
@Suppress("UNCHECKED_CAST")
return range.first as TElement
}
final override fun doIt(postProcessing: (PsiChildRange) -> PsiChildRange): TElement {
assert(codeToInline.statementsBefore.isEmpty())
val mainExpression = codeToInline.mainExpression ?: error("mainExpression mustn't be null")
val dummyElement = createDummyElement(mainExpression)
val replaced = elementToBeReplaced.replace(dummyElement)
codeToInline.performPostInsertionActions(listOf(replaced))
return rangeToElement(postProcessing(PsiChildRange.singleElement(replaced)))
}
}
internal class AnnotationEntryReplacementPerformer(
codeToInline: MutableCodeToInline,
elementToBeReplaced: KtAnnotationEntry
) : AbstractSimpleReplacementPerformer<KtAnnotationEntry>(codeToInline, elementToBeReplaced) {
private val useSiteTarget = elementToBeReplaced.useSiteTarget?.getAnnotationUseSiteTarget()
override fun createDummyElement(mainExpression: KtExpression): KtAnnotationEntry =
createByPattern("@Dummy($0)", mainExpression) { psiFactory.createAnnotationEntry(it) }
override fun rangeToElement(range: PsiChildRange): KtAnnotationEntry {
val useSiteTargetText = useSiteTarget?.renderName?.let { "$it:" } ?: ""
val isFileUseSiteTarget = useSiteTarget == AnnotationUseSiteTarget.FILE
assert(range.first == range.last)
assert(range.first is KtAnnotationEntry)
val annotationEntry = range.first as KtAnnotationEntry
val text = annotationEntry.valueArguments.single().getArgumentExpression()!!.text
val newAnnotationEntry = if (isFileUseSiteTarget)
psiFactory.createFileAnnotation(text)
else
psiFactory.createAnnotationEntry("@$useSiteTargetText$text")
return annotationEntry.replaced(newAnnotationEntry)
}
}
internal class SuperTypeCallEntryReplacementPerformer(
codeToInline: MutableCodeToInline,
elementToBeReplaced: KtSuperTypeCallEntry
) : AbstractSimpleReplacementPerformer<KtSuperTypeCallEntry>(codeToInline, elementToBeReplaced) {
override fun createDummyElement(mainExpression: KtExpression): KtSuperTypeCallEntry {
val text = if (mainExpression is KtCallElement && mainExpression.lambdaArguments.isNotEmpty()) {
callWithoutLambdaArguments(mainExpression)
} else {
mainExpression.text
}
return psiFactory.createSuperTypeCallEntry(text)
}
}
private fun callWithoutLambdaArguments(callExpression: KtCallElement): String {
val copy = callExpression.copy() as KtCallElement
val lambdaArgument = copy.lambdaArguments.first()
val argumentExpression = lambdaArgument.getArgumentExpression() ?: return callExpression.text
return lambdaArgument.moveInsideParenthesesAndReplaceWith(
replacement = argumentExpression,
functionLiteralArgumentName = null,
withNameCheck = false
).text ?: callExpression.text
}
internal class ExpressionReplacementPerformer(
codeToInline: MutableCodeToInline,
expressionToBeReplaced: KtExpression
) : ReplacementPerformer<KtExpression>(codeToInline, expressionToBeReplaced) {
private fun KtExpression.replacedWithStringTemplate(templateExpression: KtStringTemplateExpression): KtExpression? {
val parent = this.parent
return if (parent is KtStringTemplateEntryWithExpression
// Do not mix raw and non-raw templates
&& parent.parent.firstChild.text == templateExpression.firstChild.text
) {
val entriesToAdd = templateExpression.entries
val grandParentTemplateExpression = parent.parent as KtStringTemplateExpression
val result = if (entriesToAdd.isNotEmpty()) {
grandParentTemplateExpression.addRangeBefore(entriesToAdd.first(), entriesToAdd.last(), parent)
val lastNewEntry = parent.prevSibling
val nextElement = parent.nextSibling
if (lastNewEntry is KtSimpleNameStringTemplateEntry &&
lastNewEntry.expression != null &&
!canPlaceAfterSimpleNameEntry(nextElement)
) {
lastNewEntry.replace(KtPsiFactory(this).createBlockStringTemplateEntry(lastNewEntry.expression!!))
}
grandParentTemplateExpression
} else null
parent.delete()
result
} else {
replaced(templateExpression)
}
}
override fun doIt(postProcessing: (PsiChildRange) -> PsiChildRange): KtExpression? {
val insertedStatements = ArrayList<KtExpression>()
for (statement in codeToInline.statementsBefore) {
val statementToUse = statement.copy()
val anchor = findOrCreateBlockToInsertStatement()
val block = anchor.parent as KtBlockExpression
val inserted = block.addBefore(statementToUse, anchor) as KtExpression
block.addBefore(psiFactory.createNewLine(), anchor)
block.addBefore(psiFactory.createNewLine(), inserted)
insertedStatements.add(inserted)
}
val replaced: KtExpression? = when (val mainExpression = codeToInline.mainExpression?.copied()) {
is KtStringTemplateExpression -> elementToBeReplaced.replacedWithStringTemplate(mainExpression)
is KtExpression -> elementToBeReplaced.replaced(mainExpression)
else -> {
// NB: Unit is never used as expression
val stub = elementToBeReplaced.replaced(psiFactory.createExpression("0"))
val bindingContext = stub.analyze()
val canDropElementToBeReplaced = !stub.isUsedAsExpression(bindingContext)
if (canDropElementToBeReplaced) {
stub.delete()
null
} else {
stub.replaced(psiFactory.createExpression("Unit"))
}
}
}
codeToInline.performPostInsertionActions(insertedStatements + listOfNotNull(replaced))
var range = if (replaced != null) {
if (insertedStatements.isEmpty()) {
PsiChildRange.singleElement(replaced)
} else {
val statement = insertedStatements.first()
PsiChildRange(statement, replaced.parentsWithSelf.first { it.parent == statement.parent })
}
} else {
if (insertedStatements.isEmpty()) {
PsiChildRange.EMPTY
} else {
PsiChildRange(insertedStatements.first(), insertedStatements.last())
}
}
val listener = replaced?.let { TrackExpressionListener(it) }
listener?.attach()
try {
range = postProcessing(range)
} finally {
listener?.detach()
}
val resultExpression = listener?.result
// simplify "${x}" to "$x"
val templateEntry = resultExpression?.parent as? KtBlockStringTemplateEntry
if (templateEntry?.canDropBraces() == true) {
return templateEntry.dropBraces().expression
}
return resultExpression ?: range.last as? KtExpression
}
/**
* Returns statement in a block to insert statement before it
*/
private fun findOrCreateBlockToInsertStatement(): KtExpression {
for (element in elementToBeReplaced.parentsWithSelf) {
val parent = element.parent
when (element) {
is KtContainerNodeForControlStructureBody -> { // control statement without block
return element.expression!!.replaceWithBlock()
}
is KtExpression -> {
if (parent is KtWhenEntry) { // when entry without block
return element.replaceWithBlock()
}
if (parent is KtDeclarationWithBody) {
withElementToBeReplacedPreserved {
ConvertToBlockBodyIntention.convert(parent)
}
return (parent.bodyExpression as KtBlockExpression).statements.single()
}
if (parent is KtBlockExpression) return element
if (parent is KtBinaryExpression) {
return element.replaceWithRun()
}
}
}
}
elementToBeReplaced = elementToBeReplaced.replaceWithRunBlockAndGetExpression()
return elementToBeReplaced
}
private fun KtElement.replaceWithRun(): KtExpression = withElementToBeReplacedPreserved {
replaceWithRunBlockAndGetExpression()
}
private fun KtElement.replaceWithRunBlockAndGetExpression(): KtExpression {
val runExpression = psiFactory.createExpressionByPattern("run { $0 }", this) as KtCallExpression
val runAfterReplacement = this.replaced(runExpression)
val ktLambdaArgument = runAfterReplacement.lambdaArguments[0]
return ktLambdaArgument.getLambdaExpression()?.bodyExpression?.statements?.singleOrNull()
?: throw KotlinExceptionWithAttachments("cant get body expression for $ktLambdaArgument").withAttachment(
"ktLambdaArgument",
ktLambdaArgument.text
)
}
private fun KtExpression.replaceWithBlock(): KtExpression = withElementToBeReplacedPreserved {
replaced(KtPsiFactory(this).createSingleStatementBlock(this))
}.statements.single()
private fun <TElement : KtElement> withElementToBeReplacedPreserved(action: () -> TElement): TElement {
elementToBeReplaced.putCopyableUserData(ELEMENT_TO_BE_REPLACED_KEY, Unit)
val result = action()
elementToBeReplaced = result.findDescendantOfType { it.getCopyableUserData(ELEMENT_TO_BE_REPLACED_KEY) != null }
?: error("Element `elementToBeReplaced` not found")
elementToBeReplaced.putCopyableUserData(ELEMENT_TO_BE_REPLACED_KEY, null)
return result
}
private class TrackExpressionListener(expression: KtExpression) : PsiTreeChangeAdapter() {
private var expression: KtExpression? = expression
private val manager = expression.manager
fun attach() {
manager.addPsiTreeChangeListener(this)
}
fun detach() {
manager.removePsiTreeChangeListener(this)
}
val result: KtExpression?
get() = expression?.takeIf { it.isValid }
override fun childReplaced(event: PsiTreeChangeEvent) {
if (event.oldChild == expression) {
expression = event.newChild as? KtExpression
}
}
}
}
private val ELEMENT_TO_BE_REPLACED_KEY = Key<Unit>("ELEMENT_TO_BE_REPLACED_KEY")
| apache-2.0 | 212e71fadbe44597e81a55dea1ef630a | 41.538721 | 158 | 0.682286 | 6.273088 | false | false | false | false |
TonnyL/Mango | app/src/main/java/io/github/tonnyl/mango/ui/user/following/FollowingFragment.kt | 1 | 5606 | /*
* Copyright (c) 2017 Lizhaotailang
*
* 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 io.github.tonnyl.mango.ui.user.following
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import io.github.tonnyl.mango.R
import io.github.tonnyl.mango.data.Followee
import io.github.tonnyl.mango.databinding.FragmentSimpleListBinding
import io.github.tonnyl.mango.ui.user.UserProfileActivity
import io.github.tonnyl.mango.ui.user.UserProfilePresenter
import kotlinx.android.synthetic.main.fragment_simple_list.*
import org.jetbrains.anko.startActivity
/**
* Created by lizhaotailang on 2017/7/29.
*
* Main ui for the user's following screen.
*/
class FollowingFragment : Fragment(), FollowingContract.View {
private lateinit var mPresenter: FollowingContract.Presenter
private var mAdapter: FollowingAdapter? = null
private var mIsLoading = false
private var mLayoutManager: LinearLayoutManager? = null
private var _binding: FragmentSimpleListBinding? = null
private val binding get() =_binding!!
companion object {
@JvmStatic
fun newInstance(): FollowingFragment {
return FollowingFragment()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentSimpleListBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViews()
setHasOptionsMenu(true)
mPresenter.subscribe()
binding.refreshLayout.setOnRefreshListener {
mIsLoading = true
mPresenter.loadFollowing()
}
binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (dy > 0 && (mLayoutManager?.findLastVisibleItemPosition() == binding.recyclerView.adapter.itemCount - 1) && !mIsLoading) {
mIsLoading = true
mPresenter.loadMoreFollowing()
}
}
})
}
override fun onDestroyView() {
super.onDestroyView()
mPresenter.unsubscribe()
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item?.itemId == android.R.id.home) {
activity?.onBackPressed()
}
return super.onOptionsItemSelected(item)
}
override fun setPresenter(presenter: FollowingContract.Presenter) {
mPresenter = presenter
}
override fun setLoadingIndicator(loading: Boolean) {
binding.refreshLayout.isRefreshing = loading
}
override fun setEmptyViewVisibility(visible: Boolean) {
binding.emptyView.visibility = if (visible && (mAdapter == null)) View.VISIBLE else View.GONE
}
override fun showNetworkError() {
Snackbar.make(binding.recyclerView, R.string.network_error, Snackbar.LENGTH_SHORT).show()
}
override fun showFollowings(followings: List<Followee>) {
if (mAdapter == null) {
mAdapter = FollowingAdapter(context ?: return, followings)
mAdapter?.setOnItemClickListener { _, position ->
context?.startActivity<UserProfileActivity>(UserProfilePresenter.EXTRA_USER to followings[position].followee)
}
binding.recyclerView.adapter = mAdapter
}
mIsLoading = false
}
override fun notifyDataAllRemoved(size: Int) {
mAdapter?.notifyItemRangeRemoved(0, size)
mIsLoading = false
}
override fun notifyDataAdded(startPosition: Int, size: Int) {
mAdapter?.notifyItemRangeInserted(startPosition, size)
mIsLoading = false
}
private fun initViews() {
mLayoutManager = LinearLayoutManager(context)
binding.recyclerView.layoutManager = mLayoutManager
binding.refreshLayout.setColorSchemeColors(ContextCompat.getColor(context ?: return, R.color.colorAccent))
}
} | mit | 613129a169766e4148f2078dd92b9366 | 34.487342 | 141 | 0.704245 | 4.939207 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-tooling/testSrc/org/jetbrains/kotlin/idea/gradleTooling/CallReflectiveTest.kt | 3 | 3267 | // 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.
@file:Suppress("unused")
package org.jetbrains.kotlin.idea.gradleTooling
import org.jetbrains.kotlin.idea.gradleTooling.reflect.*
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
// 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.
class CallReflectiveTest {
class TestLogger : ReflectionLogger {
val messages = mutableListOf<String>()
val exceptions = mutableListOf<Throwable?>()
override fun logIssue(message: String, exception: Throwable?) {
messages.add(message)
exceptions.add(exception)
}
}
private val logger = TestLogger()
@Test
fun `call get property`() {
class Tested(val myProperty: String)
val instance = Tested("abc")
assertEquals("abc", instance.callReflectiveGetter("getMyProperty", logger))
}
@Test
fun `call get missing property`() {
class Tested(val myProperty: String)
val instance = Tested("abc")
assertNull(instance.callReflectiveGetter("getWrongPropertyName", logger))
assertEquals(1, logger.messages.size)
}
@Test
fun `call property with wrong return type`() {
class Tested(val myProperty: String)
val instance = Tested("abc")
assertNull(instance.callReflective("getMyProperty", parameters(), returnType<Int>(), logger))
assertEquals(1, logger.messages.size, "Expected single issue being reported")
val message = logger.messages.single()
assertTrue("String" in message, "Expected logged message to mention 'String'")
assertTrue("Int" in message, "Expected logged message to mention 'Int'")
}
@Test
fun `call function`() {
class Tested {
fun addTwo(value: Int) = value + 2
fun minus(first: Int, second: Int) = first - second
}
val instance = Tested()
assertEquals(4, instance.callReflective("addTwo", parameters(parameter(2)), returnType<Int>(), logger))
assertEquals(0, logger.messages.size)
assertEquals(3, instance.callReflective("minus", parameters(parameter(6), parameter(3)), returnType<Int>(), logger))
assertEquals(0, logger.messages.size)
}
@Test
fun `call function with null value (int) parameter`() {
class Tested {
fun orZero(value: Int?): Int = value ?: 0
}
val instance = Tested()
assertEquals(0, instance.callReflective("orZero", parameters(parameter<Int?>(null)), returnType<Int>(), logger))
assertEquals(0, logger.messages.size)
}
@Test
fun `call function with null value (string) parameter`() {
class Tested {
fun orEmpty(value: String?) = value ?: ""
}
val instance = Tested()
assertEquals("", instance.callReflective("orEmpty", parameters(parameter<String?>(null)), returnType<String>(), logger))
assertEquals(0, logger.messages.size)
}
}
| apache-2.0 | a3e9ec1b0154d19a33db293e78f1734d | 34.129032 | 158 | 0.655647 | 4.614407 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/refactoringTesting/FileSystemChangesTracker.kt | 6 | 1576 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.actions.internal.refactoringTesting
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.*
internal class FileSystemChangesTracker : Disposable {
private val trackerListener = object : VirtualFileListener, Disposable {
val createdFilesMutable = mutableSetOf<VirtualFile>()
@Volatile
private var disposed = false
init {
VirtualFileManager.getInstance().addVirtualFileListener(this, this@FileSystemChangesTracker)
Disposer.register(this@FileSystemChangesTracker, this)
}
@Synchronized
override fun dispose() {
if (!disposed) {
disposed = true
createdFilesMutable.clear()
}
}
override fun fileCreated(event: VirtualFileEvent) {
createdFilesMutable.add(event.file)
}
override fun fileCopied(event: VirtualFileCopyEvent) {
createdFilesMutable.add(event.file)
}
override fun fileMoved(event: VirtualFileMoveEvent) {
createdFilesMutable.add(event.file)
}
}
fun reset() {
trackerListener.createdFilesMutable.clear()
}
val createdFiles: Set<VirtualFile> = trackerListener.createdFilesMutable
override fun dispose() {
trackerListener.dispose()
}
} | apache-2.0 | bc378c30d5465543281b70caee39668e | 28.754717 | 158 | 0.668147 | 5.13355 | false | false | false | false |
gregcockroft/AndroidMath | mathdisplaylib/src/main/java/com/agog/mathdisplay/render/MTDrawFreeType.kt | 1 | 1789 | package com.agog.mathdisplay.render
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import com.pvporbit.freetype.FreeTypeConstants
import android.util.Log
import com.agog.mathdisplay.parse.MathDisplayException
class MTDrawFreeType(val mathfont: MTFontMathTable) {
fun drawGlyph(canvas: Canvas, p: Paint, gid: Int, x: Float, y: Float) {
val face = mathfont.checkFontSize()
/* load glyph image into the slot and render (erase previous one) */
if (gid != 0 && !face.loadGlyph(gid, FreeTypeConstants.FT_LOAD_RENDER)) {
val gslot = face.getGlyphSlot()
val plainbitmap = gslot.getBitmap()
if (plainbitmap != null) {
if (plainbitmap.width == 0 || plainbitmap.rows == 0) {
if (gid != 1 && gid != 33) {
throw MathDisplayException("missing glyph slot $gid.")
}
} else {
val bitmap = Bitmap.createBitmap(plainbitmap.width, plainbitmap.rows, Bitmap.Config.ALPHA_8)
bitmap.copyPixelsFromBuffer(plainbitmap.buffer)
val metrics = gslot.metrics
val offx = metrics.horiBearingX / 64.0f // 26.6 fixed point integer from freetype
val offy = metrics.horiBearingY / 64.0f
canvas.drawBitmap(bitmap, x + offx, y - offy, p)
}
}
}
}
//val enclosing = BoundingBox()
/*
val numGrays: Short
get() = FreeType.FT_Bitmap_Get_num_grays(pointer)
val paletteMode: Char
get() = FreeType.FT_Bitmap_Get_palette_mode(pointer)
val pixelMode: Char
get() = FreeType.FT_Bitmap_Get_pixel_mode(pointer)
*/
} | mit | efbe5aed9a5a661deb33a47f9b74e00b | 35.530612 | 112 | 0.593069 | 4.056689 | false | false | false | false |
douzifly/clear-todolist | app/src/main/java/douzifly/list/ui/home/DetailActivity.kt | 1 | 11828 | package douzifly.list.ui.home
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.util.TypedValue
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
import com.github.clans.fab.FloatingActionButton
import com.mikepenz.google_material_typeface_library.GoogleMaterial
import com.nineoldandroids.animation.ObjectAnimator
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog
import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog
import douzifly.list.R
import douzifly.list.model.Thing
import douzifly.list.model.ThingGroup
import douzifly.list.model.ThingsManager
import douzifly.list.settings.Settings
import douzifly.list.utils.*
import douzifly.list.widget.ColorPicker
import douzifly.list.widget.FontSizeBar
import java.util.*
/**
* Created by douzifly on 12/14/15.
*/
class DetailActivity : AppCompatActivity(), DatePickerDialog.OnDateSetListener,
TimePickerDialog.OnTimeSetListener {
override fun onDateSet(view: DatePickerDialog?, year: Int, monthOfYear: Int, dayOfMonth: Int) {
reminderDate = Date(year - 1900, monthOfYear, dayOfMonth)
showTimePicker()
}
override fun onTimeSet(view: RadialPickerLayout?, hourOfDay: Int, minute: Int, second: Int) {
"${hourOfDay} : ${minute}".logd("oooo")
reminderDate?.hours = hourOfDay
reminderDate?.minutes = minute
initDate = reminderDate
updateTimeUI(reminderDate)
}
fun updateTimeUI(date: Date?) {
if (date == null) {
txtReminder.text = ""
delReminder.visibility = View.GONE
} else {
delReminder.visibility = View.VISIBLE
txtReminder.text = formatDateTime(date)
formatTextViewcolor(txtReminder, date)
}
}
companion object {
val EXTRA_THING_ID = "thing_id"
private val TAG = "DetailActivity"
val RESULT_DELETE = 2
val RESULT_UPDATE = 3
val REQ_CHANGE_GROUP = 100
}
var reminderDate: Date? = null
var thing: Thing? = null
var initDate: Date? = null
val actionDone: FloatingActionButton by lazy {
val v = findViewById(R.id.action_done) as FloatingActionButton
v.setImageDrawable(
GoogleMaterial.Icon.gmd_done.colorResOf(R.color.redPrimary)
)
v
}
val actionDelete: FloatingActionButton by lazy {
val v = findViewById(R.id.action_delete) as FloatingActionButton
v.setImageDrawable(
GoogleMaterial.Icon.gmd_delete.colorOf(Color.WHITE)
)
v
}
val txtTitle: TextView by lazy {
findViewById(R.id.txt_title) as TextView
}
val editTitle: EditText by lazy {
findViewById(R.id.edit_title) as EditText
}
val editContent: EditText by lazy {
findViewById(R.id.txt_content) as EditText
}
val addReminder: FloatingActionButton by lazy {
findViewById(R.id.fab_add_reminder) as FloatingActionButton
}
val txtReminder: TextView by lazy {
findViewById(R.id.txt_reminder) as TextView
}
val colorPicker: ColorPicker by lazy {
findViewById(R.id.color_picker) as ColorPicker
}
val txtGroup : TextView by lazy {
findViewById(R.id.txt_group) as TextView
}
val delReminder: View by lazy {
val v = findViewById(R.id.reminder_del)
v.setOnClickListener {
cancelPickTime()
}
v
}
val focusChangeListener = View.OnFocusChangeListener {
v, hasFocus ->
if (!hasFocus) {
when (v) {
editTitle -> {
setTitleEditMode(false)
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.detail_activity)
initView()
parseIntent()
val alphaAnim = ObjectAnimator.ofFloat(editContent, "alpha", 0.0f, 1.0f)
alphaAnim.setDuration(500)
alphaAnim.start()
addReminder.setImageDrawable(
GoogleMaterial.Icon.gmd_alarm.colorResOf(R.color.greyPrimary)
)
addReminder.setOnClickListener {
showDatePicker()
}
txtReminder.typeface = fontRailway
loadData()
}
fun finishCompact() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
finishAfterTransition()
} else {
finish()
}
}
fun cancelPickTime() {
reminderDate = null
updateTimeUI(reminderDate)
}
fun showDatePicker() {
val selectedDate = Calendar.getInstance();
if (initDate != null) {
selectedDate.time = initDate
}
val dpd = DatePickerDialog.newInstance(
this,
selectedDate.get(Calendar.YEAR),
selectedDate.get(Calendar.MONTH),
selectedDate.get(Calendar.DAY_OF_MONTH)
);
if (initDate != null) {
}
dpd.accentColor = colorPicker.selectedColor
ui {
editTitle.hideKeyboard()
editContent.hideKeyboard()
}
dpd.show((this as AppCompatActivity).getFragmentManager(), "Datepickerdialog");
}
fun showTimePicker() {
val selectTime = Calendar.getInstance();
if (initDate != null) {
selectTime.time = initDate
}
val dpd = TimePickerDialog.newInstance(
this,
selectTime.get(Calendar.HOUR_OF_DAY),
selectTime.get(Calendar.MINUTE),
true)
dpd.accentColor = colorPicker.selectedColor
dpd.show((this as AppCompatActivity).getFragmentManager(), "Timepickerdialog");
}
fun parseIntent() {
val id = intent?.getLongExtra(EXTRA_THING_ID, 0) ?: 0
if (id > 0) {
thing = ThingsManager.getThingByIdAtCurrentGroup(id)
initDate = if (thing!!.reminderTime > 0) Date(thing!!.reminderTime) else null
updateGroupText(thing!!.group!!)
}
}
var selectedGroup: ThingGroup? = null
fun updateGroupText(group: ThingGroup) {
selectedGroup = group
txtGroup.text = selectedGroup?.title ?: "Unknown"
}
fun loadData() {
if (thing == null) return
txtTitle.text = thing!!.title
editTitle.setText(thing!!.title)
editContent.setText(thing!!.content)
editContent.setBackgroundColor(0x0000)
txtTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, FontSizeBar.fontSizeToDp(Settings.fontSize) + 2)
editTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, FontSizeBar.fontSizeToDp(Settings.fontSize) + 2)
editContent.setTextSize(TypedValue.COMPLEX_UNIT_PX, FontSizeBar.fontSizeToDp(Settings.fontSize))
txtGroup.setTextSize(TypedValue.COMPLEX_UNIT_PX, FontSizeBar.fontSizeToDp(Settings.fontSize))
ui(200) {
colorPicker.setSelected(thing!!.color)
}
updateTimeUI(
if (thing!!.reminderTime > 0) Date(thing!!.reminderTime)
else null
)
if (thing!!.reminderTime > 0) {
reminderDate = Date(thing!!.reminderTime)
}
}
fun saveData() {
editTitle.hideKeyboard()
editContent.hideKeyboard()
var changed = false
val newTitle = editTitle.text.toString()
val newContent = editContent.text.toString()
val newColor = colorPicker.selectedColor
val newReminderTime = reminderDate?.time ?: 0
if (thing!!.title != newTitle) {
thing!!.title = newTitle
changed = true
}
if (thing!!.content != newContent) {
thing!!.content = newContent
changed = true
}
if (thing!!.color != newColor) {
thing!!.color = newColor
ThingsManager.getGroupByGroupId(Settings.selectedGroupId)?.clearAllDisplayColor()
changed = true
}
if (thing!!.reminderTime != newReminderTime) {
thing!!.reminderTime = newReminderTime
changed = true
}
if (selectedGroup != null) {
changed = true
}
if (changed) {
bg {
setResult(RESULT_UPDATE)
ThingsManager.saveThing(thing!!, selectedGroup)
}
}
}
fun initView() {
txtTitle.typeface = fontSourceSansPro
txtGroup.typeface = fontSourceSansPro
editContent.typeface = fontSourceSansPro
editTitle.typeface = fontSourceSansPro
editTitle.visibility = View.GONE
actionDelete.setOnClickListener {
val intent = Intent()
intent.putExtra(EXTRA_THING_ID, thing!!.id)
setResult(RESULT_DELETE, intent)
finishCompact()
}
actionDone.setOnClickListener {
bg {
saveData()
ui {
finishCompact()
}
}
}
txtTitle.setOnClickListener(onClickListener)
editTitle.onFocusChangeListener = focusChangeListener
editContent.isFocusable = false
editContent.isFocusableInTouchMode = false
editContent.setOnClickListener {
v ->
editContentRequestFocus()
}
editTitle.setOnEditorActionListener {
textView, actionId, keyEvent ->
if (actionId == EditorInfo.IME_ACTION_NEXT) {
editContentRequestFocus()
true
}
false
};
txtGroup.setOnClickListener {
showGroupChoose()
}
}
fun showGroupChoose() {
ui {
editTitle.hideKeyboard()
editContent.hideKeyboard()
}
val intent = Intent(this, GroupEditorActivity::class.java)
intent.putExtra(GroupEditorActivity.EXTRA_KEY_SHOW_ALL, false)
startActivityForResult(intent, REQ_CHANGE_GROUP)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQ_CHANGE_GROUP && resultCode == RESULT_OK) {
val id = data!!.getLongExtra("id", -1L)
if (id != thing!!.group!!.id) {
// groupId changed
selectedGroup = ThingsManager.getGroupByGroupId(id)
"group changed to : ${selectedGroup?.title ?: "not changed"}".logd(TAG)
updateGroupText(selectedGroup!!)
}
}
}
private fun editContentRequestFocus() {
editContent.isFocusable = true
editContent.isFocusableInTouchMode = true
editContent.requestFocus()
ui(100) {
editContent.showKeyboard()
}
}
fun setTitleEditMode(editMode: Boolean) {
if (editMode) {
// show edittext
txtTitle.visibility = View.GONE
editTitle.setText(txtTitle.text)
editTitle.visibility = View.VISIBLE
editTitle.requestFocus()
editTitle.showKeyboard()
} else {
txtTitle.visibility = View.VISIBLE
editTitle.visibility = View.GONE
txtTitle.setText(editTitle.text)
}
}
val onClickListener: (v: View) -> Unit = {
v ->
if (v == txtTitle) {
setTitleEditMode(true)
}
}
} | gpl-3.0 | ba3437e74a7982bd2faa0aa673650153 | 28.279703 | 106 | 0.604921 | 4.963491 | false | false | false | false |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/project/petal/Base/BasePetalActivity.kt | 1 | 3395 | package stan.androiddemo.project.petal.Base
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import rx.Subscription
import rx.subscriptions.CompositeSubscription
import stan.androiddemo.R
import stan.androiddemo.project.petal.Config.Config
import stan.androiddemo.project.petal.Config.UserSingleton
import stan.androiddemo.tool.Base64Utils
import stan.androiddemo.tool.NetUtils
import stan.androiddemo.tool.SPUtils
/**
* Created by stanhu on 10/8/2017.
*/
public abstract class BasePetalActivity :AppCompatActivity(){
protected val TAG = getTag()
abstract fun getTag():String
abstract fun getLayoutId():Int
var isLogin = false
var mAuthorization:String = ""
lateinit var mFormatImageUrlBig: String
//大图的后缀
lateinit var mFormatImageGeneral: String
lateinit var mContext:Context
override fun toString(): String {
return javaClass.simpleName + " @" + Integer.toHexString(hashCode());
}
private var mCompositeSubscription: CompositeSubscription? = null
fun getCompositeSubscription(): CompositeSubscription {
if (this.mCompositeSubscription == null) {
this.mCompositeSubscription = CompositeSubscription()
}
return this.mCompositeSubscription!!
}
fun addSubscription(s: Subscription?) {
if (s == null) {
return
}
if (this.mCompositeSubscription == null) {
this.mCompositeSubscription = CompositeSubscription()
}
this.mCompositeSubscription!!.add(s)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT){
if (isTranslucentStatusBar()){
val wd = window
wd.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
}
}
mFormatImageGeneral = resources.getString(R.string.url_image_general)
mFormatImageUrlBig = resources.getString(R.string.url_image_big)
setContentView(getLayoutId())
mContext = this
getLoginData()
initResAndListener()
}
open fun isTranslucentStatusBar():Boolean{ return true }
fun getLoginData(){
UserSingleton.instance.isLogin(application)
isLogin = SPUtils.get(mContext,Config.ISLOGIN,false) as Boolean
mAuthorization = getAuthorizations(isLogin)
}
open fun initResAndListener(){ }
protected fun getAuthorizations(isLogin: Boolean): String {
val temp = " "
if (isLogin) {
return (SPUtils.get(mContext, Config.TOKENTYPE, temp) as String) + temp + (SPUtils.get(mContext, Config.TOKENACCESS, temp) as String)
}
return Base64Utils.mClientInto
}
override fun onDestroy() {
super.onDestroy()
if (this.mCompositeSubscription != null){
this.mCompositeSubscription = null
}
}
fun checkException(e:Throwable,mRootView:View){
NetUtils.checkHttpException(mContext,e,mRootView)
}
fun toast(msg:String){
Toast.makeText(mContext,msg,Toast.LENGTH_SHORT).show()
}
} | mit | e672e727804f55c3a4439d45f84eef76 | 27.453782 | 145 | 0.685672 | 4.701389 | false | true | false | false |
7449/Album | core/src/main/java/com/gallery/core/extensions/ExtensionsView.kt | 1 | 462 | package com.gallery.core.extensions
import android.view.View
/** 隐藏 */
fun View.hideExpand(): View = apply { if (!isGoneExpand()) visibility = View.GONE }
/** 是否为隐藏GONE */
fun View.isGoneExpand(): Boolean = visibility == View.GONE
/** 显示 */
fun View.showExpand(): View = apply { if (!isVisibleExpand()) visibility = View.VISIBLE }
/** 是否为显示VISIBLE */
fun View.isVisibleExpand(): Boolean = visibility == View.VISIBLE | mpl-2.0 | e275028c2a5abc4a0a9d407b822d7376 | 27.066667 | 89 | 0.675115 | 3.647059 | false | false | false | false |
migafgarcia/programming-challenges | advent_of_code/2018/solutions/day_9_b.kt | 1 | 1106 | import java.io.File
import java.util.*
fun main(args: Array<String>) {
val input = File(args[0]).readText().split(" ").mapNotNull { it.toIntOrNull() }
assert(score(9, 25) == 32L)
assert(score(10, 1618) == 8317L)
assert(score(13, 7999) == 146373L)
assert(score(17, 1104) == 2764L)
assert(score(21, 6111) == 54718L)
assert(score(30, 5807) == 37305L)
println(score(input[0], input[1] * 100))
}
fun score(nPlayers: Int, lastMarble: Int): Long {
val circle = LinkedList<Int>()
val players = LongArray(nPlayers)
circle.add(0)
for (i in 1..lastMarble) {
if (i % 23 == 0) {
circle.rotate(7)
players[i % nPlayers] = players[i % nPlayers] + circle.removeLast() + i
circle.rotate(-1)
} else {
circle.rotate(-1)
circle.addLast(i)
}
}
return players.max()!!
}
private fun <E> LinkedList<E>.rotate(n: Int) {
if(n > 0)
repeat(n) {
addFirst(removeLast())
}
else
repeat(-n) {
addLast(removeFirst())
}
}
| mit | 45caed1881e3d3c816a213b948af89bc | 19.481481 | 83 | 0.536166 | 3.272189 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.