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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/ndrei/teslacorelib/gui/GhostedItemStackRenderPiece.kt | 1 | 1098 | package net.ndrei.teslacorelib.gui
import net.minecraft.client.renderer.RenderHelper
import net.minecraft.item.ItemStack
import net.ndrei.teslacorelib.render.GhostedItemRenderer
/**
* Created by CF on 2017-07-04.
*/
open class GhostedItemStackRenderPiece(left: Int, top: Int, val alpha: Float = .42f, val stack: ItemStack? = null)
: BasicContainerGuiPiece(left, top, 18, 18) {
override fun drawBackgroundLayer(container: BasicTeslaGuiContainer<*>, guiX: Int, guiY: Int, partialTicks: Float, mouseX: Int, mouseY: Int) {
super.drawBackgroundLayer(container, guiX, guiY, partialTicks, mouseX, mouseY)
val left = this.left + guiX + 1
val top = this.top + guiY + 1
val stack = this.getRenderStack()
if (!stack.isEmpty) {
RenderHelper.enableGUIStandardItemLighting()
GhostedItemRenderer.renderItemInGUI(container.itemRenderer, stack, left, top, this.alpha)
RenderHelper.disableStandardItemLighting()
}
}
open fun getRenderStack(): ItemStack {
return this.stack ?: ItemStack.EMPTY
}
}
| mit | 3f3449626de34932f06ac7e4511c6f29 | 35.6 | 145 | 0.695811 | 4.066667 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/closures/closureOnTopLevel1.kt | 2 | 452 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS
package test
val p = { "OK" }()
val getter: String
get() = { "OK" }()
fun f() = { "OK" }()
val obj = object : Function0<String> {
override fun invoke() = "OK"
}
fun box(): String {
if (p != "OK") return "FAIL"
if (getter != "OK") return "FAIL"
if (f() != "OK") return "FAIL"
if (obj() != "OK") return "FAIL"
return "OK"
}
| apache-2.0 | 67d986a0524253c3f213f388a54dcc48 | 17.833333 | 72 | 0.54646 | 2.993377 | false | false | false | false |
WillowChat/Kale | src/main/kotlin/chat/willow/kale/irc/message/rfc1459/rpl/Rpl005Message.kt | 2 | 2166 | package chat.willow.kale.irc.message.rfc1459.rpl
import chat.willow.kale.core.ICommand
import chat.willow.kale.core.message.*
import chat.willow.kale.irc.CharacterCodes
object Rpl005Message : ICommand {
override val command = "005"
data class Message(val source: String, val target: String, val tokens: Map<String, String?>) {
object Descriptor : KaleDescriptor<Message>(matcher = commandMatcher(command), parser = Parser)
object Parser : MessageParser<Message>() {
override fun parseFromComponents(components: IrcMessageComponents): Message? {
if (components.parameters.size < 2) {
return null
}
val source = components.prefix ?: ""
val target = components.parameters[0]
val tokens = mutableMapOf<String, String?>()
for (i in 1 until components.parameters.size) {
val token = components.parameters[i].split(delimiters = CharacterCodes.EQUALS, limit = 2)
if (token.isEmpty() || token[0].isEmpty()) {
continue
}
var value = token.getOrNull(1)
if (value != null && value.isEmpty()) {
value = null
}
tokens[token[0]] = value
}
return Message(source, target, tokens)
}
}
object Serialiser : MessageSerialiser<Message>(command) {
override fun serialiseToComponents(message: Message): IrcMessageComponents {
val tokens = mutableListOf<String>()
for ((key, value) in message.tokens) {
if (value.isNullOrEmpty()) {
tokens.add(key)
} else {
tokens.add("$key${CharacterCodes.EQUALS}$value")
}
}
val parameters = listOf(message.target) + tokens
return IrcMessageComponents(prefix = message.source, parameters = parameters)
}
}
}
} | isc | c35f3b6c6f4f1b8349108274a51207e0 | 30.405797 | 109 | 0.529548 | 5.361386 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/trace/impl/interpret/FilterTraceInterpreter.kt | 6 | 3074 | // 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.debugger.sequence.trace.impl.interpret
import com.intellij.debugger.streams.trace.CallTraceInterpreter
import com.intellij.debugger.streams.trace.TraceElement
import com.intellij.debugger.streams.trace.TraceInfo
import com.intellij.debugger.streams.trace.impl.TraceElementImpl
import com.intellij.debugger.streams.trace.impl.interpret.ex.UnexpectedValueTypeException
import com.intellij.debugger.streams.wrapper.StreamCall
import com.sun.jdi.ArrayReference
import com.sun.jdi.BooleanValue
import com.sun.jdi.IntegerValue
import com.sun.jdi.Value
class FilterTraceInterpreter(private val predicateValueToAccept: Boolean) : CallTraceInterpreter {
override fun resolve(call: StreamCall, value: Value): TraceInfo {
if (value !is ArrayReference) throw UnexpectedValueTypeException("array reference excepted, but actual: ${value.type().name()}")
val before = resolveValuesBefore(value.getValue(0))
val filteringMap = value.getValue(1)
val after = resolveValuesAfter(before, filteringMap)
return ValuesOrder(call, before, after)
}
private fun resolveValuesBefore(map: Value): Map<Int, TraceElement> {
val (keys, objects) = InterpreterUtil.extractMap(map)
val result: MutableList<TraceElement> = mutableListOf()
for (i in 0.until(keys.length())) {
val time = keys.getValue(i)
val value = objects.getValue(i)
if (time !is IntegerValue) throw UnexpectedValueTypeException("time should be represented by integer value")
result.add(TraceElementImpl(time.value(), value))
}
return InterpreterUtil.createIndexByTime(result)
}
private fun resolveValuesAfter(before: Map<Int, TraceElement>, filteringMap: Value): Map<Int, TraceElement> {
val predicateValues = extractPredicateValues(filteringMap)
val result = linkedMapOf<Int, TraceElement>()
for ((beforeTime, element) in before) {
val predicateValue = predicateValues[beforeTime]
if (predicateValue == predicateValueToAccept) {
result[beforeTime + 1] = TraceElementImpl(beforeTime + 1, element.value)
}
}
return result
}
private fun extractPredicateValues(filteringMap: Value): Map<Int, Boolean> {
val (keys, values) = InterpreterUtil.extractMap(filteringMap)
val result = mutableMapOf<Int, Boolean>()
for (i in 0.until(keys.length())) {
val time = keys.getValue(i)
val value = values.getValue(i)
if (time !is IntegerValue) throw UnexpectedValueTypeException("time should be represented by integer value")
if (value !is BooleanValue) throw UnexpectedValueTypeException("predicate value should be represented by boolean value")
result[time.value()] = value.value()
}
return result
}
} | apache-2.0 | a100e568bcf8a35cddecfbf00a8b4ab8 | 46.307692 | 158 | 0.708523 | 4.520588 | false | false | false | false |
Flank/flank | tool/log/format/src/main/kotlin/flank/log/Builder.kt | 1 | 1974 | package flank.log
import kotlin.reflect.KClass
/**
* Factory method for building and creating generic [Formatter].
*/
fun <T> buildFormatter(build: Builder<T>.() -> Unit): Formatter<T> =
Builder<T>().apply(build).run {
@Suppress("UNCHECKED_CAST")
Formatter(
static = static as Map<StaticMatcher, Format<Any, T>>,
dynamic = dynamic as Map<DynamicMatcher, Format<Any, T>>,
)
}
/**
* Generic formatters builder.
*/
class Builder<T> internal constructor() {
internal val static = mutableMapOf<StaticMatcher, Format<*, T>>()
internal val dynamic = mutableMapOf<DynamicMatcher, Format<*, T>>()
/**
* Registers [V] formatter with [KClass] based static matcher.
*
* @receiver [KClass] as a identifier.
* @param context Optional context.
* @param format Reference to formatting function.
*/
operator fun <V : Event.Data> KClass<V>.invoke(
context: Any? = null,
format: Format<V, T>,
) {
static += listOfNotNull(context, java) to format
}
/**
* Registers [V] formatter with [Event.Type] based static matcher.
*
* @receiver [Event.Type] as a identifier.
* @param context Optional context.
* @param format Reference to formatting function.
*/
operator fun <V> Event.Type<V>.invoke(
context: Any? = null,
format: Format<V, T>
) {
static += listOfNotNull(context, this) to format
}
/**
* Creates matcher function.
*/
fun <V> match(f: (Any.(Any) -> V?)) = f
/**
* Registers [V] formatter with dynamic matcher function.
*
* @receiver Matching event function. The receiver is a context where
* @param format Reference to formatting function.
*/
infix fun <V> (Any.(Any) -> V?).to(
format: Format<V, T>
) {
val wrap: DynamicMatcher = { invoke(this, it) != null }
dynamic += wrap to format
}
}
| apache-2.0 | 94ff9c926faad47d936c21b8dcc994f5 | 27.2 | 73 | 0.595745 | 4.070103 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/viewmodels/projectpage/ProjectPageViewModel.kt | 1 | 56328 | package com.kickstarter.viewmodels.projectpage
import android.content.Intent
import android.util.Pair
import androidx.annotation.NonNull
import com.kickstarter.R
import com.kickstarter.libs.ActivityRequestCodes
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.Either
import com.kickstarter.libs.Environment
import com.kickstarter.libs.ProjectPagerTabs
import com.kickstarter.libs.RefTag
import com.kickstarter.libs.models.OptimizelyExperiment
import com.kickstarter.libs.rx.transformers.Transformers.combineLatestPair
import com.kickstarter.libs.rx.transformers.Transformers.errors
import com.kickstarter.libs.rx.transformers.Transformers.ignoreValues
import com.kickstarter.libs.rx.transformers.Transformers.neverError
import com.kickstarter.libs.rx.transformers.Transformers.takePairWhen
import com.kickstarter.libs.rx.transformers.Transformers.takeWhen
import com.kickstarter.libs.rx.transformers.Transformers.values
import com.kickstarter.libs.utils.EventContextValues.ContextPageName.PROJECT
import com.kickstarter.libs.utils.EventContextValues.ContextSectionName.CAMPAIGN
import com.kickstarter.libs.utils.EventContextValues.ContextSectionName.ENVIRONMENT
import com.kickstarter.libs.utils.EventContextValues.ContextSectionName.FAQS
import com.kickstarter.libs.utils.EventContextValues.ContextSectionName.OVERVIEW
import com.kickstarter.libs.utils.EventContextValues.ContextSectionName.RISKS
import com.kickstarter.libs.utils.ExperimentData
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.libs.utils.ProjectViewUtils
import com.kickstarter.libs.utils.RefTagUtils
import com.kickstarter.libs.utils.UrlUtils
import com.kickstarter.libs.utils.extensions.ProjectMetadata
import com.kickstarter.libs.utils.extensions.backedReward
import com.kickstarter.libs.utils.extensions.isErrored
import com.kickstarter.libs.utils.extensions.isFalse
import com.kickstarter.libs.utils.extensions.isNonZero
import com.kickstarter.libs.utils.extensions.isTrue
import com.kickstarter.libs.utils.extensions.metadataForProject
import com.kickstarter.libs.utils.extensions.negate
import com.kickstarter.libs.utils.extensions.updateProjectWith
import com.kickstarter.libs.utils.extensions.userIsCreator
import com.kickstarter.models.Backing
import com.kickstarter.models.Project
import com.kickstarter.models.Reward
import com.kickstarter.models.User
import com.kickstarter.ui.IntentKey
import com.kickstarter.ui.activities.ProjectPageActivity
import com.kickstarter.ui.data.CheckoutData
import com.kickstarter.ui.data.MediaElement
import com.kickstarter.ui.data.PledgeData
import com.kickstarter.ui.data.PledgeFlowContext
import com.kickstarter.ui.data.PledgeReason
import com.kickstarter.ui.data.ProjectData
import com.kickstarter.ui.data.VideoModelElement
import com.kickstarter.ui.intentmappers.ProjectIntentMapper
import com.kickstarter.viewmodels.usecases.ShowPledgeFragmentUseCase
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
import java.math.RoundingMode
import java.util.concurrent.TimeUnit
interface ProjectPageViewModel {
interface Inputs {
/** Call when the cancel pledge option is clicked. */
fun cancelPledgeClicked()
/** Call when the comments text view is clicked. */
fun commentsTextViewClicked()
/** Call when the contact creator option is clicked. */
fun contactCreatorClicked()
/** Call when the fix payment method is clicked. */
fun fixPaymentMethodButtonClicked()
/** Call when the count of fragments on the back stack changes. */
fun fragmentStackCount(count: Int)
/** Call when the heart button is clicked. */
fun heartButtonClicked()
/** Call when the native_project_action_button is clicked. */
fun nativeProjectActionButtonClicked()
/** Call when the view has been laid out. */
fun onGlobalLayout()
/** Call when the fullscreen video button is clicked. */
fun fullScreenVideoButtonClicked(videoInfo: kotlin.Pair<String, Long>)
/** Call when the pledge's payment method has been successfully updated. */
fun pledgePaymentSuccessfullyUpdated()
/** Call when the pledge has been successfully canceled. */
fun pledgeSuccessfullyCancelled()
/** Call when the pledge has been successfully created. */
fun pledgeSuccessfullyCreated(checkoutDataAndPledgeData: Pair<CheckoutData, PledgeData>)
/** Call when the pledge has been successfully updated. */
fun pledgeSuccessfullyUpdated()
/** Call when the user clicks the navigation icon of the pledge toolbar. */
fun pledgeToolbarNavigationClicked()
/** Call when the user has triggered a manual refresh of the project. */
fun refreshProject()
/** Call when the reload container is clicked. */
fun reloadProjectContainerClicked()
/** Call when the share button is clicked. */
fun shareButtonClicked()
/** Call when the update payment option is clicked. */
fun updatePaymentClicked()
/** Call when the update pledge option is clicked. */
fun updatePledgeClicked()
/** Call when the updates button is clicked. */
fun updatesTextViewClicked()
/** Call when the view rewards option is clicked. */
fun viewRewardsClicked()
/** Call when some tab on the Tablayout has been pressed, with the position */
fun tabSelected(position: Int)
fun closeFullScreenVideo(seekPosition: Long)
fun onVideoPlayButtonClicked()
}
interface Outputs {
/** Emits a boolean that determines if the backing details should be visible. */
fun backingDetailsIsVisible(): Observable<Boolean>
/** Emits a string or string resource ID of the backing details subtitle. */
fun backingDetailsSubtitle(): Observable<Either<String, Int>?>
/** Emits the string resource ID of the backing details title. */
fun backingDetailsTitle(): Observable<Int>
/** Emits when rewards sheet should expand and if it should animate. */
fun expandPledgeSheet(): Observable<Pair<Boolean, Boolean>>
/** Emits when we should go back in the navigation hierarchy. */
fun goBack(): Observable<Void>
/** Emits a drawable id that corresponds to whether the project is saved. */
fun heartDrawableId(): Observable<Int>
/** Emits a menu for managing your pledge or null if there's no menu. */
fun managePledgeMenu(): Observable<Int?>
/** Emits the color resource ID for the pledge action button. */
fun pledgeActionButtonColor(): Observable<Int>
/** Emits a boolean that determines if the pledge action button container should be visible. */
fun pledgeActionButtonContainerIsGone(): Observable<Boolean>
/** Emits the string resource ID for the pledge action button. */
fun pledgeActionButtonText(): Observable<Int>
/** Emits the proper string resource ID for the pledge toolbar navigation icon. */
fun pledgeToolbarNavigationIcon(): Observable<Int>
/** Emits the proper string resource ID for the pledge toolbar title. */
fun pledgeToolbarTitle(): Observable<Int>
/** Emits the url of a prelaunch activated project to open in the browser. */
fun prelaunchUrl(): Observable<String>
/** Emits [ProjectData]. If the view model is created with a full project
* model, this observable will emit that project immediately, and then again when it has updated from the api. */
fun projectData(): Observable<ProjectData>
/** Emits a boolean that determines if the reload project container should be visible. */
fun reloadProjectContainerIsGone(): Observable<Boolean>
/** Emits a boolean that determines if the progress bar in the retry container should be visible. */
fun reloadProgressBarIsGone(): Observable<Boolean>
/** Emits when we should reveal the [com.kickstarter.ui.fragments.RewardsFragment] with an animation. */
fun revealRewardsFragment(): Observable<Void>
/** Emits a boolean that determines if the scrim for secondary pledging actions should be visible. */
fun scrimIsVisible(): Observable<Boolean>
/** Emits when we should set the Y position of the rewards container. */
fun setInitialRewardsContainerY(): Observable<Void>
/** Emits when we should show the [com.kickstarter.ui.fragments.CancelPledgeFragment]. */
fun showCancelPledgeFragment(): Observable<Project>
/** Emits when the backing has successfully been canceled. */
fun showCancelPledgeSuccess(): Observable<Void>
/** Emits when we should show the not cancelable dialog. */
fun showPledgeNotCancelableDialog(): Observable<Void>
/** Emits when the success prompt for saving should be displayed. */
fun showSavedPrompt(): Observable<Void>
/** Emits when we should show the share sheet with the name of the project and share URL. */
fun showShareSheet(): Observable<Pair<String, String>>
/** Emits when we should show the [com.kickstarter.ui.fragments.PledgeFragment]. */
fun showUpdatePledge(): Observable<Triple<PledgeData, PledgeReason, Boolean>>
/** Emits when the backing has successfully been updated. */
fun showUpdatePledgeSuccess(): Observable<Void>
/** Emits when we should start [com.kickstarter.ui.activities.RootCommentsActivity]. */
fun startRootCommentsActivity(): Observable<ProjectData>
fun startRootCommentsForCommentsThreadActivity(): Observable<Pair<String, ProjectData>>
/** Emits when we should start [com.kickstarter.ui.activities.LoginToutActivity]. */
fun startLoginToutActivity(): Observable<Void>
/** Emits when we should show the [com.kickstarter.ui.activities.MessagesActivity]. */
fun startMessagesActivity(): Observable<Project>
/** Emits when we should start [com.kickstarter.ui.activities.UpdateActivity]. */
fun startProjectUpdateActivity(): Observable< Pair<Pair<String, Boolean>, Pair<Project, ProjectData>>>
/** Emits when we should start [com.kickstarter.ui.activities.UpdateActivity]. */
fun startProjectUpdateToRepliesDeepLinkActivity(): Observable< Pair<Pair<String, String>, Pair<Project, ProjectData>>>
/** Emits when we the pledge was successful and should start the [com.kickstarter.ui.activities.ThanksActivity]. */
fun startThanksActivity(): Observable<Pair<CheckoutData, PledgeData>>
/** Emits when we should update the [com.kickstarter.ui.fragments.BackingFragment] and [com.kickstarter.ui.fragments.RewardsFragment]. */
fun updateFragments(): Observable<ProjectData>
fun projectMedia(): Observable<MediaElement>
/** Emits when the play button should be gone. */
fun playButtonIsVisible(): Observable<Boolean>
/** Emits when the backing view group should be gone. */
fun backingViewGroupIsVisible(): Observable<Boolean>
/** Will emmit the need to show/hide the Campaign Tab and the Environmental Tab. */
fun updateTabs(): Observable<Boolean>
fun hideVideoPlayer(): Observable<Boolean>
fun onOpenVideoInFullScreen(): Observable<kotlin.Pair<String, Long>>
fun updateVideoCloseSeekPosition(): Observable<Long>
}
class ViewModel(@NonNull val environment: Environment) :
ActivityViewModel<ProjectPageActivity>(environment),
Inputs,
Outputs {
private val cookieManager = requireNotNull(environment.cookieManager())
private val currentUser = requireNotNull(environment.currentUser())
private val ksCurrency = requireNotNull(environment.ksCurrency())
private val optimizely = requireNotNull(environment.optimizely())
private val sharedPreferences = requireNotNull(environment.sharedPreferences())
private val apolloClient = requireNotNull(environment.apolloClient())
private val currentConfig = requireNotNull(environment.currentConfig())
private val closeFullScreenVideo = BehaviorSubject.create<Long>()
private val cancelPledgeClicked = PublishSubject.create<Void>()
private val commentsTextViewClicked = PublishSubject.create<Void>()
private val contactCreatorClicked = PublishSubject.create<Void>()
private val fixPaymentMethodButtonClicked = PublishSubject.create<Void>()
private val fragmentStackCount = PublishSubject.create<Int>()
private val heartButtonClicked = PublishSubject.create<Void>()
private val nativeProjectActionButtonClicked = PublishSubject.create<Void>()
private val onGlobalLayout = PublishSubject.create<Void>()
private val fullScreenVideoButtonClicked = PublishSubject.create<kotlin.Pair<String, Long>>()
private val pledgePaymentSuccessfullyUpdated = PublishSubject.create<Void>()
private val pledgeSuccessfullyCancelled = PublishSubject.create<Void>()
private val pledgeSuccessfullyCreated = PublishSubject.create<Pair<CheckoutData, PledgeData>>()
private val pledgeSuccessfullyUpdated = PublishSubject.create<Void>()
private val pledgeToolbarNavigationClicked = PublishSubject.create<Void>()
private val refreshProject = PublishSubject.create<Void>()
private val reloadProjectContainerClicked = PublishSubject.create<Void>()
private val shareButtonClicked = PublishSubject.create<Void>()
private val updatePaymentClicked = PublishSubject.create<Void>()
private val updatePledgeClicked = PublishSubject.create<Void>()
private val updatesTextViewClicked = PublishSubject.create<Void>()
private val viewRewardsClicked = PublishSubject.create<Void>()
private val onVideoPlayButtonClicked = PublishSubject.create<Void>()
private val backingDetailsIsVisible = BehaviorSubject.create<Boolean>()
private val backingDetailsSubtitle = BehaviorSubject.create<Either<String, Int>?>()
private val backingDetailsTitle = BehaviorSubject.create<Int>()
private val expandPledgeSheet = BehaviorSubject.create<Pair<Boolean, Boolean>>()
private val goBack = PublishSubject.create<Void>()
private val heartDrawableId = BehaviorSubject.create<Int>()
private val managePledgeMenu = BehaviorSubject.create<Int?>()
private val pledgeActionButtonColor = BehaviorSubject.create<Int>()
private val pledgeActionButtonContainerIsGone = BehaviorSubject.create<Boolean>()
private val pledgeActionButtonText = BehaviorSubject.create<Int>()
private val pledgeToolbarNavigationIcon = BehaviorSubject.create<Int>()
private val pledgeToolbarTitle = BehaviorSubject.create<Int>()
private val prelaunchUrl = BehaviorSubject.create<String>()
private val projectData = BehaviorSubject.create<ProjectData>()
private val retryProgressBarIsGone = BehaviorSubject.create<Boolean>()
private val reloadProjectContainerIsGone = BehaviorSubject.create<Boolean>()
private val revealRewardsFragment = PublishSubject.create<Void>()
private val scrimIsVisible = BehaviorSubject.create<Boolean>()
private val setInitialRewardPosition = BehaviorSubject.create<Void>()
private val showCancelPledgeFragment = PublishSubject.create<Project>()
private val showCancelPledgeSuccess = PublishSubject.create<Void>()
private val showPledgeNotCancelableDialog = PublishSubject.create<Void>()
private val showShareSheet = PublishSubject.create<Pair<String, String>>()
private val showSavedPrompt = PublishSubject.create<Void>()
private val updatePledgeData = PublishSubject.create<Pair<PledgeData, PledgeReason>>()
private val showUpdatePledge = PublishSubject.create<Triple<PledgeData, PledgeReason, Boolean>>()
private val showUpdatePledgeSuccess = PublishSubject.create<Void>()
private val startRootCommentsActivity = PublishSubject.create<ProjectData>()
private val startRootCommentsForCommentsThreadActivity = PublishSubject.create<Pair<String, ProjectData>>()
private val startLoginToutActivity = PublishSubject.create<Void>()
private val startMessagesActivity = PublishSubject.create<Project>()
private val startProjectUpdateActivity = PublishSubject.create< Pair<Pair<String, Boolean>, Pair<Project, ProjectData>>>()
private val startProjectUpdateToRepliesDeepLinkActivity = PublishSubject.create< Pair<Pair<String, String>, Pair<Project, ProjectData>>>()
private val startThanksActivity = PublishSubject.create<Pair<CheckoutData, PledgeData>>()
private val updateFragments = BehaviorSubject.create<ProjectData>()
private val hideVideoPlayer = BehaviorSubject.create<Boolean>()
private val tabSelected = PublishSubject.create<Int>()
private val projectMedia = PublishSubject.create<MediaElement>()
private val playButtonIsVisible = PublishSubject.create<Boolean>()
private val backingViewGroupIsVisible = PublishSubject.create<Boolean>()
private val updateTabs = PublishSubject.create< Boolean>()
private val onOpenVideoInFullScreen = PublishSubject.create<kotlin.Pair<String, Long>>()
private val updateVideoCloseSeekPosition = BehaviorSubject.create< Long>()
val inputs: Inputs = this
val outputs: Outputs = this
init {
val progressBarIsGone = PublishSubject.create<Boolean>()
val mappedProjectNotification = Observable.merge(
intent(),
intent()
.compose(takeWhen<Intent, Void>(this.reloadProjectContainerClicked))
)
.switchMap {
ProjectIntentMapper.project(it, this.apolloClient)
.doOnSubscribe {
progressBarIsGone.onNext(false)
}
.doAfterTerminate {
progressBarIsGone.onNext(true)
}
.withLatestFrom(currentConfig.observable(), currentUser.observable()) { project, config, user ->
return@withLatestFrom project.updateProjectWith(config, user)
}
.materialize()
}
.share()
activityResult()
.filter { it.isOk }
.filter { it.isRequestCode(ActivityRequestCodes.SHOW_REWARDS) }
.compose(bindToLifecycle())
.subscribe { this.expandPledgeSheet.onNext(Pair(true, true)) }
intent()
.take(1)
.filter { it.getBooleanExtra(IntentKey.EXPAND_PLEDGE_SHEET, false) }
.compose(bindToLifecycle())
.subscribe { this.expandPledgeSheet.onNext(Pair(true, true)) }
val pledgeSheetExpanded = this.expandPledgeSheet
.map { it.first }
.startWith(false)
progressBarIsGone
.compose(bindToLifecycle())
.subscribe(this.retryProgressBarIsGone)
val mappedProjectValues = mappedProjectNotification
.compose(values())
val mappedProjectErrors = mappedProjectNotification
.compose(errors())
mappedProjectValues
.filter { it.displayPrelaunch().isTrue() }
.map { it.webProjectUrl() }
.compose(bindToLifecycle())
.subscribe(this.prelaunchUrl)
val initialProject = mappedProjectValues
.filter {
it.displayPrelaunch().isFalse()
}
// An observable of the ref tag stored in the cookie for the project. Can emit `null`.
val cookieRefTag = initialProject
.take(1)
.map { p -> RefTagUtils.storedCookieRefTagForProject(p, this.cookieManager, this.sharedPreferences) }
val refTag = intent()
.flatMap { ProjectIntentMapper.refTag(it) }
val saveProjectFromDeepLinkActivity = intent()
.take(1)
.delay(3, TimeUnit.SECONDS, environment.scheduler()) // add delay to wait until activity subscribed to viewmodel
.filter {
it.getBooleanExtra(IntentKey.DEEP_LINK_SCREEN_PROJECT_SAVE, false)
}
.flatMap { ProjectIntentMapper.deepLinkSaveFlag(it) }
val saveProjectFromDeepUrl = intent()
.take(1)
.delay(3, TimeUnit.SECONDS, environment.scheduler()) // add delay to wait until activity subscribed to viewmodel
.filter { ObjectUtils.isNotNull(it.data) }
.map { requireNotNull(it.data) }
.filter {
ProjectIntentMapper.hasSaveQueryFromUri(it)
}
.map { UrlUtils.saveFlag(it.toString()) }
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
val loggedInUserOnHeartClick = this.currentUser.observable()
.compose<User>(takeWhen(this.heartButtonClicked))
.filter { u -> u != null }
val loggedOutUserOnHeartClick = this.currentUser.observable()
.compose<User>(takeWhen(this.heartButtonClicked))
.filter { u -> u == null }
val projectOnUserChangeSave = initialProject
.compose(takeWhen<Project, User>(loggedInUserOnHeartClick))
.withLatestFrom(projectData) { initProject, latestProjectData ->
if (latestProjectData.project().isStarred() != initProject.isStarred())
latestProjectData.project()
else
initProject
}
.switchMap {
this.toggleProjectSave(it)
}
.share()
val refreshProjectEvent = Observable.merge(
this.pledgeSuccessfullyCancelled,
this.pledgeSuccessfullyCreated.compose(ignoreValues()),
this.pledgeSuccessfullyUpdated,
this.pledgePaymentSuccessfullyUpdated,
this.refreshProject
)
val refreshedProjectNotification = initialProject
.compose(takeWhen<Project, Void>(refreshProjectEvent))
.switchMap {
it.slug()?.let { slug ->
this.apolloClient.getProject(slug)
.doOnSubscribe {
progressBarIsGone.onNext(false)
}
.doAfterTerminate {
progressBarIsGone.onNext(true)
}
.withLatestFrom(currentConfig.observable(), currentUser.observable()) { project, config, user ->
return@withLatestFrom project.updateProjectWith(config, user)
}
.materialize()
}
}
.share()
loggedOutUserOnHeartClick
.compose(ignoreValues())
.subscribe(this.startLoginToutActivity)
val savedProjectOnLoginSuccess = this.startLoginToutActivity
.compose<Pair<Void, User>>(combineLatestPair(this.currentUser.observable()))
.filter { su -> su.second != null }
.withLatestFrom<Project, Project>(initialProject) { _, p -> p }
.take(1)
.switchMap {
this.saveProject(it)
}
.share()
val projectOnDeepLinkChangeSave = Observable.merge(saveProjectFromDeepLinkActivity, saveProjectFromDeepUrl)
.compose(combineLatestPair(this.currentUser.observable()))
.filter { it.second != null }
.withLatestFrom(initialProject) { userAndFlag, p ->
Pair(userAndFlag, p)
}
.take(1)
.filter {
it.second.isStarred() != it.first.first
}.switchMap {
if (it.first.first) {
this.saveProject(it.second)
} else {
this.unSaveProject(it.second)
}
}.share()
val currentProject = Observable.merge(
initialProject,
refreshedProjectNotification.compose(values()),
projectOnUserChangeSave,
savedProjectOnLoginSuccess,
projectOnDeepLinkChangeSave
)
val projectSavedStatus = Observable.merge(projectOnUserChangeSave, savedProjectOnLoginSuccess, projectOnDeepLinkChangeSave)
projectSavedStatus
.compose(bindToLifecycle())
.subscribe { this.analyticEvents.trackWatchProjectCTA(it, PROJECT) }
projectSavedStatus
.filter { p -> p.isStarred() && p.isLive && !p.isApproachingDeadline }
.compose(ignoreValues())
.compose(bindToLifecycle())
.subscribe(this.showSavedPrompt)
val currentProjectData = Observable.combineLatest<RefTag, RefTag, Project, ProjectData>(refTag, cookieRefTag, currentProject) { refTagFromIntent, refTagFromCookie, project ->
projectData(refTagFromIntent, refTagFromCookie, project)
}
currentProjectData
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe {
this.projectData.onNext(it)
val showEnvironmentalTab = it.project().envCommitments()?.isNotEmpty() ?: false
this.updateTabs.onNext(showEnvironmentalTab)
}
currentProject
.compose<Project>(takeWhen(this.shareButtonClicked))
.map { Pair(it.name(), UrlUtils.appendRefTag(it.webProjectUrl(), RefTag.projectShare().tag())) }
.compose(bindToLifecycle())
.subscribe(this.showShareSheet)
val latestProjectAndProjectData = currentProject.compose<Pair<Project, ProjectData>>(combineLatestPair(projectData))
intent()
.take(1)
.delay(3, TimeUnit.SECONDS, environment.scheduler()) // add delay to wait until activity subscribed to viewmodel
.filter {
it.getBooleanExtra(IntentKey.DEEP_LINK_SCREEN_PROJECT_COMMENT, false) &&
it.getStringExtra(IntentKey.COMMENT)?.isEmpty() ?: true
}
.withLatestFrom(latestProjectAndProjectData) { _, project ->
project
}
.map { it.second }
.compose(bindToLifecycle())
.subscribe {
this.startRootCommentsActivity.onNext(it)
}
intent()
.take(1)
.delay(3, TimeUnit.SECONDS, environment.scheduler()) // add delay to wait until activity subscribed to viewmodel
.filter {
it.getBooleanExtra(IntentKey.DEEP_LINK_SCREEN_PROJECT_COMMENT, false) &&
it.getStringExtra(IntentKey.COMMENT)?.isNotEmpty() ?: false
}
.withLatestFrom(latestProjectAndProjectData) { intent, project ->
Pair(intent.getStringExtra(IntentKey.COMMENT) ?: "", project)
}
.map { Pair(it.first, it.second.second) }
.compose(bindToLifecycle())
.subscribe {
this.startRootCommentsForCommentsThreadActivity.onNext(it)
}
intent()
.take(1)
.delay(3, TimeUnit.SECONDS, environment.scheduler()) // add delay to wait until activity subscribed to viewmodel
.filter {
it.getStringExtra(IntentKey.DEEP_LINK_SCREEN_PROJECT_UPDATE)?.isNotEmpty() ?: false &&
it.getStringExtra(IntentKey.COMMENT)?.isEmpty() ?: true
}.map {
Pair(
requireNotNull(it.getStringExtra(IntentKey.DEEP_LINK_SCREEN_PROJECT_UPDATE)),
it.getBooleanExtra(IntentKey.DEEP_LINK_SCREEN_PROJECT_UPDATE_COMMENT, false)
)
}
.withLatestFrom(latestProjectAndProjectData) { updateId, project ->
Pair(updateId, project)
}
.compose(bindToLifecycle())
.subscribe {
this.startProjectUpdateActivity.onNext(it)
}
intent()
.take(1)
.delay(3, TimeUnit.SECONDS, environment.scheduler()) // add delay to wait until activity subscribed to viewmodel
.filter {
it.getStringExtra(IntentKey.DEEP_LINK_SCREEN_PROJECT_UPDATE)?.isNotEmpty() ?: false &&
it.getStringExtra(IntentKey.COMMENT)?.isNotEmpty() ?: false
}.map {
Pair(
requireNotNull(it.getStringExtra(IntentKey.DEEP_LINK_SCREEN_PROJECT_UPDATE)),
it.getStringExtra(IntentKey.COMMENT) ?: ""
)
}
.withLatestFrom(latestProjectAndProjectData) { updateId, project ->
Pair(updateId, project)
}
.compose(bindToLifecycle())
.subscribe { this.startProjectUpdateToRepliesDeepLinkActivity.onNext(it) }
fullScreenVideoButtonClicked
.compose(bindToLifecycle())
.subscribe(this.onOpenVideoInFullScreen)
closeFullScreenVideo
.compose(bindToLifecycle())
.subscribe {
updateVideoCloseSeekPosition.onNext(it)
}
this.onGlobalLayout
.compose(bindToLifecycle())
.subscribe(this.setInitialRewardPosition)
this.nativeProjectActionButtonClicked
.map { Pair(true, true) }
.compose(bindToLifecycle())
.subscribe(this.expandPledgeSheet)
val fragmentStackCount = this.fragmentStackCount.startWith(0)
fragmentStackCount
.compose(takeWhen(this.pledgeToolbarNavigationClicked))
.filter { it <= 0 }
.map { Pair(false, true) }
.compose(bindToLifecycle())
.subscribe(this.expandPledgeSheet)
fragmentStackCount
.compose<Int>(takeWhen(this.pledgeToolbarNavigationClicked))
.filter { it > 0 }
.compose(ignoreValues())
.compose(bindToLifecycle())
.subscribe(this.goBack)
Observable.merge(this.pledgeSuccessfullyCancelled, this.pledgeSuccessfullyCreated)
.map { Pair(false, false) }
.compose(bindToLifecycle())
.subscribe(this.expandPledgeSheet)
val projectHasRewardsAndSheetCollapsed = currentProject
.map { it.hasRewards() }
.distinctUntilChanged()
.compose<Pair<Boolean, Boolean>>(combineLatestPair(pledgeSheetExpanded))
.filter { it.second.isFalse() }
.map { it.first }
val rewardsLoaded = projectHasRewardsAndSheetCollapsed
.filter { it.isTrue() }
.map { true }
Observable.merge(rewardsLoaded, this.reloadProjectContainerClicked.map { true })
.compose(bindToLifecycle())
.subscribe(this.reloadProjectContainerIsGone)
mappedProjectErrors
.map { false }
.compose(bindToLifecycle())
.subscribe(this.reloadProjectContainerIsGone)
projectHasRewardsAndSheetCollapsed
.compose<Pair<Boolean, Boolean>>(combineLatestPair(this.retryProgressBarIsGone))
.map { (it.first && it.second).negate() }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.pledgeActionButtonContainerIsGone)
val projectData = Observable.combineLatest<RefTag, RefTag, Project, ProjectData>(refTag, cookieRefTag, currentProject) { refTagFromIntent, refTagFromCookie, project -> projectData(refTagFromIntent, refTagFromCookie, project) }
projectData
.filter { it.project().hasRewards() && !it.project().isBacking() }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.updateFragments)
currentProject
.compose<Pair<Project, Int>>(combineLatestPair(fragmentStackCount))
.map { managePledgeMenu(it) }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.managePledgeMenu)
projectData
.compose(takePairWhen(this.tabSelected))
.distinctUntilChanged()
.delay(150, TimeUnit.MILLISECONDS, environment.scheduler()) // add delay to wait
// until fragment subscribed to viewmodel
.subscribe {
this.projectData.onNext(it.first)
}
tabSelected
.map { it != 0 }
.compose(bindToLifecycle())
.subscribe { this.hideVideoPlayer.onNext(it) }
val backedProject = currentProject
.filter { it.isBacking() }
val backing = backedProject
.map { it.backing() }
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
// - Update fragments with the backing data
projectData
.filter { it.project().hasRewards() }
.compose<Pair<ProjectData, Backing>>(combineLatestPair(backing))
.map {
val updatedProject = if (it.first.project().isBacking())
it.first.project().toBuilder().backing(it.second).build()
else it.first.project()
projectData(it.first.refTagFromIntent(), it.first.refTagFromCookie(), updatedProject)
}
.compose(bindToLifecycle())
.subscribe(this.updateFragments)
backedProject
.compose<Project>(takeWhen(this.cancelPledgeClicked))
.filter { (it.backing()?.cancelable() ?: false).isTrue() }
.compose(bindToLifecycle())
.subscribe(this.showCancelPledgeFragment)
backedProject
.compose<Project>(takeWhen(this.cancelPledgeClicked))
.filter { it.backing()?.cancelable().isFalse() }
.compose(ignoreValues())
.compose(bindToLifecycle())
.subscribe(this.showPledgeNotCancelableDialog)
currentProject
.compose<Project>(takeWhen(this.contactCreatorClicked))
.compose(bindToLifecycle())
.subscribe(this.startMessagesActivity)
val projectDataAndBackedReward = projectData
.compose<Pair<ProjectData, Backing>>(combineLatestPair(backing))
.map { pD ->
pD.first.project().backing()?.backedReward(pD.first.project())?.let {
Pair(pD.first.toBuilder().backing(pD.second).build(), it)
}
}
projectDataAndBackedReward
.compose(takeWhen<Pair<ProjectData, Reward>, Void>(this.fixPaymentMethodButtonClicked))
.map { Pair(pledgeData(it.second, it.first, PledgeFlowContext.FIX_ERRORED_PLEDGE), PledgeReason.FIX_PLEDGE) }
.compose(bindToLifecycle())
.subscribe(this.updatePledgeData)
projectDataAndBackedReward
.compose(takeWhen<Pair<ProjectData, Reward>, Void>(this.updatePaymentClicked))
.map { Pair(pledgeData(it.second, it.first, PledgeFlowContext.MANAGE_REWARD), PledgeReason.UPDATE_PAYMENT) }
.compose(bindToLifecycle())
.subscribe {
this.updatePledgeData.onNext(it)
this.analyticEvents.trackChangePaymentMethod(it.first)
}
projectDataAndBackedReward
.compose(takeWhen<Pair<ProjectData, Reward>, Void>(this.updatePledgeClicked))
.map { Pair(pledgeData(it.second, it.first, PledgeFlowContext.MANAGE_REWARD), PledgeReason.UPDATE_PLEDGE) }
.compose(bindToLifecycle())
.subscribe(this.updatePledgeData)
this.viewRewardsClicked
.compose(bindToLifecycle())
.subscribe(this.revealRewardsFragment)
currentProject
.map { it.isBacking() && it.isLive || it.backing()?.isErrored() == true }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.backingDetailsIsVisible)
currentProject
.filter { it.isBacking() }
.map { if (it.backing()?.isErrored() == true) R.string.Payment_failure else R.string.Youre_a_backer }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.backingDetailsTitle)
currentProject
.filter { it.isBacking() }
.map { backingDetailsSubtitle(it) }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.backingDetailsSubtitle)
val currentProjectAndUser = currentProject
.compose<Pair<Project, User>>(combineLatestPair(this.currentUser.observable()))
Observable.combineLatest(currentProjectData, this.currentUser.observable()) { data, user ->
val experimentData = ExperimentData(user, data.refTagFromIntent(), data.refTagFromCookie())
ProjectViewUtils.pledgeActionButtonText(
data.project(),
user,
this.optimizely?.variant(OptimizelyExperiment.Key.PLEDGE_CTA_COPY, experimentData)
)
}
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.pledgeActionButtonText)
currentProject
.compose<Pair<Project, Int>>(combineLatestPair(fragmentStackCount))
.map { if (it.second <= 0) R.drawable.ic_arrow_down else R.drawable.ic_arrow_back }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.pledgeToolbarNavigationIcon)
currentProjectAndUser
.map { ProjectViewUtils.pledgeToolbarTitle(it.first, it.second) }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.pledgeToolbarTitle)
currentProjectAndUser
.map { ProjectViewUtils.pledgeActionButtonColor(it.first, it.second) }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.pledgeActionButtonColor)
this.pledgePaymentSuccessfullyUpdated
.compose(bindToLifecycle())
.subscribe(this.showUpdatePledgeSuccess)
this.pledgeSuccessfullyCancelled
.compose(bindToLifecycle())
.subscribe(this.showCancelPledgeSuccess)
this.pledgeSuccessfullyCreated
.compose(bindToLifecycle())
.subscribe(this.startThanksActivity)
this.pledgeSuccessfullyUpdated
.compose(bindToLifecycle())
.subscribe(this.showUpdatePledgeSuccess)
this.fragmentStackCount
.compose<Pair<Int, Project>>(combineLatestPair(currentProject))
.map { if (it.second.isBacking()) it.first > 4 else it.first > 3 }
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe(this.scrimIsVisible)
currentProject
.map { p -> if (p.isStarred()) R.drawable.icon__heart else R.drawable.icon__heart_outline }
.subscribe(this.heartDrawableId)
val projectPhoto = currentProject
.map { it.photo()?.full() }
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
val projectVideo = currentProject.map { it.video() }
.map { it?.hls() ?: it?.high() }
.distinctUntilChanged()
.take(1)
projectPhoto
.compose(combineLatestPair(projectVideo))
.compose(bindToLifecycle())
.subscribe {
this.projectMedia.onNext(MediaElement(VideoModelElement(it.second), it.first))
}
currentProject
.map { it.hasVideo() }
.subscribe(this.playButtonIsVisible)
// Tracking
val currentFullProjectData = currentProjectData
.filter { it.project().hasRewards() }
val fullProjectDataAndCurrentUser = currentFullProjectData
.compose<Pair<ProjectData, User?>>(combineLatestPair(this.currentUser.observable()))
val fullProjectDataAndPledgeFlowContext = fullProjectDataAndCurrentUser
.map { Pair(it.first, pledgeFlowContext(it.first.project(), it.second)) }
fullProjectDataAndPledgeFlowContext
.take(1)
.compose(bindToLifecycle())
.subscribe { projectDataAndPledgeFlowContext ->
val data = projectDataAndPledgeFlowContext.first
val pledgeFlowContext = projectDataAndPledgeFlowContext.second
// If a cookie hasn't been set for this ref+project then do so.
if (data.refTagFromCookie() == null) {
data.refTagFromIntent()?.let { RefTagUtils.storeCookie(it, data.project(), this.cookieManager, this.sharedPreferences) }
}
val dataWithStoredCookieRefTag = storeCurrentCookieRefTag(data)
this.analyticEvents.trackProjectScreenViewed(dataWithStoredCookieRefTag, OVERVIEW.contextName)
}
fullProjectDataAndPledgeFlowContext
.map { it.first }
.take(1)
.compose(takePairWhen(this.tabSelected))
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe {
this.analyticEvents.trackProjectPageTabChanged(it.first, getSelectedTabContextName(it.second))
}
fullProjectDataAndPledgeFlowContext
.compose<Pair<ProjectData, PledgeFlowContext?>>(takeWhen(this.nativeProjectActionButtonClicked))
.filter { it.first.project().isLive && !it.first.project().isBacking() }
.compose(bindToLifecycle())
.subscribe {
this.analyticEvents.trackPledgeInitiateCTA(it.first)
}
currentProject
.map { it.metadataForProject() }
.map { ProjectMetadata.BACKING == it }
.compose(bindToLifecycle())
.subscribe(backingViewGroupIsVisible)
ShowPledgeFragmentUseCase(this.updatePledgeData)
.data(currentUser.observable(), this.optimizely)
.compose(bindToLifecycle())
.subscribe {
this.showUpdatePledge.onNext(it)
}
onVideoPlayButtonClicked
.distinctUntilChanged()
.compose(bindToLifecycle())
.subscribe {
backingViewGroupIsVisible.onNext(false)
}
}
private fun getSelectedTabContextName(selectedTabIndex: Int): String = when (selectedTabIndex) {
ProjectPagerTabs.OVERVIEW.ordinal -> OVERVIEW.contextName
ProjectPagerTabs.CAMPAIGN.ordinal -> CAMPAIGN.contextName
ProjectPagerTabs.FAQS.ordinal -> FAQS.contextName
ProjectPagerTabs.RISKS.ordinal -> RISKS.contextName
ProjectPagerTabs.ENVIRONMENTAL_COMMITMENT.ordinal -> ENVIRONMENT.contextName
else -> OVERVIEW.contextName
}
private fun managePledgeMenu(projectAndFragmentStackCount: Pair<Project, Int>): Int? {
val project = projectAndFragmentStackCount.first
val count = projectAndFragmentStackCount.second
return when {
!project.isBacking() || count.isNonZero() -> null
project.isLive -> when {
project.backing()?.status() == Backing.STATUS_PREAUTH -> R.menu.manage_pledge_preauth
else -> R.menu.manage_pledge_live
}
else -> R.menu.manage_pledge_ended
}
}
private fun pledgeData(reward: Reward, projectData: ProjectData, pledgeFlowContext: PledgeFlowContext): PledgeData {
return PledgeData.with(pledgeFlowContext, projectData, reward)
}
private fun pledgeFlowContext(project: Project, currentUser: User?): PledgeFlowContext? {
return when {
project.userIsCreator(currentUser) -> null
project.isLive && !project.isBacking() -> PledgeFlowContext.NEW_PLEDGE
!project.isLive && project.backing()?.isErrored() ?: false -> PledgeFlowContext.FIX_ERRORED_PLEDGE
else -> null
}
}
private fun projectData(refTagFromIntent: RefTag?, refTagFromCookie: RefTag?, project: Project): ProjectData {
return ProjectData
.builder()
.refTagFromIntent(refTagFromIntent)
.refTagFromCookie(refTagFromCookie)
.project(project)
.build()
}
private fun storeCurrentCookieRefTag(data: ProjectData): ProjectData {
return data
.toBuilder()
.refTagFromCookie(RefTagUtils.storedCookieRefTagForProject(data.project(), cookieManager, sharedPreferences))
.build()
}
override fun tabSelected(position: Int) {
this.tabSelected.onNext(position)
}
override fun cancelPledgeClicked() {
this.cancelPledgeClicked.onNext(null)
}
override fun commentsTextViewClicked() {
this.commentsTextViewClicked.onNext(null)
}
override fun contactCreatorClicked() {
this.contactCreatorClicked.onNext(null)
}
override fun fixPaymentMethodButtonClicked() {
this.fixPaymentMethodButtonClicked.onNext(null)
}
override fun fragmentStackCount(count: Int) {
this.fragmentStackCount.onNext(count)
}
override fun heartButtonClicked() {
this.heartButtonClicked.onNext(null)
}
override fun nativeProjectActionButtonClicked() {
this.nativeProjectActionButtonClicked.onNext(null)
}
override fun onGlobalLayout() {
this.onGlobalLayout.onNext(null)
}
override fun pledgePaymentSuccessfullyUpdated() {
this.pledgePaymentSuccessfullyUpdated.onNext(null)
}
override fun pledgeSuccessfullyCancelled() {
this.pledgeSuccessfullyCancelled.onNext(null)
}
override fun pledgeSuccessfullyCreated(checkoutDataAndPledgeData: Pair<CheckoutData, PledgeData>) {
this.pledgeSuccessfullyCreated.onNext(checkoutDataAndPledgeData)
}
override fun pledgeSuccessfullyUpdated() {
this.pledgeSuccessfullyUpdated.onNext(null)
}
override fun pledgeToolbarNavigationClicked() {
this.pledgeToolbarNavigationClicked.onNext(null)
}
override fun refreshProject() {
this.refreshProject.onNext(null)
}
override fun reloadProjectContainerClicked() {
this.reloadProjectContainerClicked.onNext(null)
}
override fun shareButtonClicked() {
this.shareButtonClicked.onNext(null)
}
override fun updatePaymentClicked() {
this.updatePaymentClicked.onNext(null)
}
override fun updatePledgeClicked() {
this.updatePledgeClicked.onNext(null)
}
override fun updatesTextViewClicked() {
this.updatesTextViewClicked.onNext(null)
}
override fun viewRewardsClicked() {
this.viewRewardsClicked.onNext(null)
}
override fun fullScreenVideoButtonClicked(videoInfo: kotlin.Pair<String, Long>) {
fullScreenVideoButtonClicked.onNext(videoInfo)
}
override fun closeFullScreenVideo(position: Long) = closeFullScreenVideo.onNext(position)
override fun onVideoPlayButtonClicked() = onVideoPlayButtonClicked.onNext(null)
override fun updateVideoCloseSeekPosition(): Observable< Long> =
updateVideoCloseSeekPosition
@NonNull
override fun backingDetailsSubtitle(): Observable<Either<String, Int>?> = this.backingDetailsSubtitle
@NonNull
override fun backingDetailsTitle(): Observable<Int> = this.backingDetailsTitle
@NonNull
override fun backingDetailsIsVisible(): Observable<Boolean> = this.backingDetailsIsVisible
@NonNull
override fun expandPledgeSheet(): Observable<Pair<Boolean, Boolean>> = this.expandPledgeSheet
@NonNull
override fun goBack(): Observable<Void> = this.goBack
@NonNull
override fun heartDrawableId(): Observable<Int> = this.heartDrawableId
@NonNull
override fun managePledgeMenu(): Observable<Int?> = this.managePledgeMenu
@NonNull
override fun pledgeActionButtonColor(): Observable<Int> = this.pledgeActionButtonColor
@NonNull
override fun pledgeActionButtonContainerIsGone(): Observable<Boolean> = this.pledgeActionButtonContainerIsGone
@NonNull
override fun pledgeActionButtonText(): Observable<Int> = this.pledgeActionButtonText
@NonNull
override fun pledgeToolbarNavigationIcon(): Observable<Int> = this.pledgeToolbarNavigationIcon
@NonNull
override fun pledgeToolbarTitle(): Observable<Int> = this.pledgeToolbarTitle
@NonNull
override fun prelaunchUrl(): Observable<String> = this.prelaunchUrl
@NonNull
override fun projectData(): Observable<ProjectData> = this.projectData
@NonNull
override fun reloadProjectContainerIsGone(): Observable<Boolean> = this.reloadProjectContainerIsGone
@NonNull
override fun reloadProgressBarIsGone(): Observable<Boolean> = this.retryProgressBarIsGone
@NonNull
override fun revealRewardsFragment(): Observable<Void> = this.revealRewardsFragment
@NonNull
override fun scrimIsVisible(): Observable<Boolean> = this.scrimIsVisible
@NonNull
override fun setInitialRewardsContainerY(): Observable<Void> = this.setInitialRewardPosition
@NonNull
override fun showCancelPledgeFragment(): Observable<Project> = this.showCancelPledgeFragment
@NonNull
override fun showCancelPledgeSuccess(): Observable<Void> = this.showCancelPledgeSuccess
@NonNull
override fun showPledgeNotCancelableDialog(): Observable<Void> = this.showPledgeNotCancelableDialog
@NonNull
override fun showSavedPrompt(): Observable<Void> = this.showSavedPrompt
@NonNull
override fun showShareSheet(): Observable<Pair<String, String>> = this.showShareSheet
@NonNull
override fun showUpdatePledge(): Observable<Triple<PledgeData, PledgeReason, Boolean>> = this.showUpdatePledge
@NonNull
override fun showUpdatePledgeSuccess(): Observable<Void> = this.showUpdatePledgeSuccess
@NonNull
override fun startRootCommentsActivity(): Observable<ProjectData> = this.startRootCommentsActivity
@NonNull
override fun startRootCommentsForCommentsThreadActivity(): Observable<Pair<String, ProjectData>> =
this.startRootCommentsForCommentsThreadActivity
@NonNull
override fun startLoginToutActivity(): Observable<Void> = this.startLoginToutActivity
@NonNull
override fun startMessagesActivity(): Observable<Project> = this.startMessagesActivity
@NonNull
override fun startThanksActivity(): Observable<Pair<CheckoutData, PledgeData>> = this.startThanksActivity
@NonNull
override fun startProjectUpdateActivity(): Observable<Pair<Pair<String, Boolean>, Pair<Project, ProjectData>>> = this.startProjectUpdateActivity
@NonNull
override fun startProjectUpdateToRepliesDeepLinkActivity(): Observable<Pair<Pair<String, String>, Pair<Project, ProjectData>>> =
this.startProjectUpdateToRepliesDeepLinkActivity
@NonNull
override fun onOpenVideoInFullScreen(): Observable<kotlin.Pair<String, Long>> = this.onOpenVideoInFullScreen
@NonNull
override fun updateTabs(): Observable<Boolean> = this.updateTabs
@NonNull
override fun hideVideoPlayer(): Observable<Boolean> = this.hideVideoPlayer
@NonNull
override fun updateFragments(): Observable<ProjectData> = this.updateFragments
@NonNull
override fun projectMedia(): Observable<MediaElement> = this.projectMedia
@NonNull
override fun playButtonIsVisible(): Observable<Boolean> = this.playButtonIsVisible
@NonNull
override fun backingViewGroupIsVisible(): Observable<Boolean> = this.backingViewGroupIsVisible
private fun backingDetailsSubtitle(project: Project): Either<String, Int>? {
return project.backing()?.let { backing ->
return if (backing.status() == Backing.STATUS_ERRORED) {
Either.Right(R.string.We_cant_process_your_pledge)
} else {
val reward = project.rewards()?.firstOrNull { it.id() == backing.rewardId() }
val title = reward?.let { "• ${it.title()}" } ?: ""
val backingAmount = backing.amount()
val formattedAmount = this.ksCurrency.format(backingAmount, project, RoundingMode.HALF_UP)
Either.Left("$formattedAmount $title".trim())
}
}
}
private fun saveProject(project: Project): Observable<Project> {
return this.apolloClient.watchProject(project)
.compose(neverError())
}
private fun unSaveProject(project: Project): Observable<Project> {
return this.apolloClient.unWatchProject(project).compose(neverError())
}
private fun toggleProjectSave(project: Project): Observable<Project> {
return if (project.isStarred())
unSaveProject(project)
else
saveProject(project)
}
}
}
| apache-2.0 | 800ad6467e857abba0784045fabf2d6b | 43.809865 | 238 | 0.627703 | 5.830849 | false | false | false | false |
tensorflow/examples | lite/examples/model_personalization/android/app/src/main/java/org/tensorflow/lite/examples/modelpersonalization/fragments/SettingFragment.kt | 1 | 3307 | /*
* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.tensorflow.lite.examples.modelpersonalization.fragments
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import org.tensorflow.lite.examples.modelpersonalization.MainViewModel
import org.tensorflow.lite.examples.modelpersonalization.databinding.FragmentSettingBinding
class SettingFragment : DialogFragment() {
companion object {
const val TAG = "SettingDialogFragment"
}
private var _fragmentSettingBinding: FragmentSettingBinding? = null
private val fragmentSettingBinding
get() = _fragmentSettingBinding!!
private var numThreads = 2
private val viewModel: MainViewModel by activityViewModels()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return super.onCreateDialog(savedInstanceState).apply {
setCancelable(false)
setCanceledOnTouchOutside(false)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_fragmentSettingBinding = FragmentSettingBinding.inflate(
inflater,
container,
false
)
return fragmentSettingBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.getNumThreads()?.let {
numThreads = it
updateDialogUi()
}
initDialogControls()
fragmentSettingBinding.btnConfirm.setOnClickListener {
viewModel.configModel(numThreads)
dismiss()
}
fragmentSettingBinding.btnCancel.setOnClickListener {
dismiss()
}
}
private fun initDialogControls() {
// When clicked, decrease the number of threads used for classification
fragmentSettingBinding.threadsMinus.setOnClickListener {
if (numThreads > 1) {
numThreads--
updateDialogUi()
}
}
// When clicked, increase the number of threads used for classification
fragmentSettingBinding.threadsPlus.setOnClickListener {
if (numThreads < 4) {
numThreads++
updateDialogUi()
}
}
}
// Update the values displayed in the dialog.
private fun updateDialogUi() {
fragmentSettingBinding.threadsValue.text =
numThreads.toString()
}
}
| apache-2.0 | e8235370eeed056d174010d0ae6245e8 | 30.495238 | 91 | 0.676746 | 5.557983 | false | false | false | false |
jotomo/AndroidAPS | app/src/test/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_CarbohydrateTest.kt | 1 | 903 | package info.nightscout.androidaps.danars.comm
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
class DanaRS_Packet_History_CarbohydrateTest : DanaRSTestBase() {
private val packetInjector = HasAndroidInjector {
AndroidInjector {
if (it is DanaRS_Packet) {
it.aapsLogger = aapsLogger
it.dateUtil = dateUtil
}
if (it is DanaRS_Packet_History_Carbohydrate) {
it.rxBus = rxBus
}
}
}
@Test fun runTest() {
val packet = DanaRS_Packet_History_Carbohydrate(packetInjector, System.currentTimeMillis())
Assert.assertEquals("REVIEW__CARBOHYDRATE", packet.friendlyName)
}
} | agpl-3.0 | 2b930460ba226ae9adfec89f44662f72 | 30.172414 | 99 | 0.678848 | 4.777778 | false | true | false | false |
jotomo/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Missed_Bolus_Alarm.kt | 1 | 1622 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.danars.encryption.BleEncryption
class DanaRS_Packet_Notify_Missed_Bolus_Alarm(
injector: HasAndroidInjector
) : DanaRS_Packet(injector) {
init {
type = BleEncryption.DANAR_PACKET__TYPE_NOTIFY
opCode = BleEncryption.DANAR_PACKET__OPCODE_NOTIFY__MISSED_BOLUS_ALARM
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
val startHour: Int
val startMin: Int
val endHour: Int
val endMin: Int
var dataIndex = DATA_START
var dataSize = 1
startHour = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 1
startMin = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 1
endHour = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 1
endMin = byteArrayToInt(getBytes(data, dataIndex, dataSize))
failed = endMin == 1 && endMin == endHour && startHour == endHour && startHour == startMin
aapsLogger.debug(LTag.PUMPCOMM, "Start hour: $startHour")
aapsLogger.debug(LTag.PUMPCOMM, "Start min: $startMin")
aapsLogger.debug(LTag.PUMPCOMM, "End hour: $endHour")
aapsLogger.debug(LTag.PUMPCOMM, "End min: $endMin")
}
override fun getFriendlyName(): String {
return "NOTIFY__MISSED_BOLUS_ALARM"
}
} | agpl-3.0 | 2fab25effc6ef821f62ae79441e2ea62 | 35.886364 | 98 | 0.672626 | 4.518106 | false | false | false | false |
ingokegel/intellij-community | plugins/git4idea/src/git4idea/log/GitCommitSignatureStatusProvider.kt | 9 | 5053 | // 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 git4idea.log
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.ui.ColorUtil
import com.intellij.util.ui.EmptyIcon
import com.intellij.util.ui.UIUtil
import com.intellij.vcs.log.data.util.VcsCommitsDataLoader
import com.intellij.vcs.log.ui.frame.VcsCommitExternalStatusPresentation
import com.intellij.vcs.log.ui.frame.VcsCommitExternalStatusProvider
import com.intellij.vcs.log.ui.table.column.util.VcsLogExternalStatusColumnService
import git4idea.GitIcons
import git4idea.commit.signature.GitCommitSignature
import git4idea.i18n.GitBundle
import org.jetbrains.annotations.Nls
import javax.swing.Icon
internal class GitCommitSignatureStatusProvider : VcsCommitExternalStatusProvider.WithColumn<GitCommitSignature>() {
override val id = ID
override val isColumnEnabledByDefault = false
override val columnName = GitBundle.message("column.name.commit.signature")
override fun createLoader(project: Project): VcsCommitsDataLoader<GitCommitSignature> {
val loader = if (SystemInfo.isWindows) NonCancellableGitCommitSignatureLoader(project)
else SimpleGitCommitSignatureLoader(project)
return service<GitCommitSignatureLoaderSharedCache>().wrapWithCaching(loader)
}
override fun getPresentation(project: Project, status: GitCommitSignature): VcsCommitExternalStatusPresentation.Signature =
GitCommitSignatureStatusPresentation(status)
override fun getExternalStatusColumnService() = service<GitCommitSignatureColumnService>()
override fun getStubStatus() = GitCommitSignature.NoSignature
companion object {
private const val ID = "Git.CommitSignature"
private class GitCommitSignatureStatusPresentation(private val signature: GitCommitSignature)
: VcsCommitExternalStatusPresentation.Signature {
override val icon: Icon
get() = when (signature) {
is GitCommitSignature.Verified -> GitIcons.Verified
is GitCommitSignature.NotVerified -> GitIcons.Signed
GitCommitSignature.Bad -> GitIcons.Signed
GitCommitSignature.NoSignature -> EmptyIcon.ICON_16
}
override val text: String
get() = when (signature) {
is GitCommitSignature.Verified -> GitBundle.message("commit.signature.verified")
is GitCommitSignature.NotVerified -> GitBundle.message("commit.signature.unverified")
GitCommitSignature.Bad -> GitBundle.message("commit.signature.bad")
GitCommitSignature.NoSignature -> GitBundle.message("commit.signature.none")
}
override val description: HtmlChunk?
get() = when (signature) {
is GitCommitSignature.Verified -> HtmlBuilder()
.append(GitBundle.message("commit.signature.verified")).br()
.br()
.append(HtmlBuilder()
.append(GitBundle.message("commit.signature.fingerprint")).br()
.append(signature.fingerprint).br()
.br()
.append(GitBundle.message("commit.signature.signed.by")).br()
.append(signature.user)
.wrapWith(HtmlChunk.span("color: ${ColorUtil.toHtmlColor(UIUtil.getContextHelpForeground())}")))
.toFragment()
is GitCommitSignature.NotVerified -> HtmlBuilder()
.append(GitBundle.message("commit.signature.unverified.with.reason", getUnverifiedReason(signature.reason)))
.toFragment()
GitCommitSignature.Bad -> HtmlChunk.text(GitBundle.message("commit.signature.bad"))
GitCommitSignature.NoSignature -> null
}
private fun getUnverifiedReason(reason: GitCommitSignature.VerificationFailureReason): @Nls String {
return when (reason) {
GitCommitSignature.VerificationFailureReason.UNKNOWN -> GitBundle.message("commit.signature.unverified.reason.unknown")
GitCommitSignature.VerificationFailureReason.EXPIRED -> GitBundle.message("commit.signature.unverified.reason.expired")
GitCommitSignature.VerificationFailureReason.EXPIRED_KEY -> GitBundle.message("commit.signature.unverified.reason.expired.key")
GitCommitSignature.VerificationFailureReason.REVOKED_KEY -> GitBundle.message("commit.signature.unverified.reason.revoked.key")
GitCommitSignature.VerificationFailureReason.CANNOT_VERIFY -> GitBundle.message("commit.signature.unverified.reason.cannot.verify")
}
}
}
}
}
@Service
internal class GitCommitSignatureColumnService : VcsLogExternalStatusColumnService<GitCommitSignature>() {
override fun getDataLoader(project: Project) = GitCommitSignatureStatusProvider().createLoader(project)
} | apache-2.0 | 3a58aa3da7c6df52ba12d37cee7d04a5 | 49.039604 | 158 | 0.746883 | 5.171955 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/coroutines/DirectUseOfResultTypeInspection.kt | 1 | 4317 | // 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.coroutines
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.types.KotlinType
class DirectUseOfResultTypeInspection : AbstractIsResultInspection(
typeShortName = SHORT_NAME,
typeFullName = "kotlin.Result",
allowedSuffix = CATCHING,
allowedNames = setOf("success", "failure", "runCatching"),
suggestedFunctionNameToCall = "getOrThrow"
) {
private fun MemberScope.hasCorrespondingNonCatchingFunction(
nameWithoutCatching: String,
valueParameters: List<ValueParameterDescriptor>,
returnType: KotlinType?,
extensionReceiverType: KotlinType?
): Boolean {
val nonCatchingFunctions = getContributedFunctions(Name.identifier(nameWithoutCatching), NoLookupLocation.FROM_IDE)
return nonCatchingFunctions.any { nonCatchingFun ->
nonCatchingFun.valueParameters.size == valueParameters.size
&& nonCatchingFun.returnType == returnType
&& nonCatchingFun.extensionReceiverParameter?.type == extensionReceiverType
}
}
private fun FunctionDescriptor.hasCorrespondingNonCatchingFunction(returnType: KotlinType, nameWithoutCatching: String): Boolean? {
val scope = when (val containingDescriptor = containingDeclaration) {
is ClassDescriptor -> containingDescriptor.unsubstitutedMemberScope
is PackageFragmentDescriptor -> containingDescriptor.getMemberScope()
else -> return null
}
val returnTypeArgument = returnType.arguments.firstOrNull()?.type
val extensionReceiverType = extensionReceiverParameter?.type
if (scope.hasCorrespondingNonCatchingFunction(nameWithoutCatching, valueParameters, returnTypeArgument, extensionReceiverType)) {
return true
}
if (extensionReceiverType != null) {
val extensionClassDescriptor = extensionReceiverType.constructor.declarationDescriptor as? ClassDescriptor
if (extensionClassDescriptor != null) {
val extensionClassScope = extensionClassDescriptor.unsubstitutedMemberScope
if (extensionClassScope.hasCorrespondingNonCatchingFunction(
nameWithoutCatching, valueParameters, returnTypeArgument, extensionReceiverType = null
)
) {
return true
}
}
}
return false
}
override fun analyzeFunctionWithAllowedSuffix(
name: String,
descriptor: FunctionDescriptor,
toReport: PsiElement,
holder: ProblemsHolder
) {
val returnType = descriptor.returnType ?: return
val nameWithoutCatching = name.substringBeforeLast(CATCHING)
if (descriptor.hasCorrespondingNonCatchingFunction(returnType, nameWithoutCatching) == false) {
val returnTypeArgument = returnType.arguments.firstOrNull()?.type
val typeName = returnTypeArgument?.constructor?.declarationDescriptor?.name?.asString() ?: "T"
holder.registerProblem(
toReport,
KotlinBundle.message(
"function.0.returning.1.without.the.corresponding",
name,
"$SHORT_NAME<$typeName>",
nameWithoutCatching,
typeName
),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
)
}
}
}
private const val SHORT_NAME = "Result"
private const val CATCHING = "Catching"
| apache-2.0 | d4ca55f6641553fa3f312717ea6b9a18 | 44.925532 | 158 | 0.69956 | 6.046218 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-telemetry/src/main/kotlin/slatekit/telemetry/MetricsLite.kt | 1 | 3734 | package slatekit.telemetry
import org.threeten.bp.Instant
import org.threeten.bp.ZonedDateTime
import slatekit.common.ext.durationFrom
import slatekit.common.Identity
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.atomic.AtomicReference
/**
* Simple / Light-Weight implementation of the Metric interface for quick/in-memory purposes.
*
* NOTES:
* 1. There is a provider/wrapper for https://micrometer.io/ available in the slatekit.providers
* 2. If you are already using micro-meter, then use the wrapper above.
* 3. SlateKit custom diagnostics components ( Calls, Counters, Events, Lasts ) are orthogonal to metrics
* 4. SlateKit has its own ( just a few ) diagnostic level components like Calls/Counters/Events/Lasts
* that are not available in other metrics libraries. These are specifically designed to work with
* the Result<T, E> component in @see[slatekit.results.Result] for counting/tracking successes/failures
*
*/
class MetricsLite(
override val id: Identity,
val tags:List<Tag> = listOf(),
override val source: String = "slatekit",
override val settings: MetricsSettings = MetricsSettings(true, true, Tags(tags))
) : Metrics {
private val counters = mutableMapOf<String, Counter>()
private val gauges = mutableMapOf<String, Gauge<*>>()
private val timers = mutableMapOf<String, Timer>()
/**
* The provider of the metrics ( Micrometer for now )
*/
override val provider: Any = this
override fun total(name: String): Double {
return getOrCreate(name, counters) { Counter(globals(), null) }.get().toDouble()
}
/**
* Increment a counter
*/
override fun count(name: String, tags: List<String>?) {
getOrCreate(name, counters) { Counter(globals(), tags) }.inc()
}
/**
* Set value on a gauge
*/
override fun <T> gauge(name: String, call: () -> T, tags: List<Tag>?) where T: kotlin.Number {
getOrCreate(name, gauges) { Gauge(globals(), call, tags, 10) }
}
/**
* Set value on a gauge
*/
override fun <T> gauge(name: String, value:T) where T: kotlin.Number {
gauges[name]?.let{ (it as Gauge<T>).set(value) }
}
/**
* Times an event
*/
override fun time(name: String, tags: List<String>?, call:() -> Unit ) {
getOrCreate(name, timers) { Timer(globals(), tags) }.record(call)
}
val emptyGlobals = listOf<Tag>()
private fun globals(): List<Tag> {
return if (settings.standardize) settings.tags.global else emptyGlobals
}
private fun <T> getOrCreate(name:String, map:MutableMap<String, T>, creator:() -> T): T {
return if(map.containsKey(name)){
map[name]!!
} else {
val item = creator()
map[name] = item
item
}
}
/**
* Simple timer
*/
data class Timer(override val tags: List<Tag>, val customTags:List<String>? = null) : Tagged {
private val last = AtomicReference<Record>()
private val value = AtomicLong(0L)
fun record(call:() -> Unit ) {
val start = ZonedDateTime.now()
call()
val end = ZonedDateTime.now()
val diffMs = end.durationFrom(start).toMillis()
last.set(Record(start.toInstant(), end.toInstant(), diffMs))
value.incrementAndGet()
}
data class Record(val start: Instant, val end: Instant, val diffMs:Long)
}
companion object {
fun build(id: Identity, tags:List<Tag> = listOf()): MetricsLite {
return MetricsLite(id, tags, settings = MetricsSettings(true, true, Tags(listOf())))
}
}
}
| apache-2.0 | cbdfb9c204a1f051fad6b2e36994e7e4 | 29.357724 | 106 | 0.629352 | 4.172067 | false | false | false | false |
siosio/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesTable.kt | 1 | 18313 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages
import com.intellij.ide.CopyProvider
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.project.Project
import com.intellij.ui.SpeedSearchComparator
import com.intellij.ui.TableSpeedSearch
import com.intellij.ui.TableUtil
import com.intellij.ui.table.JBTable
import com.intellij.util.ui.UIUtil
import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration
import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.OperationExecutor
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.SelectedPackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperationFactory
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.ActionsColumn
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.NameColumn
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.ScopeColumn
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.VersionColumn
import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint
import com.jetbrains.packagesearch.intellij.plugin.ui.util.Displayable
import com.jetbrains.packagesearch.intellij.plugin.ui.util.autosizeColumnsAt
import com.jetbrains.packagesearch.intellij.plugin.ui.util.onMouseMotion
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.util.AppUI
import com.jetbrains.packagesearch.intellij.plugin.util.TraceInfo
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.awt.Dimension
import java.awt.KeyboardFocusManager
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.awt.event.FocusAdapter
import java.awt.event.FocusEvent
import javax.swing.ListSelectionModel
import javax.swing.event.ListSelectionListener
import javax.swing.table.DefaultTableCellRenderer
import javax.swing.table.TableCellEditor
import javax.swing.table.TableCellRenderer
import javax.swing.table.TableColumn
import kotlin.math.roundToInt
internal typealias SelectedPackageModelListener = (SelectedPackageModel<*>?) -> Unit
@Suppress("MagicNumber") // Swing dimension constants
internal class PackagesTable(
project: Project,
private val operationExecutor: OperationExecutor,
operationFactory: PackageSearchOperationFactory,
private val onItemSelectionChanged: SelectedPackageModelListener
) : JBTable(), CopyProvider, DataProvider, Displayable<PackagesTable.ViewModel> {
private val operationFactory = PackageSearchOperationFactory()
private val tableModel: PackagesTableModel
get() = model as PackagesTableModel
private var selectedPackage: SelectedPackageModel<*>? = null
var transferFocusUp: () -> Unit = { transferFocusBackward() }
private val columnWeights = listOf(
.5f, // Name column
.2f, // Scope column
.2f, // Version column
.1f // Actions column
)
private val nameColumn = NameColumn()
private val scopeColumn = ScopeColumn { packageModel, newScope -> updatePackageScope(packageModel, newScope) }
private val versionColumn = VersionColumn { packageModel, newVersion ->
updatePackageVersion(packageModel, newVersion)
}
private val actionsColumn = ActionsColumn(
operationExecutor = ::executeUpdateActionColumnOperations,
operationFactory = operationFactory
)
private val actionsColumnIndex: Int
private val autosizingColumnsIndices: List<Int>
private var targetModules: TargetModules = TargetModules.None
private var knownRepositoriesInTargetModules = KnownRepositories.InTargetModules.EMPTY
private var allKnownRepositories = KnownRepositories.All.EMPTY
private val listSelectionListener = ListSelectionListener {
val item = getSelectedTableItem()
if (selectedIndex >= 0 && item != null) {
TableUtil.scrollSelectionToVisible(this)
updateAndRepaint()
selectedPackage = item.toSelectedPackageModule()
onItemSelectionChanged(selectedPackage)
PackageSearchEventsLogger.logPackageSelected(item is PackagesTableItem.InstalledPackage)
} else {
selectedPackage = null
}
}
val hasInstalledItems: Boolean
get() = tableModel.items.any { it is PackagesTableItem.InstalledPackage }
val firstPackageIndex: Int
get() = tableModel.items.indexOfFirst { it is PackagesTableItem.InstalledPackage }
var selectedIndex: Int
get() = selectedRow
set(value) {
if (tableModel.items.isNotEmpty() && (0 until tableModel.items.count()).contains(value)) {
setRowSelectionInterval(value, value)
} else {
clearSelection()
}
}
init {
require(columnWeights.sum() == 1.0f) { "The column weights must sum to 1.0" }
model = PackagesTableModel(
onlyStable = PackageSearchGeneralConfiguration.getInstance(project).onlyStable,
columns = arrayOf(nameColumn, scopeColumn, versionColumn, actionsColumn)
)
val columnInfos = tableModel.columnInfos
actionsColumnIndex = columnInfos.indexOf(actionsColumn)
autosizingColumnsIndices = listOf(
columnInfos.indexOf(scopeColumn),
columnInfos.indexOf(versionColumn),
actionsColumnIndex
)
setTableHeader(InvisibleResizableHeader())
getTableHeader().apply {
reorderingAllowed = false
resizingAllowed = true
}
columnSelectionAllowed = false
setShowGrid(false)
rowHeight = 20.scaled()
background = UIUtil.getTableBackground()
foreground = UIUtil.getTableForeground()
selectionBackground = UIUtil.getTableSelectionBackground(true)
selectionForeground = UIUtil.getTableSelectionForeground(true)
setExpandableItemsEnabled(false)
selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION
putClientProperty("terminateEditOnFocusLost", true)
intercellSpacing = Dimension(0, 2)
// By default, JTable uses Tab/Shift-Tab for navigation between cells; Ctrl-Tab/Ctrl-Shift-Tab allows to break out of the JTable.
// In this table, we don't want to navigate between cells - so override the traversal keys by default values.
setFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS)
)
setFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS)
)
addFocusListener(object : FocusAdapter() {
override fun focusGained(e: FocusEvent?) {
if (tableModel.rowCount > 0 && selectedRows.isEmpty()) {
setRowSelectionInterval(0, 0)
}
}
})
PackageSearchUI.overrideKeyStroke(this, "jtable:RIGHT", "RIGHT") { transferFocus() }
PackageSearchUI.overrideKeyStroke(this, "jtable:ENTER", "ENTER") { transferFocus() }
PackageSearchUI.overrideKeyStroke(this, "shift ENTER") {
clearSelection()
transferFocusUp()
}
selectionModel.addListSelectionListener(listSelectionListener)
addFocusListener(object : FocusAdapter() {
override fun focusGained(e: FocusEvent?) {
if (selectedIndex == -1) {
selectedIndex = firstPackageIndex
}
}
})
TableSpeedSearch(this) { item, _ ->
if (item is PackagesTableItem.InstalledPackage) {
item.packageModel.identifier
} else {
""
}
}.apply {
comparator = SpeedSearchComparator(false)
}
addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
applyColumnSizes(columnModel.totalColumnWidth, columnModel.columns.toList(), columnWeights)
removeComponentListener(this)
}
})
onMouseMotion(
onMouseMoved = {
val point = it.point
val hoverColumn = columnAtPoint(point)
val hoverRow = rowAtPoint(point)
if (tableModel.items.isEmpty() || !(0 until tableModel.items.count()).contains(hoverColumn)) {
actionsColumn.hoverItem = null
return@onMouseMotion
}
val item = tableModel.items[hoverRow]
if (actionsColumn.hoverItem != item && hoverColumn == actionsColumnIndex) {
actionsColumn.hoverItem = item
updateAndRepaint()
} else {
actionsColumn.hoverItem = null
}
}
)
}
override fun getCellRenderer(row: Int, column: Int): TableCellRenderer =
tableModel.columns[column].getRenderer(tableModel.items[row]) ?: DefaultTableCellRenderer()
override fun getCellEditor(row: Int, column: Int): TableCellEditor? =
tableModel.columns[column].getEditor(tableModel.items[row])
internal data class ViewModel(
val displayItems: List<PackagesTableItem<*>>,
val onlyStable: Boolean,
val targetModules: TargetModules,
val knownRepositoriesInTargetModules: KnownRepositories.InTargetModules,
val allKnownRepositories: KnownRepositories.All,
val traceInfo: TraceInfo
)
override suspend fun display(viewModel: ViewModel) = withContext(Dispatchers.AppUI) {
knownRepositoriesInTargetModules = viewModel.knownRepositoriesInTargetModules
allKnownRepositories = viewModel.allKnownRepositories
targetModules = viewModel.targetModules
logDebug(viewModel.traceInfo, "PackagesTable#displayData()") { "Displaying ${viewModel.displayItems.size} item(s)" }
// We need to update those immediately before setting the items, on EDT, to avoid timing issues
// where the target modules or only stable flags get updated after the items data change, thus
// causing issues when Swing tries to render things (e.g., targetModules doesn't match packages' usages)
versionColumn.updateData(viewModel.onlyStable, viewModel.targetModules)
actionsColumn.updateData(viewModel.onlyStable, viewModel.targetModules, knownRepositoriesInTargetModules, allKnownRepositories)
val previouslySelectedIdentifier = selectedPackage?.packageModel?.identifier
selectionModel.removeListSelectionListener(listSelectionListener)
tableModel.items = viewModel.displayItems
if (viewModel.displayItems.isEmpty() || previouslySelectedIdentifier == null) {
selectionModel.addListSelectionListener(listSelectionListener)
onItemSelectionChanged(null)
return@withContext
}
autosizeColumnsAt(autosizingColumnsIndices)
var indexToSelect: Int? = null
// TODO factor out with a lambda
for ((index, item) in viewModel.displayItems.withIndex()) {
if (item.packageModel.identifier == previouslySelectedIdentifier) {
logDebug(viewModel.traceInfo, "PackagesTable#displayData()") { "Found previously selected package at index $index" }
indexToSelect = index
}
}
selectionModel.addListSelectionListener(listSelectionListener)
if (indexToSelect != null) {
selectedIndex = indexToSelect
} else {
logDebug(viewModel.traceInfo, "PackagesTable#displayData()") { "Previous selection not available anymore, clearing..." }
}
updateAndRepaint()
}
override fun getData(dataId: String): Any? = when {
PlatformDataKeys.COPY_PROVIDER.`is`(dataId) -> this
else -> null
}
override fun performCopy(dataContext: DataContext) {
getSelectedTableItem()?.performCopy(dataContext)
}
override fun isCopyEnabled(dataContext: DataContext) = getSelectedTableItem()?.isCopyEnabled(dataContext) ?: false
override fun isCopyVisible(dataContext: DataContext) = getSelectedTableItem()?.isCopyVisible(dataContext) ?: false
private fun getSelectedTableItem(): PackagesTableItem<*>? {
if (selectedIndex == -1) {
return null
}
return tableModel.getValueAt(selectedIndex, 0) as? PackagesTableItem<*>
}
private fun updatePackageScope(packageModel: PackageModel, newScope: PackageScope) {
if (packageModel is PackageModel.Installed) {
val operations = operationFactory.createChangePackageScopeOperations(packageModel, newScope, targetModules, repoToInstall = null)
logDebug("PackagesTable#updatePackageScope()") {
"The user has selected a new scope for ${packageModel.identifier}: '$newScope'. This resulted in ${operations.size} operation(s)."
}
operationExecutor.executeOperations(operations)
} else if (packageModel is PackageModel.SearchResult) {
tableModel.replaceItemMatching(packageModel) { item ->
when (item) {
is PackagesTableItem.InstalledPackage -> {
throw IllegalStateException("Expecting a search result item model, got an installed item model")
}
is PackagesTableItem.InstallablePackage -> item.copy(item.selectedPackageModel.copy(selectedScope = newScope))
}
}
logDebug("PackagesTable#updatePackageScope()") {
"The user has selected a new scope for search result ${packageModel.identifier}: '$newScope'."
}
updateAndRepaint()
}
}
private fun updatePackageVersion(packageModel: PackageModel, newVersion: PackageVersion) {
when (packageModel) {
is PackageModel.Installed -> {
val operations = packageModel.usageInfo.flatMap {
val repoToInstall = knownRepositoriesInTargetModules.repositoryToAddWhenInstallingOrUpgrading(
packageModel,
newVersion,
allKnownRepositories
)
operationFactory.createChangePackageVersionOperations(
packageModel = packageModel,
newVersion = newVersion,
targetModules = targetModules,
repoToInstall = repoToInstall
)
}
logDebug("PackagesTable#updatePackageVersion()") {
"The user has selected a new version for ${packageModel.identifier}: '$newVersion'. " +
"This resulted in ${operations.size} operation(s)."
}
operationExecutor.executeOperations(operations)
}
is PackageModel.SearchResult -> {
tableModel.replaceItemMatching(packageModel) { item ->
when (item) {
is PackagesTableItem.InstalledPackage -> item.copy(item.selectedPackageModel.copy(selectedVersion = newVersion))
is PackagesTableItem.InstallablePackage -> item.copy(item.selectedPackageModel.copy(selectedVersion = newVersion))
}
}
logDebug("PackagesTable#updatePackageVersion()") {
"The user has selected a new version for search result ${packageModel.identifier}: '$newVersion'."
}
updateAndRepaint()
}
}
}
private fun executeUpdateActionColumnOperations(operations: List<PackageSearchOperation<*>>) {
logDebug("PackagesTable#updatePackageVersion()") {
"The user has clicked the update action for a package. This resulted in ${operations.size} operation(s)."
}
operationExecutor.executeOperations(operations)
}
private fun PackagesTableItem<*>.toSelectedPackageModule() = SelectedPackageModel(
packageModel = packageModel,
selectedVersion = (tableModel.columns[2] as VersionColumn).valueOf(this).selectedVersion,
selectedScope = (tableModel.columns[1] as ScopeColumn).valueOf(this).selectedScope,
mixedBuildSystemTargets = targetModules.isMixedBuildSystems
)
private fun applyColumnSizes(tW: Int, columns: List<TableColumn>, weights: List<Float>) {
require(columnWeights.size == columns.size) {
"Column weights count != columns count! We have ${columns.size} columns, ${columnWeights.size} weights"
}
for (column in columns) {
column.preferredWidth = (weights[column.modelIndex] * tW).roundToInt()
}
}
}
| apache-2.0 | 5633f1392d65e13e70886dbe3944acbe | 43.775061 | 146 | 0.688418 | 5.75157 | false | false | false | false |
siosio/intellij-community | plugins/git-features-trainer/src/git4idea/ift/lesson/GitCommitLesson.kt | 1 | 11905 | // 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.ift.lesson
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.VcsConfiguration
import com.intellij.openapi.vcs.changes.ChangeListChange
import com.intellij.openapi.vcs.changes.ChangesViewManager
import com.intellij.openapi.vcs.changes.ui.ChangesListView
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.ui.RefreshableOnComponent
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBOptionButton
import com.intellij.ui.table.JBTable
import com.intellij.util.DocumentUtil
import com.intellij.util.ui.tree.TreeUtil
import com.intellij.vcs.commit.*
import com.intellij.vcs.log.ui.frame.VcsLogChangesBrowser
import git4idea.i18n.GitBundle
import git4idea.ift.GitLessonsBundle
import git4idea.ift.GitLessonsUtil.checkoutBranch
import git4idea.ift.GitLessonsUtil.highlightSubsequentCommitsInGitLog
import git4idea.ift.GitLessonsUtil.openCommitWindowText
import git4idea.ift.GitLessonsUtil.resetGitLogWindow
import git4idea.ift.GitLessonsUtil.showWarningIfCommitWindowClosed
import git4idea.ift.GitLessonsUtil.showWarningIfGitWindowClosed
import git4idea.ift.GitLessonsUtil.showWarningIfModalCommitEnabled
import training.dsl.*
import training.project.ProjectUtils
import training.ui.LearningUiHighlightingManager
import java.awt.Rectangle
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import javax.swing.JTree
import javax.swing.KeyStroke
import javax.swing.tree.TreePath
class GitCommitLesson : GitLesson("Git.Commit", GitLessonsBundle.message("git.commit.lesson.name")) {
override val existedFile = "git/puss_in_boots.yml"
private val branchName = "feature"
private val firstFileName = "simple_cat.yml"
private val secondFileName = "puss_in_boots.yml"
private val firstFileAddition = """
|
| - play:
| condition: boring
| actions: [ run after favourite plush mouse ]""".trimMargin()
private val secondFileAddition = """
|
| - play:
| condition: boring
| actions: [ run after mice or own tail ]""".trimMargin()
override val testScriptProperties = TaskTestContext.TestScriptProperties(skipTesting = true)
override val lessonContent: LessonContext.() -> Unit = {
checkoutBranch(branchName)
prepareRuntimeTask {
modifyFiles()
}
showWarningIfModalCommitEnabled()
task {
openCommitWindowText(GitLessonsBundle.message("git.commit.open.commit.window"))
stateCheck {
ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.COMMIT)?.isVisible == true
}
}
prepareRuntimeTask {
val lastCommitMessage = "Add facts about playing cats"
VcsConfiguration.getInstance(project).apply {
REFORMAT_BEFORE_PROJECT_COMMIT = false
LAST_COMMIT_MESSAGE = lastCommitMessage
myLastCommitMessages = mutableListOf(lastCommitMessage)
}
val commitWorkflowHandler: AbstractCommitWorkflowHandler<*, *> = ChangesViewManager.getInstanceEx(project).commitWorkflowHandler
?: return@prepareRuntimeTask
commitWorkflowHandler.workflow.commitOptions.allOptions.forEach(RefreshableOnComponent::restoreState)
commitWorkflowHandler.setCommitMessage(lastCommitMessage)
}
task {
triggerByPartOfComponent(false) l@{ ui: ChangesListView ->
val path = TreeUtil.treePathTraverser(ui).find { it.getPathComponent(it.pathCount - 1).toString().contains(firstFileName) }
?: return@l null
val rect = ui.getPathBounds(path) ?: return@l null
Rectangle(rect.x, rect.y, 20, rect.height)
}
}
val commitWindowName = VcsBundle.message("commit.dialog.configurable")
task {
text(GitLessonsBundle.message("git.commit.choose.files", strong(commitWindowName), strong(secondFileName)))
text(GitLessonsBundle.message("git.commit.choose.files.balloon"),
LearningBalloonConfig(Balloon.Position.below, 300, cornerToPointerDistance = 55))
highlightVcsChange(firstFileName)
triggerOnOneChangeIncluded(secondFileName)
showWarningIfCommitWindowClosed()
}
task {
triggerByUiComponentAndHighlight(usePulsation = true) { ui: ActionButton ->
ActionManager.getInstance().getId(ui.action) == "ChangesView.ShowCommitOptions"
}
}
lateinit var showOptionsTaskId: TaskContext.TaskId
task {
showOptionsTaskId = taskId
text(GitLessonsBundle.message("git.commit.open.before.commit.options", icon(AllIcons.General.Gear)))
text(GitLessonsBundle.message("git.commit.open.options.tooltip", strong(commitWindowName)),
LearningBalloonConfig(Balloon.Position.above, 0))
triggerByUiComponentAndHighlight(false, false) { _: CommitOptionsPanel -> true }
showWarningIfCommitWindowClosed()
}
val reformatCodeButtonText = VcsBundle.message("checkbox.checkin.options.reformat.code").dropMnemonic()
task {
triggerByUiComponentAndHighlight { ui: JBCheckBox ->
if (ui.text == reformatCodeButtonText) {
ui.isSelected = false
true
}
else false
}
}
task {
val analyzeOptionText = VcsBundle.message("before.checkin.standard.options.check.smells").dropMnemonic()
text(GitLessonsBundle.message("git.commit.analyze.code.explanation", strong(analyzeOptionText)))
text(GitLessonsBundle.message("git.commit.enable.reformat.code", strong(reformatCodeButtonText)))
triggerByUiComponentAndHighlight(false, false) { ui: JBCheckBox ->
ui.text == reformatCodeButtonText && ui.isSelected
}
restoreByUi(showOptionsTaskId)
}
task {
text(GitLessonsBundle.message("git.commit.close.commit.options", LessonUtil.rawKeyStroke(KeyEvent.VK_ESCAPE)))
stateCheck {
previous.ui?.isShowing != true
}
}
val commitButtonText = GitBundle.message("commit.action.name").dropMnemonic()
task {
text(GitLessonsBundle.message("git.commit.perform.commit", strong(commitButtonText)))
triggerByUiComponentAndHighlight(usePulsation = true) { ui: JBOptionButton ->
ui.text?.contains(commitButtonText) == true
}
triggerOnCommitPerformed()
showWarningIfCommitWindowClosed()
}
task("ActivateVersionControlToolWindow") {
before {
LearningUiHighlightingManager.clearHighlights()
}
text(GitLessonsBundle.message("git.commit.open.git.window", action(it)))
stateCheck {
val toolWindowManager = ToolWindowManager.getInstance(project)
toolWindowManager.getToolWindow(ToolWindowId.VCS)?.isVisible == true
}
}
resetGitLogWindow()
task {
text(GitLessonsBundle.message("git.commit.select.top.commit"))
triggerOnTopCommitSelected()
showWarningIfGitWindowClosed()
}
task {
text(GitLessonsBundle.message("git.commit.committed.file.explanation"))
triggerByUiComponentAndHighlight(highlightInside = false, usePulsation = true) { _: VcsLogChangesBrowser -> true }
proceedLink()
showWarningIfGitWindowClosed(restoreTaskWhenResolved = false)
}
task {
val amendCheckboxText = VcsBundle.message("checkbox.amend").dropMnemonic()
text(GitLessonsBundle.message("git.commit.select.amend.checkbox",
strong(amendCheckboxText),
LessonUtil.rawKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.ALT_DOWN_MASK)),
strong(commitWindowName)))
triggerByUiComponentAndHighlight(usePulsation = true) { ui: JBCheckBox ->
ui.text?.contains(amendCheckboxText) == true
}
triggerByUiComponentAndHighlight(false, false) { ui: JBCheckBox ->
ui.text?.contains(amendCheckboxText) == true && ui.isSelected
}
showWarningIfCommitWindowClosed()
}
task {
text(GitLessonsBundle.message("git.commit.select.file"))
highlightVcsChange(firstFileName)
triggerOnOneChangeIncluded(firstFileName)
showWarningIfCommitWindowClosed()
}
task {
val amendButtonText = VcsBundle.message("amend.action.name", commitButtonText)
text(GitLessonsBundle.message("git.commit.amend.commit", strong(amendButtonText)))
triggerByUiComponentAndHighlight { ui: JBOptionButton ->
ui.text?.contains(amendButtonText) == true
}
triggerOnCommitPerformed()
showWarningIfCommitWindowClosed()
}
task {
text(GitLessonsBundle.message("git.commit.select.top.commit.again"))
triggerOnTopCommitSelected()
showWarningIfGitWindowClosed()
}
text(GitLessonsBundle.message("git.commit.two.committed.files.explanation"))
}
private fun TaskContext.highlightVcsChange(changeFileName: String, highlightBorder: Boolean = true) {
triggerByFoundPathAndHighlight(highlightBorder) { _: JTree, path: TreePath ->
path.pathCount > 2 && path.getPathComponent(2).toString().contains(changeFileName)
}
}
private fun TaskContext.triggerOnOneChangeIncluded(changeFileName: String) {
triggerByUiComponentAndHighlight(false, false) l@{ ui: ChangesListView ->
val includedChanges = ui.includedSet
if (includedChanges.size != 1) return@l false
val change = includedChanges.first() as? ChangeListChange ?: return@l false
change.virtualFile?.name == changeFileName
}
}
private fun TaskContext.triggerOnTopCommitSelected() {
highlightSubsequentCommitsInGitLog(0)
triggerByUiComponentAndHighlight(false, false) { ui: JBTable ->
ui.isCellSelected(0, 1)
}
}
private fun TaskContext.triggerOnCommitPerformed() {
addFutureStep {
val commitWorkflowHandler: NonModalCommitWorkflowHandler<*, *> = ChangesViewManager.getInstanceEx(project).commitWorkflowHandler
?: error("Changes view not initialized")
commitWorkflowHandler.workflow.addListener(object : CommitWorkflowListener {
override fun vcsesChanged() {}
override fun executionStarted() {}
override fun executionEnded() {
completeStep()
}
override fun beforeCommitChecksStarted() {}
override fun beforeCommitChecksEnded(isDefaultCommit: Boolean, result: CheckinHandler.ReturnResult) {}
}, taskDisposable)
}
}
private fun TaskRuntimeContext.modifyFiles() = invokeLater {
DocumentUtil.writeInRunUndoTransparentAction {
val projectRoot = ProjectUtils.getProjectRoot(project)
appendToFile(projectRoot, firstFileName, firstFileAddition)
appendToFile(projectRoot, secondFileName, secondFileAddition)
}
}
private fun appendToFile(projectRoot: VirtualFile, fileName: String, text: String) {
val file = VfsUtil.collectChildrenRecursively(projectRoot).find { it.name == fileName }
?: error("Failed to find ${fileName} in project root: ${projectRoot}")
file.refresh(false, false)
val document = FileDocumentManager.getInstance().getDocument(file)!! // it's not directory or binary file and it isn't large
document.insertString(document.textLength, text)
}
} | apache-2.0 | 50497a7f6679aabbd27982cf38dd8fff | 39.496599 | 140 | 0.723394 | 5.089782 | false | false | false | false |
lsmaira/gradle | buildSrc/subprojects/docs/src/main/kotlin/org/gradle/gradlebuild/docs/PegDown.kt | 1 | 1126 | package org.gradle.gradlebuild.docs
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.pegdown.PegDownProcessor
import java.io.File
import java.nio.charset.Charset
import java.nio.charset.Charset.defaultCharset
import javax.inject.Inject
@CacheableTask
open class PegDown @Inject constructor(
@get:PathSensitive(PathSensitivity.NONE) @get:InputFile val markdownFile: File,
@get:OutputFile val destination: File
) : DefaultTask() {
@Input
val inputEncoding = defaultCharset().name()
@Input
val outputEncoding = defaultCharset().name()
@TaskAction
fun process() {
val processor = PegDownProcessor(0)
val markdown = markdownFile.readText(Charset.forName(inputEncoding))
val html = processor.markdownToHtml(markdown)
destination.writeText(html, Charset.forName(outputEncoding))
}
}
| apache-2.0 | 19ac0d9097f3ea2911a0aca3b8e661b7 | 27.871795 | 83 | 0.768206 | 4.021429 | false | false | false | false |
idea4bsd/idea4bsd | platform/script-debugger/debugger-ui/src/VmConnection.kt | 10 | 3796 | /*
* 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.connection
import com.intellij.ide.browsers.WebBrowser
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import com.intellij.util.EventDispatcher
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.io.socketConnection.ConnectionState
import com.intellij.util.io.socketConnection.ConnectionStatus
import com.intellij.util.io.socketConnection.SocketConnectionListener
import org.jetbrains.annotations.TestOnly
import org.jetbrains.concurrency.*
import org.jetbrains.debugger.DebugEventListener
import org.jetbrains.debugger.Vm
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import javax.swing.event.HyperlinkListener
abstract class VmConnection<T : Vm> : Disposable {
open val browser: WebBrowser? = null
private val stateRef = AtomicReference(ConnectionState(ConnectionStatus.NOT_CONNECTED))
private val dispatcher = EventDispatcher.create(DebugEventListener::class.java)
private val connectionDispatcher = ContainerUtil.createLockFreeCopyOnWriteList<(ConnectionState) -> Unit>()
@Volatile var vm: T? = null
protected set
private val opened = AsyncPromise<Any?>()
private val closed = AtomicBoolean()
val state: ConnectionState
get() = stateRef.get()
fun addDebugListener(listener: DebugEventListener) {
dispatcher.addListener(listener)
}
@TestOnly
fun opened(): Promise<*> = opened
fun executeOnStart(runnable: Runnable) {
opened.done { runnable.run() }
}
protected fun setState(status: ConnectionStatus, message: String? = null, messageLinkListener: HyperlinkListener? = null) {
val newState = ConnectionState(status, message, messageLinkListener)
val oldState = stateRef.getAndSet(newState)
if (oldState == null || oldState.status != status) {
if (status == ConnectionStatus.CONNECTION_FAILED) {
opened.setError(newState.message)
}
for (listener in connectionDispatcher) {
listener(newState)
}
}
}
fun stateChanged(listener: (ConnectionState) -> Unit) {
connectionDispatcher.add(listener)
}
// backward compatibility, go debugger
fun addListener(listener: SocketConnectionListener) {
stateChanged { listener.statusChanged(it.status) }
}
protected val debugEventListener: DebugEventListener
get() = dispatcher.multicaster
protected open fun startProcessing() {
opened.setResult(null)
}
fun close(message: String?, status: ConnectionStatus) {
if (!closed.compareAndSet(false, true)) {
return
}
if (opened.isPending) {
opened.setError("closed")
}
setState(status, message)
Disposer.dispose(this, false)
}
override fun dispose() {
vm = null
}
open fun detachAndClose(): Promise<*> {
if (opened.isPending) {
opened.setError(createError("detached and closed"))
}
val currentVm = vm
val callback: Promise<*>
if (currentVm == null) {
callback = nullPromise()
}
else {
vm = null
callback = currentVm.attachStateManager.detach()
}
close(null, ConnectionStatus.DISCONNECTED)
return callback
}
} | apache-2.0 | d17e6114c637dd7825cdfe5a86da540e | 29.620968 | 125 | 0.734984 | 4.579011 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/api/patrons/PatronsRepository.kt | 1 | 1447 | package io.github.feelfreelinux.wykopmobilny.api.patrons
import io.github.feelfreelinux.wykopmobilny.base.WykopSchedulers
import io.github.feelfreelinux.wykopmobilny.models.pojo.apiv2.patrons.Patron
import io.reactivex.Single
import retrofit2.Retrofit
class PatronsRepository(val retrofit: Retrofit) : PatronsApi {
private val patronsApi by lazy { retrofit.create(PatronsRetrofitApi::class.java) }
override lateinit var patrons : List<Patron>
override fun <T>ensurePatrons(d : T) : Single<T> {
return Single.create {
emitter ->
if (!::patrons.isInitialized) {
getPatrons().subscribeOn(WykopSchedulers().backgroundThread()).observeOn(WykopSchedulers().mainThread())
.subscribe({
patrons ->
this.patrons = patrons
emitter.onSuccess(d)
}, { e ->
this.patrons = listOf()
emitter.onSuccess(d)
})
} else {
emitter.onSuccess(d)
}
}
}
override fun getPatrons(): Single<List<Patron>> =
patronsApi.getPatrons().map { it.patrons }
.doOnSuccess {
this.patrons = it
}.doOnError {
this.patrons = listOf()
}
} | mit | e065125f9695a6ce606d1f4d4d20a6d1 | 36.128205 | 120 | 0.530753 | 5.223827 | false | false | false | false |
ErikKarlsson/SmashApp-Android | app/src/main/java/net/erikkarlsson/smashapp/feature/tournament/domain/TournamentModel.kt | 1 | 3094 | package net.erikkarlsson.smashapp.feature.tournament.domain
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableMap
import net.erikkarlsson.smashapp.base.data.Lce
import net.erikkarlsson.smashapp.base.data.model.ranking.Smasher
import net.erikkarlsson.smashapp.base.data.model.tournament.Match
import net.erikkarlsson.smashapp.base.data.model.tournament.Participant
import net.erikkarlsson.smashapp.base.data.model.tournament.Tournament
import net.erikkarlsson.smashapp.feature.tournament.domain.projection.ProjectedMatchResult
/**
* This model is streamed to all Presenters interested in the state of the application.
* The state is immutable which makes it thread safe and a lot easier to reason about.
* This model will be incrementally re-created as results come back from the different actions.
*/
data class TournamentModel(val tournamentLce: Lce<Tournament>,
val myParticipantId: Long,
val projection: ImmutableList<ProjectedMatchResult>,
val participantIdSmasherMap: ImmutableMap<Long, Smasher>) {
companion object {
@JvmField val EMPTY = TournamentModel(Lce.idle<Tournament>(), 0L, ImmutableList.of(), ImmutableMap.of())
}
val participantSmasherMap: ImmutableMap<Participant, Smasher>
get() {
val participantSmasherMapBuilder = ImmutableMap.builder<Participant, Smasher>()
tournament().participants.forEach {
val smasher: Smasher = participantIdSmasherMap[it.id] ?: Smasher.NO_SMASHER
participantSmasherMapBuilder.put(it, smasher)
}
return participantSmasherMapBuilder.build()
}
fun tournament(): Tournament {
return tournamentLce.data ?: Tournament.NO_TOURNAMENT
}
fun isLoading(): Boolean {
return tournamentLce.isLoading()
}
fun hasError(): Boolean {
return tournamentLce.hasError()
}
fun isParticipating(): Boolean {
return myParticipantId != 0L
}
fun shouldSearchForTournament(): Boolean {
return tournamentLce.isIdle || isTournamentNotFound() || tournamentLce.hasError()
}
fun shouldFetchTournament(): Boolean {
return isTournamentFound()
}
fun isTournamentFound(): Boolean {
return tournament() != Tournament.NO_TOURNAMENT
}
fun isBracketProjected(): Boolean {
return projection.size > 0
}
fun isAllSmashersFetched(): Boolean {
return participantIdSmasherMap.size == tournament().participants.size
}
fun isTournamentNotFound(): Boolean {
return tournamentLce.hasData() && tournamentLce.data === Tournament.NO_TOURNAMENT
}
fun nextMatch(): Match {
return tournament().nextMatch(myParticipantId)
}
fun hasTournamentBeenUpdated(updatedTournament: Tournament): Boolean {
return tournament().updatedAt != updatedTournament.updatedAt
}
fun participants(): ImmutableList<Participant> {
return tournament().participants
}
} | apache-2.0 | 6a0e56159524e69dbd365b841a0cf1b2 | 34.574713 | 112 | 0.698772 | 4.982287 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/stories/viewer/post/StoryPostState.kt | 1 | 1003 | package org.thoughtcrime.securesms.stories.viewer.post
import android.graphics.Typeface
import android.net.Uri
import org.thoughtcrime.securesms.blurhash.BlurHash
import org.thoughtcrime.securesms.database.model.databaseprotos.StoryTextPost
import org.thoughtcrime.securesms.linkpreview.LinkPreview
import kotlin.time.Duration
sealed class StoryPostState {
data class TextPost(
val storyTextPost: StoryTextPost? = null,
val linkPreview: LinkPreview? = null,
val typeface: Typeface? = null,
val loadState: LoadState = LoadState.INIT
) : StoryPostState()
data class ImagePost(
val imageUri: Uri,
val blurHash: BlurHash?
) : StoryPostState()
data class VideoPost(
val videoUri: Uri,
val size: Long,
val clipStart: Duration,
val clipEnd: Duration,
val blurHash: BlurHash?
) : StoryPostState()
data class None(private val ts: Long = System.currentTimeMillis()) : StoryPostState()
enum class LoadState {
INIT,
LOADED,
FAILED
}
}
| gpl-3.0 | 52348a28dd8d89f1b8227e4802fc3edd | 25.394737 | 87 | 0.739781 | 4.304721 | false | false | false | false |
androidx/androidx | room/room-compiler/src/test/kotlin/androidx/room/vo/DatabaseTest.kt | 3 | 2963 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.vo
import androidx.room.compiler.processing.XConstructorElement
import androidx.room.compiler.processing.XElement
import androidx.room.compiler.processing.XType
import androidx.room.compiler.processing.XTypeElement
import org.apache.commons.codec.digest.DigestUtils
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mockito.mock
@RunWith(JUnit4::class)
class DatabaseTest {
@Test
fun indexLegacyHash() {
val database = Database(
element = mock(XTypeElement::class.java),
type = mock(XType::class.java),
entities = listOf(
Entity(
mock(XTypeElement::class.java),
tableName = "TheTable",
type = mock(XType::class.java),
fields = emptyList(),
embeddedFields = emptyList(),
primaryKey = PrimaryKey(mock(XElement::class.java), Fields(), false),
indices = listOf(
Index(
name = "leIndex",
unique = false,
fields = Fields(),
orders = emptyList()
),
Index(
name = "leIndex2",
unique = true,
fields = Fields(),
orders = emptyList()
)
),
foreignKeys = emptyList(),
constructor = Constructor(mock(XConstructorElement::class.java), emptyList()),
shadowTableName = null
)
),
views = emptyList(),
daoMethods = emptyList(),
version = 1,
exportSchema = false,
enableForeignKeys = false
)
val expectedLegacyHash = DigestUtils.md5Hex(
"CREATE TABLE IF NOT EXISTS `TheTable` ()¯\\_(ツ)_/¯" +
"CREATE INDEX `leIndex` ON `TheTable` ()¯\\_(ツ)_/¯" +
"CREATE UNIQUE INDEX `leIndex2` ON `TheTable` ()"
)
assertEquals(expectedLegacyHash, database.legacyIdentityHash)
}
} | apache-2.0 | 8dc1e30ecdd123791c08e0b8237c22f9 | 36.417722 | 98 | 0.553638 | 5.175131 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/ContainsOperatorReferenceSearcher.kt | 4 | 2395 | // 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.search.usagesSearch.operators
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.SearchRequestCollector
import com.intellij.psi.search.SearchScope
import com.intellij.util.Processor
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance
class ContainsOperatorReferenceSearcher(
targetFunction: PsiElement,
searchScope: SearchScope,
consumer: Processor<in PsiReference>,
optimizer: SearchRequestCollector,
options: KotlinReferencesSearchOptions
) : OperatorReferenceSearcher<KtOperationReferenceExpression>(
targetFunction,
searchScope,
consumer,
optimizer,
options,
wordsToSearch = listOf("in")
) {
private companion object {
private val OPERATION_TOKENS = setOf(KtTokens.IN_KEYWORD, KtTokens.NOT_IN)
}
override fun processPossibleReceiverExpression(expression: KtExpression) {
when (val parent = expression.parent) {
is KtBinaryExpression -> {
if (parent.operationToken in OPERATION_TOKENS && expression == parent.right) {
processReferenceElement(parent.operationReference)
}
}
is KtWhenConditionInRange -> {
processReferenceElement(parent.operationReference)
}
}
}
override fun isReferenceToCheck(ref: PsiReference): Boolean {
if (ref !is KtSimpleNameReference) return false
val element = ref.element as? KtOperationReferenceExpression ?: return false
return element.getReferencedNameElementType() in OPERATION_TOKENS
}
override fun extractReference(element: KtElement): PsiReference? {
val referenceExpression = element as? KtOperationReferenceExpression ?: return null
if (referenceExpression.getReferencedNameElementType() !in OPERATION_TOKENS) return null
return referenceExpression.references.firstIsInstance<KtSimpleNameReference>()
}
} | apache-2.0 | c94eafd212c42bc9465d83d0d1e59e2a | 39.610169 | 158 | 0.741962 | 5.518433 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/build/output/KotlincOutputParser.kt | 4 | 9092 | // 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.build.output
import com.intellij.build.FilePosition
import com.intellij.build.events.BuildEvent
import com.intellij.build.events.BuildEventsNls
import com.intellij.build.events.MessageEvent
import com.intellij.build.events.impl.FileMessageEventImpl
import com.intellij.build.events.impl.MessageEventImpl
import com.intellij.lang.LangBundle
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.annotations.Contract
import org.jetbrains.annotations.NonNls
import java.io.File
import java.net.URI
import java.util.function.Consumer
import java.util.regex.Matcher
import java.util.regex.Pattern
import kotlin.io.path.toPath
/**
* Parses kotlinc's output.
*/
class KotlincOutputParser : BuildOutputParser {
companion object {
private val COMPILER_MESSAGES_GROUP: @BuildEventsNls.Title String
@BuildEventsNls.Title
get() = LangBundle.message("build.event.title.kotlin.compiler")
private val WINDOWS_PATH = "^\\s*.:(/|\\\\)".toRegex()
private val WINDOWS_URI = "^\\s*file:/+.:(/|\\\\)".toRegex()
private val UNIX_URI = "^\\s*file:/".toRegex()
fun extractPath(line: String): String? {
if (!line.contains(":")) return null
val systemPrefixLen = listOf(WINDOWS_PATH, WINDOWS_URI, UNIX_URI).firstNotNullOfOrNull {
it.find(line)?.groups?.last()?.range?.endInclusive
} ?: 0
val colonIndex = line.indexOf(':', systemPrefixLen)
if (colonIndex < 0) return null
return line.substring(0, colonIndex)
}
}
override fun parse(line: String, reader: BuildOutputInstantReader, consumer: Consumer<in BuildEvent>): Boolean {
val colonIndex1 = line.colon()
val severity = if (colonIndex1 >= 0) line.substringBeforeAndTrim(colonIndex1) else return false
if (!severity.startsWithSeverityPrefix()) return false
val lineWoSeverity = line.substringAfterAndTrim(colonIndex1)
var path = extractPath(lineWoSeverity) ?: return false
val file = if (path.startsWith("file:")) {
try {
URI(path).toPath().toFile()
} catch (_: Exception){
File(path)
}
} else {
File(path)
}
val fileExtension = file.extension.toLowerCase()
if (!file.isFile || (fileExtension != "kt" && fileExtension != "kts" && fileExtension != "java")) { //NON-NLS
@NlsSafe
val combinedMessage = lineWoSeverity.amendNextLinesIfNeeded(reader)
return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), lineWoSeverity, combinedMessage), consumer)
}
val lineWoPath = lineWoSeverity.substringAfterAndTrim(path.length)
var lineWoPositionIndex = -1
var matcher: Matcher? = null
if (lineWoPath.startsWith('(')) {
val colonIndex3 = lineWoPath.colon()
if (colonIndex3 >= 0) {
lineWoPositionIndex = colonIndex3
}
if (lineWoPositionIndex >= 0) {
val position = lineWoPath.substringBeforeAndTrim(lineWoPositionIndex)
matcher = KOTLIN_POSITION_PATTERN.matcher(position).takeIf { it.matches() } ?: JAVAC_POSITION_PATTERN.matcher(position)
}
} else if (URI_POSITION_PATTERN.toRegex().find(lineWoPath) != null) {
val parts = URI_POSITION_PATTERN.toRegex().find(lineWoPath)!!
println(parts)
val position = parts.groupValues.first()
lineWoPositionIndex = position.length
matcher = URI_POSITION_PATTERN.matcher(position)
} else {
val colonIndex4 = lineWoPath.colon(1)
if (colonIndex4 >= 0) {
lineWoPositionIndex = colonIndex4
}
else {
lineWoPositionIndex = lineWoPath.colon()
}
if (lineWoPositionIndex >= 0) {
val position = lineWoPath.substringBeforeAndTrim(colonIndex4)
matcher = LINE_COLON_COLUMN_POSITION_PATTERN.matcher(position).takeIf { it.matches() } ?: JAVAC_POSITION_PATTERN.matcher(position)
}
}
if (lineWoPositionIndex >= 0) {
val relatedNextLines = "".amendNextLinesIfNeeded(reader)
val message = lineWoPath.substringAfterAndTrim(lineWoPositionIndex) + relatedNextLines
val details = line + relatedNextLines
if (matcher != null && matcher.matches()) {
val lineNumber = matcher.group(1)
val symbolNumber = if (matcher.groupCount() >= 2) matcher.group(2) else "1"
if (lineNumber != null) {
val symbolNumberText = symbolNumber.toInt()
return addMessage(createMessageWithLocation(
reader.parentEventId, getMessageKind(severity), message, file, lineNumber.toInt(), symbolNumberText, details), consumer)
}
}
return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), message, details), consumer)
}
else {
@NlsSafe
val combinedMessage = lineWoSeverity.amendNextLinesIfNeeded(reader)
return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), lineWoSeverity, combinedMessage), consumer)
}
}
private val COLON = ":"
private val KOTLIN_POSITION_PATTERN = Pattern.compile("\\(([0-9]*), ([0-9]*)\\)")
private val URI_POSITION_PATTERN = Pattern.compile("^([0-9]*):([0-9]*)")
private val JAVAC_POSITION_PATTERN = Pattern.compile("([0-9]+)")
private val LINE_COLON_COLUMN_POSITION_PATTERN = Pattern.compile("([0-9]*):([0-9]*)")
private fun String.amendNextLinesIfNeeded(reader: BuildOutputInstantReader): String {
var nextLine = reader.readLine()
val builder = StringBuilder(this)
while (nextLine != null) {
if (nextLine.isNextMessage()) {
reader.pushBack()
break
}
else {
builder.append("\n").append(nextLine)
nextLine = reader.readLine()
}
}
return builder.toString()
}
private fun String.isNextMessage(): Boolean {
val colonIndex1 = indexOf(COLON)
return colonIndex1 == 0
|| (colonIndex1 >= 0 && substring(0, colonIndex1).startsWithSeverityPrefix()) // Next Kotlin message
|| StringUtil.startsWith(this, "Note: ") // Next javac info message candidate //NON-NLS
|| StringUtil.startsWith(this, "> Task :") // Next gradle message candidate //NON-NLS
|| StringUtil.containsIgnoreCase(this, "FAILURE") //NON-NLS
|| StringUtil.containsIgnoreCase(this, "FAILED") //NON-NLS
}
private fun String.startsWithSeverityPrefix() = getMessageKind(this) != MessageEvent.Kind.SIMPLE
@NonNls
private fun getMessageKind(kind: @NonNls String) = when (kind) {
"e" -> MessageEvent.Kind.ERROR
"w" -> MessageEvent.Kind.WARNING
"i" -> MessageEvent.Kind.INFO
"v" -> MessageEvent.Kind.SIMPLE
else -> MessageEvent.Kind.SIMPLE
}
@Contract(pure = true)
private fun String.substringAfterAndTrim(index: Int) = substring(index + 1).trim()
@Contract(pure = true)
private fun String.substringBeforeAndTrim(index: Int) = substring(0, index).trim()
private fun String.colon() = indexOf(COLON)
private fun String.colon(skip: Int): Int {
var index = -1
repeat(skip + 1) {
index = indexOf(COLON, index + 1)
if (index < 0) return index
}
return index
}
private val KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT
get() =
// KaptError::class.java.canonicalName + ": " + KaptError.Kind.ERROR_RAISED.message
"org.jetbrains.kotlin.kapt3.diagnostic.KaptError" + ": " + LangBundle.message("kapterror.error.while.annotation.processing")
private fun isKaptErrorWhileAnnotationProcessing(message: MessageEvent): Boolean {
if (message.kind != MessageEvent.Kind.ERROR) return false
val messageText = message.message
return messageText.startsWith(IllegalStateException::class.java.name)
&& messageText.contains(KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT)
}
private fun addMessage(message: MessageEvent, consumer: Consumer<in MessageEvent>): Boolean {
// Ignore KaptError.ERROR_RAISED message from kapt. We already processed all errors from annotation processing
if (isKaptErrorWhileAnnotationProcessing(message)) return true
consumer.accept(message)
return true
}
private fun createMessage(parentId: Any,
messageKind: MessageEvent.Kind,
text: @BuildEventsNls.Message String,
detail: @BuildEventsNls.Description String): MessageEvent {
return MessageEventImpl(parentId, messageKind, COMPILER_MESSAGES_GROUP, text.trim(), detail) //NON-NLS
}
private fun createMessageWithLocation(
parentId: Any,
messageKind: MessageEvent.Kind,
text: @BuildEventsNls.Message String,
file: File,
lineNumber: Int,
columnIndex: Int,
detail: @BuildEventsNls.Description String
): FileMessageEventImpl {
return FileMessageEventImpl(parentId, messageKind, COMPILER_MESSAGES_GROUP, text.trim(), detail, //NON-NLS
FilePosition(file, lineNumber - 1, columnIndex - 1))
}
} | apache-2.0 | 3f233d89f8dabcce7f513b323a7b5243 | 38.363636 | 140 | 0.686868 | 4.580353 | false | false | false | false |
siosio/intellij-community | plugins/markdown/src/org/intellij/plugins/markdown/fileActions/utils/MarkdownImportExportUtils.kt | 1 | 8242 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.fileActions.utils
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.ProcessOutput
import com.intellij.execution.util.ExecUtil
import com.intellij.ide.actions.OpenFileAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.impl.VirtualFileImpl
import com.intellij.psi.PsiManager
import com.intellij.refactoring.RefactoringBundle
import com.intellij.ui.TextFieldWithHistoryWithBrowseButton
import com.intellij.ui.layout.*
import com.intellij.util.ModalityUiUtil
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.MarkdownNotifier
import org.intellij.plugins.markdown.fileActions.export.MarkdownDocxExportProvider
import org.intellij.plugins.markdown.lang.MarkdownFileType
import org.intellij.plugins.markdown.settings.pandoc.PandocApplicationSettings
import org.intellij.plugins.markdown.ui.actions.MarkdownActionUtil
import org.intellij.plugins.markdown.ui.preview.MarkdownPreviewFileEditor
import org.intellij.plugins.markdown.ui.preview.jcef.JCEFHtmlPanelProvider
import java.io.File
/**
* Utilities used mainly for import/export from markdown.
*/
object MarkdownImportExportUtils {
/**
* Returns the preview of markdown file or null if the preview editor or project is null.
*/
fun getPreviewEditor(event: AnActionEvent, fileType: String): MarkdownPreviewFileEditor? {
val project = event.project ?: return null
val previewEditor = MarkdownActionUtil.findMarkdownPreviewEditor(event)
if (previewEditor == null) {
MarkdownNotifier.notifyIfConvertFailed(
project,
MarkdownBundle.message("markdown.export.validation.failure.msg", fileType)
)
return null
}
return previewEditor
}
/**
* recursively refreshes the specified directory in the project tree,
* if the directory is not specified, the base directory of the project is refreshed.
*/
fun refreshProjectDirectory(project: Project, refreshPath: String) {
ModalityUiUtil.invokeLaterIfNeeded(
{
LocalFileSystem
.getInstance()
.refreshAndFindFileByIoFile(File(refreshPath))
?.refresh(true, true)
},
ModalityState.defaultModalityState()
)
}
/**
* suggests a minimally conflicting name when importing a file,
* checking for the existence of both docx and markdown files.
*/
fun suggestFileNameToCreate(project: Project, fileToImport: VirtualFile, dataContext: DataContext): String {
val defaultFileName = fileToImport.nameWithoutExtension
val dirToImport = when (val selectedVirtualFile = CommonDataKeys.VIRTUAL_FILE.getData(dataContext)) {
null -> File(project.basePath!!)
is VirtualFileImpl -> File(selectedVirtualFile.parent.path)
else -> File(selectedVirtualFile.path)
}
val suggestMdFile = FileUtil.createSequentFileName(dirToImport, defaultFileName, MarkdownFileType.INSTANCE.defaultExtension)
val suggestFileName = File(suggestMdFile).nameWithoutExtension
val suggestDocxFile = FileUtil.createSequentFileName(dirToImport, suggestFileName, MarkdownDocxExportProvider.format.extension)
return FileUtil.join(dirToImport.path, suggestDocxFile)
}
/**
* converts the specified docx file using the pandoc utility,
* and also calls the copy method for it to the same directory if the conversion was successful.
*/
fun copyAndConvertToMd(project: Project,
vFileToImport: VirtualFile,
selectedFileUrl: String,
@NlsContexts.DialogTitle taskTitle: String) {
object : Task.Modal(project, taskTitle, true) {
private lateinit var createdFilePath: String
private lateinit var output: ProcessOutput
private val dirToImport = File(selectedFileUrl).parent
private val newFileName = File(selectedFileUrl).nameWithoutExtension
private val resourcesDir = PandocApplicationSettings.getInstance().state.myPathToImages ?: project.basePath!!
override fun run(indicator: ProgressIndicator) {
val filePath = FileUtil.join(dirToImport, "${newFileName}.${MarkdownFileType.INSTANCE.defaultExtension}")
val cmd = getConvertDocxToMdCommandLine(vFileToImport, resourcesDir, filePath)
output = ExecUtil.execAndGetOutput(cmd)
createdFilePath = filePath
}
override fun onCancel() {
val mdFile = File(createdFilePath)
if (mdFile.exists()) FileUtil.delete(mdFile)
}
override fun onThrowable(error: Throwable) {
MarkdownNotifier.notifyIfConvertFailed(project, "[${vFileToImport.name}] ${error.localizedMessage}")
}
override fun onSuccess() {
if (output.stderrLines.isEmpty()) {
vFileToImport.copySelectedFile(project, dirToImport, newFileName)
OpenFileAction.openFile(createdFilePath, project)
}
else {
MarkdownNotifier.notifyIfConvertFailed(project, "[${vFileToImport.name}] ${output.stderrLines.joinToString("\n")}")
}
}
}.queue()
}
/**
* Copies the selected file to the specified directory.
* If the copying failed, sends a notification to the user about it.
*/
private fun VirtualFile.copySelectedFile(project: Project, dirToImport: String, newFileName: String) {
val fileNameWithExtension = "$newFileName.${MarkdownDocxExportProvider.format.extension}"
try {
val localFS = LocalFileSystem.getInstance()
val dirToImportVF = localFS.findFileByPath(dirToImport) ?: localFS.findFileByPath(project.basePath!!)!!
runWriteAction {
val directory = PsiManager.getInstance(project).findDirectory(dirToImportVF)!!
val file = PsiManager.getInstance(project).findFile(this)!!
directory.copyFileFrom(fileNameWithExtension, file)
}
}
catch (exception: Throwable) {
MarkdownNotifier.notifyIfConvertFailed(project, "[$fileNameWithExtension] ${exception.localizedMessage}")
}
}
private const val TARGET_FORMAT_NAME = "markdown"
/**
* returns a platform-independent cmd to perform the converting of docx to markdown using pandoc.
*/
private fun getConvertDocxToMdCommandLine(file: VirtualFile, mediaSrc: String, targetFile: String) = GeneralCommandLine(
"pandoc",
"--extract-media=$mediaSrc",
file.path,
"-f",
MarkdownDocxExportProvider.format.extension,
"-t",
TARGET_FORMAT_NAME,
"-s",
"-o",
targetFile
)
/**
* Checks whether the JCEF panel, which is needed for exporting to HTML and PDF, is open in the markdown editor.
*/
fun isJCEFPanelOpen(editor: MarkdownPreviewFileEditor): Boolean {
return editor.lastPanelProviderInfo?.className == JCEFHtmlPanelProvider::class.java.name
}
/**
* Checks the directory selection field and returns an error if it is not filled in.
*/
fun ValidationInfoBuilder.validateTargetDir(field: TextFieldWithHistoryWithBrowseButton): ValidationInfo? {
return when {
field.childComponent.text.isNullOrEmpty() -> error(RefactoringBundle.message("no.target.directory.specified"))
else -> null
}
}
fun notifyAndRefreshIfExportSuccess(file: File, project: Project) {
MarkdownNotifier.notifyOfSuccessfulExport(
project,
MarkdownBundle.message("markdown.export.success.msg", file.name)
)
val dirToExport = file.parent
refreshProjectDirectory(project, dirToExport)
}
}
| apache-2.0 | 1561255be9ac39fbc3d23bbca059773b | 39.009709 | 140 | 0.746421 | 4.9118 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/refactoring/rename/impl/DefaultReferenceUsage.kt | 12 | 1758 | // 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.refactoring.rename.impl
import com.intellij.model.Pointer
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import com.intellij.psi.SmartPointerManager
import com.intellij.psi.SmartPsiFileRange
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.rename.api.PsiRenameUsage
import com.intellij.refactoring.rename.api.RenameConflict
import com.intellij.refactoring.rename.api.RenameUsage
/**
* If [RenameUsage] is not defined for a reference,
* then the platform treats the reference as a non-renameable [RenameUsage]
* by creating an instance of this class.
*/
internal class DefaultReferenceUsage(
override val file: PsiFile,
override val range: TextRange
) : PsiRenameUsage {
override val declaration: Boolean get() = false
override fun conflicts(newName: String): List<RenameConflict> {
return listOf(RenameConflict.fromText(RefactoringBundle.message("rename.usage.unmodifiable")))
}
override fun createPointer(): Pointer<out DefaultReferenceUsage> = DefaultReferenceUsagePointer(file, range)
private class DefaultReferenceUsagePointer(file: PsiFile, range: TextRange) : Pointer<DefaultReferenceUsage> {
private val rangePointer: SmartPsiFileRange = SmartPointerManager.getInstance(file.project).createSmartPsiFileRangePointer(file, range)
override fun dereference(): DefaultReferenceUsage? {
val file: PsiFile = rangePointer.element ?: return null
val range: TextRange = rangePointer.range?.let(TextRange::create) ?: return null
return DefaultReferenceUsage(file, range)
}
}
}
| apache-2.0 | 82d28af8b95ff3d338b9ba11f84ceb7e | 40.857143 | 140 | 0.791809 | 4.650794 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/KotlinGradleProjectResolverExtension.kt | 1 | 24897 | // 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.gradleJava.configuration
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.*
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.roots.DependencyScope
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.io.FileUtil
import org.gradle.api.artifacts.Dependency
import org.gradle.internal.impldep.org.apache.commons.lang.math.RandomUtils
import org.gradle.tooling.model.idea.IdeaModule
import org.jetbrains.kotlin.idea.gradle.configuration.KotlinGradleProjectData
import org.jetbrains.kotlin.idea.gradle.configuration.KotlinGradleSourceSetData
import org.jetbrains.kotlin.idea.gradle.configuration.kotlinGradleSourceSetDataNodes
import org.jetbrains.kotlin.idea.gradle.statistics.KotlinGradleFUSLogger
import org.jetbrains.kotlin.idea.gradleJava.inspections.getDependencyModules
import org.jetbrains.kotlin.idea.gradleTooling.*
import org.jetbrains.kotlin.idea.projectModel.KotlinTarget
import org.jetbrains.kotlin.idea.statistics.KotlinIDEGradleActionsFUSCollector
import org.jetbrains.kotlin.idea.util.NotNullableCopyableDataNodeUserDataProperty
import org.jetbrains.kotlin.idea.util.PsiPrecedences
import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty
import org.jetbrains.plugins.gradle.model.ExternalProjectDependency
import org.jetbrains.plugins.gradle.model.ExternalSourceSet
import org.jetbrains.plugins.gradle.model.FileCollectionDependency
import org.jetbrains.plugins.gradle.model.ProjectImportModelProvider
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolver
import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverUtil
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext
import java.io.File
import java.util.*
val DataNode<out ModuleData>.kotlinGradleProjectDataNodeOrNull: DataNode<KotlinGradleProjectData>?
get() = when (this.data) {
is GradleSourceSetData -> ExternalSystemApiUtil.findParent(this, ProjectKeys.MODULE)?.kotlinGradleProjectDataNodeOrNull
else -> ExternalSystemApiUtil.find(this, KotlinGradleProjectData.KEY)
}
val DataNode<out ModuleData>.kotlinGradleProjectDataNodeOrFail: DataNode<KotlinGradleProjectData>
get() = kotlinGradleProjectDataNodeOrNull
?: error("Failed to find KotlinGradleProjectData node for $this")
val DataNode<out ModuleData>.kotlinGradleProjectDataOrNull: KotlinGradleProjectData?
get() = when (this.data) {
is GradleSourceSetData -> ExternalSystemApiUtil.findParent(this, ProjectKeys.MODULE)?.kotlinGradleProjectDataOrNull
else -> kotlinGradleProjectDataNodeOrNull?.data
}
val DataNode<out ModuleData>.kotlinGradleProjectDataOrFail: KotlinGradleProjectData
get() = kotlinGradleProjectDataOrNull
?: error("Failed to find KotlinGradleProjectData for $this")
@Deprecated("Use KotlinGradleSourceSetData#isResolved instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.isResolved: Boolean
get() = kotlinGradleProjectDataOrFail.isResolved
set(value) {
kotlinGradleProjectDataOrFail.isResolved = value
}
@Deprecated("Use KotlinGradleSourceSetData#hasKotlinPlugin instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.hasKotlinPlugin: Boolean
get() = kotlinGradleProjectDataOrFail.hasKotlinPlugin
set(value) {
kotlinGradleProjectDataOrFail.hasKotlinPlugin = value
}
@Suppress("TYPEALIAS_EXPANSION_DEPRECATION")
@Deprecated("Use KotlinGradleSourceSetData#compilerArgumentsBySourceSet instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.compilerArgumentsBySourceSet: CompilerArgumentsBySourceSet?
@Suppress("DEPRECATION_ERROR")
get() = compilerArgumentsBySourceSet()
set(value) = throw UnsupportedOperationException("Changing of compilerArguments is available only through GradleSourceSetData.")
@Suppress("TYPEALIAS_EXPANSION_DEPRECATION", "DEPRECATION_ERROR")
fun DataNode<out ModuleData>.compilerArgumentsBySourceSet(): CompilerArgumentsBySourceSet? =
ExternalSystemApiUtil.findAllRecursively(this, KotlinGradleSourceSetData.KEY).ifNotEmpty {
map { it.data }.filter { it.sourceSetName != null }.associate { it.sourceSetName!! to it.compilerArguments }
}
@Deprecated("Use KotlinGradleSourceSetData#additionalVisibleSourceSets instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.additionalVisibleSourceSets: AdditionalVisibleSourceSetsBySourceSet
@Suppress("DEPRECATION_ERROR")
get() = ExternalSystemApiUtil.findAllRecursively(this, KotlinGradleSourceSetData.KEY)
.map { it.data }
.filter { it.sourceSetName != null }
.associate { it.sourceSetName!! to it.additionalVisibleSourceSets }
set(value) {
ExternalSystemApiUtil.findAllRecursively(this, KotlinGradleSourceSetData.KEY).filter { it.data.sourceSetName != null }.forEach {
if (value.containsKey(it.data.sourceSetName!!))
it.data.additionalVisibleSourceSets = value.getValue(it.data.sourceSetName!!)
}
}
@Deprecated("Use KotlinGradleSourceSetData#coroutines instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.coroutines: String?
get() = kotlinGradleProjectDataOrFail.coroutines
set(value) {
kotlinGradleProjectDataOrFail.coroutines = value
}
@Deprecated("Use KotlinGradleSourceSetData#isHmpp instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.isHmpp: Boolean
get() = kotlinGradleProjectDataOrFail.isHmpp
set(value) {
kotlinGradleProjectDataOrFail.isHmpp = value
}
@Deprecated("Use KotlinGradleSourceSetData#platformPluginId instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.platformPluginId: String?
get() = kotlinGradleProjectDataOrFail.platformPluginId
set(value) {
kotlinGradleProjectDataOrFail.platformPluginId = value
}
@Deprecated("Use KotlinGradleSourceSetData#kotlinNativeHome instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.kotlinNativeHome: String
get() = kotlinGradleProjectDataOrFail.kotlinNativeHome
set(value) {
kotlinGradleProjectDataOrFail.kotlinNativeHome = value
}
@Deprecated("Use KotlinGradleSourceSetData#implementedModuleNames instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.implementedModuleNames: List<String>
@Suppress("DEPRECATION_ERROR")
get() = when (data) {
is GradleSourceSetData -> ExternalSystemApiUtil.find(this, KotlinGradleSourceSetData.KEY)?.data?.implementedModuleNames
?: error("Failed to find KotlinGradleSourceSetData for $this")
else -> ExternalSystemApiUtil.find(this@implementedModuleNames, KotlinGradleProjectData.KEY)?.data?.implementedModuleNames
?: error("Failed to find KotlinGradleProjectData for $this")
}
set(value) = throw UnsupportedOperationException("Changing of implementedModuleNames is available only through KotlinGradleSourceSetData.")
@Deprecated("Use KotlinGradleSourceSetData#dependenciesCache instead", level = DeprecationLevel.ERROR)
// Project is usually the same during all import, thus keeping Map Project->Dependencies makes model a bit more complicated but allows to avoid future problems
var DataNode<out ModuleData>.dependenciesCache: MutableMap<DataNode<ProjectData>, Collection<DataNode<out ModuleData>>>
get() = kotlinGradleProjectDataOrFail.dependenciesCache
set(value) = with(kotlinGradleProjectDataOrFail.dependenciesCache) {
clear()
putAll(value)
}
@Deprecated("Use KotlinGradleSourceSetData#implementedModuleNames instead", level = DeprecationLevel.ERROR)
var DataNode<out ModuleData>.pureKotlinSourceFolders: MutableCollection<String>
get() = kotlinGradleProjectDataOrFail.pureKotlinSourceFolders
set(value) = with(kotlinGradleProjectDataOrFail.pureKotlinSourceFolders) {
clear()
addAll(value)
}
class KotlinGradleProjectResolverExtension : AbstractProjectResolverExtension() {
val isAndroidProjectKey = Key.findKeyByName("IS_ANDROID_PROJECT_KEY")
private val cacheManager = KotlinCompilerArgumentsCacheMergeManager
override fun getToolingExtensionsClasses(): Set<Class<out Any>> {
return setOf(KotlinGradleModelBuilder::class.java, KotlinTarget::class.java, RandomUtils::class.java, Unit::class.java)
}
override fun getExtraProjectModelClasses(): Set<Class<out Any>> {
error("getModelProvider() is overridden instead")
}
override fun getModelProvider(): ProjectImportModelProvider {
val isAndroidPluginRequestingKotlinGradleModelKey = Key.findKeyByName("IS_ANDROID_PLUGIN_REQUESTING_KOTLIN_GRADLE_MODEL_KEY")
val isAndroidPluginRequestingKotlinGradleModel =
isAndroidPluginRequestingKotlinGradleModelKey != null && resolverCtx.getUserData(isAndroidPluginRequestingKotlinGradleModelKey) != null
return AndroidAwareGradleModelProvider(KotlinGradleModel::class.java, isAndroidPluginRequestingKotlinGradleModel)
}
override fun createModule(gradleModule: IdeaModule, projectDataNode: DataNode<ProjectData>): DataNode<ModuleData>? {
return super.createModule(gradleModule, projectDataNode)?.also {
cacheManager.mergeCache(gradleModule, resolverCtx)
initializeModuleData(gradleModule, it, projectDataNode, resolverCtx)
}
}
private fun initializeModuleData(
gradleModule: IdeaModule,
mainModuleNode: DataNode<ModuleData>,
projectDataNode: DataNode<ProjectData>,
resolverCtx: ProjectResolverContext
) {
LOG.logDebugIfEnabled("Start initialize data for Gradle module: [$gradleModule], Ide module: [$mainModuleNode], Ide project: [$projectDataNode]")
val mppModel = resolverCtx.getMppModel(gradleModule)
val project = resolverCtx.externalSystemTaskId.findProject()
if (mppModel != null) {
mppModel.targets.forEach { target ->
KotlinIDEGradleActionsFUSCollector.logImport(
project,
"MPP.${target.platform.id + (target.presetName?.let { ".$it" } ?: "")}")
}
return
}
val gradleModel = resolverCtx.getExtraProject(gradleModule, KotlinGradleModel::class.java) ?: return
if (gradleModel.hasKotlinPlugin) {
KotlinIDEGradleActionsFUSCollector.logImport(project, gradleModel.kotlinTarget ?: "unknown")
}
KotlinGradleProjectData().apply {
isResolved = true
kotlinTarget = gradleModel.kotlinTarget
hasKotlinPlugin = gradleModel.hasKotlinPlugin
coroutines = gradleModel.coroutines
platformPluginId = gradleModel.platformPluginId
pureKotlinSourceFolders.addAll(
gradleModel.kotlinTaskProperties.flatMap { it.value.pureKotlinSourceFolders ?: emptyList() }.map { it.absolutePath }
)
mainModuleNode.createChild(KotlinGradleProjectData.KEY, this)
}
if (gradleModel.hasKotlinPlugin) {
initializeGradleSourceSetsData(gradleModel, mainModuleNode)
}
}
private fun initializeGradleSourceSetsData(kotlinModel: KotlinGradleModel, mainModuleNode: DataNode<ModuleData>) {
kotlinModel.cachedCompilerArgumentsBySourceSet.forEach { (sourceSetName, cachedArgs) ->
KotlinGradleSourceSetData(sourceSetName).apply {
cachedArgsInfo = cachedArgs
additionalVisibleSourceSets = kotlinModel.additionalVisibleSourceSets.getValue(sourceSetName)
kotlinPluginVersion = kotlinModel.kotlinTaskProperties.getValue(sourceSetName).pluginVersion
mainModuleNode.kotlinGradleProjectDataNodeOrFail.createChild(KotlinGradleSourceSetData.KEY, this)
}
}
}
private fun useModulePerSourceSet(): Boolean {
// See AndroidGradleProjectResolver
if (isAndroidProjectKey != null && resolverCtx.getUserData(isAndroidProjectKey) == true) {
return false
}
return resolverCtx.isResolveModulePerSourceSet
}
private fun getDependencyByFiles(
files: Collection<File>,
outputToSourceSet: Map<String, com.intellij.openapi.util.Pair<String, ExternalSystemSourceType>>?,
sourceSetByName: Map<String, com.intellij.openapi.util.Pair<DataNode<GradleSourceSetData>, ExternalSourceSet>>?
) = files
.mapTo(HashSet()) {
val path = FileUtil.toSystemIndependentName(it.path)
val targetSourceSetId = outputToSourceSet?.get(path)?.first ?: return@mapTo null
sourceSetByName?.get(targetSourceSetId)?.first
}
.singleOrNull()
private fun DataNode<out ModuleData>.getDependencies(ideProject: DataNode<ProjectData>): Collection<DataNode<out ModuleData>> {
val cache = kotlinGradleProjectDataOrNull?.dependenciesCache ?: dependencyCacheFallback
if (cache.containsKey(ideProject)) {
return cache.getValue(ideProject)
}
val outputToSourceSet = ideProject.getUserData(GradleProjectResolver.MODULES_OUTPUTS)
val sourceSetByName = ideProject.getUserData(GradleProjectResolver.RESOLVED_SOURCE_SETS) ?: return emptySet()
val externalSourceSet = sourceSetByName[data.id]?.second ?: return emptySet()
val result = externalSourceSet.dependencies.mapNotNullTo(LinkedHashSet()) { dependency ->
when (dependency) {
is ExternalProjectDependency -> {
if (dependency.configurationName == Dependency.DEFAULT_CONFIGURATION) {
@Suppress("UNCHECKED_CAST") val targetModuleNode = ExternalSystemApiUtil.findFirstRecursively(ideProject) {
(it.data as? ModuleData)?.id == dependency.projectPath
} as DataNode<ModuleData>? ?: return@mapNotNullTo null
ExternalSystemApiUtil.findAll(targetModuleNode, GradleSourceSetData.KEY)
.firstOrNull { it.sourceSetName == "main" }
} else {
getDependencyByFiles(dependency.projectDependencyArtifacts, outputToSourceSet, sourceSetByName)
}
}
is FileCollectionDependency -> {
getDependencyByFiles(dependency.files, outputToSourceSet, sourceSetByName)
}
else -> null
}
}
cache[ideProject] = result
return result
}
private fun addTransitiveDependenciesOnImplementedModules(
gradleModule: IdeaModule,
ideModule: DataNode<ModuleData>,
ideProject: DataNode<ProjectData>
) {
val moduleNodesToProcess = if (useModulePerSourceSet()) {
ExternalSystemApiUtil.findAll(ideModule, GradleSourceSetData.KEY)
} else listOf(ideModule)
val ideaModulesByGradlePaths = gradleModule.project.modules.groupBy { it.gradleProject.path }
var dirtyDependencies = true
for (currentModuleNode in moduleNodesToProcess) {
val toProcess = ArrayDeque<DataNode<out ModuleData>>().apply { add(currentModuleNode) }
val discovered = HashSet<DataNode<out ModuleData>>().apply { add(currentModuleNode) }
while (toProcess.isNotEmpty()) {
val moduleNode = toProcess.pollLast()
val moduleNodeForGradleModel = if (useModulePerSourceSet()) {
ExternalSystemApiUtil.findParent(moduleNode, ProjectKeys.MODULE)
} else moduleNode
val ideaModule = if (moduleNodeForGradleModel != ideModule) {
moduleNodeForGradleModel?.data?.id?.let { ideaModulesByGradlePaths[it]?.firstOrNull() }
} else gradleModule
val implementsModuleIds = resolverCtx.getExtraProject(ideaModule, KotlinGradleModel::class.java)?.implements
?: emptyList()
for (implementsModuleId in implementsModuleIds) {
val targetModule = findModuleById(ideProject, gradleModule, implementsModuleId) ?: continue
if (useModulePerSourceSet()) {
val targetSourceSetsByName = ExternalSystemApiUtil
.findAll(targetModule, GradleSourceSetData.KEY)
.associateBy { it.sourceSetName }
val targetMainSourceSet = targetSourceSetsByName["main"] ?: targetModule
val targetSourceSet = targetSourceSetsByName[currentModuleNode.sourceSetName]
if (targetSourceSet != null) {
addDependency(currentModuleNode, targetSourceSet)
}
if (currentModuleNode.sourceSetName == "test" && targetMainSourceSet != targetSourceSet) {
addDependency(currentModuleNode, targetMainSourceSet)
}
} else {
dirtyDependencies = true
addDependency(currentModuleNode, targetModule)
}
}
val dependencies = if (useModulePerSourceSet()) {
moduleNode.getDependencies(ideProject)
} else {
if (dirtyDependencies) getDependencyModules(ideModule, gradleModule.project).also {
dirtyDependencies = false
} else emptyList()
}
// queue only those dependencies that haven't been discovered earlier
dependencies.filterTo(toProcess, discovered::add)
}
}
}
override fun populateModuleDependencies(
gradleModule: IdeaModule,
ideModule: DataNode<ModuleData>,
ideProject: DataNode<ProjectData>
) {
LOG.logDebugIfEnabled("Start populate module dependencies. Gradle module: [$gradleModule], Ide module: [$ideModule], Ide project: [$ideProject]")
val mppModel = resolverCtx.getMppModel(gradleModule)
if (mppModel != null) {
return super.populateModuleDependencies(gradleModule, ideModule, ideProject)
}
val gradleModel = resolverCtx.getExtraProject(gradleModule, KotlinGradleModel::class.java)
?: return super.populateModuleDependencies(gradleModule, ideModule, ideProject)
if (!useModulePerSourceSet()) {
super.populateModuleDependencies(gradleModule, ideModule, ideProject)
}
addTransitiveDependenciesOnImplementedModules(gradleModule, ideModule, ideProject)
addImplementedModuleNames(gradleModule, ideModule, ideProject, gradleModel)
if (useModulePerSourceSet()) {
super.populateModuleDependencies(gradleModule, ideModule, ideProject)
}
LOG.logDebugIfEnabled("Finish populating module dependencies. Gradle module: [$gradleModule], Ide module: [$ideModule], Ide project: [$ideProject]")
}
private fun addImplementedModuleNames(
gradleModule: IdeaModule,
dependentModule: DataNode<ModuleData>,
ideProject: DataNode<ProjectData>,
gradleModel: KotlinGradleModel
) {
val implementedModules = gradleModel.implements.mapNotNull { findModuleById(ideProject, gradleModule, it) }
val kotlinGradleProjectDataNode = dependentModule.kotlinGradleProjectDataNodeOrFail
val kotlinGradleProjectData = kotlinGradleProjectDataNode.data
val kotlinGradleSourceSetDataList = kotlinGradleProjectDataNode.kotlinGradleSourceSetDataNodes.map { it.data }
if (useModulePerSourceSet() && kotlinGradleProjectData.hasKotlinPlugin) {
val dependentSourceSets = dependentModule.getSourceSetsMap()
val implementedSourceSetMaps = implementedModules.map { it.getSourceSetsMap() }
for ((sourceSetName, _) in dependentSourceSets) {
kotlinGradleSourceSetDataList.find { it.sourceSetName == sourceSetName }?.implementedModuleNames =
implementedSourceSetMaps.mapNotNull { it[sourceSetName]?.data?.internalName }
}
} else {
kotlinGradleProjectData.implementedModuleNames = implementedModules.map { it.data.internalName }
}
}
private fun findModuleById(ideProject: DataNode<ProjectData>, gradleModule: IdeaModule, moduleId: String): DataNode<ModuleData>? {
val isCompositeProject = resolverCtx.models.ideaProject != gradleModule.project
val compositePrefix =
if (isCompositeProject && moduleId.startsWith(":")) gradleModule.project.name
else ""
val fullModuleId = compositePrefix + moduleId
@Suppress("UNCHECKED_CAST")
return ideProject.children.find { (it.data as? ModuleData)?.id == fullModuleId } as DataNode<ModuleData>?
}
override fun populateModuleContentRoots(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) {
nextResolver.populateModuleContentRoots(gradleModule, ideModule)
val moduleNamePrefix = GradleProjectResolverUtil.getModuleId(resolverCtx, gradleModule)
resolverCtx.getExtraProject(gradleModule, KotlinGradleModel::class.java)?.let { gradleModel ->
KotlinGradleFUSLogger.populateGradleUserDir(gradleModel.gradleUserHome)
val gradleSourceSets = ExternalSystemApiUtil.findAll(ideModule, GradleSourceSetData.KEY)
for (gradleSourceSetNode in gradleSourceSets) {
val propertiesForSourceSet =
gradleModel.kotlinTaskProperties.filter { (k, _) -> gradleSourceSetNode.data.id == "$moduleNamePrefix:$k" }
.toList().singleOrNull()
gradleSourceSetNode.children.forEach { dataNode ->
val data = dataNode.data as? ContentRootData
if (data != null) {
/*
Code snippet for setting in content root properties
if (propertiesForSourceSet?.second?.pureKotlinSourceFolders?.contains(File(data.rootPath)) == true) {
@Suppress("UNCHECKED_CAST")
(dataNode as DataNode<ContentRootData>).isPureKotlinSourceFolder = true
}*/
val packagePrefix = propertiesForSourceSet?.second?.packagePrefix
if (packagePrefix != null) {
ExternalSystemSourceType.values().filter { !(it.isResource || it.isGenerated) }.forEach { type ->
val paths = data.getPaths(type)
val newPaths = paths.map { ContentRootData.SourceRoot(it.path, packagePrefix) }
paths.clear()
paths.addAll(newPaths)
}
}
}
}
}
}
}
companion object {
private val LOG = Logger.getInstance(PsiPrecedences::class.java)
private fun Logger.logDebugIfEnabled(message: String) {
if (isDebugEnabled) debug(message)
}
private fun DataNode<ModuleData>.getSourceSetsMap() =
ExternalSystemApiUtil.getChildren(this, GradleSourceSetData.KEY).associateBy { it.sourceSetName }
private val DataNode<out ModuleData>.sourceSetName
get() = (data as? GradleSourceSetData)?.id?.substringAfterLast(':')
private fun addDependency(ideModule: DataNode<out ModuleData>, targetModule: DataNode<out ModuleData>) {
val moduleDependencyData = ModuleDependencyData(ideModule.data, targetModule.data)
moduleDependencyData.scope = DependencyScope.COMPILE
moduleDependencyData.isExported = false
moduleDependencyData.isProductionOnTestDependency = targetModule.sourceSetName == "test"
ideModule.createChild(ProjectKeys.MODULE_DEPENDENCY, moduleDependencyData)
}
private var DataNode<out ModuleData>.dependencyCacheFallback by NotNullableCopyableDataNodeUserDataProperty(
Key.create<MutableMap<DataNode<ProjectData>, Collection<DataNode<out ModuleData>>>>("MODULE_DEPENDENCIES_CACHE"),
hashMapOf()
)
}
}
| apache-2.0 | 5cfb7d4a60cfe42dbede6b475a3b8208 | 51.085774 | 159 | 0.703378 | 6.023954 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/UnaryOperatorReferenceSearcher.kt | 6 | 2203 | // 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.search.usagesSearch.operators
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.SearchRequestCollector
import com.intellij.psi.search.SearchScope
import com.intellij.util.Processor
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtUnaryExpression
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance
class UnaryOperatorReferenceSearcher(
targetFunction: PsiElement,
private val operationToken: KtSingleValueToken,
searchScope: SearchScope,
consumer: Processor<in PsiReference>,
optimizer: SearchRequestCollector,
options: KotlinReferencesSearchOptions
) : OperatorReferenceSearcher<KtUnaryExpression>(
targetFunction,
searchScope,
consumer,
optimizer,
options,
wordsToSearch = listOf(operationToken.value)
) {
override fun processPossibleReceiverExpression(expression: KtExpression) {
val unaryExpression = expression.parent as? KtUnaryExpression ?: return
if (unaryExpression.operationToken != operationToken) return
processReferenceElement(unaryExpression)
}
override fun isReferenceToCheck(ref: PsiReference): Boolean {
if (ref !is KtSimpleNameReference) return false
val element = ref.element
if (element.parent !is KtUnaryExpression) return false
return element.getReferencedNameElementType() == operationToken
}
override fun extractReference(element: KtElement): PsiReference? {
val unaryExpression = element as? KtUnaryExpression ?: return null
if (unaryExpression.operationToken != operationToken) return null
return unaryExpression.operationReference.references.firstIsInstance<KtSimpleNameReference>()
}
} | apache-2.0 | 778ac7e28ec04df8ce08a2b8a6c96da3 | 41.384615 | 158 | 0.788016 | 5.426108 | false | false | false | false |
ianhanniballake/muzei | muzei-api/src/main/java/com/google/android/apps/muzei/api/internal/RemoteActionBroadcastReceiver.kt | 1 | 3985 | /*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.api.internal
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_COMMAND
import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_COMMAND_ARTWORK_ID
import com.google.android.apps.muzei.api.internal.ProtocolConstants.KEY_COMMAND_AUTHORITY
import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_TRIGGER_COMMAND
import com.google.android.apps.muzei.api.provider.ProviderContract
/**
* A [BroadcastReceiver] specifically for maintaining backward compatibility with the
* `getCommands()` and `onCommand()` APIs for apps that upgrade to the latest version
* of the Muzei API without updating their `MuzeiArtProvider` to use the new
* [com.google.android.apps.muzei.api.provider.MuzeiArtProvider.getCommandActions].
*/
@RequiresApi(Build.VERSION_CODES.KITKAT)
public class RemoteActionBroadcastReceiver : BroadcastReceiver() {
public companion object {
/**
* Construct a [PendingIntent] suitable for passing to
* [androidx.core.app.RemoteActionCompat] that will trigger the
* `onCommand()` API of the `MuzeiArtProvider` associated with
* the [authority].
*
* When building your own [androidx.core.app.RemoteActionCompat], you
* should **not** use this method. Instead, register your own
* [BroadcastReceiver], [android.app.Service], or directly launch
* an [android.app.Activity] as needed by your command rather than go
* through the inefficiency of starting this receiver just to trigger
* your [com.google.android.apps.muzei.api.provider.MuzeiArtProvider].
*/
public fun createPendingIntent(
context: Context,
authority: String,
artworkId: Long,
id: Int
): PendingIntent {
val intent = Intent(context, RemoteActionBroadcastReceiver::class.java).apply {
putExtra(KEY_COMMAND_AUTHORITY, authority)
putExtra(KEY_COMMAND_ARTWORK_ID, artworkId)
putExtra(KEY_COMMAND, id)
}
return PendingIntent.getBroadcast(context,
id + 1000 * artworkId.toInt(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT)
}
}
override fun onReceive(context: Context, intent: Intent?) {
val authority = intent?.getStringExtra(KEY_COMMAND_AUTHORITY)
if (authority != null) {
val contentUri = ContentUris.withAppendedId(
ProviderContract.getContentUri(authority),
intent.getLongExtra(KEY_COMMAND_ARTWORK_ID, -1))
val id = intent.getIntExtra(KEY_COMMAND, -1)
val pendingResult = goAsync()
try {
context.contentResolver.call(contentUri,
METHOD_TRIGGER_COMMAND,
contentUri.toString(),
Bundle().apply { putInt(KEY_COMMAND, id) })
} finally {
pendingResult.finish()
}
}
}
}
| apache-2.0 | aed699ced903534a495cc5a400c371c4 | 42.791209 | 91 | 0.669009 | 4.789663 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/stash/ui/GitCompareWithLocalFromStashAction.kt | 1 | 1550 | // 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 git4idea.stash.ui
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.AnActionExtensionProvider
import com.intellij.openapi.vcs.changes.actions.ShowDiffWithLocalAction
import com.intellij.openapi.vcs.changes.actions.diff.ShowDiffAction
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase
class GitCompareWithLocalFromStashAction: AnActionExtensionProvider {
override fun isActive(e: AnActionEvent): Boolean {
return e.getData(GitStashUi.GIT_STASH_UI) != null &&
e.getData(ChangesBrowserBase.DATA_KEY) == null
}
override fun update(e: AnActionEvent) {
val project = e.project
val stashUi = e.getData(GitStashUi.GIT_STASH_UI)
if (project == null || stashUi == null) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.isVisible = true
e.presentation.isEnabled = stashUi.changesBrowser.changes.any { change ->
ShowDiffWithLocalAction.getChangeWithLocal(change, false) != null
}
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val changes = e.getRequiredData(GitStashUi.GIT_STASH_UI).changesBrowser.changes
val changesWithLocal = changes.mapNotNull { change ->
ShowDiffWithLocalAction.getChangeWithLocal(change, false)
}
ShowDiffAction.showDiffForChange(project, changesWithLocal)
}
} | apache-2.0 | 4bf4b9ec4781e5adb2b1c8de720600c8 | 40.918919 | 158 | 0.760645 | 4.258242 | false | false | false | false |
xmartlabs/bigbang | app/src/main/java/com/xmartlabs/template/model/BuildInfo.kt | 2 | 389 | package com.xmartlabs.template.model
import com.xmartlabs.template.BuildConfig
import com.xmartlabs.bigbang.core.model.BuildInfo as CoreBuildInfo
class BuildInfo : CoreBuildInfo {
override val isDebug = BuildConfig.DEBUG
override val isStaging = BuildConfig.FLAVOR == BuildType.STAGING.toString()
override val isProduction = BuildConfig.FLAVOR == BuildType.PRODUCTION.toString()
}
| apache-2.0 | 9dfee0a98126bee160d2710ee0025ae3 | 37.9 | 83 | 0.812339 | 4.630952 | false | true | false | false |
excref/kotblog | blog/service/impl/src/test/kotlin/com/excref/kotblog/blog/service/user/UserServiceIntegrationTest.kt | 1 | 1527 | package com.excref.kotblog.blog.service.user
import com.excref.kotblog.blog.service.test.AbstractServiceIntegrationTest
import com.excref.kotblog.blog.service.user.domain.UserRole
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
/**
* @author Arthur Asatryan
* @since 6/8/17 1:21 AM
*/
class UserServiceIntegrationTest : AbstractServiceIntegrationTest() {
//region Dependencies
@Autowired
private lateinit var userService: UserService
//endregion
//region Test methods
@Test
fun testCreate() {
// given
val email = "[email protected]"
val password = "you can't even guess me! :P"
val role = UserRole.USER
// when
val result = userService.create(email, password, role)
// then
assertThat(result).isNotNull().extracting("email", "password", "role").containsOnly(email, password, role)
}
@Test
fun testGetByUuid() {
// given
val user = helper.persistUser()
val uuid = user.uuid
// when
val result = userService.getByUuid(uuid)
// then
assertThat(result).isNotNull().isEqualTo(user)
}
@Test
fun testExistsForEmail() {
// given
val email = "[email protected]"
helper.persistUser(email = email)
// when
val existsForEmail = userService.existsForEmail(email)
assertThat(existsForEmail).isTrue()
}
//endregion
} | apache-2.0 | e31426bc3be27f92895c90d8653864b9 | 27.296296 | 114 | 0.655534 | 4.400576 | false | true | false | false |
google/intellij-gn-plugin | src/main/java/com/google/idea/gn/psi/builtin/SetDefaultToolchain.kt | 1 | 850 | // Copyright (c) 2020 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package com.google.idea.gn.psi.builtin
import com.google.idea.gn.completion.CompletionIdentifier
import com.google.idea.gn.psi.Function
import com.google.idea.gn.psi.GnCall
import com.google.idea.gn.psi.GnValue
import com.google.idea.gn.psi.scope.Scope
class SetDefaultToolchain : Function {
// TODO implement
override fun execute(call: GnCall, targetScope: Scope): GnValue? = null
override val isBuiltin: Boolean
get() = true
override val identifierName: String
get() = NAME
override val identifierType: CompletionIdentifier.IdentifierType
get() = CompletionIdentifier.IdentifierType.FUNCTION
companion object {
const val NAME = "set_default_toolchain"
}
}
| bsd-3-clause | 834b3d7a5580f88e839ad054862316e5 | 31.692308 | 73 | 0.763529 | 3.953488 | false | false | false | false |
EMResearch/EvoMaster | e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/nullableInput/DataRepository.kt | 1 | 1296 | package com.foo.graphql.nullableInput
import com.foo.graphql.nullableInput.type.Flower
import org.springframework.stereotype.Component
@Component
open class DataRepository {
//flowersNullInNullOut(id: [Int]): Flower
fun findFlowersNullInNullOut(id: Array<Int?>?): Flower? {
return if (id == null) null
else
if (id.all { it != null }) Flower(0, "flowerNameX") else null
}
//flowersNullIn(id: [Int]!): Flower
fun findFlowersNullIn(id: Array<Int?>): Flower? {
return if (id.all { it != null }) Flower(0, "flowerNameX") else null
}
//flowersNullOut(id: [Int!]): Flower
fun findFlowersNullOut(id: Array<Int>?): Flower? {
return if (id == null) null
else Flower(0, "flowerNameX")
}
// flowersNotNullInOut(id: [Int!]!): Flower
fun findFlowersNotNullInOut(id: Array<Int>): Flower? {
return Flower(0, "flowerNameX")
}
fun findFlowersScalarNullable(id: Boolean?): Flower? {
return if (id == null) null else
if (id) Flower(1, "flowerNameIdTrue")
else Flower(0, "flowerNameIdFalse")
}
fun findFlowersScalarNotNullable(id: Boolean): Flower? {
return if (id) Flower(1, "flowerNameIdTrue")
else Flower(0, "flowerNameIdFalse")
}
}
| lgpl-3.0 | ec6b7341943fa0f82028a78423db08cd | 26.574468 | 76 | 0.628858 | 3.915408 | false | false | false | false |
Litote/kmongo | kmongo-rxjava2-core-tests/src/main/kotlin/org/litote/kmongo/rxjava2/FindOneAndModifyTest.kt | 1 | 3508 | /*
* Copyright (C) 2016/2022 Litote
*
* 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.litote.kmongo.rxjava2
import com.mongodb.client.model.FindOneAndUpdateOptions
import com.mongodb.client.model.ReturnDocument.AFTER
import org.bson.Document
import org.bson.types.ObjectId
import org.junit.Test
import org.litote.kmongo.MongoOperator.set
import org.litote.kmongo.MongoOperator.setOnInsert
import org.litote.kmongo.json
import org.litote.kmongo.model.ExposableFriend
import org.litote.kmongo.model.Friend
import kotlin.test.assertEquals
import kotlin.test.assertNull
/**
*
*/
class FindOneAndModifyTest : KMongoRxBaseTest<Friend>() {
@Test
fun canFindAndUpdateOne() {
col.insertOne(Friend("John", "22 Wall Street Avenue")).blockingAwait()
col.findOneAndUpdate("{name:'John'}", "{$set: {address: 'A better place'}}").blockingGet() ?: throw AssertionError("Value cannot null!")
val savedFriend = col.findOne("{name:'John'}").blockingGet() ?: throw AssertionError("Value cannot null!")
assertEquals("John", savedFriend.name)
assertEquals("A better place", savedFriend.address)
}
@Test
fun canFindAndUpdateWithNullValue() {
col.insertOne(Friend("John", "22 Wall Street Avenue")).blockingAwait()
col.findOneAndUpdate("{name:'John'}", "{$set: {address: null}}").blockingGet() ?: throw AssertionError("Value cannot null!")
val friend = col.findOne("{name:'John'}").blockingGet() ?: throw AssertionError("Value cannot null!")
assertEquals("John", friend.name)
assertNull(friend.address)
}
@Test
fun canFindAndUpdateWithDocument() {
val col2 = col.withDocumentClass<Document>()
col.insertOne(Friend("John", "22 Wall Street Avenue")).blockingAwait()
col2.findOneAndUpdate("{name:'John'}", "{$set: {address: 'A better place'}}").blockingGet() ?: throw AssertionError("Value cannot null!")
val friend = col2.findOne("{name:'John'}").blockingGet() ?: throw AssertionError("Value cannot null!")
assertEquals("John", friend["name"])
assertEquals("A better place", friend["address"])
}
@Test
fun canUpsertByObjectId() {
val expected = Friend(ObjectId(), "John")
val friend = col.findOneAndUpdate(
"{_id:${expected._id!!.json}}",
"{$setOnInsert: {name: 'John'}}",
FindOneAndUpdateOptions().upsert(true).returnDocument(AFTER)).blockingGet() ?: throw AssertionError("Value cannot null!")
assertEquals(expected, friend)
}
@Test
fun canUpsertByStringId() {
val expected = ExposableFriend(ObjectId().toString(), "John")
val friend = col.withDocumentClass<ExposableFriend>().findOneAndUpdate(
"{_id:${expected._id.json}}",
"{$setOnInsert: {name: 'John'}}",
FindOneAndUpdateOptions().upsert(true).returnDocument(AFTER)).blockingGet()
assertEquals(expected, friend)
}
} | apache-2.0 | a581c552a156fd3c232e02337186dce6 | 39.802326 | 145 | 0.678734 | 4.514801 | false | true | false | false |
EMResearch/EvoMaster | core/src/test/kotlin/org/evomaster/core/output/WriteXMLTest.kt | 1 | 5819 | package org.evomaster.core.output
import org.evomaster.client.java.controller.api.dto.database.schema.DatabaseType
import org.evomaster.core.EMConfig
import org.evomaster.core.database.DbAction
import org.evomaster.core.database.schema.Column
import org.evomaster.core.database.schema.ColumnDataType
import org.evomaster.core.database.schema.Table
import org.evomaster.core.output.EvaluatedIndividualBuilder.Companion.buildEvaluatedIndividual
import org.evomaster.core.output.service.PartialOracles
import org.evomaster.core.output.service.RestTestCaseWriter
import org.evomaster.core.search.gene.ObjectGene
import org.evomaster.core.search.gene.sql.SqlXMLGene
import org.evomaster.core.search.gene.string.StringGene
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class WriteXMLTest {
private fun getConfig(format: OutputFormat): EMConfig {
val config = EMConfig()
config.outputFormat = format
config.expectationsActive = false
config.testTimeout = -1
return config
}
@Test
fun testEmptyXML() {
val xmlColumn = Column("xmlColumn", ColumnDataType.XML, 10, primaryKey = false, autoIncrement = false, databaseType = DatabaseType.POSTGRES)
val table = Table("Table0", setOf(xmlColumn), setOf())
val objectGene = ObjectGene("anElement", listOf())
val sqlXMLGene = SqlXMLGene("xmlColumn", objectGene)
val insert = DbAction(table, setOf(xmlColumn), 0L, listOf(sqlXMLGene))
val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insert))
val config = getConfig(format)
val test = TestCase(test = ei, name = "test")
val writer = RestTestCaseWriter(config, PartialOracles())
val lines = writer.convertToCompilableTestCode(test, baseUrlOfSut)
val expectedLines = Lines().apply {
add("@Test")
add("public void test() throws Exception {")
indent()
add("List<InsertionDto> insertions = sql().insertInto(\"Table0\", 0L)")
indent()
indent()
add(".d(\"xmlColumn\", \"\\\"<anElement></anElement>\\\"\")")
deindent()
add(".dtos();")
deindent()
add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);")
deindent()
add("}")
}
Assertions.assertEquals(expectedLines.toString(), lines.toString())
}
@Test
fun testChildrenXML() {
val xmlColumn = Column("xmlColumn", ColumnDataType.XML, 10, primaryKey = false, autoIncrement = false,
databaseType = DatabaseType.POSTGRES)
val table = Table("Table0", setOf(xmlColumn), setOf())
val child0 = ObjectGene("child", listOf())
val child1 = ObjectGene("child", listOf())
val child2 = ObjectGene("child", listOf())
val child3 = ObjectGene("child", listOf())
val objectGene = ObjectGene("anElement", listOf(child0, child1, child2, child3))
val sqlXMLGene = SqlXMLGene("xmlColumn", objectGene)
val insert = DbAction(table, setOf(xmlColumn), 0L, listOf(sqlXMLGene))
val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insert))
val config = getConfig(format)
val test = TestCase(test = ei, name = "test")
val writer = RestTestCaseWriter(config, PartialOracles())
val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut)
val expectedLines = Lines().apply {
add("@Test")
add("public void test() throws Exception {")
indent()
add("List<InsertionDto> insertions = sql().insertInto(\"Table0\", 0L)")
indent()
indent()
add(".d(\"xmlColumn\", \"\\\"<anElement><child></child><child></child><child></child><child></child></anElement>\\\"\")")
deindent()
add(".dtos();")
deindent()
add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);")
deindent()
add("}")
}
Assertions.assertEquals(expectedLines.toString(), lines.toString())
}
@Test
fun testString() {
val xmlColumn = Column("xmlColumn", ColumnDataType.XML, 10, primaryKey = false, autoIncrement = false,
databaseType = DatabaseType.POSTGRES)
val table = Table("Table0", setOf(xmlColumn), setOf())
val stringGene = StringGene("stringValue", value = "</element>")
val objectGene = ObjectGene("anElement", listOf(stringGene))
val sqlXMLGene = SqlXMLGene("xmlColumn", objectGene)
val insert = DbAction(table, setOf(xmlColumn), 0L, listOf(sqlXMLGene))
val (format, baseUrlOfSut, ei) = buildEvaluatedIndividual(mutableListOf(insert))
val config = getConfig(format)
val test = TestCase(test = ei, name = "test")
val writer = RestTestCaseWriter(config, PartialOracles())
val lines = writer.convertToCompilableTestCode( test, baseUrlOfSut)
val expectedLines = Lines().apply {
add("@Test")
add("public void test() throws Exception {")
indent()
add("List<InsertionDto> insertions = sql().insertInto(\"Table0\", 0L)")
indent()
indent()
add(".d(\"xmlColumn\", \"\\\"<anElement></element></anElement>\\\"\")")
deindent()
add(".dtos();")
deindent()
add("InsertionResultsDto insertionsresult = controller.execInsertionsIntoDatabase(insertions);")
deindent()
add("}")
}
Assertions.assertEquals(expectedLines.toString(), lines.toString())
}
}
| lgpl-3.0 | 170303887876f50b4e7743fac429ebc5 | 35.597484 | 148 | 0.633958 | 4.869456 | false | true | false | false |
sonnytron/FitTrainerBasic | mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/adapters/ExerciseItemUi.kt | 1 | 1211 | package com.sonnyrodriguez.fittrainer.fittrainerbasic.adapters
import android.support.v4.content.ContextCompat
import android.view.Gravity
import android.view.ViewGroup
import com.sonnyrodriguez.fittrainer.fittrainerbasic.R
import org.jetbrains.anko.*
class ExerciseItemUi: AnkoComponent<ViewGroup> {
override fun createView(ui: AnkoContext<ViewGroup>) = with(ui) {
relativeLayout {
backgroundDrawable = ContextCompat.getDrawable(ctx, R.drawable.list_background_white)
lparams(width = matchParent, height = wrapContent) {
horizontalMargin = dip(16)
verticalPadding = dip(8)
}
verticalLayout {
themedTextView(R.style.BasicListItemTitle) {
id = R.id.exercise_item_title
}.lparams(width = matchParent, height = wrapContent) {
gravity = Gravity.CENTER
}
themedTextView(R.style.BasicListItemStyle) {
id = R.id.exercise_item_muscle
}.lparams(width = matchParent, height = wrapContent) {
gravity = Gravity.BOTTOM
}
}
}
}
}
| apache-2.0 | 12ba5c21a7a2c70940215565b985b9e6 | 36.84375 | 97 | 0.604459 | 5.045833 | false | false | false | false |
memoizr/shank | android/src/main/java/life/shank/android/ShankContentProvider.kt | 1 | 1013 | package life.shank.android
import android.app.Application
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
class ShankContentProvider : ContentProvider() {
override fun onCreate(): Boolean {
(context!!.applicationContext as Application).registerActivityLifecycleCallbacks(AutoScopedActivityLifecycleCallbacks)
AppContextModule.apply { context = [email protected]!!.applicationContext }
return true
}
override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? = null
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int = 0
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int = 0
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun getType(uri: Uri): String? = ""
} | apache-2.0 | b35e459c027c030662ed9142b29258e5 | 47.285714 | 147 | 0.752221 | 4.870192 | false | false | false | false |
frendyxzc/KotlinNews | model/src/main/java/vip/frendy/model/net/Request.kt | 1 | 1432 | package vip.frendy.model.net
import android.content.Context
import com.google.gson.Gson
import vip.frendy.model.entity.*
import vip.frendy.model.util.DeviceInfo
/**
* Created by iiMedia on 2017/6/2.
*/
class Request(val context: Context, val gson: Gson = Gson()) {
fun init(): UserID {
val params: ReqInit = ReqInit(DeviceInfo.getAndroidID(context))
val url = RequestCommon.INIT_URL + gson.toJson(params)
val jsonStr = RequestCommon(url).run()
return gson.fromJson(jsonStr, RespInit::class.java).data
}
fun getChannelList(uid: String, type: Int = 0): ArrayList<Channel> {
val url = RequestCommon.GET_CHANNEL + "×tamp=" + System.currentTimeMillis() + "&uid=" + uid + "&news_type=" + type
val jsonStr = RequestCommon(url).run()
return gson.fromJson(jsonStr, RespGetChannel::class.java).data.channel_list
}
fun getNewsList(uid: String, cid: String): ArrayList<News> {
val url = RequestCommon.GET_NEWS_LIST + "&uid=" + uid + "&type_id=" + cid
val jsonStr = RequestCommon(url).run()
return gson.fromJson(jsonStr, RespGetNews::class.java).data
}
fun getVideoList(uid: String, cid: String): ArrayList<News> {
val url = RequestCommon.GET_VIDEO_LIST + "&uid=" + uid + "&type_id=" + cid
val jsonStr = RequestCommon(url).run()
return gson.fromJson(jsonStr, RespGetNews::class.java).data
}
} | mit | c0bf460f157ed1c11c4cbe1ce4540a12 | 33.95122 | 127 | 0.65852 | 3.768421 | false | false | false | false |
AlmasB/FXGL | fxgl-samples/src/main/kotlin/sandbox/subscene/AboutSubScene.kt | 1 | 916 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package sandbox.subscene
import com.almasb.fxgl.dsl.FXGL
import com.almasb.fxgl.scene.SubScene
import javafx.event.EventHandler
import javafx.scene.paint.Color
class AboutSubScene : SubScene() {
init {
var top = 30.0
val title = FXGL.getUIFactoryService().newText("About Screen", Color.BLACK, 22.0)
title.translateX = LEFT
title.translateY = top
contentRoot.children.add(title)
top += VERTICAL_GAP
val exitButton = FXGL.getUIFactoryService().newButton("Main Menu")
exitButton.translateX = LEFT
exitButton.translateY = top
exitButton.onAction = EventHandler {
FXGL.getEventBus().fireEvent(NavigateEvent(MAIN_VIEW))
}
contentRoot.children.add(exitButton)
}
}
| mit | 759a164656bbf11810838e383ef8f66b | 25.171429 | 89 | 0.667031 | 4.240741 | false | false | false | false |
dim1989/zhangzhoujun.github.io | KLMLibrary/library/src/main/java/com/kalemao/library/base/BaseActivity.kt | 1 | 11941 | package com.kalemao.library.base
import android.Manifest
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import butterknife.ButterKnife
import com.kalemao.library.R
import com.kalemao.library.utils.ActivityManager
import org.jetbrains.anko.alert
import org.jetbrains.anko.toast
/**
* Created by dim on 2017/5/27 10:07
* 邮箱:[email protected]
*/
abstract class BaseActivity : AppCompatActivity() {
// 检测SD卡权限
val WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 1
// 相机权限
val CAMERA_REQUEST_CODE = 2
// 电话权限
val CALL_PHONE_REQUEST_CODE = 3
// READ_PHONE_STATE
val READ_PHONE_STATE = 4
// 精准定位服务
val ACCESS_FINE_LOCATION = 5
// 大致定位服务
val ACCESS_COARSE_LOCATION = 6
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ActivityManager.getInstance().addActivity(this)
beforeInit()
if (getContentViewLayoutID() != 0) {
setContentView(getContentViewLayoutID())
}
//绑定activity
ButterKnife.bind( this ) ;
initView(savedInstanceState)
}
override fun onDestroy() {
super.onDestroy()
ActivityManager.getInstance().popOneActivity(this)
}
/**
* 界面初始化前期准备
*/
protected fun beforeInit() {}
/**
* 获取布局ID
* @return 布局id
*/
abstract protected fun getContentViewLayoutID(): Int
/**
* 初始化布局以及View控件
*/
protected abstract fun initView(savedInstanceState: Bundle?)
/**
* 申请对应的权限
*/
protected fun doesNeedCheckoutPermission(requestCode: Int): Boolean {
if (Build.VERSION.SDK_INT >= 23) {
// 申请WRITE_EXTERNAL_STORAGE权限
if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// 申请WRITE_EXTERNAL_STORAGE权限
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), WRITE_EXTERNAL_STORAGE_REQUEST_CODE)
} else if (requestCode == CAMERA_REQUEST_CODE && ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
// 申请CAMERA权限
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), CAMERA_REQUEST_CODE)
} else if (requestCode == CALL_PHONE_REQUEST_CODE && ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// 申请电话权限
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE), CALL_PHONE_REQUEST_CODE)
} else if (requestCode == READ_PHONE_STATE && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
// 申请READ_PHONE_STATE权限
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_PHONE_STATE), READ_PHONE_STATE)
} else if (requestCode == ACCESS_FINE_LOCATION && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 申请精准定位服务
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), ACCESS_FINE_LOCATION)
} else if (requestCode == ACCESS_COARSE_LOCATION && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 申请大致定位服务
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), ACCESS_COARSE_LOCATION)
} else {
return false
}
return true
} else {
// Pre-Marshmallow
return false
}
}
/**
* 是否具有某种权限
* @param requestCode
* *
* @return
*/
protected fun doesHaveCheckoutPermission(requestCode: Int): Boolean {
if (Build.VERSION.SDK_INT >= 23) {
if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
} else if (requestCode == CAMERA_REQUEST_CODE && ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
} else if (requestCode == CALL_PHONE_REQUEST_CODE && ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
} else if (requestCode == READ_PHONE_STATE && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
} else if (requestCode == ACCESS_FINE_LOCATION && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
} else if (requestCode == ACCESS_COARSE_LOCATION && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
} else {
return false
}
return true
} else {
// Pre-Marshmallow
return false
}
}
/**
* 是否需要申请SD卡权限
* @return
*/
protected fun doesNeedCheckoutPermissionWriteExternalStorage(): Boolean {
return doesNeedCheckoutPermission(WRITE_EXTERNAL_STORAGE_REQUEST_CODE)
}
/**
* 是否需要申请相机权限
* @return
*/
protected fun doesNeedCheckoutPermissionCamera(): Boolean {
return doesNeedCheckoutPermission(CAMERA_REQUEST_CODE)
}
/**
* 是否需要申请READ_PHONE_STATE权限
* @return
*/
protected fun doesNeedCheckoutPermissionPhotoState(): Boolean {
return doesNeedCheckoutPermission(READ_PHONE_STATE)
}
/**
* 是否需要申请打电话权限
* @return
*/
protected fun doesNeedCheckoutPermissionCallPhone(): Boolean {
return doesNeedCheckoutPermission(CALL_PHONE_REQUEST_CODE)
}
/**
* 是否需要打开精准定位服务
* @return
*/
protected fun doesNeedCheckoutPermissionPreciseLocation(): Boolean {
return doesNeedCheckoutPermission(ACCESS_FINE_LOCATION)
}
/**
* 是否需要打开大致定位服务
* @return
*/
protected fun doesNeedCheckoutPermissionApproximateLocation(): Boolean {
return doesNeedCheckoutPermission(ACCESS_COARSE_LOCATION)
}
/**
* 是否具有大致定位服务
* @return
*/
protected fun doesHaveCheckoutPermissionApproximateLocation(): Boolean {
return doesHaveCheckoutPermission(ACCESS_COARSE_LOCATION)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
doRequestPermissionsNext(requestCode, grantResults)
}
/*
* 处理申请权限返回判断
*/
protected fun doRequestPermissionsNext(requestCode: Int, grantResults: IntArray) {
if (grantResults.size != 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted 允许
onRequestPermissionsGranted(requestCode)
} else {
// Permission Denied 拒绝
onRequestPermissionsDenied(requestCode)
}
}
}
/**
* 申请权限同意返回的
* @param requestCode
* * 当前权限类型
*/
protected fun onRequestPermissionsGranted(requestCode: Int) {
toast(resources.getString(R.string.permission_ok))
}
/**
* 申请权限拒绝了返回的
* @param requestCode
* * 当前权限类型
*/
protected fun onRequestPermissionsDenied(requestCode: Int) {
showDeniedPermissionsAlert(requestCode)
}
/**
* 申请权限初次取消再次弹窗提示然后弹窗消失的时候的回调
* @param requestCode
*/
protected fun onRequestPermissionsDialogDismiss(requestCode: Int, goToSet: Boolean) {}
/**
* 申请权限拒绝之后的提醒对话框
* @param requestCode
*/
protected fun showDeniedPermissionsAlert(requestCode: Int) {
if (requestCode == 65543) {
return
}
var toastMessageRequest = ""
var toastMessage: String
// 申请WRITE_EXTERNAL_STORAGE权限
if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
toastMessageRequest = resources.getString(R.string.request_write_external_storage)
} else if (requestCode == CAMERA_REQUEST_CODE) {
toastMessageRequest = resources.getString(R.string.request_camera)
} else if (requestCode == CALL_PHONE_REQUEST_CODE) {
toastMessageRequest = resources.getString(R.string.request_call_phone)
} else if (requestCode == ACCESS_FINE_LOCATION) {
toastMessageRequest = resources.getString(R.string.request_access_fine_location)
} else if (requestCode == ACCESS_COARSE_LOCATION) {
toastMessageRequest = resources.getString(R.string.request_access_fine_location)
} else if (requestCode == READ_PHONE_STATE) {
toastMessageRequest = resources.getString(R.string.request_read_phone)
} else {
return
}
toastMessage = String.format("%s%s%s%s%s%s", resources.getString(R.string.request_access_left), getApplicationName(), toastMessageRequest, resources.getString(R.string.request_access_right_1),
getApplicationName(), resources.getString(R.string.request_access_right_2))
alert(toastMessage, resources.getString(R.string.permission_need)) {
positiveButton(resources.getString(R.string.go_set)) {
gotoSetPermissions()
[email protected]()
onRequestPermissionsDialogDismiss(requestCode, true)
}
negativeButton(resources.getString(R.string.cancel)) {
[email protected]()
onRequestPermissionsDialogDismiss(requestCode, false)
doesNeedFinish()
}
}.show()
}
protected fun doesNeedFinish(){
}
/**
* 获取当前应用的名称
*/
protected fun getApplicationName(): String {
var packageManager: PackageManager? = null
var applicationInfo: ApplicationInfo? = null
try {
packageManager = applicationContext.packageManager
applicationInfo = packageManager!!.getApplicationInfo(packageName, 0)
} catch (e: PackageManager.NameNotFoundException) {
applicationInfo = null
}
val applicationName = packageManager!!.getApplicationLabel(applicationInfo) as String
return applicationName
}
/**
* 打开权限设置界面
*/
protected fun gotoSetPermissions() {
val intent = Intent(Settings.ACTION_APPLICATION_SETTINGS)
startActivity(intent)
}
override fun onBackPressed() {
super.onBackPressed()
[email protected]()
}
} | epl-1.0 | 12678885f05bf043d53a29114ca8c82d | 35.101587 | 200 | 0.656407 | 4.808034 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/TiledAppearance.kt | 1 | 5405 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle
import org.joml.Matrix4f
import uk.co.nickthecoder.tickle.graphics.Renderer
import uk.co.nickthecoder.tickle.util.Rectd
import uk.co.nickthecoder.tickle.util.string
/**
* Tiles a single Pose to build an image of the required width and height.
* This is useful for creating rectangular objects that can have an arbitrary size, such as floors and walls
* as well as patterned backgrounds.
*
* Note that rendering is done by repeatedly drawing the Pose, so if the Pose is small compared to the Actor's size,
* then it will be somewhat slow. So if you want to tile a small pattern, consider making the Pose have multiple copies
* of the pattern.
*/
class TiledAppearance(actor: Actor, val pose: Pose) : ResizeAppearance(actor) {
override val directionRadians: Double
get() = pose.direction.radians
private val poseWidth = pose.rect.width
private val poseHeight = pose.rect.height
private val partPose = pose.copy()
init {
size.x = pose.rect.width.toDouble()
size.y = pose.rect.height.toDouble()
oldSize.set(size)
sizeAlignment.x = pose.offsetX / pose.rect.width
sizeAlignment.y = pose.offsetY / pose.rect.height
oldAlignment.set(sizeAlignment)
}
override fun draw(renderer: Renderer) {
//println("Drawing tiled")
val left = actor.x - sizeAlignment.x * width()
val bottom = actor.y - sizeAlignment.y * height()
val simple = actor.isSimpleImage()
val modelMatrix: Matrix4f?
if (!simple) {
modelMatrix = actor.calculateModelMatrix()
} else {
modelMatrix = null
}
// Draw all of the complete pieces (i.e. where the pose does not need clipping).
var y = 0.0
while (y < size.y - poseHeight) {
var x = 0.0
while (x < size.x - poseWidth) {
//println("Drawing whole part from ${pose.rect}")
drawPart(
renderer,
left + x, bottom + y, left + x + poseWidth, bottom + y + poseHeight,
pose.rectd,
modelMatrix)
x += poseWidth
}
y += poseHeight
}
val rightEdge = size.x - if (size.x % poseWidth == 0.0) poseWidth.toDouble() else size.x % poseWidth
val topEdge = y
val partWidth = size.x - rightEdge
val partHeight = size.y - topEdge
//println("Size.x = ${size.x} rightEdge = $rightEdge partWidth = ${partWidth} topEdge = ")
// Draw the partial pieces on the right edge
y = 0.0
partPose.rect.top = pose.rect.top
partPose.rect.right = (pose.rect.left + partWidth).toInt()
partPose.updateRectd()
while (y < size.y - poseHeight) {
//println("Drawing right edge from ${partPose.rect}")
drawPart(renderer,
left + rightEdge, bottom + y, left + size.x, bottom + y + poseHeight,
partPose.rectd,
modelMatrix)
y += poseHeight
}
// Draw the partial pieces on the top edge
var x = 0.0
partPose.rect.top = (pose.rect.bottom - partHeight).toInt()
partPose.rect.right = pose.rect.right
partPose.updateRectd()
while (x < size.x - poseWidth) {
//println("Drawing top edge from ${partPose.rect}")
drawPart(renderer,
left + x, bottom + topEdge, left + x + poseWidth, bottom + size.y,
partPose.rectd,
modelMatrix)
x += poseWidth
}
// Draw the partial piece in the top right corner
if (rightEdge < size.x && topEdge < size.y) {
partPose.rect.right = (pose.rect.left + partWidth).toInt()
partPose.rect.top = (pose.rect.bottom - partHeight).toInt()
partPose.updateRectd()
// println("Drawing corner from ${partPose.rect}")
drawPart(renderer,
left + rightEdge, bottom + topEdge, left + size.x, bottom + size.y,
partPose.rectd,
modelMatrix)
}
// println("Done tiled\n")
}
fun drawPart(renderer: Renderer, x0: Double, y0: Double, x1: Double, y1: Double, srcRect: Rectd, modelMatrix: Matrix4f?) {
if (modelMatrix == null) {
renderer.drawTexture(pose.texture, x0, y0, x1, y1, srcRect, actor.color)
} else {
renderer.drawTexture(pose.texture, x0, y0, x1, y1, srcRect, actor.color, modelMatrix)
}
}
override fun toString() = "TiledAppearance pose=$pose size=${size.string()}"
}
| gpl-3.0 | d56915d132c9a18ac69378ae607cfd1e | 36.275862 | 126 | 0.604995 | 4.279493 | false | false | false | false |
FWDekker/intellij-randomness | src/main/kotlin/com/fwdekker/randomness/fixedlength/FixedLengthDecorator.kt | 1 | 1727 | package com.fwdekker.randomness.fixedlength
import com.fwdekker.randomness.Bundle
import com.fwdekker.randomness.SchemeDecorator
/**
* Forces generated strings to be exactly [length] characters.
*
* @property enabled Whether to apply this decorator.
* @property length The enforced length.
* @property filler The character to pad strings that are too short with.
*/
data class FixedLengthDecorator(
var enabled: Boolean = DEFAULT_ENABLED,
var length: Int = DEFAULT_LENGTH,
var filler: String = DEFAULT_FILLER
) : SchemeDecorator() {
override val decorators: List<SchemeDecorator> = emptyList()
override val name = Bundle("fixed_length.title")
override fun generateUndecoratedStrings(count: Int): List<String> =
if (enabled) generator(count).map { it.take(length).padStart(length, filler[0]) }
else generator(count)
override fun doValidate() =
if (length < MIN_LENGTH) Bundle("fixed_length.error.length_too_low", MIN_LENGTH)
else if (filler.length != 1) Bundle("fixed_length.error.filler_length")
else null
override fun deepCopy(retainUuid: Boolean) = copy().also { if (retainUuid) it.uuid = this.uuid }
/**
* Holds constants.
*/
companion object {
/**
* The default value of the [enabled] field.
*/
const val DEFAULT_ENABLED = false
/**
* The minimum valid value of the [length] field.
*/
const val MIN_LENGTH = 1
/**
* The default value of the [length] field.
*/
const val DEFAULT_LENGTH = 3
/**
* The default value of the [filler] field.
*/
const val DEFAULT_FILLER = "0"
}
}
| mit | dd03a8e8450c64e8bcb4070544746a16 | 27.783333 | 100 | 0.636364 | 4.222494 | false | false | false | false |
coil-kt/coil | coil-base/src/main/java/coil/util/ImageLoaderOptions.kt | 1 | 1289 | package coil.util
import coil.ImageLoader
import coil.RealImageLoader
import coil.decode.BitmapFactoryDecoder.Companion.DEFAULT_MAX_PARALLELISM
import coil.decode.ExifOrientationPolicy
/**
* Private configuration options used by [RealImageLoader].
*
* @see ImageLoader.Builder
*/
internal class ImageLoaderOptions(
val addLastModifiedToFileCacheKey: Boolean = true,
val networkObserverEnabled: Boolean = true,
val respectCacheHeaders: Boolean = true,
val bitmapFactoryMaxParallelism: Int = DEFAULT_MAX_PARALLELISM,
val bitmapFactoryExifOrientationPolicy: ExifOrientationPolicy = ExifOrientationPolicy.RESPECT_PERFORMANCE
) {
fun copy(
addLastModifiedToFileCacheKey: Boolean = this.addLastModifiedToFileCacheKey,
networkObserverEnabled: Boolean = this.networkObserverEnabled,
respectCacheHeaders: Boolean = this.respectCacheHeaders,
bitmapFactoryMaxParallelism: Int = this.bitmapFactoryMaxParallelism,
bitmapFactoryExifOrientationPolicy: ExifOrientationPolicy = this.bitmapFactoryExifOrientationPolicy,
) = ImageLoaderOptions(
addLastModifiedToFileCacheKey,
networkObserverEnabled,
respectCacheHeaders,
bitmapFactoryMaxParallelism,
bitmapFactoryExifOrientationPolicy
)
}
| apache-2.0 | 3701d632563e52f6f332729e12236d97 | 36.911765 | 109 | 0.783553 | 5.304527 | false | false | false | false |
andrey7mel/realm_example | app/src/main/java/com/andrey7mel/realm_example/view/fragments/realm_list/RealmListFragment.kt | 1 | 1524 | package com.andrey7mel.realm_example.view.fragments.realm_list
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.andrey7mel.realm_example.App
import com.andrey7mel.realm_example.R
import com.andrey7mel.realm_example.presenter.RealmResultsPresenter
import kotlinx.android.synthetic.main.list_fragment.*
import javax.inject.Inject
class RealmListFragment : Fragment() {
@Inject
lateinit var presenter: RealmResultsPresenter
private var adapter: RealmListAdapter? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.list_fragment, container, false)
(activity.application as App).component.inject(this)
return view
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fab.setOnClickListener { presenter.addObject() }
presenter.onCreate()
adapter = RealmListAdapter(presenter.getObjects(), presenter)
recycler_view.layoutManager = LinearLayoutManager(context)
recycler_view.adapter = adapter
type.text = "Type: RealmListFragment"
empty.visibility = View.GONE
}
override fun onDestroyView() {
super.onDestroyView()
presenter.onDestroy()
}
}
| apache-2.0 | 6653f5bc7a65d976b3f428275ceaace4 | 32.130435 | 116 | 0.743438 | 4.508876 | false | false | false | false |
tronalddump-io/tronald-app | src/main/kotlin/io/tronalddump/app/search/SearchController.kt | 1 | 4467 | package io.tronalddump.app.search
import io.swagger.v3.oas.annotations.Operation
import io.tronalddump.app.Url
import io.tronalddump.app.exception.EntityNotFoundException
import io.tronalddump.app.quote.QuoteEntity
import io.tronalddump.app.quote.QuoteRepository
import io.tronalddump.app.tag.TagRepository
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Pageable
import org.springframework.hateoas.MediaTypes
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.*
import org.springframework.web.server.ResponseStatusException
import org.springframework.web.servlet.ModelAndView
@RequestMapping(value = [Url.SEARCH])
@RestController
class SearchController(
private val assembler: PageModelAssembler,
private val quoteRepository: QuoteRepository,
private val tagRepository: TagRepository
) {
@Operation(summary = "Search quotes by query or tags", tags = ["quote"])
@ResponseBody
@RequestMapping(
headers = [
"${HttpHeaders.ACCEPT}=${MediaType.APPLICATION_JSON_VALUE}",
"${HttpHeaders.ACCEPT}=${MediaType.TEXT_HTML_VALUE}",
"${HttpHeaders.ACCEPT}=${MediaTypes.HAL_JSON_VALUE}"
],
method = [RequestMethod.GET],
produces = [
MediaType.APPLICATION_JSON_VALUE,
MediaType.TEXT_HTML_VALUE
],
value = ["/quote"]
)
fun quote(
@RequestHeader(HttpHeaders.ACCEPT) acceptHeader: String,
@RequestParam("query", required = false, defaultValue = "") query: String,
@RequestParam("tag", required = false, defaultValue = "") tag: String,
@RequestParam(value = "page", defaultValue = "0") pageNumber: Int
): Any {
val page: Pageable = PageRequest.of(pageNumber, 10)
if (query.isNotEmpty()) {
val result: Page<QuoteEntity> = quoteRepository.findByValueIgnoreCaseContaining(query, page)
val model: PageModel = assembler.toModel(result)
val linkBuilder: WebMvcLinkBuilder = linkTo(this::class.java)
model.add(linkBuilder.slash("quote/?query=${query}&page=${pageNumber}").withSelfRel())
model.add(linkBuilder.slash("quote/?query=${query}&page=${page.first().pageNumber}").withRel("first"))
model.add(linkBuilder.slash("quote/?query=${query}&page=${page.previousOrFirst().pageNumber}").withRel("prev"))
model.add(linkBuilder.slash("quote/?query=${query}&page=${page.next().pageNumber}").withRel("next"))
model.add(linkBuilder.slash("quote/?query=${query}&page=${result.totalPages}").withRel("last"))
if (acceptHeader.contains(MediaType.TEXT_HTML_VALUE)) {
return ModelAndView("search")
.addObject("model", model)
.addObject("query", query)
.addObject("result", result)
}
return model
}
if (tag.isNotEmpty()) {
val entity = tagRepository.findByValue(tag).orElseThrow {
EntityNotFoundException("Tag with value \"$tag\" not found.")
}
val result: Page<QuoteEntity> = quoteRepository.findByTagsEquals(entity, page)
val model: PageModel = assembler.toModel(result)
val linkBuilder: WebMvcLinkBuilder = linkTo(this::class.java)
model.add(linkBuilder.slash("quote/?tag=${tag}&page=${pageNumber}").withSelfRel())
model.add(linkBuilder.slash("quote/?tag=${tag}&page=${page.first().pageNumber}").withRel("first"))
model.add(linkBuilder.slash("quote/?tag=${tag}&page=${page.previousOrFirst().pageNumber}").withRel("prev"))
model.add(linkBuilder.slash("quote/?tag=${tag}&page=${page.next().pageNumber}").withRel("next"))
model.add(linkBuilder.slash("quote/?tag=${tag}&page=${result.totalPages}").withRel("last"))
return model
}
throw ResponseStatusException(
HttpStatus.BAD_REQUEST,
"Either a query or tag parameter must be provided"
)
}
}
| gpl-3.0 | 5056bd1eae94d58b6b203e4b6042e13f | 45.051546 | 123 | 0.653906 | 4.702105 | false | false | false | false |
kotlintest/kotlintest | kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/maps.kt | 1 | 2129 | package io.kotest.property.arbitrary
import io.kotest.property.Shrinker
/**
* Returns an [Arb] where each generated value is a map, with the entries of the map
* drawn from the given pair generating arb. The size of each
* generated map is a random value between the specified min and max bounds.
*
* There are no edgecases.
*
* This arbitrary uses a [Shrinker] which will reduce the size of a failing map by
* removing elements from the failed case until it is empty.
*
* @see MapShrinker
*/
fun <K, V> Arb.Companion.map(
arb: Arb<Pair<K, V>>,
minSize: Int = 1,
maxSize: Int = 100
): Arb<Map<K, V>> = arb(MapShrinker()) { random ->
val size = random.random.nextInt(minSize, maxSize)
val pairs = List(size) { arb.single(random) }
pairs.toMap()
}
/**
* Returns an [Arb] where each generated value is a map, with the entries of the map
* drawn by combining values from the key gen and value gen. The size of each
* generated map is a random value between the specified min and max bounds.
*
* There are no edgecases.
*
* This arbitrary uses a [Shrinker] which will reduce the size of a failing map by
* removing elements until they map is empty.
*
* @see MapShrinker
*
*/
fun <K, V> Arb.Companion.map(
keyArb: Arb<K>,
valueArb: Arb<V>,
minSize: Int = 1,
maxSize: Int = 100
): Arb<Map<K, V>> {
require(minSize >= 0) { "minSize must be positive" }
require(maxSize >= 0) { "maxSize must be positive" }
return arb(MapShrinker()) { random ->
val size = random.random.nextInt(minSize, maxSize)
val pairs = List(size) {
keyArb.single(random) to valueArb.single(random)
}
pairs.toMap()
}
}
class MapShrinker<K, V> : Shrinker<Map<K, V>> {
override fun shrink(value: Map<K, V>): List<Map<K, V>> {
return when (value.size) {
0 -> emptyList()
1 -> listOf(emptyMap())
else -> listOf(
value.toList().take(value.size / 2).toMap(),
value.toList().drop(1).toMap()
)
}
}
}
fun <K, V> Arb.Companion.pair(k: Arb<K>, v: Arb<V>) = arb {
k.single(it) to v.single(it)
}
| apache-2.0 | 01d13f882b37b909d2dc8ab07daad196 | 28.164384 | 84 | 0.637388 | 3.439418 | false | false | false | false |
ansman/kotshi | compiler/src/main/kotlin/se/ansman/kotshi/kapt/KotshiProcessor.kt | 1 | 5907 | package se.ansman.kotshi.kapt
import com.google.auto.service.AutoService
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableSetMultimap
import com.google.common.collect.Multimaps
import com.google.common.collect.SetMultimap
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.metadata.classinspectors.ElementsClassInspector
import net.ltgt.gradle.incap.IncrementalAnnotationProcessor
import net.ltgt.gradle.incap.IncrementalAnnotationProcessorType.AGGREGATING
import se.ansman.kotshi.Errors
import se.ansman.kotshi.Options
import se.ansman.kotshi.model.GeneratedAdapter
import se.ansman.kotshi.model.GeneratedAnnotation
import javax.annotation.processing.*
import javax.lang.model.SourceVersion
import javax.lang.model.element.Element
import javax.lang.model.element.TypeElement
import javax.lang.model.util.Elements
import javax.lang.model.util.Types
@AutoService(Processor::class)
@IncrementalAnnotationProcessor(AGGREGATING)
class KotshiProcessor : AbstractProcessor() {
private var createAnnotationsUsingConstructor: Boolean? = null
private var useLegacyDataClassRenderer: Boolean = false
private var generatedAnnotation: GeneratedAnnotation? = null
private lateinit var elements: Elements
private lateinit var types: Types
private lateinit var metadataAccessor: MetadataAccessor
private lateinit var steps: ImmutableList<out ProcessingStep>
override fun getSupportedSourceVersion(): SourceVersion = SourceVersion.latestSupported()
private fun initSteps(): Iterable<ProcessingStep> {
val adapters: MutableList<GeneratedAdapter> = mutableListOf()
return listOf(
AdaptersProcessingStep(
processor = this,
metadataAccessor = metadataAccessor,
messager = processingEnv.messager,
filer = processingEnv.filer,
adapters = adapters,
types = types,
elements = processingEnv.elementUtils,
generatedAnnotation = generatedAnnotation,
createAnnotationsUsingConstructor = createAnnotationsUsingConstructor,
useLegacyDataClassRenderer = useLegacyDataClassRenderer,
),
FactoryProcessingStep(
processor = this,
messager = processingEnv.messager,
filer = processingEnv.filer,
types = processingEnv.typeUtils,
elements = processingEnv.elementUtils,
generatedAnnotation = generatedAnnotation,
generatedAdapters = adapters,
metadataAccessor = metadataAccessor,
createAnnotationsUsingConstructor = createAnnotationsUsingConstructor,
)
)
}
@Synchronized
override fun init(processingEnv: ProcessingEnvironment) {
super.init(processingEnv)
createAnnotationsUsingConstructor = processingEnv.options[Options.createAnnotationsUsingConstructor]?.toBooleanStrict()
useLegacyDataClassRenderer = processingEnv.options[Options.useLegacyDataClassRenderer]?.toBooleanStrict() ?: useLegacyDataClassRenderer
generatedAnnotation = processingEnv.options[Options.generatedAnnotation]
?.let { name ->
Options.possibleGeneratedAnnotations[name] ?: run {
processingEnv.messager.logKotshiError(Errors.invalidGeneratedAnnotation(name), element = null)
null
}
}
?.let { GeneratedAnnotation(it, KotshiProcessor::class.asClassName()) }
elements = processingEnv.elementUtils
types = processingEnv.typeUtils
metadataAccessor = MetadataAccessor(ElementsClassInspector.create(elements, processingEnv.typeUtils))
steps = ImmutableList.copyOf(initSteps())
}
private fun getSupportedAnnotationClasses(): Set<Class<out Annotation>> =
steps.flatMapTo(mutableSetOf()) { it.annotations }
/**
* Returns the set of supported annotation types as a collected from registered
* [processing steps][ProcessingStep].
*/
override fun getSupportedAnnotationTypes(): Set<String> =
getSupportedAnnotationClasses().mapTo(mutableSetOf()) { it.canonicalName }
override fun getSupportedOptions(): Set<String> = setOf("kotshi.createAnnotationsUsingConstructor")
override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean {
if (!roundEnv.processingOver()) {
process(validElements(roundEnv), roundEnv)
}
return false
}
private fun validElements(roundEnv: RoundEnvironment): ImmutableSetMultimap<Class<out Annotation>, Element> {
val validElements = ImmutableSetMultimap.builder<Class<out Annotation>, Element>()
for (annotationClass in getSupportedAnnotationClasses()) {
validElements.putAll(annotationClass, roundEnv.getElementsAnnotatedWith(annotationClass))
}
return validElements.build()
}
/** Processes the valid elements, including those previously deferred by each step. */
private fun process(validElements: ImmutableSetMultimap<Class<out Annotation>, Element>, roundEnv: RoundEnvironment) {
for (step in steps) {
val stepElements = Multimaps.filterKeys(validElements) { it in step.annotations }
if (!stepElements.isEmpty) {
step.process(stepElements, roundEnv)
}
}
}
interface ProcessingStep {
val annotations: Set<Class<out Annotation>>
fun process(elementsByAnnotation: SetMultimap<Class<out Annotation>, Element>, roundEnv: RoundEnvironment)
}
abstract class GeneratingProcessingStep : ProcessingStep {
protected abstract val filer: Filer
protected abstract val processor: KotshiProcessor
}
} | apache-2.0 | 2f50b931a6d510c4b94472e27c4f9a69 | 44.099237 | 143 | 0.711359 | 5.901099 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/api/internal/registries/fuel/FluidFuelManager.kt | 2 | 1495 | package com.cout970.magneticraft.api.internal.registries.fuel
import com.cout970.magneticraft.api.registries.fuel.IFluidFuel
import com.cout970.magneticraft.api.registries.fuel.IFluidFuelManager
import net.minecraftforge.fluids.FluidStack
import java.util.*
object FluidFuelManager : IFluidFuelManager {
/**
* This field determines if the mod should use it's own FluidFuelManager or use a wrapper around
* another fluid fuel provider like BuildcraftFuelRegistry.fuel
*
* This field is changed in preInit if buildcraft api is found, so all registrations must be done at init
*/
@JvmField
internal var FLUID_FUEL_MANAGER: IFluidFuelManager = FluidFuelManager
private val fuels = mutableListOf<IFluidFuel>()
override fun findFuel(fluidStack: FluidStack): IFluidFuel? = fuels.firstOrNull { it.matches(fluidStack) }
override fun getFuels(): MutableList<IFluidFuel> = Collections.unmodifiableList(fuels)
override fun registerFuel(recipe: IFluidFuel): Boolean {
if (findFuel(recipe.fluid) != null) return false
if (recipe.totalBurningTime <= 0.0) return false
if (recipe.powerPerCycle <= 0.0) return false
fuels += recipe
return true
}
override fun removeFuel(recipe: IFluidFuel): Boolean = fuels.remove(recipe)
override fun createFuel(fluidStack: FluidStack, burningTime: Int, powerPerCycle: Double): IFluidFuel {
return FluidFuel(fluidStack, burningTime, powerPerCycle)
}
} | gpl-2.0 | 3e9a48a7117ca2ced4b29f92b9b589c6 | 37.358974 | 109 | 0.740468 | 4.671875 | false | false | false | false |
Ph1b/MaterialAudiobookPlayer | data/src/main/kotlin/de/ph1b/audiobook/data/repo/ChapterRepo.kt | 1 | 1363 | package de.ph1b.audiobook.data.repo
import de.ph1b.audiobook.data.Chapter2
import de.ph1b.audiobook.data.repo.internals.dao.Chapter2Dao
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import timber.log.Timber
import java.time.Instant
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ChapterRepo
@Inject constructor(
private val dao: Chapter2Dao
) {
private val cache = mutableMapOf<Chapter2.Id, Chapter2?>()
private val _chapterChanged = MutableSharedFlow<Chapter2.Id>()
val chapterChanged: Flow<Chapter2.Id> get() = _chapterChanged
suspend fun get(id: Chapter2.Id, lastModified: Instant? = null): Chapter2? {
if (!cache.containsKey(id)) {
cache[id] = dao.chapter(id).also {
Timber.d("Chapter for $id wasn't in the map, fetched $it")
}
}
return cache[id]?.takeIf {
lastModified == null || it.fileLastModified == lastModified
}
}
suspend fun put(chapter: Chapter2) {
dao.insert(chapter)
val oldChapter = cache[chapter.id]
cache[chapter.id] = chapter
if (oldChapter != chapter) {
_chapterChanged.emit(chapter.id)
}
}
suspend inline fun getOrPut(id: Chapter2.Id, lastModified: Instant, defaultValue: () -> Chapter2?): Chapter2? {
return get(id, lastModified)
?: defaultValue()?.also { put(it) }
}
}
| lgpl-3.0 | 5b4e2fa4428f20ef8c4ce9fa063ab08c | 28 | 113 | 0.705062 | 3.663978 | false | false | false | false |
wireapp/wire-android | app/src/main/java/com/waz/zclient/markdown/utils/Extensions.kt | 1 | 3004 | /**
* Wire
* Copyright (C) 2018 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.waz.zclient.markdown.utils
import org.commonmark.internal.renderer.text.ListHolder
import org.commonmark.internal.renderer.text.OrderedListHolder
import org.commonmark.node.*
/**
* Helper extention properties and methods.
*/
/**
* The paragraph node is the root or the direct child of a Document node.
*/
val Paragraph.isOuterMost: Boolean get() = parent is Document?
/**
* The block quote's direct parent is also a BlockQuote node.
*/
val BlockQuote.isNested: Boolean get() = parent is BlockQuote
/**
* The block quote node is the root or the direct child of a Document node.
*/
val BlockQuote.isOuterMost: Boolean get() = parent is Document?
/**
* The number of parents of this list holder.
*/
val ListHolder.depth: Int get() {
var depth = 0
var next = parent
while (next != null) { depth++; next = next.parent }
return depth
}
/**
* True if the list holder has no parents.
*/
val ListHolder.isRoot: Boolean get() = depth == 0
/**
* The number of direct children of this node.
*/
val Node.numberOfChildren: Int get() {
var count = 0
var child: Node? = firstChild
while (child != null) { count++; child = child.next }
return count
}
/**
* Returns true if the list item contains a line break. If `includeSoft` is true,
* soft line breaks will be considered.
*/
fun ListItem.hasLineBreak(includeSoft: Boolean = false): Boolean {
// the sole child of a list item is a paragraph
var node = firstChild
if (node !is Paragraph) return false
// iterate through children of paragraph
node = node.firstChild
while (node != null) {
// return true on first occurence of line break
if (node is HardLineBreak || (includeSoft && node is SoftLineBreak)) return true
node = node.next
}
return false
}
/**
* The number of items in this list. Note, this assumes that each item is a direct child
* of this node.
*/
val OrderedList.numberOfItems: Int get() = numberOfChildren
/**
* The prefix number of the last item in the list.
*/
val OrderedList.largestPrefix: Int get() = startNumber + numberOfItems - 1
/**
* The number of digits in this number.
*/
val Int.numberOfDigits: Int get() {
var e = 1
while (this.toDouble() >= Math.pow(10.0, e.toDouble())) e++
return e
}
| gpl-3.0 | 38808f62856441865e797cb015c7a486 | 27.339623 | 88 | 0.693409 | 3.93709 | false | false | false | false |
gravidence/gravifon | gravifon/src/main/kotlin/org/gravidence/gravifon/playback/backend/gstreamer/TrackQueue.kt | 1 | 955 | package org.gravidence.gravifon.playback.backend.gstreamer
import org.gravidence.gravifon.domain.track.VirtualTrack
class TrackQueue(
private var activeTrack: VirtualTrack? = null, // queue is inactive initially
private val nextTracks: ArrayDeque<VirtualTrack> = ArrayDeque()
) {
private fun makeNextActive(): VirtualTrack? {
activeTrack = nextTracks.removeFirstOrNull()
return activeTrack
}
fun peekActive(): VirtualTrack? {
return activeTrack
}
fun pollActive(): Pair<VirtualTrack?, VirtualTrack?> {
return Pair(
peekActive(),
makeNextActive()
)
}
fun pushNext(track: VirtualTrack) {
nextTracks += track
}
fun peekNext(): VirtualTrack? {
return nextTracks.firstOrNull()
}
fun pollNext(): VirtualTrack? {
val nextTrack = nextTracks.firstOrNull()
nextTracks.clear()
return nextTrack
}
} | mit | 63ed870321117fe7d8fce67501737c7c | 22.9 | 81 | 0.646073 | 4.948187 | false | false | false | false |
siosio/DomaSupport | src/main/java/siosio/doma/inspection/dao/BatchInsertMethodRule.kt | 1 | 4621 | package siosio.doma.inspection.dao
import com.intellij.codeInsight.daemon.impl.quickfix.*
import com.intellij.openapi.project.*
import com.intellij.psi.*
import com.intellij.psi.impl.source.*
import com.intellij.psi.search.*
import siosio.doma.extension.*
import siosio.doma.psi.*
val batchInsertMethodRule =
rule {
sql(false)
// check parameter count
parameterRule {
message = "inspection.dao.batch-insert.param-size-error"
rule = {
when (size) {
1 -> true
else -> false
}
}
}
// check parameter type(sqlなし)
parameterRule {
message = "inspection.dao.batch-insert.param-error"
rule = { daoMethod ->
if (size == 1 && daoMethod.useSqlFile().not()) {
firstOrNull()?.let {
val type = it.type as PsiClassReferenceType
isIterableType(daoMethod.project, type) && type.reference.typeParameters.first().isEntity()
} ?: true
} else {
true
}
}
}
// check parameter type(sqlあり)
parameterRule {
message = "inspection.dao.batch-insert.use-sql.param-error"
rule = { daoMethod ->
if (size == 1 && daoMethod.useSqlFile()) {
firstOrNull()?.type?.let {
isIterableType(daoMethod.project, it)
} ?: true
} else {
true
}
}
}
// return type(not immutable entity)
returnRule {
message = "inspection.dao.batch-insert.mutable-insert-return-type"
rule = block@{ daoMethod ->
quickFix = { MethodReturnTypeFix(daoMethod.psiMethod, PsiType.INT.createArrayType(), false) }
if (daoMethod.parameters.size == 1) {
// 最初のパラメータの型パラメータを取得してチェックする
val typeParameter = getFirstParametersTypeParameter(daoMethod) ?: return@block true
if (typeParameter.isImmutableEntity().not()) {
type.isAssignableFrom(PsiType.INT.createArrayType())
} else {
true
}
} else {
true
}
}
}
// return type( immutable entity)
returnRule {
message = "inspection.dao.batch-insert.immutable-insert-return-type"
rule = block@{ daoMethod ->
if (daoMethod.parameters.size == 1) {
// 最初のパラメータの型パラメータを取得してチェックする
val typeParameter = getFirstParametersTypeParameter(daoMethod) ?: return@block true
quickFix = {
MethodReturnTypeFix(
daoMethod.psiMethod,
PsiType.getTypeByName(
"org.seasar.doma.jdbc.BatchResult<${typeParameter.canonicalText}>", project, resolveScope), false)
}
if (typeParameter.isImmutableEntity()) {
messageArgs = arrayOf(typeParameter.canonicalText)
type.isAssignableFrom(PsiType.getTypeByName("org.seasar.doma.jdbc.BatchResult", daoMethod.project, resolveScope))
} else {
true
}
} else {
true
}
}
}
}
private fun getFirstParametersTypeParameter(daoMethod: PsiDaoMethod): PsiType? {
val parameterType = daoMethod.parameterList.parameters.first().type as PsiClassReferenceType
return parameterType.reference.typeParameters.firstOrNull()
}
private fun isIterableType(project: Project, psiType: PsiType): Boolean {
val iterableType = PsiType.getTypeByName("java.lang.Iterable", project, GlobalSearchScope.allScope(project))
return psiType.superTypes.any { iterableType.isAssignableFrom(it) }
}
| mit | 34fda16a24cf9bb05d09459d98f3ea41 | 39.621622 | 142 | 0.483256 | 5.803089 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/bugreport/LawnchairBugReporter.kt | 1 | 5199 | package app.lawnchair.bugreport
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import android.util.Log
import androidx.core.content.getSystemService
import app.lawnchair.LawnchairApp
import com.android.launcher3.BuildConfig
import com.android.launcher3.R
import com.android.launcher3.util.MainThreadInitializedObject
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
class LawnchairBugReporter(private val context: Context) {
private val notificationManager = context.getSystemService<NotificationManager>()!!
private val logsFolder by lazy { File(context.cacheDir, "logs").apply { mkdirs() } }
private val appName by lazy { context.getString(R.string.derived_app_name) }
init {
notificationManager.createNotificationChannel(
NotificationChannel(
BugReportReceiver.notificationChannelId,
context.getString(R.string.bugreport_channel_name),
NotificationManager.IMPORTANCE_HIGH
)
)
notificationManager.createNotificationChannel(
NotificationChannel(
BugReportReceiver.statusChannelId,
context.getString(R.string.status_channel_name),
NotificationManager.IMPORTANCE_NONE
)
)
val defaultHandler = Thread.getDefaultUncaughtExceptionHandler()
Thread.setDefaultUncaughtExceptionHandler { thread, throwable ->
sendNotification(throwable)
defaultHandler?.uncaughtException(thread, throwable)
}
removeDismissedLogs()
}
private fun removeDismissedLogs() {
val activeIds = notificationManager.activeNotifications
.mapTo(mutableSetOf()) { String.format("%x", it.id) }
(logsFolder.listFiles() as Array<File>)
.filter { it.name !in activeIds }
.forEach { it.deleteRecursively() }
}
private fun sendNotification(throwable: Throwable) {
val bugReport = Report(BugReport.TYPE_UNCAUGHT_EXCEPTION, throwable)
.generateBugReport() ?: return
val notifications = notificationManager.activeNotifications
val hasNotification = notifications.any { it.id == bugReport.notificationId }
if (hasNotification || notifications.size > 3) {
return
}
BugReportReceiver.notify(context, bugReport)
}
inner class Report(val error: String, val throwable: Throwable? = null) {
private val fileName = "$appName bug report ${SimpleDateFormat.getDateTimeInstance().format(Date())}"
fun generateBugReport(): BugReport? {
val contents = writeContents()
val contentsWithHeader = "$fileName\n$contents"
val id = contents.hashCode()
val reportFile = save(contentsWithHeader, id)
return BugReport(id, error, getDescription(throwable ?: return null), contentsWithHeader, reportFile)
}
private fun getDescription(throwable: Throwable): String {
return "${throwable::class.java.name}: ${throwable.message}"
}
private fun save(contents: String, id: Int): File? {
val dest = File(logsFolder, String.format("%x", id))
dest.mkdirs()
val file = File(dest, "$fileName.txt")
if (!file.createNewFile()) return null
file.writeText(contents)
return file
}
private fun writeContents() = StringBuilder()
.appendLine("version: ${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})")
.appendLine("commit: ${BuildConfig.COMMIT_HASH}")
.appendLine("build.brand: ${Build.BRAND}")
.appendLine("build.device: ${Build.DEVICE}")
.appendLine("build.display: ${Build.DISPLAY}")
.appendLine("build.fingerprint: ${Build.FINGERPRINT}")
.appendLine("build.hardware: ${Build.HARDWARE}")
.appendLine("build.id: ${Build.ID}")
.appendLine("build.manufacturer: ${Build.MANUFACTURER}")
.appendLine("build.model: ${Build.MODEL}")
.appendLine("build.product: ${Build.PRODUCT}")
.appendLine("build.type: ${Build.TYPE}")
.appendLine("version.codename: ${Build.VERSION.CODENAME}")
.appendLine("version.incremental: ${Build.VERSION.INCREMENTAL}")
.appendLine("version.release: ${Build.VERSION.RELEASE}")
.appendLine("version.sdk_int: ${Build.VERSION.SDK_INT}")
.appendLine("display.density_dpi: ${context.resources.displayMetrics.densityDpi}")
.appendLine("isRecentsEnabled: ${LawnchairApp.isRecentsEnabled}")
.appendLine()
.appendLine("error: $error")
.also {
if (throwable != null) {
it
.appendLine()
.appendLine(Log.getStackTraceString(throwable))
}
}
.toString()
}
companion object {
val INSTANCE = MainThreadInitializedObject(::LawnchairBugReporter)
}
}
| gpl-3.0 | 647bac6b8ac434e2bcc31d27eb77196b | 39.302326 | 113 | 0.633776 | 5.102061 | false | false | false | false |
xfournet/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/uast/GroovyUastPlugin.kt | 1 | 5775 | // Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.uast
import com.intellij.lang.Language
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.util.parents
import org.jetbrains.plugins.groovy.GroovyLanguage
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes
import org.jetbrains.plugins.groovy.lang.psi.GrQualifiedReference
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.uast.*
/**
* This is a very limited implementation of UastPlugin for Groovy,
* provided only to make Groovy play with UAST-based reference contributors and spring class annotators
*/
class GroovyUastPlugin : UastLanguagePlugin {
override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? =
convertElementWithParent(element, { parent }, requiredType)
override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? =
convertElementWithParent(element, { makeUParent(element) }, requiredType)
private fun convertElementWithParent(element: PsiElement,
parentProvider: () -> UElement?,
requiredType: Class<out UElement>?): UElement? =
when (element) {
is GroovyFile -> GrUFile(element, this)
is GrLiteral -> GrULiteral(element, parentProvider)
is GrAnnotationNameValuePair -> GrUNamedExpression(element, parentProvider)
is GrAnnotation -> GrUAnnotation(element, parentProvider)
is GrTypeDefinition -> GrUClass(element, parentProvider)
is GrMethod -> GrUMethod(element, parentProvider)
is GrParameter -> GrUParameter(element, parentProvider)
is GrQualifiedReference<*> -> GrUReferenceExpression(element, parentProvider)
is LeafPsiElement -> if (element.elementType == GroovyTokenTypes.mIDENT) LazyParentUIdentifier(element, null) else null
else -> null
}?.takeIf { requiredType?.isAssignableFrom(it.javaClass) ?: true }
private fun makeUParent(element: PsiElement) =
element.parent.parents().mapNotNull { convertElementWithParent(it, null) }.firstOrNull()
override fun getMethodCallExpression(element: PsiElement,
containingClassFqName: String?,
methodName: String): UastLanguagePlugin.ResolvedMethod? = null //not implemented
override fun getConstructorCallExpression(element: PsiElement,
fqName: String): UastLanguagePlugin.ResolvedConstructor? = null //not implemented
override fun isExpressionValueUsed(element: UExpression): Boolean = TODO("not implemented")
override val priority = 0
override fun isFileSupported(fileName: String) = fileName.endsWith(".groovy", ignoreCase = true)
override val language: Language = GroovyLanguage
}
class GrULiteral(val grElement: GrLiteral, val parentProvider: () -> UElement?) : ULiteralExpression, JvmDeclarationUElement {
override val value: Any?
get() = grElement.value
override val uastParent by lazy(parentProvider)
override val psi: PsiElement? = grElement
override val annotations: List<UAnnotation> = emptyList() //not implemented
}
class GrUNamedExpression(val grElement: GrAnnotationNameValuePair, val parentProvider: () -> UElement?) : UNamedExpression, JvmDeclarationUElement {
override val name: String?
get() = grElement.name
override val expression: UExpression
get() = grElement.value.toUElementOfType() ?: GrUnknownUExpression(grElement.value, this)
override val uastParent by lazy(parentProvider)
override val psi = grElement
override val annotations: List<UAnnotation> = emptyList() //not implemented
}
class GrUAnnotation(val grElement: GrAnnotation,
val parentProvider: () -> UElement?) : UAnnotationEx, JvmDeclarationUElement, UAnchorOwner {
override val javaPsi: PsiAnnotation = grElement
override val qualifiedName: String?
get() = grElement.qualifiedName
override fun resolve(): PsiClass? = grElement.nameReferenceElement?.resolve() as PsiClass?
override val uastAnchor: UIdentifier?
get() = grElement.classReference.referenceNameElement?.let { UIdentifier(it, this) }
override val attributeValues: List<UNamedExpression> by lazy {
grElement.parameterList.attributes.map {
GrUNamedExpression(it, { this })
}
}
override fun findAttributeValue(name: String?): UExpression? = null //not implemented
override fun findDeclaredAttributeValue(name: String?): UExpression? = null //not implemented
override val uastParent by lazy(parentProvider)
override val psi: PsiElement? = grElement
}
class GrUnknownUExpression(override val psi: PsiElement?, override val uastParent: UElement?) : UExpression, JvmDeclarationUElement {
override fun asLogString(): String = "GrUnknownUExpression(grElement)"
override val annotations: List<UAnnotation> = emptyList() //not implemented
} | apache-2.0 | a5b22a628674ebd5dafba634e43d941c | 45.208 | 148 | 0.754459 | 5.039267 | false | false | false | false |
Kotlin/dokka | plugins/versioning/src/main/kotlin/org/jetbrains/dokka/versioning/VersioningStorage.kt | 1 | 2650 | package org.jetbrains.dokka.versioning
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.plugability.configuration
import java.io.File
data class VersionDirs(val src: File, val dst: File)
data class CurrentVersion(val name: String, val dir: File)
interface VersioningStorage {
val previousVersions: Map<VersionId, VersionDirs>
val currentVersion: CurrentVersion
fun createVersionFile()
}
typealias VersionId = String
class DefaultVersioningStorage(val context: DokkaContext) : VersioningStorage {
private val mapper = ObjectMapper()
private val configuration = configuration<VersioningPlugin, VersioningConfiguration>(context)
override val previousVersions: Map<VersionId, VersionDirs> by lazy {
configuration?.let { versionsConfiguration ->
getPreviousVersions(versionsConfiguration.allOlderVersions(), context.configuration.outputDir)
} ?: emptyMap()
}
override val currentVersion: CurrentVersion by lazy {
configuration?.let { versionsConfiguration ->
CurrentVersion(versionsConfiguration.versionFromConfigurationOrModule(context),
context.configuration.outputDir)
}?: CurrentVersion(context.configuration.moduleVersion.orEmpty(), context.configuration.outputDir)
}
override fun createVersionFile() {
mapper.writeValue(
currentVersion.dir.resolve(VersioningConfiguration.VERSIONS_FILE),
Version(currentVersion.name)
)
}
private fun getPreviousVersions(olderVersions: List<File>, output: File): Map<String, VersionDirs> =
versionsFrom(olderVersions).associate { (key, srcDir) ->
key to VersionDirs(srcDir, output.resolve(VersioningConfiguration.OLDER_VERSIONS_DIR).resolve(key))
}
private fun versionsFrom(olderVersions: List<File>) =
olderVersions.mapNotNull { versionDir ->
versionDir.listFiles { _, name -> name == VersioningConfiguration.VERSIONS_FILE }?.firstOrNull()
?.let { file ->
val versionsContent = mapper.readValue<Version>(file)
Pair(versionsContent.version, versionDir)
}.also {
if (it == null) context.logger.warn("Failed to find versions file named ${VersioningConfiguration.VERSIONS_FILE} in $versionDir")
}
}
private data class Version(
@JsonProperty("version") val version: String,
)
}
| apache-2.0 | 4fda2152ca090ef92e2e9c836a119380 | 39.769231 | 149 | 0.707925 | 5.145631 | false | true | false | false |
rpradal/OCTOMeuh | app/src/main/kotlin/com/octo/mob/octomeuh/countdown/manager/PreferencesPersistor.kt | 1 | 2380 | package com.octo.mob.octomeuh.countdown.manager
import android.content.SharedPreferences
import com.octo.mob.octomeuh.countdown.model.RepetitionMode
import java.util.*
interface PreferencesPersistor {
fun saveInitialDuration(initialDurationSeconds: Int)
fun getInitialDuration(): Int
fun getRepetitionMode(): RepetitionMode
fun saveRepetitionMode(repetitionMode: RepetitionMode)
}
class PreferencesPersistorImpl(val sharedPreferences: SharedPreferences) : PreferencesPersistor {
// ---------------------------------
// CONSTANTS
// ---------------------------------
companion object {
internal val INITIAL_DURATION_KEY = "INITIAL_DURATION_KEY"
internal val REPETITION_MODE_KEY = "REPETITION_MODE_KEY"
internal val DEFAULT_COUNTDOWN_DURATION_SECONDS = 60
internal val DEFAULT_REPETITION_MODE = RepetitionMode.STEP_BY_STEP
}
// ---------------------------------
// INTERFACE IMPLEM
// ---------------------------------
override fun getInitialDuration(): Int {
try {
return sharedPreferences.getInt(INITIAL_DURATION_KEY, DEFAULT_COUNTDOWN_DURATION_SECONDS)
} catch (exception: ClassCastException) {
return DEFAULT_COUNTDOWN_DURATION_SECONDS
}
}
override fun saveInitialDuration(initialDurationSeconds: Int) {
sharedPreferences.edit()
.putInt(INITIAL_DURATION_KEY, initialDurationSeconds)
.apply()
}
override fun getRepetitionMode(): RepetitionMode {
return extractEnumValue(RepetitionMode.values(), REPETITION_MODE_KEY, DEFAULT_REPETITION_MODE)
}
override fun saveRepetitionMode(repetitionMode: RepetitionMode) {
sharedPreferences.edit()
.putString(REPETITION_MODE_KEY, repetitionMode.name)
.apply()
}
// ---------------------------------
// PRIVATE METHOD
// ---------------------------------
private fun <T : kotlin.Enum<T>> extractEnumValue(valueLists: Array<T>, key: String, defaultValue: T): T {
val extractedValue: T
try {
extractedValue = valueLists.first { it.name == sharedPreferences.getString(key, defaultValue.name) }
} catch (exception: NoSuchElementException) {
extractedValue = defaultValue
}
return extractedValue
}
} | mit | 6969a00a7563ced68f6436cb84892ea2 | 31.175676 | 112 | 0.619748 | 5.3125 | false | false | false | false |
MrDoomy/Seeya | app/src/main/java/com/doomy/seeya/Utils.kt | 1 | 2398 | /**
* Copyright (C) 2017 Damien Chazoule
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package com.doomy.seeya
import android.app.Activity
import android.content.Context
import android.provider.Settings
import android.support.design.widget.Snackbar
import android.view.View
import android.widget.TextView
object Utils {
fun mapValueFromRangeToRange(value: Double, fromLow: Double, fromHigh: Double, toLow: Double, toHigh: Double): Double {
return toLow + (value - fromLow) / (fromHigh - fromLow) * (toHigh - toLow)
}
fun clamp(value: Double, low: Double, high: Double): Double {
return Math.min(Math.max(value, low), high)
}
fun hasAccessGranted(context: Context): Boolean {
val mContentResolver = context.contentResolver
val mEnabledNotificationListeners = Settings.Secure.getString(mContentResolver, "enabled_notification_listeners")
val mPackageName = context.packageName
// Check To See If The 'mEnabledNotificationListeners' String Contains Our Package Name
return !(mEnabledNotificationListeners == null || !mEnabledNotificationListeners.contains(mPackageName))
}
fun makeText(context: Context, message: String, duration: Int): Snackbar {
val mActivity = context as Activity
val mLayout: View
val mSnackBar = Snackbar.make(mActivity.findViewById(android.R.id.content), message, duration)
mLayout = mSnackBar.view
// Customize Colors
mLayout.setBackgroundColor(context.getResources().getColor(R.color.colorPrimaryDark))
val mTextView = mLayout.findViewById<TextView>(android.support.design.R.id.snackbar_text)
mTextView.setTextColor(context.getResources().getColor(R.color.colorLight))
return mSnackBar
}
}
| gpl-3.0 | a3c73030e1e27a9ee49b0da74c321455 | 40.344828 | 123 | 0.728941 | 4.344203 | false | false | false | false |
jtlalka/fiszki | app/src/main/kotlin/net/tlalka/fiszki/domain/controllers/TestController.kt | 1 | 4208 | package net.tlalka.fiszki.domain.controllers
import net.tlalka.fiszki.core.annotations.ActivityScope
import net.tlalka.fiszki.domain.services.CacheService
import net.tlalka.fiszki.domain.services.LessonService
import net.tlalka.fiszki.domain.services.StorageService
import net.tlalka.fiszki.domain.services.WordService
import net.tlalka.fiszki.domain.utils.ValidUtils
import net.tlalka.fiszki.model.dto.parcel.LessonDto
import net.tlalka.fiszki.model.entities.Lesson
import net.tlalka.fiszki.model.entities.Word
import net.tlalka.fiszki.model.types.LanguageType
import java.util.ArrayList
import java.util.Random
import javax.inject.Inject
@ActivityScope
class TestController
@Inject constructor(cacheService: CacheService, storageService: StorageService, lessonDto: LessonDto) {
@Inject
lateinit var lessonService: LessonService
@Inject
lateinit var wordService: WordService
private val lesson: Lesson = cacheService.getLesson(lessonDto.lessonId)
private val words: MutableList<Word> = cacheService.getWords(lesson).toMutableList()
private val language: LanguageType = storageService.language
private var translation: LanguageType = storageService.translation
private var answers: MutableList<String> = emptyList<String>().toMutableList()
private var correctAnswer: String = ""
private var activeWord: Word = Word()
private var correctScore: Int = 0
private var incorrectScore: Int = 0
var wordIndex: Int = 0
private set
init {
this.randomiseCollection(words)
}
fun getLanguages(): List<LanguageType> {
val languages = this.wordService.getLanguages(this.activeWord).toMutableList()
languages.remove(this.language)
languages.remove(this.translation)
return languages
}
fun getNextWord(): String {
this.activeWord = this.words[wordIndex++]
return this.activeWord.value
}
fun getTestSize(): Int {
return this.words.size
}
fun getThisAnswers(): List<String> {
val answer = this.getTranslateWord(this.activeWord)
return if (ValidUtils.isNotNull(answer)) {
this.correctAnswer = answer.value
this.answers = ArrayList()
this.answers.add(correctAnswer)
this.generateAnswers(answers, 3)
this.randomiseCollection(answers)
answers
} else {
emptyList()
}
}
private fun generateAnswers(answers: MutableList<String>, size: Int) {
if (size > 0 && this.generateAnswer(answers, 100)) {
this.generateAnswers(answers, size - 1)
}
}
private fun generateAnswer(answers: MutableList<String>, repetitions: Int): Boolean {
val word = words[Random().nextInt(words.size)]
val value = this.getTranslateWord(word).value
return if (repetitions - 1 > 0) {
if (answers.contains(value)) generateAnswer(answers, repetitions - 1) else answers.add(value)
} else {
answers.add("...")
}
}
private fun getTranslateWord(word: Word): Word {
return this.wordService.getTranslation(word, this.translation)
}
private fun randomiseCollection(list: MutableList<*>) {
list.shuffle()
}
fun setTranslation(translation: LanguageType) {
this.translation = translation
}
fun hasNextWord(): Boolean {
return this.wordIndex < this.words.size
}
fun validAnswer(index: Int): Boolean {
return if (this.answers.indexOf(this.correctAnswer) == index) {
this.correctScore++
true
} else {
this.incorrectScore++
false
}
}
fun updateLessonDto(lessonDto: LessonDto) {
lessonDto.setScoreValues(calculateScore(), correctScore, incorrectScore)
}
fun updateBestScore() {
val newScore = this.calculateScore()
if (newScore > this.lesson.score) {
this.lessonService.updateScore(lesson, newScore)
}
}
private fun calculateScore(): Int {
return Math.round(Math.max((correctScore - incorrectScore).toFloat(), 0.0f) * 100 / correctScore)
}
}
| mit | 76b0e872aa59918ed4e78d52e60dd918 | 30.402985 | 107 | 0.673241 | 4.443506 | false | false | false | false |
jtransc/jtransc | benchmark_kotlin_mpp/wip/jzlib/InflaterInputStream.kt | 1 | 6490 | /* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ /*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jtransc.compression.jzlib
import com.jtransc.annotation.JTranscInvisible
import java.io.EOFException
import java.io.FilterInputStream
import java.io.IOException
import java.lang.IndexOutOfBoundsException
import java.lang.NullPointerException
@JTranscInvisible
class InflaterInputStream(
`in`: java.io.InputStream?,
inflater: Inflater?,
size: Int, close_in: Boolean
) : FilterInputStream(`in`) {
protected val inflater: Inflater
protected var buf: ByteArray
private var closed = false
private var eof = false
private val close_in = true
@JvmOverloads
constructor(`in`: java.io.InputStream?, nowrap: Boolean = false) : this(`in`, Inflater(nowrap)) {
myinflater = true
}
constructor(`in`: java.io.InputStream?, inflater: Inflater?) : this(`in`, inflater, DEFAULT_BUFSIZE) {}
constructor(
`in`: java.io.InputStream?,
inflater: Inflater?, size: Int
) : this(`in`, inflater, size, true) {
}
protected var myinflater = false
private val byte1 = ByteArray(1)
@Throws(IOException::class)
override fun read(): Int {
if (closed) {
throw IOException("Stream closed")
}
return if (read(byte1, 0, 1) == -1) -1 else byte1[0] and 0xff
}
@Throws(IOException::class)
override fun read(b: ByteArray, off: Int, len: Int): Int {
var off = off
if (closed) {
throw IOException("Stream closed")
}
if (b == null) {
throw NullPointerException()
} else if (off < 0 || len < 0 || len > b.size - off) {
throw IndexOutOfBoundsException()
} else if (len == 0) {
return 0
} else if (eof) {
return -1
}
var n = 0
inflater.setOutput(b, off, len)
while (!eof) {
if (inflater.avail_in === 0) fill()
val err: Int = inflater.inflate(JZlib.Z_NO_FLUSH)
n += inflater.next_out_index - off
off = inflater.next_out_index
when (err) {
JZlib.Z_DATA_ERROR -> throw IOException(inflater.msg)
JZlib.Z_STREAM_END, JZlib.Z_NEED_DICT -> {
eof = true
if (err == JZlib.Z_NEED_DICT) return -1
}
else -> {
}
}
if (inflater.avail_out === 0) break
}
return n
}
@Throws(IOException::class)
override fun available(): Int {
if (closed) {
throw IOException("Stream closed")
}
return if (eof) {
0
} else {
1
}
}
private val b = ByteArray(512)
@Throws(IOException::class)
override fun skip(n: Long): Long {
if (n < 0) {
throw java.lang.IllegalArgumentException("negative skip length")
}
if (closed) {
throw IOException("Stream closed")
}
val max = java.lang.Math.min(n, Int.MAX_VALUE.toLong()) as Int
var total = 0
while (total < max) {
var len = max - total
if (len > b.size) {
len = b.size
}
len = read(b, 0, len)
if (len == -1) {
eof = true
break
}
total += len
}
return total.toLong()
}
@Throws(IOException::class)
override fun close() {
if (!closed) {
if (myinflater) inflater.end()
if (close_in) `in`.close()
closed = true
}
}
@Throws(IOException::class)
protected fun fill() {
if (closed) {
throw IOException("Stream closed")
}
var len: Int = `in`.read(buf, 0, buf.size)
if (len == -1) {
if (inflater.istate.wrap === 0 &&
!inflater.finished()
) {
buf[0] = 0
len = 1
} else if (inflater.istate.was !== -1) { // in reading trailer
throw IOException("footer is not found")
} else {
throw EOFException("Unexpected end of ZLIB input stream")
}
}
inflater.setInput(buf, 0, len, true)
}
override fun markSupported(): Boolean {
return false
}
@Synchronized
override fun mark(readlimit: Int) {
}
@Synchronized
@Throws(IOException::class)
override fun reset() {
throw IOException("mark/reset not supported")
}
val totalIn: Long
get() = inflater.getTotalIn()
val totalOut: Long
get() = inflater.getTotalOut()
val availIn: ByteArray?
get() {
if (inflater.avail_in <= 0) return null
val tmp = ByteArray(inflater.avail_in)
java.lang.System.arraycopy(
inflater.next_in, inflater.next_in_index,
tmp, 0, inflater.avail_in
)
return tmp
}
@Throws(IOException::class)
fun readHeader() {
val empty: ByteArray = "".toByteArray()
inflater.setInput(empty, 0, 0, false)
inflater.setOutput(empty, 0, 0)
var err: Int = inflater.inflate(JZlib.Z_NO_FLUSH)
if (!inflater.istate.inParsingHeader()) {
return
}
val b1 = ByteArray(1)
do {
val i: Int = `in`.read(b1)
if (i <= 0) throw IOException("no input")
inflater.setInput(b1)
err = inflater.inflate(JZlib.Z_NO_FLUSH)
if (err != 0 /*Z_OK*/) throw IOException(inflater.msg)
} while (inflater.istate.inParsingHeader())
}
fun getInflater(): Inflater {
return inflater
}
companion object {
protected const val DEFAULT_BUFSIZE = 512
}
init {
if (`in` == null || inflater == null) {
throw NullPointerException()
} else if (size <= 0) {
throw java.lang.IllegalArgumentException("buffer size must be greater than 0")
}
this.inflater = inflater
buf = ByteArray(size)
this.close_in = close_in
}
} | apache-2.0 | 9f4c2272f9ac35268d7d9efa82c97ac5 | 25.93361 | 104 | 0.679507 | 3.333333 | false | false | false | false |
msebire/intellij-community | platform/configuration-store-impl/testSrc/DefaultProjectStoreTest.kt | 1 | 5039 | // 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.configurationStore
import com.intellij.externalDependencies.DependencyOnPlugin
import com.intellij.externalDependencies.ExternalDependenciesManager
import com.intellij.externalDependencies.ProjectExternalDependency
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.components.*
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.JDOMUtil
import com.intellij.testFramework.*
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.testFramework.rules.InMemoryFsRule
import com.intellij.util.io.delete
import com.intellij.util.io.getDirectoryTree
import com.intellij.util.isEmpty
import com.intellij.util.loadElement
import kotlinx.coroutines.runBlocking
import org.jdom.Element
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.nio.file.Paths
private const val TEST_COMPONENT_NAME = "DefaultProjectStoreTestComponent"
@State(name = TEST_COMPONENT_NAME, storages = [(Storage(value = "testSchemes", stateSplitter = TestStateSplitter::class))])
private class TestComponent : PersistentStateComponent<Element> {
private var element = Element("state")
override fun getState() = element.clone()
override fun loadState(state: Element) {
element = state.clone()
}
}
internal class DefaultProjectStoreTest {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
}
@JvmField
@Rule
val fsRule = InMemoryFsRule()
private val tempDirManager = TemporaryDirectory()
private val requiredPlugins = listOf<ProjectExternalDependency>(DependencyOnPlugin("fake", "0", "1"))
@JvmField
@Rule
val ruleChain = RuleChain(
tempDirManager,
WrapRule {
val path = Paths.get(ApplicationManager.getApplication().stateStore.storageManager.expandMacros(APP_CONFIG))
return@WrapRule {
path.delete()
}
}
)
@Test
fun `new project from default - file-based storage`() = runBlocking {
val externalDependenciesManager = ProjectManager.getInstance().defaultProject.service<ExternalDependenciesManager>()
externalDependenciesManager.allDependencies = requiredPlugins
try {
createProjectAndUseInLoadComponentStateMode(tempDirManager) {
assertThat(it.service<ExternalDependenciesManager>().allDependencies).isEqualTo(requiredPlugins)
}
}
finally {
externalDependenciesManager.allDependencies = emptyList()
}
}
@Test
fun `new project from default - directory-based storage`() = runBlocking {
val defaultProject = ProjectManager.getInstance().defaultProject
val defaultTestComponent = TestComponent()
defaultTestComponent.loadState(JDOMUtil.load("""
<component>
<main name="$TEST_COMPONENT_NAME"/><sub name="foo" /><sub name="bar" />
</component>""".trimIndent()))
val stateStore = defaultProject.stateStore as ComponentStoreImpl
stateStore.initComponent(defaultTestComponent, true)
try {
// obviously, project must be directory-based also
createProjectAndUseInLoadComponentStateMode(tempDirManager, directoryBased = true) {
val component = TestComponent()
it.stateStore.initComponent(component, true)
assertThat(component.state).isEqualTo(defaultTestComponent.state)
}
}
finally {
// clear state
defaultTestComponent.loadState(Element("empty"))
defaultProject.stateStore.save()
stateStore.removeComponent(TEST_COMPONENT_NAME)
}
}
@Test
fun `new project from default - remove workspace component configuration`() {
val testData = Paths.get(PathManagerEx.getCommunityHomePath(), "platform/configuration-store-impl/testData")
val element = loadElement(testData.resolve("testData1.xml"))
val tempDir = fsRule.fs.getPath("")
normalizeDefaultProjectElement(ProjectManager.getInstance().defaultProject, element, tempDir)
assertThat(element.isEmpty()).isTrue()
val directoryTree = tempDir.getDirectoryTree()
assertThat(directoryTree.trim()).isEqualTo(testData.resolve("testData1.txt"))
}
@Test
fun `new IPR project from default - remove workspace component configuration`() {
val testData = Paths.get(PathManagerEx.getCommunityHomePath(), "platform/configuration-store-impl/testData")
val element = loadElement(testData.resolve("testData1.xml"))
val tempDir = fsRule.fs.getPath("")
moveComponentConfiguration(ProjectManager.getInstance().defaultProject, element) { if (it == "workspace.xml") tempDir.resolve("test.iws") else tempDir.resolve("test.ipr") }
assertThat(element).isEqualTo(loadElement(testData.resolve("normalize-ipr.xml")))
val directoryTree = tempDir.getDirectoryTree()
assertThat(directoryTree.trim()).isEqualTo(testData.resolve("testData1-ipr.txt"))
}
} | apache-2.0 | dfbc2b075b059d45460d70d8a04cfbc9 | 37.769231 | 176 | 0.758484 | 4.896987 | false | true | false | false |
facebookincubator/ktfmt | core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt | 1 | 85434 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.ktfmt.format
import com.google.common.base.Throwables
import com.google.common.collect.ImmutableList
import com.google.googlejavaformat.Doc
import com.google.googlejavaformat.FormattingError
import com.google.googlejavaformat.Indent
import com.google.googlejavaformat.Indent.Const.ZERO
import com.google.googlejavaformat.OpsBuilder
import com.google.googlejavaformat.Output
import com.google.googlejavaformat.Output.BreakTag
import java.util.ArrayDeque
import java.util.Optional
import org.jetbrains.kotlin.com.intellij.psi.PsiComment
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtAnnotatedExpression
import org.jetbrains.kotlin.psi.KtAnnotation
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtAnnotationUseSiteTarget
import org.jetbrains.kotlin.psi.KtArrayAccessExpression
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtBinaryExpressionWithTypeRHS
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtBreakExpression
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtCallableReferenceExpression
import org.jetbrains.kotlin.psi.KtCatchClause
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassInitializer
import org.jetbrains.kotlin.psi.KtClassLiteralExpression
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtCollectionLiteralExpression
import org.jetbrains.kotlin.psi.KtConstantExpression
import org.jetbrains.kotlin.psi.KtConstructorDelegationCall
import org.jetbrains.kotlin.psi.KtContainerNode
import org.jetbrains.kotlin.psi.KtContinueExpression
import org.jetbrains.kotlin.psi.KtDelegatedSuperTypeEntry
import org.jetbrains.kotlin.psi.KtDestructuringDeclaration
import org.jetbrains.kotlin.psi.KtDestructuringDeclarationEntry
import org.jetbrains.kotlin.psi.KtDoWhileExpression
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtDynamicType
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtEnumEntry
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtFileAnnotationList
import org.jetbrains.kotlin.psi.KtFinallySection
import org.jetbrains.kotlin.psi.KtForExpression
import org.jetbrains.kotlin.psi.KtFunctionType
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.KtImportList
import org.jetbrains.kotlin.psi.KtIntersectionType
import org.jetbrains.kotlin.psi.KtIsExpression
import org.jetbrains.kotlin.psi.KtLabelReferenceExpression
import org.jetbrains.kotlin.psi.KtLabeledExpression
import org.jetbrains.kotlin.psi.KtLambdaArgument
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtModifierList
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtNullableType
import org.jetbrains.kotlin.psi.KtPackageDirective
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtParameterList
import org.jetbrains.kotlin.psi.KtParenthesizedExpression
import org.jetbrains.kotlin.psi.KtPostfixExpression
import org.jetbrains.kotlin.psi.KtPrefixExpression
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
import org.jetbrains.kotlin.psi.KtProjectionKind
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPropertyAccessor
import org.jetbrains.kotlin.psi.KtPropertyDelegate
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.KtScript
import org.jetbrains.kotlin.psi.KtSecondaryConstructor
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.KtSuperExpression
import org.jetbrains.kotlin.psi.KtSuperTypeCallEntry
import org.jetbrains.kotlin.psi.KtSuperTypeList
import org.jetbrains.kotlin.psi.KtThisExpression
import org.jetbrains.kotlin.psi.KtThrowExpression
import org.jetbrains.kotlin.psi.KtTreeVisitorVoid
import org.jetbrains.kotlin.psi.KtTryExpression
import org.jetbrains.kotlin.psi.KtTypeAlias
import org.jetbrains.kotlin.psi.KtTypeArgumentList
import org.jetbrains.kotlin.psi.KtTypeConstraint
import org.jetbrains.kotlin.psi.KtTypeConstraintList
import org.jetbrains.kotlin.psi.KtTypeParameter
import org.jetbrains.kotlin.psi.KtTypeParameterList
import org.jetbrains.kotlin.psi.KtTypeProjection
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.psi.KtUserType
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.KtValueArgumentList
import org.jetbrains.kotlin.psi.KtWhenConditionInRange
import org.jetbrains.kotlin.psi.KtWhenConditionIsPattern
import org.jetbrains.kotlin.psi.KtWhenConditionWithExpression
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.kotlin.psi.KtWhileExpression
import org.jetbrains.kotlin.psi.psiUtil.children
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.psi.psiUtil.startsWithComment
/** An AST visitor that builds a stream of {@link Op}s to format. */
class KotlinInputAstVisitor(
private val options: FormattingOptions,
private val builder: OpsBuilder
) : KtTreeVisitorVoid() {
private val isGoogleStyle = options.style == FormattingOptions.Style.GOOGLE
/** Standard indentation for a block */
private val blockIndent: Indent.Const = Indent.Const.make(options.blockIndent, 1)
/**
* Standard indentation for a long expression or function call, it is different than block
* indentation on purpose
*/
private val expressionBreakIndent: Indent.Const = Indent.Const.make(options.continuationIndent, 1)
private val blockPlusExpressionBreakIndent: Indent.Const =
Indent.Const.make(options.blockIndent + options.continuationIndent, 1)
private val doubleExpressionBreakIndent: Indent.Const =
Indent.Const.make(options.continuationIndent, 2)
private val expressionBreakNegativeIndent: Indent.Const =
Indent.Const.make(-options.continuationIndent, 1)
/** A record of whether we have visited into an expression. */
private val inExpression = ArrayDeque(ImmutableList.of(false))
/** Tracks whether we are handling an import directive */
private var inImport = false
/** Example: `fun foo(n: Int) { println(n) }` */
override fun visitNamedFunction(function: KtNamedFunction) {
builder.sync(function)
builder.block(ZERO) {
visitFunctionLikeExpression(
function.modifierList,
"fun",
function.typeParameterList,
function.receiverTypeReference,
function.nameIdentifier?.text,
true,
function.valueParameterList,
function.typeConstraintList,
function.bodyBlockExpression,
function.bodyExpression,
function.typeReference,
function.bodyBlockExpression?.lBrace != null)
}
}
/** Example `Int`, `(String)` or `() -> Int` */
override fun visitTypeReference(typeReference: KtTypeReference) {
builder.sync(typeReference)
// Normally we'd visit the children nodes through accessors on 'typeReference', and we wouldn't
// loop over children.
// But, in this case the modifier list can either be inside the parenthesis:
// ... (@Composable (x) -> Unit)
// or outside of them:
// ... @Composable ((x) -> Unit)
val modifierList = typeReference.modifierList
val typeElement = typeReference.typeElement
for (child in typeReference.node.children()) {
when {
child.psi == modifierList -> visit(modifierList)
child.psi == typeElement -> visit(typeElement)
child.elementType == KtTokens.LPAR -> builder.token("(")
child.elementType == KtTokens.RPAR -> builder.token(")")
}
}
}
override fun visitDynamicType(type: KtDynamicType) {
builder.token("dynamic")
}
/** Example: `String?` or `((Int) -> Unit)?` */
override fun visitNullableType(nullableType: KtNullableType) {
builder.sync(nullableType)
val innerType = nullableType.innerType
val addParenthesis = innerType is KtFunctionType
if (addParenthesis) {
builder.token("(")
}
visit(nullableType.modifierList)
visit(innerType)
if (addParenthesis) {
builder.token(")")
}
builder.token("?")
}
/** Example: `String` or `List<Int>`, */
override fun visitUserType(type: KtUserType) {
builder.sync(type)
if (type.qualifier != null) {
visit(type.qualifier)
builder.token(".")
}
visit(type.referenceExpression)
val typeArgumentList = type.typeArgumentList
if (typeArgumentList != null) {
builder.block(expressionBreakIndent) { visit(typeArgumentList) }
}
}
/** Example: `A & B`, */
override fun visitIntersectionType(type: KtIntersectionType) {
builder.sync(type)
// TODO(strulovich): Should this have the same indentation behaviour as `x && y`?
visit(type.getLeftTypeRef())
builder.space()
builder.token("&")
builder.space()
visit(type.getRightTypeRef())
}
/** Example `<Int, String>` in `List<Int, String>` */
override fun visitTypeArgumentList(typeArgumentList: KtTypeArgumentList) {
builder.sync(typeArgumentList)
visitEachCommaSeparated(
typeArgumentList.arguments,
typeArgumentList.trailingComma != null,
prefix = "<",
postfix = ">",
)
}
override fun visitTypeProjection(typeProjection: KtTypeProjection) {
builder.sync(typeProjection)
val typeReference = typeProjection.typeReference
when (typeProjection.projectionKind) {
KtProjectionKind.IN -> {
builder.token("in")
builder.space()
visit(typeReference)
}
KtProjectionKind.OUT -> {
builder.token("out")
builder.space()
visit(typeReference)
}
KtProjectionKind.STAR -> builder.token("*")
KtProjectionKind.NONE -> visit(typeReference)
}
}
/**
* @param keyword e.g., "fun" or "class".
* @param typeOrDelegationCall for functions, the return typeOrDelegationCall; for classes, the
* list of supertypes.
*/
private fun visitFunctionLikeExpression(
modifierList: KtModifierList?,
keyword: String,
typeParameters: KtTypeParameterList?,
receiverTypeReference: KtTypeReference?,
name: String?,
emitParenthesis: Boolean,
parameterList: KtParameterList?,
typeConstraintList: KtTypeConstraintList?,
bodyBlockExpression: KtBlockExpression?,
nonBlockBodyExpressions: KtExpression?,
typeOrDelegationCall: KtElement?,
emitBraces: Boolean
) {
builder.block(ZERO) {
if (modifierList != null) {
visitModifierList(modifierList)
}
builder.token(keyword)
if (typeParameters != null) {
builder.space()
builder.block(ZERO) { visit(typeParameters) }
}
if (name != null || receiverTypeReference != null) {
builder.space()
}
builder.block(ZERO) {
if (receiverTypeReference != null) {
visit(receiverTypeReference)
builder.breakOp(Doc.FillMode.INDEPENDENT, "", expressionBreakIndent)
builder.token(".")
}
if (name != null) {
builder.token(name)
}
}
if (emitParenthesis) {
builder.token("(")
}
var paramBlockNeedsClosing = false
builder.block(ZERO) {
if (parameterList != null && parameterList.parameters.isNotEmpty()) {
paramBlockNeedsClosing = true
builder.open(expressionBreakIndent)
builder.breakOp(Doc.FillMode.UNIFIED, "", expressionBreakIndent)
visit(parameterList)
}
if (emitParenthesis) {
if (parameterList != null && parameterList.parameters.isNotEmpty()) {
builder.breakOp(Doc.FillMode.UNIFIED, "", expressionBreakNegativeIndent)
}
builder.token(")")
} else {
if (paramBlockNeedsClosing) {
builder.close()
}
}
if (typeOrDelegationCall != null) {
builder.block(ZERO) {
if (typeOrDelegationCall is KtConstructorDelegationCall) {
builder.space()
}
builder.token(":")
if (parameterList?.parameters.isNullOrEmpty()) {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) { visit(typeOrDelegationCall) }
} else {
builder.space()
builder.block(expressionBreakNegativeIndent) { visit(typeOrDelegationCall) }
}
}
}
}
if (paramBlockNeedsClosing) {
builder.close()
}
if (typeConstraintList != null) {
builder.space()
visit(typeConstraintList)
}
if (bodyBlockExpression != null) {
builder.space()
visitBlockBody(bodyBlockExpression, emitBraces)
} else if (nonBlockBodyExpressions != null) {
builder.space()
builder.block(ZERO) {
builder.token("=")
if (isLambdaOrScopingFunction(nonBlockBodyExpressions)) {
visitLambdaOrScopingFunction(nonBlockBodyExpressions)
} else {
builder.block(expressionBreakIndent) {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", ZERO)
builder.block(ZERO) { visit(nonBlockBodyExpressions) }
}
}
}
}
builder.guessToken(";")
}
if (name != null) {
builder.forcedBreak()
}
}
private fun genSym(): Output.BreakTag {
return Output.BreakTag()
}
private fun visitBlockBody(bodyBlockExpression: PsiElement, emitBraces: Boolean) {
if (emitBraces) {
builder.token("{", Doc.Token.RealOrImaginary.REAL, blockIndent, Optional.of(blockIndent))
}
val statements = bodyBlockExpression.children
if (statements.isNotEmpty()) {
builder.block(blockIndent) {
builder.forcedBreak()
builder.blankLineWanted(OpsBuilder.BlankLineWanted.PRESERVE)
visitStatements(statements)
}
builder.forcedBreak()
builder.blankLineWanted(OpsBuilder.BlankLineWanted.NO)
}
if (emitBraces) {
builder.token("}", blockIndent)
}
}
private fun visitStatement(statement: PsiElement) {
builder.block(ZERO) { visit(statement) }
builder.guessToken(";")
}
private fun visitStatements(statements: Array<PsiElement>) {
var first = true
builder.guessToken(";")
for (statement in statements) {
builder.forcedBreak()
if (!first) {
builder.blankLineWanted(OpsBuilder.BlankLineWanted.PRESERVE)
}
first = false
visitStatement(statement)
}
}
override fun visitProperty(property: KtProperty) {
builder.sync(property)
builder.block(ZERO) {
declareOne(
kind = DeclarationKind.FIELD,
modifiers = property.modifierList,
valOrVarKeyword = property.valOrVarKeyword.text,
typeParameters = property.typeParameterList,
receiver = property.receiverTypeReference,
name = property.nameIdentifier?.text,
type = property.typeReference,
typeConstraintList = property.typeConstraintList,
delegate = property.delegate,
initializer = property.initializer,
accessors = property.accessors)
}
builder.guessToken(";")
if (property.parent !is KtWhenExpression) {
builder.forcedBreak()
}
}
/**
* Example: "com.facebook.bla.bla" in imports or "a.b.c.d" in expressions.
*
* There's a few cases that are different. We deal with imports by keeping them on the same line.
* For regular chained expressions we go the left most descendant so we can start indentation only
* before the first break (a `.` or `?.`), and keep the seem indentation for this chain of calls.
*/
override fun visitQualifiedExpression(expression: KtQualifiedExpression) {
builder.sync(expression)
val receiver = expression.receiverExpression
when {
inImport -> {
visit(receiver)
val selectorExpression = expression.selectorExpression
if (selectorExpression != null) {
builder.token(".")
visit(selectorExpression)
}
}
receiver is KtStringTemplateExpression -> {
val isMultiline = receiver.text.contains('\n')
builder.block(if (isMultiline) expressionBreakIndent else ZERO) {
visit(receiver)
if (isMultiline) {
builder.forcedBreak()
}
builder.token(expression.operationSign.value)
visit(expression.selectorExpression)
}
}
receiver is KtWhenExpression -> {
builder.block(ZERO) {
visit(receiver)
builder.token(expression.operationSign.value)
visit(expression.selectorExpression)
}
}
else -> {
emitQualifiedExpression(expression)
}
}
}
/** Extra data to help [emitQualifiedExpression] know when to open and close a group */
private class GroupingInfo {
var groupOpenCount = 0
var shouldCloseGroup = false
}
/**
* Handles a chain of qualified expressions, i.e. `a[5].b!!.c()[4].f()`
*
* This is by far the most complicated part of this formatter. We start by breaking the expression
* to the steps it is executed in (which are in the opposite order of how the syntax tree is
* built).
*
* We then calculate information to know which parts need to be groups, and finally go part by
* part, emitting it to the [builder] while closing and opening groups.
*/
private fun emitQualifiedExpression(expression: KtExpression) {
val parts = breakIntoParts(expression)
// whether we want to make a lambda look like a block, this make Kotlin DSLs look as expected
val useBlockLikeLambdaStyle = parts.last().isLambda() && parts.count { it.isLambda() } == 1
val groupingInfos = computeGroupingInfo(parts, useBlockLikeLambdaStyle)
builder.block(expressionBreakIndent) {
val nameTag = genSym() // allows adjusting arguments indentation if a break will be made
for ((index, ktExpression) in parts.withIndex()) {
if (ktExpression is KtQualifiedExpression) {
builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO, Optional.of(nameTag))
}
repeat(groupingInfos[index].groupOpenCount) { builder.open(ZERO) }
when (ktExpression) {
is KtQualifiedExpression -> {
builder.token(ktExpression.operationSign.value)
val selectorExpression = ktExpression.selectorExpression
if (selectorExpression !is KtCallExpression) {
// selector is a simple field access
visit(selectorExpression)
if (groupingInfos[index].shouldCloseGroup) {
builder.close()
}
} else {
// selector is a function call, we may close a group after its name
// emit `doIt` from `doIt(1, 2) { it }`
visit(selectorExpression.calleeExpression)
// close groups according to instructions
if (groupingInfos[index].shouldCloseGroup) {
builder.close()
}
// close group due to last lambda to allow block-like style in `as.forEach { ... }`
val isTrailingLambda = useBlockLikeLambdaStyle && index == parts.size - 1
if (isTrailingLambda) {
builder.close()
}
val argsIndentElse = if (index == parts.size - 1) ZERO else expressionBreakIndent
val lambdaIndentElse = if (isTrailingLambda) expressionBreakNegativeIndent else ZERO
val negativeLambdaIndentElse = if (isTrailingLambda) expressionBreakIndent else ZERO
// emit `(1, 2) { it }` from `doIt(1, 2) { it }`
visitCallElement(
null,
selectorExpression.typeArgumentList,
selectorExpression.valueArgumentList,
selectorExpression.lambdaArguments,
argumentsIndent = Indent.If.make(nameTag, expressionBreakIndent, argsIndentElse),
lambdaIndent = Indent.If.make(nameTag, ZERO, lambdaIndentElse),
negativeLambdaIndent = Indent.If.make(nameTag, ZERO, negativeLambdaIndentElse),
)
}
}
is KtArrayAccessExpression -> {
visitArrayAccessBrackets(ktExpression)
builder.close()
}
is KtPostfixExpression -> {
builder.token(ktExpression.operationReference.text)
builder.close()
}
else -> {
check(index == 0)
visit(ktExpression)
}
}
}
}
}
/**
* Decomposes a qualified expression into parts, so `rainbow.red.orange.yellow` becomes `[rainbow,
* rainbow.red, rainbow.red.orange, rainbow.orange.yellow]`
*/
private fun breakIntoParts(expression: KtExpression): List<KtExpression> {
val parts = ArrayDeque<KtExpression>()
// use an ArrayDeque and add elements to the beginning so the innermost expression comes first
// foo.bar.yay -> [yay, bar.yay, foo.bar.yay]
var node: KtExpression? = expression
while (node != null) {
parts.addFirst(node)
node =
when (node) {
is KtQualifiedExpression -> node.receiverExpression
is KtArrayAccessExpression -> node.arrayExpression
is KtPostfixExpression -> node.baseExpression
else -> null
}
}
return parts.toList()
}
/**
* Generates the [GroupingInfo] array to go with an array of [KtQualifiedExpression] parts
*
* For example, the expression `a.b[2].c.d()` is made of four expressions:
* 1. [KtQualifiedExpression] `a.b[2].c . d()` (this will be `parts[4]`)
* 1. [KtQualifiedExpression] `a.b[2] . c` (this will be `parts[3]`)
* 2. [KtArrayAccessExpression] `a.b [2]` (this will be `parts[2]`)
* 3. [KtQualifiedExpression] `a . b` (this will be `parts[1]`)
* 4. [KtSimpleNameExpression] `a` (this will be `parts[0]`)
*
* Once in parts, these are in the reverse order. To render the array correct we need to make sure
* `b` and [2] are in a group so we avoid splitting them. To do so we need to open a group for `b`
* (that will be done in part 2), and always close a group for an array.
*
* Here is the same expression, with justified braces marking the groupings it will get:
* ```
* a . b [2] . c . d ()
* {a . b} --> Grouping `a.b` because it can be a package name or simple field access so we add 1
* to the number of groups to open at groupingInfos[0], and mark to close a group at
* groupingInfos[1]
* {a . b [2]} --> Grouping `a.b` with `[2]`, since otherwise we may break inside the brackets
* instead of preferring breaks before dots. So we open a group at [0], but since
* we always close a group after brackets, we don't store that information.
* {c . d} --> another group to attach the first function name to the fields before it
* this time we don't start the group in the beginning, and use
* lastIndexToOpen to track the spot after the last time we stopped
* grouping.
* ```
* The final expression with groupings:
* ```
* {{a.b}[2]}.{c.d}()
* ```
*/
private fun computeGroupingInfo(
parts: List<KtExpression>,
useBlockLikeLambdaStyle: Boolean
): List<GroupingInfo> {
val groupingInfos = List(parts.size) { GroupingInfo() }
var lastIndexToOpen = 0
for ((index, part) in parts.withIndex()) {
when (part) {
is KtQualifiedExpression -> {
val receiverExpression = part.receiverExpression
val previous =
(receiverExpression as? KtQualifiedExpression)?.selectorExpression
?: receiverExpression
val current = checkNotNull(part.selectorExpression)
if (lastIndexToOpen == 0 &&
shouldGroupPartWithPrevious(parts, part, index, previous, current)) {
// this and the previous items should be grouped for better style
// we add another group to open in index 0
groupingInfos[0].groupOpenCount++
// we don't always close a group when emitting this node, so we need this flag to
// mark if we need to close a group
groupingInfos[index].shouldCloseGroup = true
} else {
// use this index in to open future groups for arrays and postfixes
// we will also stop grouping field access to the beginning of the expression
lastIndexToOpen = index
}
}
is KtArrayAccessExpression,
is KtPostfixExpression -> {
// we group these with the last item with a name, and we always close them
groupingInfos[lastIndexToOpen].groupOpenCount++
}
}
}
if (useBlockLikeLambdaStyle) {
// a trailing lambda adds a group that we stop before emitting the lambda
groupingInfos[0].groupOpenCount++
}
return groupingInfos
}
/** Decide whether a [KtQualifiedExpression] part should be grouped with the previous part */
private fun shouldGroupPartWithPrevious(
parts: List<KtExpression>,
part: KtExpression,
index: Int,
previous: KtExpression,
current: KtExpression
): Boolean {
// this is the second, and the first is short, avoid `.` "hanging in air"
if (index == 1 && previous.text.length < options.continuationIndent) {
return true
}
// the previous part is `this` or `super`
if (previous is KtSuperExpression || previous is KtThisExpression) {
return true
}
// this and the previous part are a package name, type name, or property
if (previous is KtSimpleNameExpression &&
current is KtSimpleNameExpression &&
part is KtDotQualifiedExpression) {
return true
}
// this is `Foo` in `com.facebook.Foo`, so everything before it is a package name
if (current.text.first().isUpperCase() &&
current is KtSimpleNameExpression &&
part is KtDotQualifiedExpression) {
return true
}
// this is the `foo()` in `com.facebook.Foo.foo()` or in `Foo.foo()`
if (current is KtCallExpression &&
(previous !is KtCallExpression) &&
previous.text?.firstOrNull()?.isUpperCase() == true) {
return true
}
// this is an invocation and the last item, and the previous it not, i.e. `a.b.c()`
// keeping it grouped and splitting the arguments makes `a.b(...)` feel like `aab()`
return current is KtCallExpression &&
previous !is KtCallExpression &&
index == parts.indices.last
}
/** Returns true if the expression represents an invocation that is also a lambda */
private fun KtExpression.isLambda(): Boolean {
return extractCallExpression(this)?.lambdaArguments?.isNotEmpty() ?: false
}
/**
* emitQualifiedExpression formats call expressions that are either part of a qualified
* expression, or standing alone. This method makes it easier to handle both cases uniformly.
*/
private fun extractCallExpression(expression: KtExpression): KtCallExpression? {
val ktExpression = (expression as? KtQualifiedExpression)?.selectorExpression ?: expression
return ktExpression as? KtCallExpression
}
override fun visitCallExpression(callExpression: KtCallExpression) {
builder.sync(callExpression)
with(callExpression) {
visitCallElement(
calleeExpression,
typeArgumentList,
valueArgumentList,
lambdaArguments,
)
}
}
/**
* Examples `foo<T>(a, b)`, `foo(a)`, `boo()`, `super(a)`
*
* @param lambdaIndent how to indent [lambdaArguments], if present
* @param negativeLambdaIndent the negative indentation of [lambdaIndent]
*/
private fun visitCallElement(
callee: KtExpression?,
typeArgumentList: KtTypeArgumentList?,
argumentList: KtValueArgumentList?,
lambdaArguments: List<KtLambdaArgument>,
argumentsIndent: Indent = expressionBreakIndent,
lambdaIndent: Indent = ZERO,
negativeLambdaIndent: Indent = ZERO,
) {
// Apply the lambda indent to the callee, type args, value args, and the lambda.
// This is undone for the first three by the negative lambda indent.
// This way they're in one block, and breaks in the argument list cause a break in the lambda.
builder.block(lambdaIndent) {
// Used to keep track of whether or not we need to indent the lambda
// This is based on if there is a break in the argument list
var brokeBeforeBrace: BreakTag? = null
builder.block(negativeLambdaIndent) {
visit(callee)
builder.block(argumentsIndent) {
builder.block(ZERO) { visit(typeArgumentList) }
if (argumentList != null) {
brokeBeforeBrace = visitValueArgumentListInternal(argumentList)
}
}
}
if (lambdaArguments.isNotEmpty()) {
builder.space()
visitArgumentInternal(
lambdaArguments.single(),
wrapInBlock = false,
brokeBeforeBrace = brokeBeforeBrace,
)
}
}
}
/** Example (`1, "hi"`) in a function call */
override fun visitValueArgumentList(list: KtValueArgumentList) {
visitValueArgumentListInternal(list)
}
/**
* Example (`1, "hi"`) in a function call
*
* @return a [BreakTag] which can tell you if a break was taken, but only when the list doesn't
* terminate in a negative closing indent. See [visitEachCommaSeparated] for examples.
*/
private fun visitValueArgumentListInternal(list: KtValueArgumentList): BreakTag? {
builder.sync(list)
val arguments = list.arguments
val isSingleUnnamedLambda =
arguments.size == 1 &&
arguments.first().getArgumentExpression() is KtLambdaExpression &&
arguments.first().getArgumentName() == null
val hasTrailingComma = list.trailingComma != null
val wrapInBlock: Boolean
val breakBeforePostfix: Boolean
val leadingBreak: Boolean
val breakAfterPrefix: Boolean
if (isSingleUnnamedLambda) {
wrapInBlock = true
breakBeforePostfix = false
leadingBreak = arguments.isNotEmpty() && hasTrailingComma
breakAfterPrefix = false
} else {
wrapInBlock = !isGoogleStyle
breakBeforePostfix = isGoogleStyle && arguments.isNotEmpty()
leadingBreak = arguments.isNotEmpty()
breakAfterPrefix = arguments.isNotEmpty()
}
return visitEachCommaSeparated(
list.arguments,
hasTrailingComma,
wrapInBlock = wrapInBlock,
breakBeforePostfix = breakBeforePostfix,
leadingBreak = leadingBreak,
prefix = "(",
postfix = ")",
breakAfterPrefix = breakAfterPrefix,
)
}
/** Example `{ 1 + 1 }` (as lambda) or `{ (x, y) -> x + y }` */
override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {
visitLambdaExpressionInternal(lambdaExpression, brokeBeforeBrace = null)
}
/**
* The internal version of [visitLambdaExpression].
*
* @param brokeBeforeBrace used for tracking if a break was taken right before the lambda
* expression. Useful for scoping functions where we want good looking indentation. For example,
* here we have correct indentation before `bar()` and `car()` because we can detect the break
* after the equals:
* ```
* fun foo() =
* coroutineScope { x ->
* bar()
* car()
* }
* ```
*/
private fun visitLambdaExpressionInternal(
lambdaExpression: KtLambdaExpression,
brokeBeforeBrace: BreakTag?,
) {
builder.sync(lambdaExpression)
val valueParams = lambdaExpression.valueParameters
val hasParams = valueParams.isNotEmpty()
val statements = (lambdaExpression.bodyExpression ?: fail()).children
val hasStatements = statements.isNotEmpty()
val hasArrow = lambdaExpression.functionLiteral.arrow != null
fun ifBrokeBeforeBrace(onTrue: Indent, onFalse: Indent): Indent {
if (brokeBeforeBrace == null) return onFalse
return Indent.If.make(brokeBeforeBrace, onTrue, onFalse)
}
/**
* Enable correct formatting of the `fun foo() = scope {` syntax.
*
* We can't denote the lambda (+ scope function) as a block, since (for multiline lambdas) the
* rectangle rule would force the entire lambda onto a lower line. Instead, we conditionally
* indent all the interior levels of the lambda based on whether we had to break before the
* opening brace (or scope function). This mimics the look of a block when the break is taken.
*
* These conditional indents should not be used inside interior blocks, since that would apply
* the condition twice.
*/
val bracePlusBlockIndent = ifBrokeBeforeBrace(blockPlusExpressionBreakIndent, blockIndent)
val bracePlusExpressionIndent =
ifBrokeBeforeBrace(doubleExpressionBreakIndent, expressionBreakIndent)
val bracePlusZeroIndent = ifBrokeBeforeBrace(expressionBreakIndent, ZERO)
builder.token("{")
if (hasParams || hasArrow) {
builder.space()
builder.block(bracePlusExpressionIndent) { visitEachCommaSeparated(valueParams) }
builder.block(bracePlusBlockIndent) {
if (lambdaExpression.functionLiteral.valueParameterList?.trailingComma != null) {
builder.token(",")
builder.forcedBreak()
} else if (hasParams) {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", ZERO)
}
builder.token("->")
}
builder.breakOp(Doc.FillMode.UNIFIED, "", bracePlusZeroIndent)
}
if (hasStatements) {
builder.breakOp(Doc.FillMode.UNIFIED, " ", bracePlusBlockIndent)
builder.block(bracePlusBlockIndent) {
builder.blankLineWanted(OpsBuilder.BlankLineWanted.NO)
if (statements.size == 1 &&
statements.first() !is KtReturnExpression &&
lambdaExpression.bodyExpression?.startsWithComment() != true) {
visitStatement(statements[0])
} else {
visitStatements(statements)
}
}
}
if (hasParams || hasArrow || hasStatements) {
// If we had to break in the body, ensure there is a break before the closing brace
builder.breakOp(Doc.FillMode.UNIFIED, " ", bracePlusZeroIndent)
builder.blankLineWanted(OpsBuilder.BlankLineWanted.NO)
}
builder.block(bracePlusZeroIndent) {
// If there are closing comments, make sure they and the brace are indented together
// The comments will indent themselves, so consume the previous break as a blank line
builder.breakOp(Doc.FillMode.INDEPENDENT, "", ZERO)
builder.token("}", blockIndent)
}
}
/** Example `this` or `this@Foo` */
override fun visitThisExpression(expression: KtThisExpression) {
builder.sync(expression)
builder.token("this")
visit(expression.getTargetLabel())
}
/** Example `Foo` or `@Foo` */
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
builder.sync(expression)
when (expression) {
is KtLabelReferenceExpression -> {
if (expression.text[0] == '@') {
builder.token("@")
builder.token(expression.getIdentifier()?.text ?: fail())
} else {
builder.token(expression.getIdentifier()?.text ?: fail())
builder.token("@")
}
}
else -> {
if (expression.text.isNotEmpty()) {
builder.token(expression.text)
}
}
}
}
/** e.g., `a: Int, b: Int, c: Int` in `fun foo(a: Int, b: Int, c: Int) { ... }`. */
override fun visitParameterList(list: KtParameterList) {
visitEachCommaSeparated(list.parameters, list.trailingComma != null, wrapInBlock = false)
}
/**
* Visit each element in [list], with comma (,) tokens in-between.
*
* Example:
* ```
* a, b, c, 3, 4, 5
* ```
*
* Either the entire list fits in one line, or each element is put on its own line:
* ```
* a,
* b,
* c,
* 3,
* 4,
* 5
* ```
*
* Optionally include a prefix and postfix:
* ```
* (
* a,
* b,
* c,
* )
* ```
*
* @param hasTrailingComma if true, each element is placed on its own line (even if they could've
* fit in a single line), and a trailing comma is emitted.
*
* Example:
* ```
* a,
* b,
* ```
*
* @param wrapInBlock if true, place all the elements in a block. When there's no [leadingBreak],
* this will be negatively indented. Note that the [prefix] and [postfix] aren't included in the
* block.
* @param leadingBreak if true, break before the first element.
* @param prefix if provided, emit this before the first element.
* @param postfix if provided, emit this after the last element (or trailing comma).
* @param breakAfterPrefix if true, emit a break after [prefix], but before the start of the
* block.
* @param breakBeforePostfix if true, place a break after the last element. Redundant when
* [hasTrailingComma] is true.
* @return a [BreakTag] which can tell you if a break was taken, but only when the list doesn't
* terminate in a negative closing indent.
*
* Example 1, this returns a BreakTag which tells you a break wasn't taken:
* ```
* (arg1, arg2)
* ```
*
* Example 2, this returns a BreakTag which tells you a break WAS taken:
* ```
* (
* arg1,
* arg2)
* ```
*
* Example 3, this returns null:
* ```
* (
* arg1,
* arg2,
* )
* ```
*
* Example 4, this also returns null (similar to example 2, but Google style):
* ```
* (
* arg1,
* arg2
* )
* ```
*/
private fun visitEachCommaSeparated(
list: Iterable<PsiElement>,
hasTrailingComma: Boolean = false,
wrapInBlock: Boolean = true,
leadingBreak: Boolean = true,
prefix: String? = null,
postfix: String? = null,
breakAfterPrefix: Boolean = true,
breakBeforePostfix: Boolean = isGoogleStyle,
): BreakTag? {
val breakAfterLastElement = hasTrailingComma || (postfix != null && breakBeforePostfix)
val nameTag = if (breakAfterLastElement) null else genSym()
if (prefix != null) {
builder.token(prefix)
if (breakAfterPrefix) {
builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO, Optional.ofNullable(nameTag))
}
}
val breakType = if (hasTrailingComma) Doc.FillMode.FORCED else Doc.FillMode.UNIFIED
fun emitComma() {
builder.token(",")
builder.breakOp(breakType, " ", ZERO)
}
val indent = if (leadingBreak) ZERO else expressionBreakNegativeIndent
builder.block(indent, isEnabled = wrapInBlock) {
if (leadingBreak) {
builder.breakOp(breakType, "", ZERO)
}
var first = true
for (value in list) {
if (!first) emitComma()
first = false
visit(value)
}
if (hasTrailingComma) {
emitComma()
}
}
if (breakAfterLastElement) {
// a negative closing indent places the postfix to the left of the elements
// see examples 2 and 4 in the docstring
builder.breakOp(breakType, "", expressionBreakNegativeIndent)
}
if (postfix != null) {
builder.token(postfix)
}
return nameTag
}
/** Example `a` in `foo(a)`, or `*a`, or `limit = 50` */
override fun visitArgument(argument: KtValueArgument) {
visitArgumentInternal(
argument,
wrapInBlock = true,
brokeBeforeBrace = null,
)
}
/**
* The internal version of [visitArgument].
*
* @param wrapInBlock if true places the argument expression in a block.
*/
private fun visitArgumentInternal(
argument: KtValueArgument,
wrapInBlock: Boolean,
brokeBeforeBrace: BreakTag?,
) {
builder.sync(argument)
val hasArgName = argument.getArgumentName() != null
val isLambda = argument.getArgumentExpression() is KtLambdaExpression
if (hasArgName) {
visit(argument.getArgumentName())
builder.space()
builder.token("=")
if (isLambda) {
builder.space()
}
}
val indent = if (hasArgName && !isLambda) expressionBreakIndent else ZERO
builder.block(indent, isEnabled = wrapInBlock) {
if (hasArgName && !isLambda) {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", ZERO)
}
if (argument.isSpread) {
builder.token("*")
}
if (isLambda) {
visitLambdaExpressionInternal(
argument.getArgumentExpression() as KtLambdaExpression,
brokeBeforeBrace = brokeBeforeBrace,
)
} else {
visit(argument.getArgumentExpression())
}
}
}
override fun visitReferenceExpression(expression: KtReferenceExpression) {
builder.sync(expression)
builder.token(expression.text)
}
override fun visitReturnExpression(expression: KtReturnExpression) {
builder.sync(expression)
builder.token("return")
visit(expression.getTargetLabel())
val returnedExpression = expression.returnedExpression
if (returnedExpression != null) {
builder.space()
visit(returnedExpression)
}
builder.guessToken(";")
}
/**
* For example `a + b`, `a + b + c` or `a..b`
*
* The extra handling here drills to the left most expression and handles it for long chains of
* binary expressions that are formatted not accordingly to the associative values That is, we
* want to think of `a + b + c` as `(a + b) + c`, whereas the AST parses it as `a + (b + c)`
*/
override fun visitBinaryExpression(expression: KtBinaryExpression) {
builder.sync(expression)
val op = expression.operationToken
if (KtTokens.ALL_ASSIGNMENTS.contains(op) && isLambdaOrScopingFunction(expression.right)) {
// Assignments are statements in Kotlin; we don't have to worry about compound assignment.
visit(expression.left)
builder.space()
builder.token(expression.operationReference.text)
visitLambdaOrScopingFunction(expression.right)
return
}
val parts =
ArrayDeque<KtBinaryExpression>().apply {
var current: KtExpression? = expression
while (current is KtBinaryExpression && current.operationToken == op) {
addFirst(current)
current = current.left
}
}
val leftMostExpression = parts.first()
visit(leftMostExpression.left)
for (leftExpression in parts) {
when (leftExpression.operationToken) {
KtTokens.RANGE -> {}
KtTokens.ELVIS -> builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
else -> builder.space()
}
builder.token(leftExpression.operationReference.text)
val isFirst = leftExpression === leftMostExpression
if (isFirst) {
builder.open(expressionBreakIndent)
}
when (leftExpression.operationToken) {
KtTokens.RANGE -> {}
KtTokens.ELVIS -> builder.space()
else -> builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
}
visit(leftExpression.right)
}
builder.close()
}
override fun visitPostfixExpression(expression: KtPostfixExpression) {
builder.sync(expression)
builder.block(ZERO) {
val baseExpression = expression.baseExpression
val operator = expression.operationReference.text
visit(baseExpression)
if (baseExpression is KtPostfixExpression &&
baseExpression.operationReference.text.last() == operator.first()) {
builder.space()
}
builder.token(operator)
}
}
override fun visitPrefixExpression(expression: KtPrefixExpression) {
builder.sync(expression)
builder.block(ZERO) {
val baseExpression = expression.baseExpression
val operator = expression.operationReference.text
builder.token(operator)
if (baseExpression is KtPrefixExpression &&
operator.last() == baseExpression.operationReference.text.first()) {
builder.space()
}
visit(baseExpression)
}
}
override fun visitLabeledExpression(expression: KtLabeledExpression) {
builder.sync(expression)
visit(expression.labelQualifier)
if (expression.baseExpression !is KtLambdaExpression) {
builder.space()
}
visit(expression.baseExpression)
}
internal enum class DeclarationKind {
FIELD,
PARAMETER
}
/**
* Declare one variable or variable-like thing.
*
* Examples:
* - `var a: Int = 5`
* - `a: Int`
* - `private val b:
*/
private fun declareOne(
kind: DeclarationKind,
modifiers: KtModifierList?,
valOrVarKeyword: String?,
typeParameters: KtTypeParameterList? = null,
receiver: KtTypeReference? = null,
name: String?,
type: KtTypeReference?,
typeConstraintList: KtTypeConstraintList? = null,
initializer: KtExpression?,
delegate: KtPropertyDelegate? = null,
accessors: List<KtPropertyAccessor>? = null
): Int {
val verticalAnnotationBreak = genSym()
val isField = kind == DeclarationKind.FIELD
if (isField) {
builder.blankLineWanted(OpsBuilder.BlankLineWanted.conditional(verticalAnnotationBreak))
}
visit(modifiers)
builder.block(ZERO) {
builder.block(ZERO) {
if (valOrVarKeyword != null) {
builder.token(valOrVarKeyword)
builder.space()
}
if (typeParameters != null) {
visit(typeParameters)
builder.space()
}
// conditionally indent the name and initializer +4 if the type spans
// multiple lines
if (name != null) {
if (receiver != null) {
visit(receiver)
builder.token(".")
}
builder.token(name)
builder.op("")
}
}
if (name != null) {
builder.open(expressionBreakIndent) // open block for named values
}
// For example `: String` in `val thisIsALongName: String` or `fun f(): String`
if (type != null) {
if (name != null) {
builder.token(":")
builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
}
visit(type)
}
}
// For example `where T : Int` in a generic method
if (typeConstraintList != null) {
builder.space()
visit(typeConstraintList)
builder.space()
}
// for example `by lazy { compute() }`
if (delegate != null) {
builder.space()
builder.token("by")
if (isLambdaOrScopingFunction(delegate.expression)) {
builder.space()
visit(delegate)
} else {
builder.breakOp(Doc.FillMode.UNIFIED, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) { visit(delegate) }
}
} else if (initializer != null) {
builder.space()
builder.token("=")
if (isLambdaOrScopingFunction(initializer)) {
visitLambdaOrScopingFunction(initializer)
} else {
builder.breakOp(Doc.FillMode.UNIFIED, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) { visit(initializer) }
}
}
if (name != null) {
builder.close() // close block for named values
}
// for example `private set` or `get = 2 * field`
if (accessors?.isNotEmpty() == true) {
builder.block(blockIndent) {
for (accessor in accessors) {
builder.forcedBreak()
// The semicolon must come after the newline, or the output code will not parse.
builder.guessToken(";")
builder.block(ZERO) {
visitFunctionLikeExpression(
accessor.modifierList,
accessor.namePlaceholder.text,
null,
null,
null,
accessor.bodyExpression != null || accessor.bodyBlockExpression != null,
accessor.parameterList,
null,
accessor.bodyBlockExpression,
accessor.bodyExpression,
accessor.returnTypeReference,
accessor.bodyBlockExpression?.lBrace != null)
}
}
}
}
builder.guessToken(";")
if (isField) {
builder.blankLineWanted(OpsBuilder.BlankLineWanted.conditional(verticalAnnotationBreak))
}
return 0
}
/**
* Returns whether an expression is a lambda or initializer expression in which case we will want
* to avoid indenting the lambda block
*
* Examples:
* 1. '... = { ... }' is a lambda expression
* 2. '... = Runnable { ... }' is considered a scoping function
* 3. '... = scope { ... }' '... = apply { ... }' is a scoping function
*
* but not:
* 1. '... = foo() { ... }' due to the empty parenthesis
* 2. '... = Runnable @Annotation { ... }' due to the annotation
*/
private fun isLambdaOrScopingFunction(expression: KtExpression?): Boolean {
if (expression is KtLambdaExpression) {
return true
}
if (expression is KtCallExpression &&
expression.valueArgumentList?.leftParenthesis == null &&
expression.lambdaArguments.isNotEmpty() &&
expression.typeArgumentList?.arguments.isNullOrEmpty() &&
expression.lambdaArguments.first().getArgumentExpression() is KtLambdaExpression) {
return true
}
return false
}
/** See [isLambdaOrScopingFunction] for examples. */
private fun visitLambdaOrScopingFunction(expr: PsiElement?) {
val breakToExpr = genSym()
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent, Optional.of(breakToExpr))
val lambdaExpression =
when (expr) {
is KtLambdaExpression -> expr
is KtCallExpression -> {
visit(expr.calleeExpression)
builder.space()
expr.lambdaArguments[0].getLambdaExpression() ?: fail()
}
else -> throw AssertionError(expr)
}
visitLambdaExpressionInternal(lambdaExpression, brokeBeforeBrace = breakToExpr)
}
override fun visitClassOrObject(classOrObject: KtClassOrObject) {
builder.sync(classOrObject)
val modifierList = classOrObject.modifierList
builder.block(ZERO) {
if (modifierList != null) {
visitModifierList(modifierList)
}
val declarationKeyword = classOrObject.getDeclarationKeyword()
if (declarationKeyword != null) {
builder.token(declarationKeyword.text ?: fail())
}
val name = classOrObject.nameIdentifier
if (name != null) {
builder.space()
builder.token(name.text)
visit(classOrObject.typeParameterList)
}
visit(classOrObject.primaryConstructor)
val superTypes = classOrObject.getSuperTypeList()
if (superTypes != null) {
builder.space()
builder.block(ZERO) {
builder.token(":")
builder.breakOp(Doc.FillMode.UNIFIED, " ", expressionBreakIndent)
visit(superTypes)
}
}
builder.space()
val typeConstraintList = classOrObject.typeConstraintList
if (typeConstraintList != null) {
if (superTypes?.entries?.lastOrNull() is KtDelegatedSuperTypeEntry) {
builder.forcedBreak()
}
visit(typeConstraintList)
builder.space()
}
val body = classOrObject.body
if (classOrObject.hasModifier(KtTokens.ENUM_KEYWORD)) {
visitEnumBody(classOrObject as KtClass)
} else if (body != null) {
visitBlockBody(body, true)
}
}
if (classOrObject.nameIdentifier != null) {
builder.forcedBreak()
}
}
/** Example `{ RED, GREEN; fun foo() { ... } }` for an enum class */
private fun visitEnumBody(enumClass: KtClass) {
val body = enumClass.body
if (body == null) {
return
}
builder.token("{", Doc.Token.RealOrImaginary.REAL, blockIndent, Optional.of(blockIndent))
builder.open(ZERO)
builder.block(blockIndent) {
builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO)
val (enumEntries, nonEnumEntryStatements) = body.children.partition { it is KtEnumEntry }
builder.forcedBreak()
visitEnumEntries(enumEntries)
if (nonEnumEntryStatements.isNotEmpty()) {
builder.forcedBreak()
builder.blankLineWanted(OpsBuilder.BlankLineWanted.PRESERVE)
visitStatements(nonEnumEntryStatements.toTypedArray())
}
}
builder.forcedBreak()
builder.blankLineWanted(OpsBuilder.BlankLineWanted.NO)
builder.token("}", blockIndent)
builder.close()
}
/** Example `RED, GREEN, BLUE,` in an enum class, or `RED, GREEN;` */
private fun visitEnumEntries(enumEntries: List<PsiElement>) {
builder.block(ZERO) {
builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO)
for (value in enumEntries) {
visit(value)
if (builder.peekToken() == Optional.of(",")) {
builder.token(",")
builder.forcedBreak()
}
}
}
builder.guessToken(";")
}
override fun visitPrimaryConstructor(constructor: KtPrimaryConstructor) {
builder.sync(constructor)
builder.block(ZERO) {
if (constructor.hasConstructorKeyword()) {
builder.open(ZERO)
builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
visit(constructor.modifierList)
builder.token("constructor")
}
builder.block(ZERO) {
builder.token("(")
builder.block(expressionBreakIndent) {
builder.breakOp(Doc.FillMode.UNIFIED, "", expressionBreakIndent)
visit(constructor.valueParameterList)
builder.breakOp(Doc.FillMode.UNIFIED, "", expressionBreakNegativeIndent)
if (constructor.hasConstructorKeyword()) {
builder.close()
}
}
builder.token(")")
}
}
}
/** Example `private constructor(n: Int) : this(4, 5) { ... }` inside a class's body */
override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) {
val delegationCall = constructor.getDelegationCall()
val bodyExpression = constructor.bodyExpression
builder.sync(constructor)
visitFunctionLikeExpression(
constructor.modifierList,
"constructor",
null,
null,
null,
true,
constructor.valueParameterList,
null,
bodyExpression,
null,
if (!delegationCall.isImplicit) delegationCall else null,
true)
}
override fun visitConstructorDelegationCall(call: KtConstructorDelegationCall) {
// Work around a misfeature in kotlin-compiler: call.calleeExpression.accept doesn't call
// visitReferenceExpression, but calls visitElement instead.
builder.block(ZERO) {
builder.token(if (call.isCallToThis) "this" else "super")
visitCallElement(
null,
call.typeArgumentList,
call.valueArgumentList,
call.lambdaArguments,
)
}
}
override fun visitClassInitializer(initializer: KtClassInitializer) {
builder.sync(initializer)
builder.token("init")
builder.space()
visit(initializer.body)
}
override fun visitConstantExpression(expression: KtConstantExpression) {
builder.sync(expression)
builder.token(expression.text)
}
/** Example `(1 + 1)` */
override fun visitParenthesizedExpression(expression: KtParenthesizedExpression) {
builder.sync(expression)
builder.token("(")
visit(expression.expression)
builder.token(")")
}
override fun visitPackageDirective(directive: KtPackageDirective) {
builder.sync(directive)
if (directive.packageKeyword == null) {
return
}
builder.token("package")
builder.space()
var first = true
for (packageName in directive.packageNames) {
if (first) {
first = false
} else {
builder.token(".")
}
builder.token(packageName.getIdentifier()?.text ?: packageName.getReferencedName())
}
builder.guessToken(";")
builder.forcedBreak()
}
/** Example `import com.foo.A; import com.bar.B` */
override fun visitImportList(importList: KtImportList) {
builder.sync(importList)
importList.imports.forEach { visit(it) }
}
/** Example `import com.foo.A` */
override fun visitImportDirective(directive: KtImportDirective) {
builder.sync(directive)
builder.token("import")
builder.space()
val importedReference = directive.importedReference
if (importedReference != null) {
inImport = true
visit(importedReference)
inImport = false
}
if (directive.isAllUnder) {
builder.token(".")
builder.token("*")
}
// Possible alias.
val alias = directive.alias?.nameIdentifier
if (alias != null) {
builder.space()
builder.token("as")
builder.space()
builder.token(alias.text ?: fail())
}
// Force a newline afterwards.
builder.guessToken(";")
builder.forcedBreak()
}
/** For example `@Magic private final` */
override fun visitModifierList(list: KtModifierList) {
builder.sync(list)
var onlyAnnotationsSoFar = true
for (child in list.node.children()) {
val psi = child.psi
if (psi is PsiWhiteSpace) {
continue
}
if (child.elementType is KtModifierKeywordToken) {
onlyAnnotationsSoFar = false
builder.token(child.text)
} else {
visit(psi)
}
if (onlyAnnotationsSoFar) {
builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
} else {
builder.space()
}
}
}
/**
* Example:
* ```
* @SuppressLint("MagicNumber")
* print(10)
* ```
*
* in
*
* ```
* fun f() {
* @SuppressLint("MagicNumber")
* print(10)
* }
* ```
*/
override fun visitAnnotatedExpression(expression: KtAnnotatedExpression) {
builder.sync(expression)
builder.block(ZERO) {
val baseExpression = expression.baseExpression
builder.block(ZERO) {
val annotationEntries = expression.annotationEntries
for (annotationEntry in annotationEntries) {
if (annotationEntry !== annotationEntries.first()) {
builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
}
visit(annotationEntry)
}
}
// Binary expressions in a block have a different meaning according to their formatting.
// If there in the line above, they refer to the entire expression, if they're in the same
// line then only to the first operand of the operator.
// We force a break to avoid such semantic changes
when {
(baseExpression is KtBinaryExpression || baseExpression is KtBinaryExpressionWithTypeRHS) &&
expression.parent is KtBlockExpression -> builder.forcedBreak()
baseExpression is KtLambdaExpression -> builder.space()
else -> builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
}
visit(expression.baseExpression)
}
}
/**
* For example, @field:[Inject Named("WEB_VIEW")]
*
* A KtAnnotation is used only to group multiple annotations with the same use-site-target. It
* only appears in a modifier list since annotated expressions do not have use-site-targets.
*/
override fun visitAnnotation(annotation: KtAnnotation) {
builder.sync(annotation)
builder.block(ZERO) {
builder.token("@")
val useSiteTarget = annotation.useSiteTarget
if (useSiteTarget != null) {
visit(useSiteTarget)
builder.token(":")
}
builder.block(expressionBreakIndent) {
builder.token("[")
builder.block(ZERO) {
var first = true
builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO)
for (value in annotation.entries) {
if (!first) {
builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
}
first = false
visit(value)
}
}
}
builder.token("]")
}
builder.forcedBreak()
}
/** For example, 'field' in @field:[Inject Named("WEB_VIEW")] */
override fun visitAnnotationUseSiteTarget(
annotationTarget: KtAnnotationUseSiteTarget,
data: Void?
): Void? {
builder.token(annotationTarget.getAnnotationUseSiteTarget().renderName)
return null
}
/** For example `@Magic` or `@Fred(1, 5)` */
override fun visitAnnotationEntry(annotationEntry: KtAnnotationEntry) {
builder.sync(annotationEntry)
if (annotationEntry.atSymbol != null) {
builder.token("@")
}
val useSiteTarget = annotationEntry.useSiteTarget
if (useSiteTarget != null && useSiteTarget.parent == annotationEntry) {
visit(useSiteTarget)
builder.token(":")
}
visitCallElement(
annotationEntry.calleeExpression,
null, // Type-arguments are included in the annotation's callee expression.
annotationEntry.valueArgumentList,
listOf())
}
override fun visitFileAnnotationList(
fileAnnotationList: KtFileAnnotationList,
data: Void?
): Void? {
for (child in fileAnnotationList.node.children()) {
if (child is PsiElement) {
continue
}
visit(child.psi)
builder.forcedBreak()
}
return null
}
override fun visitSuperTypeList(list: KtSuperTypeList) {
builder.sync(list)
builder.block(expressionBreakIndent) { visitEachCommaSeparated(list.entries) }
}
override fun visitSuperTypeCallEntry(call: KtSuperTypeCallEntry) {
builder.sync(call)
visitCallElement(call.calleeExpression, null, call.valueArgumentList, call.lambdaArguments)
}
/**
* Example `Collection<Int> by list` in `class MyList(list: List<Int>) : Collection<Int> by list`
*/
override fun visitDelegatedSuperTypeEntry(specifier: KtDelegatedSuperTypeEntry) {
builder.sync(specifier)
visit(specifier.typeReference)
builder.space()
builder.token("by")
builder.space()
visit(specifier.delegateExpression)
}
override fun visitWhenExpression(expression: KtWhenExpression) {
builder.sync(expression)
builder.block(ZERO) {
emitKeywordWithCondition("when", expression.subjectExpression)
builder.space()
builder.token("{", Doc.Token.RealOrImaginary.REAL, blockIndent, Optional.of(blockIndent))
expression.entries.forEach { whenEntry ->
builder.block(blockIndent) {
builder.forcedBreak()
if (whenEntry.isElse) {
builder.token("else")
} else {
builder.block(ZERO) {
val conditions = whenEntry.conditions
for ((index, condition) in conditions.withIndex()) {
visit(condition)
builder.guessToken(",")
if (index != conditions.lastIndex) {
builder.forcedBreak()
}
}
}
}
val whenExpression = whenEntry.expression
builder.space()
builder.token("->")
if (whenExpression is KtBlockExpression) {
builder.space()
visit(whenExpression)
} else {
builder.block(expressionBreakIndent) {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", ZERO)
visit(whenExpression)
}
}
builder.guessToken(";")
}
builder.forcedBreak()
}
builder.token("}")
}
}
override fun visitBlockExpression(expression: KtBlockExpression) {
builder.sync(expression)
visitBlockBody(expression, true)
}
override fun visitWhenConditionWithExpression(condition: KtWhenConditionWithExpression) {
builder.sync(condition)
visit(condition.expression)
}
override fun visitWhenConditionIsPattern(condition: KtWhenConditionIsPattern) {
builder.sync(condition)
builder.token(if (condition.isNegated) "!is" else "is")
builder.space()
visit(condition.typeReference)
}
/** Example `in 1..2` as part of a when expression */
override fun visitWhenConditionInRange(condition: KtWhenConditionInRange) {
builder.sync(condition)
// TODO: replace with 'condition.isNegated' once https://youtrack.jetbrains.com/issue/KT-34395
// is fixed.
val isNegated = condition.firstChild?.node?.findChildByType(KtTokens.NOT_IN) != null
builder.token(if (isNegated) "!in" else "in")
builder.space()
visit(condition.rangeExpression)
}
override fun visitIfExpression(expression: KtIfExpression) {
builder.sync(expression)
builder.block(ZERO) {
emitKeywordWithCondition("if", expression.condition)
if (expression.then is KtBlockExpression) {
builder.space()
builder.block(ZERO) { visit(expression.then) }
} else {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) { visit(expression.then) }
}
if (expression.elseKeyword != null) {
if (expression.then is KtBlockExpression) {
builder.space()
} else {
builder.breakOp(Doc.FillMode.UNIFIED, " ", ZERO)
}
builder.block(ZERO) {
builder.token("else")
if (expression.`else` is KtBlockExpression || expression.`else` is KtIfExpression) {
builder.space()
builder.block(ZERO) { visit(expression.`else`) }
} else {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) { visit(expression.`else`) }
}
}
}
}
}
/** Example `a[3]`, `b["a", 5]` or `a.b.c[4]` */
override fun visitArrayAccessExpression(expression: KtArrayAccessExpression) {
builder.sync(expression)
if (expression.arrayExpression is KtQualifiedExpression) {
emitQualifiedExpression(expression)
} else {
visit(expression.arrayExpression)
visitArrayAccessBrackets(expression)
}
}
/**
* Example `[3]` in `a[3]` or `a[3].b` Separated since it needs to be used from a top level array
* expression (`a[3]`) and from within a qualified chain (`a[3].b)
*/
private fun visitArrayAccessBrackets(expression: KtArrayAccessExpression) {
builder.block(ZERO) {
builder.token("[")
builder.breakOp(Doc.FillMode.UNIFIED, "", expressionBreakIndent)
builder.block(expressionBreakIndent) {
visitEachCommaSeparated(
expression.indexExpressions, expression.trailingComma != null, wrapInBlock = true)
}
}
builder.token("]")
}
/** Example `val (a, b: Int) = Pair(1, 2)` */
override fun visitDestructuringDeclaration(destructuringDeclaration: KtDestructuringDeclaration) {
builder.sync(destructuringDeclaration)
val valOrVarKeyword = destructuringDeclaration.valOrVarKeyword
if (valOrVarKeyword != null) {
builder.token(valOrVarKeyword.text)
builder.space()
}
val hasTrailingComma = destructuringDeclaration.trailingComma != null
builder.block(ZERO) {
builder.token("(")
builder.breakOp(Doc.FillMode.UNIFIED, "", expressionBreakIndent)
builder.block(expressionBreakIndent) {
visitEachCommaSeparated(
destructuringDeclaration.entries, hasTrailingComma, wrapInBlock = true)
}
}
builder.token(")")
val initializer = destructuringDeclaration.initializer
if (initializer != null) {
builder.space()
builder.token("=")
if (hasTrailingComma) {
builder.space()
} else {
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
}
builder.block(expressionBreakIndent, !hasTrailingComma) { visit(initializer) }
}
}
/** Example `a: String` which is part of `(a: String, b: String)` */
override fun visitDestructuringDeclarationEntry(
multiDeclarationEntry: KtDestructuringDeclarationEntry
) {
builder.sync(multiDeclarationEntry)
declareOne(
initializer = null,
kind = DeclarationKind.PARAMETER,
modifiers = multiDeclarationEntry.modifierList,
name = multiDeclarationEntry.nameIdentifier?.text ?: fail(),
type = multiDeclarationEntry.typeReference,
valOrVarKeyword = null,
)
}
/** Example `"Hello $world!"` or `"""Hello world!"""` */
override fun visitStringTemplateExpression(expression: KtStringTemplateExpression) {
builder.sync(expression)
builder.token(WhitespaceTombstones.replaceTrailingWhitespaceWithTombstone(expression.text))
}
/** Example `super` in `super.doIt(5)` or `super<Foo>` in `super<Foo>.doIt(5)` */
override fun visitSuperExpression(expression: KtSuperExpression) {
builder.sync(expression)
builder.token("super")
val superTypeQualifier = expression.superTypeQualifier
if (superTypeQualifier != null) {
builder.token("<")
visit(superTypeQualifier)
builder.token(">")
}
visit(expression.labelQualifier)
}
/** Example `<T, S>` */
override fun visitTypeParameterList(list: KtTypeParameterList) {
builder.sync(list)
builder.block(ZERO) {
builder.token("<")
val parameters = list.parameters
if (parameters.isNotEmpty()) {
// Break before args.
builder.breakOp(Doc.FillMode.UNIFIED, "", expressionBreakIndent)
builder.block(expressionBreakIndent) {
visitEachCommaSeparated(list.parameters, list.trailingComma != null, wrapInBlock = true)
}
}
builder.token(">")
}
}
override fun visitTypeParameter(parameter: KtTypeParameter) {
builder.sync(parameter)
visit(parameter.modifierList)
builder.token(parameter.nameIdentifier?.text ?: "")
val extendsBound = parameter.extendsBound
if (extendsBound != null) {
builder.space()
builder.token(":")
builder.space()
visit(extendsBound)
}
}
/** Example `where T : View, T : Listener` */
override fun visitTypeConstraintList(list: KtTypeConstraintList) {
builder.token("where")
builder.space()
builder.sync(list)
visitEachCommaSeparated(list.constraints)
}
/** Example `T : Foo` */
override fun visitTypeConstraint(constraint: KtTypeConstraint) {
builder.sync(constraint)
// TODO(nreid260): What about annotations on the type reference? `where @A T : Int`
visit(constraint.subjectTypeParameterName)
builder.space()
builder.token(":")
builder.space()
visit(constraint.boundTypeReference)
}
/** Example `for (i in items) { ... }` */
override fun visitForExpression(expression: KtForExpression) {
builder.sync(expression)
builder.block(ZERO) {
builder.token("for")
builder.space()
builder.token("(")
visit(expression.loopParameter)
builder.space()
builder.token("in")
builder.block(ZERO) {
builder.breakOp(Doc.FillMode.UNIFIED, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) { visit(expression.loopRange) }
}
builder.token(")")
builder.space()
visit(expression.body)
}
}
/** Example `while (a < b) { ... }` */
override fun visitWhileExpression(expression: KtWhileExpression) {
builder.sync(expression)
emitKeywordWithCondition("while", expression.condition)
builder.space()
visit(expression.body)
}
/** Example `do { ... } while (a < b)` */
override fun visitDoWhileExpression(expression: KtDoWhileExpression) {
builder.sync(expression)
builder.token("do")
builder.space()
if (expression.body != null) {
visit(expression.body)
builder.space()
}
emitKeywordWithCondition("while", expression.condition)
}
/** Example `break` or `break@foo` in a loop */
override fun visitBreakExpression(expression: KtBreakExpression) {
builder.sync(expression)
builder.token("break")
visit(expression.labelQualifier)
}
/** Example `continue` or `continue@foo` in a loop */
override fun visitContinueExpression(expression: KtContinueExpression) {
builder.sync(expression)
builder.token("continue")
visit(expression.labelQualifier)
}
/** Example `f: String`, or `private val n: Int` or `(a: Int, b: String)` (in for-loops) */
override fun visitParameter(parameter: KtParameter) {
builder.sync(parameter)
builder.block(ZERO) {
val destructuringDeclaration = parameter.destructuringDeclaration
val typeReference = parameter.typeReference
if (destructuringDeclaration != null) {
builder.block(ZERO) {
visit(destructuringDeclaration)
if (typeReference != null) {
builder.token(":")
builder.space()
visit(typeReference)
}
}
} else {
declareOne(
kind = DeclarationKind.PARAMETER,
modifiers = parameter.modifierList,
valOrVarKeyword = parameter.valOrVarKeyword?.text,
name = parameter.nameIdentifier?.text,
type = typeReference,
initializer = parameter.defaultValue)
}
}
}
/** Example `String::isNullOrEmpty` */
override fun visitCallableReferenceExpression(expression: KtCallableReferenceExpression) {
builder.sync(expression)
visit(expression.receiverExpression)
// For some reason, expression.receiverExpression doesn't contain the question-mark token in
// case of a nullable type, e.g., in String?::isNullOrEmpty.
// Instead, KtCallableReferenceExpression exposes a method that looks for the QUEST token in
// its children.
if (expression.hasQuestionMarks) {
builder.token("?")
}
builder.block(expressionBreakIndent) {
builder.token("::")
builder.breakOp(Doc.FillMode.INDEPENDENT, "", ZERO)
visit(expression.callableReference)
}
}
override fun visitClassLiteralExpression(expression: KtClassLiteralExpression) {
builder.sync(expression)
val receiverExpression = expression.receiverExpression
if (receiverExpression is KtCallExpression) {
visitCallElement(
receiverExpression.calleeExpression,
receiverExpression.typeArgumentList,
receiverExpression.valueArgumentList,
receiverExpression.lambdaArguments)
} else {
visit(receiverExpression)
}
builder.token("::")
builder.token("class")
}
override fun visitFunctionType(type: KtFunctionType) {
builder.sync(type)
val receiver = type.receiver
if (receiver != null) {
visit(receiver)
builder.token(".")
}
builder.block(expressionBreakIndent) {
val parameterList = type.parameterList
if (parameterList != null) {
visitEachCommaSeparated(
parameterList.parameters,
prefix = "(",
postfix = ")",
hasTrailingComma = parameterList.trailingComma != null,
)
}
}
builder.space()
builder.token("->")
builder.space()
builder.block(expressionBreakIndent) { visit(type.returnTypeReference) }
}
/** Example `a is Int` or `b !is Int` */
override fun visitIsExpression(expression: KtIsExpression) {
builder.sync(expression)
val openGroupBeforeLeft = expression.leftHandSide !is KtQualifiedExpression
if (openGroupBeforeLeft) builder.open(ZERO)
visit(expression.leftHandSide)
if (!openGroupBeforeLeft) builder.open(ZERO)
val parent = expression.parent
if (parent is KtValueArgument ||
parent is KtParenthesizedExpression ||
parent is KtContainerNode) {
builder.breakOp(Doc.FillMode.UNIFIED, " ", expressionBreakIndent)
} else {
builder.space()
}
visit(expression.operationReference)
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) { visit(expression.typeReference) }
builder.close()
}
/** Example `a as Int` or `a as? Int` */
override fun visitBinaryWithTypeRHSExpression(expression: KtBinaryExpressionWithTypeRHS) {
builder.sync(expression)
val openGroupBeforeLeft = expression.left !is KtQualifiedExpression
if (openGroupBeforeLeft) builder.open(ZERO)
visit(expression.left)
if (!openGroupBeforeLeft) builder.open(ZERO)
builder.breakOp(Doc.FillMode.UNIFIED, " ", expressionBreakIndent)
visit(expression.operationReference)
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) { visit(expression.right) }
builder.close()
}
/**
* Example:
* ```
* fun f() {
* val a: Array<Int> = [1, 2, 3]
* }
* ```
*/
override fun visitCollectionLiteralExpression(expression: KtCollectionLiteralExpression) {
builder.sync(expression)
builder.block(expressionBreakIndent) {
visitEachCommaSeparated(
expression.getInnerExpressions(),
expression.trailingComma != null,
prefix = "[",
postfix = "]",
wrapInBlock = true)
}
}
override fun visitTryExpression(expression: KtTryExpression) {
builder.sync(expression)
builder.token("try")
builder.space()
visit(expression.tryBlock)
for (catchClause in expression.catchClauses) {
visit(catchClause)
}
visit(expression.finallyBlock)
}
override fun visitCatchSection(catchClause: KtCatchClause) {
builder.sync(catchClause)
builder.space()
builder.token("catch")
builder.space()
builder.block(ZERO) {
builder.token("(")
builder.block(expressionBreakIndent) {
builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO)
visit(catchClause.catchParameter)
builder.guessToken(",")
}
}
builder.token(")")
builder.space()
visit(catchClause.catchBody)
}
override fun visitFinallySection(finallySection: KtFinallySection) {
builder.sync(finallySection)
builder.space()
builder.token("finally")
builder.space()
visit(finallySection.finalExpression)
}
override fun visitThrowExpression(expression: KtThrowExpression) {
builder.sync(expression)
builder.token("throw")
builder.space()
visit(expression.thrownExpression)
}
/** Example `RED(0xFF0000)` in an enum class */
override fun visitEnumEntry(enumEntry: KtEnumEntry) {
builder.sync(enumEntry)
builder.block(ZERO) {
visit(enumEntry.modifierList)
builder.token(enumEntry.nameIdentifier?.text ?: fail())
enumEntry.initializerList?.initializers?.forEach { visit(it) }
val body = enumEntry.body
if (body != null) {
builder.space()
visitBlockBody(body, true)
}
}
}
/** Example `private typealias TextChangedListener = (string: String) -> Unit` */
override fun visitTypeAlias(typeAlias: KtTypeAlias) {
builder.sync(typeAlias)
builder.block(ZERO) {
visit(typeAlias.modifierList)
builder.token("typealias")
builder.space()
builder.token(typeAlias.nameIdentifier?.text ?: fail())
visit(typeAlias.typeParameterList)
builder.space()
builder.token("=")
builder.breakOp(Doc.FillMode.INDEPENDENT, " ", expressionBreakIndent)
builder.block(expressionBreakIndent) {
visit(typeAlias.getTypeReference())
visit(typeAlias.typeConstraintList)
builder.guessToken(";")
}
builder.forcedBreak()
}
}
/**
* visitElement is called for almost all types of AST nodes. We use it to keep track of whether
* we're currently inside an expression or not.
*
* @throws FormattingError
*/
override fun visitElement(element: PsiElement) {
inExpression.addLast(element is KtExpression || inExpression.peekLast())
val previous = builder.depth()
try {
super.visitElement(element)
} catch (e: FormattingError) {
throw e
} catch (t: Throwable) {
throw FormattingError(builder.diagnostic(Throwables.getStackTraceAsString(t)))
} finally {
inExpression.removeLast()
}
builder.checkClosed(previous)
}
override fun visitKtFile(file: KtFile) {
markForPartialFormat()
var importListEmpty = false
var isFirst = true
for (child in file.children) {
if (child.text.isBlank()) {
importListEmpty = child is KtImportList
continue
}
if (!isFirst && child !is PsiComment && (child !is KtScript || !importListEmpty)) {
builder.blankLineWanted(OpsBuilder.BlankLineWanted.YES)
}
visit(child)
isFirst = false
}
markForPartialFormat()
}
override fun visitScript(script: KtScript) {
markForPartialFormat()
var lastChildHadBlankLineBefore = false
var first = true
for (child in script.blockExpression.children) {
if (child.text.isBlank()) {
continue
}
builder.forcedBreak()
val childGetsBlankLineBefore = child !is KtProperty
if (first) {
builder.blankLineWanted(OpsBuilder.BlankLineWanted.PRESERVE)
} else if (child !is PsiComment &&
(childGetsBlankLineBefore || lastChildHadBlankLineBefore)) {
builder.blankLineWanted(OpsBuilder.BlankLineWanted.YES)
}
visit(child)
builder.guessToken(";")
lastChildHadBlankLineBefore = childGetsBlankLineBefore
first = false
}
markForPartialFormat()
}
private fun inExpression(): Boolean {
return inExpression.peekLast()
}
/**
* markForPartialFormat is used to delineate the smallest areas of code that must be formatted
* together.
*
* When only parts of the code are being formatted, the requested area is expanded until it's
* covered by an area marked by this method.
*/
private fun markForPartialFormat() {
if (!inExpression()) {
builder.markForPartialFormat()
}
}
/**
* Emit a [Doc.Token].
*
* @param token the [String] to wrap in a [Doc.Token]
* @param plusIndentCommentsBefore extra block for comments before this token
*/
private fun OpsBuilder.token(token: String, plusIndentCommentsBefore: Indent = ZERO) {
token(
token,
Doc.Token.RealOrImaginary.REAL,
plusIndentCommentsBefore,
/* breakAndIndentTrailingComment */ Optional.empty())
}
/**
* Opens a new level, emits into it and closes it.
*
* This is a helper method to make it easier to keep track of [OpsBuilder.open] and
* [OpsBuilder.close] calls
*
* @param plusIndent the block level to pass to the block
* @param block a code block to be run in this block level
*/
private inline fun OpsBuilder.block(
plusIndent: Indent,
isEnabled: Boolean = true,
block: () -> Unit
) {
if (isEnabled) {
open(plusIndent)
}
block()
if (isEnabled) {
close()
}
}
/** Helper method to sync the current offset to match any element in the AST */
private fun OpsBuilder.sync(psiElement: PsiElement) {
sync(psiElement.startOffset)
}
/**
* Throws a formatting error
*
* This is used as `expr ?: fail()` to avoid using the !! operator and provide better error
* messages.
*/
private fun fail(message: String = "Unexpected"): Nothing {
throw FormattingError(builder.diagnostic(message))
}
/** Helper function to improve readability */
private fun visit(element: PsiElement?) {
element?.accept(this)
}
/** Emits a key word followed by a condition, e.g. `if (b)` or `while (c < d )` */
private fun emitKeywordWithCondition(keyword: String, condition: KtExpression?) {
if (condition == null) {
builder.token(keyword)
return
}
builder.block(ZERO) {
builder.token(keyword)
builder.space()
builder.token("(")
if (isGoogleStyle) {
builder.block(expressionBreakIndent) {
builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO)
visit(condition)
builder.breakOp(Doc.FillMode.UNIFIED, "", expressionBreakNegativeIndent)
}
} else {
builder.block(ZERO) { visit(condition) }
}
}
builder.token(")")
}
}
| apache-2.0 | 82c62c53227bf481f1a3cbb383ae9289 | 32.781732 | 100 | 0.657876 | 4.801821 | false | false | false | false |
krischik/Fit-Import | JavaLib/src/main/kotlin/com.krischik/fit_import/Ketfit.kt | 1 | 2516 | /********************************************************** {{{1 ***********
* Copyright © 2015 … 2016 "Martin Krischik" «[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/
********************************************************** }}}1 **********/
package com.krischik.fit_import
/**
* <p>
* </p>
*
* <pre>
* Datum ;Zeit ;Dauer ;Watt;Puls;u/min;kcal;km;°
* 02.02.2014;18:42;00:40:00 ;88 ;118 ;48 ;294 ;6 ;-;
* 03.02.2014;18:29;00:40:00 ;88 ;94 ;61 ;294 ;6 ;-;
* </pre>
* @author "Martin Krischik" «[email protected]»
* @version 1.0
* @since 1.0
*/
data class Ketfit(
val start: java.util.Date,
val end: java.util.Date,
val watt: Int,
val puls: Int,
val uMin: Int,
val kCal: Int,
val km: Int,
val ω: Int)
{
/**
* <p>Kettler measures km and GoogleFit uses m</p>
*/
public val meter: Float
get() = km.toFloat() * 1000.0f
/**
* <p>Steps per minute. One cycle is two steps.</p>
*/
public val stepMin: Float
get() = uMin * 2.0f
/*
* <p>Google fit stores the steps for cross trainer.
* First we calculate the total revolutions from the average revolution per minute and the
* the time of session. * We consider one revolution to be one step.
*/
public val steps: Int
get() = (stepMin * durationInMinutes).toInt ()
/**
* <p>Training duration ins minutes</p>
*/
public val durationInMinutes: Float
get () = durationInSeconds / 60.0f
/**
* <p>Training duration ins seconds</p>
*/
public val durationInSeconds: Float
get () = (end.time - start.time).toFloat() / 1000.0f
}
// vim: set nowrap tabstop=8 shiftwidth=4 softtabstop=4 expandtab :
// vim: set textwidth=0 filetype=kotlin foldmethod=marker spell spelllang=en_gb :
| gpl-3.0 | df50aff368d3430f3c959a32add53da3 | 31.558442 | 93 | 0.590746 | 3.481944 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/libanki/template/Tokenizer.kt | 1 | 11188 | /****************************************************************************************
* Copyright (c) 2020 Arthur Milchior <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.libanki.template
import androidx.annotation.VisibleForTesting
import com.ichi2.libanki.template.TemplateError.NoClosingBrackets
import java.util.NoSuchElementException
import kotlin.Throws
/**
* This class encodes template.rs's file creating template.
* Due to the way iterator work in java, it's easier for the class to keep track of the template
*/
class Tokenizer internal constructor(template: String) : Iterator<Tokenizer.Token> {
/**
* The remaining of the string to read.
*/
private var mTemplate: String
/**
* Become true if lexing failed. That is, the string start with {{, but no }} is found.
*/
private var mFailed = false
/**
* Whether we consider <% and %> as handlebar
*/
private val mLegacy: Boolean
override fun hasNext(): Boolean {
return mTemplate.length > 0 && !mFailed
}
/**
* The kind of data we can find in a template and may want to consider for card generation
*/
enum class TokenKind {
/**
* Some text, assumed not to contains {{*}}
*/
TEXT,
/**
* {{Field name}}
*/
REPLACEMENT,
/**
* {{#Field name}}
*/
OPEN_CONDITIONAL,
/**
* {{^Field name}}
*/
OPEN_NEGATED,
/**
* {{/Field name}}
*/
CLOSE_CONDITIONAL
}
/**
* This is equivalent to upstream's template.rs's Token type.
*
*/
@VisibleForTesting
class Token(
val kind: TokenKind,
/**
* If mKind is Text, then this contains the text.
* Otherwise, it contains the content between "{{" and "}}", without the curly braces.
*/
val text: String
) {
override fun toString(): String {
return kind.toString() + "(\"" + text + "\")"
}
override fun equals(other: Any?): Boolean {
if (other !is Token) {
return false
}
val t = other
return kind == t.kind && text == t.text
}
@VisibleForTesting
fun new_to_legacy(): Token {
return Token(
kind,
new_to_legacy(
text
)
)
}
}
/**
* This is similar to template.rs's type IResult<&str, Token>.
* That is, it contains a token that was parsed, and the remaining of the string that must be read.
*/
@VisibleForTesting
internal class IResult(
val token: Token,
/**
* The part of the string that must still be read.
*/
/*
This is a substring of the template. Java deal efficiently with substring by encoding it as original string,
start index and length, so there is no loss in efficiency in using string instead of position.
*/
val remaining: String
) {
override fun toString(): String {
return "($token, \"$remaining\")"
}
override fun equals(other: Any?): Boolean {
if (other !is IResult) {
return false
}
val r = other
return token == r.token && remaining == r.remaining
}
@VisibleForTesting
fun new_to_legacy(): IResult {
return IResult(token.new_to_legacy(), new_to_legacy(remaining))
}
}
/**
* @return The next token.
* @throws TemplateError.NoClosingBrackets with no message if the template is entirely lexed, and with the remaining string otherwise.
*/
@Throws(NoClosingBrackets::class)
override fun next(): Token {
if (mTemplate.length == 0) {
throw NoSuchElementException()
}
val ir = next_token(mTemplate, mLegacy)
if (ir == null) {
// Missing closing }}
mFailed = true
throw NoClosingBrackets(mTemplate)
}
mTemplate = ir.remaining
return ir.token
}
companion object {
/**
* If this text appears at the top of a template (not considering whitespaces and other \s symbols), then the
* template accept legacy handlebars. That is <% foo %> is interpreted similarly as {{ foo }}.
* This is used for compatibility with legacy version of anki.
*
* Same as rslib/src/template's ALT_HANDLEBAR_DIRECTIVE upstream */
@VisibleForTesting
val ALT_HANDLEBAR_DIRECTIVE = "{{=<% %>=}}"
@VisibleForTesting
fun new_to_legacy(template_part: String): String {
return template_part.replace("{{", "<%").replace("}}", "%>")
}
/**
* @param template The part of the template that must still be lexed
* @param legacy whether <% is accepted as a handlebar
* @return The longest prefix without handlebar, or null if it's empty.
*/
@VisibleForTesting
internal fun text_token(template: String, legacy: Boolean): IResult? {
val first_legacy_handlebar = if (legacy) template.indexOf("<%") else -1
val first_new_handlebar = template.indexOf("{{")
val text_size: Int
text_size = if (first_new_handlebar == -1) {
if (first_legacy_handlebar == -1) {
template.length
} else {
first_legacy_handlebar
}
} else {
if (first_legacy_handlebar == -1 || first_new_handlebar < first_legacy_handlebar) {
first_new_handlebar
} else {
first_legacy_handlebar
}
}
return if (text_size == 0) {
null
} else IResult(
Token(
TokenKind.TEXT,
template.substring(0, text_size)
),
template.substring(text_size)
)
}
/**
* classify handle based on leading character
* @param handle The content between {{ and }}
*/
internal fun classify_handle(handle: String): Token {
var start_pos = 0
while (start_pos < handle.length && handle[start_pos] == '{') {
start_pos++
}
val start = handle.substring(start_pos).trim { it <= ' ' }
return if (start.length < 2) {
Token(
TokenKind.REPLACEMENT,
start
)
} else when (start[0]) {
'#' -> Token(
TokenKind.OPEN_CONDITIONAL,
start.substring(1).trim { it <= ' ' }
)
'/' -> Token(
TokenKind.CLOSE_CONDITIONAL,
start.substring(1).trim { it <= ' ' }
)
'^' -> Token(
TokenKind.OPEN_NEGATED,
start.substring(1).trim { it <= ' ' }
)
else -> Token(
TokenKind.REPLACEMENT,
start
)
}
}
/**
* @param template a part of a template to lex
* @param legacy Whether to also consider handlebar starting with <%
* @return The content of handlebar at start of template
*/
@VisibleForTesting
internal fun handlebar_token(template: String, legacy: Boolean): IResult? {
val new_handlebar_token = new_handlebar_token(template)
if (new_handlebar_token != null) {
return new_handlebar_token
}
return if (legacy) {
legacy_handlebar_token(template)
} else null
}
/**
* @param template a part of a template to lex
* @return The content of handlebar at start of template
*/
@VisibleForTesting
internal fun new_handlebar_token(template: String): IResult? {
return handlebar_token(template, "{{", "}}")
}
private fun handlebar_token(template: String, prefix: String, suffix: String): IResult? {
if (!template.startsWith(prefix)) {
return null
}
val end = template.indexOf(suffix)
if (end == -1) {
return null
}
val content = template.substring(prefix.length, end)
val handlebar = classify_handle(content)
return IResult(handlebar, template.substring(end + suffix.length))
}
/**
* @param template a part of a template to lex
* @return The content of handlebar at start of template
*/
@VisibleForTesting
internal fun legacy_handlebar_token(template: String): IResult? {
return handlebar_token(template, "<%", "%>")
}
/**
* @param template The remaining of template to lex
* @param legacy Whether to accept <% as handlebar
* @return The next token, or null at end of string
*/
internal fun next_token(template: String, legacy: Boolean): IResult? {
val t = handlebar_token(template, legacy)
return t ?: text_token(template, legacy)
}
}
/**
* @param template A question or answer template.
*/
init {
@Suppress("NAME_SHADOWING")
var template = template
val trimmed = template.trim { it <= ' ' }
mLegacy = trimmed.startsWith(ALT_HANDLEBAR_DIRECTIVE)
if (mLegacy) {
template = trimmed.substring(ALT_HANDLEBAR_DIRECTIVE.length)
}
mTemplate = template
}
}
| gpl-3.0 | 8f056ab9247c1d9b1f2998c771c61269 | 33.9625 | 138 | 0.502503 | 5.090082 | false | false | false | false |
Aidanvii7/Toolbox | common/src/main/java/com/aidanvii/toolbox/TypeAliases.kt | 1 | 288 | package com.aidanvii.toolbox
typealias Action = () -> Unit
typealias Consumer<T> = (T) -> Unit
typealias Provider<T> = () -> T
typealias ExtensionAction<T> = T.() -> Unit
typealias ExtensionConsumer<T, I> = T.(I) -> Unit
val consumerStub: Consumer<Any> = {}
val actionStub: Action = {} | apache-2.0 | 2cd46ef840d3c8dc1b772b073f557ca0 | 25.272727 | 49 | 0.677083 | 3.388235 | false | false | false | false |
wleroux/fracturedskies | src/main/kotlin/com/fracturedskies/task/TaskExecutionSystem.kt | 1 | 1494 | package com.fracturedskies.task
import com.fracturedskies.api.*
import com.fracturedskies.api.task.BehaviorStatus
import com.fracturedskies.api.task.BehaviorStatus.*
import com.fracturedskies.engine.Id
import com.fracturedskies.engine.api.Update
import javax.enterprise.event.*
import javax.inject.*
@Singleton
class TaskExecutionSystem {
@Inject
lateinit var world: World
@Inject
lateinit var events: Event<Any>
private val behavior = mutableMapOf<Id, Iterator<BehaviorStatus>>()
fun onColonistSelectedTask(@Observes message: ColonistTaskSelected) {
val colonist = world.colonists[message.colonistId]!!
if (message.taskId == null) {
behavior.remove(message.colonistId)
} else {
val selectedTask = world.tasks[message.taskId]!!
behavior[colonist.id] = selectedTask.details.behavior.execute(world, colonist).iterator()
}
}
fun onUpdate(@Observes update: Update) {
behavior.entries.map { (colonistId, behavior) ->
if (behavior.hasNext()) {
val taskId = world.colonists[colonistId]!!.assignedTask
val status = behavior.next()
when (status) {
SUCCESS -> {
if (taskId != null) {
world.completeTask(colonistId, taskId, update.cause)
}
}
FAILURE -> {
if (taskId != null) {
world.rejectTask(colonistId, taskId, update.cause)
}
}
RUNNING -> {
}
}
}
}
}
}
| unlicense | 4954c5351211a0d01b7b400cd8ed4c9e | 26.163636 | 95 | 0.640562 | 4.317919 | false | false | false | false |
pdvrieze/ProcessManager | PE-common/src/javaMain/kotlin/nl/adaptivity/xml/WritableCompactFragment.kt | 1 | 2345 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.xml
import nl.adaptivity.io.Writable
import nl.adaptivity.xmlutil.IterableNamespaceContext
import nl.adaptivity.xmlutil.Namespace
import nl.adaptivity.xmlutil.XmlWriter
import nl.adaptivity.xmlutil.util.CompactFragment
import nl.adaptivity.xmlutil.util.ICompactFragment
import nl.adaptivity.xmlutil.util.XMLFragmentStreamReader
import java.io.IOException
import java.io.Writer
/**
* Created by pdvrieze on 27/11/15.
*/
actual class WritableCompactFragment private actual constructor(
private val data: ICompactFragment,
dummy: Boolean
) : ICompactFragment, Writable {
override val isEmpty: Boolean
get() = data.isEmpty
override val namespaces: IterableNamespaceContext
get() = data.namespaces
override val content: CharArray
get() = data.content
override val contentString: String
get() = data.contentString
actual constructor(namespaces: Iterable<Namespace>, content: CharArray) : this(
CompactFragment(namespaces, content),
false
)
actual constructor(string: String) : this(CompactFragment(string), false) {}
actual constructor(orig: ICompactFragment) : this(CompactFragment(orig.namespaces, orig.contentString), false) {}
override fun getXmlReader() = XMLFragmentStreamReader.from(this)
@Throws(IOException::class)
override fun writeTo(destination: Writer) {
destination.write(content)
}
override fun serialize(out: XmlWriter) {
data.serialize(out)
}
}
| lgpl-3.0 | 6759d8bdc9361189e26194dc08439715 | 32.5 | 117 | 0.697655 | 4.895616 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | fluxc/src/main/java/org/wordpress/android/fluxc/store/stats/time/ClicksStore.kt | 2 | 2338 | package org.wordpress.android.fluxc.store.stats.time
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.stats.LimitMode.Top
import org.wordpress.android.fluxc.model.stats.time.TimeStatsMapper
import org.wordpress.android.fluxc.network.rest.wpcom.stats.time.ClicksRestClient
import org.wordpress.android.fluxc.network.utils.StatsGranularity
import org.wordpress.android.fluxc.persistence.TimeStatsSqlUtils.ClicksSqlUtils
import org.wordpress.android.fluxc.store.StatsStore.OnStatsFetched
import org.wordpress.android.fluxc.store.StatsStore.StatsError
import org.wordpress.android.fluxc.store.StatsStore.StatsErrorType.INVALID_RESPONSE
import org.wordpress.android.fluxc.tools.CoroutineEngine
import org.wordpress.android.util.AppLog.T.STATS
import java.util.Date
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ClicksStore
@Inject constructor(
private val restClient: ClicksRestClient,
private val sqlUtils: ClicksSqlUtils,
private val timeStatsMapper: TimeStatsMapper,
private val coroutineEngine: CoroutineEngine
) {
suspend fun fetchClicks(
site: SiteModel,
granularity: StatsGranularity,
limitMode: Top,
date: Date,
forced: Boolean = false
) = coroutineEngine.withDefaultContext(STATS, this, "fetchClicks") {
if (!forced && sqlUtils.hasFreshRequest(site, granularity, date, limitMode.limit)) {
return@withDefaultContext OnStatsFetched(getClicks(site, granularity, limitMode, date), cached = true)
}
val payload = restClient.fetchClicks(site, granularity, date, limitMode.limit + 1, forced)
return@withDefaultContext when {
payload.isError -> OnStatsFetched(payload.error)
payload.response != null -> {
sqlUtils.insert(site, payload.response, granularity, date, limitMode.limit)
OnStatsFetched(timeStatsMapper.map(payload.response, limitMode))
}
else -> OnStatsFetched(StatsError(INVALID_RESPONSE))
}
}
fun getClicks(site: SiteModel, period: StatsGranularity, limitMode: Top, date: Date) =
coroutineEngine.run(STATS, this, "getClicks") {
sqlUtils.select(site, period, date)?.let { timeStatsMapper.map(it, limitMode) }
}
}
| gpl-2.0 | b757cdec8f8c1385ac3b9d916ad38772 | 44.843137 | 114 | 0.735672 | 4.478927 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/handler/login/LoginEncryptionResponseHandler.kt | 1 | 5747 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.vanilla.packet.handler.login
import com.google.gson.Gson
import com.google.gson.JsonObject
import org.lanternpowered.api.cause.causeOf
import org.lanternpowered.api.event.EventManager
import org.lanternpowered.api.text.translatableTextOf
import org.lanternpowered.server.event.LanternEventFactory
import org.lanternpowered.server.network.NetworkContext
import org.lanternpowered.server.network.NetworkSession
import org.lanternpowered.server.network.WrappedServerSideConnection
import org.lanternpowered.server.network.packet.PacketHandler
import org.lanternpowered.server.network.pipeline.PacketEncryptionHandler
import org.lanternpowered.server.network.vanilla.packet.type.login.LoginEncryptionResponsePacket
import org.lanternpowered.server.network.vanilla.packet.type.login.LoginFinishPacket
import org.lanternpowered.server.profile.LanternGameProfile
import org.lanternpowered.server.profile.LanternProfileProperty
import org.lanternpowered.server.util.EncryptionHelper
import org.lanternpowered.server.util.InetAddressHelper
import org.lanternpowered.server.util.UUIDHelper
import org.lanternpowered.server.util.future.thenAsync
import org.lanternpowered.server.util.gson.fromJson
import java.io.UnsupportedEncodingException
import java.net.URLEncoder
import java.util.concurrent.CompletableFuture
import javax.crypto.spec.SecretKeySpec
object LoginEncryptionResponseHandler : PacketHandler<LoginEncryptionResponsePacket> {
private const val authBaseUrl = "https://sessionserver.mojang.com/session/minecraft/hasJoined"
private val gson = Gson()
override fun handle(ctx: NetworkContext, packet: LoginEncryptionResponsePacket) {
val session = ctx.session
val keyPair = session.server.keyPair
val authData: LoginAuthData? = ctx.channel.attr(LoginStartHandler.AUTH_DATA).getAndSet(null)
checkNotNull(authData) { "No login auth data." }
val decryptedVerifyToken = EncryptionHelper.decryptRsa(keyPair, packet.verifyToken)
check(!(decryptedVerifyToken contentEquals authData.verifyToken)) { "Invalid verify token." }
val decryptedSharedSecret = EncryptionHelper.decryptRsa(keyPair, packet.sharedSecret)
val serverId = EncryptionHelper.generateServerId(decryptedSharedSecret, keyPair.public)
val preventProxiesIp = this.preventProxiesIp(ctx.session)
val secretKey = SecretKeySpec(decryptedSharedSecret, "AES")
val connection = WrappedServerSideConnection(ctx.session)
this.requestAuth(ctx, authData.username, serverId, preventProxiesIp)
.thenAsync(session.server.syncExecutor) { profile ->
val cause = causeOf(session, profile)
val originalMessage = translatableTextOf("multiplayer.disconnect.not_allowed_to_join")
val event = LanternEventFactory.createServerSideConnectionEventAuth(
cause, originalMessage, originalMessage, connection, false)
EventManager.post(event)
if (event.isCancelled) {
session.close(event.message)
null
} else profile
}
.thenAsync(ctx.channel.eventLoop()) { profile ->
if (profile == null)
return@thenAsync
ctx.channel.pipeline().replace(NetworkSession.ENCRYPTION, NetworkSession.ENCRYPTION,
PacketEncryptionHandler(secretKey))
session.packetReceived(LoginFinishPacket(profile))
}
}
private fun preventProxiesIp(session: NetworkSession): String? {
if (!session.server.config.server.preventProxyConnections)
return null
val address = session.address.address
// Ignore local addresses, they will always fail
if (InetAddressHelper.isLocalAddress(address))
return null
return try {
URLEncoder.encode(address.hostAddress, Charsets.UTF_8)
} catch (e: UnsupportedEncodingException) {
throw IllegalStateException("Failed to encode the ip address to prevent proxies.", e)
}
}
private fun requestAuth(
context: NetworkContext, username: String, serverId: String, preventProxiesIp: String?
): CompletableFuture<LanternGameProfile> {
var url = "$authBaseUrl?username=$username&serverId=$serverId"
if (preventProxiesIp != null)
url += "?ip=$preventProxiesIp"
return context.server.httpClient.get(url, context.channel.eventLoop()).thenApply { response ->
if (response.body.isEmpty())
throw IllegalStateException("Invalid username or session id.")
val json = try {
gson.fromJson<JsonObject>(response.body)
} catch (e: Exception) {
throw IllegalStateException("Username $username failed to authenticate.")
}
val name = json["name"].asString
val id = json["id"].asString
val uniqueId = UUIDHelper.parseFlatStringOrNull(id) ?: error("Received an invalid uuid: $id")
val properties = LanternProfileProperty.createPropertiesMapFromJson(
json.getAsJsonArray("properties"))
LanternGameProfile(uniqueId, name, properties)
}
}
}
| mit | 3afeea6f8478c4e0e0284d913a1c061c | 47.294118 | 106 | 0.701583 | 5.050088 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/pipeline/PacketFramingHandler.kt | 1 | 3492 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
/*
* Copyright (c) 2011-2014 Glowstone - Tad Hardesty
* Copyright (c) 2010-2011 Lightstone - Graham Edgecombe
*
* 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 org.lanternpowered.server.network.pipeline
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.ByteToMessageCodec
import io.netty.handler.codec.DecoderException
import org.lanternpowered.server.network.buffer.LanternByteBuffer
class PacketFramingHandler : ByteToMessageCodec<ByteBuf>() {
override fun encode(ctx: ChannelHandlerContext, buf: ByteBuf, output: ByteBuf) {
LanternByteBuffer.writeVarInt(output, buf.readableBytes())
output.writeBytes(buf)
}
override fun decode(ctx: ChannelHandlerContext, buf: ByteBuf, output: MutableList<Any>) {
while (true) {
val length = readableMessage(buf)
if (length == -1)
break
output.add(buf.readRetainedSlice(length))
}
}
/**
* Reads the length and checks if the message can be read in one call.
*
* @param buf The byte buffer
* @return The message length, or -1 if it's not possible to read a message
*/
private fun readableMessage(buf: ByteBuf): Int {
val index = buf.readerIndex()
var bits = 0
var length = 0
var b: Byte
do {
// The variable integer is not complete, try again next time
if (buf.readableBytes() < 1) {
buf.readerIndex(index)
return -1
}
b = buf.readByte()
length = length or (b.toInt() and 0x7F shl bits)
bits += 7
if (bits > 35)
throw DecoderException("Variable length is too long!")
} while (b.toInt() and 0x80 != 0)
if (length < 0)
throw DecoderException("Message length cannot be negative: $length")
// Not all the message bytes are available yet, try again later
if (buf.readableBytes() < length) {
buf.readerIndex(index)
return -1
}
return length
}
}
| mit | ab56ee5a8ab633e1f8b7160e168c10b0 | 38.235955 | 93 | 0.668385 | 4.386935 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/service/pagination/LanternPaginationList.kt | 1 | 2986 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.service.pagination
import org.lanternpowered.api.Lantern
import org.lanternpowered.api.audience.Audience
import org.lanternpowered.api.entity.player.Player
import org.lanternpowered.api.text.Text
import org.lanternpowered.api.text.format.NamedTextColor
import org.lanternpowered.api.util.optional.asOptional
import org.lanternpowered.api.util.optional.orNull
import org.lanternpowered.server.util.reference.asProvider
import org.spongepowered.api.command.exception.CommandException
import org.spongepowered.api.service.pagination.PaginationList
import java.lang.ref.WeakReference
import java.util.Optional
internal class LanternPaginationList(
private val service: LanternPaginationService,
private val contents: Iterable<Text>,
private val title: Text?,
private val header: Text?,
private val footer: Text?,
private val paginationSpacer: Text,
private val linesPerPage: Int
) : PaginationList {
override fun getContents(): Iterable<Text> = this.contents
override fun getTitle(): Optional<Text> = this.title.asOptional()
override fun getHeader(): Optional<Text> = this.header.asOptional()
override fun getFooter(): Optional<Text> = this.footer.asOptional()
override fun getPadding(): Text = this.paginationSpacer
override fun getLinesPerPage(): Int = this.linesPerPage
override fun sendTo(receiver: Audience, page: Int) {
val calculator = PaginationCalculator(this.linesPerPage)
val counts = this.contents
.map { input -> input to calculator.getLines(input) }
var title: Text? = this.title
if (title != null)
title = calculator.center(title, this.paginationSpacer)
val source: () -> Audience? = if (receiver is Player) {
val uniqueId = receiver.uniqueId
{ Lantern.server.getPlayer(uniqueId).orNull() }
} else {
WeakReference(receiver).asProvider()
}
val pagination = if (this.contents is List<*>) {
ListPagination(source, calculator, counts, title,
this.header, this.footer, this.paginationSpacer)
} else {
IterablePagination(source, calculator, counts, title,
this.header, this.footer, this.paginationSpacer)
}
this.service.getPaginationState(receiver, true)!!.put(pagination)
try {
pagination.specificPage(page)
} catch (e: CommandException) {
val text = e.text
if (text != null)
receiver.sendMessage(text.color(NamedTextColor.RED))
}
}
}
| mit | 39541778a845a5a489c228d3efdac8a4 | 38.813333 | 73 | 0.683858 | 4.47006 | false | false | false | false |
mercadopago/px-android | px-checkout/src/main/java/com/mercadopago/android/px/internal/features/payment_result/remedies/RemediesModel.kt | 1 | 1605 | package com.mercadopago.android.px.internal.features.payment_result.remedies
import android.os.Parcel
import android.os.Parcelable
import com.mercadopago.android.px.internal.features.payment_result.remedies.view.RetryPaymentFragment
import com.mercadopago.android.px.internal.features.payment_result.remedies.view.HighRiskRemedy
import com.mercadopago.android.px.internal.viewmodel.PaymentResultType
internal data class RemediesModel(val title: String, val retryPayment: RetryPaymentFragment.Model?,
val highRisk: HighRiskRemedy.Model?, val trackingData: Map<String, String>?) : Parcelable {
constructor(parcel: Parcel) : this(parcel.readString()!!,
parcel.readParcelable(RetryPaymentFragment.Model::class.java.classLoader),
parcel.readParcelable(HighRiskRemedy.Model::class.java.classLoader),
HashMap()) {
parcel.readMap(trackingData, String::class.java.classLoader)
}
fun hasRemedies() = retryPayment != null || highRisk != null
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(title)
parcel.writeParcelable(retryPayment, flags)
parcel.writeParcelable(highRisk, flags)
parcel.writeMap(trackingData)
}
override fun describeContents() = 0
companion object {
@JvmField val DECORATOR = PaymentResultType.PENDING
@JvmField val CREATOR = object : Parcelable.Creator<RemediesModel> {
override fun createFromParcel(parcel: Parcel) = RemediesModel(parcel)
override fun newArray(size: Int) = arrayOfNulls<RemediesModel?>(size)
}
}
} | mit | 79835d9427571a67be374979b31cbcd9 | 43.611111 | 101 | 0.74081 | 4.470752 | false | false | false | false |
aucd29/common | library/src/main/java/net/sarangnamu/common/BkLayoutParams.kt | 1 | 5044 | /*
* Copyright 2016 Burke Choi All rights reserved.
* http://www.sarangnamu.net
*
* 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("NOTHING_TO_INLINE", "unused")
package net.sarangnamu.common
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.RelativeLayout
/**
* Created by <a href="mailto:[email protected]">Burke Choi</a> on 2017. 9. 28.. <p/>
*/
// LinearLayout
inline fun LinearLayout.lp(w: Int, h: Int) {
layoutParams = LinearLayout.LayoutParams(w, h)
}
inline fun LinearLayout.lpmm() {
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
}
inline fun LinearLayout.lpwm() {
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)
}
inline fun LinearLayout.lpmw() {
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
}
inline fun LinearLayout.lpww() {
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
}
// RelativeLayout
inline fun RelativeLayout.lp(w: Int, h: Int) {
layoutParams = RelativeLayout.LayoutParams(w, h)
}
inline fun RelativeLayout.lpmm() {
layoutParams = RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)
}
inline fun RelativeLayout.lpwm() {
layoutParams = RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT)
}
inline fun RelativeLayout.lpmw() {
layoutParams = RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
}
inline fun RelativeLayout.lpww() {
layoutParams = RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
}
// FrameLayout
inline fun FrameLayout.lp(w: Int, h: Int) {
layoutParams = FrameLayout.LayoutParams(w, h)
}
inline fun FrameLayout.lpmm() {
layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
}
inline fun FrameLayout.lpwm() {
layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT)
}
inline fun FrameLayout.lpmw() {
layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)
}
inline fun FrameLayout.lpww() {
layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT)
}
// ViewGroup
inline fun ViewGroup.lp(w: Int, h: Int) {
layoutParams = ViewGroup.LayoutParams(w, h)
}
inline fun ViewGroup.lpmm() {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
inline fun ViewGroup.lpwm() {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
inline fun ViewGroup.lpmw() {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
inline fun ViewGroup.lpww() {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
// Window
inline fun Window.lp(w: Int, h: Int) {
val lp = attributes
lp.width = w
lp.height = h
attributes = lp
}
inline fun Window.lpmm() {
attributes = WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT)
}
inline fun Window.lpwm() {
attributes = WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.MATCH_PARENT)
}
inline fun Window.lpmw() {
attributes = WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT)
}
inline fun Window.lpww() {
attributes = WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT)
} | apache-2.0 | af6ace4aa1d9082fca7dd77280bc66e4 | 29.762195 | 95 | 0.737906 | 4.420684 | false | false | false | false |
ageery/kwicket | kwicket-wicket-extensions/src/main/kotlin/org/kwicket/wicket/extensions/markup/html/form/KDateTextField.kt | 1 | 1868 | package org.kwicket.wicket.extensions.markup.html.form
import org.apache.wicket.behavior.Behavior
import org.apache.wicket.extensions.markup.html.form.DateTextField
import org.apache.wicket.model.IModel
import org.kwicket.component.init
import org.kwicket.model.toDateModel
import java.time.LocalDate
/**
* [DateTextField] with named parameters and a [LocalDate] model.
*
* @param id Wicket component id
* @param model backing model for the component
* @param pattern the date pattern to use for parsing and rendering dates from and to strings
* @param outputMarkupId whether to output an id in the markup for the component
* @param outputMarkupPlaceholderTag whether to output a placeholder tag for the component if it is not initially
* visible
* @param visible whether the component is visible
* @param enabled whether the component is enabled
* @param escapeModelStrings whether the value of the model should have HTML tags escaped
* @param renderBodyOnly whether the tag containing the component should not be rendered
* @param behaviors list of [Behavior]s to add to the component
*/
open class KDateTextField(
id: String,
model: IModel<LocalDate?>,
pattern: String,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
escapeModelStrings: Boolean? = null,
renderBodyOnly: Boolean? = null,
behaviors: List<Behavior>? = null
) : DateTextField(id, toDateModel(model), pattern) {
init {
init(
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
escapeModelStrings = escapeModelStrings,
renderBodyOnly = renderBodyOnly,
behaviors = behaviors
)
}
} | apache-2.0 | 9131ebeffda6d71b85c5b98160a48dc4 | 36.38 | 113 | 0.727516 | 4.789744 | false | false | false | false |
ykrank/S1-Next | app/src/main/java/me/ykrank/s1next/view/fragment/PmGroupsFragment.kt | 1 | 3032 | package me.ykrank.s1next.view.fragment
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import android.view.View
import com.github.ykrank.androidtools.util.MathUtil
import com.github.ykrank.androidtools.widget.RxBus
import io.reactivex.Single
import me.ykrank.s1next.App
import me.ykrank.s1next.R
import me.ykrank.s1next.data.api.model.PmGroup
import me.ykrank.s1next.data.api.model.collection.PmGroups
import me.ykrank.s1next.data.api.model.wrapper.BaseDataWrapper
import me.ykrank.s1next.view.adapter.BaseRecyclerViewAdapter
import me.ykrank.s1next.view.adapter.PmGroupsRecyclerViewAdapter
import me.ykrank.s1next.view.event.NoticeRefreshEvent
import java.util.*
import javax.inject.Inject
class PmGroupsFragment : BaseLoadMoreRecycleViewFragment<BaseDataWrapper<PmGroups>>() {
private lateinit var mRecyclerAdapter: PmGroupsRecyclerViewAdapter
@Inject
internal lateinit var mRxBus: RxBus
override val recyclerViewAdapter: BaseRecyclerViewAdapter
get() = mRecyclerAdapter
override val isCardViewContainer: Boolean
get() = true
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
App.appComponent.inject(this)
super.onViewCreated(view, savedInstanceState)
leavePageMsg("PmGroupsFragment")
activity?.setTitle(R.string.pms)
val recyclerView = recyclerView
recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
mRecyclerAdapter = PmGroupsRecyclerViewAdapter(activity)
recyclerView.adapter = mRecyclerAdapter
}
override fun getPageSourceObservable(pageNum: Int): Single<BaseDataWrapper<PmGroups>> {
return mS1Service.getPmGroups(pageNum)
}
override fun onNext(data: BaseDataWrapper<PmGroups>) {
super.onNext(data)
val pmGroups = data.data
if (pmGroups.pmGroupList != null) {
mRecyclerAdapter.diffNewDataSet(pmGroups.pmGroupList!!, false)
// update total page
setTotalPages(MathUtil.divide(pmGroups.total, pmGroups.pmPerPage))
}
if (pageNum == 1) {
mRxBus.post(NoticeRefreshEvent::class.java, NoticeRefreshEvent(data.data.hasNew(), null))
}
}
override fun appendNewData(oldData: BaseDataWrapper<PmGroups>?, newData: BaseDataWrapper<PmGroups>): BaseDataWrapper<PmGroups> {
if (oldData != null) {
val oldPmGroups = oldData.data.pmGroupList
var newPmGroups: MutableList<PmGroup>? = newData.data.pmGroupList
if (newPmGroups == null) {
newPmGroups = ArrayList()
newData.data.pmGroupList = newPmGroups
}
if (oldPmGroups != null) {
newPmGroups.addAll(0, oldPmGroups)
}
}
return newData
}
companion object {
val TAG = PmGroupsFragment::class.java.name
fun newInstance(): PmGroupsFragment {
return PmGroupsFragment()
}
}
}
| apache-2.0 | ecddb75e8a50ba354dcc0c7efd05a726 | 34.255814 | 132 | 0.703826 | 4.614916 | false | false | false | false |
FHannes/intellij-community | python/src/com/jetbrains/python/breadcrumbs/PyBreadcrumbsInfoProvider.kt | 6 | 7449 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.breadcrumbs
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.impl.source.tree.LeafElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.xml.breadcrumbs.BreadcrumbsInfoProvider
import com.jetbrains.python.PyTokenTypes
import com.jetbrains.python.PythonLanguage
import com.jetbrains.python.psi.*
class PyBreadcrumbsInfoProvider : BreadcrumbsInfoProvider() {
companion object {
private val LANGUAGES = arrayOf(PythonLanguage.getInstance())
private val HELPERS = listOf<Helper<*>>(
LambdaHelper,
SimpleHelper(PyTryPart::class.java, "try"),
ExceptHelper,
SimpleHelper(PyFinallyPart::class.java, "finally"),
SimpleHelper(PyElsePart::class.java, "else"),
IfHelper,
ForHelper,
WhileHelper,
WithHelper,
ClassHelper,
FunctionHelper,
KeyValueHelper
)
}
override fun getLanguages() = LANGUAGES
override fun acceptElement(e: PsiElement) = getHelper(e) != null
override fun getParent(e: PsiElement): PsiElement? {
val default = e.parent
val currentOffset = currentOffset(e) ?: return default
if (!isElementToMoveBackward(e, currentOffset)) return default
val nonWhiteSpace = moveBackward(e, currentOffset) ?: return default
val psiFile = e.containingFile ?: return default
val document = PsiDocumentManager.getInstance(e.project).getDocument(psiFile) ?: return default
val sameLine = document.getLineNumber(nonWhiteSpace.textOffset) == document.getLineNumber(currentOffset)
return if (sameLine) nonWhiteSpace.parent else default
}
override fun getElementInfo(e: PsiElement) = getHelper(e)!!.elementInfo(e as PyElement)
override fun getElementTooltip(e: PsiElement) = getHelper(e)!!.elementTooltip(e as PyElement)
private fun getHelper(e: PsiElement): Helper<in PyElement>? {
if (e !is PyElement) return null
@Suppress("UNCHECKED_CAST")
return HELPERS.firstOrNull { it.type.isInstance(e) && (it as Helper<in PyElement>).accepts(e) } as Helper<in PyElement>?
}
private fun currentOffset(e: PsiElement): Int? {
val virtualFile = e.containingFile?.virtualFile ?: return null
val selectedEditor = FileEditorManager.getInstance(e.project).getSelectedEditor(virtualFile) as? TextEditor ?: return null
return selectedEditor.editor.caretModel.offset
}
private fun isElementToMoveBackward(e: PsiElement, currentOffset: Int): Boolean {
if (e is PsiWhiteSpace) return true
if (e !is LeafElement || e.startOffset < currentOffset) return false
val elementType = e.elementType
return elementType == PyTokenTypes.COMMA || elementType in PyTokenTypes.CLOSE_BRACES
}
private fun moveBackward(e: PsiElement, currentOffset: Int): PsiElement? {
var result = PsiTreeUtil.prevLeaf(e)
while (result != null && isElementToMoveBackward(result, currentOffset)) {
result = PsiTreeUtil.prevLeaf(result)
}
return result
}
private abstract class Helper<T : PyElement>(val type: Class<T>) {
abstract fun accepts(e: T): Boolean
abstract fun elementInfo(e: T): String
abstract fun elementTooltip(e: T): String
}
private abstract class AbstractHelper<T : PyElement>(type: Class<T>) : Helper<T>(type) {
override fun accepts(e: T): Boolean = true
override fun elementInfo(e: T): String = getTruncatedPresentation(e, 16)
override fun elementTooltip(e: T): String = getTruncatedPresentation(e, 96)
abstract fun getPresentation(e: T): String
private fun getTruncatedPresentation(e: T, maxLength: Int) = StringUtil.shortenTextWithEllipsis(getPresentation(e), maxLength, 0, true)
}
private class SimpleHelper<T : PyElement>(type: Class<T>, val representation: String) : AbstractHelper<T>(type) {
override fun getPresentation(e: T) = representation
}
private object LambdaHelper : AbstractHelper<PyLambdaExpression>(PyLambdaExpression::class.java) {
override fun getPresentation(e: PyLambdaExpression) = "lambda ${e.parameterList.getPresentableText(false)}"
}
private object ExceptHelper : AbstractHelper<PyExceptPart>(PyExceptPart::class.java) {
override fun getPresentation(e: PyExceptPart): String {
val exceptClass = e.exceptClass ?: return "except"
val target = e.target ?: return "except ${exceptClass.text}"
return "except ${exceptClass.text} as ${target.text}"
}
}
private object IfHelper : AbstractHelper<PyIfPart>(PyIfPart::class.java) {
override fun getPresentation(e: PyIfPart): String {
val prefix = if (e.isElif) "elif" else "if"
val condition = e.condition ?: return prefix
return "$prefix ${condition.text}"
}
}
private object ForHelper : AbstractHelper<PyForPart>(PyForPart::class.java) {
override fun getPresentation(e: PyForPart): String {
val parent = e.parent
val prefix = if (parent is PyForStatement && parent.isAsync) "async for" else "for"
val target = e.target ?: return prefix
val source = e.source ?: return prefix
return "$prefix ${target.text} in ${source.text}"
}
}
private object WhileHelper : AbstractHelper<PyWhilePart>(PyWhilePart::class.java) {
override fun getPresentation(e: PyWhilePart): String {
val condition = e.condition ?: return "while"
return "while ${condition.text}"
}
}
private object WithHelper : AbstractHelper<PyWithStatement>(PyWithStatement::class.java) {
override fun getPresentation(e: PyWithStatement): String {
val getItemPresentation = fun(item: PyWithItem): String? {
val expression = item.expression ?: return null
val target = item.target ?: return expression.text
return "${expression.text} as ${target.text}"
}
val prefix = if (e.isAsync) "async with " else "with "
return e.withItems
.orEmpty()
.asSequence()
.map(getItemPresentation)
.filterNotNull()
.joinToString(prefix = prefix)
}
}
private object ClassHelper : AbstractHelper<PyClass>(PyClass::class.java) {
override fun getPresentation(e: PyClass) = e.name ?: "class"
}
private object FunctionHelper : AbstractHelper<PyFunction>(PyFunction::class.java) {
override fun getPresentation(e: PyFunction): String {
val prefix = if (e.isAsync) "async " else ""
val name = e.name ?: return "function"
return "$prefix$name()"
}
}
private object KeyValueHelper : AbstractHelper<PyKeyValueExpression>(PyKeyValueExpression::class.java) {
override fun getPresentation(e: PyKeyValueExpression): String = e.key.text ?: "key"
}
}
| apache-2.0 | 79947e1108f6a8774278fef16c7741bd | 36.059701 | 139 | 0.718486 | 4.335856 | false | false | false | false |
timusus/Shuttle | app/src/main/java/com/simplecity/amp_library/ui/dialog/ChangelogDialog.kt | 1 | 3122 | package com.simplecity.amp_library.ui.dialog
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v4.app.FragmentManager
import android.support.v4.content.ContextCompat
import android.view.LayoutInflater
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.CheckBox
import android.widget.ProgressBar
import com.afollestad.aesthetic.Aesthetic
import com.afollestad.materialdialogs.MaterialDialog
import com.simplecity.amp_library.R
import com.simplecity.amp_library.utils.SettingsManager
import com.simplecity.amp_library.utils.ViewUtils
import dagger.android.support.AndroidSupportInjection
import javax.inject.Inject
class ChangelogDialog : DialogFragment() {
@Inject lateinit var settingsManager: SettingsManager
override fun onAttach(context: Context?) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
@SuppressLint("InflateParams")
val customView = LayoutInflater.from(context).inflate(R.layout.dialog_changelog, null)
val webView = customView.findViewById<WebView>(R.id.webView)
webView.setBackgroundColor(ContextCompat.getColor(context!!, android.R.color.transparent))
val checkBox = customView.findViewById<CheckBox>(R.id.checkbox)
checkBox.isChecked = settingsManager.showChangelogOnLaunch
checkBox.setOnCheckedChangeListener { buttonView, isChecked -> settingsManager.showChangelogOnLaunch = isChecked }
val progressBar = customView.findViewById<ProgressBar>(R.id.progress)
webView.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
ViewUtils.fadeOut(progressBar) { ViewUtils.fadeIn(webView, null) }
}
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
if (intent.resolveActivity(context!!.packageManager) != null) {
context?.startActivity(intent)
return true
}
return false
}
}
Aesthetic.get(context)
.isDark
.take(1)
.subscribe { isDark -> webView.loadUrl(if (isDark) "file:///android_asset/web/info_dark.html" else "file:///android_asset/web/info.html") }
return MaterialDialog.Builder(context!!)
.title(R.string.pref_title_changelog)
.customView(customView, false)
.negativeText(R.string.close)
.build()
}
fun show(fragmentManager: FragmentManager) {
show(fragmentManager, TAG)
}
companion object {
private const val TAG = "ChangelogDialog"
fun newInstance() = ChangelogDialog()
}
} | gpl-3.0 | c6773959536c9009ae67cec22556036d | 35.741176 | 151 | 0.699552 | 4.795699 | false | false | false | false |
thm-projects/arsnova-backend | gateway/src/main/kotlin/de/thm/arsnova/service/httpgateway/service/RoomService.kt | 1 | 2406 | package de.thm.arsnova.service.httpgateway.service
import de.thm.arsnova.service.httpgateway.config.HttpGatewayProperties
import de.thm.arsnova.service.httpgateway.model.Room
import org.slf4j.LoggerFactory
import org.springframework.core.ParameterizedTypeReference
import org.springframework.stereotype.Service
import org.springframework.web.reactive.function.client.WebClient
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import java.util.Optional
@Service
class RoomService(
private val webClient: WebClient,
private val httpGatewayProperties: HttpGatewayProperties
) {
private val logger = LoggerFactory.getLogger(javaClass)
fun get(roomId: String): Mono<Room> {
val url = "${httpGatewayProperties.httpClient.core}/room/$roomId"
logger.trace("Querying core for room with url: {}", url)
return webClient.get().uri(url)
.retrieve().bodyToMono(Room::class.java).cache()
.checkpoint("Request failed in ${this::class.simpleName}::get(roomId).")
.onErrorResume { exception ->
logger.debug("Error on getting room with id: {}", roomId, exception)
Mono.empty()
}
}
fun get(roomIds: List<String>): Flux<Optional<Room>> {
val path = "${httpGatewayProperties.httpClient.core}/room/"
val url = "$path?ids=${roomIds.joinToString(",")}&skipMissing=false"
logger.trace("Querying core for room with url: {}", url)
val typeRef: ParameterizedTypeReference<List<Room?>> = object : ParameterizedTypeReference<List<Room?>>() {}
return webClient.get().uri(url)
.retrieve().bodyToMono(typeRef).cache()
.checkpoint("Request failed in ${this::class.simpleName}::get(roomIds).")
.flatMapMany { roomList: List<Room?> ->
Flux.fromIterable(
roomList.map { entry ->
if (entry != null) {
Optional.of(Room(entry.id, entry.shortId, entry.name))
} else {
Optional.empty()
}
}
)
}
}
fun getByShortId(shortId: String): Mono<Room> {
val path = "${httpGatewayProperties.httpClient.core}/room/"
val url = "$path~$shortId"
logger.trace("Querying core for room by shortId with url: {}", url)
return webClient
.get()
.uri(url)
.retrieve()
.bodyToMono(Room::class.java)
.checkpoint("Request failed in ${this::class.simpleName}::${::getByShortId.name}.")
}
}
| gpl-3.0 | 385fca27b4a9fc419503119ed430d585 | 36.59375 | 112 | 0.678304 | 4.250883 | false | false | false | false |
bravelocation/yeltzland-android | app/src/main/java/com/bravelocation/yeltzlandnew/tweet/QuotedTweet.kt | 1 | 1053 | package com.bravelocation.yeltzlandnew.tweet
import com.google.gson.annotations.SerializedName
import java.util.*
class QuotedTweet : DisplayTweet {
@SerializedName("id_str")
var id: String? = null
@SerializedName("full_text")
override var fullText: String? = null
@SerializedName("user")
override var user: User? = null
@SerializedName("created_at")
override var createdDate: Date? = null
@SerializedName("entities")
override var entities: Entities? = null
@SerializedName("extended_entities")
override var extendedEntities: ExtendedEntities? = null
@SerializedName("quoted_status")
var quotedTweet: QuotedTweet? = null
override val isRetweet: Boolean
get() = false
override fun quote(): QuotedTweet? {
return quotedTweet
}
override fun userTwitterUrl(): String {
return "https://twitter.com/" + user?.screenName
}
override fun bodyTwitterUrl(): String {
return "https://twitter.com/" + user?.screenName + "/status/" + id
}
} | mit | 7681e8ea221569f966194f9cbca17114 | 24.707317 | 74 | 0.673314 | 4.461864 | false | false | false | false |
WonderBeat/suchmarines | src/main/kotlin/org/wow/learning/FileBasedLearner.kt | 1 | 1776 | package org.wow.learning
import java.io.File
import org.wow.logger.GameTurn
import org.slf4j.LoggerFactory
import reactor.core.composable.spec.Promises
import reactor.core.composable.spec.Streams
import org.wow.logger.LogsParser
import reactor.core.Environment
import reactor.function.Consumer
import java.util.concurrent.TimeUnit
public class FileBasedLearner<T>(
val env: reactor.core.Environment,
val files: List<File>,
val parser: LogsParser,
val vectorizer: (List<GameTurn>) -> List<T>,
val timeoutMin: Long = 1000) {
private val logger = LoggerFactory.getLogger(javaClass<FileBasedLearner<T>>())!!
fun <B, K : Learner<T, B>> learn(data: K): K {
val doneDefer = Promises.defer<K>()!!.env(env)!!.get()!!
val completePromise = doneDefer.compose()
val complete = Consumer<K> { doneDefer.accept(it) }
val deferred = Streams.defer<File>()!!.env(env)!!.dispatcher(Environment.RING_BUFFER)!!.get();
deferred!!.compose()!!
.map { file ->
logger.debug("Parsing: " + file)
parser.parse(file!!) }!!
.map { game ->
vectorizer(game!!)}!!
.batch(files.size)!!
.reduce ({ (current) ->
current!!.getT1()!!.forEach { current.getT2()!!.learn(it) }; current.getT2()
}, data)!!
.consume(complete)!!
.`when`(javaClass<Exception>(), { ex ->
logger.error(ex.toString())})
files.forEach{ deferred.accept(it) }
return completePromise!!.await(timeoutMin, TimeUnit.MINUTES)!!
}
}
| mit | 387f6345b4b74b871fa0c63ddedb4c23 | 40.302326 | 102 | 0.556306 | 4.428928 | false | false | false | false |
arturbosch/detekt | detekt-test/src/main/kotlin/io/gitlab/arturbosch/detekt/test/FindingsAssertions.kt | 1 | 4021 | package io.gitlab.arturbosch.detekt.test
import io.gitlab.arturbosch.detekt.api.Finding
import io.gitlab.arturbosch.detekt.api.SourceLocation
import io.gitlab.arturbosch.detekt.api.TextLocation
import org.assertj.core.api.AbstractAssert
import org.assertj.core.api.AbstractListAssert
import org.assertj.core.util.CheckReturnValue
import java.util.Objects
@CheckReturnValue
fun assertThat(findings: List<Finding>) = FindingsAssert(findings)
@CheckReturnValue
fun assertThat(finding: Finding) = FindingAssert(finding)
fun List<Finding>.assert() = FindingsAssert(this)
class FindingsAssert(actual: List<Finding>) :
AbstractListAssert<FindingsAssert, List<Finding>,
Finding, FindingAssert>(actual, FindingsAssert::class.java) {
override fun newAbstractIterableAssert(iterable: MutableIterable<Finding>): FindingsAssert {
throw UnsupportedOperationException("not implemented")
}
override fun toAssert(value: Finding?, description: String?): FindingAssert =
FindingAssert(value).`as`(description)
fun hasSourceLocations(vararg expected: SourceLocation) = apply {
val actualSources = actual.asSequence()
.map { it.location.source }
.sortedWith(compareBy({ it.line }, { it.column }))
val expectedSources = expected.asSequence()
.sortedWith(compareBy({ it.line }, { it.column }))
if (!Objects.deepEquals(actualSources.toList(), expectedSources.toList())) {
failWithMessage(
"Expected source locations to be ${expectedSources.toList()} but was ${actualSources.toList()}"
)
}
}
fun hasSourceLocation(line: Int, column: Int) = apply {
hasSourceLocations(SourceLocation(line, column))
}
fun hasTextLocations(vararg expected: Pair<Int, Int>) = apply {
val actualSources = actual.asSequence()
.map { it.location.text }
.sortedWith(compareBy({ it.start }, { it.end }))
val expectedSources = expected.asSequence()
.map { (start, end) -> TextLocation(start, end) }
.sortedWith(compareBy({ it.start }, { it.end }))
if (!Objects.deepEquals(actualSources.toList(), expectedSources.toList())) {
failWithMessage(
"Expected text locations to be ${expectedSources.toList()} but was ${actualSources.toList()}"
)
}
}
fun hasTextLocations(vararg expected: String): FindingsAssert {
val finding = actual.firstOrNull()
if (finding == null) {
if (expected.isEmpty()) {
return this
} else {
failWithMessage("Expected ${expected.size} findings but was 0")
}
}
val code = requireNotNull(finding?.entity?.ktElement?.run { containingKtFile.text }) {
"Finding expected to provide a KtElement."
}
val textLocations = expected.map { snippet ->
val index = code.indexOf(snippet)
if (index < 0) {
failWithMessage("The snippet \"$snippet\" doesn't exist in the code")
} else {
if (code.indexOf(snippet, index + 1) >= 0) {
failWithMessage("The snippet \"$snippet\" appears multiple times in the code")
}
}
index to index + snippet.length
}.toTypedArray()
return hasTextLocations(*textLocations)
}
}
class FindingAssert(val actual: Finding?) : AbstractAssert<FindingAssert, Finding>(actual, FindingAssert::class.java) {
fun hasMessage(expectedMessage: String) = apply {
if (expectedMessage.isNotBlank() && actual.message.isBlank()) {
failWithMessage("Expected message <$expectedMessage> but finding has no message")
}
if (!actual.message.trim().equals(expectedMessage.trim(), ignoreCase = true)) {
failWithMessage("Expected message <$expectedMessage> but actual message was <${actual.message}>")
}
}
}
| apache-2.0 | 025282e30907d6919a430f305172f977 | 37.663462 | 119 | 0.640388 | 4.821343 | false | false | false | false |
nextcloud/android | app/src/main/java/com/nextcloud/client/media/ExoplayerListener.kt | 1 | 2497 | /*
* Nextcloud Android client application
*
* @author Álvaro Brey
* Copyright (C) 2022 Álvaro Brey
* Copyright (C) 2022 Nextcloud GmbH
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.nextcloud.client.media
import android.content.Context
import android.content.DialogInterface
import android.view.View
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.PlaybackException
import com.google.android.exoplayer2.Player
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.owncloud.android.R
import com.owncloud.android.lib.common.utils.Log_OC
class ExoplayerListener(private val context: Context, private val playerView: View, private val exoPlayer: ExoPlayer) :
Player.Listener {
override fun onPlaybackStateChanged(playbackState: Int) {
super.onPlaybackStateChanged(playbackState)
if (playbackState == Player.STATE_ENDED) {
onCompletion()
}
}
override fun onIsPlayingChanged(isPlaying: Boolean) {
super.onIsPlayingChanged(isPlaying)
Log_OC.d(TAG, "Exoplayer keep screen on: $isPlaying")
playerView.keepScreenOn = isPlaying
}
private fun onCompletion() {
exoPlayer.let {
it.seekToDefaultPosition()
it.pause()
}
}
override fun onPlayerError(error: PlaybackException) {
super.onPlayerError(error)
Log_OC.e(TAG, "Exoplayer error", error)
val message = ErrorFormat.toString(context, error)
MaterialAlertDialogBuilder(context)
.setMessage(message)
.setPositiveButton(R.string.common_ok) { _: DialogInterface?, _: Int ->
onCompletion()
}
.setCancelable(false)
.show()
}
companion object {
private const val TAG = "ExoplayerListener"
}
}
| gpl-2.0 | ee161a0f8f743a54b0394a86a7436fc2 | 32.716216 | 119 | 0.7002 | 4.536364 | false | false | false | false |
ibaton/3House | mobile/src/main/java/treehou/se/habit/ui/control/cells/config/CellIncDecConfigFragment.kt | 1 | 7145 | package treehou.se.habit.ui.control.cells.config
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.trello.rxlifecycle2.components.support.RxFragment
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import io.realm.Realm
import kotlinx.android.synthetic.main.inc_dec_controller_action.*
import se.treehou.ng.ohcommunicator.connector.models.OHItem
import treehou.se.habit.R
import treehou.se.habit.core.db.model.ItemDB
import treehou.se.habit.core.db.model.ServerDB
import treehou.se.habit.core.db.model.controller.CellDB
import treehou.se.habit.core.db.model.controller.IncDecCellDB
import treehou.se.habit.ui.util.IconPickerActivity
import treehou.se.habit.util.ConnectionFactory
import treehou.se.habit.util.Constants
import treehou.se.habit.util.Util
import treehou.se.habit.util.logging.Logger
import java.util.*
import javax.inject.Inject
class CellIncDecConfigFragment : RxFragment() {
@Inject lateinit var connectionFactory: ConnectionFactory
@Inject lateinit var logger: Logger
lateinit var realm: Realm
private var itemAdapter: ArrayAdapter<OHItem>? = null
private val items = ArrayList<OHItem>()
private var incDecCell: IncDecCellDB? = null
private var cell: CellDB? = null
private var item: OHItem? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Util.getApplicationComponent(this).inject(this)
realm = Realm.getDefaultInstance()
if (arguments != null) {
val id = arguments!!.getLong(ARG_CELL_ID)
cell = CellDB.load(realm, id)
incDecCell = cell!!.getCellIncDec()
if (incDecCell == null) {
realm.executeTransaction { realm ->
incDecCell = IncDecCellDB()
incDecCell = realm.copyToRealm(incDecCell!!)
cell!!.setCellIncDec(incDecCell!!)
realm.copyToRealmOrUpdate(cell!!)
}
}
val itemDB = incDecCell!!.item
if (itemDB != null) {
item = itemDB.toGeneric()
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.inc_dec_controller_action, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
maxText.setText("" + incDecCell!!.max)
minText.setText("" + incDecCell!!.min)
valueText.setText("" + incDecCell!!.value)
itemsSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
realm.beginTransaction()
val item = items[position]
if (item != null) {
val itemDB = ItemDB.createOrLoadFromGeneric(realm, item)
incDecCell!!.item = itemDB
}
realm.commitTransaction()
}
override fun onNothingSelected(parent: AdapterView<*>) {}
}
itemAdapter = ArrayAdapter(activity!!, android.R.layout.simple_spinner_dropdown_item, items)
itemsSpinner.adapter = itemAdapter
val servers = realm.where(ServerDB::class.java).findAll()
items.clear()
val item = item
if (item != null) {
items.add(item)
itemAdapter!!.add(item)
itemAdapter!!.notifyDataSetChanged()
}
if (incDecCell!!.item != null) {
items.add(incDecCell!!.item!!.toGeneric())
}
for (serverDB in servers) {
val server = serverDB.toGeneric()
val serverHandler = connectionFactory.createServerHandler(server, context)
serverHandler.requestItemsRx()
.map<List<OHItem>>({ this.filterItems(it) })
.compose(bindToLifecycle())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ newItems ->
this.items.addAll(newItems)
itemAdapter!!.notifyDataSetChanged()
}, { logger.e(TAG, "Failed to load items", it) })
}
updateIconImage()
setIconButton.setOnClickListener {
val intent = Intent(activity, IconPickerActivity::class.java)
startActivityForResult(intent, REQUEST_ICON)
}
}
private fun updateIconImage() {
setIconButton.setImageDrawable(Util.getIconDrawable(activity, incDecCell!!.icon))
}
private fun filterItems(items: MutableList<OHItem>): List<OHItem> {
val tempItems = ArrayList<OHItem>()
for (item in items) {
if (Constants.SUPPORT_INC_DEC.contains(item.type)) {
tempItems.add(item)
}
}
items.clear()
items.addAll(tempItems)
return items
}
override fun onPause() {
super.onPause()
realm.beginTransaction()
try {
incDecCell!!.max = Integer.parseInt(maxText.text.toString())
} catch (e: NumberFormatException) {
incDecCell!!.max = 100
}
try {
incDecCell!!.min = Integer.parseInt(minText.text.toString())
} catch (e: NumberFormatException) {
incDecCell!!.min = 0
}
try {
incDecCell!!.value = Integer.parseInt(valueText.text.toString())
} catch (e: NumberFormatException) {
incDecCell!!.value = 1
}
realm.commitTransaction()
}
override fun onDestroy() {
super.onDestroy()
realm.close()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_ICON &&
resultCode == Activity.RESULT_OK &&
data!!.hasExtra(IconPickerActivity.RESULT_ICON)) {
val iconName = data.getStringExtra(IconPickerActivity.RESULT_ICON)
realm.beginTransaction()
incDecCell!!.icon = if (iconName == "") null else iconName
realm.commitTransaction()
updateIconImage()
}
}
companion object {
private val TAG = "CellIncDecConfigFragment"
private val ARG_CELL_ID = "ARG_CELL_ID"
private val REQUEST_ICON = 183
fun newInstance(cell: CellDB): CellIncDecConfigFragment {
val fragment = CellIncDecConfigFragment()
val args = Bundle()
args.putLong(ARG_CELL_ID, cell.id)
fragment.arguments = args
return fragment
}
}
}// Required empty public constructor
| epl-1.0 | 06da4643144c2fa0b2b923b33767c203 | 33.186603 | 102 | 0.615815 | 4.944637 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/baseview/BaseView.kt | 1 | 6333 | package com.soywiz.korge.baseview
import com.soywiz.klock.*
import com.soywiz.korge.component.*
import com.soywiz.korge.internal.*
import com.soywiz.korge.view.*
open class BaseView {
@KorgeInternal
@PublishedApi
internal var _components: Components? = null
@KorgeInternal
@PublishedApi
internal val componentsSure: Components
get() {
if (_components == null) _components = Components()
return _components!!
}
/** Creates a typed [T] component (using the [gen] factory function) if the [View] doesn't have any of that kind, or returns a component of that type if already attached */
//Deprecated("")
//inline fun <reified T : Component> ComponentContainer.getOrCreateComponent(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : Component> getOrCreateComponentOther(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : MouseComponent> getOrCreateComponentMouse(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : KeyComponent> getOrCreateComponentKey(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : GamepadComponent> getOrCreateComponentGamepad(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : TouchComponent> getOrCreateComponentTouch(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : EventComponent> getOrCreateComponentEvent(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : UpdateComponentWithViews> getOrCreateComponentUpdateWithViews(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : UpdateComponent> getOrCreateComponentUpdate(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : ResizeComponent> getOrCreateComponentResize(gen: (BaseView) -> T): T = componentsSure.getOrCreateComponent(this, T::class, gen)
inline fun <reified T : UpdateComponent> getComponentUpdate(): T? = componentsSure.getComponentUpdate<T>()
/** Removes a specific [c] component from the view */
fun removeComponent(c: Component) {
_components?.remove(c)
}
fun removeComponent(c: MouseComponent) {
_components?.remove(c)
}
fun removeComponent(c: KeyComponent) {
_components?.remove(c)
}
fun removeComponent(c: GamepadComponent) {
_components?.remove(c)
}
fun removeComponent(c: TouchComponent) {
_components?.remove(c)
}
fun removeComponent(c: EventComponent) {
_components?.remove(c)
}
fun removeComponent(c: UpdateComponentWithViews) {
_components?.remove(c)
}
fun removeComponent(c: UpdateComponent) {
_components?.remove(c)
}
fun removeComponent(c: ResizeComponent) {
_components?.remove(c)
}
//fun removeComponents(c: KClass<out Component>) { components?.removeAll { it.javaClass.isSubtypeOf(c) } }
///** Removes a set of components of the type [c] from the view */
//@eprecated("")
//fun removeComponents(c: KClass<out Component>) { _components?.removeAll(c) }
/** Removes all the components attached to this view */
fun removeAllComponents(): Unit {
_components?.removeAll()
}
/** Adds a component to this view */
fun addComponent(c: Component): Component = componentsSure.add(c)
fun addComponent(c: MouseComponent) = componentsSure.add(c)
fun addComponent(c: KeyComponent) = componentsSure.add(c)
fun addComponent(c: GamepadComponent) = componentsSure.add(c)
fun addComponent(c: TouchComponent) = componentsSure.add(c)
fun addComponent(c: EventComponent) = componentsSure.add(c)
fun addComponent(c: UpdateComponentWithViews) = componentsSure.add(c)
fun addComponent(c: UpdateComponent) = componentsSure.add(c)
fun addComponent(c: ResizeComponent) = componentsSure.add(c)
/** Registers a [block] that will be executed once in the next frame that this [View] is displayed with the [Views] singleton */
fun deferWithViews(block: (views: Views) -> Unit) {
addComponent(DeferWithViewsUpdateComponentWithViews(this@BaseView, block))
}
internal class DeferWithViewsUpdateComponentWithViews(override val view: BaseView, val block: (views: Views) -> Unit) :
UpdateComponentWithViews {
override fun update(views: Views, dt: TimeSpan) {
block(views)
detach()
}
}
// region Properties
private val _props = linkedMapOf<String, Any?>()
/** Immutable map of custom String properties attached to this view. Should use [hasProp], [getProp] and [addProp] methods to control this */
val props: Map<String, Any?> get() = _props
/** Checks if this view has the [key] property */
fun hasProp(key: String) = key in _props
/** Gets the [key] property of this view as a [String] or [default] when not found */
fun getPropString(key: String, default: String = "") = _props[key]?.toString() ?: default
/** Gets the [key] property of this view as an [Double] or [default] when not found */
fun getPropDouble(key: String, default: Double = 0.0): Double {
val value = _props[key]
if (value is Number) return value.toDouble()
if (value is String) return value.toDoubleOrNull() ?: default
return default
}
/** Gets the [key] property of this view as an [Int] or [default] when not found */
fun getPropInt(key: String, default: Int = 0) = getPropDouble(key, default.toDouble()).toInt()
/** Adds or replaces the property [key] with the [value] */
fun addProp(key: String, value: Any?) {
_props[key] = value
//val componentGen = views.propsTriggers[key]
//if (componentGen != null) {
// componentGen(this, key, value)
//}
}
/** Adds a list of [values] properties at once */
fun addProps(values: Map<String, Any?>) {
for (pair in values) addProp(pair.key, pair.value)
}
// endregion
}
| apache-2.0 | c3c0832d9d4e260bf64c629e06201851 | 42.376712 | 176 | 0.681825 | 4.244638 | false | false | false | false |
CherepanovAleksei/BinarySearchTree | tests/RBTree/equalTree.kt | 1 | 5660 |
/**
* Created by [email protected]
*/
import BTree.BTree
import BinaryTree.BinarySearchTree
import RBTree.RedBlackTree
import org.junit.jupiter.api.Test
import java.util.*
internal class EqualTreeTest {
@Test
fun BinTreeRandom() {
val BinTree = BinarySearchTree<Int, Int>()
var number:Int = 100
while (number < 10000001) {
var start = System.currentTimeMillis()
for (i in 1..number) {
val key = Random().nextInt(number-1) + 1
BinTree.insert(key, key)
}
var finish = System.currentTimeMillis()
var timeConsumedMillis:Float = (finish - start).toFloat()/1000
println("InsertBinTreeRandom(${number}):"+timeConsumedMillis)
start = System.currentTimeMillis()
for (i in 1..number) {
val key = Random().nextInt(number-1) + 1
BinTree.search(key)
}
finish = System.currentTimeMillis()
timeConsumedMillis = (finish - start).toFloat()/1000
println("SearchBinTreeRandom(${number}):"+timeConsumedMillis)
number *= 10
println()
}
}
@Test
fun BinTreeQueue() {
val BinTree = BinarySearchTree<Int, Int>()
var number:Int = 100
while (number < 10000001) {
var start = System.currentTimeMillis()
for (key in 1..number) BinTree.insert(key, key)
var finish = System.currentTimeMillis()
var timeConsumedMillis:Float = (finish - start).toFloat()/1000
println("InsertBinTreeQueue(${number}):"+timeConsumedMillis)
start = System.currentTimeMillis()
for (key in 1..number) {
BinTree.search(key)
}
finish = System.currentTimeMillis()
timeConsumedMillis = (finish - start).toFloat()/1000
println("SearchBinTreeQueue(${number}):"+timeConsumedMillis)
number *= 10
println()
}
}
@Test
fun RBTreeRandom() {
val RBTree = RedBlackTree<Int, Int>()
var number:Int = 100
while (number < 10000001) {
var start = System.currentTimeMillis()
for (i in 1..number) {
val key = Random().nextInt(number-1) + 1
RBTree.insert(key, key)
}
var finish = System.currentTimeMillis()
var timeConsumedMillis:Float = (finish - start).toFloat()/1000
println("InsertRBTreeRandom(${number}):"+timeConsumedMillis)
start = System.currentTimeMillis()
for (i in 1..number) {
val key = Random().nextInt(number-1) + 1
RBTree.search(key)
}
finish = System.currentTimeMillis()
timeConsumedMillis = (finish - start).toFloat()/1000
println("SearchRBTreeRandom(${number}):"+timeConsumedMillis)
number *= 10
println()
}
}
@Test
fun RBTreeQueue() {
val RBTree = RedBlackTree<Int, Int>()
var number:Int = 100
while (number < 10000001) {
var start = System.currentTimeMillis()
for (key in 1..number) RBTree.insert(key, key)
var finish = System.currentTimeMillis()
var timeConsumedMillis:Float = (finish - start).toFloat()/1000
println("InsertRBTreeQueue(${number}):"+timeConsumedMillis)
start = System.currentTimeMillis()
for (key in 1..number) {
RBTree.search(key)
}
finish = System.currentTimeMillis()
timeConsumedMillis = (finish - start).toFloat()/1000
println("SearchRBTreeQueue(${number}):"+timeConsumedMillis)
number *= 10
println()
}
}
@Test
fun BTreeRandom() {
val BTree = BTree<Int>(100)
var number:Int = 100
while (number < 10000001) {
var start = System.currentTimeMillis()
for (i in 1..number) {
val key = Random().nextInt(number-1) + 1
BTree.insert(key)
}
var finish = System.currentTimeMillis()
var timeConsumedMillis:Float = (finish - start).toFloat()/1000
println("InsertBTreeRandom(${number}):"+timeConsumedMillis)
start = System.currentTimeMillis()
for (i in 1..number) {
val key = Random().nextInt(number-1) + 1
BTree.search(key)
}
finish = System.currentTimeMillis()
timeConsumedMillis = (finish - start).toFloat()/1000
println("SearchBTreeRandom(${number}):"+timeConsumedMillis)
number *= 10
println()
}
}
@Test
fun BTreeQueue() {
val BTree = BTree<Int>(100)
var number:Int = 100
while (number < 10000001) {
var start = System.currentTimeMillis()
for (key in 1..number) BTree.insert(key)
var finish = System.currentTimeMillis()
var timeConsumedMillis:Float = (finish - start).toFloat()/1000
println("InsertBTreeQueue(${number}):"+timeConsumedMillis)
start = System.currentTimeMillis()
for (key in 1..number) {
BTree.search(key)
}
finish = System.currentTimeMillis()
timeConsumedMillis = (finish - start).toFloat()/1000
println("SearchBTreeQueue(${number}):"+timeConsumedMillis)
number *= 10
println()
}
}
} | mit | 8ca5d8d0357670aa224fb983949b75ca | 31.912791 | 74 | 0.544523 | 5.085355 | false | false | false | false |
isuPatches/WiseFy | wisefy/src/androidTest/java/com/isupatches/wisefy/GetNearbyAccessPointsTests.kt | 1 | 6225 | package com.isupatches.wisefy
import com.isupatches.wisefy.callbacks.GetNearbyAccessPointsCallbacks
import com.isupatches.wisefy.constants.MISSING_PARAMETER
import com.isupatches.wisefy.internal.base.BaseInstrumentationTest
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.Mockito.mock
import org.mockito.Mockito.timeout
import org.mockito.Mockito.verify
/**
* Tests the ability to retrieve a list of nearby access points for a device.
*
* @author Patches
* @since 3.0
*/
internal class GetNearbyAccessPointsTests : BaseInstrumentationTest() {
@Test
fun sync_failure_prechecks_filterDuplicates_false() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_failure()
assertEquals(null, wisefy.getNearbyAccessPoints(false))
}
@Test
fun sync_failure_prechecks_filterDuplicates_true() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_failure()
assertEquals(null, wisefy.getNearbyAccessPoints(true))
}
@Test
fun sync_failure_filterDuplicates_false() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
mockWiseFySearchUtil.nearbyAccessPoints_null(false)
val nearbyAccessPoints = wisefy.getNearbyAccessPoints(false)
assertEquals(null, nearbyAccessPoints)
}
@Test
fun sync_failure_filterDuplicates_true() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
mockWiseFySearchUtil.nearbyAccessPoints_null(true)
val nearbyAccessPoints = wisefy.getNearbyAccessPoints(true)
assertEquals(null, nearbyAccessPoints)
}
@Test
fun sync_success_filterDuplicates_false() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
val accessPoints = mockWiseFySearchUtil.nearbyAccessPoints_success(false)
val nearbyAccessPoints = wisefy.getNearbyAccessPoints(false)
assertEquals(accessPoints, nearbyAccessPoints)
}
@Test
fun sync_success_filterDuplicates_true() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
val accessPoints = mockWiseFySearchUtil.nearbyAccessPoints_success(true)
val nearbyAccessPoints = wisefy.getNearbyAccessPoints(true)
assertEquals(accessPoints, nearbyAccessPoints)
}
@Test
fun async_failure_prechecks_filterDuplicates_false() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_failure()
val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java)
wisefy.getNearbyAccessPoints(false, mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).wisefyFailure(MISSING_PARAMETER)
}
@Test
fun async_failure_prechecks_filterDuplicates_false_nullCallback() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_failure()
nullCallbackUtil.callGetNearbyAccessPoints(false)
}
@Test
fun async_failure_prechecks_filterDuplicates_true() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_failure()
val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java)
wisefy.getNearbyAccessPoints(true, mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).wisefyFailure(MISSING_PARAMETER)
}
@Test
fun async_failure_prechecks_filterDuplicates_true_nullCallback() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_failure()
nullCallbackUtil.callGetNearbyAccessPoints(true)
}
@Test
fun async_failure_filterDuplicates_false() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
mockWiseFySearchUtil.nearbyAccessPoints_null(false)
val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java)
wisefy.getNearbyAccessPoints(false, mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).noAccessPointsFound()
}
@Test
fun async_failure_filterDuplicates_false_nullCallback() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
mockWiseFySearchUtil.nearbyAccessPoints_success(true)
nullCallbackUtil.callGetNearbyAccessPoints(false)
}
@Test
fun async_failure_filterDuplicates_true() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
mockWiseFySearchUtil.nearbyAccessPoints_null(true)
val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java)
wisefy.getNearbyAccessPoints(true, mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).noAccessPointsFound()
}
@Test
fun async_failure_filterDuplicates_true_nullCallback() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
mockWiseFySearchUtil.nearbyAccessPoints_null(true)
nullCallbackUtil.callGetNearbyAccessPoints(true)
}
@Test
fun async_success_filterDuplicates_false() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
val accessPoints = mockWiseFySearchUtil.nearbyAccessPoints_success(false)
val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java)
wisefy.getNearbyAccessPoints(false, mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).retrievedNearbyAccessPoints(accessPoints)
}
@Test
fun async_success_filterDuplicates_false_nullCallback() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
mockWiseFySearchUtil.nearbyAccessPoints_success(true)
nullCallbackUtil.callGetNearbyAccessPoints(false)
}
@Test
fun async_success_filterDuplicates_true() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
val accessPoints = mockWiseFySearchUtil.nearbyAccessPoints_success(true)
val mockCallbacks = mock(GetNearbyAccessPointsCallbacks::class.java)
wisefy.getNearbyAccessPoints(true, mockCallbacks)
verify(mockCallbacks, timeout(VERIFICATION_SUCCESS_TIMEOUT)).retrievedNearbyAccessPoints(accessPoints)
}
@Test
fun async_success_filterDuplicates_true_nullCallback() {
mockWiseFyPrechecksUtil.getNearbyAccessPoints_success()
mockWiseFySearchUtil.nearbyAccessPoints_success(true)
nullCallbackUtil.callGetNearbyAccessPoints(true)
}
}
| apache-2.0 | 0b063147b93d63477bd322ce83649616 | 39.16129 | 110 | 0.755181 | 5.861582 | false | true | false | false |
apixandru/intellij-community | platform/lvcs-impl/src/com/intellij/history/integration/ValidateHistoryAction.kt | 20 | 2497 | /*
* 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 com.intellij.history.integration
import com.intellij.history.core.changes.ChangeSet
import com.intellij.history.core.changes.ChangeVisitor
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.ui.Messages
import com.intellij.util.ExceptionUtil
class ValidateHistoryAction : AnAction() {
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = ApplicationManager.getApplication().isInternal
}
override fun actionPerformed(e: AnActionEvent) {
object : Task.Modal(e.project, "Checking local history storage", true) {
override fun run(indicator: ProgressIndicator) {
val t = System.currentTimeMillis()
try {
LocalHistoryImpl.getInstanceImpl().facade?.accept(object : ChangeVisitor() {
private var count = 0
override fun end(c: ChangeSet) {
indicator.checkCanceled()
if (++count % 10 == 0) {
indicator.text = "${count} records checked"
}
}
override fun finished() {
val message = "Local history storage seems to be OK (checked ${count} records in ${System.currentTimeMillis() - t} ms)"
ApplicationManager.getApplication().invokeLater { Messages.showInfoMessage(e.project, message, "Local History Validation") }
}
})
}
catch(ex: ProcessCanceledException) { throw ex }
catch(ex: Exception) {
Messages.showErrorDialog(e.project, ExceptionUtil.getThrowableText(ex), "Local History Validation Error")
}
}
}.queue()
}
} | apache-2.0 | 80eb41cc20ae640a23272587e8fafa3c | 38.650794 | 138 | 0.702443 | 4.66729 | false | false | false | false |
chilangolabs/MDBancomer | app/src/main/java/com/chilangolabs/mdb/ConfirmTransferActivity.kt | 1 | 4280 | package com.chilangolabs.mdb
import android.hardware.fingerprint.FingerprintManager
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.chilangolabs.mdb.utils.logd
import com.chilangolabs.mdb.utils.loge
import com.chilangolabs.mdb.utils.logw
import com.dev21.fingerprintassistant.FingerprintAuthListener
import com.dev21.fingerprintassistant.FingerprintHelper
import com.dev21.fingerprintassistant.FingerprintResultsHandler
import com.dev21.fingerprintassistant.ResponseCode
import kotlinx.android.synthetic.main.activity_confirm_transfer.*
import org.jetbrains.anko.intentFor
import org.jetbrains.anko.singleTop
import org.jetbrains.anko.toast
class ConfirmTransferActivity : AppCompatActivity(), FingerprintAuthListener {
private val fingerPrintHelper: FingerprintHelper? by lazy {
FingerprintHelper(this, "FingerPrintMDB")
}
private val fingerprintresulthandler: FingerprintResultsHandler? by lazy {
FingerprintResultsHandler(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_confirm_transfer)
val a = fingerprintresulthandler
btnConfirmTransfer.setOnClickListener {
startActivity(intentFor<CardsActivity>().singleTop())
}
}
override fun onResume() {
super.onResume()
val responseCode = fingerPrintHelper?.checkAndEnableFingerPrintService()
when (responseCode) {
ResponseCode.FINGERPRINT_SERVICE_INITIALISATION_SUCCESS -> {
// toast("Fingerprint sensor service initialisation success")
fingerprintresulthandler?.setFingerprintAuthListener(this)
fingerprintresulthandler?.startListening(fingerPrintHelper?.fingerprintManager, fingerPrintHelper?.cryptoObject)
}
ResponseCode.OS_NOT_SUPPORTED -> toast("OS doesn't support fingerprint api")
ResponseCode.FINGER_PRINT_SENSOR_UNAVAILABLE -> toast("Fingerprint sensor not found")
ResponseCode.ENABLE_FINGER_PRINT_SENSOR_ACCESS -> toast("Provide access to use fingerprint sensor")
ResponseCode.NO_FINGER_PRINTS_ARE_ENROLLED -> toast("No fingerprints found")
ResponseCode.FINGERPRINT_SERVICE_INITIALISATION_FAILED -> toast("Fingerprint service initialisation failed")
ResponseCode.DEVICE_NOT_KEY_GUARD_SECURED -> toast("Device is not key guard protected")
}
fingerprintresulthandler?.let {
if (it.isAlreadyListening) {
it.startListening(fingerPrintHelper?.fingerprintManager, fingerPrintHelper?.cryptoObject)
}
}
}
override fun onStop() {
super.onStop()
fingerprintresulthandler?.stopListening()
}
override fun onAuthentication(helpOrErrorCode: Int,
infoString: CharSequence?,
authenticationResult: FingerprintManager.AuthenticationResult?,
authCode: Int) {
when (authCode) {
ResponseCode.AUTH_ERROR -> {
loge("AUTH Error")
logd("$infoString")
txtConfirmTransfer.text = "Error al leer tu huella, intena de nuevo"
imgFingerPrint.setImageResource(R.drawable.ic_finger_print_red)
}
ResponseCode.AUTH_FAILED -> {
loge("AUTH Failed")
logd("$infoString")
txtConfirmTransfer.text = "Error al leer tu huella, intena de nuevo"
imgFingerPrint.setImageResource(R.drawable.ic_finger_print_red)
}
ResponseCode.AUTH_HELP -> {
logw("AUTH HELP")
logd("$infoString")
txtConfirmTransfer.text = "Error al leer tu huella, intena de nuevo"
imgFingerPrint.setImageResource(R.drawable.ic_finger_print_red)
}
ResponseCode.AUTH_SUCCESS -> {
logd("AUTH Success")
logd("$infoString")
txtConfirmTransfer.text = "Huella confirmada"
imgFingerPrint.setImageResource(R.drawable.ic_finger_print_green)
}
}
}
}
| mit | 1721e86df3ad5a2ad39785d0614ed754 | 40.553398 | 128 | 0.661449 | 5.290482 | false | false | false | false |
konfko/konfko | konfko-core/src/test/kotlin/com/github/konfko/core/sample/SimpleSettingsSample.kt | 1 | 1108 | @file:JvmName("SimpleSettingsSample")
package com.github.konfko.core.sample
import com.github.konfko.core.derived.subSettings
import com.github.konfko.core.source.SettingsMaker
/**
* @author markopi
*/
fun main(args: Array<String>) {
val settings = SettingsMaker().make {
classpath("com/github/konfko/core/dataSources.properties")
}
// read a single setting
val firstUrl: String = settings["dataSource.first.url"]
// partial views
val firstDataSource = settings.subSettings("dataSource.first")
val secondDataSource = settings.subSettings("dataSource").subSettings("second")
val secondUrl: String = secondDataSource["url"]
println("First url: $firstUrl, second url: $secondUrl")
// optional Int settings
val firstConnectionTimeout: Int? = firstDataSource.find("connectionTimeout")
val secondConnectionTimeout: Int? = secondDataSource.find("connectionTimeout")
println("First timeout: $firstConnectionTimeout, second timeout: $secondConnectionTimeout")
println("All data sources: ${settings.subSettings("dataSource").topLevelKeys}")
}
| apache-2.0 | f68447daf0e46b9416aa612238ec4b2c | 32.575758 | 95 | 0.738267 | 4.294574 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/media/MediaPreloader.kt | 1 | 3062 | /*
* 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.util.media
import android.content.Context
import android.content.SharedPreferences
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.Target
import org.mariotaku.kpreferences.get
import de.vanita5.twittnuker.constant.mediaPreloadKey
import de.vanita5.twittnuker.constant.mediaPreloadOnWifiOnlyKey
import de.vanita5.twittnuker.extension.loadProfileImage
import de.vanita5.twittnuker.model.ParcelableActivity
import de.vanita5.twittnuker.model.ParcelableMedia
import de.vanita5.twittnuker.model.ParcelableStatus
import de.vanita5.twittnuker.extension.model.activityStatus
class MediaPreloader(val context: Context) {
var isNetworkMetered: Boolean = true
private var preloadEnabled: Boolean = true
private var preloadOnWifiOnly: Boolean = true
private val shouldPreload: Boolean get() = preloadEnabled && (!preloadOnWifiOnly || !isNetworkMetered)
fun preloadStatus(status: ParcelableStatus) {
if (!shouldPreload) return
preLoadProfileImage(status)
preloadMedia(status.media)
preloadMedia(status.quoted_media)
}
fun preloadActivity(activity: ParcelableActivity) {
if (!shouldPreload) return
activity.activityStatus?.let { preloadStatus(it) }
}
fun reloadOptions(preferences: SharedPreferences) {
preloadEnabled = preferences[mediaPreloadKey]
preloadOnWifiOnly = preferences[mediaPreloadOnWifiOnlyKey]
}
private fun preloadMedia(media: Array<ParcelableMedia>?) {
media?.forEach { item ->
val url = item.preview_url ?: run {
if (item.type != ParcelableMedia.Type.IMAGE) return@run null
return@run item.media_url
} ?: return@forEach
preloadPreviewImage(url)
}
}
private fun preLoadProfileImage(status: ParcelableStatus) {
Glide.with(context).loadProfileImage(context, status, 0).into(Target.SIZE_ORIGINAL,
Target.SIZE_ORIGINAL)
}
private fun preloadPreviewImage(url: String?) {
Glide.with(context).load(url).into(Target.SIZE_ORIGINAL,
Target.SIZE_ORIGINAL)
}
} | gpl-3.0 | 70db37b724fc30d8dfbcb54b0bd76f7d | 35.035294 | 106 | 0.726649 | 4.405755 | false | false | false | false |
Xenoage/Zong | core/src/com/xenoage/zong/core/music/beam/Beam.kt | 1 | 6423 | package com.xenoage.zong.core.music.beam
import com.xenoage.utils.collections.checkIndex
import com.xenoage.utils.math.Fraction
import com.xenoage.utils.throwEx
import com.xenoage.zong.core.music.Voice
import com.xenoage.zong.core.music.WaypointPosition
import com.xenoage.zong.core.music.WaypointPosition.*
import com.xenoage.zong.core.music.beam.Beam.VerticalSpan.Other
import com.xenoage.zong.core.music.chord.Chord
import com.xenoage.zong.core.music.util.flagsCount
import com.xenoage.zong.core.position.MP
import com.xenoage.zong.core.position.MP.Companion.unknown
import com.xenoage.zong.core.position.MPElement
import kotlin.math.max
import kotlin.math.min
/**
* Class for a beam that connects two or more chords.
*
* A beam can be placed within a single staff (the common case) or
* cross two staves (e.g. in a piano score). When crossing two staves,
* the beam belongs to the staff of the first chord.
*/
class Beam(
/** The waypoints in this beam */
val waypoints: List<BeamWaypoint>
) : MPElement {
init { check() }
//cache
private var _verticalSpan: VerticalSpan? = null
private var _upperStaffIndex = -1
private var _lowerStaffIndex = -1
val start: BeamWaypoint
get() = waypoints.first()
val stop: BeamWaypoint
get() = waypoints.last()
/** The maximum number of beam lines used in the this beam */
val maxLinesCount: Int
get() {
val minDuration = waypoints.asSequence().map{ it.chord.displayedDuration }.min() ?: throw IllegalStateException()
return minDuration.flagsCount
}
/**
* The parent of the beam is defined as the voice of the start of the beam.
*/
override val parent: Voice?
get() = waypoints.first().chord.parent
/**
* The [MP] of the beam is the same as the [MP] of the first chord in the beam.
*/
override val mp: MP?
get() = waypoints.first().chord.mp
/** Spread of this beam within a system. */
enum class VerticalSpan {
/** Beam within a single staff. */
SingleStaff,
/** Beam crossing two adjacent staves. */
CrossStaff,
/** Other span (not supported). */
Other
}
/** Gets the waypoint at the given index. */
operator fun get(waypointIndex: Int): BeamWaypoint =
waypoints[waypointIndex]
/**
* Checks the correctness of the beam:
* The beam must have at least one line
* It must have at least 2 chords, must exist in a single measure column
* and the chords must be sorted by beat.
*/
private fun check() {
check(maxLinesCount > 0, { "A beam must have at least one line" })
check(waypoints.size >=2, { "At least two chords are needed to create a beam!" })
//check single column and beat order
var lastBeat: Fraction? = null
var wasLastChordGrace = false
val startMeasure = mp?.measure
if (startMeasure != unknown) {
for (wp in waypoints) {
val chordMP = wp.chord.mp ?: continue //if unknown MP, this waypoint can not be checked
val (_, wpMeasure, _, beat) = chordMP
//check, if all chords are in the same measure column
if (wpMeasure != startMeasure)
throw IllegalArgumentException("A beam may only span over one measure column")
//check, if chords are sorted by beat.
//for grace notes, the same beat is ok.
if (lastBeat != null && beat != null) {
val compare = beat.compareTo(lastBeat)
if (false == wasLastChordGrace && compare <= 0 || wasLastChordGrace && compare < 0)
throw IllegalArgumentException("Beamed chords must be sorted by beat")
}
lastBeat = beat
wasLastChordGrace = wp.chord.isGrace
}
}
}
/** The number of chords in this beam. */
val size: Int = waypoints.size
/** Gets the position of the given waypoint. */
fun getWaypointPosition(wp: BeamWaypoint): WaypointPosition =
getWaypointPosition(wp.chord)
/** Gets the position of the given chord. */
fun getWaypointPosition(chord: Chord): WaypointPosition {
return when (getWaypointIndex(chord)) {
0 -> Start
waypoints.size - 1 -> Stop
else -> Continue
}
}
/** Gets the index of the given chord within the beam. */
fun getWaypointIndex(chord: Chord): Int =
waypoints.indexOfFirst { it.chord === chord }.checkIndex { "Given chord is not part of this beam." }
/** The vertical spanning of this beam. */
val verticalSpan: VerticalSpan
get() {
if (_verticalSpan == null)
computeSpan()
return _verticalSpan!!
}
/** The index of the topmost staff this beam belongs to. */
val getUpperStaffIndex: Int
get() {
if (_upperStaffIndex == -1)
computeSpan()
return _upperStaffIndex
}
/** The index of the bottommost staff this beam belongs to. */
val getLowerStaffIndex: Int
get() {
if (_lowerStaffIndex == -1)
computeSpan()
return _lowerStaffIndex
}
/** Replaces the given old chord with the given new one. */
fun replaceChord(oldChord: Chord, newChord: Chord) {
for (i in waypoints.indices) {
if (waypoints[i].chord === oldChord) {
oldChord.beam = null
waypoints[i].chord = newChord
newChord.beam = this
computeSpan()
return
}
}
throwEx("Given chord is not part of this beam")
}
/**
* Returns true, if a beam lines subdivision ends at the chord
* with the given index.
*/
fun isEndOfSubdivision(chordIndex: Int): Boolean =
waypoints[chordIndex].subdivision
/** Gets the chord with the given index. */
fun getChord(chordIndex: Int): Chord =
waypoints[chordIndex].chord
/** Computes the vertical span of this beam. */
private fun computeSpan() {
var minStaffIndex = Int.MAX_VALUE
var maxStaffIndex = Int.MIN_VALUE
//check if the beam spans over a single staff or two adjacent staves or more
for (waypoint in waypoints) {
val chord = waypoint.chord
val mpChord = chord.mp
if (mpChord == null || mpChord.staff == unknown) { //unknown MP? then we can not compute this beam
_verticalSpan = Other
_upperStaffIndex = unknown
_lowerStaffIndex = unknown
return
}
minStaffIndex = min(minStaffIndex, mpChord.staff)
maxStaffIndex = max(maxStaffIndex, mpChord.staff)
}
var verticalSpan = Other
if (maxStaffIndex == minStaffIndex)
verticalSpan = VerticalSpan.SingleStaff
else if (maxStaffIndex - minStaffIndex == 1)
verticalSpan = VerticalSpan.CrossStaff
_verticalSpan = verticalSpan
_upperStaffIndex = minStaffIndex
_lowerStaffIndex = maxStaffIndex
}
companion object {
operator fun invoke(chords: List<Chord>) =
Beam(chords.map { BeamWaypoint(it) })
}
}
| agpl-3.0 | 1ba65610b6657062142c512ae02d60e4 | 28.599078 | 116 | 0.699206 | 3.626765 | false | false | false | false |
randombyte-developer/lottery | src/main/kotlin/de/randombyte/lottery/Lottery.kt | 1 | 8182 | package de.randombyte.lottery
import com.google.inject.Inject
import de.randombyte.kosp.PlayerExecutedCommand
import de.randombyte.kosp.config.ConfigManager
import de.randombyte.kosp.extensions.getUser
import de.randombyte.kosp.extensions.gray
import de.randombyte.kosp.extensions.toText
import de.randombyte.kosp.getServiceOrFail
import de.randombyte.lottery.commands.AddPotCommand
import de.randombyte.lottery.commands.BuyTicketCommand
import de.randombyte.lottery.commands.InfoCommand
import ninja.leaping.configurate.commented.CommentedConfigurationNode
import ninja.leaping.configurate.loader.ConfigurationLoader
import org.bstats.sponge.Metrics
import org.slf4j.Logger
import org.spongepowered.api.Sponge
import org.spongepowered.api.command.CommandResult
import org.spongepowered.api.command.args.CommandContext
import org.spongepowered.api.command.args.GenericArguments.integer
import org.spongepowered.api.command.args.GenericArguments.optional
import org.spongepowered.api.command.spec.CommandSpec
import org.spongepowered.api.config.DefaultConfig
import org.spongepowered.api.entity.living.player.Player
import org.spongepowered.api.event.Listener
import org.spongepowered.api.event.cause.Cause
import org.spongepowered.api.event.cause.EventContext
import org.spongepowered.api.event.game.GameReloadEvent
import org.spongepowered.api.event.game.state.GameInitializationEvent
import org.spongepowered.api.plugin.Plugin
import org.spongepowered.api.plugin.PluginContainer
import org.spongepowered.api.scheduler.Task
import org.spongepowered.api.service.economy.Currency
import org.spongepowered.api.service.economy.EconomyService
import org.spongepowered.api.text.Text
import java.math.BigDecimal
import java.time.Duration
import java.time.Instant
import java.util.*
import java.util.concurrent.TimeUnit
@Plugin(id = Lottery.ID, name = Lottery.NAME, version = Lottery.VERSION, authors = [(Lottery.AUTHOR)])
class Lottery @Inject constructor(
val logger: Logger,
@DefaultConfig(sharedRoot = true) configLoader: ConfigurationLoader<CommentedConfigurationNode>,
pluginContainer: PluginContainer,
private val bstats: Metrics
) {
companion object {
const val ID = "lottery"
const val NAME = "Lottery"
const val VERSION = "2.0.2"
const val AUTHOR = "RandomByte"
const val ROOT_PERMISSION = ID
}
val configManager = ConfigManager(
configLoader = configLoader,
clazz = Config::class.java,
simpleTextSerialization = true,
simpleTextTemplateSerialization = true,
simpleDurationSerialization = true)
val PLUGIN_CAUSE: Cause = Cause.builder().append(pluginContainer).build(EventContext.empty())
// Set on startup in setDurationUntilDraw()
lateinit var nextDraw: Instant
@Listener
fun onInit(event: GameInitializationEvent) {
configManager.generate()
Sponge.getCommandManager().register(this, CommandSpec.builder()
.child(CommandSpec.builder()
.permission("$ROOT_PERMISSION.ticket.buy")
.executor(BuyTicketCommand(configManager, PLUGIN_CAUSE))
.arguments(optional(integer("ticketAmount".toText())))
.build(), "buy")
.child(CommandSpec.builder()
.permission("$ROOT_PERMISSION.addpot")
.executor(AddPotCommand(configManager, PLUGIN_CAUSE))
.arguments(integer("amount".toText()))
.build(), "addpot")
.child(CommandSpec.builder()
.permission("$ROOT_PERMISSION.draw")
.executor(object : PlayerExecutedCommand() {
override fun executedByPlayer(player: Player, args: CommandContext): CommandResult {
draw(configManager.get())
return CommandResult.success()
}
})
.build(), "draw")
.child(CommandSpec.builder()
.executor(InfoCommand(configManager, durationUntilDraw = { getDurationUntilDraw() }))
.build(), "info")
.build(), "lottery", "lot")
val config = configManager.get()
// Manually set the duration because the draw task in resetTasks() may be executed too late
setDurationUntilDraw(config)
resetTasks(config)
logger.info("$NAME loaded: $VERSION")
}
@Listener
fun onReload(event: GameReloadEvent) {
configManager.generate()
resetTasks(configManager.get())
logger.info("Lottery reloaded!")
}
fun draw(config: Config) {
val ticketBuyers = config.internalData.boughtTickets.map { Collections.nCopies(it.value, it.key) }.flatten()
if (ticketBuyers.isEmpty()) {
broadcast("No tickets were bought, the draw is postponed!".gray())
return
}
Collections.shuffle(ticketBuyers) // Here comes the randomness
val winner = ticketBuyers.first()
playerWon(config, winner)
val drawEvent = DrawEvent(winner, config.calculatePot(), PLUGIN_CAUSE)
Sponge.getEventManager().post(drawEvent)
resetPot(config)
}
fun playerWon(config: Config, uuid: UUID) {
val playerName = uuid.getUser()?.name ?: "unknown"
val pot = config.calculatePot()
val defaultCurrency = getDefaultCurrency()
val message = config.messages.drawMessageBroadcast.apply(mapOf(
"winnerName" to playerName,
"pot" to pot,
"currencySymbol" to defaultCurrency.symbol,
"currencyName" to defaultCurrency.pluralDisplayName
)).build()
broadcast(message)
val economyService = getEconomyServiceOrFail()
economyService.getOrCreateAccount(uuid).get().deposit(economyService.defaultCurrency, BigDecimal(pot), PLUGIN_CAUSE)
}
fun resetPot(config: Config) {
val newInternalData = config.internalData.copy(pot = 0, boughtTickets = emptyMap())
val newConfig = config.copy(internalData = newInternalData)
configManager.save(newConfig)
}
fun getDurationUntilDraw(): Duration = Duration.between(Instant.now(), nextDraw)
fun setDurationUntilDraw(config : Config) {
nextDraw = Instant.ofEpochSecond(Instant.now().epochSecond + config.drawInterval.seconds)
}
fun resetTasks(config: Config) {
Sponge.getScheduler().getScheduledTasks(this).forEach { it.cancel() }
// Don't make the tasks async because it may happen that the broadcast and draw task are
// executed simultaneously. Irritating messages could be produced.
Task.builder()
.interval(config.drawInterval.seconds, TimeUnit.SECONDS)
.execute { ->
val currentConfig = configManager.get()
draw(currentConfig)
setDurationUntilDraw(currentConfig)
}.submit(this)
Task.builder()
.delay(5, TimeUnit.SECONDS) // First start: let economy plugin load
.interval(config.broadcasts.timedBroadcastInterval.seconds, TimeUnit.SECONDS)
.execute { ->
val currentConfig = configManager.get()
val currency = getDefaultCurrency()
val broadcastText = currentConfig.messages.broadcast.apply(mapOf(
"currencySymbol" to currency.symbol,
"currencyName" to currency.name,
"pot" to currentConfig.calculatePot()
)).build()
broadcast(broadcastText)
}.submit(this)
}
}
fun getEconomyServiceOrFail() = getServiceOrFail(EconomyService::class, "No economy plugin loaded!")
fun getDefaultCurrency(): Currency = getEconomyServiceOrFail().defaultCurrency
fun broadcast(text: Text) = Sponge.getServer().broadcastChannel.send(text) | gpl-2.0 | 33b6aeb33aac31e6728985663832744e | 41.180412 | 124 | 0.658396 | 4.964806 | false | true | false | false |
Dmedina88/SSB | generator-ssb/generators/templates/template-normal/app/src/main/kotlin/com/grayherring/temp/viewmodel/ViewModelFactory.kt | 1 | 911 | package <%= appPackage %>.viewmodel
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider.Factory
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
@Singleton
class ViewModelFactory @Inject
constructor(private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>) : Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
var creator: Provider<out ViewModel>? = creators[modelClass]
if (creator == null) {
for ((key, value) in creators) {
if (modelClass.isAssignableFrom(key)) {
creator = value
break
}
}
}
if (creator == null) {
throw IllegalArgumentException("unknown model class " + modelClass)
}
try {
return creator.get() as T
} catch (e: Exception) {
throw RuntimeException(e)
}
}
} | apache-2.0 | 518739dd1fdc473475d04739ba367847 | 26.636364 | 115 | 0.67618 | 4.443902 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/cargo/toolchain/tools/Rustup.kt | 2 | 7999 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.toolchain.tools
import com.intellij.execution.process.ProcessListener
import com.intellij.execution.process.ProcessOutput
import com.intellij.notification.NotificationType
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.runconfig.wasmpack.WasmPackBuildTaskProvider.Companion.WASM_TARGET
import org.rust.cargo.toolchain.RsToolchainBase
import org.rust.cargo.util.DownloadResult
import org.rust.ide.actions.InstallComponentAction
import org.rust.ide.actions.InstallTargetAction
import org.rust.ide.notifications.showBalloon
import org.rust.openapiext.*
import org.rust.stdext.RsResult
import org.rust.stdext.capitalized
import org.rust.stdext.unwrapOrThrow
import java.nio.file.Path
private val LOG: Logger = logger<Rustup>()
val RsToolchainBase.isRustupAvailable: Boolean get() = hasExecutable(Rustup.NAME)
fun RsToolchainBase.rustup(cargoProjectDirectory: Path): Rustup? {
if (!isRustupAvailable) return null
return Rustup(this, cargoProjectDirectory)
}
class Rustup(toolchain: RsToolchainBase, private val projectDirectory: Path) : RsTool(NAME, toolchain) {
data class Component(val name: String, val isInstalled: Boolean) {
companion object {
fun from(line: String): Component {
val name = line.substringBefore(' ')
val isInstalled = line.substringAfter(' ') in listOf("(installed)", "(default)")
return Component(name, isInstalled)
}
}
}
data class Target(val name: String, val isInstalled: Boolean) {
companion object {
fun from(line: String): Target {
val name = line.substringBefore(' ')
val isInstalled = line.substringAfter(' ') in listOf("(installed)", "(default)")
return Target(name, isInstalled)
}
}
}
private fun listComponents(): List<Component> =
createBaseCommandLine(
"component", "list",
workingDirectory = projectDirectory
).execute(toolchain.executionTimeoutInMilliseconds)?.stdoutLines?.map { Component.from(it) }.orEmpty()
private fun listTargets(): List<Target> =
createBaseCommandLine(
"target", "list",
workingDirectory = projectDirectory
).execute(toolchain.executionTimeoutInMilliseconds)?.stdoutLines?.map { Target.from(it) }.orEmpty()
fun downloadStdlib(owner: Disposable? = null, listener: ProcessListener? = null): DownloadResult<VirtualFile> {
// Sometimes we have stdlib but don't have write access to install it (for example, github workflow)
if (needInstallComponent("rust-src")) {
val commandLine = createBaseCommandLine(
"component", "add", "rust-src",
workingDirectory = projectDirectory
)
val downloadProcessOutput = if (owner == null) {
commandLine.execute(null)
} else {
commandLine.execute(owner, listener = listener).ignoreExitCode().unwrapOrThrow()
}
if (downloadProcessOutput?.isSuccess != true) {
val message = "rustup failed: `${downloadProcessOutput?.stderr ?: ""}`"
LOG.warn(message)
return DownloadResult.Err(message)
}
}
val sources = toolchain.rustc().getStdlibFromSysroot(projectDirectory)
?: return DownloadResult.Err("Failed to find stdlib in sysroot")
LOG.info("stdlib path: ${sources.path}")
fullyRefreshDirectory(sources)
return DownloadResult.Ok(sources)
}
fun downloadComponent(owner: Disposable, componentName: String): DownloadResult<Unit> =
createBaseCommandLine(
"component", "add", componentName,
workingDirectory = projectDirectory
).execute(owner).convertResult()
fun downloadTarget(owner: Disposable, targetName: String): DownloadResult<Unit> =
createBaseCommandLine(
"target", "add", targetName,
workingDirectory = projectDirectory
).execute(owner).convertResult()
fun activeToolchainName(): String? {
val output = createBaseCommandLine("show", "active-toolchain", workingDirectory = projectDirectory)
.execute(toolchain.executionTimeoutInMilliseconds) ?: return null
if (!output.isSuccess) return null
// Expected outputs:
// 1.48.0-x86_64-apple-darwin (default)
// stable-x86_64-apple-darwin (overridden by '/path/to/rust-toolchain.toml')
// nightly-x86_64-apple-darwin (directory override for '/path/to/override/dir')
return output.stdout.substringBefore("(").trim()
}
private fun RsProcessResult<ProcessOutput>.convertResult() =
when (this) {
is RsResult.Ok -> DownloadResult.Ok(Unit)
is RsResult.Err -> {
val message = "rustup failed: `${err.message}`"
LOG.warn(message)
DownloadResult.Err(message)
}
}
private fun needInstallComponent(componentName: String): Boolean {
val isInstalled = listComponents()
.find { (name, _) -> name.startsWith(componentName) }
?.isInstalled
?: return false
return !isInstalled
}
private fun needInstallTarget(targetName: String): Boolean {
val isInstalled = listTargets()
.find { it.name == targetName }
?.isInstalled
?: return false
return !isInstalled
}
companion object {
const val NAME: String = "rustup"
fun checkNeedInstallClippy(project: Project, cargoProjectDirectory: Path): Boolean =
checkNeedInstallComponent(project, cargoProjectDirectory, "clippy")
fun checkNeedInstallRustfmt(project: Project, cargoProjectDirectory: Path): Boolean =
checkNeedInstallComponent(project, cargoProjectDirectory, "rustfmt")
fun checkNeedInstallWasmTarget(project: Project, cargoProjectDirectory: Path): Boolean =
checkNeedInstallTarget(project, cargoProjectDirectory, WASM_TARGET)
// We don't want to install the component if:
// 1. It is already installed
// 2. We don't have Rustup
// 3. Rustup doesn't have this component
private fun checkNeedInstallComponent(
project: Project,
cargoProjectDirectory: Path,
componentName: String
): Boolean {
val rustup = project.toolchain?.rustup(cargoProjectDirectory) ?: return false
val needInstall = rustup.needInstallComponent(componentName)
if (needInstall) {
project.showBalloon(
"${componentName.capitalized()} is not installed",
NotificationType.ERROR,
InstallComponentAction(cargoProjectDirectory, componentName)
)
}
return needInstall
}
fun checkNeedInstallTarget(
project: Project,
cargoProjectDirectory: Path,
targetName: String
): Boolean {
val rustup = project.toolchain?.rustup(cargoProjectDirectory) ?: return false
val needInstall = rustup.needInstallTarget(targetName)
if (needInstall) {
project.showBalloon(
"$targetName target is not installed",
NotificationType.ERROR,
InstallTargetAction(cargoProjectDirectory, targetName)
)
}
return needInstall
}
}
}
| mit | e59688d7b568f4363e49846b16cc151b | 38.019512 | 115 | 0.64308 | 5.286847 | false | false | false | false |
deva666/anko | anko/library/static/commons/src/dialogs/AndroidDialogs.kt | 2 | 5837 | /*
* Copyright 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.
*/
@file:Suppress("NOTHING_TO_INLINE", "unused")
package org.jetbrains.anko
import android.app.AlertDialog
import android.app.Fragment
import android.app.ProgressDialog
import android.content.Context
import android.content.DialogInterface
inline fun AnkoContext<*>.alert(
message: String,
title: String? = null,
noinline init: (AlertBuilder<DialogInterface>.() -> Unit)? = null
) = ctx.alert(message, title, init)
inline fun Fragment.alert(
message: String,
title: String? = null,
noinline init: (AlertBuilder<DialogInterface>.() -> Unit)? = null
) = activity.alert(message, title, init)
fun Context.alert(
message: String,
title: String? = null,
init: (AlertBuilder<DialogInterface>.() -> Unit)? = null
): AlertBuilder<AlertDialog> {
return AndroidAlertBuilder(this).apply {
if (title != null) {
this.title = title
}
this.message = message
if (init != null) init()
}
}
inline fun AnkoContext<*>.alert(
message: Int,
title: Int? = null,
noinline init: (AlertBuilder<DialogInterface>.() -> Unit)? = null
) = ctx.alert(message, title, init)
inline fun Fragment.alert(
message: Int,
title: Int? = null,
noinline init: (AlertBuilder<DialogInterface>.() -> Unit)? = null
) = activity.alert(message, title, init)
fun Context.alert(
messageResource: Int,
titleResource: Int? = null,
init: (AlertBuilder<DialogInterface>.() -> Unit)? = null
): AlertBuilder<DialogInterface> {
return AndroidAlertBuilder(this).apply {
if (titleResource != null) {
this.titleResource = titleResource
}
this.messageResource = messageResource
if (init != null) init()
}
}
inline fun AnkoContext<*>.alert(noinline init: AlertBuilder<DialogInterface>.() -> Unit) = ctx.alert(init)
inline fun Fragment.alert(noinline init: AlertBuilder<DialogInterface>.() -> Unit) = activity.alert(init)
fun Context.alert(init: AlertBuilder<DialogInterface>.() -> Unit): AlertBuilder<DialogInterface> {
return AndroidAlertBuilder(this).apply { init() }
}
inline fun AnkoContext<*>.progressDialog(
message: Int? = null,
title: Int? = null,
noinline init: (ProgressDialog.() -> Unit)? = null
) = ctx.progressDialog(message, title, init)
inline fun Fragment.progressDialog(
message: Int? = null,
title: Int? = null,
noinline init: (ProgressDialog.() -> Unit)? = null
) = activity.progressDialog(message, title, init)
fun Context.progressDialog(
message: Int? = null,
title: Int? = null,
init: (ProgressDialog.() -> Unit)? = null
) = progressDialog(false, message?.let { getString(it) }, title?.let { getString(it) }, init)
inline fun AnkoContext<*>.indeterminateProgressDialog(
message: Int? = null,
title: Int? = null,
noinline init: (ProgressDialog.() -> Unit)? = null
) = ctx.indeterminateProgressDialog(message, title, init)
inline fun Fragment.indeterminateProgressDialog(
message: Int? = null,
title: Int? = null,
noinline init: (ProgressDialog.() -> Unit)? = null
) = activity.progressDialog(message, title, init)
fun Context.indeterminateProgressDialog(
message: Int? = null,
title: Int? = null,
init: (ProgressDialog.() -> Unit)? = null
) = progressDialog(true, message?.let { getString(it) }, title?.let { getString(it) }, init)
inline fun AnkoContext<*>.progressDialog(
message: String? = null,
title: String? = null,
noinline init: (ProgressDialog.() -> Unit)? = null
) = ctx.progressDialog(message, title, init)
inline fun Fragment.progressDialog(
message: String? = null,
title: String? = null,
noinline init: (ProgressDialog.() -> Unit)? = null
) = activity.progressDialog(message, title, init)
fun Context.progressDialog(
message: String? = null,
title: String? = null,
init: (ProgressDialog.() -> Unit)? = null
) = progressDialog(false, message, title, init)
inline fun AnkoContext<*>.indeterminateProgressDialog(
message: String? = null,
title: String? = null,
noinline init: (ProgressDialog.() -> Unit)? = null
) = ctx.indeterminateProgressDialog(message, title, init)
inline fun Fragment.indeterminateProgressDialog(
message: String? = null,
title: String? = null,
noinline init: (ProgressDialog.() -> Unit)? = null
) = activity.indeterminateProgressDialog(message, title, init)
fun Context.indeterminateProgressDialog(
message: String? = null,
title: String? = null,
init: (ProgressDialog.() -> Unit)? = null
) = progressDialog(true, message, title, init)
private fun Context.progressDialog(
indeterminate: Boolean,
message: String? = null,
title: String? = null,
init: (ProgressDialog.() -> Unit)? = null
) = ProgressDialog(this).apply {
isIndeterminate = indeterminate
if (!indeterminate) setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
if (message != null) setMessage(message)
if (title != null) setTitle(title)
if (init != null) init()
show()
} | apache-2.0 | bc8bce4f40f3381b826ae7228f6b7452 | 32.551724 | 106 | 0.654103 | 4.288758 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/actor/ActorContextMenu.kt | 1 | 6280 | /*
* Copyright (C) 2015 yvolk (Yuri Volkov), http://yurivolkov.com
*
* 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.andstatus.app.actor
import android.view.ContextMenu
import android.view.ContextMenu.ContextMenuInfo
import android.view.MenuItem
import android.view.View
import org.andstatus.app.R
import org.andstatus.app.activity.ActivityViewItem
import org.andstatus.app.note.NoteEditorContainer
import org.andstatus.app.origin.Origin
import org.andstatus.app.timeline.ContextMenuHeader
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.StringUtil
import org.andstatus.app.view.MyContextMenu
open class ActorContextMenu(val menuContainer: NoteEditorContainer, menuGroup: Int) : MyContextMenu(menuContainer.getActivity(), menuGroup) {
override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenuInfo?) {
val method = "onCreateContextMenu"
saveContextOfSelectedItem(v)
if (getViewItem().isEmpty) {
return
}
val actor = getViewItem().actor
if (!getMyContext().accounts.succeededForSameUser(actor).contains(getSelectedActingAccount())) {
setSelectedActingAccount(
getMyContext().accounts.firstOtherSucceededForSameUser(actor, getActingAccount())
)
}
var order = 0
try {
ContextMenuHeader(getActivity(), menu)
.setTitle(actor.toActorTitle())
.setSubtitle(getActingAccount().getAccountName())
val shortName = actor.getUsername()
if (actor.groupType == GroupType.LIST_MEMBERS) {
ActorContextMenuItem.LIST_MEMBERS.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.list_members, shortName))
} else if (actor.groupType.isGroupLike) {
ActorContextMenuItem.GROUP_NOTES.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.group_notes, shortName))
} else if (actor.isIdentified()) {
ActorContextMenuItem.NOTES_BY_ACTOR.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.menu_item_user_messages, shortName))
if (actor.origin.originType.hasListsOfUser) {
ActorContextMenuItem.LISTS.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.lists_of_user, shortName))
}
ActorContextMenuItem.FRIENDS.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.friends_of, shortName))
ActorContextMenuItem.FOLLOWERS.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.followers_of, shortName))
if (getActingAccount().actor.notSameUser(actor)) {
if (getActingAccount().isFollowing(actor)) {
ActorContextMenuItem.STOP_FOLLOWING.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.menu_item_stop_following_user, shortName))
} else {
ActorContextMenuItem.FOLLOW.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.menu_item_follow_user, shortName))
}
if (menuContainer.getNoteEditor()?.isVisible() == false) {
ActorContextMenuItem.POST_TO.addTo(menu, menuGroup, order++,
StringUtil.format(getActivity(), R.string.post_to, shortName))
}
}
when (getMyContext().accounts.succeededForSameUser(actor).size) {
0, 1 -> {
}
2 -> ActorContextMenuItem.ACT_AS_FIRST_OTHER_ACCOUNT.addTo(menu, menuGroup, order++,
StringUtil.format(
getActivity(), R.string.menu_item_act_as_user,
getMyContext().accounts
.firstOtherSucceededForSameUser(actor, getActingAccount())
.getShortestUniqueAccountName()))
else -> ActorContextMenuItem.ACT_AS.addTo(menu, menuGroup, order++, R.string.menu_item_act_as)
}
}
if (actor.canGetActor()) {
ActorContextMenuItem.GET_ACTOR.addTo(menu, menuGroup, order++, R.string.get_user)
}
} catch (e: Exception) {
MyLog.i(this, method, e)
}
}
fun onContextItemSelected(item: MenuItem): Boolean {
val ma = getActingAccount()
return if (ma.isValid) {
val contextMenuItem: ActorContextMenuItem = ActorContextMenuItem.fromId(item.getItemId())
MyLog.v(this) {
("onContextItemSelected: " + contextMenuItem + "; account="
+ ma.getAccountName() + "; actor=" + getViewItem().actor.uniqueName)
}
contextMenuItem.execute(this)
} else {
false
}
}
fun getViewItem(): ActorViewItem {
if (mViewItem.isEmpty) {
return ActorViewItem.EMPTY
}
return if (mViewItem is ActivityViewItem) {
getViewItem(mViewItem as ActivityViewItem)
} else mViewItem as ActorViewItem
}
protected open fun getViewItem(activityViewItem: ActivityViewItem): ActorViewItem {
return activityViewItem.getObjActorItem()
}
fun getOrigin(): Origin {
return getViewItem().actor.origin
}
}
| apache-2.0 | b42c606d50d2928cad418040b83f11c2 | 46.938931 | 141 | 0.605414 | 5.072698 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/debugger/remote/MobClient.kt | 2 | 5703 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.debugger.remote
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.openapi.application.ApplicationManager
import com.tang.intellij.lua.debugger.LogConsoleType
import com.tang.intellij.lua.debugger.remote.commands.DebugCommand
import com.tang.intellij.lua.debugger.remote.commands.DefaultCommand
import java.io.IOException
import java.io.OutputStreamWriter
import java.net.SocketException
import java.nio.ByteBuffer
import java.nio.channels.SocketChannel
import java.nio.charset.Charset
import java.util.*
import java.util.regex.Pattern
class MobClient(private val socketChannel: SocketChannel, private val listener: MobServerListener) {
private var isStopped: Boolean = false
private val commands = LinkedList<DebugCommand>()
private var currentCommandWaitForResp: DebugCommand? = null
private var streamWriter: OutputStreamWriter? = null
private val socket = socketChannel.socket()
private val receiveBufferSize = 1024 * 1024
init {
socket.receiveBufferSize = receiveBufferSize
ApplicationManager.getApplication().executeOnPooledThread {
doReceive()
}
ApplicationManager.getApplication().executeOnPooledThread {
doSend()
}
}
private fun doSend() {
try {
streamWriter = OutputStreamWriter(socket.getOutputStream(), Charset.forName("UTF-8"))
while (socket.isConnected) {
if (isStopped) break
var command: DebugCommand
while (commands.size > 0 && currentCommandWaitForResp == null) {
if (currentCommandWaitForResp == null) {
command = commands.poll()
command.debugProcess = listener.process
command.write(this)
streamWriter!!.write("\n")
streamWriter!!.flush()
if (command.getRequireRespLines() > 0)
currentCommandWaitForResp = command
}
}
Thread.sleep(5)
}
} catch (e: SocketException) {
//e.message?.let { listener.error(it) }
} catch (e: Exception) {
e.message?.let { listener.error(it) }
} finally {
onClosed()
}
}
private fun doReceive() {
try {
var readSize: Int
val bf = ByteBuffer.allocate(receiveBufferSize)
while (!isStopped) {
readSize = socketChannel.read(bf)
if (readSize > 0) {
var begin = 0
for (i in 1..readSize + 1) {
if (bf[i - 1].toInt() == '\n'.toInt()) {
onResp(String(bf.array(), begin, i))
begin = i
}
}
if (begin < readSize) {
onResp(String(bf.array(), begin, readSize))
}
bf.clear()
}
}
} catch (e: IOException) {
onSocketClosed()
} catch (e: Exception) {
e.message?.let { listener.error(it) }
}
}
private fun onResp(data: String) {
val cmd = currentCommandWaitForResp
if (cmd != null) {
val eat = cmd.handle(data)
if (eat > 0) {
if (cmd.isFinished())
currentCommandWaitForResp = null
return
}
}
val pattern = Pattern.compile("(\\d+) (\\w+)( (.+))?")
val matcher = pattern.matcher(data)
if (matcher.find()) {
val code = Integer.parseInt(matcher.group(1))
//String status = matcher.group(2);
val context = matcher.group(4)
listener.handleResp(this, code, context)
}
}
private fun onSocketClosed() {
listener.onDisconnect(this)
}
@Throws(IOException::class)
fun write(data: String) {
streamWriter!!.write(data)
//println("send:" + data)
}
fun stop() {
try {
streamWriter?.write("done\n")
} catch (ignored: IOException) {
}
currentCommandWaitForResp = null
try {
socket.close()
} catch (ignored: Exception) {
}
onClosed()
isStopped = true
}
private fun onClosed() {
if (!isStopped) {
isStopped = true
listener.println("Disconnected.", LogConsoleType.NORMAL, ConsoleViewContentType.SYSTEM_OUTPUT)
}
}
fun sendAddBreakpoint(file: String, line: Int) {
addCommand("SETB $file $line")
}
fun sendRemoveBreakpoint(file: String, line: Int) {
addCommand("DELB $file $line")
}
fun addCommand(command: String, rl: Int = 1) {
addCommand(DefaultCommand(command, rl))
}
fun addCommand(command: DebugCommand) {
commands.add(command)
}
} | apache-2.0 | 44b205f5f5b3bfaa3997bfef2dfb7b30 | 31.225989 | 106 | 0.566018 | 4.824873 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/parser/LexerState.kt | 1 | 8513 | package org.jetbrains.haskell.parser
import com.intellij.psi.tree.IElementType
import org.jetbrains.grammar.HaskellLexerTokens
import java.util.Arrays
import java.util.HashSet
import java.util.ArrayList
import org.jetbrains.haskell.parser.lexer.HaskellLexer
import com.intellij.psi.TokenType
import org.jetbrains.haskell.parser.token.NEW_LINE
import org.jetbrains.haskell.parser.token.END_OF_LINE_COMMENT
import org.jetbrains.haskell.parser.token.BLOCK_COMMENT
import java.io.PrintStream
import com.intellij.lang.PsiBuilder
import com.intellij.lang.WhitespaceSkippedCallback
import org.jetbrains.grammar.dumb.NonTerminalTree
import org.jetbrains.grammar.dumb.TerminalTree
import org.jetbrains.haskell.parser.token.PRAGMA
import org.jetbrains.haskell.parser.token.COMMENTS
val INDENT_TOKENS = HashSet<IElementType>(Arrays.asList(
HaskellLexerTokens.DO,
HaskellLexerTokens.OF,
HaskellLexerTokens.LET,
HaskellLexerTokens.WHERE))
class IntStack(val indent: Int,
val parent: IntStack?)
public fun getCachedTokens(lexer: HaskellLexer, stream: PrintStream?): CachedTokens {
val tokens = ArrayList<IElementType>()
val starts = ArrayList<Int>()
val indents = ArrayList<Int>()
val lineStarts = ArrayList<Boolean>()
var currentIndent = 0
var isLineStart = true
stream?.println("-------------------")
while (lexer.getTokenType() != null) {
val tokenType = lexer.getTokenType()
if (!COMMENTS.contains(tokenType) && tokenType != TokenType.WHITE_SPACE) {
if (tokenType == NEW_LINE) {
currentIndent = 0
isLineStart = true
stream?.println()
} else {
tokens.add(tokenType)
starts.add(lexer.getTokenStart())
indents.add(currentIndent)
lineStarts.add(isLineStart)
isLineStart = false
stream?.print("${tokenType} ")
}
}
if (tokenType != NEW_LINE) {
for (ch in lexer.getTokenText()) {
if (ch == '\t') {
currentIndent += 8;
} else {
currentIndent += 1;
}
}
}
lexer.advance();
}
stream?.println("-------------------")
return CachedTokens(tokens, starts, indents, lineStarts)
}
public fun getCachedTokens(builder: PsiBuilder): CachedTokens {
val tokens = ArrayList<IElementType>()
val starts = ArrayList<Int>()
val indents = ArrayList<Int>()
val lineStarts = ArrayList<Boolean>()
var currentIndent = 0
var isLineStart = true
builder.setWhitespaceSkippedCallback(object : WhitespaceSkippedCallback {
override fun onSkip(type: IElementType?, start: Int, end: Int) {
if (type == NEW_LINE) {
currentIndent = 0
isLineStart = true
} else {
val charSequence = builder.getOriginalText()
for (i in start..(end-1)) {
if (charSequence.charAt(i) == '\t') {
currentIndent += 8;
} else {
currentIndent += 1;
}
}
}
}
})
while (builder.getTokenType() != null) {
tokens.add(builder.getTokenType())
starts.add(builder.getCurrentOffset())
indents.add(currentIndent)
lineStarts.add(isLineStart)
isLineStart = false
currentIndent += builder.getTokenText()!!.length()
builder.advanceLexer()
}
return CachedTokens(tokens, starts, indents, lineStarts)
}
public fun newLexerState(tokens: CachedTokens): LexerState {
if (tokens.tokens.firstOrNull() == HaskellLexerTokens.MODULE) {
return LexerState(tokens, 0, 0, null, null)
} else {
return LexerState(tokens, 0, 0, null, IntStack(0, null))
}
}
public class CachedTokens(val tokens: List<IElementType>,
val starts: List<Int>,
val indents: ArrayList<Int>,
val lineStart: ArrayList<Boolean>) {
}
public class LexerState(val tokens: CachedTokens,
val position: Int,
val readedLexemNumber: Int,
val currentToken: HaskellTokenType?,
val indentStack: IntStack?) {
fun match(token: HaskellTokenType): Boolean {
if (currentToken != null) {
return currentToken == token
}
if (position < tokens.tokens.size() && tokens.tokens[position] == token) {
return true
}
return false
}
fun next(): LexerState {
if (currentToken != null) {
if (currentToken == HaskellLexerTokens.VCCURLY && indentStack != null) {
return checkIndent(position)
}
return LexerState(tokens, position, readedLexemNumber + 1, null, indentStack)
}
if (position == tokens.tokens.size()) {
return last()
}
if (tokens.tokens[position] == HaskellLexerTokens.OCURLY) {
return LexerState(tokens,
position + 1,
readedLexemNumber + 1,
null,
IntStack(-1, indentStack))
}
val nextPosition = position + 1
if (nextPosition == tokens.tokens.size()) {
return last()
}
if (INDENT_TOKENS.contains(tokens.tokens[position]) &&
tokens.tokens[nextPosition] != HaskellLexerTokens.OCURLY) {
val indent = tokens.indents[nextPosition]
return LexerState(tokens,
nextPosition,
readedLexemNumber + 1,
HaskellLexerTokens.VOCURLY,
IntStack(indent, indentStack))
}
return checkIndent(nextPosition)
}
private fun last(): LexerState {
if (indentStack != null) {
return LexerState(tokens,
tokens.tokens.size(),
readedLexemNumber + 1,
HaskellLexerTokens.VCCURLY,
indentStack.parent)
} else {
return LexerState(tokens, tokens.tokens.size(), readedLexemNumber, null, null)
}
}
private fun checkIndent(position: Int): LexerState {
if (position == tokens.tokens.size()) {
return last()
}
if (tokens.lineStart[position]) {
val indent = tokens.indents[position]
if (indentStack != null) {
if (indentStack.indent == indent) {
return LexerState(tokens, position, readedLexemNumber + 1, HaskellLexerTokens.SEMI, indentStack)
} else if (indentStack.indent < indent) {
return checkCurly(position)
} else {
return LexerState(tokens, position, readedLexemNumber + 1, HaskellLexerTokens.VCCURLY, indentStack.parent)
}
} else {
//if (0 == indent) {
// return LexerState(tokens, position, lexemNumber + 1, HaskellLexerTokens.SEMI, indentStack)
//} else {
// return checkCurly(position)
//}
}
}
return checkCurly(position)
}
private fun checkCurly(nextPosition: Int): LexerState {
if (tokens.tokens[nextPosition] == HaskellLexerTokens.CCURLY) {
if (indentStack!!.indent > -1) {
return LexerState(tokens, nextPosition - 1, readedLexemNumber + 1, HaskellLexerTokens.VCCURLY, indentStack.parent)
}
return LexerState(tokens, nextPosition, readedLexemNumber + 1, null, indentStack.parent)
}
return LexerState(tokens, nextPosition, readedLexemNumber + 1, null, indentStack)
}
fun dropIndent() = LexerState(
tokens,
position,
readedLexemNumber + 1,
HaskellLexerTokens.VCCURLY,
indentStack?.parent)
fun getToken(): IElementType? {
if (currentToken != null) {
return currentToken
}
if (position < tokens.tokens.size()) {
return tokens.tokens[position];
}
return null;
}
fun eof(): Boolean {
return currentToken == null && position == tokens.tokens.size();
}
} | apache-2.0 | 80fe5c2c397cae72da9a942651bfbab3 | 32.920319 | 130 | 0.566075 | 5.153148 | false | false | false | false |
mildsauce45/spiffy | src/main/kotlin/com/pinchotsoft/spiffy/mapping/ResultContext.kt | 1 | 1413 | package com.pinchotsoft.spiffy.mapping
import com.pinchotsoft.spiffy.ReflectionHelper
import com.pinchotsoft.spiffy.isPrimitive
import java.lang.reflect.Constructor
import java.sql.ResultSet
class ResultContext(rs: ResultSet, clazz: Class<*>) {
private val columns: List<String>
private val calculatedColumnAvailability = HashMap<String, Boolean>()
private var _constructor: Constructor<*>? = null
private var _isDataClass = false
val isPrimitiveType: Boolean
val isDataClass: Boolean
get() = _isDataClass
val constructor: Constructor<*>?
get() = _constructor
init {
val metadata = rs.metaData
columns = (1..metadata.columnCount).map { metadata.getColumnName(it) }
isPrimitiveType = isPrimitive(clazz)
if (!isPrimitiveType) {
val cons = ReflectionHelper.getClassConstructor(clazz, true)
if (cons != null) {
_constructor = cons
} else {
_constructor = ReflectionHelper.getClassConstructor(clazz, false)!!
_isDataClass = true
}
}
}
fun hasColumn(columnName: String): Boolean {
if (!calculatedColumnAvailability.containsKey(columnName))
calculatedColumnAvailability.put(columnName, columns.any { it.equals(columnName, true) })
return calculatedColumnAvailability[columnName]!!
}
} | mit | 984035b1bb9e93dde1c44bee9fe03636 | 29.085106 | 101 | 0.65959 | 4.975352 | false | false | false | false |
Gnar-Team/Gnar-bot | src/main/kotlin/xyz/gnarbot/gnar/commands/music/JumpCommand.kt | 1 | 3174 | package xyz.gnarbot.gnar.commands.music
import xyz.gnarbot.gnar.commands.*
import xyz.gnarbot.gnar.commands.template.CommandTemplate
import xyz.gnarbot.gnar.commands.template.annotations.Description
import xyz.gnarbot.gnar.utils.Utils
import java.time.Duration
@Command(
aliases = ["jump", "seek"],
usage = "(to|forward|backward) (time)",
description = "Set the time marker of the music playback."
)
@BotInfo(
id = 65,
category = Category.MUSIC,
scope = Scope.VOICE
)
class JumpCommand : CommandTemplate() {
@Description("Set the time marker of the player.")
fun to(context: Context, duration: Duration) {
val manager = context.bot.players.getExisting(context.guild)!!
manager.player.playingTrack.position = duration.toMillis().coerceIn(0, manager.player.playingTrack.duration)
context.send().info("The position of the track has been set to ${Utils.getTimestamp(manager.player.playingTrack.position)}.").queue()
}
@Description("Move the time marker forward.")
fun forward(context: Context, duration: Duration) {
val manager = context.bot.players.getExisting(context.guild)!!
manager.player.playingTrack.position = (manager.player.playingTrack.position + duration.toMillis())
.coerceIn(0, manager.player.playingTrack.duration)
context.send().info("The position of the track has been set to ${Utils.getTimestamp(manager.player.playingTrack.position)}.").queue()
}
@Description("Move the time marker backward.")
fun backward(context: Context, duration: Duration) {
val manager = context.bot.players.getExisting(context.guild)!!
manager.player.playingTrack.position = (manager.player.playingTrack.position - duration.toMillis())
.coerceIn(0, manager.player.playingTrack.duration)
context.send().embed("Jump Backward") {
desc { "The position of the track has been set to ${Utils.getTimestamp(manager.player.playingTrack.position)}." }
}.action().queue()
}
override fun execute(context: Context, label: String, args: Array<out String>) {
val manager = context.bot.players.getExisting(context.guild)
if (manager == null) {
context.send().error("There's no music player in this guild.\n$PLAY_MESSAGE").queue()
return
}
val botChannel = context.selfMember.voiceState?.channel
if (botChannel == null) {
context.send().error("The bot is not currently in a channel.\n$PLAY_MESSAGE").queue()
return
}
if (context.voiceChannel != botChannel) {
context.send().error("You're not in the same channel as the context.bot.").queue()
return
}
if (manager.player.playingTrack == null) {
context.send().error("The player is not playing anything.").queue()
return
}
if (!manager.player.playingTrack.isSeekable) {
context.send().error("You can't change the time marker on this track.").queue()
return
}
super.execute(context, label, args)
}
}
| mit | 81055b18853c39f58c80c2c2ceba40e0 | 38.185185 | 141 | 0.654694 | 4.414465 | false | false | false | false |
EmpowerOperations/getoptk | src/test/kotlin/com/empowerops/getoptk/ErrorExamples.kt | 1 | 3541 | package com.empowerops.getoptk
import junit.framework.AssertionFailedError
import org.assertj.core.api.Assertions.*
import org.junit.Test
import java.lang.UnsupportedOperationException
class ErrorExamples {
@Test fun `when two cli classes have args that map to the same name should get configuration error`(){
//setup & act
val ex = assertThrows<ConfigurationException> {
emptyArray<String>().parsedAs("prog") { DuplicateInferredNamesArgBundle() }
}
//assert
assertThat(ex.messages.single().message).isEqualTo(
"the options 'val excess: String by getValueOpt()' and 'val extra: String by getValueOpt()' have the same short name 'e'."
)
}
class DuplicateInferredNamesArgBundle : CLI(){
val extra: String by getValueOpt<String>()
val excess: String by getValueOpt()
}
@Test fun `when using the wrong type to destructure should generate unconsumed tokens warnings`(){
//setup & act
val ex = assertThrows<ParseFailedException>{
arrayOf("--eh", "hello_world", "1.0").parsedAs("prog") { ConfusedTypeArgBundle() }
}
//assert
assertThat(ex.message).isEqualTo(
"""Failed to parse value for val eh: A by getValueOpt()
|prog --eh hello_world 1.0
|at: ~~~
|java.lang.NumberFormatException: For input string: "1.0"
""".trimMargin()
)
assertThat(ex.cause).isInstanceOf(NumberFormatException::class.java)
}
data class A(val name: String, val x: Int)
data class B(val name: String, val x: Double)
class ConfusedTypeArgBundle: CLI(){
val eh: A by getOpt()
}
@Test fun `when attempting to use the wrong option name should generate nice error messages`(){
//setup
val args = arrayOf("--name", "bob")
//act
val ex = assertThrows<ParseFailedException> { args.parsedAs("prog") { ValueOfAbleCLI() } }
//assert
assertThat(ex.message).isEqualTo(
"""unknown option 'name', expected 'parsable', 'help'
|prog --name bob
|at: ~~~~
""".trimMargin()
)
}
class ValueOfAbleCLI : CLI(){
val parsable: ValueOfAble by getValueOpt()
}
data class ValueOfAble(val name: String) {
companion object {
fun valueOf(str: String) = ValueOfAble(str + "_thingy")
}
}
@Test fun `when custom converter throws should recover and display proper error message`(){
//setup
val args = arrayOf("--problem", "sam")
//act
val ex = assertThrows<ParseFailedException> { args.parsedAs("prog") { BadConvertingCLI() }}
//assert
assertThat(ex.message).isEqualTo(
"""Failed to parse value for val problem: String by getValueOpt()
|prog --problem sam
|at: ~~~
|java.lang.UnsupportedOperationException: no sam's allowed!
""".trimMargin()
)
assertThat(ex.cause).isInstanceOf(UnsupportedOperationException::class.java)
}
class BadConvertingCLI: CLI(){
val problem: String by getValueOpt {
converter = { when(it){
"sam" -> throw UnsupportedOperationException("no sam's allowed!")
"bob" -> "bobbo"
else -> TODO()
}}
}
}
}
| apache-2.0 | b26c9e2a397d435087f2cf64713c7822 | 32.72381 | 138 | 0.575261 | 4.837432 | false | false | false | false |
Shockah/Godwit | core/src/pl/shockah/godwit/geom/polygon/ClosedPolygon.kt | 1 | 2888 | package pl.shockah.godwit.geom.polygon
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import pl.shockah.godwit.LazyDirty
import pl.shockah.godwit.ObservableList
import pl.shockah.godwit.geom.*
class ClosedPolygon(
points: List<Vec2>
) : Polygon(points), Shape.Filled {
var triangulator: Triangulator = BasicTriangulator()
private val dirtyTriangles = LazyDirty {
triangulator.triangulate(points) ?: throw IllegalStateException("Cannot triangulate polygon.")
}
val triangles: List<Triangle> by dirtyTriangles
override val lines: List<Line>
get() {
val result = mutableListOf<Line>()
for (i in 0 until points.size) {
result += Line(points[i], points[(i + 1) % points.size])
}
return result
}
constructor(vararg points: Vec2) : this(points.toList())
init {
super.points.listeners += object : ObservableList.ChangeListener<MutableVec2> {
override fun onAddedToList(element: MutableVec2) {
dirtyTriangles.invalidate()
}
override fun onRemovedFromList(element: MutableVec2) {
dirtyTriangles.invalidate()
}
}
}
companion object {
init {
Shape.registerCollisionHandler { a: ClosedPolygon, b: ClosedPolygon ->
for (aTriangle in a.triangles) {
for (bTriangle in b.triangles) {
if (aTriangle collides bTriangle)
return@registerCollisionHandler true
}
}
return@registerCollisionHandler false
}
Shape.registerCollisionHandler { polygon: ClosedPolygon, triangle: Triangle ->
for (polygonTriangle in polygon.triangles) {
if (triangle collides polygonTriangle)
return@registerCollisionHandler true
}
return@registerCollisionHandler false
}
Shape.registerCollisionHandler { polygon: ClosedPolygon, line: Line ->
for (polygonTriangle in polygon.triangles) {
if (line collides polygonTriangle)
return@registerCollisionHandler true
}
return@registerCollisionHandler false
}
}
}
override fun copy(): ClosedPolygon {
return ClosedPolygon(points).apply {
triangulator = [email protected]
}
}
override fun contains(point: Vec2): Boolean {
for (triangle in triangles) {
if (point in triangle)
return true
}
return false
}
override fun ease(other: Polygon, f: Float): ClosedPolygon {
if (other !is ClosedPolygon)
throw IllegalArgumentException()
if (points.size != other.points.size)
throw IllegalArgumentException()
return ClosedPolygon(points.mapIndexed { index, point -> point.ease(other.points[index], f) })
}
private fun draw(shapes: ShapeRenderer) {
val vertices = FloatArray(points.size * 2)
for (i in 0 until points.size) {
vertices[i * 2] = points[i].x
vertices[i * 2 + 1] = points[i].y
}
shapes.polygon(vertices)
}
override fun drawFilled(shapes: ShapeRenderer) {
draw(shapes)
}
override fun drawOutline(shapes: ShapeRenderer) {
draw(shapes)
}
} | apache-2.0 | 50d288df5640da198b667ce66187bd93 | 26 | 96 | 0.717452 | 3.760417 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.