repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/util/ContextExtensions.kt | 1 | 2140 | package org.stepic.droid.util
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.TypedValue
import android.widget.Toast
import androidx.annotation.AttrRes
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.appcompat.content.res.AppCompatResources
fun Context.copyTextToClipboard(label: String? = null, textToCopy: String, toastMessage: String) {
val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboardManager.setPrimaryClip(ClipData.newPlainText(label, textToCopy))
Toast.makeText(this, toastMessage, Toast.LENGTH_SHORT).show()
}
/**
* Workaround appcompat-1.1.0 bug https://issuetracker.google.com/issues/141132133
*/
fun Context.contextForWebView(): Context =
if (Build.VERSION.SDK_INT in 21..22) {
applicationContext
} else {
this
}
fun Context.resolveAttribute(@AttrRes attributeResId: Int): TypedValue? {
val typedValue = TypedValue()
return if (theme.resolveAttribute(attributeResId, typedValue, true)) {
typedValue
} else {
null
}
}
@ColorInt
fun Context.resolveColorAttribute(@AttrRes attributeResId: Int): Int =
resolveAttribute(attributeResId)?.data ?: 0
fun Context.resolveFloatAttribute(@AttrRes attributeResId: Int): Float =
resolveAttribute(attributeResId)?.float ?: 0f
fun Context.resolveResourceIdAttribute(@AttrRes attributeResId: Int): Int =
resolveAttribute(attributeResId)?.resourceId ?: 0
/**
* "com.google.android.googlequicksearchbox" is necessary to launch Scene Viewer
* Reference: https://developers.google.com/ar/develop/java/scene-viewer#3d-or-ar
*/
fun Context.isARSupported(): Boolean =
try {
packageManager.getApplicationInfo("com.google.android.googlequicksearchbox", 0)
true
} catch (e : PackageManager.NameNotFoundException) {
false
} | apache-2.0 | 975367347510f1e932798293ec0857fe | 32.453125 | 98 | 0.765421 | 4.358452 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android | player_framework/src/main/java/com/vmenon/mpo/player/framework/di/dagger/PlayerFrameworkModule.kt | 1 | 2604 | package com.vmenon.mpo.player.framework.di.dagger
import android.app.Application
import android.content.Context
import androidx.core.content.ContextCompat
import com.vmenon.mpo.navigation.domain.NavigationController
import com.vmenon.mpo.navigation.domain.NavigationDestination
import com.vmenon.mpo.navigation.domain.player.*
import com.vmenon.mpo.player.domain.*
import com.vmenon.mpo.player.framework.AndroidMediaBrowserServicePlayerEngine
import com.vmenon.mpo.player.framework.DefaultNavigationParamsConverter
import com.vmenon.mpo.player.framework.MPOMediaBrowserService
import com.vmenon.mpo.player.framework.MPOPlayer
import com.vmenon.mpo.player.framework.exo.MPOExoPlayer
import com.vmenon.mpo.view.R
import dagger.Module
import dagger.Provides
@Module
object PlayerFrameworkModule {
@Provides
@PlayerFrameworkScope
fun providePlayerEngine(application: Application): MediaPlayerEngine =
AndroidMediaBrowserServicePlayerEngine(
application
)
@Provides
@PlayerFrameworkScope
fun providePlayer(application: Application): MPOPlayer =
MPOExoPlayer(application)
@Provides
@PlayerFrameworkScope
fun providesMPOMediaBrowserServiceConfiguration(
application: Application,
playerDestination: NavigationDestination<PlayerNavigationLocation>,
navigationController: NavigationController
): MPOMediaBrowserService.Configuration = MPOMediaBrowserService.Configuration(
{ request: PlaybackMediaRequest?, context: Context ->
navigationController.createNavigationRequest(
context,
PlayerNavigationParams(
request?.let {
Media(
mediaId = request.media.mediaId,
mediaSource = FileMediaSource(request.mediaFile),
title = request.media.title,
album = request.media.album,
genres = request.media.genres,
artworkUrl = request.media.artworkUrl,
author = request.media.author
)
}
),
playerDestination
)
},
{ builder ->
builder.color = ContextCompat.getColor(
application,
R.color.colorPrimary
)
})
@Provides
@PlayerFrameworkScope
fun provideNavigationParamsConverters(): NavigationParamsConverter =
DefaultNavigationParamsConverter()
} | apache-2.0 | cde4cc2db23d1c609f5f11d431a2bc55 | 36.214286 | 83 | 0.660138 | 5.425 | false | false | false | false |
Heiner1/AndroidAPS | wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt | 1 | 6123 | @file:Suppress("DEPRECATION")
package info.nightscout.androidaps.watchfaces
import android.annotation.SuppressLint
import android.support.wearable.watchface.WatchFaceStyle
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.viewbinding.ViewBinding
import info.nightscout.androidaps.R
import info.nightscout.androidaps.databinding.ActivityDigitalstyleBinding
import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.watchfaces.utils.BaseWatchFace
import info.nightscout.shared.logging.LTag
class DigitalStyleWatchface : BaseWatchFace() {
private lateinit var binding: ActivityDigitalstyleBinding
override fun inflateLayout(inflater: LayoutInflater): ViewBinding {
binding = ActivityDigitalstyleBinding.inflate(inflater)
return binding
}
override fun getWatchFaceStyle(): WatchFaceStyle {
return WatchFaceStyle.Builder(this)
.setAcceptsTapEvents(true)
.setHideNotificationIndicator(false)
.setShowUnreadCountIndicator(true)
.build()
}
override fun setColorDark() {
val color = when (singleBg.sgvLevel) {
1L -> R.color.dark_highColor
0L -> R.color.dark_midColor
-1L -> R.color.dark_lowColor
else -> R.color.dark_midColor
}
binding.sgv.setTextColor(ContextCompat.getColor(this, color))
binding.direction.setTextColor(ContextCompat.getColor(this, color))
val colorTime = if (ageLevel == 1) R.color.dark_midColor else R.color.dark_TimestampOld
binding.timestamp.setTextColor(ContextCompat.getColor(this, colorTime))
val colorBat = if (status.batteryLevel == 1) R.color.dark_midColor else R.color.dark_uploaderBatteryEmpty
binding.uploaderBattery.setTextColor(ContextCompat.getColor(this, colorBat))
highColor = ContextCompat.getColor(this, R.color.dark_highColor)
lowColor = ContextCompat.getColor(this, R.color.dark_lowColor)
midColor = ContextCompat.getColor(this, R.color.dark_midColor)
gridColor = ContextCompat.getColor(this, R.color.dark_gridColor)
basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_dark)
basalCenterColor = ContextCompat.getColor(this, R.color.basal_light)
pointSize = 1
setupCharts()
setWatchfaceStyle()
}
@SuppressLint("SetTextI18n")
private fun setWatchfaceStyle() {
/* frame styles*/
val mShapesElements = layoutView?.findViewById<LinearLayout>(R.id.shapes_elements)
if (mShapesElements != null) {
val displayFormatType = if (mShapesElements.contentDescription.toString().startsWith("round")) "round" else "rect"
val displayStyle = sp.getString(R.string.key_digital_style_frame_style, "full")
val displayFrameColor = sp.getString(R.string.key_digital_style_frame_color, "red")
val displayFrameColorSaturation = sp.getString(R.string.key_digital_style_frame_color_saturation, "500")
val displayFrameColorOpacity = sp.getString(R.string.key_digital_style_frame_color_opacity, "1")
// Load image with shapes
val styleDrawableName = "digitalstyle_bg_" + displayStyle + "_" + displayFormatType
try {
mShapesElements.background = ContextCompat.getDrawable(this, resources.getIdentifier(styleDrawableName, "drawable", this.packageName))
} catch (e: Exception) {
aapsLogger.error("digitalstyle_frameStyle", "RESOURCE NOT FOUND >> $styleDrawableName")
}
// set background-tint-color
if (displayFrameColor.equals("multicolor", ignoreCase = true) || displayStyle.equals("none", ignoreCase = true)) {
mShapesElements.backgroundTintList = null
} else {
val strColorName = if (displayFrameColor == "white" || displayFrameColor == "black") displayFrameColor else displayFrameColor + "_" + displayFrameColorSaturation
aapsLogger.debug(LTag.WEAR, "digitalstyle_strColorName", strColorName)
try {
val colorStateList = ContextCompat.getColorStateList(this, resources.getIdentifier(strColorName, "color", this.packageName))
mShapesElements.backgroundTintList = colorStateList
} catch (e: Exception) {
mShapesElements.backgroundTintList = null
aapsLogger.error("digitalstyle_colorName", "COLOR NOT FOUND >> $strColorName")
}
}
// set opacity of shapes
mShapesElements.alpha = displayFrameColorOpacity.toFloat()
}
/* optimize font-size --> when date is off then increase font-size of time */
val isShowDate = sp.getBoolean(R.string.key_show_date, false)
if (!isShowDate) {
layoutView?.findViewById<View>(R.id.date_time)?.visibility = View.GONE
binding.hour.textSize = 62f
binding.minute.textSize = 40f
binding.hour.letterSpacing = (-0.066).toFloat()
binding.minute.letterSpacing = (-0.066).toFloat()
} else {
layoutView?.findViewById<View>(R.id.date_time)?.visibility = View.VISIBLE
binding.hour.textSize = 40f
binding.minute.textSize = 26f
binding.hour.letterSpacing = 0.toFloat()
binding.minute.letterSpacing = 0.toFloat()
/* display week number */
val mWeekNumber = layoutView?.findViewById<TextView>(R.id.week_number)
mWeekNumber?.visibility = sp.getBoolean(R.string.key_show_week_number, false).toVisibility()
mWeekNumber?.text = "(" + dateUtil.weekString() + ")"
}
}
override fun setColorLowRes() {
setColorDark()
}
override fun setColorBright() {
setColorDark() /* getCurrentWatchMode() == WatchMode.AMBIENT or WatchMode.INTERACTIVE */
}
}
| agpl-3.0 | e6f78055fc60698651adbdfe4ad070b8 | 45.740458 | 177 | 0.670423 | 4.542285 | false | false | false | false |
kvakil/venus | src/main/kotlin/venus/riscv/insts/mulh.kt | 1 | 345 | package venus.riscv.insts
import venus.riscv.insts.dsl.RTypeInstruction
val mulh = RTypeInstruction(
name = "mulh",
opcode = 0b0110011,
funct3 = 0b001,
funct7 = 0b0000001,
eval32 = { a, b ->
val x = a.toLong()
val y = b.toLong()
((x * y) ushr 32).toInt()
}
)
| mit | a4367f117b2628f8520c1c4caa6a4539 | 22 | 45 | 0.513043 | 3.349515 | false | false | false | false |
exponentjs/exponent | packages/expo-dev-launcher/android/src/release/java/expo/modules/devlauncher/DevLauncherController.kt | 2 | 4077 | package expo.modules.devlauncher
import android.content.Context
import android.content.Intent
import android.net.Uri
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.ReactNativeHost
import com.facebook.react.bridge.ReactContext
import expo.modules.devlauncher.launcher.DevLauncherClientHost
import expo.modules.devlauncher.launcher.DevLauncherControllerInterface
import expo.modules.devlauncher.launcher.DevLauncherReactActivityDelegateSupplier
import expo.modules.manifests.core.Manifest
import expo.modules.updatesinterface.UpdatesInterface
import kotlinx.coroutines.CoroutineScope
const val DEV_LAUNCHER_IS_NOT_AVAILABLE = "DevLauncher isn't available in release builds"
class DevLauncherController private constructor() : DevLauncherControllerInterface {
enum class Mode {
LAUNCHER, APP
}
override val latestLoadedApp: Uri? = null
override val mode: Mode
get() = throw IllegalStateException(DEV_LAUNCHER_IS_NOT_AVAILABLE)
override val devClientHost: DevLauncherClientHost
get() = throw IllegalStateException(DEV_LAUNCHER_IS_NOT_AVAILABLE)
override val manifest: Manifest
get() = throw IllegalStateException(DEV_LAUNCHER_IS_NOT_AVAILABLE)
override val manifestURL: Uri
get() = throw IllegalStateException(DEV_LAUNCHER_IS_NOT_AVAILABLE)
override val appHost: ReactNativeHost
get() = throw IllegalStateException(DEV_LAUNCHER_IS_NOT_AVAILABLE)
override var updatesInterface: UpdatesInterface?
get() = throw IllegalStateException(DEV_LAUNCHER_IS_NOT_AVAILABLE)
set(_) {}
override val coroutineScope: CoroutineScope
get() = throw IllegalStateException(DEV_LAUNCHER_IS_NOT_AVAILABLE)
override val useDeveloperSupport = false
override fun maybeInitDevMenuDelegate(context: ReactContext) {
throw IllegalStateException(DEV_LAUNCHER_IS_NOT_AVAILABLE)
}
override fun getCurrentReactActivityDelegate(activity: ReactActivity, delegateSupplierDevLauncher: DevLauncherReactActivityDelegateSupplier): ReactActivityDelegate {
throw IllegalStateException(DEV_LAUNCHER_IS_NOT_AVAILABLE)
}
override fun handleIntent(intent: Intent?, activityToBeInvalidated: ReactActivity?): Boolean {
throw IllegalStateException(DEV_LAUNCHER_IS_NOT_AVAILABLE)
}
override fun navigateToLauncher() {
throw IllegalStateException(DEV_LAUNCHER_IS_NOT_AVAILABLE)
}
override fun maybeSynchronizeDevMenuDelegate() {
throw IllegalStateException(DEV_LAUNCHER_IS_NOT_AVAILABLE)
}
override suspend fun loadApp(url: Uri, mainActivity: ReactActivity?) {
throw IllegalStateException(DEV_LAUNCHER_IS_NOT_AVAILABLE)
}
override fun onAppLoaded(context: ReactContext) {
throw IllegalStateException(DEV_LAUNCHER_IS_NOT_AVAILABLE)
}
override fun onAppLoadedWithError() {
throw IllegalStateException(DEV_LAUNCHER_IS_NOT_AVAILABLE)
}
override fun getRecentlyOpenedApps(): Map<String, String?> {
throw IllegalStateException(DEV_LAUNCHER_IS_NOT_AVAILABLE)
}
companion object {
private var sInstance: DevLauncherController? = null
@JvmStatic
val instance: DevLauncherController
get() = checkNotNull(sInstance) {
"DevelopmentClientController.getInstance() was called before the module was initialized"
}
@JvmStatic
fun initialize(context: Context, reactNativeHost: ReactNativeHost) {
check(sInstance == null) { "DevelopmentClientController was initialized." }
sInstance = DevLauncherController()
}
@JvmStatic
fun initialize(context: Context, appHost: ReactNativeHost, cazz: Class<*>) {
initialize(context, appHost)
}
@JvmStatic
fun wrapReactActivityDelegate(reactActivity: ReactActivity, devLauncherReactActivityDelegateSupplier: DevLauncherReactActivityDelegateSupplier): ReactActivityDelegate {
return devLauncherReactActivityDelegateSupplier.get()
}
@JvmStatic
fun tryToHandleIntent(reactActivity: ReactActivity, intent: Intent): Boolean = false
@JvmStatic
fun wasInitialized(): Boolean = false
}
}
| bsd-3-clause | 5bdde756a0d544bbf48ec173d8631a60 | 33.846154 | 172 | 0.783174 | 4.90024 | false | false | false | false |
cyclestreets/android | libraries/cyclestreets-fragments/src/main/java/net/cyclestreets/itinerary/ElevationProfileFragment.kt | 1 | 4584 | package net.cyclestreets.itinerary
import android.graphics.Color
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import com.jjoe64.graphview.GraphView
import com.jjoe64.graphview.GridLabelRenderer
import com.jjoe64.graphview.LabelFormatter
import com.jjoe64.graphview.Viewport
import com.jjoe64.graphview.series.DataPoint
import com.jjoe64.graphview.series.LineGraphSeries
import net.cyclestreets.fragments.R
import net.cyclestreets.routing.ElevationFormatter
import net.cyclestreets.routing.Journey
import net.cyclestreets.routing.Route
import net.cyclestreets.routing.Waypoints
import net.cyclestreets.util.Theme
import java.util.ArrayList
class ElevationProfileFragment : Fragment(), Route.Listener {
private lateinit var graphHolder: LinearLayout
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View {
val elevation = inflater.inflate(R.layout.elevation, container, false)
graphHolder = elevation.findViewById(R.id.graphview)
return elevation
}
override fun onResume() {
super.onResume()
Route.onResume()
Route.registerListener(this)
}
override fun onPause() {
Route.unregisterListener(this)
super.onPause()
}
override fun onNewJourney(journey: Journey, waypoints: Waypoints) {
drawGraph(journey)
fillInOverview(journey, requireView(), requireContext().getString(R.string.elevation_route))
}
override fun onResetJourney() {}
private fun drawGraph(journey: Journey) {
val graphView = GraphView(context)
val formatter = elevationFormatter()
// The elevation data series for the whole route
val elevationData = ArrayList<DataPoint>()
for (elevation in journey.elevation.profile())
elevationData.add(DataPoint(elevation.distance().toDouble(), elevation.elevation().toDouble()))
val elevationSeries = LineGraphSeries(elevationData.toTypedArray())
elevationSeries.isDrawBackground = true
graphView.addSeries(elevationSeries)
// The elevation data series for the current segment - highlight
journey.activeSegment()?.let { segment ->
val segmentEndDistance = segment.cumulativeDistance
val segmentStartDistance = segmentEndDistance - segment.distance
val segmentElevationData = elevationData.slice(IntRange(
elevationData.indexOfFirst { dp -> dp.x >= segmentStartDistance.toDouble() },
elevationData.indexOfLast { dp -> dp.x <= segmentEndDistance.toDouble() }
))
val segmentElevationSeries = LineGraphSeries(segmentElevationData.toTypedArray())
segmentElevationSeries.color = Theme.highlightColor(context)
segmentElevationSeries.backgroundColor = Color.argb(153, 0, 152, 0) //0x99009800
segmentElevationSeries.isDrawBackground = true
graphView.addSeries(segmentElevationSeries)
}
// Allow zooming & scrolling on the x-axis (y-axis remains fixed)
val viewport = graphView.viewport
viewport.isScalable = true
viewport.isYAxisBoundsManual = true
viewport.setMinY(formatter.roundHeightBelow(journey.elevation.minimum()))
viewport.setMaxY(formatter.roundHeightAbove(journey.elevation.maximum()))
val gridLabelRenderer = graphView.gridLabelRenderer
gridLabelRenderer.gridStyle = GridLabelRenderer.GridStyle.BOTH
gridLabelRenderer.numHorizontalLabels = 5
gridLabelRenderer.numVerticalLabels = 5
gridLabelRenderer.labelFormatter = ElevationLabelFormatter(formatter)
// we handle y-rounding ourselves, and x-rounding makes labels overlap - see https://github.com/jjoe64/GraphView/issues/413
gridLabelRenderer.setHumanRounding(false, false)
graphHolder.removeAllViews()
graphHolder.addView(graphView)
}
private class ElevationLabelFormatter constructor(private val formatter: ElevationFormatter) : LabelFormatter {
override fun setViewport(viewport: Viewport) {}
override fun formatLabel(value: Double, isValueX: Boolean): String {
return if (isValueX)
if (value != 0.0) formatter.distance(value.toInt()) else ""
else formatter.roundedHeight(value.toInt())
}
}
}
| gpl-3.0 | 6de6de4f7a42bac6f337278daaeb225a | 40.297297 | 131 | 0.711824 | 4.9718 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/showcase/kotlintypes/TypeWriter.kt | 1 | 364 | package arcs.showcase.kotlintypes
class TypeWriter : AbstractTypeWriter() {
override fun onFirstStart() {
handles.outputs.store(
KotlinTypes(
aByte = 42.toByte(),
aShort = 280.toShort(),
anInt = 70000,
aLong = 10000000000L,
aChar = 'A',
aFloat = 255.5f,
aDouble = 255.5E100
)
)
}
}
| bsd-3-clause | 3b5f537d21634f7e92f8fc020e2897e8 | 19.222222 | 41 | 0.56044 | 3.913978 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/command/Argument.kt | 1 | 1736 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.command
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.group.visual.VimSelection
import com.maddyhome.idea.vim.handler.Motion
import com.maddyhome.idea.vim.handler.MotionActionHandler
import java.util.*
/**
* This represents a command argument.
*/
class Argument private constructor(
val character: Char = 0.toChar(),
val motion: Command = EMPTY_COMMAND,
val offsets: Map<VimCaret, VimSelection> = emptyMap(),
val string: String = "",
val type: Type,
) {
constructor(motionArg: Command) : this(motion = motionArg, type = Type.MOTION)
constructor(charArg: Char) : this(character = charArg, type = Type.CHARACTER)
constructor(strArg: String) : this(string = strArg, type = Type.EX_STRING)
constructor(offsets: Map<VimCaret, VimSelection>) : this(offsets = offsets, type = Type.OFFSETS)
enum class Type {
MOTION, CHARACTER, DIGRAPH, EX_STRING, OFFSETS
}
companion object {
@JvmField
val EMPTY_COMMAND = Command(
0,
object : MotionActionHandler.SingleExecution() {
override fun getOffset(
editor: VimEditor,
context: ExecutionContext,
argument: Argument?,
operatorArguments: OperatorArguments
) = Motion.NoMotion
override val motionType: MotionType = MotionType.EXCLUSIVE
},
Command.Type.MOTION, EnumSet.noneOf(CommandFlags::class.java)
)
}
}
| mit | a99dc53eb932302de1b2e67d185c8f69 | 30.563636 | 98 | 0.711406 | 4.027842 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/viewmodel/ResourceProvider.kt | 1 | 2424 | package org.wordpress.android.viewmodel
import android.graphics.drawable.Drawable
import androidx.annotation.ColorRes
import androidx.annotation.DimenRes
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import javax.inject.Inject
class ResourceProvider @Inject constructor(private val contextProvider: ContextProvider) {
fun getString(@StringRes resourceId: Int): String {
return contextProvider.getContext().getString(resourceId)
}
fun getString(@StringRes resourceId: Int, vararg formatArgs: Any): String {
return contextProvider.getContext().getString(resourceId, *formatArgs)
}
fun getStringArray(id: Int): Array<String> = contextProvider.getContext().resources.getStringArray(id)
fun getColor(@ColorRes resourceId: Int): Int {
return ContextCompat.getColor(contextProvider.getContext(), resourceId)
}
fun getDimensionPixelSize(@DimenRes dimen: Int): Int {
val resources = contextProvider.getContext().resources
return resources.getDimensionPixelSize(dimen)
}
fun getDimension(@DimenRes dimen: Int): Float {
val resources = contextProvider.getContext().resources
return resources.getDimension(dimen)
}
/**
* Formats the string for the given quantity, using the given arguments.
* We need this because our translation platform doesn't support Android plurals.
*
* @param zero The desired string identifier to get when quantity is exactly 0
* @param one The desired string identifier to get when quantity is exactly 1
* @param other The desired string identifier to get when quantity is not (0 or 1)
* @param quantity The number used to get the correct string
*/
fun getQuantityString(@StringRes zero: Int, @StringRes one: Int, @StringRes other: Int, quantity: Int): String? {
if (quantity == 0) {
return contextProvider.getContext().getString(zero)
}
return if (quantity == 1) {
contextProvider.getContext().getString(one)
} else String.format(contextProvider.getContext().getString(other), quantity)
}
fun getDimensionPixelOffset(id: Int): Int {
return contextProvider.getContext().resources.getDimensionPixelOffset(id)
}
fun getDrawable(iconId: Int): Drawable? {
return ContextCompat.getDrawable(contextProvider.getContext(), iconId)
}
}
| gpl-2.0 | 892b8a093e489e9f04734257bcedb9fc | 39.4 | 117 | 0.719472 | 5.092437 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/composeUtils.kt | 4 | 3147 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.core
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.DebugProcess
import com.intellij.debugger.requests.ClassPrepareRequestor
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.application.runReadAction
import com.intellij.psi.JavaPsiFacade
import com.sun.jdi.ReferenceType
import com.sun.jdi.request.ClassPrepareRequest
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils
import org.jetbrains.kotlin.psi.KtFile
private const val COMPOSABLE_SINGLETONS_PREFIX = "ComposableSingletons"
private const val ANDROIDX_COMPOSE_PACKAGE_NAME = "androidx.compose"
/**
* Compute the name of the ComposableSingletons class for the given file.
*
* Compose compiler plugin creates per-file ComposableSingletons classes to cache
* composable lambdas without captured variables. We need to locate these classes in order
* to search them for breakpoint locations.
*
* NOTE: The pattern for ComposableSingletons classes needs to be kept in sync with the
* code in `ComposerLambdaMemoization.getOrCreateComposableSingletonsClass`.
* The optimization was introduced in I8c967b14c5d9bf67e5646e60f630f2e29e006366
*/
fun computeComposableSingletonsClassName(file: KtFile): String {
// The code in `ComposerLambdaMemoization` always uses the file short name and
// ignores `JvmName` annotations, but (implicitly) respects `JvmPackageName`
// annotations.
val filePath = file.virtualFile?.path ?: file.name
val fileName = filePath.split('/').last()
val shortName = PackagePartClassUtils.getFilePartShortName(fileName)
val fileClassFqName = runReadAction { JvmFileClassUtil.getFileClassInfoNoResolve(file) }.facadeClassFqName
val classNameSuffix = "$COMPOSABLE_SINGLETONS_PREFIX\$$shortName"
val filePackageName = fileClassFqName.parent()
if (filePackageName.isRoot) {
return classNameSuffix
}
return "${filePackageName.asString()}.$classNameSuffix"
}
fun SourcePosition.isInsideProjectWithCompose(): Boolean =
ReadAction.nonBlocking<Boolean> {
JavaPsiFacade.getInstance(file.project).findPackage(ANDROIDX_COMPOSE_PACKAGE_NAME) != null
}.executeSynchronously()
fun getComposableSingletonsClasses(debugProcess: DebugProcess, file: KtFile): List<ReferenceType> {
val vm = debugProcess.virtualMachineProxy
val composableSingletonsClassName = computeComposableSingletonsClassName(file)
return vm.classesByName(composableSingletonsClassName).flatMap { referenceType ->
if (referenceType.isPrepared) vm.nestedTypes(referenceType) else listOf()
}
}
fun getClassPrepareRequestForComposableSingletons(
debugProcess: DebugProcess,
requestor: ClassPrepareRequestor,
file: KtFile
): ClassPrepareRequest? {
return debugProcess.requestsManager.createClassPrepareRequest(
requestor,
"${computeComposableSingletonsClassName(file)}\$*"
)
}
| apache-2.0 | 711697fbff9f9b2733e61e29ddc246ec | 45.279412 | 120 | 0.790912 | 4.627941 | false | false | false | false |
mdaniel/intellij-community | java/java-impl/src/com/intellij/internal/statistic/libraryUsage/LibraryUsageStatisticsStorageService.kt | 5 | 2149 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.statistic.libraryUsage
import com.intellij.openapi.components.*
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.project.Project
import com.intellij.util.xmlb.annotations.XMap
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
@Service(Service.Level.PROJECT)
@State(
name = "LibraryUsageStatistics",
storages = [Storage(StoragePathMacros.CACHE_FILE)],
reportStatistic = false,
reloadable = false,
)
class LibraryUsageStatisticsStorageService : PersistentStateComponent<LibraryUsageStatisticsStorageService.LibraryUsageStatisticsState> {
private val lock = ReentrantReadWriteLock()
private var statistics = Object2IntOpenHashMap<LibraryUsage>()
override fun getState(): LibraryUsageStatisticsState = lock.read {
val result = LibraryUsageStatisticsState()
result.statistics.putAll(statistics)
result
}
override fun loadState(state: LibraryUsageStatisticsState): Unit = lock.write {
statistics = Object2IntOpenHashMap(state.statistics)
}
fun getStatisticsAndResetState(): Map<LibraryUsage, Int> = lock.write {
val old = statistics
statistics = Object2IntOpenHashMap()
old
}
fun increaseUsages(libraries: Collection<LibraryUsage>): Unit = lock.write {
libraries.forEach {
statistics.addTo(it, 1)
}
}
class LibraryUsageStatisticsState {
@XMap
@JvmField
val statistics = HashMap<LibraryUsage, Int>()
}
companion object {
fun getInstance(project: Project): LibraryUsageStatisticsStorageService = project.service()
}
}
data class LibraryUsage(
var name: String? = null,
var version: String? = null,
var fileTypeName: String? = null,
) {
constructor(name: String, version: String, fileType: FileType) : this(name = name, version = version, fileTypeName = fileType.name)
override fun toString(): String = "$name-$version for $fileTypeName"
}
| apache-2.0 | 75163a240299121cf30ff8936ac834a5 | 32.061538 | 137 | 0.765472 | 4.449275 | false | false | false | false |
parkito/virtualAtmosphere | src/main/kotlin/ru/siksmfp/network/harness/implementation/nio/simple/NioServer.kt | 1 | 3162 | package ru.siksmfp.network.harness.implementation.nio.simple
import ru.siksmfp.network.harness.api.Handler
import ru.siksmfp.network.harness.api.Server
import ru.siksmfp.network.harness.implementation.nio.simple.server.AcceptHandler
import ru.siksmfp.network.harness.implementation.nio.simple.server.ReadHandler
import ru.siksmfp.network.harness.implementation.nio.simple.server.WriteHandler
import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.nio.channels.SelectionKey.OP_ACCEPT
import java.nio.channels.Selector
import java.nio.channels.ServerSocketChannel
import java.nio.channels.SocketChannel
import java.util.Queue
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentLinkedDeque
import java.util.concurrent.atomic.AtomicBoolean
class NioServer(
private val port: Int,
threadNumber: Int?
) : Server<String> {
private lateinit var serverChannel: ServerSocketChannel
private lateinit var selector: Selector
private val clients = ConcurrentHashMap<SocketChannel, ByteBuffer>()
private val selectorActions: Queue<Runnable> = ConcurrentLinkedDeque()
private val acceptHandler = AcceptHandler(clients)
private val readHandler = ReadHandler(clients, selectorActions)
private val writeHandler = WriteHandler(clients)
private lateinit var isRunning: AtomicBoolean
override fun start() {
isRunning = AtomicBoolean(true)
serverChannel = ServerSocketChannel.open()
serverChannel.bind(InetSocketAddress(port))
serverChannel.configureBlocking(false)
selector = Selector.open()
serverChannel.register(selector, OP_ACCEPT)
println("Server nio started on $port")
while (isRunning.get()) {
selector.select()
processSelectorAction(selectorActions)
val keys = selector.selectedKeys()
val keysIterator = keys.iterator()
while (keysIterator.hasNext()) {
val key = keysIterator.next()
keysIterator.remove()
if (key.isValid) {
when {
key.isAcceptable -> {
acceptHandler.handle(key)
}
key.isReadable -> {
readHandler.handle(key)
}
key.isWritable -> {
writeHandler.handle(key)
}
}
}
}
}
}
private fun processSelectorAction(selectorAction: Queue<Runnable>) {
var task: Runnable? = selectorAction.peek()
while (task != null) {
task.run();
task = selectorAction.poll()
}
}
override fun stop() {
isRunning.set(false)
readHandler.close()
clients.forEach { it.key.close() }
serverChannel.close()
selector.close()
selectorActions.clear()
println("Nio server stopped")
}
override fun setHandler(handler: Handler<String>) {
readHandler.setHandler(handler)
}
} | apache-2.0 | b098eef181522e7a5df180cc19ca4cb6 | 33.380435 | 80 | 0.63599 | 4.864615 | false | false | false | false |
mdaniel/intellij-community | platform/diagnostic/src/startUpPerformanceReporter/StartUpPerformanceReporter.kt | 1 | 10317 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet")
package com.intellij.diagnostic.startUpPerformanceReporter
import com.fasterxml.jackson.core.JsonGenerator
import com.intellij.diagnostic.ActivityCategory
import com.intellij.diagnostic.ActivityImpl
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.diagnostic.StartUpMeasurer.Activities
import com.intellij.diagnostic.StartUpPerformanceService
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.plugins.cl.PluginAwareClassLoader
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.InitProjectActivity
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.SystemProperties
import com.intellij.util.io.jackson.IntelliJPrettyPrinter
import com.intellij.util.io.write
import com.intellij.util.lang.ClassPath
import it.unimi.dsi.fastutil.objects.Object2IntMap
import it.unimi.dsi.fastutil.objects.Object2LongMap
import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap
import kotlinx.coroutines.launch
import java.io.File
import java.nio.ByteBuffer
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.TimeUnit
import java.util.function.Consumer
class StartUpPerformanceReporter : InitProjectActivity, StartUpPerformanceService {
init {
val app = ApplicationManager.getApplication()
if (app.isUnitTestMode || app.isHeadlessEnvironment) {
throw ExtensionNotApplicableException.create()
}
}
private var pluginCostMap: Map<String, Object2LongMap<String>>? = null
private var lastReport: ByteBuffer? = null
private var lastMetrics: Object2IntMap<String>? = null
companion object {
internal val LOG = logger<StartUpMeasurer>()
internal const val VERSION = "38"
internal fun sortItems(items: MutableList<ActivityImpl>) {
items.sortWith(Comparator { o1, o2 ->
if (o1 == o2.parent) {
return@Comparator -1
}
else if (o2 == o1.parent) {
return@Comparator 1
}
compareTime(o1, o2)
})
}
fun logStats(projectName: String) {
doLogStats(projectName)
}
}
override fun getMetrics() = lastMetrics
override fun getPluginCostMap() = pluginCostMap!!
override fun getLastReport() = lastReport
override suspend fun run(project: Project) {
if (ActivityImpl.listener != null) {
return
}
val projectName = project.name
ActivityImpl.listener = ActivityListener(projectName)
}
private inner class ActivityListener(private val projectName: String) : Consumer<ActivityImpl> {
@Volatile
private var projectOpenedActivitiesPassed = false
// not all activities are performed always, so, we wait only activities that were started
@Volatile
private var editorRestoringTillPaint = true
override fun accept(activity: ActivityImpl) {
if (activity.category != null && activity.category != ActivityCategory.DEFAULT) {
return
}
if (activity.end == 0L) {
if (activity.name == Activities.EDITOR_RESTORING_TILL_PAINT) {
editorRestoringTillPaint = false
}
}
else {
when (activity.name) {
Activities.PROJECT_DUMB_POST_START_UP_ACTIVITIES -> {
projectOpenedActivitiesPassed = true
if (editorRestoringTillPaint) {
completed()
}
}
Activities.EDITOR_RESTORING_TILL_PAINT -> {
editorRestoringTillPaint = true
if (projectOpenedActivitiesPassed) {
completed()
}
}
}
}
}
private fun completed() {
ActivityImpl.listener = null
StartUpMeasurer.stopPluginCostMeasurement()
// don't report statistic from here if we want to measure project import duration
if (!java.lang.Boolean.getBoolean("idea.collect.project.import.performance")) {
keepAndLogStats(projectName)
}
}
}
override fun reportStatistics(project: Project) {
project.coroutineScope.launch {
keepAndLogStats(project.name)
}
}
@Synchronized
private fun keepAndLogStats(projectName: String) {
val params = doLogStats(projectName)
pluginCostMap = params.pluginCostMap
lastReport = params.lastReport
lastMetrics = params.lastMetrics
}
}
private fun doLogStats(projectName: String): StartUpPerformanceReporterValues {
val instantEvents = mutableListOf<ActivityImpl>()
// write activity category in the same order as first reported
val activities = LinkedHashMap<String, MutableList<ActivityImpl>>()
val serviceActivities = HashMap<String, MutableList<ActivityImpl>>()
val services = mutableListOf<ActivityImpl>()
val threadNameManager = IdeThreadNameManager()
var end = -1L
StartUpMeasurer.processAndClear(SystemProperties.getBooleanProperty("idea.collect.perf.after.first.project", false)) { item ->
// process it now to ensure that thread will have a first name (because report writer can process events in any order)
threadNameManager.getThreadName(item)
if (item.end == -1L) {
instantEvents.add(item)
}
else {
when (val category = item.category ?: ActivityCategory.DEFAULT) {
ActivityCategory.DEFAULT -> {
if (item.name == Activities.PROJECT_DUMB_POST_START_UP_ACTIVITIES) {
end = item.end
}
activities.computeIfAbsent(category.jsonName) { mutableListOf() }.add(item)
}
ActivityCategory.APP_COMPONENT, ActivityCategory.PROJECT_COMPONENT, ActivityCategory.MODULE_COMPONENT,
ActivityCategory.APP_SERVICE, ActivityCategory.PROJECT_SERVICE, ActivityCategory.MODULE_SERVICE,
ActivityCategory.SERVICE_WAITING -> {
services.add(item)
serviceActivities.computeIfAbsent(category.jsonName) { mutableListOf() }.add(item)
}
else -> {
activities.computeIfAbsent(category.jsonName) { mutableListOf() }.add(item)
}
}
}
}
val pluginCostMap = computePluginCostMap()
val w = IdeIdeaFormatWriter(activities, pluginCostMap, threadNameManager)
val defaultActivities = activities.get(ActivityCategory.DEFAULT.jsonName)
val startTime = defaultActivities?.first()?.start ?: 0
if (defaultActivities != null) {
for (item in defaultActivities) {
val pluginId = item.pluginId ?: continue
StartUpMeasurer.doAddPluginCost(pluginId, item.category?.name ?: "unknown", item.end - item.start, pluginCostMap)
}
}
w.write(startTime, serviceActivities, instantEvents, end, projectName)
val currentReport = w.toByteBuffer()
if (System.getProperty("idea.log.perf.stats", "false").toBoolean()) {
w.writeToLog(StartUpPerformanceReporter.LOG)
}
val perfFilePath = System.getProperty("idea.log.perf.stats.file")
if (!perfFilePath.isNullOrBlank()) {
StartUpPerformanceReporter.LOG.info("StartUp Measurement report was written to: $perfFilePath")
Path.of(perfFilePath).write(currentReport)
currentReport.flip()
}
val classReport = System.getProperty("idea.log.class.list.file")
if (!classReport.isNullOrBlank()) {
generateJarAccessLog(Path.of(FileUtil.expandUserHome(classReport)))
}
for (instantEvent in instantEvents.filter { setOf("splash shown", "splash hidden").contains(it.name) }) {
w.publicStatMetrics.put("event:${instantEvent.name}",
TimeUnit.NANOSECONDS.toMillis(instantEvent.start - StartUpMeasurer.getStartTime()).toInt())
}
return StartUpPerformanceReporterValues(pluginCostMap, currentReport, w.publicStatMetrics)
}
private class StartUpPerformanceReporterValues(val pluginCostMap: MutableMap<String, Object2LongOpenHashMap<String>>,
val lastReport: ByteBuffer,
val lastMetrics: Object2IntMap<String>)
private fun computePluginCostMap(): MutableMap<String, Object2LongOpenHashMap<String>> {
val result = HashMap(StartUpMeasurer.pluginCostMap)
StartUpMeasurer.pluginCostMap.clear()
for (plugin in PluginManagerCore.getLoadedPlugins()) {
val id = plugin.pluginId.idString
val classLoader = (plugin as IdeaPluginDescriptorImpl).pluginClassLoader as? PluginAwareClassLoader ?: continue
val costPerPhaseMap = result.computeIfAbsent(id) {
val m = Object2LongOpenHashMap<String>()
m.defaultReturnValue(-1)
m
}
costPerPhaseMap.put("classloading (EDT)", classLoader.edtTime)
costPerPhaseMap.put("classloading (background)", classLoader.backgroundTime)
}
return result
}
// to make output more compact (quite a lot of slow components)
internal class MyJsonPrettyPrinter : IntelliJPrettyPrinter() {
private var objectLevel = 0
override fun writeStartObject(g: JsonGenerator) {
objectLevel++
if (objectLevel > 1) {
_objectIndenter = FixedSpaceIndenter.instance
}
super.writeStartObject(g)
}
override fun writeEndObject(g: JsonGenerator, nrOfEntries: Int) {
super.writeEndObject(g, nrOfEntries)
objectLevel--
if (objectLevel <= 1) {
_objectIndenter = UNIX_LINE_FEED_INSTANCE
}
}
}
internal fun compareTime(o1: ActivityImpl, o2: ActivityImpl): Int {
return when {
o1.start > o2.start -> 1
o1.start < o2.start -> -1
else -> {
when {
o1.end > o2.end -> -1
o1.end < o2.end -> 1
else -> 0
}
}
}
}
private fun generateJarAccessLog(outFile: Path) {
val homeDir = Path.of(PathManager.getHomePath())
val builder = StringBuilder()
for (item in ClassPath.getLoadedClasses()) {
val source = item.value
if (!source.startsWith(homeDir)) {
continue
}
builder.append(item.key).append(':').append(homeDir.relativize(source).toString().replace(File.separatorChar, '/'))
builder.append('\n')
}
Files.createDirectories(outFile.parent)
Files.writeString(outFile, builder)
}
| apache-2.0 | 3df8fb5124c241c1fb8c79bb3632e932 | 33.39 | 128 | 0.711641 | 4.454663 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildWithNullsOppositeMultipleImpl.kt | 1 | 8868 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildWithNullsOppositeMultipleImpl: ChildWithNullsOppositeMultiple, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentWithNullsOppositeMultiple::class.java, ChildWithNullsOppositeMultiple::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
@JvmField var _childData: String? = null
override val childData: String
get() = _childData!!
override val parentEntity: ParentWithNullsOppositeMultiple?
get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ChildWithNullsOppositeMultipleData?): ModifiableWorkspaceEntityBase<ChildWithNullsOppositeMultiple>(), ChildWithNullsOppositeMultiple.Builder {
constructor(): this(ChildWithNullsOppositeMultipleData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildWithNullsOppositeMultiple is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isChildDataInitialized()) {
error("Field ChildWithNullsOppositeMultiple#childData should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field ChildWithNullsOppositeMultiple#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var childData: String
get() = getEntityData().childData
set(value) {
checkModificationAllowed()
getEntityData().childData = value
changedProperty.add("childData")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var parentEntity: ParentWithNullsOppositeMultiple?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? ParentWithNullsOppositeMultiple
} else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? ParentWithNullsOppositeMultiple
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityData(): ChildWithNullsOppositeMultipleData = result ?: super.getEntityData() as ChildWithNullsOppositeMultipleData
override fun getEntityClass(): Class<ChildWithNullsOppositeMultiple> = ChildWithNullsOppositeMultiple::class.java
}
}
class ChildWithNullsOppositeMultipleData : WorkspaceEntityData<ChildWithNullsOppositeMultiple>() {
lateinit var childData: String
fun isChildDataInitialized(): Boolean = ::childData.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildWithNullsOppositeMultiple> {
val modifiable = ChildWithNullsOppositeMultipleImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ChildWithNullsOppositeMultiple {
val entity = ChildWithNullsOppositeMultipleImpl()
entity._childData = childData
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildWithNullsOppositeMultiple::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildWithNullsOppositeMultipleData
if (this.childData != other.childData) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildWithNullsOppositeMultipleData
if (this.childData != other.childData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + childData.hashCode()
return result
}
} | apache-2.0 | c05f08df94293c62521599029fb45b5f | 42.053398 | 219 | 0.646256 | 6.065663 | false | false | false | false |
androidstarters/androidstarters.com | templates/androidstarters-kotlin/app/src/main/java/io/mvpstarter/sample/features/detail/MapsSampleActivity.kt | 1 | 1847 | package <%= appPackage %>.features.detail
import android.os.Bundle
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import <%= appPackage %>.R
import <%= appPackage %>.features.base.BaseActivity
class MapsSampleActivity : BaseActivity(), OnMapReadyCallback {
private var map: GoogleMap? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
override fun layoutId() = R.layout.activity_maps_sample
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
override fun onMapReady(googleMap: GoogleMap) {
map = googleMap
// Add a marker in Sydney and move the camera
val sydney = LatLng(-34.0, 151.0)
googleMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
} | mit | ae6373b0c66a9afec9f702a887a78d3a | 41 | 99 | 0.727125 | 4.629073 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/quest/show/usecase/SplitDurationForPomodoroTimerUseCase.kt | 1 | 2550 | package io.ipoli.android.quest.show.usecase
import io.ipoli.android.Constants
import io.ipoli.android.common.UseCase
import io.ipoli.android.quest.Quest
import io.ipoli.android.quest.TimeRange
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 1/16/18.
*/
open class SplitDurationForPomodoroTimerUseCase :
UseCase<SplitDurationForPomodoroTimerUseCase.Params, SplitDurationForPomodoroTimerUseCase.Result> {
override fun execute(parameters: Params): Result {
val quest = parameters.quest
val duration = quest.duration
val pomodoroDuration =
Constants.DEFAULT_POMODORO_WORK_DURATION + Constants.DEFAULT_POMODORO_BREAK_DURATION
if (!quest.hasPomodoroTimer && duration < pomodoroDuration) {
return Result.DurationNotSplit
}
val ranges = quest.timeRanges.toMutableList()
var scheduledDuration = ranges.sumBy { it.duration }
while (scheduledDuration < duration) {
val range =
if (ranges.isEmpty() || ranges.last().type == TimeRange.Type.POMODORO_SHORT_BREAK
|| ranges.last().type == TimeRange.Type.POMODORO_LONG_BREAK) {
val workDuration =
Math.min(
Constants.DEFAULT_POMODORO_WORK_DURATION,
duration - scheduledDuration
)
TimeRange(TimeRange.Type.POMODORO_WORK, workDuration)
} else {
val (breakType, breakDuration) = if ((ranges.size + 1) % 8 == 0) {
val longDuration = Math.min(
Constants.DEFAULT_POMODORO_LONG_BREAK_DURATION,
duration - scheduledDuration
)
Pair(TimeRange.Type.POMODORO_LONG_BREAK, longDuration)
} else {
Pair(
TimeRange.Type.POMODORO_SHORT_BREAK,
Constants.DEFAULT_POMODORO_BREAK_DURATION
)
}
TimeRange(breakType, breakDuration)
}
scheduledDuration += range.duration
ranges.add(range)
}
return Result.DurationSplit(
ranges
)
}
data class Params(val quest: Quest)
sealed class Result {
data class DurationSplit(val timeRanges: List<TimeRange>) : Result()
object DurationNotSplit : Result()
}
} | gpl-3.0 | fb330db7310bfeb7aee267744c144c88 | 37.651515 | 103 | 0.563529 | 5.059524 | false | false | false | false |
JetBrains/teamcity-nuget-support | nuget-feed/src/jetbrains/buildServer/nuget/feed/server/json/AsyncJsonPackageVersionsController.kt | 1 | 2271 | package jetbrains.buildServer.nuget.feed.server.json
import jetbrains.buildServer.nuget.feed.server.NuGetAsyncTaskExecutor
import jetbrains.buildServer.nuget.feed.server.NuGetFeedConstants
import jetbrains.buildServer.nuget.feed.server.NuGetFeedConstants.PROP_NUGET_FEED_ASYNC_REQUEST_TIMOEUT
import jetbrains.buildServer.serverSide.TeamCityProperties
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.context.request.async.WebAsyncTask
import java.util.concurrent.Callable
import javax.servlet.http.HttpServletRequest
@RestController
@RequestMapping(NuGetFeedConstants. NUGET_FEED_ASYNC_V3_PACKAGE_VERSIONS)
class AsyncJsonPackageVersionsController(
private val asyncTaskExecutor: NuGetAsyncTaskExecutor,
private val packageSourceFactory: JsonPackageSourceFactory,
private val adapterFactory: JsonPackageAdapterFactory
) {
@RequestMapping("/{id:.+}/", method = [RequestMethod.GET], produces = ["application/json; charset=UTF-8"])
fun getVersions(
@PathVariable("id") id: String,
request: HttpServletRequest
): WebAsyncTask<ResponseEntity<String>> {
val context = DispatcherUtils.getContext(request)
return asyncTaskExecutor.createAsyncTask<ResponseEntity<String>>
{
if (context == null) {
return@createAsyncTask ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error")
}
val packageSource = packageSourceFactory.create(context.feed)
val results = packageSource.getPackages(id)
if (!results.isEmpty()) {
val adapter = adapterFactory.create(context)
return@createAsyncTask ResponseEntity.ok(JsonExtensions.gson.toJson(adapter.createPackageVersionsResponse(results)))
} else {
return@createAsyncTask ResponseEntity.status(HttpStatus.NOT_FOUND).body("Package $id not found")
}
}
}
}
| apache-2.0 | fa468a6cd713061005e4eb2b02c0c89b | 49.466667 | 132 | 0.752532 | 4.751046 | false | false | false | false |
Turbo87/intellij-emberjs | src/main/kotlin/com/emberjs/cli/EmberCliGenerateTask.kt | 1 | 3717 | package com.emberjs.cli
import com.intellij.history.LocalHistory
import com.intellij.history.LocalHistoryAction
import com.intellij.ide.IdeView
import com.intellij.notification.Notification
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.RefreshQueue
import com.intellij.psi.PsiManager
import kotlin.text.Regex
class EmberCliGenerateTask(project: Project, val workDir: VirtualFile, val template: String,
val name: String, val view: IdeView?) :
Task.Modal(project, "Generate Ember.js ${EmberCli.BLUEPRINTS[template]} '$name'", true) {
private var notification: Notification? = null
private val files = arrayListOf<VirtualFile>()
private fun setNotification(content: String, type: NotificationType) {
notification = NOTIFICATION_GROUP.createNotification("<b>Problem running ember-cli:</b><br/>$content", type)
}
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
indicator.log("Preparing ember command ...")
val cli = EmberCli(project, "generate", template, name)
.apply { workDirectory = workDir.path }
LocalHistory.getInstance().startAction(title).use {
indicator.log("Running ember generate $template $name ...")
val output = try {
cli.run()
} catch (e: Exception) {
return setNotification(e.message?.trim() ?: "Unknown exception occurred", NotificationType.ERROR)
}
indicator.log("Processing ember-cli output ...")
// match " creates some/file.js" lines
val paths = output.lineSequence()
.map { (CREATED_REGEX.find(it) ?: ROUTER_REGEX.matchEntire(it))?.groups?.get(1)?.value }
.map { if (it == "router") "app/router.js" else it }
.filterNotNull()
.toList()
indicator.log("ember-cli modified ${paths.size} files")
// find file in virtual file system
files.addAll(paths
.map { LocalFileSystem.getInstance().refreshAndFindFileByPath("${workDir.path}/$it") }
.filterNotNull())
indicator.log("Refreshing ${files.size} modified files ...")
RefreshQueue.getInstance().refresh(false, true, null, *files.toTypedArray())
}
}
override fun onSuccess() {
notification?.notify(project)
if (view != null) {
val psiManager = PsiManager.getInstance(project)
files.map { psiManager.findFile(it) }.filterNotNull().firstOrNull()?.apply {
view.selectElement(this)
}
}
}
private fun ProgressIndicator.log(string: String) {
text = string
}
private inline fun LocalHistoryAction.use(function: LocalHistoryAction.() -> Unit) {
try {
function()
} finally {
finish()
}
}
companion object {
private val CREATED_REGEX = Regex(" (?:create|overwrite)\\s+(.+)")
private val ROUTER_REGEX = Regex("updating (router)")
val NOTIFICATION_GROUP = NotificationGroup.balloonGroup("ember-cli")
}
}
| apache-2.0 | fc4b42fd818011cac1563ea52f507bea | 38.967742 | 121 | 0.604789 | 4.982574 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantLambdaOrAnonymousFunctionInspection.kt | 5 | 2614 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.refactoring.inline.KotlinInlineAnonymousFunctionProcessor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.codeinsight.utils.findExistingEditor
class RedundantLambdaOrAnonymousFunctionInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : KtVisitorVoid() {
override fun visitNamedFunction(function: KtNamedFunction) {
processExpression(function)
}
override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {
processExpression(lambdaExpression.functionLiteral)
}
private fun processExpression(function: KtFunction) {
if (findCallIfApplicableTo(function) == null) return
val message = if (function is KtNamedFunction)
KotlinBundle.message("inspection.redundant.anonymous.function.description")
else
KotlinBundle.message("inspection.redundant.lambda.description")
holder.registerProblem(function, message, RedundantLambdaOrAnonymousFunctionFix())
}
}
private class RedundantLambdaOrAnonymousFunctionFix : LocalQuickFix {
override fun startInWriteAction(): Boolean = false
override fun getFamilyName(): String = KotlinBundle.message("inspection.redundant.lambda.or.anonymous.function.fix")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val function = descriptor.psiElement as? KtFunction ?: return
val call = KotlinInlineAnonymousFunctionProcessor.findCallExpression(function) ?: return
KotlinInlineAnonymousFunctionProcessor(function, call, function.findExistingEditor(), project).run()
}
}
companion object {
fun findCallIfApplicableTo(function: KtFunction): KtExpression? = if (function.hasBody())
KotlinInlineAnonymousFunctionProcessor.findCallExpression(function)
else
null
}
}
| apache-2.0 | 61e49433fa2b9e87444064ca7b61c7e7 | 46.527273 | 124 | 0.752104 | 5.609442 | false | false | false | false |
GunoH/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/util.kt | 2 | 4015 | // 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.jetbrains.intellij.build.images
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.ui.svg.SvgTranscoder
import com.intellij.ui.svg.createSvgDocument
import com.intellij.util.io.DigestUtil
import java.awt.Dimension
import java.awt.image.BufferedImage
import java.io.File
import java.io.IOException
import java.math.BigInteger
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import javax.imageio.ImageIO
internal val File.children: List<File>
get() = if (isDirectory) listFiles()?.toList() ?: emptyList() else emptyList()
internal fun isImage(file: Path, iconsOnly: Boolean): Boolean {
return if (iconsOnly) isIcon(file) else isImage(file)
}
// allow other project path setups to generate Android Icons
var androidIcons: Path = Paths.get(PathManager.getCommunityHomePath(), "android/artwork/resources")
internal fun isIcon(file: Path): Boolean {
if (!isImage(file)) {
return false
}
val size = imageSize(file) ?: return false
if (file.startsWith(androidIcons)) {
return true
}
return size.height == size.width || size.height <= 100 && size.width <= 100
}
internal fun isImage(file: Path) = ImageExtension.fromName(file.fileName.toString()) != null
internal fun isImage(file: File) = ImageExtension.fromName(file.name) != null
internal fun imageSize(file: Path, failOnMalformedImage: Boolean = false): Dimension? {
val image = try {
loadImage(file, failOnMalformedImage)
}
catch (e: Exception) {
if (failOnMalformedImage) throw e
null
}
if (image == null) {
if (failOnMalformedImage) error("Can't load $file")
println("WARNING: can't load $file")
return null
}
val width = image.width
val height = image.height
return Dimension(width, height)
}
private fun loadImage(file: Path, failOnMalformedImage: Boolean): BufferedImage? {
if (file.toString().endsWith(".svg")) {
// don't mask any exception for svg file
Files.newInputStream(file).use {
try {
return SvgTranscoder.createImage(1f, createSvgDocument(null, it), null)
}
catch (e: Exception) {
throw IOException("Cannot decode $file", e)
}
}
}
try {
return Files.newInputStream(file).buffered().use {
ImageIO.read(it)
}
}
catch (e: Exception) {
if (failOnMalformedImage) throw e
return null
}
}
internal fun md5(file: Path): String {
val hash = DigestUtil.md5().digest(Files.readAllBytes(file))
return BigInteger(hash).abs().toString(16)
}
internal enum class ImageType(private val suffix: String) {
BASIC(""), RETINA("@2x"), DARCULA("_dark"), RETINA_DARCULA("@2x_dark"), STROKE("_stroke");
companion object {
fun getBasicName(suffix: String, prefix: String): String {
return "$prefix/${stripSuffix(FileUtilRt.getNameWithoutExtension(suffix))}"
}
fun fromFile(file: Path): ImageType {
return fromName(FileUtilRt.getNameWithoutExtension(file.fileName.toString()))
}
private fun fromName(name: String): ImageType {
return when {
name.endsWith(RETINA_DARCULA.suffix) -> RETINA_DARCULA
name.endsWith(RETINA.suffix) -> RETINA
name.endsWith(DARCULA.suffix) -> DARCULA
name.endsWith(STROKE.suffix) -> STROKE
else -> BASIC
}
}
fun stripSuffix(name: String): String {
return name.removeSuffix(fromName(name).suffix)
}
}
}
internal enum class ImageExtension(private val suffix: String) {
PNG(".png"), SVG(".svg"), GIF(".gif");
companion object {
fun fromFile(file: Path) = fromName(file.fileName.toString())
fun fromName(name: String): ImageExtension? {
if (name.endsWith(PNG.suffix)) return PNG
if (name.endsWith(SVG.suffix)) return SVG
if (name.endsWith(GIF.suffix)) return GIF
return null
}
}
} | apache-2.0 | 8a924c20a95ccb3d1f84a2bb1e46e3ca | 29.195489 | 140 | 0.696887 | 3.909445 | false | false | false | false |
pureal-code/pureal-os | traits/src/net/pureal/traits/math/Calculatable.kt | 1 | 6429 | package net.pureal.traits.math
public abstract class Calculatable : Number(), Comparable<Any?> {
// INHERITED STUFF
final override fun compareTo(other: Any?): Int = compareTo(other, false)
final fun compareTo(other: Any?, inner: Boolean): Int {
if (other == null) throw IllegalArgumentException()
val it = other.asCalculatable()
try {
return tryCompareTo(it)
} catch (e: IllegalArgumentException) {
try {
return -it.tryCompareTo(this)
} catch (e: IllegalArgumentException) {
if (!inner) return activeEnvironment.intReal(this).compareTo(activeEnvironment.intReal(other), true)
throw e
}
}
}
override fun equals(other: Any?): Boolean = compareTo(other) == 0
override abstract fun toDouble(): Double
override fun toFloat(): Float = toDouble().toFloat()
override abstract fun toLong(): Long
override fun toInt(): Int = toLong().toInt()
override fun toShort(): Short = toLong().toShort()
override fun toByte(): Byte = toLong().toByte()
override fun toChar(): Char = toLong().toChar()
// WHAT IS IMPORTANT
abstract fun tryCompareTo(other: Calculatable): Int
open fun plus(): Calculatable = this
abstract fun minus(): Calculatable
open fun plus(other: Any?): Calculatable = plus(other, false)
// NOTE: plus is open so inherited classes can define its own return type: recommended implementations
// - return plus(other, false) as T
// - return super<Calculatable>.plus(other) as T
// same goes with minus, times etc
// But be careful, that the result may not always be of that type
final fun plus(other: Any?, inner: Boolean): Calculatable {
if (other == null) throw IllegalArgumentException()
val it = other.asCalculatable()
try {
return tryPlus(it)
} catch (e: IllegalArgumentException) {
try {
return it.tryPlus(this)
} catch (e: IllegalArgumentException) {
if (!inner) return activeEnvironment.intReal(this).plus(activeEnvironment.intReal(other), true)
throw e
}
}
}
open fun minus(other: Any?): Calculatable = minus(other, false)
final fun minus(other: Any?, inner: Boolean): Calculatable {
if (other == null) throw IllegalArgumentException()
val it = other.asCalculatable()
try {
return tryMinus(it)
} catch (e: IllegalArgumentException) {
try {
return -it.tryPlus(this)
} catch (e: IllegalArgumentException) {
if (!inner) return activeEnvironment.intReal(this).minus(activeEnvironment.intReal(other), true)
throw e
}
}
}
open fun times(other: Any?): Calculatable = times(other, false)
final fun times(other: Any?, inner: Boolean): Calculatable {
if (other == null) throw IllegalArgumentException()
val it = other.asCalculatable()
try {
return tryTimes(it)
} catch (e: IllegalArgumentException) {
try {
return it.tryTimes(this)
} catch (e: IllegalArgumentException) {
if (!inner) return activeEnvironment.intReal(this).times(activeEnvironment.intReal(other), true)
throw e
}
}
}
open fun div(other: Any?): Calculatable = div(other, false)
final fun div(other: Any?, inner: Boolean): Calculatable {
if (other == null) throw IllegalArgumentException()
val it = other.asCalculatable()
try {
return tryDiv(it)
} catch (e: IllegalArgumentException) {
if (!inner) return activeEnvironment.intReal(this).plus(activeEnvironment.intReal(other), true)
return activeEnvironment.intReal(1).tryDiv(it).tryTimes(this)
}
}
open fun mod(other: Any?): Calculatable = mod(other, false)
final fun mod(other: Any?, inner: Boolean): Calculatable {
if (other == null) throw IllegalArgumentException()
val it = other.asCalculatable()
try {
return tryMod(it)
} catch (e: IllegalArgumentException) {
if (!inner) return activeEnvironment.intReal(this).plus(activeEnvironment.intReal(other), true)
throw e
}
}
open fun divideAndRemainder(other: Any?): Array<Calculatable> = array(this / other, this % other)
// may be optimized by inherited classes
abstract fun tryPlus(other: Any?): Calculatable
abstract fun tryMinus(other: Any?): Calculatable
abstract fun tryTimes(other: Any?): Calculatable
abstract fun tryDiv(other: Any?): Calculatable
abstract fun tryMod(other: Any?): Calculatable
abstract fun floor(): Calculatable
abstract fun ceil(): Calculatable
abstract fun round(): Calculatable
abstract fun abs(): Calculatable
final val shell: MathShell
init {
shell = activeShell
}
final val env: MathEnvironment get() = shell.environment
}
fun Any.asCalculatable(): Calculatable = if (this is Calculatable) this; else activeEnvironment.intReal(this)
fun gcd(a: Number, b: Number): Calculatable {
var a = a.asCalculatable().abs()
var b = b.asCalculatable().abs()
var c: Calculatable
if (a equals 0) return b
if (b equals 0) return a
if (a > b) {
c = a
a = b
b = c
}
var i = 0
while (a > 0 && a != b && i < 2 * activeEnvironment.accuracy) {
c = b % a
b = a
a = c
i++
}
if (i >= 2 * activeEnvironment.accuracy) return 0.asCalculatable()
return b
}
fun lcm(a: Number, b: Number): Calculatable {
val a = a.asCalculatable().abs()
val b = b.asCalculatable().abs()
val g = gcd(a, b)
if (g equals 0) return Infinity
return a * b / g
}
fun Number.plus(other: Calculatable): Calculatable = other + this
fun Number.minus(other: Calculatable): Calculatable = -other + this
fun Number.times(other: Calculatable): Calculatable = other * this
fun Number.div(other: Calculatable): Calculatable = this.asCalculatable() / other
fun Number.mod(other: Calculatable): Calculatable = this.asCalculatable() % other
fun Number.divideAndRemainder(other: Calculatable): Array<Calculatable> = array(this / other, this % other) | bsd-3-clause | 5fb9eed6e7373cc1016ca681e4b99d01 | 34.722222 | 116 | 0.620625 | 4.283145 | false | false | false | false |
ClearVolume/scenery | src/test/kotlin/graphics/scenery/tests/unit/repl/REPLTests.kt | 2 | 1631 | package graphics.scenery.tests.unit.repl
import graphics.scenery.Hub
import graphics.scenery.repl.REPL
import graphics.scenery.utils.LazyLogger
import org.junit.BeforeClass
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
/**
* Class containing tests for the [graphics.scenery.repl.REPL].
*
* @author Ulrik Guenther <[email protected]>
*/
class REPLTests {
private val logger by LazyLogger()
/** Companion object for test setup */
companion object {
@JvmStatic @BeforeClass
fun setHeadless() {
System.setProperty("scenery.Headless", "true")
}
}
/** Tests the default startup script */
@Test
fun testStartupScript() {
val hub = Hub()
val repl = REPL(hub)
val result = repl.start()
assertNotNull(result, "Required REPL initialisation result to be non-null.")
}
/** Tests evaluation and return. */
@Test
fun testEval() {
val hub = Hub()
val repl = REPL(hub)
repl.start()
val resultAddition = repl.eval("1+2")
assertEquals(3, resultAddition, "Required 1+2 to be 3.")
val resultBool = repl.eval("6*7 == 42")
assertEquals(true, resultBool, "Required 6*7 == 42 to be true.")
}
/** Tests object accessibility. */
@Test
fun testObjectAccess() {
val hub = Hub()
val repl = REPL(hub)
repl.start()
repl.addAccessibleObject(repl)
val result = repl.eval("locate('REPL') != None")
assertEquals(true, result, "Required REPL to be accessible from script.")
}
}
| lgpl-3.0 | d46e4be205e9cf1ee6d9d8e756bcb99e | 24.484375 | 84 | 0.62477 | 4.171355 | false | true | false | false |
mdanielwork/intellij-community | uast/uast-common/src/org/jetbrains/uast/expressions/UCallExpression.kt | 6 | 3571 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiType
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.internal.log
import org.jetbrains.uast.visitor.UastTypedVisitor
import org.jetbrains.uast.visitor.UastVisitor
/**
* Represents a call expression (method/constructor call, array initializer).
*/
interface UCallExpression : UExpression, UResolvable {
/**
* Returns the call kind.
*/
val kind: UastCallKind
/**
* Returns the called method name, or null if the call is not a method call.
* This property should return the actual resolved function name.
*/
val methodName: String?
/**
* Returns the expression receiver.
* For example, for call `a.b.[c()]` the receiver is `a.b`.
*/
val receiver: UExpression?
/**
* Returns the receiver type, or null if the call has not a receiver.
*/
val receiverType: PsiType?
/**
* Returns the function reference expression if the call is a non-constructor method call, null otherwise.
*/
val methodIdentifier: UIdentifier?
/**
* Returns the class reference if the call is a constructor call, null otherwise.
*/
val classReference: UReferenceExpression?
/**
* Returns the value argument count.
*
* Retrieving the argument count could be faster than getting the [valueArguments.size],
* because there is no need to create actual [UExpression] instances.
*/
val valueArgumentCount: Int
/**
* Returns the list of value arguments.
*/
val valueArguments: List<UExpression>
/**
* Returns the type argument count.
*/
val typeArgumentCount: Int
/**
* Returns the type arguments for the call.
*/
val typeArguments: List<PsiType>
/**
* Returns the return type of the called function, or null if the call is not a function call.
*/
val returnType: PsiType?
/**
* Resolve the called method.
*
* @return the [PsiMethod], or null if the method was not resolved.
* Note that the [PsiMethod] is an unwrapped [PsiMethod], not a [UMethod].
*/
override fun resolve(): PsiMethod?
override fun accept(visitor: UastVisitor) {
if (visitor.visitCallExpression(this)) return
annotations.acceptList(visitor)
methodIdentifier?.accept(visitor)
classReference?.accept(visitor)
valueArguments.acceptList(visitor)
visitor.afterVisitCallExpression(this)
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R =
visitor.visitCallExpression(this, data)
override fun asLogString(): String = log("kind = $kind, argCount = $valueArgumentCount)")
override fun asRenderString(): String {
val ref = classReference?.asRenderString() ?: methodName ?: methodIdentifier?.asRenderString() ?: "<noref>"
return ref + "(" + valueArguments.joinToString { it.asRenderString() } + ")"
}
}
interface UCallExpressionEx : UCallExpression {
fun getArgumentForParameter(i: Int): UExpression?
} | apache-2.0 | bcc9d72e6b8186243b5b64397eb237b0 | 28.766667 | 111 | 0.711005 | 4.425031 | false | false | false | false |
dahlstrom-g/intellij-community | java/java-tests/testSrc/com/intellij/java/refactoring/RefactorThisTest.kt | 8 | 5881 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.refactoring
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.impl.PresentationFactory
import com.intellij.openapi.actionSystem.impl.Utils
import com.intellij.refactoring.actions.*
import com.intellij.testFramework.LightJavaCodeInsightTestCase
import org.jetbrains.annotations.NonNls
class RefactorThisTest: LightJavaCodeInsightTestCase() {
private val BASE_PATH: @NonNls String = "/refactoring/refactorThis"
fun testPullMembersUpWithExtends() {
assertTrue(doActionExists<PullUpAction>())
}
fun testPullMembersUpWithImplements() {
assertTrue(doActionExists<PullUpAction>())
}
fun testPullMembersUpFromAnonymousClass() {
assertTrue(doActionExists<PullUpAction>())
}
fun testPullMembersUpFiltered() {
assertFalse(doActionExists<PullUpAction>())
}
fun testInheritanceToDelegationWithExtends() {
assertTrue(doActionExists<InheritanceToDelegationAction>())
}
fun testInheritanceToDelegationWithImplements() {
assertTrue(doActionExists<InheritanceToDelegationAction>())
}
fun testInheritanceToDelegationNoSuperClass() {
assertFalse(doActionExists<InheritanceToDelegationAction>())
}
fun testInheritanceToDelegationOutsideDeclaration() {
assertFalse(doActionExists<InheritanceToDelegationAction>())
}
fun testReplaceMethodWithMethodObjectIsFiltered() {
assertFalse(doActionExists<ReplaceMethodWithMethodObjectAction>())
}
fun testFindAndReplaceDuplicatesIsFiltered() {
assertFalse(doActionExists<MethodDuplicatesAction>())
}
fun testFindAndReplaceDuplicatesOnMethodDeclaration() {
assertTrue(doActionExists<MethodDuplicatesAction>())
}
fun testFindAndReplaceDuplicatesOnFieldDeclaration() {
assertTrue(doActionExists<MethodDuplicatesAction>())
}
fun testGenerifyIsFiltered() {
assertFalse(doActionExists<TypeCookAction>())
}
fun testUseInterfaceWherePossibleOnDeclaration() {
assertTrue(doActionExists<TurnRefsToSuperAction>())
}
fun testUseInterfaceWherePossibleFilteredOnReference() {
assertFalse(doActionExists<TurnRefsToSuperAction>())
}
fun testUseInterfaceWherePossibleIsFiltered() {
assertFalse(doActionExists<TurnRefsToSuperAction>())
}
fun testSafeDeleteIsFilteredOnClassReference() {
assertFalse(doActionExists<SafeDeleteAction>())
}
fun testSafeDeleteIsFilteredOnMethodReference() {
assertFalse(doActionExists<SafeDeleteAction>())
}
fun testSafeDeleteIsFilteredOnVariableReference() {
assertFalse(doActionExists<SafeDeleteAction>())
}
fun testSafeDeleteOnClassDeclaration() {
assertTrue(doActionExists<SafeDeleteAction>())
}
fun testSafeDeleteOnMethodDeclaration() {
assertTrue(doActionExists<SafeDeleteAction>())
}
fun testSafeDeleteOnVariableDeclaration() {
assertTrue(doActionExists<SafeDeleteAction>())
}
fun testMoveIsFilteredOnStatement() {
assertFalse(doActionExists<MoveAction>())
}
fun testMoveIsFilteredOnMethodReference() {
assertFalse(doActionExists<MoveAction>())
}
fun testMoveIsFilteredOnConstructor() {
assertFalse(doActionExists<MoveAction>())
}
fun testMoveOnMethodDeclaration() {
assertTrue(doActionExists<MoveAction>())
}
fun testMoveOnClassDeclaration() {
assertTrue(doActionExists<MoveAction>())
}
fun testIntroduceParameterObject() {
assertTrue(doActionExists<IntroduceParameterObjectAction>())
}
fun testIntroduceParameterObjectFiltered() {
assertFalse(doActionExists<IntroduceParameterObjectAction>())
}
fun testIntroduceParameterObjectFiltered2() {
assertFalse(doActionExists<IntroduceParameterObjectAction>())
}
fun testMakeStaticOnMethodDeclaration() {
assertTrue(doActionExists<MakeStaticAction>())
}
fun testMakeStaticOnClassDeclaration() {
assertTrue(doActionExists<MakeStaticAction>())
}
fun testMakeStaticFilteredOnStaticClass() {
assertFalse(doActionExists<MakeStaticAction>())
}
fun testMakeStaticFiltered() {
assertFalse(doActionExists<MakeStaticAction>())
}
fun testConvertToInstanceMethod() {
assertTrue(doActionExists<ConvertToInstanceMethodAction>())
}
fun testConvertToInstanceMethodFiltered() {
assertFalse(doActionExists<ConvertToInstanceMethodAction>())
}
fun testPushDownOnMethod() {
assertTrue(doActionExists<PushDownAction>())
}
fun testPushDownOnClass() {
assertTrue(doActionExists<PushDownAction>())
}
fun testPushDownFiltered() {
assertFalse(doActionExists<PushDownAction>())
}
fun testIntroduceFunctionalVariableFromExpression() {
assertTrue(doActionExists<IntroduceFunctionalVariableAction>())
}
fun testIntroduceFunctionalVariableFromStatement() {
assertTrue(doActionExists<IntroduceFunctionalVariableAction>())
}
fun testIntroduceFunctionalVariableFiltered() {
assertFalse(doActionExists<IntroduceFunctionalVariableAction>())
}
private inline fun <reified A> doActionExists(): Boolean {
configureByFile("$BASE_PATH/${getTestName(false)}.java")
val actions = findAvailableActions()
return actions.any { action -> action is A }
}
private fun findAvailableActions(): List<AnAction> {
val action = RefactoringQuickListPopupAction()
val group = DefaultActionGroup()
val dataContext = Utils.wrapDataContext(DataManager.getInstance().getDataContext(editor.component))
action.fillActions(project, group, dataContext)
return Utils.expandActionGroup(group, PresentationFactory(), dataContext, ActionPlaces.REFACTORING_QUICKLIST)
}
} | apache-2.0 | 5f9a0289c039b73ec05ab12a9c80e7d7 | 28.557789 | 158 | 0.78065 | 4.975465 | false | true | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/api/AbstractHLInspection.kt | 2 | 4318 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.fir.api
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.api.applicator.HLApplicator
import org.jetbrains.kotlin.idea.api.applicator.HLApplicatorInput
import org.jetbrains.kotlin.idea.fir.api.applicator.*
import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt
import org.jetbrains.kotlin.analysis.api.analyzeWithReadAction
import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtVisitorVoid
import kotlin.reflect.KClass
abstract class AbstractHLInspection<PSI : KtElement, INPUT : HLApplicatorInput>(
val elementType: KClass<PSI>
) : AbstractKotlinInspection() {
final override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) =
object : KtVisitorVoid() {
override fun visitKtElement(element: KtElement) {
super.visitKtElement(element)
if (!elementType.isInstance(element) || element.textLength == 0) return
@Suppress("UNCHECKED_CAST")
visitTargetElement(element as PSI, holder, isOnTheFly)
}
}
private fun visitTargetElement(element: PSI, holder: ProblemsHolder, isOnTheFly: Boolean) {
if (!applicator.isApplicableByPsi(element, holder.project)) return
val targets = applicabilityRange.getApplicabilityRanges(element)
if (targets.isEmpty()) return
val input = getInput(element) ?: return
require(input.isValidFor(element)) { "Input should be valid after creation" }
registerProblems(holder, element, targets, isOnTheFly, input)
}
private fun registerProblems(
holder: ProblemsHolder,
element: PSI,
ranges: List<TextRange>,
isOnTheFly: Boolean,
input: INPUT
) {
val highlightType = presentation.getHighlightType(element)
if (!isOnTheFly && highlightType == ProblemHighlightType.INFORMATION) return
val description = applicator.getActionName(element, input)
val fix = applicator.asLocalQuickFix(input, actionName = applicator.getActionName(element, input))
ranges.forEach { range ->
registerProblem(holder, element, range, description, highlightType, isOnTheFly, fix)
}
}
private fun registerProblem(
holder: ProblemsHolder,
element: PSI,
range: TextRange,
description: String,
highlightType: ProblemHighlightType,
isOnTheFly: Boolean,
fix: LocalQuickFix
) {
with(holder) {
val problemDescriptor = manager.createProblemDescriptor(element, range, description, highlightType, isOnTheFly, fix)
registerProblem(problemDescriptor)
}
}
@OptIn(KtAllowAnalysisOnEdt::class)
private fun getInput(element: PSI): INPUT? = allowAnalysisOnEdt {
analyzeWithReadAction(element) {
with(inputProvider) { provideInput(element) }
}
}
abstract val presentation: HLPresentation<PSI>
abstract val applicabilityRange: HLApplicabilityRange<PSI>
abstract val inputProvider: HLApplicatorInputProvider<PSI, INPUT>
abstract val applicator: HLApplicator<PSI, INPUT>
}
private fun <PSI : PsiElement, INPUT : HLApplicatorInput> HLApplicator<PSI, INPUT>.asLocalQuickFix(
input: INPUT,
actionName: String,
): LocalQuickFix = object : LocalQuickFix {
override fun startInWriteAction() = false
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
@Suppress("UNCHECKED_CAST")
val element = descriptor.psiElement as PSI
if (isApplicableByPsi(element, project) && input.isValidFor(element)) {
applyTo(element, input, project, editor = null)
}
}
override fun getFamilyName() = [email protected]()
override fun getName() = actionName
} | apache-2.0 | a48fa72ca5cd5310b2726bef18a2b1e5 | 38.263636 | 158 | 0.712598 | 5.009281 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/fixers/fixersUtil.kt | 6 | 706 | // 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.editor.fixers
import com.intellij.openapi.editor.Document
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
val PsiElement.range: TextRange get() = textRange!!
val TextRange.start: Int get() = startOffset
val TextRange.end: Int get() = endOffset
fun PsiElement.startLine(doc: Document): Int = doc.getLineNumber(range.start)
fun PsiElement.endLine(doc: Document): Int = doc.getLineNumber(range.end)
fun PsiElement?.isWithCaret(caret: Int) = this?.textRange?.contains(caret) == true
| apache-2.0 | 635f29b7972c10aea0cabf915f195a0e | 46.066667 | 158 | 0.784703 | 3.857923 | false | false | false | false |
cdietze/klay | tripleklay/tripleklay-demo/src/main/kotlin/tripleklay/demo/core/anim/FramesDemo.kt | 1 | 3047 | package tripleklay.demo.core.anim
import klay.core.Surface
import klay.scene.GroupLayer
import klay.scene.Layer
import tripleklay.anim.Flipbook
import tripleklay.demo.core.DemoScreen
import tripleklay.ui.Group
import tripleklay.ui.Root
import tripleklay.util.PackedFrames
import tripleklay.util.SimpleFrames
class FramesDemo : DemoScreen() {
override fun name(): String {
return "Flipbook"
}
override fun title(): String {
return "Flipbook Demo"
}
override fun createIface(root: Root): Group? {
val width = size().width
val height = size().height
val bg = object : Layer() {
override fun paintImpl(surf: Surface) {
surf.setFillColor(0xFFCCCCCC.toInt())
surf.fillRect(0f, 0f, width, height)
}
}
bg.setDepth(-1f)
layer.add(bg)
// test our simple frames
val box = GroupLayer()
layer.addAt(box, 0f, 100f)
val sheet = assets().getImage("images/spritesheet.png")
val frames = SimpleFrames(sheet, 60f, 60f, 60)
iface.anim.repeat(box).flipbook(box, Flipbook(frames, 66f))
iface.anim.repeat(box).tweenX(box).to(width - frames.width()).`in`(2000f).easeInOut().then().tweenX(box).to(0f).`in`(2000f).easeInOut()
// test our packed frames
val packed = assets().getImage("images/orb_burst.png")
assets().getText("images/orb_burst.json").onSuccess({ json: String ->
val box = GroupLayer()
layer.addAt(box, 100f, 200f)
iface.anim.repeat(box).flipbook(
box, Flipbook(PackedFrames(packed, json().parse(json)), 99f)).then().setVisible(box, false).then().delay(500f).then().setVisible(box, true)
val pbox = GroupLayer()
layer.addAt(pbox, 300f, 200f)
iface.anim.repeat(pbox).flipbook(
pbox, Flipbook(PackedFrames(packed, PACKED), 99f)).then().setVisible(pbox, false).then().delay(500f).then().setVisible(pbox, true)
})
return null
}
companion object {
// copied from assets/target/classes/assets/images/orb_burst.java
protected val PACKED = arrayOf(floatArrayOf(202.0f, 204.0f), floatArrayOf(41.0f, 50.0f), floatArrayOf(320.0f, 162.0f, 117.0f, 117.0f), floatArrayOf(42.0f, 50.0f), floatArrayOf(438.0f, 162.0f, 117.0f, 117.0f), floatArrayOf(43.0f, 50.0f), floatArrayOf(320.0f, 280.0f, 117.0f, 117.0f), floatArrayOf(42.0f, 50.0f), floatArrayOf(438.0f, 280.0f, 117.0f, 117.0f), floatArrayOf(28.0f, 31.0f), floatArrayOf(176.0f, 162.0f, 143.0f, 161.0f), floatArrayOf(41.0f, 28.0f), floatArrayOf(176.0f, 324.0f, 119.0f, 147.0f), floatArrayOf(32.0f, 0.0f), floatArrayOf(0.0f, 346.0f, 134.0f, 174.0f), floatArrayOf(16.0f, 18.0f), floatArrayOf(402.0f, 0.0f, 166.0f, 143.0f), floatArrayOf(0.0f, 45.0f), floatArrayOf(201.0f, 0.0f, 200.0f, 130.0f), floatArrayOf(0.0f, 30.0f), floatArrayOf(0.0f, 0.0f, 200.0f, 161.0f), floatArrayOf(10.0f, 21.0f), floatArrayOf(0.0f, 162.0f, 175.0f, 183.0f))
}
}
| apache-2.0 | fdc23096e838e64d3860b0ad56a7f571 | 46.609375 | 867 | 0.64063 | 3.121926 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/KotlinDslGradleKotlinFrameworkSupportProvider.kt | 2 | 13417 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleJava.configuration
import com.intellij.framework.FrameworkTypeEx
import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider
import com.intellij.ide.util.frameworkSupport.FrameworkSupportModel
import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys
import com.intellij.openapi.externalSystem.model.project.ProjectId
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ModifiableModelsProvider
import com.intellij.openapi.roots.ModifiableRootModel
import org.gradle.util.GradleVersion
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.KotlinIcons
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.configuration.DEFAULT_GRADLE_PLUGIN_REPOSITORY
import org.jetbrains.kotlin.idea.configuration.LAST_SNAPSHOT_VERSION
import org.jetbrains.kotlin.idea.configuration.getRepositoryForVersion
import org.jetbrains.kotlin.idea.configuration.toKotlinRepositorySnippet
import org.jetbrains.kotlin.idea.formatter.KotlinStyleGuideCodeStyle
import org.jetbrains.kotlin.idea.formatter.ProjectCodeStyleImporter
import org.jetbrains.kotlin.idea.gradle.KotlinIdeaGradleBundle
import org.jetbrains.kotlin.idea.gradle.configuration.GradlePropertiesFileFacade
import org.jetbrains.kotlin.idea.gradle.configuration.MIN_GRADLE_VERSION_FOR_NEW_PLUGIN_SYNTAX
import org.jetbrains.kotlin.idea.gradleJava.configuration.KotlinBuildScriptManipulator.Companion.GSK_KOTLIN_VERSION_PROPERTY_NAME
import org.jetbrains.kotlin.idea.gradleJava.configuration.KotlinBuildScriptManipulator.Companion.getKotlinGradlePluginClassPathSnippet
import org.jetbrains.kotlin.idea.gradleJava.configuration.KotlinBuildScriptManipulator.Companion.getKotlinModuleDependencySnippet
import org.jetbrains.kotlin.idea.projectWizard.WizardStatsService
import org.jetbrains.kotlin.idea.versions.MAVEN_JS_STDLIB_ID
import org.jetbrains.kotlin.idea.versions.getDefaultJvmTarget
import org.jetbrains.kotlin.idea.versions.getStdlibArtifactId
import org.jetbrains.plugins.gradle.frameworkSupport.BuildScriptDataBuilder
import org.jetbrains.plugins.gradle.frameworkSupport.KotlinDslGradleFrameworkSupportProvider
import javax.swing.Icon
abstract class KotlinDslGradleKotlinFrameworkSupportProvider(
val frameworkTypeId: String,
@Nls val displayName: String,
val frameworkIcon: Icon
) : KotlinDslGradleFrameworkSupportProvider() {
override fun getFrameworkType(): FrameworkTypeEx = object : FrameworkTypeEx(frameworkTypeId) {
override fun getIcon(): Icon = frameworkIcon
override fun getPresentableName(): String = displayName
override fun createProvider(): FrameworkSupportInModuleProvider = this@KotlinDslGradleKotlinFrameworkSupportProvider
}
override fun createConfigurable(model: FrameworkSupportModel) = KotlinGradleFrameworkSupportInModuleConfigurable(model, this)
override fun addSupport(
projectId: ProjectId,
module: Module,
rootModel: ModifiableRootModel,
modifiableModelsProvider: ModifiableModelsProvider,
buildScriptData: BuildScriptDataBuilder
) {
var kotlinVersion = KotlinPluginLayout.standaloneCompilerVersion
val additionalRepository = getRepositoryForVersion(kotlinVersion)
if (KotlinPluginLayout.standaloneCompilerVersion.isSnapshot) {
kotlinVersion = LAST_SNAPSHOT_VERSION
}
val useNewSyntax = buildScriptData.gradleVersion >= MIN_GRADLE_VERSION_FOR_NEW_PLUGIN_SYNTAX
if (useNewSyntax) {
if (additionalRepository != null) {
val repository = additionalRepository.toKotlinRepositorySnippet()
updateSettingsScript(module) {
with(it) {
addPluginRepository(additionalRepository)
addMavenCentralPluginRepository()
addPluginRepository(DEFAULT_GRADLE_PLUGIN_REPOSITORY)
}
}
buildScriptData.addRepositoriesDefinition("mavenCentral()")
buildScriptData.addRepositoriesDefinition(repository)
}
buildScriptData
.addPluginDefinitionInPluginsGroup(getPluginDefinition() + " version \"${kotlinVersion.artifactVersion}\"")
} else {
if (additionalRepository != null) {
val repository = additionalRepository.toKotlinRepositorySnippet()
buildScriptData.addBuildscriptRepositoriesDefinition(repository)
buildScriptData.addRepositoriesDefinition("mavenCentral()")
buildScriptData.addRepositoriesDefinition(repository)
}
buildScriptData
.addPropertyDefinition("val $GSK_KOTLIN_VERSION_PROPERTY_NAME: String by extra")
.addPluginDefinition(getOldSyntaxPluginDefinition())
.addBuildscriptRepositoriesDefinition("mavenCentral()")
// TODO: in gradle > 4.1 this could be single declaration e.g. 'val kotlin_version: String by extra { "1.1.11" }'
.addBuildscriptPropertyDefinition("var $GSK_KOTLIN_VERSION_PROPERTY_NAME: String by extra\n $GSK_KOTLIN_VERSION_PROPERTY_NAME = \"${kotlinVersion.artifactVersion}\"")
.addBuildscriptDependencyNotation(getKotlinGradlePluginClassPathSnippet())
}
buildScriptData.addRepositoriesDefinition("mavenCentral()")
val isNewProject = module.project.getUserData(ExternalSystemDataKeys.NEWLY_CREATED_PROJECT) == true
if (isNewProject) {
ProjectCodeStyleImporter.apply(module.project, KotlinStyleGuideCodeStyle.INSTANCE)
GradlePropertiesFileFacade.forProject(module.project).addCodeStyleProperty(KotlinStyleGuideCodeStyle.CODE_STYLE_SETTING)
}
val projectCreationStats = WizardStatsService.ProjectCreationStats("Gradle", this.presentableName, "gradleKotlin")
WizardStatsService.logDataOnProjectGenerated(session = null, module.project, projectCreationStats)
}
protected abstract fun getOldSyntaxPluginDefinition(): String
protected abstract fun getPluginDefinition(): String
protected fun composeDependency(buildScriptData: BuildScriptDataBuilder, artifactId: String): String {
return if (buildScriptData.gradleVersion >= MIN_GRADLE_VERSION_FOR_NEW_PLUGIN_SYNTAX)
"implementation(${getKotlinModuleDependencySnippet(artifactId, null)})"
else
"implementation(${getKotlinModuleDependencySnippet(artifactId, "\$$GSK_KOTLIN_VERSION_PROPERTY_NAME")})"
}
}
class KotlinDslGradleKotlinJavaFrameworkSupportProvider :
KotlinDslGradleKotlinFrameworkSupportProvider(
"KOTLIN",
KotlinIdeaGradleBundle.message("display.name.kotlin.jvm"),
KotlinIcons.SMALL_LOGO
) {
override fun getOldSyntaxPluginDefinition() = "plugin(\"${KotlinGradleModuleConfigurator.KOTLIN}\")"
override fun getPluginDefinition() = "kotlin(\"jvm\")"
override fun addSupport(
projectId: ProjectId,
module: Module,
rootModel: ModifiableRootModel,
modifiableModelsProvider: ModifiableModelsProvider,
buildScriptData: BuildScriptDataBuilder
) {
super.addSupport(projectId, module, rootModel, modifiableModelsProvider, buildScriptData)
val jvmTarget = getDefaultJvmTarget(rootModel.sdk, KotlinPluginLayout.standaloneCompilerVersion)
if (jvmTarget != null) {
addJvmTargetTask(buildScriptData)
}
val artifactId = getStdlibArtifactId(rootModel.sdk, KotlinPluginLayout.standaloneCompilerVersion)
buildScriptData.addDependencyNotation(composeDependency(buildScriptData, artifactId))
}
private fun addJvmTargetTask(buildScriptData: BuildScriptDataBuilder) {
val minGradleVersion = GradleVersion.version("5.0")
if (buildScriptData.gradleVersion >= minGradleVersion)
buildScriptData
.addOther(
"""
tasks {
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
}""".trimIndent()
)
else {
buildScriptData
.addImport("org.jetbrains.kotlin.gradle.tasks.KotlinCompile")
.addOther("tasks.withType<KotlinCompile> {\n kotlinOptions.jvmTarget = \"1.8\"\n}\n")
}
}
}
abstract class AbstractKotlinDslGradleKotlinJSFrameworkSupportProvider(
frameworkTypeId: String,
@Nls displayName: String
) : KotlinDslGradleKotlinFrameworkSupportProvider(frameworkTypeId, displayName, KotlinIcons.JS) {
abstract val jsSubTargetName: String
override fun addSupport(
projectId: ProjectId,
module: Module,
rootModel: ModifiableRootModel,
modifiableModelsProvider: ModifiableModelsProvider,
buildScriptData: BuildScriptDataBuilder
) {
super.addSupport(projectId, module, rootModel, modifiableModelsProvider, buildScriptData)
buildScriptData.addOther(
"""
kotlin {
js {
$jsSubTargetName {
""".trimIndent() +
(
additionalSubTargetSettings()
?.lines()
?.joinToString("\n", "\n", "\n") { line: String ->
if (line.isBlank()) {
line
} else {
line
.prependIndent()
.prependIndent()
.prependIndent()
}
} ?: "\n"
) +
"""
}
binaries.executable()
}
}
""".trimIndent()
)
val artifactId = MAVEN_JS_STDLIB_ID.removePrefix("kotlin-")
buildScriptData.addDependencyNotation(composeDependency(buildScriptData, artifactId))
}
abstract fun additionalSubTargetSettings(): String?
override fun getOldSyntaxPluginDefinition(): String = "plugin(\"${KotlinJsGradleModuleConfigurator.KOTLIN_JS}\")"
override fun getPluginDefinition(): String = "id(\"org.jetbrains.kotlin.js\")"
}
class KotlinDslGradleKotlinJSBrowserFrameworkSupportProvider :
AbstractKotlinDslGradleKotlinJSFrameworkSupportProvider(
"KOTLIN_JS_BROWSER",
KotlinIdeaGradleBundle.message("display.name.kotlin.js.for.browser")
) {
override val jsSubTargetName: String
get() = "browser"
override fun addSupport(
projectId: ProjectId,
module: Module,
rootModel: ModifiableRootModel,
modifiableModelsProvider: ModifiableModelsProvider,
buildScriptData: BuildScriptDataBuilder
) {
super.addSupport(projectId, module, rootModel, modifiableModelsProvider, buildScriptData)
addBrowserSupport(module)
}
override fun additionalSubTargetSettings(): String =
browserConfiguration()
}
class KotlinDslGradleKotlinJSNodeFrameworkSupportProvider :
AbstractKotlinDslGradleKotlinJSFrameworkSupportProvider(
"KOTLIN_JS_NODE",
KotlinIdeaGradleBundle.message("display.name.kotlin.js.for.node.js")
) {
override val jsSubTargetName: String
get() = "nodejs"
override fun additionalSubTargetSettings(): String? =
null
}
class KotlinDslGradleKotlinMPPFrameworkSupportProvider :
KotlinDslGradleKotlinFrameworkSupportProvider(
"KOTLIN_MPP",
KotlinIdeaGradleBundle.message("display.name.kotlin.multiplatform"),
KotlinIcons.MPP
) {
override fun getOldSyntaxPluginDefinition() = "plugin(\"org.jetbrains.kotlin.multiplatform\")"
override fun getPluginDefinition() = "kotlin(\"multiplatform\")"
override fun addSupport(
projectId: ProjectId,
module: Module,
rootModel: ModifiableRootModel,
modifiableModelsProvider: ModifiableModelsProvider,
buildScriptData: BuildScriptDataBuilder
) {
super.addSupport(projectId, module, rootModel, modifiableModelsProvider, buildScriptData)
buildScriptData.addOther(
"""kotlin {
/* Targets configuration omitted.
* To find out how to configure the targets, please follow the link:
* https://kotlinlang.org/docs/reference/building-mpp-with-gradle.html#setting-up-targets */
sourceSets {
val commonMain by getting {
dependencies {
implementation(kotlin("stdlib-common"))
}
}
val commonTest by getting {
dependencies {
implementation(kotlin("test-common"))
implementation(kotlin("test-annotations-common"))
}
}
}
}"""
)
}
}
| apache-2.0 | 881be21e738b97ecb095116066581a42 | 43.723333 | 185 | 0.67966 | 5.9341 | false | true | false | false |
CThawanapong/styleable-views | styleable-views/src/main/java/com/github/cthawanapong/view/StyleableButton.kt | 1 | 10023 | package com.github.cthawanapong.view
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.Parcelable
import android.support.v4.content.ContextCompat
import android.support.v7.content.res.AppCompatResources
import android.support.v7.widget.CardView
import android.util.AttributeSet
import android.util.SparseArray
import android.util.TypedValue
import android.view.View
import android.widget.Button
import com.github.cthawanapong.model.BundleSavedState
import com.github.cthawanapong.styleableviews.R
import kotlinx.android.synthetic.main.view_styleable_button.view.*
/**
* Created by CThawanapong on 27/1/2018 AD.
* Email: [email protected]
*/
class StyleableButton @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0
) : CardView(context, attrs, defStyleAttr) {
companion object {
@JvmStatic
private val TAG = StyleableButton::class.java.simpleName
@JvmStatic
private val ARG_CHILD_STATES = "childrenStates"
@JvmStatic
private val ARG_BUTTON_TEXT = "ARG_BUTTON_TEXT"
@JvmStatic
private val ARG_TEXT_SIZE = "ARG_TEXT_SIZE"
@JvmStatic
private val ARG_BUTTON_BACKGROUND = "ARG_BUTTON_BACKGROUND"
@JvmStatic
private val ARG_TEXT_COLOR = "ARG_TEXT_COLOR"
@JvmStatic
private val ARG_DRAWABLE_PADDING = "ARG_DRAWABLE_PADDING"
@JvmStatic
private val ARG_HORIZONTAL_PADDING = "ARG_HORIZONTAL_PADDING"
@JvmStatic
private val ARG_VERTICAL_PADDING = "ARG_VERTICAL_PADDING"
@JvmStatic
private val ARG_BORDER_COLOR = "ARG_BORDER_COLOR"
@JvmStatic
private val ARG_CORNER_RADIUS = "ARG_CORNER_RADIUS"
@JvmStatic
private val ARG_ELEVATION = "ARG_ELEVATION"
}
//Data Members
var buttonText: String = ""
set(value) {
field = value
setInternalButtonText(field)
}
var buttonTextSize: Float = 0.toFloat()
set(value) {
field = value
setInternalTextSize(field)
}
var buttonBackgroundColor: Int = 0
set(value) {
field = value
setInternalButtonBackgroundColor(field)
}
var buttonTextColor: Int = 0
set(value) {
field = value
setInternalButtonTextColor(field)
}
var buttonLeftIcon: Drawable? = null
set(value) {
field = value
setInternalButtonLeftIcon(field)
}
var buttonDrawablePadding: Int = 0
set(value) {
field = value
setInternalButtonDrawablePadding(field)
}
var buttonHorizontalPadding: Int = 0
set(value) {
field = value
setInternalButtonPadding()
}
var buttonVerticalPadding: Int = 0
set(value) {
field = value
setInternalButtonPadding()
}
var buttonBorderColor: Int = 0
set(value) {
field = value
setInternalButtonBorderColor(field)
}
var buttonCornerRadius: Int = 0
set(value) {
field = value
setInternalButtonCornerRadius(field)
}
var buttonElevation: Int = 0
set(value) {
field = value
setInternalButtonElevation(field)
}
val styleableButton: Button
get() = button
init {
initInflate()
initInstance(context, attrs, defStyleAttr)
}
private fun initInflate() {
View.inflate(context, R.layout.view_styleable_button, this)
}
private fun initInstance(context: Context, attrs: AttributeSet?, defStyleAttr: Int) {
attrs?.let {
val ta = context.obtainStyledAttributes(it, R.styleable.StyleableButton)
with(ta) {
buttonText = ta.getString(R.styleable.StyleableButton_styleableButtonText)
buttonTextSize = ta.getDimensionPixelSize(R.styleable.StyleableButton_styleableButtonTextSize, context.resources.getDimensionPixelSize(R.dimen.styleable_default_button_text_size)).toFloat()
buttonBackgroundColor = ta.getColor(R.styleable.StyleableButton_styleableButtonBackgroundColor, Color.TRANSPARENT)
buttonTextColor = ta.getColor(R.styleable.StyleableButton_styleableButtonTextColor, ContextCompat.getColor(context, R.color.default_text_color))
val buttonLeftIconRes = ta.getResourceId(R.styleable.StyleableButton_styleableButtonLeftDrawable, 0)
if (buttonLeftIconRes != 0) {
buttonLeftIcon = AppCompatResources.getDrawable(context, buttonLeftIconRes)
}
buttonDrawablePadding = ta.getDimensionPixelSize(R.styleable.StyleableButton_styleableButtonDrawablePadding, 0)
buttonHorizontalPadding = ta.getDimensionPixelSize(R.styleable.StyleableButton_styleableButtonHorizontalPadding, 0)
buttonVerticalPadding = ta.getDimensionPixelSize(R.styleable.StyleableButton_styleableButtonVerticalPadding, context.resources.getDimension(R.dimen.styleable_default_button_horizontal_padding).toInt())
buttonBorderColor = ta.getColor(R.styleable.StyleableButton_styleableButtonBorderColor, Color.TRANSPARENT)
buttonCornerRadius = ta.getDimensionPixelSize(R.styleable.StyleableButton_styleableButtonCornerRadius, 0)
buttonElevation = ta.getDimensionPixelSize(R.styleable.StyleableButton_styleableButtonElevation, 0)
}
ta.recycle()
}
}
private fun setInternalButtonText(buttonText: String) {
button.text = buttonText
}
private fun setInternalTextSize(textSize: Float) {
button.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
}
private fun setInternalButtonBackgroundColor(backgroundColor: Int) {
layoutText.setCardBackgroundColor(backgroundColor)
}
private fun setInternalButtonTextColor(color: Int) {
button.setTextColor(color)
}
private fun setInternalButtonLeftIcon(leftIcon: Drawable?) {
button.setCompoundDrawablesWithIntrinsicBounds(leftIcon, null, null, null)
}
private fun setInternalButtonDrawablePadding(padding: Int) {
button.compoundDrawablePadding = padding
}
private fun setInternalButtonPadding() {
button.setPadding(buttonHorizontalPadding, buttonVerticalPadding, buttonHorizontalPadding, buttonVerticalPadding)
}
private fun setInternalButtonBorderColor(color: Int) {
setCardBackgroundColor(color)
}
private fun setInternalButtonCornerRadius(newRadius: Int) {
layoutText.radius = newRadius.toFloat()
radius = newRadius.toFloat()
}
private fun setInternalButtonElevation(elevation: Int) {
cardElevation = elevation.toFloat()
}
override fun dispatchSaveInstanceState(container: SparseArray<Parcelable>) {
dispatchFreezeSelfOnly(container)
}
override fun dispatchRestoreInstanceState(container: SparseArray<Parcelable>) {
dispatchThawSelfOnly(container)
}
override fun onSaveInstanceState(): Parcelable? {
val superState = super.onSaveInstanceState()
//Save Child State
var id: Int
val childrenStates = Bundle()
for (i in 0 until childCount) {
id = getChildAt(i).id
if (id != 0) {
val childrenState = SparseArray<Parcelable>()
getChildAt(i).saveHierarchyState(childrenState)
childrenStates.putSparseParcelableArray(id.toString(), childrenState)
}
}
val saveBundle = Bundle().apply {
putBundle(ARG_CHILD_STATES, childrenStates)
putString(ARG_BUTTON_TEXT, buttonText)
putFloat(ARG_TEXT_SIZE, buttonTextSize)
putInt(ARG_BUTTON_BACKGROUND, buttonBackgroundColor)
putInt(ARG_TEXT_COLOR, buttonTextColor)
putInt(ARG_DRAWABLE_PADDING, buttonDrawablePadding)
putInt(ARG_HORIZONTAL_PADDING, buttonHorizontalPadding)
putInt(ARG_VERTICAL_PADDING, buttonVerticalPadding)
putInt(ARG_BORDER_COLOR, buttonBorderColor)
putInt(ARG_CORNER_RADIUS, buttonCornerRadius)
putInt(ARG_ELEVATION, buttonElevation)
}
//Save it to Parcelable
return BundleSavedState(superState)
.apply {
bundle = saveBundle
}
}
override fun onRestoreInstanceState(state: Parcelable) {
val ss = state as BundleSavedState
super.onRestoreInstanceState(ss.superState)
//Restore SparseArray
val bundle = ss.bundle
val childStates = bundle.getBundle(ARG_CHILD_STATES)
//Restore Children's state
var id: Int
for (i in 0 until childCount) {
id = getChildAt(i).id
if (id != 0) {
if (childStates.containsKey(id.toString())) {
val childrenState = childStates.getSparseParcelableArray<Parcelable>(id.toString())
getChildAt(i).restoreHierarchyState(childrenState)
}
}
}
//Restore State Here
buttonText = bundle.getString(ARG_BUTTON_TEXT)
buttonTextSize = bundle.getFloat(ARG_TEXT_SIZE)
buttonBackgroundColor = bundle.getInt(ARG_BUTTON_BACKGROUND)
buttonTextColor = bundle.getInt(ARG_TEXT_COLOR)
buttonDrawablePadding = bundle.getInt(ARG_DRAWABLE_PADDING)
buttonHorizontalPadding = bundle.getInt(ARG_HORIZONTAL_PADDING)
buttonVerticalPadding = bundle.getInt(ARG_VERTICAL_PADDING)
buttonBorderColor = bundle.getInt(ARG_BORDER_COLOR)
buttonCornerRadius = bundle.getInt(ARG_CORNER_RADIUS)
buttonElevation = bundle.getInt(ARG_ELEVATION)
}
} | apache-2.0 | b3b095eef3de0490356c6dd6e1825559 | 36.543071 | 217 | 0.661778 | 4.867897 | false | false | false | false |
JamesLaverack/wulin-dice | src/main/kotlin/com/jameslaverack/wulindice/DiceIterator.kt | 1 | 1148 | package com.jameslaverack.wulindice
import java.util.*
/**
* Iterates over all possible results of a given type of dice pool.
*/
class DiceIterator<T>(val numberOfDice: Int, val faces: List<T>) : Iterator<List<T>> {
var indexes = ArrayList<Int>()
var done = false
init {
for (i in 1..numberOfDice) {
indexes.add(0)
}
}
fun increment() {
bump(numberOfDice - 1)
}
fun bump(index: Int) {
// Don't permit negative indexing
if (index < 0) {
done = true
return
}
var digit = indexes[index] + 1
if (digit == faces.size) {
indexes[index] = 0;
bump(index - 1);
} else {
indexes[index] = digit;
}
}
override fun next(): List<T> {
var previousPool = toPool();
increment();
return previousPool
}
fun toPool(): List<T> {
var pool = mutableListOf<T>()
for (index in indexes) {
pool.add(faces[index])
}
return pool
}
override fun hasNext(): Boolean {
return !done
}
}
| mit | ea8959a65281de4729a401a7a0c27c69 | 19.872727 | 86 | 0.50784 | 3.986111 | false | false | false | false |
esafirm/android-playground | app/src/main/java/com/esafirm/androidplayground/ui/glide/GlideController.kt | 1 | 3467 | package com.esafirm.androidplayground.ui.glide
import android.os.Debug
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.view.setPadding
import com.bumptech.glide.Glide
import com.bumptech.glide.request.Request
import com.esafirm.androidplayground.common.BaseController
import com.esafirm.androidplayground.utils.button
import com.esafirm.androidplayground.utils.dp
import com.esafirm.androidplayground.utils.matchParent
import com.esafirm.androidplayground.utils.row
import com.esafirm.androidplayground.utils.switch
import kotlin.random.Random
class GlideController : BaseController() {
private var imageView: ImageView? = null
private var useCache: Boolean = false
private val requestInfoPasser = RequestInfoPasser()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View {
return row {
setPadding(16.dp.toInt())
switch("Use cache") { isChecked ->
useCache = isChecked
}
button("Request") {
imageView?.requestImage()
}
button("Request with Measure") {
imageView?.requestImageWithMeasure()
}
button("Request with cache") {
val img = imageView!!
val id = Random.nextInt()
val target = CallbackImageViewTarget(img) { req ->
if (req == null) error("Request is null")
val info = requestInfoPasser.getInfo(req)
if (info == null) {
Log.d("Glide", "Callback info null with id $id")
} else {
Log.d("Glide", "Callback with id $info")
}
}
target.request?.let { req ->
requestInfoPasser.setInfo(req, id)
}
Glide.with(img)
.load("https://s-light.tiket.photos/t/01E25EBZS3W0FY9GTG6C42E1SE/rsfit500500gsm/mobile-modules/2021/07/05/84b94d79-4a46-47a5-9cc1-caf129191fc1-1625495902018-f425ad5f10accdce8e3c2c561cde9ff9.png")
.into(target)
Log.d("Glide", "Actual id: $id")
}
button("Request without image loader - Tracing") {
Debug.startMethodTracing("Load image")
val img = imageView!!
Glide.with(img)
.load("https://s-light.tiket.photos/t/01E25EBZS3W0FY9GTG6C42E1SE/rsfit500500gsm/mobile-modules/2021/07/05/84b94d79-4a46-47a5-9cc1-caf129191fc1-1625495902018-f425ad5f10accdce8e3c2c561cde9ff9.png")
.into(CallbackImageViewTarget(img) {
Debug.stopMethodTracing()
})
}
imageView = addImageView()
}
}
private fun ViewGroup.addImageView(): ImageView {
val imageView = ImageView(context).apply {
matchParent(vertical = false)
}
addView(imageView)
return imageView
}
}
class RequestInfoPasser() {
private val backingMap = mutableMapOf<Request, Int>()
fun setInfo(request: Request, info: Int) {
backingMap[request] = info
}
fun getInfo(request: Request): Int? {
val info = backingMap[request]
backingMap.remove(request)
return info
}
} | mit | 8592bf88411fa5b364804f36cc0356a4 | 34.387755 | 215 | 0.603692 | 4.207524 | false | false | false | false |
toddbernhard/server | src/main/kotlin/tech/pronghorn/http/protocol/AsciiConstants.kt | 1 | 1128 | /*
* Copyright 2017 Pronghorn Technology LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tech.pronghorn.http.protocol
const val carriageReturnNewLineShort: Short = 3338
const val colonSpaceShort: Short = 14880
const val colonByte: Byte = 0x3A
const val tabByte: Byte = 0x9
const val forwardSlashByte: Byte = 0x2F
const val ampersandByte: Byte = 0x26
const val equalsByte: Byte = 0x3D
const val asteriskByte: Byte = 0x2A
const val percentByte: Byte = 0x25
const val questionByte: Byte = 0x3F
const val spaceByte: Byte = 0x20
const val carriageReturnByte: Byte = 0xD
const val newLineByte: Byte = 0xA
| apache-2.0 | 224e91f0800c782e38039a33814bf1de | 35.387097 | 75 | 0.762411 | 3.686275 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrLambdaExpressionImpl.kt | 1 | 2418 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.impl
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import com.intellij.psi.ResolveState
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.CachedValueProvider.Result.create
import com.intellij.psi.util.CachedValuesManager.getCachedValue
import com.intellij.psi.util.PsiModificationTracker
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor
import org.jetbrains.plugins.groovy.lang.psi.api.GrLambdaBody
import org.jetbrains.plugins.groovy.lang.psi.api.GrLambdaExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter
import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.GrExpressionImpl
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.params.GrParameterListImpl
class GrLambdaExpressionImpl(node: ASTNode) : GrExpressionImpl(node), GrLambdaExpression {
override fun getParameters(): Array<GrParameter> = parameterList.parameters
override fun getParameterList(): GrParameterList = findNotNullChildByClass(GrParameterListImpl::class.java)
override fun accept(visitor: GroovyElementVisitor) = visitor.visitLambdaExpression(this)
override fun isVarArgs(): Boolean = false
override fun getBody(): GrLambdaBody? = lastChild as? GrLambdaBody
override fun processDeclarations(processor: PsiScopeProcessor, state: ResolveState, lastParent: PsiElement?, place: PsiElement): Boolean {
return processParameters(processor, state) && processClosureClassMembers(processor, state, lastParent, place)
}
override fun getAllParameters(): Array<GrParameter> = parameters
override fun getOwnerType(): PsiType? {
return getCachedValue(this) {
create(doGetOwnerType(), PsiModificationTracker.MODIFICATION_COUNT)
}
}
override fun getArrow(): PsiElement = findNotNullChildByType(GroovyElementTypes.T_ARROW)
override fun getReturnType(): PsiType? = body?.returnType
override fun getType(): PsiType? = GrClosureType.create(this, true)
override fun toString(): String = "Lambda expression"
}
| apache-2.0 | 6a5aaf1fbf8b821b0a24eab1889fc334 | 45.5 | 140 | 0.814309 | 4.562264 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/internal/ui/uiDslTestAction/CheckBoxRadioButtonPanel.kt | 1 | 3016 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.internal.ui.uiDslTestAction
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBRadioButton
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.DslComponentProperty
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.ui.dsl.gridLayout.VerticalAlign
import com.intellij.util.ui.JBUI
import org.jetbrains.annotations.ApiStatus
import java.awt.Color
import javax.swing.BoxLayout
import javax.swing.JCheckBox
import javax.swing.JPanel
import javax.swing.JToggleButton
import javax.swing.border.Border
@Suppress("DialogTitleCapitalization")
@ApiStatus.Internal
internal class CheckBoxRadioButtonPanel {
val panel = panel {
row {
panel {
buttonsGroup {
row {
label("Marker")
}
for (i in 1..5) {
row { checkBox("DcheckBox$i") }
}
}
}.resizableColumn()
.verticalAlign(VerticalAlign.TOP)
panel {
row {
label("Marker")
}
buttonsGroup {
for (i in 1..5) {
row { radioButton("DradioButton$i") }
}
}
}.resizableColumn()
.verticalAlign(VerticalAlign.TOP)
}
buttonsGroup {
row {
checkBox("Border: 2,10,20,30")
.customize(Color.GREEN, JBUI.Borders.customLine(Color.ORANGE, 2, 10, 20, 30))
radioButton("Border: 10,20,30,2")
.customize(Color.ORANGE, JBUI.Borders.customLine(Color.GREEN, 10, 20, 30, 2))
checkBox("Border: 0,0,0,0")
.customize(Color.GREEN, JBUI.Borders.customLine(Color.ORANGE, 0, 0, 0, 0))
radioButton("Border: 0,0,0,0")
.customize(Color.ORANGE, JBUI.Borders.customLine(Color.GREEN, 0, 0, 0, 0))
}
}
buttonsGroup {
row {
val checkBox = JBCheckBox()
cell(checkBox)
.comment("checkBox(null), prefSize = ${checkBox.preferredSize}")
val radioButton = JBRadioButton()
cell(radioButton)
.comment("radioButton(null), prefSize = ${radioButton.preferredSize}")
}
}
row {
val panel = JPanel()
panel.layout = BoxLayout(panel, BoxLayout.Y_AXIS)
for (i in 1..5) {
panel.add(JCheckBox("BoxLayout$i"))
}
cell(panel)
}
buttonsGroup {
row {
checkBox("Base line check")
comment("Some comment")
}
row {
radioButton("Base line check")
comment("Some small comment")
.applyToComponent { font = font.deriveFont(font.size - 2.0f) }
}
}
}
}
private fun Cell<JToggleButton>.customize(background: Color, border: Border) {
applyToComponent {
isOpaque = true
this.background = background
this.border = border
putClientProperty(DslComponentProperty.VISUAL_PADDINGS, Gaps.EMPTY)
}
}
| apache-2.0 | a4b44051b47e917bb26055c836b71aec | 27.186916 | 120 | 0.629973 | 4.092266 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/SampleEntity.kt | 2 | 7975 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import java.util.UUID
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import java.util.*
interface SampleEntity : WorkspaceEntity {
val booleanProperty: Boolean
val stringProperty: String
val stringListProperty: List<String>
val stringMapProperty: Map<String, String>
val fileProperty: VirtualFileUrl
val children: List<@Child ChildSampleEntity>
val nullableData: String?
val randomUUID: UUID?
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : SampleEntity, ModifiableWorkspaceEntity<SampleEntity>, ObjBuilder<SampleEntity> {
override var entitySource: EntitySource
override var booleanProperty: Boolean
override var stringProperty: String
override var stringListProperty: MutableList<String>
override var stringMapProperty: Map<String, String>
override var fileProperty: VirtualFileUrl
override var children: List<ChildSampleEntity>
override var nullableData: String?
override var randomUUID: UUID?
}
companion object : Type<SampleEntity, Builder>() {
operator fun invoke(booleanProperty: Boolean,
stringProperty: String,
stringListProperty: List<String>,
stringMapProperty: Map<String, String>,
fileProperty: VirtualFileUrl,
entitySource: EntitySource,
init: (Builder.() -> Unit)? = null): SampleEntity {
val builder = builder()
builder.booleanProperty = booleanProperty
builder.stringProperty = stringProperty
builder.stringListProperty = stringListProperty.toMutableWorkspaceList()
builder.stringMapProperty = stringMapProperty
builder.fileProperty = fileProperty
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: SampleEntity, modification: SampleEntity.Builder.() -> Unit) = modifyEntity(
SampleEntity.Builder::class.java, entity, modification)
//endregion
interface ChildSampleEntity : WorkspaceEntity {
val data: String
val parentEntity: SampleEntity?
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ChildSampleEntity, ModifiableWorkspaceEntity<ChildSampleEntity>, ObjBuilder<ChildSampleEntity> {
override var entitySource: EntitySource
override var data: String
override var parentEntity: SampleEntity?
}
companion object : Type<ChildSampleEntity, Builder>() {
operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ChildSampleEntity {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ChildSampleEntity, modification: ChildSampleEntity.Builder.() -> Unit) = modifyEntity(
ChildSampleEntity.Builder::class.java, entity, modification)
//endregion
abstract class MyData(val myData: MyContainer)
class MyConcreteImpl(myData: MyContainer) : MyData(myData) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is MyConcreteImpl) return false
return this.myData == other.myData
}
override fun hashCode(): Int {
return this.myData.hashCode()
}
}
data class MyContainer(val info: String)
interface SecondSampleEntity : WorkspaceEntity {
val intProperty: Int
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : SecondSampleEntity, ModifiableWorkspaceEntity<SecondSampleEntity>, ObjBuilder<SecondSampleEntity> {
override var entitySource: EntitySource
override var intProperty: Int
}
companion object : Type<SecondSampleEntity, Builder>() {
operator fun invoke(intProperty: Int, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): SecondSampleEntity {
val builder = builder()
builder.intProperty = intProperty
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: SecondSampleEntity, modification: SecondSampleEntity.Builder.() -> Unit) = modifyEntity(
SecondSampleEntity.Builder::class.java, entity, modification)
//endregion
interface SourceEntity : WorkspaceEntity {
val data: String
val children: List<@Child ChildSourceEntity>
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : SourceEntity, ModifiableWorkspaceEntity<SourceEntity>, ObjBuilder<SourceEntity> {
override var entitySource: EntitySource
override var data: String
override var children: List<ChildSourceEntity>
}
companion object : Type<SourceEntity, Builder>() {
operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): SourceEntity {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: SourceEntity, modification: SourceEntity.Builder.() -> Unit) = modifyEntity(
SourceEntity.Builder::class.java, entity, modification)
//endregion
interface ChildSourceEntity : WorkspaceEntity {
val data: String
val parentEntity: SourceEntity
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : ChildSourceEntity, ModifiableWorkspaceEntity<ChildSourceEntity>, ObjBuilder<ChildSourceEntity> {
override var entitySource: EntitySource
override var data: String
override var parentEntity: SourceEntity
}
companion object : Type<ChildSourceEntity, Builder>() {
operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ChildSourceEntity {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: ChildSourceEntity, modification: ChildSourceEntity.Builder.() -> Unit) = modifyEntity(
ChildSourceEntity.Builder::class.java, entity, modification)
//endregion
interface PersistentIdEntity : WorkspaceEntityWithPersistentId {
val data: String
override val persistentId: LinkedListEntityId
get() {
return LinkedListEntityId(data)
}
//region generated code
@GeneratedCodeApiVersion(1)
interface Builder : PersistentIdEntity, ModifiableWorkspaceEntity<PersistentIdEntity>, ObjBuilder<PersistentIdEntity> {
override var entitySource: EntitySource
override var data: String
}
companion object : Type<PersistentIdEntity, Builder>() {
operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): PersistentIdEntity {
val builder = builder()
builder.data = data
builder.entitySource = entitySource
init?.invoke(builder)
return builder
}
}
//endregion
}
//region generated code
fun MutableEntityStorage.modifyEntity(entity: PersistentIdEntity, modification: PersistentIdEntity.Builder.() -> Unit) = modifyEntity(
PersistentIdEntity.Builder::class.java, entity, modification)
//endregion
| apache-2.0 | 226ecf8bf91b3a5edfb31b25721db972 | 33.081197 | 134 | 0.744828 | 5.281457 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/simpleapp1_16_0/SO_PROPERTY.kt | 2 | 2853 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* 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.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0
import org.apache.causeway.client.kroviz.snapshots.Response
object SO_PROPERTY : Response(){
override val url = "http://localhost:8080/restful/objects/simple.SimpleObject/119/properties/notes"
override val str = """{
"id": "notes",
"memberType": "property",
"links": [{
"rel": "self",
"href": "http://localhost:8080/restful/objects/simple.SimpleObject/119/properties/notes",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-property\""
}, {
"rel": "up",
"href": "http://localhost:8080/restful/objects/simple.SimpleObject/119",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"",
"title": "Object: Boo"
}, {
"rel": "urn:org.restfulobjects:rels/modifyproperty=\"notes\"",
"href": "http://localhost:8080/restful/objects/simple.SimpleObject/119/properties/notes",
"method": "PUT",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-property\"",
"arguments": {
"value": null
}
}, {
"rel": "urn:org.restfulobjects:rels/clearproperty=\"notes\"",
"href": "http://localhost:8080/restful/objects/simple.SimpleObject/119/properties/notes",
"method": "DELETE",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-property\""
}, {
"rel": "describedby",
"href": "http://localhost:8080/restful/domain-types/simple.SimpleObject/properties/notes",
"method": "GET",
"type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/property-description\""
}],
"value": null,
"extensions": {
"x-causeway-format": "string"
}
}"""
}
| apache-2.0 | 8bac77361040c1ef77c57aa7efd931dc | 44.285714 | 104 | 0.626008 | 4.164964 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/entity/model/IRepitchable.kt | 2 | 979 | package io.github.chrislo27.rhre3.entity.model
import io.github.chrislo27.rhre3.sfxdb.SFXDatabase
import io.github.chrislo27.rhre3.sfxdb.datamodel.ContainerModel
import io.github.chrislo27.rhre3.sfxdb.datamodel.impl.Cue
import io.github.chrislo27.rhre3.util.Semitones
interface IRepitchable {
companion object {
fun anyInModel(model: ContainerModel): Lazy<Boolean> {
return lazy {
model.cues.any {
(SFXDatabase.data.objectMap[it.id] as? Cue)?.repitchable == true
}
}
}
val DEFAULT_RANGE: IntRange = -(Semitones.SEMITONES_IN_OCTAVE * 2)..(Semitones.SEMITONES_IN_OCTAVE * 2)
}
var semitone: Int
val canBeRepitched: Boolean
val semitoneRange: IntRange
get() = DEFAULT_RANGE
val rangeWrapsAround: Boolean
get() = false
val persistSemitoneData: Boolean
get() = true
val showPitchOnTooltip: Boolean
get() = true
} | gpl-3.0 | 08c6ece406de0f0dd3d708d91893c5f8 | 27 | 111 | 0.651685 | 3.652985 | false | false | false | false |
ahjsrhj/ShareToQRCode | app/src/main/java/cn/imrhj/sharetoqrcode/util/Commander.kt | 1 | 1787 | package cn.imrhj.sharetoqrcode.util
import android.util.Log
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.IOException
import java.io.InputStreamReader
object Commander {
private var mHaveRoot = false
fun haveRoot(): Boolean {
if (!mHaveRoot) {
val result = execRootCmdSilent("echo test")
Log.d(Thread.currentThread().name, "class = Commander rhjlog haveRoot: root echo: $result")
if (result != -1) {
Log.d(Thread.currentThread().name, "class = Commander rhjlog haveRoot: true")
mHaveRoot = true
} else {
Log.d(Thread.currentThread().name, "class = Commander rhjlog haveRoot: false")
}
}
return mHaveRoot
}
fun execRootCmdSilent(cmd: String): Int {
var result = -1
var dos: DataOutputStream? = null
try {
val process = Runtime.getRuntime().exec("su")
dos = DataOutputStream(process.outputStream)
Log.d(Thread.currentThread().name, "class = Commander rhjlog execRootCmdSilent: $cmd")
dos.writeBytes(cmd + "\n")
dos.flush()
dos.writeBytes("exit\n")
dos.flush()
process.waitFor()
for (line in BufferedReader(InputStreamReader(process.inputStream)).lines) {
Log.d(Thread.currentThread().name, "class = Commander rhjlog execRootCmdSilent: $line")
}
result = process.exitValue()
} catch (e: Exception) {
e.printStackTrace()
} finally {
try {
dos?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
return result
}
} | apache-2.0 | 927ccbc0c27344600a116b5d872b04cc | 32.735849 | 103 | 0.564633 | 4.347932 | false | false | false | false |
allotria/intellij-community | platform/projectModel-impl/src/com/intellij/configurationStore/scheme-impl.kt | 1 | 5760 | // 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.configurationStore
import com.intellij.openapi.options.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.io.FileUtil
import com.intellij.project.isDirectoryBased
import com.intellij.util.SmartList
import com.intellij.util.io.DigestUtil
import com.intellij.util.io.sanitizeFileName
import com.intellij.util.isEmpty
import com.intellij.util.throwIfNotEmpty
import com.intellij.util.xmlb.annotations.Attribute
import org.jdom.Element
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import java.io.OutputStream
import java.security.MessageDigest
import java.util.concurrent.atomic.AtomicReference
import java.util.function.Function
typealias SchemeNameToFileName = (name: String) -> String
val OLD_NAME_CONVERTER: SchemeNameToFileName = { FileUtil.sanitizeFileName(it, true) }
val CURRENT_NAME_CONVERTER: SchemeNameToFileName = { FileUtil.sanitizeFileName(it, false) }
val MODERN_NAME_CONVERTER: SchemeNameToFileName = { sanitizeFileName(it) }
interface SchemeDataHolder<in T> {
/**
* You should call updateDigest() after read on init.
*/
fun read(): Element
fun updateDigest(scheme: T) = Unit
fun updateDigest(data: Element?) = Unit
}
/**
* A scheme processor can implement this interface to provide a file extension different from default .xml.
* @see SchemeProcessor
*/
interface SchemeExtensionProvider {
/**
* @return The scheme file extension **with a leading dot**, for example ".ext".
*/
val schemeExtension: String
}
// applicable only for LazySchemeProcessor
interface SchemeContentChangedHandler<MUTABLE_SCHEME> {
fun schemeContentChanged(scheme: MUTABLE_SCHEME, name: String, dataHolder: SchemeDataHolder<MUTABLE_SCHEME>)
}
abstract class LazySchemeProcessor<SCHEME : Any, MUTABLE_SCHEME : SCHEME>(private val nameAttribute: String = "name") : SchemeProcessor<SCHEME, MUTABLE_SCHEME>() {
open fun getSchemeKey(attributeProvider: Function<String, String?>, fileNameWithoutExtension: String): String? {
return attributeProvider.apply(nameAttribute)
}
abstract fun createScheme(dataHolder: SchemeDataHolder<MUTABLE_SCHEME>,
name: String,
attributeProvider: Function<in String, String?>,
isBundled: Boolean = false): MUTABLE_SCHEME
override fun writeScheme(scheme: MUTABLE_SCHEME): Element? = (scheme as SerializableScheme).writeScheme()
open fun isSchemeFile(name: CharSequence) = true
open fun isSchemeDefault(scheme: MUTABLE_SCHEME, digest: ByteArray) = false
open fun isSchemeEqualToBundled(scheme: MUTABLE_SCHEME) = false
}
private class DigestOutputStream(private val digest: MessageDigest) : OutputStream() {
override fun write(b: Int) {
digest.update(b.toByte())
}
override fun write(b: ByteArray, off: Int, len: Int) {
digest.update(b, off, len)
}
override fun write(b: ByteArray) {
digest.update(b)
}
override fun toString() = "[Digest Output Stream] $digest"
fun digest(): ByteArray = digest.digest()
}
private val sha1MessageDigestThreadLocal = ThreadLocal.withInitial { DigestUtil.sha1() }
// sha-1 is enough, sha-256 is slower, see https://www.nayuki.io/page/native-hash-functions-for-java
fun createDataDigest(): MessageDigest {
val digest = sha1MessageDigestThreadLocal.get()
digest.reset()
return digest
}
@JvmOverloads
fun Element.digest(messageDigest: MessageDigest = createDataDigest()): ByteArray {
val digestOut = DigestOutputStream(messageDigest)
serializeElementToBinary(this, digestOut)
return digestOut.digest()
}
abstract class SchemeWrapper<out T>(name: String) : ExternalizableSchemeAdapter(), SerializableScheme {
protected abstract val lazyScheme: Lazy<T>
val scheme: T
get() = lazyScheme.value
override fun getSchemeState(): SchemeState = if (lazyScheme.isInitialized()) SchemeState.POSSIBLY_CHANGED else SchemeState.UNCHANGED
init {
this.name = name
}
}
abstract class LazySchemeWrapper<T>(name: String, dataHolder: SchemeDataHolder<SchemeWrapper<T>>, protected val writer: (scheme: T) -> Element) : SchemeWrapper<T>(name) {
protected val dataHolder: AtomicReference<SchemeDataHolder<SchemeWrapper<T>>> = AtomicReference(dataHolder)
final override fun writeScheme(): Element {
val dataHolder = dataHolder.get()
@Suppress("IfThenToElvis")
return if (dataHolder == null) writer(scheme) else dataHolder.read()
}
}
class InitializedSchemeWrapper<out T : Scheme>(scheme: T, private val writer: (scheme: T) -> Element) : SchemeWrapper<T>(scheme.name) {
override val lazyScheme: Lazy<T> = lazyOf(scheme)
override fun writeScheme() = writer(scheme)
}
fun unwrapState(element: Element, project: Project, iprAdapter: SchemeManagerIprProvider?, schemeManager: SchemeManager<*>): Element? {
val data = if (project.isDirectoryBased) element.getChild("settings") else element
iprAdapter?.let {
it.load(data)
schemeManager.reload()
}
return data
}
fun wrapState(element: Element, project: Project): Element {
if (element.isEmpty() || !project.isDirectoryBased) {
element.name = "state"
return element
}
val wrapper = Element("state")
wrapper.addContent(element)
return wrapper
}
class BundledSchemeEP {
@Attribute("path")
var path: String? = null
}
fun SchemeManager<*>.save() {
val errors = SmartList<Throwable>()
save(errors)
throwIfNotEmpty(errors)
}
@ApiStatus.Internal
@TestOnly
val LISTEN_SCHEME_VFS_CHANGES_IN_TEST_MODE = Key.create<Boolean>("LISTEN_VFS_CHANGES_IN_TEST_MODE") | apache-2.0 | 5e715bf8ece5b07395f89083609d40aa | 32.888235 | 170 | 0.749479 | 4.314607 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit/src/main/kotlin/slatekit/SlateKit.kt | 1 | 6127 | package slatekit
import slatekit.apis.support.Authenticator
import slatekit.app.App
import slatekit.app.AppOptions
import slatekit.cli.CliSettings
import slatekit.context.Context
import slatekit.common.args.ArgsSchema
import slatekit.common.conf.Conf
import slatekit.common.convert.B64Java8
import slatekit.common.crypto.Encryptor
import slatekit.common.info.About
import slatekit.common.info.ApiKey
import slatekit.common.info.Folders
import slatekit.common.log.Logger
import slatekit.connectors.cli.CliApi
import slatekit.generator.Help
import slatekit.generator.Setup
import slatekit.results.Success
import slatekit.serialization.Serialization
import slatekit.results.Failure
class SlateKit(ctx: Context) : App<Context>(ctx, AppOptions(showWelcome = false, showDisplay = false, showSummary = false)), SlateKitServices {
private lateinit var settingsConf: Conf
private val setup = Setup(SlateKit::class.java, ctx)
private val help = Help(TITLE)
companion object {
// setup the command line arguments.
// NOTE:
// 1. These values can can be setup in the env.conf file
// 2. If supplied on command line, they override the values in .conf file
// 3. If any of these are required and not supplied, then an error is display and program exists
// 4. Help text can be easily built from this schema.
val schema = ArgsSchema()
.text("", "env", "the environment to run in", false, "dev", "dev", "dev1|qa1|stg1|pro")
.text("", "region", "the region linked to app", false, "us", "us", "us|europe|india|*")
.text("", "log.level", "the log level for logging", false, "info", "info", "debug|info|warn|error")
/**
* Default static info about the app.
* This can be overriden in your env.conf file
*/
val about = About(
company = "slatekit",
area = "tools",
name = "cli",
desc = "Slate Kit CLI for creating projects and access to other tools",
region = "NY",
url = "www.slatekit.life",
contact = "[email protected]",
tags = "sample, template, app",
examples = "http://www.slatekit.com"
)
/**
* Encryptor for files
*/
val encryptor = Encryptor("aksf2409bklja24b", "k3l4lkdfaoi97042", B64Java8)
const val TITLE = "Slate Kit CLI"
fun log(about: About, logger: Logger){
val folders = Folders.userDir(about)
folders.create()
logger.debug("root : " + folders.root )
logger.debug("area : " + folders.area )
logger.debug("app : " + folders.app )
logger.debug("conf : " + folders.pathToConf )
logger.debug("cache : " + folders.pathToCache )
logger.debug("inputs : " + folders.pathToInputs )
logger.debug("logs : " + folders.pathToLogs )
logger.debug("outputs: " + folders.pathToOutputs )
logger.debug("temp : " + folders.pathToTemp )
}
}
override suspend fun init() {
// Install the directories and settings( if needed )
settingsConf = setup.configure()
}
/**
* executes the app
*
* @return
*/
override suspend fun exec(): Any? {
// Create the CLI
// All commands are dispatched to it as it handles the
// integration between CLI inputs -> API requests
val cli = build()
// Determine if running in CLI interactive mode or executing a project generator
val args = ctx.args
when {
args.isHelp -> info()
args.parts.isEmpty() -> run(cli)
else -> gen(cli)
}
return OK
}
override suspend fun done(result:Any?) {
}
private suspend fun info(){
help.show() { help.settings(ctx, settingsConf) }
}
/**
* Generate the project
*/
private suspend fun gen(cli: CliApi) {
// Show settings only
help.intro()
help.settings(ctx, settingsConf)
// slatekit new api -name="MyApp1" -package="company1.apps"
//
// NOTES:
// 1. Slate Kit is the actual bash/batch script generated with gradle application plugin
// 2. APIs in slate kit have a 3 part routing convention AREA API ACTION
// 3. The GeneratorAPI is annotated with "area" = "slatekit" for discovery
// 4. So we append the "slatekit" to the parts field parsed from the Args
// The parts are ["slatekit", "new", "app"]
val args = ctx.args
val copy = args.withPrefix("slatekit")
val result = cli.executeArgs(copy)
when(result) {
is Failure -> println("Failure: " + result.error)
is Success -> println("Success: " + result.value.desc)
}
}
/**
* Begin interactive mode
*/
private suspend fun run(cli: CliApi) {
// Show startup info
info()
help.exit()
cli.run()
}
private fun build(): CliApi {
// The APIs ( DocApi, SetupApi are authenticated using an sample API key )
val keys = listOf(ApiKey(name = "cli", key = "abc", roles = "dev,qa,ops,admin"))
// Authenticator using API keys
// Production usage should use industry standard Auth components such as OAuth, JWT, etc.
val auth = Authenticator(keys)
// Load all the Slate Kit Universal APIs
val apis = apis(settingsConf)
// Makes the APIs accessible on the CLI
val cli = CliApi(
ctx = ctx,
auth = auth,
settings = CliSettings(enableLogging = true, enableOutput = true),
apiItems = apis,
metaTransform = {
listOf("api-key" to keys.first().key)
},
serializer = Serialization::serialize
)
return cli
}
} | apache-2.0 | 935919bd0d4bfbfebfc45f2653acee89 | 32.856354 | 143 | 0.579729 | 4.373305 | false | false | false | false |
zdary/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/ProjectDataProvider.kt | 1 | 4496 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models
import com.jetbrains.packagesearch.intellij.plugin.api.PackageSearchApiClient
import com.jetbrains.packagesearch.intellij.plugin.api.http.ApiResult
import com.jetbrains.packagesearch.intellij.plugin.api.model.StandardV2Package
import com.jetbrains.packagesearch.intellij.plugin.api.model.StandardV2PackagesWithRepos
import com.jetbrains.packagesearch.intellij.plugin.api.model.V2Repository
import com.jetbrains.packagesearch.intellij.plugin.util.TraceInfo
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import com.jetbrains.packagesearch.intellij.plugin.util.logTrace
import com.jetbrains.packagesearch.intellij.plugin.util.logWarn
import org.apache.commons.collections.map.LRUMap
internal class ProjectDataProvider(
private val apiClient: PackageSearchApiClient
) {
private val packagesCache = LRUMap(500)
fun fetchKnownRepositories(): ApiResult<List<V2Repository>> = apiClient.repositories()
.mapSuccess { it.repositories }
fun doSearch(searchQuery: String, filterOptions: FilterOptions): ApiResult<StandardV2PackagesWithRepos> {
val repositoryIds = filterOptions.onlyRepositoryIds
return apiClient.packagesByQuery(
searchQuery = searchQuery,
onlyStable = filterOptions.onlyStable,
onlyMpp = filterOptions.onlyKotlinMultiplatform,
repositoryIds = repositoryIds.toList()
)
}
fun fetchInfoFor(installedDependencies: List<InstalledDependency>, traceInfo: TraceInfo): Map<InstalledDependency, StandardV2Package> {
if (installedDependencies.isEmpty()) {
return emptyMap()
}
val apiInfoByDependency = fetchInfoFromCacheOrApiFor(installedDependencies, traceInfo)
val filteredApiInfo = apiInfoByDependency.filterValues { it == null }
if (filteredApiInfo.isNotEmpty() && filteredApiInfo.size != installedDependencies.size) {
val failedDependencies = filteredApiInfo.keys
logWarn(traceInfo, "ProjectDataProvider#fetchInfoFor()") {
"Failed obtaining data for ${failedDependencies.size} dependencies:\n" +
failedDependencies.joinToString("\n") { "\t* '${it.coordinatesString}'" }
}
}
@Suppress("UNCHECKED_CAST") // We filter out null values before casting, we should be ok
return apiInfoByDependency.filterValues { it != null } as Map<InstalledDependency, StandardV2Package>
}
private fun fetchInfoFromCacheOrApiFor(
dependencies: List<InstalledDependency>,
traceInfo: TraceInfo
): Map<InstalledDependency, StandardV2Package?> {
logDebug(traceInfo, "ProjectDataProvider#fetchInfoFromCacheOrApiFor()") {
"Fetching data for ${dependencies.count()} dependencies..."
}
val dependenciesMap = mutableMapOf<InstalledDependency, StandardV2Package?>()
val packagesToFetch = mutableListOf<InstalledDependency>()
for (dependency in dependencies) {
val standardV2Package = packagesCache[dependency]
dependenciesMap[dependency] = standardV2Package as StandardV2Package?
if (standardV2Package == null) {
packagesToFetch += dependency
}
}
if (packagesToFetch.isEmpty()) {
logTrace(traceInfo, "ProjectDataProvider#fetchInfoFromCacheOrApiFor()") {
"Found all ${dependencies.count() - packagesToFetch.count()} packages in cache"
}
return dependenciesMap
}
logTrace(traceInfo, "ProjectDataProvider#fetchInfoFromCacheOrApiFor()") {
"Found ${dependencies.count() - packagesToFetch.count()} packages in cache, still need to fetch ${packagesToFetch.count()} from API"
}
val fetchedPackages = packagesToFetch.asSequence()
.map { dependency -> dependency.coordinatesString }
.chunked(size = 25)
.map { dependenciesToFetch -> apiClient.packagesByRange(dependenciesToFetch) }
.filterIsInstance<ApiResult.Success<StandardV2PackagesWithRepos>>()
.map { it.result.packages }
.flatten()
for (v2Package in fetchedPackages) {
val dependency = InstalledDependency.from(v2Package)
packagesCache[dependency] = v2Package
dependenciesMap[dependency] = v2Package
}
return dependenciesMap
}
}
| apache-2.0 | edbf1d48bb9974ef64ceb795d946cf77 | 43.96 | 144 | 0.700845 | 5.173763 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/properties/propertyOfNestedClassAndArrayType.kt | 2 | 646 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.reflect.KMutableProperty1
class A {
class B(val result: String)
var p: A.B? = null
var q: Array<Array<A.B>>? = null
}
fun box(): String {
val a = A()
val aq = A::class.members.single { it.name == "q" } as KMutableProperty1<A, Array<Array<A.B>>>
aq.set(a, arrayOf(arrayOf(A.B("array"))))
if (a.q!![0][0].result != "array") return "Fail array"
val ap = A::class.members.single { it.name == "p" } as KMutableProperty1<A, A.B>
ap.set(a, A.B("OK"))
return a.p!!.result
}
| apache-2.0 | 8d247c577ad40c5cd412e26ce68a3632 | 24.84 | 98 | 0.614551 | 2.949772 | false | false | false | false |
prangbi/LottoPop-Android | LottoPop/app/src/main/java/com/prangbi/android/lottopop/helper/database/NLottoDB.kt | 1 | 4317 | package com.prangbi.android.lottopop.helper.database
import android.content.ContentValues
import android.database.SQLException
import android.database.sqlite.SQLiteDatabase
/**
* Created by Prangbi on 2017. 8. 19..
* 나눔로또 DB
*/
interface INLottoDB {
fun insertWinResult(drwNo: Int, jsonString: String): Long
fun insertMyLotto(drwNo: Int, jsonString: String): Long
fun selectWinResults(drwNo: Int, count: Int): List<Map<String, Any>>
fun selectLatestWinResult(): Map<String, Any>?
fun selectMyLottos(drwNo: Int, count: Int): List<Map<String, Any>>
fun deleteMyLotto(drwNo: Int): Int
}
class NLottoDB constructor(val readableDB: SQLiteDatabase, val writableDB: SQLiteDatabase): INLottoDB {
companion object {
val TABLE_NLOTTO = "nLotto"
val TABLE_MY_NLOTTO = "myNLotto"
}
override fun insertWinResult(drwNo: Int, jsonString: String): Long {
var count = 0L
val contentValues = ContentValues()
contentValues.put("drwNo", drwNo)
contentValues.put("jsonString", jsonString)
try {
count = writableDB.insertOrThrow(TABLE_NLOTTO, null, contentValues)
} catch (e: SQLException) {
}
return count
}
override fun insertMyLotto(drwNo: Int, jsonString: String): Long {
var count = 0L
val contentValues = ContentValues()
contentValues.put("drwNo", drwNo)
contentValues.put("jsonString", jsonString)
try {
count = writableDB.insertOrThrow(TABLE_MY_NLOTTO, null, contentValues)
} catch (e: SQLException) {
}
return count
}
override fun selectWinResults(drwNo: Int, count: Int): List<Map<String, Any>> {
val list = mutableListOf<Map<String, Any>>()
val last = drwNo
var first = last - if (0 < count - 1) count - 1 else 0
if (0 > first) {
first = 0
}
val query = "SELECT * FROM " + TABLE_NLOTTO +
" WHERE drwNo BETWEEN " + first + " AND " + last +
" ORDER BY drwNo DESC;"
val result = readableDB.rawQuery(query, null)
if (result.moveToFirst()) {
do {
val resDrwNo = result.getInt(1)
val resJsonString = result.getString(2)
val map = mutableMapOf<String, Any>()
map.put("drwNo", resDrwNo)
map.put("jsonString", resJsonString)
list.add(map)
} while (result.moveToNext())
}
result.close()
return list
}
override fun selectLatestWinResult(): Map<String, Any>? {
var winResultMap: Map<String, Any>? = null
val query = "SELECT * FROM " + TABLE_NLOTTO +
" ORDER BY drwNo DESC LIMIT 1;"
val result = readableDB.rawQuery(query, null)
if (result.moveToFirst()) {
val resDrwNo = result.getInt(1)
val resJsonString = result.getString(2)
val map = mutableMapOf<String, Any>()
map.put("drwNo", resDrwNo)
map.put("jsonString", resJsonString)
winResultMap = map
}
result.close()
return winResultMap
}
override fun selectMyLottos(drwNo: Int, count: Int): List<Map<String, Any>> {
val list = mutableListOf<Map<String, Any>>()
val last = drwNo
var first = last - if (0 < count - 1) count - 1 else 0
if (0 > first) {
first = 0
}
val query = "SELECT * FROM " + TABLE_NLOTTO +
" WHERE drwNo BETWEEN " + first + " AND " + last +
" ORDER BY drwNo DESC;"
val result = readableDB.rawQuery(query, null)
if (result.moveToFirst()) {
do {
val resDrwNo = result.getInt(1)
val resJsonString = result.getString(2)
val map = mutableMapOf<String, Any>()
map.put("drwNo", resDrwNo)
map.put("jsonString", resJsonString)
list.add(map)
} while (result.moveToNext())
}
result.close()
return list
}
override fun deleteMyLotto(drwNo: Int): Int {
val count = writableDB.delete(TABLE_MY_NLOTTO, "drwNo=" + drwNo, null)
return count
}
}
| mit | 844829b047b9b7762c4046114fb00294 | 31.156716 | 103 | 0.571826 | 3.917273 | false | false | false | false |
sczerwinski/android-delegates-shared-preferences | delegates-shared-preferences/src/androidTest/kotlin/it/czerwinski/android/delegates/sharedpreferences/IntPreferenceDelegateInActivityTest.kt | 1 | 2435 | package it.czerwinski.android.delegates.sharedpreferences
import android.preference.PreferenceManager
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
@RunWith(AndroidJUnit4::class)
class IntPreferenceDelegateInActivityTest {
@Rule
@JvmField
var activityRule = ActivityTestRule<IntPreferenceDelegateActivity>(IntPreferenceDelegateActivity::class.java)
@Before
@Throws(Exception::class)
fun clearSharedPreferences() {
val delegateActivity = activityRule.activity
val preferences = PreferenceManager.getDefaultSharedPreferences(delegateActivity)
preferences.edit().clear().apply()
}
@Test
@Throws(Exception::class)
fun delegatedActivityFieldForUninitializedPreferenceShouldBeNull() {
// given:
val delegateActivity = activityRule.activity
// when:
val delegateValue = delegateActivity.readOnlyPreference
// then:
assertNull(delegateValue)
}
@Test
@Throws(Exception::class)
fun delegatedActivityFieldForUninitializedPreferenceShouldReturnDefaultValue() {
// given:
val delegateActivity = activityRule.activity
// when:
val delegateValue = delegateActivity.readOnlyPreferenceWithDefaultValue
// then:
assertEquals(1024, delegateValue)
}
@Test
@Throws(Exception::class)
fun delegatedActivityFieldShouldSetPreferenceValue() {
// given:
val delegateActivity = activityRule.activity
val preferences = PreferenceManager.getDefaultSharedPreferences(delegateActivity)
// when:
delegateActivity.writablePreference = 512
// then:
assertEquals(512, preferences.getInt("TEST_DELEGATE_KEY", 0))
}
@Test
@Throws(Exception::class)
fun valueWrittenToActivityFieldShouldBeReadFromLocalDelegate() {
// given:
val delegateActivity = activityRule.activity
val testPreference by delegateActivity.intSharedPreference("TEST_DELEGATE_KEY", 117)
// when:
delegateActivity.writablePreference = 256
// then:
assertEquals(256, testPreference)
}
@Test
@Throws(Exception::class)
fun valueWrittenToLocalDelegateShouldBeReadFromActivityField() {
// given:
val delegateActivity = activityRule.activity
var testPreference by delegateActivity.intSharedPreference("TEST_DELEGATE_KEY", 3)
// when:
testPreference = 4096
// then:
assertEquals(4096, delegateActivity.readOnlyPreference)
}
}
| apache-2.0 | 1058b8058bf4ffa86be0dd25d8c7de9a | 27.313953 | 110 | 0.794251 | 4.120135 | false | true | false | false |
AndroidX/androidx | core/core-i18n/src/main/java/androidx/core/i18n/IDateTimeFormatterImpl.kt | 3 | 3029 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.i18n
import android.os.Build
import androidx.annotation.RequiresApi
import java.text.DateFormat
import java.text.FieldPosition
import java.util.Calendar
import java.util.Locale
internal interface IDateTimeFormatterImpl {
fun format(calendar: Calendar): String
}
internal class DateTimeFormatterImplAndroid(skeleton: String, locale: Locale) :
IDateTimeFormatterImpl {
private val sdf = java.text.SimpleDateFormat(
android.text.format.DateFormat.getBestDateTimePattern(locale, skeleton), locale
)
override fun format(calendar: Calendar): String {
return sdf.format(calendar.time)
}
}
// ICU4J will give better results, so we use it if we can.
// And android.text.format.DateFormat.getBestDateTimePattern has a bug in API 26 and 27.
// For some skeletons it returns "b" instead of "a" in patterns (the am/pm).
// That is invalid, and throws when used to build the SimpleDateFormat
// Using ICU avoids that.
// Should also be faster, as the Android used JNI.
@RequiresApi(Build.VERSION_CODES.N)
internal class DateTimeFormatterImplIcu(skeleton: String, private var locale: Locale) :
IDateTimeFormatterImpl {
private val sdf = android.icu.text.DateFormat.getInstanceForSkeleton(skeleton, locale)
override fun format(calendar: Calendar): String {
val result = StringBuffer()
val tz = android.icu.util.TimeZone.getTimeZone(calendar.timeZone.id)
val ucal = android.icu.util.Calendar.getInstance(tz, locale)
sdf.calendar = ucal
val fp = FieldPosition(0)
sdf.format(calendar.timeInMillis, result, fp)
return result.toString()
}
}
internal class DateTimeFormatterImplJdkStyle(dateStyle: Int, timeStyle: Int, locale: Locale) :
IDateTimeFormatterImpl {
private val sdf =
if (dateStyle == -1) {
if (timeStyle == -1) {
DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale)
} else {
DateFormat.getTimeInstance(timeStyle, locale)
}
} else {
if (timeStyle == -1) {
DateFormat.getDateInstance(dateStyle, locale)
} else {
DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale)
}
}
override fun format(calendar: Calendar): String {
return sdf.format(calendar.time)
}
}
| apache-2.0 | baafbfa389f01adbf1e672eec38574b5 | 34.22093 | 94 | 0.698911 | 4.290368 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/social/UserParty.kt | 1 | 557 | package com.habitrpg.android.habitica.models.social
import com.google.gson.annotations.SerializedName
import com.habitrpg.android.habitica.models.inventory.Quest
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class UserParty : RealmObject() {
@PrimaryKey
var userId: String? = null
@SerializedName("_id")
var id: String = ""
var quest: Quest? = null
@SerializedName("order")
var partyOrder: String? = null//Order to display ppl
var orderAscending: String? = null//Order type
}
| gpl-3.0 | 0d6737f6ad3f10903f8d956fcdbb4e3e | 27.315789 | 59 | 0.710952 | 4.065693 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/viewmodels/LoginToutViewModel.kt | 1 | 13907 | package com.kickstarter.viewmodels
import android.util.Pair
import androidx.annotation.VisibleForTesting
import com.facebook.CallbackManager
import com.facebook.CallbackManager.Factory.create
import com.facebook.FacebookAuthorizationException
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.kickstarter.libs.ActivityRequestCodes
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.CurrentUserType
import com.kickstarter.libs.Environment
import com.kickstarter.libs.models.OptimizelyFeature
import com.kickstarter.libs.rx.transformers.Transformers
import com.kickstarter.libs.utils.EventContextValues.ContextPageName
import com.kickstarter.libs.utils.EventContextValues.ContextTypeName
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.services.ApiClientType
import com.kickstarter.services.apiresponses.AccessTokenEnvelope
import com.kickstarter.services.apiresponses.ErrorEnvelope
import com.kickstarter.ui.IntentKey
import com.kickstarter.ui.activities.DisclaimerItems
import com.kickstarter.ui.activities.LoginToutActivity
import com.kickstarter.ui.data.ActivityResult
import com.kickstarter.ui.data.LoginReason
import rx.Notification
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
interface LoginToutViewModel {
interface Inputs {
/** Call when the Login to Facebook button is clicked. */
fun facebookLoginClick(activity: LoginToutActivity?, facebookPermissions: List<String>)
/** Call when the login button is clicked. */
fun loginClick()
/** Call when the signup button is clicked. */
fun signupClick()
/** Call when the disclaimer Item is clicked. */
fun disclaimerItemClicked(disclaimerItem: DisclaimerItems)
/** call with facebook error dialog reset password button*/
fun onResetPasswordFacebookErrorDialogClicked()
/** call with facebook error dialog login button*/
fun onLoginFacebookErrorDialogClicked()
}
interface Outputs {
/** Emits when a user has successfully logged in; the login flow should finish with a result indicating success. */
fun finishWithSuccessfulResult(): Observable<Void>
/** Emits when a user has failed to authenticate using Facebook. */
fun showFacebookAuthorizationErrorDialog(): Observable<String>
/** Emits when the API was unable to create a new Facebook user. */
fun showFacebookInvalidAccessTokenErrorToast(): Observable<String?>
/** Emits when the API could not retrieve an email for the Facebook user. */
fun showMissingFacebookEmailErrorToast(): Observable<String?>
/** Emits when a login attempt is unauthorized. */
fun showUnauthorizedErrorDialog(): Observable<String>
/** Emits a Facebook user and an access token string to confirm Facebook signup. */
fun startFacebookConfirmationActivity(): Observable<Pair<ErrorEnvelope.FacebookUser, String>>
/** Emits when the login activity should be started. */
fun startLoginActivity(): Observable<Void>
/** Emits when the signup activity should be started. */
fun startSignupActivity(): Observable<Void>
/** Emits when a user has successfully logged in using Facebook, but has require two-factor authentication enabled. */
fun startTwoFactorChallenge(): Observable<Void>
/** Emits when click one of disclaimer items */
fun showDisclaimerActivity(): Observable<DisclaimerItems>
/** Emits when the there is error with facebook login */
fun showFacebookErrorDialog(): Observable<Void>
/** Emits when the resetPassword should be started. */
fun startResetPasswordActivity(): Observable<Void>
}
class ViewModel(val environment: Environment) :
ActivityViewModel<LoginToutActivity>(environment),
Inputs,
Outputs {
private var callbackManager: CallbackManager? = null
private val currentUser: CurrentUserType = requireNotNull(environment.currentUser())
private val client: ApiClientType = requireNotNull(environment.apiClient())
private fun clearFacebookSession(e: FacebookException) {
LoginManager.getInstance().logOut()
}
private fun loginWithFacebookAccessToken(fbAccessToken: String): Observable<Notification<AccessTokenEnvelope?>> {
return client.loginWithFacebook(fbAccessToken)
.materialize()
}
private fun registerFacebookCallback() {
callbackManager = create()
LoginManager.getInstance()
.registerCallback(
callbackManager,
object : FacebookCallback<LoginResult> {
override fun onSuccess(result: LoginResult) {
facebookAccessToken.onNext(result.accessToken.token)
}
override fun onCancel() {
// continue
}
override fun onError(error: FacebookException) {
if (error is FacebookAuthorizationException) {
facebookAuthorizationError.onNext(error)
}
}
}
)
}
@VisibleForTesting val facebookAccessToken = PublishSubject.create<String>()
private val facebookLoginClick = PublishSubject.create<List<String>>()
private val loginClick = PublishSubject.create<Void>()
private val onResetPasswordFacebookErrorDialogClicked = PublishSubject.create<Void>()
private val onLoginFacebookErrorDialogClicked = PublishSubject.create<Void>()
@VisibleForTesting val loginError = PublishSubject.create<ErrorEnvelope?>()
private val loginReason = PublishSubject.create<LoginReason>()
private val signupClick = PublishSubject.create<Void>()
private val disclaimerItemClicked = PublishSubject.create<DisclaimerItems>()
@VisibleForTesting val facebookAuthorizationError = BehaviorSubject.create<FacebookException>()
private val finishWithSuccessfulResult = BehaviorSubject.create<Void>()
private val showFacebookErrorDialog = BehaviorSubject.create<Void>()
private val startResetPasswordActivity = BehaviorSubject.create<Void>()
private val startFacebookConfirmationActivity: Observable<Pair<ErrorEnvelope.FacebookUser, String>>
private val startLoginActivity: Observable<Void>
private val startSignupActivity: Observable<Void>
private val showDisclaimerActivity: Observable<DisclaimerItems>
val inputs: Inputs = this
val outputs: Outputs = this
override fun facebookLoginClick(
activity: LoginToutActivity?,
facebookPermissions: List<String>
) {
facebookLoginClick.onNext(facebookPermissions)
if (activity != null) {
LoginManager.getInstance()
.logInWithReadPermissions(activity, facebookPermissions)
}
}
override fun onLoginFacebookErrorDialogClicked() {
onLoginFacebookErrorDialogClicked.onNext(null)
}
override fun onResetPasswordFacebookErrorDialogClicked() {
onResetPasswordFacebookErrorDialogClicked.onNext(null)
}
override fun loginClick() {
loginClick.onNext(null)
}
override fun signupClick() {
signupClick.onNext(null)
}
override fun disclaimerItemClicked(disclaimerItem: DisclaimerItems) {
disclaimerItemClicked.onNext(disclaimerItem)
}
override fun finishWithSuccessfulResult(): Observable<Void> {
return finishWithSuccessfulResult
}
override fun showFacebookAuthorizationErrorDialog(): Observable<String> {
return facebookAuthorizationError
.filter { environment.optimizely()?.isFeatureEnabled(OptimizelyFeature.Key.ANDROID_FACEBOOK_LOGIN_REMOVE) == false }
.map { it.localizedMessage }
}
override fun showFacebookInvalidAccessTokenErrorToast(): Observable<String?> {
return loginError
.filter(ErrorEnvelope::isFacebookInvalidAccessTokenError)
.map { it.errorMessage() }
}
override fun showMissingFacebookEmailErrorToast(): Observable<String?> {
return loginError
.filter(ErrorEnvelope::isMissingFacebookEmailError)
.map { it.errorMessage() }
}
override fun showUnauthorizedErrorDialog(): Observable<String> {
return loginError
.filter(ErrorEnvelope::isUnauthorizedError)
.map { it.errorMessage() }
}
override fun startFacebookConfirmationActivity(): Observable<Pair<ErrorEnvelope.FacebookUser, String>> {
return startFacebookConfirmationActivity
}
override fun startLoginActivity(): Observable<Void> {
return startLoginActivity
}
override fun startSignupActivity(): Observable<Void> {
return startSignupActivity
}
override fun startTwoFactorChallenge(): Observable<Void> {
return loginError
.filter(ErrorEnvelope::isTfaRequiredError)
.map { null }
}
override fun showDisclaimerActivity(): Observable<DisclaimerItems> {
return showDisclaimerActivity
}
override fun showFacebookErrorDialog(): Observable<Void> {
return showFacebookErrorDialog
}
override fun startResetPasswordActivity(): Observable<Void> {
return startResetPasswordActivity
}
init {
registerFacebookCallback()
val facebookAccessTokenEnvelope = facebookAccessToken
.switchMap {
loginWithFacebookAccessToken(
it
)
}
.share()
intent()
.map { it.getSerializableExtra(IntentKey.LOGIN_REASON) }
.ofType(LoginReason::class.java)
.compose(bindToLifecycle())
.subscribe { it: LoginReason ->
loginReason.onNext(it)
analyticEvents.trackLoginOrSignUpPagedViewed()
}
activityResult()
.compose(bindToLifecycle())
.subscribe {
callbackManager?.onActivityResult(
it.requestCode(),
it.resultCode(),
it.intent()
)
}
activityResult()
.filter { it.isRequestCode(ActivityRequestCodes.LOGIN_FLOW) }
.filter(ActivityResult::isOk)
.compose(bindToLifecycle())
.subscribe { finishWithSuccessfulResult.onNext(null) }
facebookAuthorizationError
.compose(bindToLifecycle())
.subscribe { clearFacebookSession(it) }
facebookAccessTokenEnvelope
.compose(Transformers.values())
.filter { ObjectUtils.isNotNull(it) }
.map { requireNotNull(it) }
.compose(bindToLifecycle())
.subscribe {
currentUser.login(it.user(), it.accessToken())
finishWithSuccessfulResult.onNext(null)
}
facebookAccessTokenEnvelope
.compose(Transformers.errors())
.map { ErrorEnvelope.fromThrowable(it) }
.filter { ObjectUtils.isNotNull(it) }
.compose(bindToLifecycle())
.subscribe { loginError.onNext(it) }
startFacebookConfirmationActivity = loginError
.filter(ErrorEnvelope::isConfirmFacebookSignupError)
.map { it.facebookUser() }
.compose(Transformers.combineLatestPair(facebookAccessToken))
facebookAuthorizationError
.filter {
environment.optimizely()?.isFeatureEnabled(OptimizelyFeature.Key.ANDROID_FACEBOOK_LOGIN_REMOVE) == true
}
.compose(bindToLifecycle())
.subscribe {
showFacebookErrorDialog.onNext(null)
}
startLoginActivity = loginClick
startSignupActivity = signupClick
showDisclaimerActivity = disclaimerItemClicked
facebookLoginClick
.compose(Transformers.ignoreValues())
.compose(bindToLifecycle())
.subscribe {
analyticEvents.trackLoginOrSignUpCtaClicked(
ContextTypeName.FACEBOOK.contextName,
ContextPageName.LOGIN_SIGN_UP.contextName
)
}
loginClick
.compose(bindToLifecycle())
.subscribe { analyticEvents.trackLogInInitiateCtaClicked() }
signupClick
.compose(bindToLifecycle())
.subscribe { analyticEvents.trackSignUpInitiateCtaClicked() }
onResetPasswordFacebookErrorDialogClicked
.compose(bindToLifecycle())
.subscribe { startResetPasswordActivity.onNext(null) }
onLoginFacebookErrorDialogClicked
.compose(bindToLifecycle())
.subscribe { startLoginActivity.onNext(null) }
}
}
}
| apache-2.0 | 1368fb1fadbbab0fa41b44da39dd51bf | 38.848138 | 132 | 0.63486 | 5.907816 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/JavaResourceRootEntityImpl.kt | 1 | 10569 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class JavaResourceRootEntityImpl : JavaResourceRootEntity, WorkspaceEntityBase() {
companion object {
internal val SOURCEROOT_CONNECTION_ID: ConnectionId = ConnectionId.create(SourceRootEntity::class.java,
JavaResourceRootEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
SOURCEROOT_CONNECTION_ID,
)
}
override val sourceRoot: SourceRootEntity
get() = snapshot.extractOneToManyParent(SOURCEROOT_CONNECTION_ID, this)!!
override var generated: Boolean = false
@JvmField
var _relativeOutputPath: String? = null
override val relativeOutputPath: String
get() = _relativeOutputPath!!
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: JavaResourceRootEntityData?) : ModifiableWorkspaceEntityBase<JavaResourceRootEntity>(), JavaResourceRootEntity.Builder {
constructor() : this(JavaResourceRootEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity JavaResourceRootEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToManyParent<WorkspaceEntityBase>(SOURCEROOT_CONNECTION_ID, this) == null) {
error("Field JavaResourceRootEntity#sourceRoot should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, SOURCEROOT_CONNECTION_ID)] == null) {
error("Field JavaResourceRootEntity#sourceRoot should be initialized")
}
}
if (!getEntityData().isRelativeOutputPathInitialized()) {
error("Field JavaResourceRootEntity#relativeOutputPath should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as JavaResourceRootEntity
this.entitySource = dataSource.entitySource
this.generated = dataSource.generated
this.relativeOutputPath = dataSource.relativeOutputPath
if (parents != null) {
this.sourceRoot = parents.filterIsInstance<SourceRootEntity>().single()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var sourceRoot: SourceRootEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(SOURCEROOT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
SOURCEROOT_CONNECTION_ID)]!! as SourceRootEntity
}
else {
this.entityLinks[EntityLink(false, SOURCEROOT_CONNECTION_ID)]!! as SourceRootEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, SOURCEROOT_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, SOURCEROOT_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(SOURCEROOT_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, SOURCEROOT_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, SOURCEROOT_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, SOURCEROOT_CONNECTION_ID)] = value
}
changedProperty.add("sourceRoot")
}
override var generated: Boolean
get() = getEntityData().generated
set(value) {
checkModificationAllowed()
getEntityData().generated = value
changedProperty.add("generated")
}
override var relativeOutputPath: String
get() = getEntityData().relativeOutputPath
set(value) {
checkModificationAllowed()
getEntityData().relativeOutputPath = value
changedProperty.add("relativeOutputPath")
}
override fun getEntityData(): JavaResourceRootEntityData = result ?: super.getEntityData() as JavaResourceRootEntityData
override fun getEntityClass(): Class<JavaResourceRootEntity> = JavaResourceRootEntity::class.java
}
}
class JavaResourceRootEntityData : WorkspaceEntityData<JavaResourceRootEntity>() {
var generated: Boolean = false
lateinit var relativeOutputPath: String
fun isRelativeOutputPathInitialized(): Boolean = ::relativeOutputPath.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<JavaResourceRootEntity> {
val modifiable = JavaResourceRootEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): JavaResourceRootEntity {
val entity = JavaResourceRootEntityImpl()
entity.generated = generated
entity._relativeOutputPath = relativeOutputPath
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return JavaResourceRootEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return JavaResourceRootEntity(generated, relativeOutputPath, entitySource) {
this.sourceRoot = parents.filterIsInstance<SourceRootEntity>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(SourceRootEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as JavaResourceRootEntityData
if (this.entitySource != other.entitySource) return false
if (this.generated != other.generated) return false
if (this.relativeOutputPath != other.relativeOutputPath) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as JavaResourceRootEntityData
if (this.generated != other.generated) return false
if (this.relativeOutputPath != other.relativeOutputPath) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + generated.hashCode()
result = 31 * result + relativeOutputPath.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + generated.hashCode()
result = 31 * result + relativeOutputPath.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 8b6a5558cf67de1e96b6cb60c51f6582 | 37.432727 | 150 | 0.705932 | 5.487539 | false | false | false | false |
dahlstrom-g/intellij-community | xml/impl/src/com/intellij/ide/wizard/HTMLNewProjectWizard.kt | 8 | 2815 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.wizard
import com.intellij.ide.actions.CreateFileFromTemplateAction
import com.intellij.ide.fileTemplates.FileTemplateManager
import com.intellij.ide.projectWizard.NewProjectWizardConstants.Language.HTML
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.module.WebModuleBuilder
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.psi.PsiManager
import com.intellij.ui.UIBundle
import com.intellij.ui.dsl.builder.Panel
import com.intellij.ui.dsl.builder.bindSelected
import com.intellij.util.PlatformUtils
import com.intellij.xml.XmlBundle
class HTMLNewProjectWizard : LanguageNewProjectWizard {
override val name = HTML
override val ordinal = 400
override fun isEnabled(context: WizardContext) = PlatformUtils.isCommunityEdition()
override fun createStep(parent: NewProjectWizardLanguageStep) = Step(parent)
class Step(private val parent: NewProjectWizardLanguageStep) : AbstractNewProjectWizardStep(parent) {
private val addSampleCode = propertyGraph.property(false)
override fun setupUI(builder: Panel) {
with(builder) {
row {
checkBox(UIBundle.message("label.project.wizard.new.project.add.sample.code"))
.bindSelected(addSampleCode)
}
}
}
override fun setupProject(project: Project) {
val builder = WebModuleBuilder<Any>().also {
it.name = parent.name
it.contentEntryPath = "${parent.path}/${parent.name}"
}
builder.commit(project)
if (!addSampleCode.get()) return
StartupManager.getInstance(project).runWhenProjectIsInitialized {
val contentEntryPath = builder.contentEntryPath ?: return@runWhenProjectIsInitialized
val root = LocalFileSystem.getInstance().findFileByPath(contentEntryPath)
if (root == null) return@runWhenProjectIsInitialized
WriteCommandAction.runWriteCommandAction(
project, null, null,
Runnable {
val fileTemplate = FileTemplateManager.getInstance(project).getInternalTemplate(
FileTemplateManager.INTERNAL_HTML5_TEMPLATE_NAME)
val directory = PsiManager.getInstance(project).findDirectory(root) ?: return@Runnable
CreateFileFromTemplateAction.createFileFromTemplate(
XmlBundle.message("html.action.new.file.name"),
fileTemplate,
directory,
null,
true
)
})
}
}
}
} | apache-2.0 | 15aa328a384000398ac1b5be8f927382 | 37.054054 | 158 | 0.731083 | 4.895652 | false | false | false | false |
androidx/androidx | compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/SlotTable.kt | 3 | 128319 | /*
* 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.
*/
@file:OptIn(InternalComposeApi::class)
package androidx.compose.runtime
import androidx.compose.runtime.snapshots.fastFilterIndexed
import androidx.compose.runtime.snapshots.fastForEach
import androidx.compose.runtime.snapshots.fastMap
import androidx.compose.runtime.tooling.CompositionData
import androidx.compose.runtime.tooling.CompositionGroup
import kotlin.math.max
import kotlin.math.min
// Nomenclature -
// Address - an absolute offset into the array ignoring its gap. See Index below.
// Anchor - an encoding of Index that allows it to not need to be updated when groups or slots
// are inserted or deleted. An anchor is positive if the Index it is tracking is
// before the gap and negative if it is after the gap. If the Anchor is negative, it
// records its distance from the end of the array. If slots or groups are inserted or
// deleted this distance doesn't change but the index it represents automatically
// reflects the deleted or inserted groups or slots. Anchors only need to be updated
// if they track indexes whose group or slot Address moves when the gap moves.
// The term anchor is used not only for the Anchor class but for the parent anchor
// and data anchors in the group fields which are also anchors but not Anchor
// instances.
// Aux - auxiliary data that can be associated with a node and set independent of groups
// slots. This is used, for example, by the composer to record CompositionLocal
// maps as the map is not known at the when the group starts, only when the map is
// calculated after using an arbitrary number of slots.
// Data - the portion of the slot array associated with the group that contains the slots as
// well as the ObjectKey, Node, and Aux if present. The slots for a group are after
// the optional fixed group data.
// Group fields - a set of 5 contiguous integer elements in the groups array aligned at 5
// containing the key, node count, group size parent anchor and an anchor to the
// group data and flags to indicate if the group is a node, has Aux or has an
// ObjectKey. There are a set of extension methods used to access the group fields.
// Group - a contiguous range in the groups array. The groups is an inlined array of group
// fields. The group fields for a group and all of its children's fields comprise
// a group. A groups describes how to interpret the slot array. Groups have an
// integer key, and optional object key, node and aux and a 0 or more slots.
// Groups form a tree where the child groups are immediately after the group
// fields for the group. This data structure favors a linear scan of the children.
// Random access is expensive unless it is through a group anchor.
// Index - the logical index of a group or slot in its array. The index doesn't change when
// the gap moves. See Address and Anchor above. The index and address of a group
// or slot are identical if the gap is at the end of the buffer. This is taken
// advantage of in the SlotReader.
// Key - an Int value used as a key by the composer.
// Node - a value of a node group that can be set independently of the slots of the group.
// This is, for example, where the LayoutNode is stored by the slot table when
// emitting using the UIEmitter.
// ObjectKey - an object that can be used by the composer as part of a groups key. The key()
// composable, for example, produces an ObjectKey. Using the key composable
// function, for example, produces an ObjectKey value.
// Slot - and element in the slot array. Slots are managed by and addressed through a group.
// Slots are allocated in the slots array and are stored in order of their respective
// groups.
// All fields and variables referring to an array index are assumed to be Index values, not Address
// values, unless explicitly ending in Address.
// For simplicity and efficiency of the reader, the gaps are always moved to the end resulting in
// Index and Address being identical in a reader.
// The public API refers only to Index values. Address values are internal.
internal class SlotTable : CompositionData, Iterable<CompositionGroup> {
/**
* An array to store group information that is stored as groups of [Group_Fields_Size]
* elements of the array. The [groups] array can be thought of as an array of an inline
* struct.
*/
var groups = IntArray(0)
private set
/**
* The number of groups contained in [groups].
*/
var groupsSize = 0
private set
/**
* An array that stores the slots for a group. The slot elements for a group start at the
* offset returned by [dataAnchor] of [groups] and continue to the next group's slots or to
* [slotsSize] for the last group. When in a writer the [dataAnchor] is an anchor instead of
* an index as [slots] might contain a gap.
*/
var slots = Array<Any?>(0) { null }
private set
/**
* The number of slots used in [slots].
*/
var slotsSize = 0
private set
/**
* Tracks the number of active readers. A SlotTable can have multiple readers but only one
* writer.
*/
private var readers = 0
/**
* Tracks whether there is an active writer.
*/
internal var writer = false
private set
/**
* An internal version that is incremented whenever a writer is created. This is used to
* detect when an iterator created by [CompositionData] is invalid.
*/
internal var version = 0
/**
* A list of currently active anchors.
*/
internal var anchors: ArrayList<Anchor> = arrayListOf()
/**
* Returns true if the slot table is empty
*/
override val isEmpty get() = groupsSize == 0
/**
* Read the slot table in [block]. Any number of readers can be created but a slot table cannot
* be read while it is being written to.
*
* @see SlotReader
*/
inline fun <T> read(block: (reader: SlotReader) -> T): T = openReader()
.let { reader ->
try {
block(reader)
} finally {
reader.close()
}
}
/**
* Write to the slot table in [block]. Only one writer can be created for a slot table at a
* time and all readers must be closed an do readers can be created while the slot table is
* being written to.
*
* @see SlotWriter
*/
inline fun <T> write(block: (writer: SlotWriter) -> T): T = openWriter()
.let { writer ->
try {
block(writer)
} finally {
writer.close()
}
}
/**
* Open a reader. Any number of readers can be created but a slot table cannot be read while
* it is being written to.
*
* @see SlotReader
*/
fun openReader(): SlotReader {
if (writer) error("Cannot read while a writer is pending")
readers++
return SlotReader(table = this)
}
/**
* Open a writer. Only one writer can be created for a slot table at a time and all readers
* must be closed an do readers can be created while the slot table is being written to.
*
* @see SlotWriter
*/
fun openWriter(): SlotWriter {
runtimeCheck(!writer) { "Cannot start a writer when another writer is pending" }
runtimeCheck(readers <= 0) { "Cannot start a writer when a reader is pending" }
writer = true
version++
return SlotWriter(this)
}
/**
* Return an anchor to the given index. [anchorIndex] can be used to determine the current index
* of the group currently at [index] after a [SlotWriter] as inserted or removed groups or the
* group itself was moved. [Anchor.valid] will be `false` if the group at [index] was removed.
*
* If an anchor is moved using [SlotWriter.moveFrom] or [SlotWriter.moveTo] the anchor will move
* to be owned by the receiving table. [ownsAnchor] can be used to determine if the group
* at [index] is still in this table.
*/
fun anchor(index: Int): Anchor {
runtimeCheck(!writer) { "use active SlotWriter to create an anchor location instead " }
require(index in 0 until groupsSize) { "Parameter index is out of range" }
return anchors.getOrAdd(index, groupsSize) {
Anchor(index)
}
}
/**
* Return the group index for [anchor]. This [SlotTable] is assumed to own [anchor] but that
* is not validated. If [anchor] is not owned by this [SlotTable] the result is undefined.
* If a [SlotWriter] is open the [SlotWriter.anchorIndex] must be called instead as [anchor]
* might be affected by the modifications being performed by the [SlotWriter].
*/
fun anchorIndex(anchor: Anchor): Int {
runtimeCheck(!writer) { "Use active SlotWriter to determine anchor location instead" }
require(anchor.valid) { "Anchor refers to a group that was removed" }
return anchor.location
}
/**
* Returns true if [anchor] is owned by this [SlotTable] or false if it is owned by a
* different [SlotTable] or no longer part of this table (e.g. it was moved or the group it
* was an anchor for was removed).
*/
fun ownsAnchor(anchor: Anchor): Boolean {
return anchor.valid && anchors.search(anchor.location, groupsSize).let {
it >= 0 && anchors[it] == anchor
}
}
/**
* Returns true if the [anchor] is for the group at [groupIndex] or one of it child groups.
*/
fun groupContainsAnchor(groupIndex: Int, anchor: Anchor): Boolean {
runtimeCheck(!writer) { "Writer is active" }
runtimeCheck(groupIndex in 0 until groupsSize) { "Invalid group index" }
return ownsAnchor(anchor) &&
anchor.location in groupIndex until (groupIndex + groups.groupSize(groupIndex))
}
/**
* Close [reader].
*/
internal fun close(reader: SlotReader) {
runtimeCheck(reader.table === this && readers > 0) { "Unexpected reader close()" }
readers--
}
/**
* Close [writer] and adopt the slot arrays returned. The [SlotTable] is invalid until
* [SlotWriter.close] is called as the [SlotWriter] is modifying [groups] and [slots]
* directly and will only make copies of the arrays if the slot table grows.
*/
internal fun close(
writer: SlotWriter,
groups: IntArray,
groupsSize: Int,
slots: Array<Any?>,
slotsSize: Int,
anchors: ArrayList<Anchor>
) {
require(writer.table === this && this.writer) { "Unexpected writer close()" }
this.writer = false
setTo(groups, groupsSize, slots, slotsSize, anchors)
}
/**
* Used internally by [SlotWriter.moveFrom] to swap arrays with a slot table target
* [SlotTable] is empty.
*/
internal fun setTo(
groups: IntArray,
groupsSize: Int,
slots: Array<Any?>,
slotsSize: Int,
anchors: ArrayList<Anchor>
) {
// Adopt the slots from the writer
this.groups = groups
this.groupsSize = groupsSize
this.slots = slots
this.slotsSize = slotsSize
this.anchors = anchors
}
/**
* Modifies the current slot table such that every group with the target key will be
* invalidated, and when recomposed, the content of those groups will be disposed and
* re-inserted.
*
* This is currently only used for developer tooling such as Live Edit to invalidate groups
* which we know will no longer have the same structure so we want to remove them before
* recomposing.
*
* Returns a list of groups if they were successfully invalidated. If this returns null then
* a full composition must be forced.
*/
internal fun invalidateGroupsWithKey(target: Int): List<RecomposeScopeImpl>? {
val anchors = mutableListOf<Anchor>()
val scopes = mutableListOf<RecomposeScopeImpl>()
var allScopesFound = true
// Invalidate groups with the target key
read { reader ->
fun scanGroup() {
val key = reader.groupKey
if (key == target) {
anchors.add(reader.anchor())
if (allScopesFound) {
val nearestScope = findEffectiveRecomposeScope(reader.currentGroup)
if (nearestScope != null) {
scopes.add(nearestScope)
} else {
allScopesFound = false
scopes.clear()
}
}
reader.skipGroup()
return
}
reader.startGroup()
while (!reader.isGroupEnd) {
scanGroup()
}
reader.endGroup()
}
scanGroup()
}
// Bash groups even if we could not invalidate it. The call is responsible for ensuring
// the group is recomposed when this happens.
write { writer ->
writer.startGroup()
anchors.fastForEach { anchor ->
if (anchor.toIndexFor(writer) >= writer.currentGroup) {
writer.seek(anchor)
writer.bashGroup()
}
}
writer.skipToGroupEnd()
writer.endGroup()
}
return if (allScopesFound) scopes else null
}
/**
* Turns true if the first group (considered the root group) contains a mark.
*/
fun containsMark(): Boolean {
return groupsSize > 0 && groups.containsMark(0)
}
/**
* Find the nearest recompose scope for [group] that, when invalidated, will cause [group]
* group to be recomposed.
*/
private fun findEffectiveRecomposeScope(group: Int): RecomposeScopeImpl? {
var current = group
while (current > 0) {
for (data in DataIterator(this, current)) {
if (data is RecomposeScopeImpl) {
return data
}
}
current = groups.parentAnchor(current)
}
return null
}
/**
* Finds the nearest recompose scope to the provided group and invalidates it. Return
* true if the invalidation will cause the scope to reccompose, otherwise false which will
* require forcing recomposition some other way.
*/
private fun invalidateGroup(group: Int): Boolean {
var current = group
// for each parent up the spine
while (current >= 0) {
for (data in DataIterator(this, current)) {
if (data is RecomposeScopeImpl) {
data.requiresRecompose = true
return data.invalidateForResult(null) != InvalidationResult.IGNORED
}
}
current = groups.parentAnchor(current)
}
return false
}
/**
* A debugging aid to validate the internal structure of the slot table. Throws an exception
* if the slot table is not in the expected shape.
*/
fun verifyWellFormed() {
// If the check passes Address and Index are identical so there is no need for
// indexToAddress conversions.
var current = 0
fun validateGroup(parent: Int, parentEnd: Int): Int {
val group = current++
val parentIndex = groups.parentAnchor(group)
check(parentIndex == parent) {
"Invalid parent index detected at $group, expected parent index to be $parent " +
"found $parentIndex"
}
val end = group + groups.groupSize(group)
check(end <= groupsSize) {
"A group extends past the end of the table at $group"
}
check(end <= parentEnd) {
"A group extends past its parent group at $group"
}
val dataStart = groups.dataAnchor(group)
val dataEnd = if (group >= groupsSize - 1) slotsSize else groups.dataAnchor(group + 1)
check(dataEnd <= slots.size) {
"Slots for $group extend past the end of the slot table"
}
check(dataStart <= dataEnd) {
"Invalid data anchor at $group"
}
val slotStart = groups.slotAnchor(group)
check(slotStart <= dataEnd) {
"Slots start out of range at $group"
}
val minSlotsNeeded = (if (groups.isNode(group)) 1 else 0) +
(if (groups.hasObjectKey(group)) 1 else 0) +
(if (groups.hasAux(group)) 1 else 0)
check(dataEnd - dataStart >= minSlotsNeeded) {
"Not enough slots added for group $group"
}
val isNode = groups.isNode(group)
check(!isNode || slots[groups.nodeIndex(group)] != null) {
"No node recorded for a node group at $group"
}
var nodeCount = 0
while (current < end) {
nodeCount += validateGroup(group, end)
}
val expectedNodeCount = groups.nodeCount(group)
val expectedSlotCount = groups.groupSize(group)
check(expectedNodeCount == nodeCount) {
"Incorrect node count detected at $group, " +
"expected $expectedNodeCount, received $nodeCount"
}
val actualSlotCount = current - group
check(expectedSlotCount == actualSlotCount) {
"Incorrect slot count detected at $group, expected $expectedSlotCount, received " +
"$actualSlotCount"
}
if (groups.containsAnyMark(group)) {
check(group <= 0 || groups.containsMark(parent)) {
"Expected group $parent to record it contains a mark because $group does"
}
}
return if (isNode) 1 else nodeCount
}
if (groupsSize > 0) {
while (current < groupsSize) {
validateGroup(-1, current + groups.groupSize(current))
}
check(current == groupsSize) {
"Incomplete group at root $current expected to be $groupsSize"
}
}
// Verify anchors are well-formed
var lastLocation = -1
anchors.fastForEach { anchor ->
val location = anchor.toIndexFor(this)
require(location in 0..groupsSize) { "Invalid anchor, location out of bound" }
require(lastLocation < location) { "Anchor is out of order" }
lastLocation = location
}
}
/**
* A debugging aid that renders the slot table as a string. [toString] is avoided as this is
* potentially a very expensive operation for large slot tables and calling it in the
* debugger should never be implicit.
*/
@Suppress("unused")
fun asString(): String {
return if (writer) super.toString() else
buildString {
append(super.toString())
append('\n')
val groupsSize = groupsSize
if (groupsSize > 0) {
var current = 0
while (current < groupsSize) {
current += emitGroup(current, 0)
}
} else
append("<EMPTY>")
}
}
/**
* A helper function used by [asString] to render a particular group.
*/
private fun StringBuilder.emitGroup(index: Int, level: Int): Int {
repeat(level) { append(' ') }
append("Group(")
append(index)
append(") key=")
append(groups.key(index))
fun dataIndex(index: Int) =
if (index >= groupsSize) slotsSize else groups.dataAnchor(index)
val groupSize = groups.groupSize(index)
append(", nodes=")
append(groups.nodeCount(index))
append(", size=")
append(groupSize)
if (groups.hasMark(index)) {
append(", mark")
}
if (groups.containsMark(index)) {
append(", contains mark")
}
val dataStart = dataIndex(index)
val dataEnd = dataIndex(index + 1)
if (dataStart in 0..dataEnd && dataEnd <= slotsSize) {
if (groups.hasObjectKey(index)) {
append(" objectKey=${slots[groups.objectKeyIndex(index)]}")
}
if (groups.isNode(index)) {
append(" node=${slots[groups.nodeIndex(index)]}")
}
if (groups.hasAux(index)) {
append(" aux=${slots[groups.auxIndex(index)]}")
}
val slotStart = groups.slotAnchor(index)
if (slotStart < dataEnd) {
append(", slots=[")
append(slotStart)
append(": ")
for (dataIndex in slotStart until dataEnd) {
if (dataIndex != slotStart) append(", ")
append(slots[dataIndex].toString())
}
append("]")
}
} else {
append(", *invalid data offsets $dataStart-$dataEnd*")
}
append('\n')
var current = index + 1
val end = index + groupSize
while (current < end) {
current += emitGroup(current, level + 1)
}
return groupSize
}
/**
* A debugging aid to list all the keys [key] values in the [groups] array.
*/
@Suppress("unused")
private fun keys() = groups.keys(groupsSize * Group_Fields_Size)
/**
* A debugging aid to list all the [nodeCount] values in the [groups] array.
*/
@Suppress("unused")
private fun nodes() = groups.nodeCounts(groupsSize * Group_Fields_Size)
/**
* A debugging aid to list all the [parentAnchor] values in the [groups] array.
*/
@Suppress("unused")
private fun parentIndexes() = groups.parentAnchors(groupsSize * Group_Fields_Size)
/**
* A debugging aid to list all the indexes into the [slots] array from the [groups] array.
*/
@Suppress("unused")
private fun dataIndexes() = groups.dataAnchors(groupsSize * Group_Fields_Size)
/**
* A debugging aid to list the [groupsSize] of all the groups in [groups].
*/
@Suppress("unused")
private fun groupSizes() = groups.groupSizes(groupsSize * Group_Fields_Size)
@Suppress("unused")
internal fun slotsOf(group: Int): List<Any?> {
val start = groups.dataAnchor(group)
val end = if (group + 1 < groupsSize) groups.dataAnchor(group + 1) else slots.size
return slots.toList().subList(start, end)
}
override val compositionGroups: Iterable<CompositionGroup> get() = this
override fun iterator(): Iterator<CompositionGroup> =
GroupIterator(this, 0, groupsSize)
override fun find(identityToFind: Any): CompositionGroup? =
SlotTableGroup(this, 0).find(identityToFind)
}
/**
* An [Anchor] tracks a groups as its index changes due to other groups being inserted and
* removed before it. If the group the [Anchor] is tracking is removed, directly or indirectly,
* [valid] will return false. The current index of the group can be determined by passing either
* the [SlotTable] or [SlotWriter] to [toIndexFor]. If a [SlotWriter] is active, it must be used
* instead of the [SlotTable] as the anchor index could have shifted due to operations performed
* on the writer.
*/
internal class Anchor(loc: Int) {
internal var location: Int = loc
val valid get() = location != Int.MIN_VALUE
fun toIndexFor(slots: SlotTable) = slots.anchorIndex(this)
fun toIndexFor(writer: SlotWriter) = writer.anchorIndex(this)
}
/**
* A reader of a slot table. See [SlotTable]
*/
internal class SlotReader(
/**
* The table for whom this is a reader.
*/
internal val table: SlotTable
) {
/**
* A copy of the [SlotTable.groups] array to avoid having indirect through [table].
*/
private val groups: IntArray = table.groups
/**
* A copy of [SlotTable.groupsSize] to avoid having to indirect through [table].
*/
private val groupsSize: Int = table.groupsSize
/**
* A copy of [SlotTable.slots] to avoid having to indirect through [table].
*/
private val slots: Array<Any?> = table.slots
/**
* A Copy of [SlotTable.slotsSize] to avoid having to indirect through [table].
*/
private val slotsSize: Int = table.slotsSize
/**
* True if the reader has been closed
*/
var closed: Boolean = false
private set
/**
* The current group that will be started with [startGroup] or skipped with [skipGroup].
*/
var currentGroup = 0
private set
/**
* The end of the [parent] group.
*/
var currentEnd = groupsSize
private set
/**
* The parent of the [currentGroup] group which is the last group started with [startGroup].
*/
var parent = -1
private set
/**
* The number of times [beginEmpty] has been called.
*/
private var emptyCount = 0
/**
* The current slot of [parent]. This slot will be the next slot returned by [next] unless it
* is equal ot [currentSlotEnd].
*/
private var currentSlot = 0
/**
* The current end slot of [parent].
*/
private var currentSlotEnd = 0
/**
* Return the total number of groups in the slot table.
*/
val size: Int get() = groupsSize
/**
* Return the current slot of the group whose value will be returned by calling [next].
*/
val slot: Int get() = currentSlot - groups.slotAnchor(parent)
/**
* Return the parent index of [index].
*/
fun parent(index: Int) = groups.parentAnchor(index)
/**
* Determine if the slot is start of a node.
*/
val isNode: Boolean get() = groups.isNode(currentGroup)
/**
* Determine if the group at [index] is a node.
*/
fun isNode(index: Int) = groups.isNode(index)
/**
* The number of nodes managed by the current group. For node groups, this is the list of the
* children nodes.
*/
val nodeCount: Int get() = groups.nodeCount(currentGroup)
/**
* Return the number of nodes for the group at [index].
*/
fun nodeCount(index: Int) = groups.nodeCount(index)
/**
* Return the node at [index] if [index] is a node group else null.
*/
fun node(index: Int): Any? = if (groups.isNode(index)) groups.node(index) else null
/**
* Determine if the reader is at the end of a group and an [endGroup] is expected.
*/
val isGroupEnd get() = inEmpty || currentGroup == currentEnd
/**
* Determine if a [beginEmpty] has been called.
*/
val inEmpty get() = emptyCount > 0
/**
* Get the size of the group at [currentGroup].
*/
val groupSize get() = groups.groupSize(currentGroup)
/**
* Get the size of the group at [index]. Will throw an exception if [index] is not a group
* start.
*/
fun groupSize(index: Int) = groups.groupSize(index)
/**
* Get location the end of the currently started group.
*/
val groupEnd get() = currentEnd
/**
* Get location of the end of the group at [index].
*/
fun groupEnd(index: Int) = index + groups.groupSize(index)
/**
* Get the key of the current group. Returns 0 if the [currentGroup] is not a group.
*/
val groupKey
get() = if (currentGroup < currentEnd) {
groups.key(currentGroup)
} else 0
/**
* Get the key of the group at [index].
*/
fun groupKey(index: Int) = groups.key(index)
/**
* The group slot index is the index into the current groups slots that will be updated by
* read by [next].
*/
val groupSlotIndex get() = currentSlot - groups.slotAnchor(parent)
/**
* Determine if the group at [index] has an object key
*/
fun hasObjectKey(index: Int) = groups.hasObjectKey(index)
/**
* Get the object key for the current group or null if no key was provide
*/
val groupObjectKey
get() =
if (currentGroup < currentEnd) groups.objectKey(currentGroup) else null
/**
* Get the object key at [index].
*/
fun groupObjectKey(index: Int) = groups.objectKey(index)
/**
* Get the current group aux data.
*/
val groupAux get() = if (currentGroup < currentEnd) groups.aux(currentGroup) else 0
/**
* Get the aux data for the group at [index]
*/
fun groupAux(index: Int) = groups.aux(index)
/**
* Get the node associated with the group if there is one.
*/
val groupNode get() = if (currentGroup < currentEnd) groups.node(currentGroup) else null
/**
* Get the group key at [anchor]. This return 0 if the anchor is not valid.
*/
fun groupKey(anchor: Anchor) = if (anchor.valid) groups.key(table.anchorIndex(anchor)) else 0
/**
* Returns true when the group at [index] was marked with [SlotWriter.markGroup].
*/
fun hasMark(index: Int) = groups.hasMark(index)
/**
* Returns true if the group contains a group, directly or indirectly, that has been marked by
* a call to [SlotWriter.markGroup].
*/
fun containsMark(index: Int) = groups.containsMark(index)
/**
* Return the number of nodes where emitted into the current group.
*/
val parentNodes: Int get() = if (parent >= 0) groups.nodeCount(parent) else 0
/**
* Return the index of the parent group of the given group
*/
fun parentOf(index: Int): Int {
@Suppress("ConvertTwoComparisonsToRangeCheck")
require(index >= 0 && index < groupsSize) { "Invalid group index $index" }
return groups.parentAnchor(index)
}
/**
* Return the number of slots allocated to the [currentGroup] group.
*/
val groupSlotCount: Int
get() {
val current = currentGroup
val start = groups.slotAnchor(current)
val next = current + 1
val end = if (next < groupsSize) groups.dataAnchor(next) else slotsSize
return end - start
}
/**
* Get the value stored at [index] in the parent group's slot.
*/
fun get(index: Int) = (currentSlot + index).let { slotIndex ->
if (slotIndex < currentSlotEnd) slots[slotIndex] else Composer.Empty
}
/**
* Get the value of the group's slot at [index] for the [currentGroup] group.
*/
fun groupGet(index: Int): Any? = groupGet(currentGroup, index)
/**
* Get the slot value of the [group] at [index]
*/
fun groupGet(group: Int, index: Int): Any? {
val start = groups.slotAnchor(group)
val next = group + 1
val end = if (next < groupsSize) groups.dataAnchor(next) else slotsSize
val address = start + index
return if (address < end) slots[address] else Composer.Empty
}
/**
* Get the value of the slot at [currentGroup] or [Composer.Empty] if at then end of a group.
* During empty mode this value is always [Composer.Empty] which is the value a newly inserted
* slot.
*/
fun next(): Any? {
if (emptyCount > 0 || currentSlot >= currentSlotEnd) return Composer.Empty
return slots[currentSlot++]
}
/**
* Begin reporting empty for all calls to next() or get(). beginEmpty() can be nested and must
* be called with a balanced number of endEmpty()
*/
fun beginEmpty() {
emptyCount++
}
/**
* End reporting [Composer.Empty] for calls to [next] and [get],
*/
fun endEmpty() {
require(emptyCount > 0) { "Unbalanced begin/end empty" }
emptyCount--
}
/**
* Close the slot reader. After all [SlotReader]s have been closed the [SlotTable] a
* [SlotWriter] can be created.
*/
fun close() {
closed = true
table.close(this)
}
/**
* Start a group.
*/
fun startGroup() {
if (emptyCount <= 0) {
require(groups.parentAnchor(currentGroup) == parent) { "Invalid slot table detected" }
parent = currentGroup
currentEnd = currentGroup + groups.groupSize(currentGroup)
val current = currentGroup++
currentSlot = groups.slotAnchor(current)
currentSlotEnd = if (current >= groupsSize - 1)
slotsSize else
groups.dataAnchor(current + 1)
}
}
/**
* Start a group and validate it is a node group
*/
fun startNode() {
if (emptyCount <= 0) {
require(groups.isNode(currentGroup)) { "Expected a node group" }
startGroup()
}
}
/**
* Skip a group. Must be called at the start of a group.
*/
fun skipGroup(): Int {
runtimeCheck(emptyCount == 0) { "Cannot skip while in an empty region" }
val count = if (groups.isNode(currentGroup)) 1 else groups.nodeCount(currentGroup)
currentGroup += groups.groupSize(currentGroup)
return count
}
/**
* Skip to the end of the current group.
*/
fun skipToGroupEnd() {
runtimeCheck(emptyCount == 0) { "Cannot skip the enclosing group while in an empty region" }
currentGroup = currentEnd
}
/**
* Reposition the read to the group at [index].
*/
fun reposition(index: Int) {
runtimeCheck(emptyCount == 0) { "Cannot reposition while in an empty region" }
currentGroup = index
val parent = if (index < groupsSize) groups.parentAnchor(index) else -1
this.parent = parent
if (parent < 0)
this.currentEnd = groupsSize
else
this.currentEnd = parent + groups.groupSize(parent)
this.currentSlot = 0
this.currentSlotEnd = 0
}
/**
* Restore the parent to a parent of the current group.
*/
fun restoreParent(index: Int) {
val newCurrentEnd = index + groups.groupSize(index)
val current = currentGroup
@Suppress("ConvertTwoComparisonsToRangeCheck")
runtimeCheck(current >= index && current <= newCurrentEnd) {
"Index $index is not a parent of $current"
}
this.parent = index
this.currentEnd = newCurrentEnd
this.currentSlot = 0
this.currentSlotEnd = 0
}
/**
* End the current group. Must be called after the corresponding [startGroup].
*/
fun endGroup() {
if (emptyCount == 0) {
runtimeCheck(currentGroup == currentEnd) {
"endGroup() not called at the end of a group"
}
val parent = groups.parentAnchor(parent)
this.parent = parent
currentEnd = if (parent < 0)
groupsSize
else
parent + groups.groupSize(parent)
}
}
/**
* Extract the keys from this point to the end of the group. The current is left unaffected.
* Must be called inside a group.
*/
fun extractKeys(): MutableList<KeyInfo> {
val result = mutableListOf<KeyInfo>()
if (emptyCount > 0) return result
var index = 0
var childIndex = currentGroup
while (childIndex < currentEnd) {
result.add(
KeyInfo(
groups.key(childIndex),
groups.objectKey(childIndex),
childIndex,
if (groups.isNode(childIndex)) 1 else groups.nodeCount(childIndex),
index++
)
)
childIndex += groups.groupSize(childIndex)
}
return result
}
internal fun forEachData(group: Int, block: (index: Int, data: Any?) -> Unit) {
val start = groups.slotAnchor(group)
val end = if (group + 1 < table.groupsSize)
table.groups.dataAnchor(group + 1) else table.slotsSize
for (index in start until end) {
block(index - start, slots[index])
}
}
override fun toString(): String = "SlotReader(current=$currentGroup, key=$groupKey, " +
"parent=$parent, end=$currentEnd)"
/**
* Create an anchor to the current reader location or [index].
*/
fun anchor(index: Int = currentGroup) = table.anchors.getOrAdd(index, groupsSize) {
Anchor(index)
}
private fun IntArray.node(index: Int) = if (isNode(index)) {
slots[nodeIndex(index)]
} else Composer.Empty
private fun IntArray.aux(index: Int) = if (hasAux(index)) {
slots[auxIndex(index)]
} else Composer.Empty
private fun IntArray.objectKey(index: Int) = if (hasObjectKey(index)) {
slots[objectKeyIndex(index)]
} else null
}
/**
* Information about groups and their keys.
*/
internal class KeyInfo internal constructor(
/**
* The group key.
*/
val key: Int,
/**
* The object key for the group
*/
val objectKey: Any?,
/**
* The location of the group.
*/
val location: Int,
/**
* The number of nodes in the group. If the group is a node this is always 1.
*/
val nodes: Int,
/**
* The index of the key info in the list returned by extractKeys
*/
val index: Int
)
/**
* The writer for a slot table. See [SlotTable] for details.
*/
internal class SlotWriter(
/**
* The [SlotTable] for whom this is writer.
*/
internal val table: SlotTable
) {
/**
* The gap buffer for groups. This might change as groups are inserted and the array needs to
* be expanded to account groups. The current valid groups occupy 0 until [groupGapStart]
* followed [groupGapStart] + [groupGapLen] until groups.size where [groupGapStart]
* until [groupGapStart] + [groupGapLen] is the gap.
*/
private var groups: IntArray = table.groups
/**
* The gap buffer for the slots. This might change as slots are inserted an and the array
* needs to be expanded to account for the new slots. The current valid slots occupy 0 until
* [slotsGapStart] and [slotsGapStart] + [slotsGapLen] until slots.size where [slotsGapStart]
* until [slotsGapStart] + [slotsGapLen] is the gap.
*/
private var slots: Array<Any?> = table.slots
/**
* A copy of the [SlotWriter.anchors] to avoid having to index through [table].
*/
private var anchors: ArrayList<Anchor> = table.anchors
/**
* Group index of the start of the gap in the groups array.
*/
private var groupGapStart: Int = table.groupsSize
/**
* The number of groups in the gap in the groups array.
*/
private var groupGapLen: Int = groups.size / Group_Fields_Size - table.groupsSize
/**
* The index end of the current group.
*/
private var currentGroupEnd = table.groupsSize
/**
* The location of the [slots] array that contains the data for the [parent] group.
*/
private var currentSlot = 0
/**
* The location of the index in [slots] after the slots for the [parent] group.
*/
private var currentSlotEnd = 0
/**
* The is the index of gap in the [slots] array.
*/
private var slotsGapStart: Int = table.slotsSize
/**
* The number of slots in the gop in the [slots] array.
*/
private var slotsGapLen: Int = slots.size - table.slotsSize
/**
* The owner of the gap is the first group that has a end relative index.
*/
private var slotsGapOwner = table.groupsSize
/**
* The number of times [beginInsert] has been called.
*/
private var insertCount = 0
/**
* The number of nodes in the current group. Used to track when nodes are being added and
* removed in the [parent] group. Once [endGroup] is called, if the nodes count has changed,
* the containing groups are updated until a node group is encountered.
*/
private var nodeCount = 0
/**
* A stack of the groups that have been explicitly started. A group can be implicitly started
* by using [seek] to seek to indirect child and calling [startGroup] on that child. The
* groups implicitly started groups will be updated when the [endGroup] is called for the
* indirect child group.
*/
private val startStack = IntStack()
/**
* A stack of the [currentGroupEnd] corresponding with the group is [startStack]. As groups
* are ended by calling [endGroup], the size of the group might have changed. This stack is a
* stack of enc group anchors where will reflect the group size change when it is restored by
* calling [restoreCurrentGroupEnd].
*/
private val endStack = IntStack()
/**
* This a count of the [nodeCount] of the explicitly started groups.
*/
private val nodeCountStack = IntStack()
/**
* The current group that will be started by [startGroup] or skipped by [skipGroup]
*/
var currentGroup = 0
private set
/**
* True if at the end of a group and an [endGroup] is expected.
*/
val isGroupEnd get() = currentGroup == currentGroupEnd
/**
* Return true if the current slot starts a node. A node is a kind of group so this will
* return true for isGroup as well.
*/
val isNode
get() =
currentGroup < currentGroupEnd && groups.isNode(groupIndexToAddress(currentGroup))
/**
* Return true if the group at [index] is a node.
*/
fun isNode(index: Int) = groups.isNode(groupIndexToAddress(index))
/**
* return the number of nodes contained in the group at [index]
*/
fun nodeCount(index: Int) = groups.nodeCount(groupIndexToAddress(index))
/**
* Return the key for the group at [index].
*/
fun groupKey(index: Int): Int = groups.key(groupIndexToAddress(index))
/**
* Return the object key for the group at [index], if it has one, or null if not.
*/
fun groupObjectKey(index: Int): Any? {
val address = groupIndexToAddress(index)
return if (groups.hasObjectKey(address)) slots[groups.objectKeyIndex(address)] else null
}
/**
* Return the size of the group at [index].
*/
fun groupSize(index: Int): Int = groups.groupSize(groupIndexToAddress(index))
/**
* Return the aux of the group at [index].
*/
fun groupAux(index: Int): Any? {
val address = groupIndexToAddress(index)
return if (groups.hasAux(address)) slots[groups.auxIndex(address)] else Composer.Empty
}
@Suppress("ConvertTwoComparisonsToRangeCheck")
fun indexInParent(index: Int): Boolean = index > parent && index < currentGroupEnd ||
(parent == 0 && index == 0)
fun indexInCurrentGroup(index: Int): Boolean = indexInGroup(index, currentGroup)
@Suppress("ConvertTwoComparisonsToRangeCheck")
fun indexInGroup(index: Int, group: Int): Boolean {
// If the group is open then the group size in the groups array has not been updated yet
// so calculate the end from the stored anchor value in the end stack.
val end = when {
group == parent -> currentGroupEnd
group > startStack.peekOr(0) -> group + groupSize(group)
else -> {
val openIndex = startStack.indexOf(group)
when {
openIndex < 0 -> group + groupSize(group)
else -> (capacity - groupGapLen) - endStack.peek(openIndex)
}
}
}
return index > group && index < end
}
/**
* Return the node at [index] if [index] is a node group or null.
*/
fun node(index: Int): Any? {
val address = groupIndexToAddress(index)
return if (groups.isNode(address))
slots[dataIndexToDataAddress(groups.nodeIndex(address))]
else null
}
/**
* Return the node at [anchor] if it is a node group or null.
*/
fun node(anchor: Anchor) = node(anchor.toIndexFor(this))
/**
* Return the index of the nearest group that contains [currentGroup].
*/
var parent: Int = -1
private set
/**
* Return the index of the parent for the group at [index].
*/
fun parent(index: Int) = groups.parent(index)
/**
* Return the index of the parent for the group referenced by [anchor]. If the anchor is not
* valid it returns -1.
*/
fun parent(anchor: Anchor) = if (anchor.valid) groups.parent(anchorIndex(anchor)) else -1
/**
* True if the writer has been closed
*/
var closed = false
private set
/**
* Close the writer
*/
fun close() {
closed = true
// Ensure, for readers, there is no gap
if (startStack.isEmpty()) {
// Only reset the writer if it closes normally.
moveGroupGapTo(size)
moveSlotGapTo(slots.size - slotsGapLen, groupGapStart)
recalculateMarks()
}
table.close(
writer = this,
groups = groups,
groupsSize = groupGapStart,
slots = slots,
slotsSize = slotsGapStart,
anchors = anchors
)
}
/**
* Reset the writer to the beginning of the slot table and in the state as if it had just been
* opened. This differs form closing a writer and opening a new one in that the instance
* doesn't change and the gap in the slots are not reset to the end of the buffer.
*/
fun reset() {
runtimeCheck(insertCount == 0) { "Cannot reset when inserting" }
recalculateMarks()
currentGroup = 0
currentGroupEnd = capacity - groupGapLen
currentSlot = 0
currentSlotEnd = 0
nodeCount = 0
}
/**
* Set the value of the next slot. Returns the previous value of the slot or [Composer.Empty]
* is being inserted.
*/
fun update(value: Any?): Any? {
val result = skip()
set(value)
return result
}
/**
* Updates the data for the current data group.
*/
fun updateAux(value: Any?) {
val address = groupIndexToAddress(currentGroup)
runtimeCheck(groups.hasAux(address)) {
"Updating the data of a group that was not created with a data slot"
}
slots[dataIndexToDataAddress(groups.auxIndex(address))] = value
}
/**
* Insert aux data into the parent group.
*
* This must be done only after at most one value has been inserted into the slot table for
* the group.
*/
fun insertAux(value: Any?) {
runtimeCheck(insertCount >= 0) { "Cannot insert auxiliary data when not inserting" }
val parent = parent
val parentGroupAddress = groupIndexToAddress(parent)
runtimeCheck(!groups.hasAux(parentGroupAddress)) { "Group already has auxiliary data" }
insertSlots(1, parent)
val auxIndex = groups.auxIndex(parentGroupAddress)
val auxAddress = dataIndexToDataAddress(auxIndex)
if (currentSlot > auxIndex) {
// One or more values were inserted into the slot table before the aux value, we need
// to move them. Currently we only will run into one or two slots (the recompose
// scope inserted by a restart group and the lambda value in a composableLambda
// instance) so this is the only case currently supported.
val slotsToMove = currentSlot - auxIndex
check(slotsToMove < 3) { "Moving more than two slot not supported" }
if (slotsToMove > 1) {
slots[auxAddress + 2] = slots[auxAddress + 1]
}
slots[auxAddress + 1] = slots[auxAddress]
}
groups.addAux(parentGroupAddress)
slots[auxAddress] = value
currentSlot++
}
/**
* Updates the node for the current node group to [value].
*/
fun updateNode(value: Any?) = updateNodeOfGroup(currentGroup, value)
/**
* Update the node of a the group at [anchor] to [value].
*/
fun updateNode(anchor: Anchor, value: Any?) = updateNodeOfGroup(anchor.toIndexFor(this), value)
/**
* Updates the node of the parent group.
*/
fun updateParentNode(value: Any?) = updateNodeOfGroup(parent, value)
/**
* Set the value at the groups current data slot
*/
fun set(value: Any?) {
runtimeCheck(currentSlot <= currentSlotEnd) {
"Writing to an invalid slot"
}
slots[dataIndexToDataAddress(currentSlot - 1)] = value
}
/**
* Set the group's slot at [index] to [value]. Returns the previous value.
*/
fun set(index: Int, value: Any?): Any? {
val address = groupIndexToAddress(currentGroup)
val slotsStart = groups.slotIndex(address)
val slotsEnd = groups.dataIndex(groupIndexToAddress(currentGroup + 1))
val slotsIndex = slotsStart + index
@Suppress("ConvertTwoComparisonsToRangeCheck")
runtimeCheck(slotsIndex >= slotsStart && slotsIndex < slotsEnd) {
"Write to an invalid slot index $index for group $currentGroup"
}
val slotAddress = dataIndexToDataAddress(slotsIndex)
val result = slots[slotAddress]
slots[slotAddress] = value
return result
}
/**
* Skip the current slot without updating. If the slot table is inserting then and
* [Composer.Empty] slot is added and [skip] return [Composer.Empty].
*/
fun skip(): Any? {
if (insertCount > 0) {
insertSlots(1, parent)
}
return slots[dataIndexToDataAddress(currentSlot++)]
}
/**
* Read the [index] slot at the group at [anchor]. Returns [Composer.Empty] if the slot is
* empty (e.g. out of range).
*/
fun slot(anchor: Anchor, index: Int) = slot(anchorIndex(anchor), index)
/**
* Read the [index] slot at the group at index [groupIndex]. Returns [Composer.Empty] if the
* slot is empty (e.g. out of range).
*/
fun slot(groupIndex: Int, index: Int): Any? {
val address = groupIndexToAddress(groupIndex)
val slotsStart = groups.slotIndex(address)
val slotsEnd = groups.dataIndex(groupIndexToAddress(groupIndex + 1))
val slotsIndex = slotsStart + index
if (slotsIndex !in slotsStart until slotsEnd) {
return Composer.Empty
}
val slotAddress = dataIndexToDataAddress(slotsIndex)
return slots[slotAddress]
}
/**
* Advance [currentGroup] by [amount]. The [currentGroup] group cannot be advanced outside the
* currently started [parent].
*/
fun advanceBy(amount: Int) {
runtimeCheck(amount >= 0) { "Cannot seek backwards" }
check(insertCount <= 0) { "Cannot call seek() while inserting" }
if (amount == 0) return
val index = currentGroup + amount
@Suppress("ConvertTwoComparisonsToRangeCheck")
runtimeCheck(index >= parent && index <= currentGroupEnd) {
"Cannot seek outside the current group ($parent-$currentGroupEnd)"
}
this.currentGroup = index
val newSlot = groups.dataIndex(groupIndexToAddress(index))
this.currentSlot = newSlot
this.currentSlotEnd = newSlot
}
/**
* Seek the current location to [anchor]. The [anchor] must be an anchor to a possibly
* indirect child of [parent].
*/
fun seek(anchor: Anchor) = advanceBy(anchor.toIndexFor(this) - currentGroup)
/**
* Skip to the end of the current group.
*/
fun skipToGroupEnd() {
val newGroup = currentGroupEnd
currentGroup = newGroup
currentSlot = groups.dataIndex(groupIndexToAddress(newGroup))
}
/**
* Begin inserting at the current location. beginInsert() can be nested and must be called with
* a balanced number of endInsert()
*/
fun beginInsert() {
if (insertCount++ == 0) {
saveCurrentGroupEnd()
}
}
/**
* Ends inserting.
*/
fun endInsert() {
check(insertCount > 0) { "Unbalanced begin/end insert" }
if (--insertCount == 0) {
runtimeCheck(nodeCountStack.size == startStack.size) {
"startGroup/endGroup mismatch while inserting"
}
restoreCurrentGroupEnd()
}
}
/**
* Enter the group at current without changing it. Requires not currently inserting.
*/
fun startGroup() {
runtimeCheck(insertCount == 0) { "Key must be supplied when inserting" }
startGroup(key = 0, objectKey = Composer.Empty, isNode = false, aux = Composer.Empty)
}
/**
* Start a group with a integer key
*/
fun startGroup(key: Int) = startGroup(key, Composer.Empty, isNode = false, aux = Composer.Empty)
/**
* Start a group with a data key
*/
fun startGroup(key: Int, dataKey: Any?) = startGroup(
key,
dataKey,
isNode = false,
aux = Composer.Empty
)
/**
* Start a node.
*/
fun startNode(key: Any?) = startGroup(NodeKey, key, isNode = true, aux = Composer.Empty)
/**
* Start a node
*/
fun startNode(key: Any?, node: Any?) = startGroup(NodeKey, key, isNode = true, aux = node)
/**
* Start a data group.
*/
fun startData(key: Int, objectKey: Any?, aux: Any?) = startGroup(
key,
objectKey,
isNode = false,
aux = aux
)
/**
* Start a data group.
*/
fun startData(key: Int, aux: Any?) = startGroup(key, Composer.Empty, isNode = false, aux = aux)
private fun startGroup(key: Int, objectKey: Any?, isNode: Boolean, aux: Any?) {
val inserting = insertCount > 0
nodeCountStack.push(nodeCount)
currentGroupEnd = if (inserting) {
insertGroups(1)
val current = currentGroup
val currentAddress = groupIndexToAddress(current)
val hasObjectKey = objectKey !== Composer.Empty
val hasAux = !isNode && aux !== Composer.Empty
groups.initGroup(
address = currentAddress,
key = key,
isNode = isNode,
hasDataKey = hasObjectKey,
hasData = hasAux,
parentAnchor = parent,
dataAnchor = currentSlot
)
currentSlotEnd = currentSlot
val dataSlotsNeeded = (if (isNode) 1 else 0) +
(if (hasObjectKey) 1 else 0) +
(if (hasAux) 1 else 0)
if (dataSlotsNeeded > 0) {
insertSlots(dataSlotsNeeded, current)
val slots = slots
var currentSlot = currentSlot
if (isNode) slots[currentSlot++] = aux
if (hasObjectKey) slots[currentSlot++] = objectKey
if (hasAux) slots[currentSlot++] = aux
this.currentSlot = currentSlot
}
nodeCount = 0
val newCurrent = current + 1
this.parent = current
this.currentGroup = newCurrent
newCurrent
} else {
val previousParent = parent
startStack.push(previousParent)
saveCurrentGroupEnd()
val currentGroup = currentGroup
val currentGroupAddress = groupIndexToAddress(currentGroup)
if (aux != Composer.Empty) {
if (isNode)
updateNode(aux)
else
updateAux(aux)
}
currentSlot = groups.slotIndex(currentGroupAddress)
currentSlotEnd = groups.dataIndex(
groupIndexToAddress(this.currentGroup + 1)
)
nodeCount = groups.nodeCount(currentGroupAddress)
this.parent = currentGroup
this.currentGroup = currentGroup + 1
currentGroup + groups.groupSize(currentGroupAddress)
}
}
/**
* End the current group. Must be called after the corresponding startGroup().
*/
fun endGroup(): Int {
val inserting = insertCount > 0
val currentGroup = currentGroup
val currentGroupEnd = currentGroupEnd
val groupIndex = parent
val groupAddress = groupIndexToAddress(groupIndex)
val newNodes = nodeCount
val newGroupSize = currentGroup - groupIndex
val isNode = groups.isNode(groupAddress)
if (inserting) {
groups.updateGroupSize(groupAddress, newGroupSize)
groups.updateNodeCount(groupAddress, newNodes)
nodeCount = nodeCountStack.pop() + if (isNode) 1 else newNodes
parent = groups.parent(groupIndex)
} else {
runtimeCheck(currentGroup == currentGroupEnd) {
"Expected to be at the end of a group"
}
// Update group length
val oldGroupSize = groups.groupSize(groupAddress)
val oldNodes = groups.nodeCount(groupAddress)
groups.updateGroupSize(groupAddress, newGroupSize)
groups.updateNodeCount(groupAddress, newNodes)
val newParent = startStack.pop()
restoreCurrentGroupEnd()
this.parent = newParent
val groupParent = groups.parent(groupIndex)
nodeCount = nodeCountStack.pop()
if (groupParent == newParent) {
// The parent group was started we just need to update the node count.
nodeCount += if (isNode) 0 else newNodes - oldNodes
} else {
// If we are closing a group for which startGroup was called after calling
// seek(). startGroup allows the indirect children to be started. If the group
// has changed size or the number of nodes it contains the groups between the
// group being closed and the group that is currently open need to be adjusted.
// This allows the caller to avoid the overhead of needing to start and end the
// groups explicitly.
val groupSizeDelta = newGroupSize - oldGroupSize
var nodesDelta = if (isNode) 0 else newNodes - oldNodes
if (groupSizeDelta != 0 || nodesDelta != 0) {
var current = groupParent
while (
current != 0 &&
current != newParent &&
(nodesDelta != 0 || groupSizeDelta != 0)
) {
val currentAddress = groupIndexToAddress(current)
if (groupSizeDelta != 0) {
val newSize = groups.groupSize(currentAddress) + groupSizeDelta
groups.updateGroupSize(currentAddress, newSize)
}
if (nodesDelta != 0) {
groups.updateNodeCount(
currentAddress,
groups.nodeCount(currentAddress) + nodesDelta
)
}
if (groups.isNode(currentAddress)) nodesDelta = 0
current = groups.parent(current)
}
}
nodeCount += nodesDelta
}
}
return newNodes
}
/**
* Wraps every child group of the current group with a group of a different key.
*/
internal fun bashGroup() {
startGroup()
while (!isGroupEnd) {
insertParentGroup(-3)
skipGroup()
}
endGroup()
}
/**
* If the start of a group was skipped using [skip], calling [ensureStarted] puts the writer
* into the same state as if [startGroup] or [startNode] was called on the group starting at
* [index]. If, after starting, the group, [currentGroup] is not at the end of the group or
* [currentGroup] is not at the start of a group for which [index] is not location the parent
* group, an exception is thrown.
*
* Calling [ensureStarted] implies that an [endGroup] should be called once the end of the
* group is reached.
*/
fun ensureStarted(index: Int) {
runtimeCheck(insertCount <= 0) { "Cannot call ensureStarted() while inserting" }
val parent = parent
if (parent != index) {
// The new parent a child of the current group.
@Suppress("ConvertTwoComparisonsToRangeCheck")
runtimeCheck(index >= parent && index < currentGroupEnd) {
"Started group at $index must be a subgroup of the group at $parent"
}
val oldCurrent = currentGroup
val oldCurrentSlot = currentSlot
val oldCurrentSlotEnd = currentSlotEnd
currentGroup = index
startGroup()
currentGroup = oldCurrent
currentSlot = oldCurrentSlot
currentSlotEnd = oldCurrentSlotEnd
}
}
fun ensureStarted(anchor: Anchor) = ensureStarted(anchor.toIndexFor(this))
/**
* Skip the current group. Returns the number of nodes skipped by skipping the group.
*/
fun skipGroup(): Int {
val groupAddress = groupIndexToAddress(currentGroup)
val newGroup = currentGroup + groups.groupSize(groupAddress)
this.currentGroup = newGroup
this.currentSlot = groups.dataIndex(groupIndexToAddress(newGroup))
return if (groups.isNode(groupAddress)) 1 else groups.nodeCount(groupAddress)
}
/**
* Remove the current group. Returns if any anchors were in the group removed.
*/
fun removeGroup(): Boolean {
runtimeCheck(insertCount == 0) { "Cannot remove group while inserting" }
val oldGroup = currentGroup
val oldSlot = currentSlot
val count = skipGroup()
// Remove any recalculate markers ahead of this delete as they are in the group
// that is being deleted.
pendingRecalculateMarks?.let {
while (it.isNotEmpty() && it.peek() >= oldGroup) {
it.takeMax()
}
}
val anchorsRemoved = removeGroups(oldGroup, currentGroup - oldGroup)
removeSlots(oldSlot, currentSlot - oldSlot, oldGroup - 1)
currentGroup = oldGroup
currentSlot = oldSlot
nodeCount -= count
return anchorsRemoved
}
/**
* Returns an iterator for all the slots of group and all the children of the group.
*/
fun groupSlots(): Iterator<Any?> {
val start = groups.dataIndex(groupIndexToAddress(currentGroup))
val end = groups.dataIndex(
groupIndexToAddress(currentGroup + groupSize(currentGroup))
)
return object : Iterator<Any?> {
var current = start
override fun hasNext(): Boolean = current < end
override fun next(): Any? =
if (hasNext()) slots[dataIndexToDataAddress(current++)] else null
}
}
/**
* Move the group at [offset] groups after [currentGroup] to be in front of [currentGroup].
* After this completes, the moved group will be the current group. [offset] must less than the
* number of groups after the [currentGroup] left in the [parent] group.
*/
fun moveGroup(offset: Int) {
runtimeCheck(insertCount == 0) { "Cannot move a group while inserting" }
runtimeCheck(offset >= 0) { "Parameter offset is out of bounds" }
if (offset == 0) return
val current = currentGroup
val parent = parent
val parentEnd = currentGroupEnd
// Find the group to move
var count = offset
var groupToMove = current
while (count > 0) {
groupToMove += groups.groupSize(
address = groupIndexToAddress(groupToMove)
)
runtimeCheck(groupToMove <= parentEnd) { "Parameter offset is out of bounds" }
count--
}
val moveLen = groups.groupSize(
address = groupIndexToAddress(groupToMove)
)
val currentSlot = currentSlot
val dataStart = groups.dataIndex(groupIndexToAddress(groupToMove))
val dataEnd = groups.dataIndex(
address = groupIndexToAddress(
index = groupToMove + moveLen
)
)
val moveDataLen = dataEnd - dataStart
// The order of operations is important here. Moving a block in the array requires,
//
// 1) inserting space for the block
// 2) copying the block
// 3) deleting the previous block
//
// Inserting into a gap buffer requires moving the gap to the location of the insert and
// then shrinking the gap. Moving the gap in the slot table requires updating all anchors
// in the group table that refer to locations that changed by the gap move. For this to
// work correctly, the groups must be in a valid state. That requires that the slot table
// must be inserted into first so there are no transitory constraint violations in the
// groups (that is, there are no invalid, duplicate or out of order anchors). Conversely,
// removing slots also involves moving the gap requiring the groups to be valid so the
// slots must be removed after the groups that reference the old locations are removed.
// So the order of operations when moving groups is,
//
// 1) insert space for the slots at the destination (must be first)
// 2) insert space for the groups at the destination
// 3) copy the groups to their new location
// 4) copy the slots to their new location
// 5) fix-up the moved group anchors to refer to the new slot locations
// 6) update any anchors in the group being moved
// 7) remove the old groups
// 8) fix parent anchors
// 9) remove the old slots (must be last)
// 1) insert space for the slots at the destination (must be first)
insertSlots(moveDataLen, max(currentGroup - 1, 0))
// 2) insert space for the groups at the destination
insertGroups(moveLen)
// 3) copy the groups to their new location
val groups = groups
val moveLocationAddress = groupIndexToAddress(groupToMove + moveLen)
val moveLocationOffset = moveLocationAddress * Group_Fields_Size
val currentAddress = groupIndexToAddress(current)
groups.copyInto(
destination = groups,
destinationOffset = currentAddress * Group_Fields_Size,
startIndex = moveLocationOffset,
endIndex = moveLocationOffset + moveLen * Group_Fields_Size
)
// 4) copy the slots to their new location
if (moveDataLen > 0) {
val slots = slots
slots.copyInto(
destination = slots,
destinationOffset = currentSlot,
startIndex = dataIndexToDataAddress(dataStart + moveDataLen),
endIndex = dataIndexToDataAddress(dataEnd + moveDataLen)
)
}
// 5) fix-up the moved group anchors to refer to the new slot locations
val dataMoveDistance = (dataStart + moveDataLen) - currentSlot
val slotsGapStart = slotsGapStart
val slotsGapLen = slotsGapLen
val slotsCapacity = slots.size
val slotsGapOwner = slotsGapOwner
for (group in current until current + moveLen) {
val groupAddress = groupIndexToAddress(group)
val oldIndex = groups.dataIndex(groupAddress)
val newIndex = oldIndex - dataMoveDistance
val newAnchor = dataIndexToDataAnchor(
index = newIndex,
gapStart = if (slotsGapOwner < groupAddress) 0 else slotsGapStart,
gapLen = slotsGapLen,
capacity = slotsCapacity
)
groups.updateDataIndex(groupAddress, newAnchor)
}
// 6) update any anchors in the group being moved
moveAnchors(groupToMove + moveLen, current, moveLen)
// 7) remove the old groups
val anchorsRemoved = removeGroups(groupToMove + moveLen, moveLen)
runtimeCheck(!anchorsRemoved) { "Unexpectedly removed anchors" }
// 8) fix parent anchors
fixParentAnchorsFor(parent, currentGroupEnd, current)
// 9) remove the old slots (must be last)
if (moveDataLen > 0) {
removeSlots(dataStart + moveDataLen, moveDataLen, groupToMove + moveLen - 1)
}
}
companion object {
private fun moveGroup(
fromWriter: SlotWriter,
fromIndex: Int,
toWriter: SlotWriter,
updateFromCursor: Boolean,
updateToCursor: Boolean
): List<Anchor> {
val groupsToMove = fromWriter.groupSize(fromIndex)
val sourceGroupsEnd = fromIndex + groupsToMove
val sourceSlotsStart = fromWriter.dataIndex(fromIndex)
val sourceSlotsEnd = fromWriter.dataIndex(sourceGroupsEnd)
val slotsToMove = sourceSlotsEnd - sourceSlotsStart
val hasMarks = fromWriter.containsAnyGroupMarks(fromIndex)
// Make room in the slot table
toWriter.insertGroups(groupsToMove)
toWriter.insertSlots(slotsToMove, toWriter.currentGroup)
// If either from gap is before the move, move the gap after the move to simplify
// the logic of this method.
if (fromWriter.groupGapStart < sourceGroupsEnd) {
fromWriter.moveGroupGapTo(sourceGroupsEnd)
}
if (fromWriter.slotsGapStart < sourceSlotsEnd) {
fromWriter.moveSlotGapTo(sourceSlotsEnd, sourceGroupsEnd)
}
// Copy the groups and slots
val groups = toWriter.groups
val currentGroup = toWriter.currentGroup
fromWriter.groups.copyInto(
destination = groups,
destinationOffset = currentGroup * Group_Fields_Size,
startIndex = fromIndex * Group_Fields_Size,
endIndex = sourceGroupsEnd * Group_Fields_Size
)
val slots = toWriter.slots
val currentSlot = toWriter.currentSlot
fromWriter.slots.copyInto(
destination = slots,
destinationOffset = currentSlot,
startIndex = sourceSlotsStart,
endIndex = sourceSlotsEnd
)
// Fix the parent anchors and data anchors. This would read better as two loops but
// conflating the loops has better locality of reference.
val parent = toWriter.parent
groups.updateParentAnchor(currentGroup, parent)
val parentDelta = currentGroup - fromIndex
val moveEnd = currentGroup + groupsToMove
val dataIndexDelta = currentSlot - with(toWriter) { groups.dataIndex(currentGroup) }
var slotsGapOwner = toWriter.slotsGapOwner
val slotsGapLen = toWriter.slotsGapLen
val slotsCapacity = slots.size
for (groupAddress in currentGroup until moveEnd) {
// Update the parent anchor, the first group has already been set.
if (groupAddress != currentGroup) {
val previousParent = groups.parentAnchor(groupAddress)
groups.updateParentAnchor(groupAddress, previousParent + parentDelta)
}
val newDataIndex = with(toWriter) {
groups.dataIndex(groupAddress) + dataIndexDelta
}
val newDataAnchor = with(toWriter) {
dataIndexToDataAnchor(
newDataIndex,
// Ensure that if the slotGapOwner is below groupAddress we get an end relative
// anchor
if (slotsGapOwner < groupAddress) 0 else slotsGapStart,
slotsGapLen,
slotsCapacity
)
}
// Update the data index
groups.updateDataAnchor(groupAddress, newDataAnchor)
// Move the slotGapOwner if necessary
if (groupAddress == slotsGapOwner) slotsGapOwner++
}
toWriter.slotsGapOwner = slotsGapOwner
// Extract the anchors in range
val startAnchors = fromWriter.anchors.locationOf(fromIndex, fromWriter.size)
val endAnchors = fromWriter.anchors.locationOf(sourceGroupsEnd, fromWriter.size)
val anchors = if (startAnchors < endAnchors) {
val sourceAnchors = fromWriter.anchors
val anchors = ArrayList<Anchor>(endAnchors - startAnchors)
// update the anchor locations to their new location
val anchorDelta = currentGroup - fromIndex
for (anchorIndex in startAnchors until endAnchors) {
val sourceAnchor = sourceAnchors[anchorIndex]
sourceAnchor.location += anchorDelta
anchors.add(sourceAnchor)
}
// Insert them into the new table
val insertLocation = toWriter.anchors.locationOf(
toWriter.currentGroup,
toWriter.size
)
toWriter.anchors.addAll(insertLocation, anchors)
// Remove them from the old table
sourceAnchors.subList(startAnchors, endAnchors).clear()
anchors
} else emptyList()
val parentGroup = fromWriter.parent(fromIndex)
val anchorsRemoved = if (updateFromCursor) {
// Remove the group using the sequence the writer expects when removing a group, that
// is the root group and the group's parent group must be correctly started and ended
// when it is not a root group.
val needsStartGroups = parentGroup >= 0
if (needsStartGroups) {
// If we are not a root group then we are removing from a group so ensure the
// root group is started and then seek to the parent group and start it.
fromWriter.startGroup()
fromWriter.advanceBy(parentGroup - fromWriter.currentGroup)
fromWriter.startGroup()
}
fromWriter.advanceBy(fromIndex - fromWriter.currentGroup)
val anchorsRemoved = fromWriter.removeGroup()
if (needsStartGroups) {
fromWriter.skipToGroupEnd()
fromWriter.endGroup()
fromWriter.skipToGroupEnd()
fromWriter.endGroup()
}
anchorsRemoved
} else {
// Remove the group directly instead of using cursor operations.
val anchorsRemoved = fromWriter.removeGroups(fromIndex, groupsToMove)
fromWriter.removeSlots(sourceSlotsStart, slotsToMove, fromIndex - 1)
anchorsRemoved
}
// Ensure we correctly do not remove anchors with the above delete.
runtimeCheck(!anchorsRemoved) { "Unexpectedly removed anchors" }
// Update the node count in the toWriter
toWriter.nodeCount += if (groups.isNode(currentGroup)) 1 else groups.nodeCount(
currentGroup
)
// Move the toWriter's currentGroup passed the insert
if (updateToCursor) {
toWriter.currentGroup = currentGroup + groupsToMove
toWriter.currentSlot = currentSlot + slotsToMove
}
// If the group being inserted has marks then update the toWriter's parent marks
if (hasMarks) {
toWriter.updateContainsMark(parent)
}
return anchors
}
}
/**
* Move (insert then delete) the group at [anchor] group into the current insert location of
* [writer]. All anchors in the group are moved into the slot table of [writer]. [anchor]
* must be a group contained in the current started group.
*
* This requires [writer] be inserting and this writer to not be inserting.
*/
fun moveTo(anchor: Anchor, offset: Int, writer: SlotWriter): List<Anchor> {
runtimeCheck(writer.insertCount > 0)
runtimeCheck(insertCount == 0)
runtimeCheck(anchor.valid)
val location = anchorIndex(anchor) + offset
val currentGroup = currentGroup
runtimeCheck(location in currentGroup until currentGroupEnd)
val parent = parent(location)
val size = groupSize(location)
val nodes = if (isNode(location)) 1 else nodeCount(location)
val result = moveGroup(
fromWriter = this,
fromIndex = location,
toWriter = writer,
updateFromCursor = false,
updateToCursor = false
)
updateContainsMark(parent)
// Fix group sizes and node counts from the parent of the moved group to the current group
var current = parent
var updatingNodes = nodes > 0
while (current >= currentGroup) {
val currentAddress = groupIndexToAddress(current)
groups.updateGroupSize(currentAddress, groups.groupSize(currentAddress) - size)
if (updatingNodes) {
if (groups.isNode(currentAddress))
updatingNodes = false
else
groups.updateNodeCount(currentAddress, groups.nodeCount(currentAddress) - nodes)
}
current = parent(current)
}
if (updatingNodes) {
runtimeCheck(nodeCount >= nodes)
nodeCount -= nodes
}
return result
}
/**
* Move (insert and then delete) the group at [index] from [slots]. All anchors in the range
* (including [index]) are moved to the slot table for which this is a reader.
*
* It is required that the writer be inserting.
*
* @return a list of the anchors that were moved
*/
fun moveFrom(table: SlotTable, index: Int): List<Anchor> {
runtimeCheck(insertCount > 0)
if (index == 0 && currentGroup == 0 && this.table.groupsSize == 0) {
// Special case for moving the entire slot table into an empty table. This case occurs
// during initial composition.
val myGroups = groups
val mySlots = slots
val myAnchors = anchors
val groups = table.groups
val groupsSize = table.groupsSize
val slots = table.slots
val slotsSize = table.slotsSize
this.groups = groups
this.slots = slots
this.anchors = table.anchors
this.groupGapStart = groupsSize
this.groupGapLen = groups.size / Group_Fields_Size - groupsSize
this.slotsGapStart = slotsSize
this.slotsGapLen = slots.size - slotsSize
this.slotsGapOwner = groupsSize
table.setTo(myGroups, 0, mySlots, 0, myAnchors)
return this.anchors
}
return table.write { tableWriter ->
moveGroup(
tableWriter,
index,
this,
updateFromCursor = true,
updateToCursor = true
)
}
}
/**
* Insert a parent group for the rest of the children in the current group. After this call
* all remaining children of the current group will be parented by a new group and the
* [currentSlot] will be moved to after the group inserted.
*/
fun insertParentGroup(key: Int) {
runtimeCheck(insertCount == 0) { "Writer cannot be inserting" }
if (isGroupEnd) {
beginInsert()
startGroup(key)
endGroup()
endInsert()
} else {
val currentGroup = currentGroup
val parent = groups.parent(currentGroup)
val currentGroupEnd = parent + groupSize(parent)
val remainingSize = currentGroupEnd - currentGroup
var nodeCount = 0
var currentNewChild = currentGroup
while (currentNewChild < currentGroupEnd) {
val newChildAddress = groupIndexToAddress(currentNewChild)
nodeCount += groups.nodeCount(newChildAddress)
currentNewChild += groups.groupSize(newChildAddress)
}
val currentSlot = groups.dataAnchor(groupIndexToAddress(currentGroup))
beginInsert()
insertGroups(1)
endInsert()
val currentAddress = groupIndexToAddress(currentGroup)
groups.initGroup(
address = currentAddress,
key = key,
isNode = false,
hasDataKey = false,
hasData = false,
parentAnchor = parent,
dataAnchor = currentSlot
)
// Update the size of the group to cover the remaining children
groups.updateGroupSize(currentAddress, remainingSize + 1)
groups.updateNodeCount(currentAddress, nodeCount)
// Update the parent to account for the new group
val parentAddress = groupIndexToAddress(parent)
addToGroupSizeAlongSpine(parentAddress, 1)
fixParentAnchorsFor(parent, currentGroupEnd, currentGroup)
this.currentGroup = currentGroupEnd
}
}
fun addToGroupSizeAlongSpine(address: Int, amount: Int) {
var current = address
while (current > 0) {
groups.updateGroupSize(current, groups.groupSize(current) + amount)
val parentAnchor = groups.parentAnchor(current)
val parentGroup = parentAnchorToIndex(parentAnchor)
val parentAddress = groupIndexToAddress(parentGroup)
current = parentAddress
}
}
/**
* Insert the group at [index] in [table] to be the content of [currentGroup] plus [offset]
* without moving [currentGroup].
*
* It is required that the writer is *not* inserting and the [currentGroup] is empty.
*
* @return a list of the anchors that were moved.
*/
fun moveIntoGroupFrom(offset: Int, table: SlotTable, index: Int): List<Anchor> {
runtimeCheck(insertCount <= 0 && groupSize(currentGroup + offset) == 1)
val previousCurrentGroup = currentGroup
val previousCurrentSlot = currentSlot
val previousCurrentSlotEnd = currentSlotEnd
advanceBy(offset)
startGroup()
beginInsert()
val anchors = table.write { tableWriter ->
moveGroup(
tableWriter,
index,
this,
updateFromCursor = false,
updateToCursor = true
)
}
endInsert()
endGroup()
currentGroup = previousCurrentGroup
currentSlot = previousCurrentSlot
currentSlotEnd = previousCurrentSlotEnd
return anchors
}
/**
* Allocate an anchor to the current group or [index].
*/
fun anchor(index: Int = currentGroup): Anchor = anchors.getOrAdd(index, size) {
Anchor(if (index <= groupGapStart) index else -(size - index))
}
fun markGroup(group: Int = parent) {
val groupAddress = groupIndexToAddress(group)
if (!groups.hasMark(groupAddress)) {
groups.updateMark(groupAddress, true)
if (!groups.containsMark(groupAddress)) {
// This is a new mark, record the parent needs to update its contains mark.
updateContainsMark(parent(group))
}
}
}
private fun containsGroupMark(group: Int) =
group >= 0 && groups.containsMark(groupIndexToAddress(group))
private fun containsAnyGroupMarks(group: Int) =
group >= 0 && groups.containsAnyMark(groupIndexToAddress(group))
private var pendingRecalculateMarks: PrioritySet? = null
private fun recalculateMarks() {
pendingRecalculateMarks?.let { set ->
while (set.isNotEmpty()) {
updateContainsMarkNow(set.takeMax(), set)
}
}
}
private fun updateContainsMark(group: Int) {
if (group >= 0) {
(pendingRecalculateMarks ?: PrioritySet().also { pendingRecalculateMarks = it })
.add(group)
}
}
private fun updateContainsMarkNow(group: Int, set: PrioritySet) {
val groupAddress = groupIndexToAddress(group)
val containsAnyMarks = childContainsAnyMarks(group)
val markChanges = groups.containsMark(groupAddress) != containsAnyMarks
if (markChanges) {
groups.updateContainsMark(groupAddress, containsAnyMarks)
val parent = parent(group)
if (parent >= 0) set.add(parent)
}
}
private fun childContainsAnyMarks(group: Int): Boolean {
var child = group + 1
val end = group + groupSize(group)
while (child < end) {
if (groups.containsAnyMark(groupIndexToAddress(child))) return true
child += groupSize(child)
}
return false
}
/**
* Return the current anchor location while changing the slot table.
*/
fun anchorIndex(anchor: Anchor) = anchor.location.let { if (it < 0) size + it else it }
override fun toString(): String {
return "SlotWriter(current = $currentGroup end=$currentGroupEnd size = $size " +
"gap=$groupGapStart-${groupGapStart + groupGapLen})"
}
/**
* Save [currentGroupEnd] to [endStack].
*/
private fun saveCurrentGroupEnd() {
// Record the end location as relative to the end of the slot table so when we pop it
// back off again all inserts and removes that happened while a child group was open
// are already reflected into its value.
endStack.push(capacity - groupGapLen - currentGroupEnd)
}
/**
* Restore [currentGroupEnd] from [endStack].
*/
private fun restoreCurrentGroupEnd(): Int {
val newGroupEnd = (capacity - groupGapLen) - endStack.pop()
currentGroupEnd = newGroupEnd
return newGroupEnd
}
/**
* As groups move their parent anchors need to be updated. This recursively updates the
* parent anchors [parent] starting at [firstChild] and ending at [endGroup]. These are
* passed as a parameter to as the [groups] does not contain the current values for [parent]
* yet.
*/
private fun fixParentAnchorsFor(parent: Int, endGroup: Int, firstChild: Int) {
val parentAnchor = parentIndexToAnchor(parent, groupGapStart)
var child = firstChild
while (child < endGroup) {
groups.updateParentAnchor(groupIndexToAddress(child), parentAnchor)
val childEnd = child + groups.groupSize(groupIndexToAddress(child))
fixParentAnchorsFor(child, childEnd, child + 1)
child = childEnd
}
}
/**
* Move the gap in [groups] to [index].
*/
private fun moveGroupGapTo(index: Int) {
val gapLen = groupGapLen
val gapStart = groupGapStart
if (gapStart != index) {
if (anchors.isNotEmpty()) updateAnchors(gapStart, index)
if (gapLen > 0) {
val groups = groups
// Here physical is used to mean an index of the actual first int of the group in the
// array as opposed ot the logical address which is in groups of Group_Field_Size
// integers. IntArray.copyInto expects physical indexes.
val groupPhysicalAddress = index * Group_Fields_Size
val groupPhysicalGapLen = gapLen * Group_Fields_Size
val groupPhysicalGapStart = gapStart * Group_Fields_Size
if (index < gapStart) {
groups.copyInto(
destination = groups,
destinationOffset = groupPhysicalAddress + groupPhysicalGapLen,
startIndex = groupPhysicalAddress,
endIndex = groupPhysicalGapStart
)
} else {
groups.copyInto(
destination = groups,
destinationOffset = groupPhysicalGapStart,
startIndex = groupPhysicalGapStart + groupPhysicalGapLen,
endIndex = groupPhysicalAddress + groupPhysicalGapLen
)
}
}
// Gap has moved so the anchor for the groups that moved have changed so the parent
// anchors that refer to these groups must be updated.
var groupAddress = if (index < gapStart) index + gapLen else gapStart
val capacity = capacity
runtimeCheck(groupAddress < capacity)
while (groupAddress < capacity) {
val oldAnchor = groups.parentAnchor(groupAddress)
val oldIndex = parentAnchorToIndex(oldAnchor)
val newAnchor = parentIndexToAnchor(oldIndex, index)
if (newAnchor != oldAnchor) {
groups.updateParentAnchor(groupAddress, newAnchor)
}
groupAddress++
if (groupAddress == index) groupAddress += gapLen
}
}
this.groupGapStart = index
}
/**
* Move the gap in [slots] to [index] where [group] is expected to receive any new slots added.
*/
private fun moveSlotGapTo(index: Int, group: Int) {
val gapLen = slotsGapLen
val gapStart = slotsGapStart
val slotsGapOwner = slotsGapOwner
if (gapStart != index) {
val slots = slots
if (index < gapStart) {
// move the gap down to index by shifting the data up.
slots.copyInto(
destination = slots,
destinationOffset = index + gapLen,
startIndex = index,
endIndex = gapStart
)
} else {
// Shift the data down, leaving the gap at index
slots.copyInto(
destination = slots,
destinationOffset = gapStart,
startIndex = gapStart + gapLen,
endIndex = index + gapLen
)
}
// Clear the gap in the data array
slots.fill(null, index, index + gapLen)
}
// Update the data anchors affected by the move
val newSlotsGapOwner = min(group + 1, size)
if (slotsGapOwner != newSlotsGapOwner) {
val slotsSize = slots.size - gapLen
if (newSlotsGapOwner < slotsGapOwner) {
var updateAddress = groupIndexToAddress(newSlotsGapOwner)
val stopUpdateAddress = groupIndexToAddress(slotsGapOwner)
val groupGapStart = groupGapStart
while (updateAddress < stopUpdateAddress) {
val anchor = groups.dataAnchor(updateAddress)
runtimeCheck(anchor >= 0) {
"Unexpected anchor value, expected a positive anchor"
}
groups.updateDataAnchor(updateAddress, -(slotsSize - anchor + 1))
updateAddress++
if (updateAddress == groupGapStart) updateAddress += groupGapLen
}
} else {
var updateAddress = groupIndexToAddress(slotsGapOwner)
val stopUpdateAddress = groupIndexToAddress(newSlotsGapOwner)
while (updateAddress < stopUpdateAddress) {
val anchor = groups.dataAnchor(updateAddress)
runtimeCheck(anchor < 0) {
"Unexpected anchor value, expected a negative anchor"
}
groups.updateDataAnchor(updateAddress, slotsSize + anchor + 1)
updateAddress++
if (updateAddress == groupGapStart) updateAddress += groupGapLen
}
}
this.slotsGapOwner = newSlotsGapOwner
}
this.slotsGapStart = index
}
/**
* Insert [size] number of groups in front of [currentGroup]. These groups are implicitly a
* child of [parent].
*/
private fun insertGroups(size: Int) {
if (size > 0) {
val currentGroup = currentGroup
moveGroupGapTo(currentGroup)
val gapStart = groupGapStart
var gapLen = groupGapLen
val oldCapacity = groups.size / Group_Fields_Size
val oldSize = oldCapacity - gapLen
if (gapLen < size) {
// Create a bigger gap
val groups = groups
// Double the size of the array, but at least MinGrowthSize and >= size
val newCapacity = max(
max(oldCapacity * 2, oldSize + size),
MinGroupGrowthSize
)
val newGroups = IntArray(newCapacity * Group_Fields_Size)
val newGapLen = newCapacity - oldSize
val oldGapEndAddress = gapStart + gapLen
val newGapEndAddress = gapStart + newGapLen
// Copy the old arrays into the new arrays
groups.copyInto(
destination = newGroups,
destinationOffset = 0,
startIndex = 0,
endIndex = gapStart * Group_Fields_Size
)
groups.copyInto(
destination = newGroups,
destinationOffset = newGapEndAddress * Group_Fields_Size,
startIndex = oldGapEndAddress * Group_Fields_Size,
endIndex = oldCapacity * Group_Fields_Size
)
// Update the gap and slots
this.groups = newGroups
gapLen = newGapLen
}
// Move the currentGroupEnd to account for inserted groups.
val currentEnd = currentGroupEnd
if (currentEnd >= gapStart) this.currentGroupEnd = currentEnd + size
// Update the gap start and length
this.groupGapStart = gapStart + size
this.groupGapLen = gapLen - size
// Replicate the current group data index to the new slots
val index = if (oldSize > 0) dataIndex(currentGroup + size) else 0
// If the slotGapOwner is before the current location ensure we get end relative offsets
val anchor = dataIndexToDataAnchor(
index,
if (slotsGapOwner < gapStart) 0 else slotsGapStart,
slotsGapLen,
slots.size
)
for (groupAddress in gapStart until gapStart + size) {
groups.updateDataAnchor(groupAddress, anchor)
}
val slotsGapOwner = slotsGapOwner
if (slotsGapOwner >= gapStart) {
this.slotsGapOwner = slotsGapOwner + size
}
}
}
/**
* Insert room into the slot table. This is performed by first moving the gap to [currentSlot]
* and then reducing the gap [size] slots. If the gap is smaller than [size] the gap is grown
* to at least accommodate [size] slots. The new slots are associated with [group].
*/
private fun insertSlots(size: Int, group: Int) {
if (size > 0) {
moveSlotGapTo(currentSlot, group)
val gapStart = slotsGapStart
var gapLen = slotsGapLen
if (gapLen < size) {
val slots = slots
// Create a bigger gap
val oldCapacity = slots.size
val oldSize = oldCapacity - gapLen
// Double the size of the array, but at least MinGrowthSize and >= size
val newCapacity = max(
max(oldCapacity * 2, oldSize + size),
MinSlotsGrowthSize
)
val newData = Array<Any?>(newCapacity) { null }
val newGapLen = newCapacity - oldSize
val oldGapEndAddress = gapStart + gapLen
val newGapEndAddress = gapStart + newGapLen
// Copy the old arrays into the new arrays
slots.copyInto(
destination = newData,
destinationOffset = 0,
startIndex = 0,
endIndex = gapStart
)
slots.copyInto(
destination = newData,
destinationOffset = newGapEndAddress,
startIndex = oldGapEndAddress,
endIndex = oldCapacity
)
// Update the gap and slots
this.slots = newData
gapLen = newGapLen
}
val currentDataEnd = currentSlotEnd
if (currentDataEnd >= gapStart) this.currentSlotEnd = currentDataEnd + size
this.slotsGapStart = gapStart + size
this.slotsGapLen = gapLen - size
}
}
/**
* Remove [len] group from [start].
*/
private fun removeGroups(start: Int, len: Int): Boolean {
return if (len > 0) {
var anchorsRemoved = false
val anchors = anchors
// Move the gap to start of the removal and grow the gap
moveGroupGapTo(start)
if (anchors.isNotEmpty()) anchorsRemoved = removeAnchors(start, len)
groupGapStart = start
val previousGapLen = groupGapLen
val newGapLen = previousGapLen + len
groupGapLen = newGapLen
// Adjust the gap owner if necessary.
val slotsGapOwner = slotsGapOwner
if (slotsGapOwner > start) {
// Use max here as if we delete the current owner this group becomes the owner.
this.slotsGapOwner = max(start, slotsGapOwner - len)
}
if (currentGroupEnd >= groupGapStart) currentGroupEnd -= len
// Update markers if necessary
if (containsGroupMark(parent)) {
updateContainsMark(parent)
}
anchorsRemoved
} else false
}
/**
* Remove [len] slots from [start].
*/
private fun removeSlots(start: Int, len: Int, group: Int) {
if (len > 0) {
val gapLen = slotsGapLen
val removeEnd = start + len
moveSlotGapTo(removeEnd, group)
slotsGapStart = start
slotsGapLen = gapLen + len
slots.fill(null, start, start + len)
val currentDataEnd = currentSlotEnd
if (currentDataEnd >= start) this.currentSlotEnd = currentDataEnd - len
}
}
/**
* A helper function to update the number of nodes in a group.
*/
private fun updateNodeOfGroup(index: Int, value: Any?) {
val address = groupIndexToAddress(index)
runtimeCheck(address < groups.size && groups.isNode(address)) {
"Updating the node of a group at $index that was not created with as a node group"
}
slots[dataIndexToDataAddress(groups.nodeIndex(address))] = value
}
/**
* A helper function to update the anchors as the gap in [groups] moves.
*/
private fun updateAnchors(previousGapStart: Int, newGapStart: Int) {
val gapLen = groupGapLen
val size = capacity - gapLen
if (previousGapStart < newGapStart) {
// Gap is moving up
// All anchors between the new gap and the old gap switch to be anchored to the
// front of the table instead of the end.
var index = anchors.locationOf(previousGapStart, size)
while (index < anchors.size) {
val anchor = anchors[index]
val location = anchor.location
if (location < 0) {
val newLocation = size + location
if (newLocation < newGapStart) {
anchor.location = size + location
index++
} else break
} else break
}
} else {
// Gap is moving down. All anchors between newGapStart and previousGapStart need now
// to be anchored to the end of the table instead of the front of the table.
var index = anchors.locationOf(newGapStart, size)
while (index < anchors.size) {
val anchor = anchors[index]
val location = anchor.location
if (location >= 0) {
anchor.location = -(size - location)
index++
} else break
}
}
}
/**
* A helper function to remove the anchors for groups that are removed.
*/
private fun removeAnchors(gapStart: Int, size: Int): Boolean {
val gapLen = groupGapLen
val removeEnd = gapStart + size
val groupsSize = capacity - gapLen
var index = anchors.locationOf(gapStart + size, groupsSize).let {
if (it >= anchors.size) it - 1 else it
}
var removeAnchorEnd = 0
var removeAnchorStart = index + 1
while (index >= 0) {
val anchor = anchors[index]
val location = anchorIndex(anchor)
if (location >= gapStart) {
if (location < removeEnd) {
anchor.location = Int.MIN_VALUE
removeAnchorStart = index
if (removeAnchorEnd == 0) removeAnchorEnd = index + 1
}
index--
} else break
}
return (removeAnchorStart < removeAnchorEnd).also {
if (it) anchors.subList(removeAnchorStart, removeAnchorEnd).clear()
}
}
/**
* A helper function to update anchors for groups that have moved.
*/
private fun moveAnchors(originalLocation: Int, newLocation: Int, size: Int) {
val end = originalLocation + size
val groupsSize = this.size
// Remove all the anchors in range from the original location
val index = anchors.locationOf(originalLocation, groupsSize)
val removedAnchors = mutableListOf<Anchor>()
if (index >= 0) {
while (index < anchors.size) {
val anchor = anchors[index]
val location = anchorIndex(anchor)
@Suppress("ConvertTwoComparisonsToRangeCheck")
if (location >= originalLocation && location < end) {
removedAnchors.add(anchor)
anchors.removeAt(index)
} else break
}
}
// Insert the anchors into there new location
val moveDelta = newLocation - originalLocation
removedAnchors.fastForEach { anchor ->
val anchorIndex = anchorIndex(anchor)
val newAnchorIndex = anchorIndex + moveDelta
if (newAnchorIndex >= groupGapStart) {
anchor.location = -(groupsSize - newAnchorIndex)
} else {
anchor.location = newAnchorIndex
}
val insertIndex = anchors.locationOf(newAnchorIndex, groupsSize)
anchors.add(insertIndex, anchor)
}
}
/**
* A debugging aid that emits [groups] as a string.
*/
@Suppress("unused")
fun groupsAsString(): String = buildString {
for (index in 0 until size) {
groupAsString(index)
append('\n')
}
}
/**
* A debugging aid that emits a group as a string into a string builder.
*/
private fun StringBuilder.groupAsString(index: Int) {
val address = groupIndexToAddress(index)
append("Group(")
if (index < 10) append(' ')
if (index < 100) append(' ')
if (index < 1000) append(' ')
append(index)
if (address != index) {
append("(")
append(address)
append(")")
}
append('#')
append(groups.groupSize(address))
fun isStarted(index: Int): Boolean =
index < currentGroup && (index == parent || startStack.indexOf(index) >= 0 ||
isStarted(parent(index)))
val openGroup = isStarted(index)
if (openGroup) append('?')
append('^')
append(parentAnchorToIndex(groups.parentAnchor(address)))
append(": key=")
append(groups.key(address))
append(", nodes=")
append(groups.nodeCount(address))
if (openGroup) append('?')
append(", dataAnchor=")
append(groups.dataAnchor(address))
append(", parentAnchor=")
append(groups.parentAnchor(address))
if (groups.isNode(address)) {
append(
", node=${
slots[
dataIndexToDataAddress(groups.nodeIndex(address))
]
}"
)
}
val startData = groups.slotIndex(address)
val endData = groups.dataIndex(address + 1)
if (endData > startData) {
append(", [")
for (dataIndex in startData until endData) {
if (dataIndex != startData) append(", ")
val dataAddress = dataIndexToDataAddress(dataIndex)
append("${slots[dataAddress]}")
}
append(']')
}
append(")")
}
internal fun verifyDataAnchors() {
var previousDataIndex = 0
val owner = slotsGapOwner
var ownerFound = false
val slotsSize = slots.size - slotsGapLen
for (index in 0 until size) {
val address = groupIndexToAddress(index)
val dataAnchor = groups.dataAnchor(address)
val dataIndex = groups.dataIndex(address)
check(dataIndex >= previousDataIndex) {
"Data index out of order at $index, previous = $previousDataIndex, current = " +
"$dataIndex"
}
check(dataIndex <= slotsSize) {
"Data index, $dataIndex, out of bound at $index"
}
if (dataAnchor < 0 && !ownerFound) {
check(owner == index) {
"Expected the slot gap owner to be $owner found gap at $index"
}
ownerFound = true
}
previousDataIndex = dataIndex
}
}
@Suppress("unused")
internal fun verifyParentAnchors() {
val gapStart = groupGapStart
val gapLen = groupGapLen
val capacity = capacity
for (groupAddress in 0 until gapStart) {
val parentAnchor = groups.parentAnchor(groupAddress)
check(parentAnchor > parentAnchorPivot) {
"Expected a start relative anchor at $groupAddress"
}
}
for (groupAddress in gapStart + gapLen until capacity) {
val parentAnchor = groups.parentAnchor(groupAddress)
val parentIndex = parentAnchorToIndex(parentAnchor)
if (parentIndex < gapStart) {
check(parentAnchor > parentAnchorPivot) {
"Expected a start relative anchor at $groupAddress"
}
} else {
check(parentAnchor <= parentAnchorPivot) {
"Expected an end relative anchor at $groupAddress"
}
}
}
}
internal val size get() = capacity - groupGapLen
private val capacity get() = groups.size / Group_Fields_Size
private fun groupIndexToAddress(index: Int) =
if (index < groupGapStart) index else index + groupGapLen
private fun dataIndexToDataAddress(dataIndex: Int) =
if (dataIndex < slotsGapStart) dataIndex else dataIndex + slotsGapLen
private fun IntArray.parent(index: Int) =
parentAnchorToIndex(parentAnchor(groupIndexToAddress(index)))
private fun dataIndex(index: Int) = groups.dataIndex(groupIndexToAddress(index))
private fun IntArray.dataIndex(address: Int) =
if (address >= capacity) slots.size - slotsGapLen
else dataAnchorToDataIndex(dataAnchor(address), slotsGapLen, slots.size)
private fun IntArray.slotIndex(address: Int) =
if (address >= capacity) slots.size - slotsGapLen
else dataAnchorToDataIndex(slotAnchor(address), slotsGapLen, slots.size)
private fun IntArray.updateDataIndex(address: Int, dataIndex: Int) {
updateDataAnchor(
address,
dataIndexToDataAnchor(dataIndex, slotsGapStart, slotsGapLen, slots.size)
)
}
private fun IntArray.nodeIndex(address: Int) = dataIndex(address)
private fun IntArray.auxIndex(address: Int) =
dataIndex(address) + countOneBits(groupInfo(address) shr (Aux_Shift + 1))
@Suppress("unused")
private fun IntArray.dataIndexes() = groups.dataAnchors().let {
it.slice(0 until groupGapStart) +
it.slice(groupGapStart + groupGapLen until (size / Group_Fields_Size))
}.fastMap { anchor -> dataAnchorToDataIndex(anchor, slotsGapLen, slots.size) }
@Suppress("unused")
private fun keys() = groups.keys().fastFilterIndexed { index, _ ->
index < groupGapStart || index >= groupGapStart + groupGapLen
}
private fun dataIndexToDataAnchor(index: Int, gapStart: Int, gapLen: Int, capacity: Int) =
if (index > gapStart) -((capacity - gapLen) - index + 1) else index
private fun dataAnchorToDataIndex(anchor: Int, gapLen: Int, capacity: Int) =
if (anchor < 0) (capacity - gapLen) + anchor + 1 else anchor
private fun parentIndexToAnchor(index: Int, gapStart: Int) =
if (index < gapStart) index else -(size - index - parentAnchorPivot)
private fun parentAnchorToIndex(index: Int) =
if (index > parentAnchorPivot) index else size + index - parentAnchorPivot
}
private class SlotTableGroup(
val table: SlotTable,
val group: Int,
val version: Int = table.version
) : CompositionGroup, Iterable<CompositionGroup> {
override val isEmpty: Boolean get() = table.groups.groupSize(group) == 0
override val key: Any
get() = if (table.groups.hasObjectKey(group))
table.slots[table.groups.objectKeyIndex(group)]!!
else table.groups.key(group)
override val sourceInfo: String?
get() = if (table.groups.hasAux(group))
table.slots[table.groups.auxIndex(group)] as? String
else null
override val node: Any?
get() = if (table.groups.isNode(group))
table.slots[table.groups.nodeIndex(group)] else
null
override val data: Iterable<Any?> get() = DataIterator(table, group)
override val identity: Any
get() {
validateRead()
return table.read { it.anchor(group) }
}
override val compositionGroups: Iterable<CompositionGroup> get() = this
override fun iterator(): Iterator<CompositionGroup> {
validateRead()
return GroupIterator(
table,
group + 1,
group + table.groups.groupSize(group)
)
}
override val groupSize: Int get() = table.groups.groupSize(group)
override val slotsSize: Int
get() {
val nextGroup = group + groupSize
val nextSlot = if (nextGroup < table.groupsSize) table.groups.dataAnchor(nextGroup)
else table.slotsSize
return nextSlot - table.groups.dataAnchor(group)
}
private fun validateRead() {
if (table.version != version) {
throw ConcurrentModificationException()
}
}
override fun find(identityToFind: Any): CompositionGroup? =
(identityToFind as? Anchor)?.let { anchor ->
if (table.ownsAnchor(anchor)) {
val anchorGroup = table.anchorIndex(anchor)
if (anchorGroup >= group && (anchorGroup - group < table.groups.groupSize(group)))
SlotTableGroup(table, anchorGroup, version)
else null
} else null
}
}
private class GroupIterator(
val table: SlotTable,
start: Int,
val end: Int
) : Iterator<CompositionGroup> {
private var index = start
private val version = table.version
init {
if (table.writer) throw ConcurrentModificationException()
}
override fun hasNext() = index < end
override fun next(): CompositionGroup {
validateRead()
val group = index
index += table.groups.groupSize(group)
return SlotTableGroup(table, group, version)
}
private fun validateRead() {
if (table.version != version) {
throw ConcurrentModificationException()
}
}
}
private class DataIterator(
val table: SlotTable,
val group: Int,
) : Iterable<Any?>, Iterator<Any?> {
val start = table.groups.dataAnchor(group)
val end = if (group + 1 < table.groupsSize)
table.groups.dataAnchor(group + 1) else table.slotsSize
var index = start
override fun iterator(): Iterator<Any?> = this
override fun hasNext(): Boolean = index < end
override fun next(): Any? = (
if (index >= 0 && index < table.slots.size)
table.slots[index]
else null
).also { index++ }
}
// Parent -1 is reserved to be the root parent index so the anchor must pivot on -2.
private const val parentAnchorPivot = -2
// Group layout
// 0 | 1 | 2 | 3 | 4 |
// Key | Group info | Parent anchor | Size | Data anchor |
private const val Key_Offset = 0
private const val GroupInfo_Offset = 1
private const val ParentAnchor_Offset = 2
private const val Size_Offset = 3
private const val DataAnchor_Offset = 4
private const val Group_Fields_Size = 5
// Key is the key parameter passed into startGroup
// Group info is laid out as follows,
// 31 30 29 28_27 26 25 24_23 22 21 20_19 18 17 16__15 14 13 12_11 10 09 08_07 06 05 04_03 02 01 00
// 0 n ks ds m cm| node count |
// where n is set when the group represents a node
// where ks is whether the group has a object key slot
// where ds is whether the group has a group data slot
// where m is whether the group is marked
// where cm is whether the group contains a mark
// Parent anchor is a group anchor to the parent, as the group gap is moved this value is updated to
// refer to the parent.
// Slot count is the total number of group slots, including itself, occupied by the group.
// Data anchor is an anchor to the group data. The value is positive if it is before the data gap
// and it is negative if it is after the data gap. As gaps are moved, these values are updated.
// Masks and flags
private const val NodeBit_Mask = 0b0100_0000_0000_0000__0000_0000_0000_0000
private const val ObjectKey_Mask = 0b0010_0000_0000_0000__0000_0000_0000_0000
private const val ObjectKey_Shift = 29
private const val Aux_Mask = 0b0001_0000_0000_0000__0000_0000_0000_0000
private const val Aux_Shift = 28
private const val Mark_Mask = 0b0000_1000_0000_0000__0000_0000_0000_0000
private const val ContainsMark_Mask = 0b0000_0100_0000_0000__0000_0000_0000_0000
private const val Slots_Shift = Aux_Shift
private const val NodeCount_Mask = 0b0000_0011_1111_1111__1111_1111_1111_1111
// Special values
// The minimum number of groups to allocate the group table
private const val MinGroupGrowthSize = 32
// The minimum number of data slots to allocate in the data slot table
private const val MinSlotsGrowthSize = 32
// The key to used for nodes
private const val NodeKey = 125
private fun IntArray.groupInfo(address: Int): Int =
this[address * Group_Fields_Size + GroupInfo_Offset]
private fun IntArray.isNode(address: Int) =
this[address * Group_Fields_Size + GroupInfo_Offset] and NodeBit_Mask != 0
private fun IntArray.nodeIndex(address: Int) = this[address * Group_Fields_Size + DataAnchor_Offset]
private fun IntArray.hasObjectKey(address: Int) =
this[address * Group_Fields_Size + GroupInfo_Offset] and ObjectKey_Mask != 0
private fun IntArray.objectKeyIndex(address: Int) = (address * Group_Fields_Size).let { slot ->
this[slot + DataAnchor_Offset] +
countOneBits(this[slot + GroupInfo_Offset] shr (ObjectKey_Shift + 1))
}
private fun IntArray.hasAux(address: Int) =
this[address * Group_Fields_Size + GroupInfo_Offset] and Aux_Mask != 0
private fun IntArray.addAux(address: Int) {
val arrayIndex = address * Group_Fields_Size + GroupInfo_Offset
this[arrayIndex] = this[arrayIndex] or Aux_Mask
}
private fun IntArray.hasMark(address: Int) =
this[address * Group_Fields_Size + GroupInfo_Offset] and Mark_Mask != 0
private fun IntArray.updateMark(address: Int, value: Boolean) {
val arrayIndex = address * Group_Fields_Size + GroupInfo_Offset
if (value) {
this[arrayIndex] = this[arrayIndex] or Mark_Mask
} else {
this[arrayIndex] = this[arrayIndex] and Mark_Mask.inv()
}
}
private fun IntArray.containsMark(address: Int) =
this[address * Group_Fields_Size + GroupInfo_Offset] and ContainsMark_Mask != 0
private fun IntArray.updateContainsMark(address: Int, value: Boolean) {
val arrayIndex = address * Group_Fields_Size + GroupInfo_Offset
if (value) {
this[arrayIndex] = this[arrayIndex] or ContainsMark_Mask
} else {
this[arrayIndex] = this[arrayIndex] and ContainsMark_Mask.inv()
}
}
private fun IntArray.containsAnyMark(address: Int) =
this[address * Group_Fields_Size + GroupInfo_Offset] and
(ContainsMark_Mask or Mark_Mask) != 0
private fun IntArray.auxIndex(address: Int) = (address * Group_Fields_Size).let { slot ->
if (slot >= size) size
else this[slot + DataAnchor_Offset] +
countOneBits(this[slot + GroupInfo_Offset] shr (Aux_Shift + 1))
}
private fun IntArray.slotAnchor(address: Int) = (address * Group_Fields_Size).let { slot ->
this[slot + DataAnchor_Offset] +
countOneBits(this[slot + GroupInfo_Offset] shr Slots_Shift)
}
// Count the 1 bits of value less than 8
private fun countOneBits(value: Int) = when (value) {
0 -> 0
1 -> 1
2 -> 1
3 -> 2
4 -> 1
5 -> 2
6 -> 2
else -> 3
}
// Key access
private fun IntArray.key(address: Int) = this[address * Group_Fields_Size]
private fun IntArray.keys(len: Int = size) =
slice(Key_Offset until len step Group_Fields_Size)
// Node count access
private fun IntArray.nodeCount(address: Int) =
this[address * Group_Fields_Size + GroupInfo_Offset] and NodeCount_Mask
private fun IntArray.updateNodeCount(address: Int, value: Int) {
@Suppress("ConvertTwoComparisonsToRangeCheck")
runtimeCheck(value >= 0 && value < NodeCount_Mask)
this[address * Group_Fields_Size + GroupInfo_Offset] =
(this[address * Group_Fields_Size + GroupInfo_Offset] and NodeCount_Mask.inv()) or value
}
private fun IntArray.nodeCounts(len: Int = size) =
slice(GroupInfo_Offset until len step Group_Fields_Size)
.fastMap { it and NodeCount_Mask }
// Parent anchor
private fun IntArray.parentAnchor(address: Int) =
this[address * Group_Fields_Size + ParentAnchor_Offset]
private fun IntArray.updateParentAnchor(address: Int, value: Int) {
this[address * Group_Fields_Size + ParentAnchor_Offset] = value
}
private fun IntArray.parentAnchors(len: Int = size) =
slice(ParentAnchor_Offset until len step Group_Fields_Size)
// Slot count access
private fun IntArray.groupSize(address: Int) = this[address * Group_Fields_Size + Size_Offset]
private fun IntArray.updateGroupSize(address: Int, value: Int) {
runtimeCheck(value >= 0)
this[address * Group_Fields_Size + Size_Offset] = value
}
private fun IntArray.slice(indices: Iterable<Int>): List<Int> {
val list = mutableListOf<Int>()
for (index in indices) {
list.add(get(index))
}
return list
}
@Suppress("unused")
private fun IntArray.groupSizes(len: Int = size) =
slice(Size_Offset until len step Group_Fields_Size)
// Data anchor access
private fun IntArray.dataAnchor(address: Int) =
this[address * Group_Fields_Size + DataAnchor_Offset]
private fun IntArray.updateDataAnchor(address: Int, anchor: Int) {
this[address * Group_Fields_Size + DataAnchor_Offset] = anchor
}
private fun IntArray.dataAnchors(len: Int = size) =
slice(DataAnchor_Offset until len step Group_Fields_Size)
// Update data
private fun IntArray.initGroup(
address: Int,
key: Int,
isNode: Boolean,
hasDataKey: Boolean,
hasData: Boolean,
parentAnchor: Int,
dataAnchor: Int
) {
val nodeBit = if (isNode) NodeBit_Mask else 0
val dataKeyBit = if (hasDataKey) ObjectKey_Mask else 0
val dataBit = if (hasData) Aux_Mask else 0
val arrayIndex = address * Group_Fields_Size
this[arrayIndex + Key_Offset] = key
this[arrayIndex + GroupInfo_Offset] = nodeBit or dataKeyBit or dataBit
this[arrayIndex + ParentAnchor_Offset] = parentAnchor
this[arrayIndex + Size_Offset] = 0
this[arrayIndex + DataAnchor_Offset] = dataAnchor
}
private fun IntArray.updateGroupKey(
address: Int,
key: Int,
) {
val arrayIndex = address * Group_Fields_Size
this[arrayIndex + Key_Offset] = key
}
private inline fun ArrayList<Anchor>.getOrAdd(
index: Int,
effectiveSize: Int,
block: () -> Anchor
): Anchor {
val location = search(index, effectiveSize)
return if (location < 0) {
val anchor = block()
add(-(location + 1), anchor)
anchor
} else get(location)
}
/**
* This is inlined here instead to avoid allocating a lambda for the compare when this is used.
*/
private fun ArrayList<Anchor>.search(location: Int, effectiveSize: Int): Int {
var low = 0
var high = size - 1
while (low <= high) {
val mid = (low + high).ushr(1) // safe from overflows
val midVal = get(mid).location.let { if (it < 0) effectiveSize + it else it }
val cmp = midVal.compareTo(location)
when {
cmp < 0 -> low = mid + 1
cmp > 0 -> high = mid - 1
else -> return mid // key found
}
}
return -(low + 1) // key not found
}
/**
* A wrapper on [search] that always returns an index in to [this] even if [index] is not in the
* array list.
*/
private fun ArrayList<Anchor>.locationOf(index: Int, effectiveSize: Int) =
search(index, effectiveSize).let { if (it >= 0) it else -(it + 1) }
/**
* PropertySet implements a set which allows recording integers into a set an efficiently
* extracting the greatest max value out of the set. It does this using the heap structure from a
* heap sort that ensures that adding or removing a value is O(log N) operation even if values are
* repeatedly added and removed.
*/
internal class PrioritySet(private val list: MutableList<Int> = mutableListOf()) {
// Add a value to the heap
fun add(value: Int) {
// Filter trivial duplicates
if (list.isNotEmpty() && (list[0] == value || list[list.size - 1] == value)) return
var index = list.size
list.add(value)
// Shift the value up the heap.
while (index > 0) {
val parent = ((index + 1) ushr 1) - 1
val parentValue = list[parent]
if (value > parentValue) {
list[index] = parentValue
} else break
index = parent
}
list[index] = value
}
fun isEmpty() = list.isEmpty()
fun isNotEmpty() = list.isNotEmpty()
fun peek() = list.first()
// Remove a de-duplicated value from the heap
fun takeMax(): Int {
runtimeCheck(list.size > 0) { "Set is empty" }
val value = list[0]
// Skip duplicates. It is not time efficient to remove duplicates from the list while
// adding so remove them when they leave the list. This also implies that the underlying
// list's size is not an accurate size of the list so this set doesn't implement size.
// If size is needed later consider de-duping on insert which might require companion map.
while (list.isNotEmpty() && list[0] == value) {
// Shift the last value down.
list[0] = list.last()
list.removeAt(list.size - 1)
var index = 0
val size = list.size
val max = list.size ushr 1
while (index < max) {
val indexValue = list[index]
val left = (index + 1) * 2 - 1
val leftValue = list[left]
val right = (index + 1) * 2
if (right < size) {
// Note: only right can exceed size because of the constraint on index being
// less than floor(list.size / 2)
val rightValue = list[right]
if (rightValue > leftValue) {
if (rightValue > indexValue) {
list[index] = rightValue
list[right] = indexValue
index = right
continue
} else break
}
}
if (leftValue > indexValue) {
list[index] = leftValue
list[left] = indexValue
index = left
} else break
}
}
return value
}
fun validateHeap() {
val size = list.size
for (index in 0 until size / 2) {
val left = (index + 1) * 2 - 1
val right = (index + 1) * 2
check(list[index] >= list[left])
check(right >= size || list[index] >= list[right])
}
}
} | apache-2.0 | fdb769702d7b76eca08bdb8b22bf49a0 | 36.259001 | 103 | 0.592352 | 4.585114 | false | false | false | false |
androidx/androidx | camera/integration-tests/timingtestapp/src/main/java/androidx/camera/integration/antelope/TimingTests.kt | 3 | 27043 | /*
* 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.camera.integration.antelope
import androidx.camera.integration.antelope.MainActivity.Companion.cameraParams
import androidx.camera.integration.antelope.MainActivity.Companion.logd
import androidx.camera.integration.antelope.cameracontrollers.camera1OpenCamera
import androidx.camera.integration.antelope.cameracontrollers.camera2OpenCamera
import androidx.camera.integration.antelope.cameracontrollers.cameraXOpenCamera
import androidx.camera.integration.antelope.cameracontrollers.cameraXTakePicture
import androidx.camera.integration.antelope.cameracontrollers.closePreviewAndCamera
import androidx.camera.integration.antelope.cameracontrollers.initializeStillCapture
// Keeps track of what iteration of a repeated test is occurring
internal var multiCounter: Int = 0
internal fun initializeTest(
activity: MainActivity,
params: CameraParams?,
config: TestConfig
) {
if (null == params)
return
// Camera1 cannot directly access physical cameras. If we try, abort.
if ((CameraAPI.CAMERA1 == config.api) &&
!(PrefHelper.getLogicalCameraIds(cameraParams).contains(config.camera))
) {
activity.resetUIAfterTest()
activity.updateLog(
"ABORTED: Camera1 API cannot access camera with id:" + config.camera,
false, false
)
return
}
when (config.currentRunningTest) {
TestType.INIT -> runInitTest(activity, params, config)
TestType.PREVIEW ->
runPreviewTest(activity, params, config)
TestType.SWITCH_CAMERA ->
runSwitchTest(activity, params, config)
TestType.MULTI_SWITCH ->
runMultiSwitchTest(activity, params, config)
TestType.PHOTO ->
runPhotoTest(activity, params, config)
TestType.MULTI_PHOTO ->
runMultiPhotoTest(activity, params, config)
TestType.MULTI_PHOTO_CHAIN ->
runMultiPhotoChainTest(activity, params, config)
TestType.NONE -> Unit
}
}
/**
* Run the INIT test
*/
internal fun runInitTest(
activity: MainActivity,
params: CameraParams,
config: TestConfig
) {
logd("Running init test")
activity.startBackgroundThread(params)
activity.showProgressBar(true)
setupImageReader(activity, params, config)
params.timer = CameraTimer()
config.currentRunningTest = TestType.INIT
params.timer.testStart = System.currentTimeMillis()
beginTest(activity, params, config)
}
/**
* Run the SWITCH test
*/
internal fun runSwitchTest(activity: MainActivity, params: CameraParams, config: TestConfig) {
// For switch test, always go from default back camera to default front camera and back 0->1->0
// TODO: Can we handle different permutations of physical cameras?
if (!PrefHelper.getLogicalCameraIds(cameraParams).contains("0") ||
!PrefHelper.getLogicalCameraIds(cameraParams).contains("1")
) {
activity.resetUIAfterTest()
activity.updateLog(
"ABORTED: Camera 0 and 1 needed for Switch test.",
false, false
)
return
}
config.switchTestCameras = arrayOf("0", "1")
config.switchTestCurrentCamera = "0"
logd("Running switch test")
logd("Starting with camera: " + config.switchTestCurrentCamera)
activity.startBackgroundThread(params)
activity.showProgressBar(true)
setupImageReader(activity, params, config)
params.timer = CameraTimer()
config.currentRunningTest = TestType.SWITCH_CAMERA
params.timer.testStart = System.currentTimeMillis()
beginTest(activity, params, config)
}
/**
* Run the MULTI_SWITCH test
*/
internal fun runMultiSwitchTest(activity: MainActivity, params: CameraParams, config: TestConfig) {
// For switch test, always go from default back camera to default front camera and back 0->1->0
// TODO: Can we handle different permutations of physical cameras?
if (!PrefHelper.getLogicalCameraIds(cameraParams).contains("0") ||
!PrefHelper.getLogicalCameraIds(cameraParams).contains("1")
) {
activity.resetUIAfterTest()
activity.updateLog(
"ABORTED: Camera 0 and 1 needed for Switch test.",
false, false
)
return
}
config.switchTestCameras = arrayOf("0", "1")
if (0 == multiCounter) {
// New test
logd("Running multi switch test")
config.switchTestCurrentCamera = "0"
activity.startBackgroundThread(params)
activity.showProgressBar(true, 0)
multiCounter = PrefHelper.getNumTests(activity)
config.currentRunningTest = TestType.MULTI_SWITCH
config.testFinished = false
} else {
// Add previous result
params.timer.testEnd = System.currentTimeMillis()
activity.showProgressBar(true, precentageCompleted(activity, multiCounter))
logd("In Multi Switch Test. Counter: " + multiCounter)
config.testResults.initialization.add(params.timer.openEnd - params.timer.openStart)
config.testResults.previewStart.add(params.timer.previewEnd - params.timer.previewStart)
config.testResults.switchToSecond
.add(params.timer.switchToSecondEnd - params.timer.switchToSecondStart)
config.testResults.switchToFirst
.add(params.timer.switchToFirstEnd - params.timer.switchToFirstStart)
config.testResults.previewClose
.add(params.timer.previewCloseEnd - params.timer.previewCloseStart)
config.testResults.cameraClose
.add(params.timer.cameraCloseEnd - params.timer.cameraCloseStart)
config.testResults.total.add(params.timer.testEnd - params.timer.testStart)
config.testFinished = false
config.isFirstOnActive = true
}
setupImageReader(activity, params, config)
params.timer = CameraTimer()
params.timer.testStart = System.currentTimeMillis()
beginTest(activity, params, config)
}
/**
* Run the PREVIEW test
*/
internal fun runPreviewTest(activity: MainActivity, params: CameraParams, config: TestConfig) {
logd("Running preview test")
activity.startBackgroundThread(params)
activity.showProgressBar(true)
setupImageReader(activity, params, config)
params.timer = CameraTimer()
config.currentRunningTest = TestType.PREVIEW
params.timer.testStart = System.currentTimeMillis()
beginTest(activity, params, config)
}
/**
* Run the PHOTO (single capture) test
*/
internal fun runPhotoTest(activity: MainActivity, params: CameraParams, config: TestConfig) {
logd("Running photo test")
activity.startBackgroundThread(params)
activity.showProgressBar(true)
setupImageReader(activity, params, config)
params.timer = CameraTimer()
config.currentRunningTest = TestType.PHOTO
params.timer.testStart = System.currentTimeMillis()
logd("About to start photo test. " + config.currentRunningTest.toString())
beginTest(activity, params, config)
}
/**
* Run the MULTI_PHOTO (repeated capture) test
*/
internal fun runMultiPhotoTest(activity: MainActivity, params: CameraParams, config: TestConfig) {
if (0 == multiCounter) {
// New test
logd("Running multi photo test")
activity.startBackgroundThread(params)
activity.showProgressBar(true, 0)
multiCounter = PrefHelper.getNumTests(activity)
config.currentRunningTest = TestType.MULTI_PHOTO
logd(
"About to start multi photo test. multi_counter: " + multiCounter + " and test: " +
config.currentRunningTest.toString()
)
} else {
// Add previous result
params.timer.testEnd = System.currentTimeMillis()
activity.showProgressBar(true, precentageCompleted(activity, multiCounter))
logd("In Multi Photo Test. Counter: " + multiCounter)
config.testResults.initialization.add(params.timer.openEnd - params.timer.openStart)
config.testResults.previewStart.add(params.timer.previewEnd - params.timer.previewStart)
config.testResults.previewFill
.add(params.timer.previewFillEnd - params.timer.previewFillStart)
config.testResults.autofocus.add(params.timer.autofocusEnd - params.timer.autofocusStart)
config.testResults.captureNoAF.add(
(params.timer.captureEnd - params.timer.captureStart) -
(params.timer.autofocusEnd - params.timer.autofocusStart)
)
config.testResults.capture.add(params.timer.captureEnd - params.timer.captureStart)
config.testResults.imageready
.add(params.timer.imageReaderEnd - params.timer.imageReaderStart)
config.testResults.capturePlusImageReady
.add(
(params.timer.captureEnd - params.timer.captureStart) +
(params.timer.imageReaderEnd - params.timer.imageReaderStart)
)
config.testResults.imagesave
.add(params.timer.imageSaveEnd - params.timer.imageSaveStart)
config.testResults.isHDRPlus.add(params.timer.isHDRPlus)
config.testResults.previewClose
.add(params.timer.previewCloseEnd - params.timer.previewCloseStart)
config.testResults.cameraClose
.add(params.timer.cameraCloseEnd - params.timer.cameraCloseStart)
config.testResults.total.add(params.timer.testEnd - params.timer.testStart)
config.testResults.totalNoPreview.add(
(params.timer.testEnd - params.timer.testStart) -
(params.timer.previewFillEnd - params.timer.previewFillStart)
)
config.testFinished = false
config.isFirstOnActive = true
config.isFirstOnCaptureComplete = true
}
setupImageReader(activity, params, config)
params.timer = CameraTimer()
params.timer.testStart = System.currentTimeMillis()
beginTest(activity, params, config)
}
/**
* Run the MULTI_PHOTO_CHAIN (multiple captures, do not close camera) test
*/
internal fun runMultiPhotoChainTest(
activity: MainActivity,
params: CameraParams,
config: TestConfig
) {
// Cannot chain with Camera 1, run default test
if (CameraAPI.CAMERA1 == config.api) {
logd("Cannot run Chain test with Camera 1, running regular multi-test instead")
config.currentRunningTest = TestType.MULTI_PHOTO
runMultiPhotoTest(activity, params, config)
return
}
if (0 == multiCounter) {
// New test
logd("Running multi photo (chain) test")
activity.startBackgroundThread(params)
activity.showProgressBar(true, 0)
multiCounter = PrefHelper.getNumTests(activity)
params.timer = CameraTimer()
params.timer.testStart = System.currentTimeMillis()
config.currentRunningTest = TestType.MULTI_PHOTO_CHAIN
logd(
"About to start multi chain test. multi_counter: " + multiCounter + " and test: " +
config.currentRunningTest.toString()
)
setupImageReader(activity, params, config)
beginTest(activity, params, config)
} else {
// Add previous result
activity.showProgressBar(true, precentageCompleted(activity, multiCounter))
if (config.api == CameraAPI.CAMERA1) {
beginTest(activity, params, config)
} else {
// Camera2 and CameraX
config.testResults.autofocus
.add(params.timer.autofocusEnd - params.timer.autofocusStart)
config.testResults.captureNoAF
.add(
(params.timer.captureEnd - params.timer.captureStart) -
(params.timer.autofocusEnd - params.timer.autofocusStart)
)
config.testResults.capture.add(params.timer.captureEnd - params.timer.captureStart)
config.testResults.imageready
.add(params.timer.imageReaderEnd - params.timer.imageReaderStart)
config.testResults.capturePlusImageReady
.add(
(params.timer.captureEnd - params.timer.captureStart) +
(params.timer.imageReaderEnd - params.timer.imageReaderStart)
)
config.testResults.imagesave
.add(params.timer.imageSaveEnd - params.timer.imageSaveStart)
config.testResults.isHDRPlus.add(params.timer.isHDRPlus)
config.testFinished = false
params.timer.clearImageTimers()
config.isFirstOnCaptureComplete = true
when (config.api) {
CameraAPI.CAMERA2 -> initializeStillCapture(activity, params, config)
CameraAPI.CAMERAX -> cameraXTakePicture(activity, params, config)
else -> {}
}
}
}
}
/**
* A test has ended. Depending on which test and if we are at the beginning, middle or end of a
* repeated test, record the results and repeat/return,
*/
internal fun testEnded(activity: MainActivity, params: CameraParams?, config: TestConfig) {
if (null == params)
return
logd(
"In testEnded. multi_counter: " + multiCounter + " and test: " +
config.currentRunningTest.toString()
)
when (config.currentRunningTest) {
TestType.INIT -> {
params.timer.testEnd = System.currentTimeMillis()
logd("Test ended")
config.testResults.initialization.add(params.timer.openEnd - params.timer.openStart)
config.testResults.cameraClose
.add(params.timer.cameraCloseEnd - params.timer.cameraCloseStart)
config.testResults.total.add(params.timer.testEnd - params.timer.testStart)
}
TestType.PREVIEW -> {
params.timer.testEnd = System.currentTimeMillis()
logd("Test ended")
config.testResults.initialization.add(params.timer.openEnd - params.timer.openStart)
config.testResults.previewStart.add(params.timer.previewEnd - params.timer.previewStart)
config.testResults.previewClose
.add(params.timer.previewCloseEnd - params.timer.previewCloseStart)
config.testResults.cameraClose
.add(params.timer.cameraCloseEnd - params.timer.cameraCloseStart)
config.testResults.total.add(params.timer.testEnd - params.timer.testStart)
}
TestType.SWITCH_CAMERA -> {
params.timer.testEnd = System.currentTimeMillis()
logd("Test ended")
config.testResults.initialization.add(params.timer.openEnd - params.timer.openStart)
config.testResults.previewStart.add(params.timer.previewEnd - params.timer.previewStart)
config.testResults.switchToSecond
.add(params.timer.switchToSecondEnd - params.timer.switchToSecondStart)
config.testResults.switchToFirst
.add(params.timer.switchToFirstEnd - params.timer.switchToFirstStart)
config.testResults.previewClose
.add(params.timer.previewCloseEnd - params.timer.previewCloseStart)
config.testResults.cameraClose
.add(params.timer.cameraCloseEnd - params.timer.cameraCloseStart)
config.testResults.total.add(params.timer.testEnd - params.timer.testStart)
}
TestType.MULTI_SWITCH -> {
if (1 == multiCounter) {
params.timer.testEnd = System.currentTimeMillis()
config.testFinished = false // Reset flag
logd("Test ended")
activity.showProgressBar(true, precentageCompleted(activity, multiCounter))
config.testResults.initialization.add(params.timer.openEnd - params.timer.openStart)
config.testResults.previewStart
.add(params.timer.previewEnd - params.timer.previewStart)
config.testResults.switchToSecond
.add(params.timer.switchToSecondEnd - params.timer.switchToSecondStart)
config.testResults.switchToFirst
.add(params.timer.switchToFirstEnd - params.timer.switchToFirstStart)
config.testResults.previewClose
.add(params.timer.previewCloseEnd - params.timer.previewCloseStart)
config.testResults.cameraClose
.add(params.timer.cameraCloseEnd - params.timer.cameraCloseStart)
config.testResults.total.add(params.timer.testEnd - params.timer.testStart)
multiCounter = 0
} else {
logd(
"Switch " + (Math.abs(multiCounter - PrefHelper.getNumTests(activity)) + 1) +
" completed."
)
multiCounter--
runMultiSwitchTest(activity, params, config)
return
}
}
TestType.PHOTO -> {
params.timer.testEnd = System.currentTimeMillis()
logd("Test ended")
config.testResults.initialization.add(params.timer.openEnd - params.timer.openStart)
config.testResults.previewStart.add(params.timer.previewEnd - params.timer.previewStart)
config.testResults.previewFill
.add(params.timer.previewFillEnd - params.timer.previewFillStart)
config.testResults.autofocus
.add(params.timer.autofocusEnd - params.timer.autofocusStart)
config.testResults.captureNoAF
.add(
(params.timer.captureEnd - params.timer.captureStart) -
(params.timer.autofocusEnd - params.timer.autofocusStart)
)
config.testResults.capture.add(params.timer.captureEnd - params.timer.captureStart)
config.testResults.imageready
.add(params.timer.imageReaderEnd - params.timer.imageReaderStart)
config.testResults.capturePlusImageReady
.add(
(params.timer.captureEnd - params.timer.captureStart) +
(params.timer.imageReaderEnd - params.timer.imageReaderStart)
)
config.testResults.imagesave
.add(params.timer.imageSaveEnd - params.timer.imageSaveStart)
config.testResults.isHDRPlus
.add(params.timer.isHDRPlus)
config.testResults.previewClose
.add(params.timer.previewCloseEnd - params.timer.previewCloseStart)
config.testResults.cameraClose
.add(params.timer.cameraCloseEnd - params.timer.cameraCloseStart)
config.testResults.total.add(params.timer.testEnd - params.timer.testStart)
config.testResults.totalNoPreview.add(
(params.timer.testEnd - params.timer.testStart) -
(params.timer.previewFillEnd - params.timer.previewFillStart)
)
}
TestType.MULTI_PHOTO -> {
val lastResult = params.timer.captureEnd - params.timer.captureStart
if (1 == multiCounter) {
params.timer.testEnd = System.currentTimeMillis()
config.testFinished = false // Reset flag
logd("Test ended")
activity.showProgressBar(true, precentageCompleted(activity, multiCounter))
config.testResults.initialization.add(params.timer.openEnd - params.timer.openStart)
config.testResults.previewStart
.add(params.timer.previewEnd - params.timer.previewStart)
config.testResults.previewFill
.add(params.timer.previewFillEnd - params.timer.previewFillStart)
config.testResults.autofocus
.add(params.timer.autofocusEnd - params.timer.autofocusStart)
config.testResults.captureNoAF
.add(
(params.timer.captureEnd - params.timer.captureStart) -
(params.timer.autofocusEnd - params.timer.autofocusStart)
)
config.testResults.capture.add(params.timer.captureEnd - params.timer.captureStart)
config.testResults.imageready
.add(params.timer.imageReaderEnd - params.timer.imageReaderStart)
config.testResults.capturePlusImageReady
.add(
(params.timer.captureEnd - params.timer.captureStart) +
(params.timer.imageReaderEnd - params.timer.imageReaderStart)
)
config.testResults.imagesave
.add(params.timer.imageSaveEnd - params.timer.imageSaveStart)
config.testResults.isHDRPlus.add(params.timer.isHDRPlus)
config.testResults.previewClose
.add(params.timer.previewCloseEnd - params.timer.previewCloseStart)
config.testResults.cameraClose
.add(params.timer.cameraCloseEnd - params.timer.cameraCloseStart)
config.testResults.total.add(params.timer.testEnd - params.timer.testStart)
config.testResults.totalNoPreview
.add(
(params.timer.testEnd - params.timer.testStart) -
(params.timer.previewFillEnd - params.timer.previewFillStart)
)
multiCounter = 0
} else {
logd(
"Capture " + (Math.abs(multiCounter - PrefHelper.getNumTests(activity)) + 1) +
" completed: " + lastResult + "ms"
)
multiCounter--
runMultiPhotoTest(activity, params, config)
return
}
}
TestType.MULTI_PHOTO_CHAIN -> {
val lastResult = params.timer.captureEnd - params.timer.captureStart
if (1 == multiCounter) {
// If this is a chain test, the camera may still be open
if (params.isOpen) {
config.testFinished = true
closePreviewAndCamera(activity, params, config)
return
}
params.timer.testEnd = System.currentTimeMillis()
logd("Test ended")
config.testFinished = false // Reset flag
activity.showProgressBar(true, precentageCompleted(activity, multiCounter))
config.testResults.initialization.add(
params.timer.openEnd -
params.timer.openStart
)
config.testResults.previewStart.add(
params.timer.previewEnd -
params.timer.previewStart
)
config.testResults.previewFill.add(
params.timer.previewFillEnd -
params.timer.previewFillStart
)
config.testResults.autofocus.add(
params.timer.autofocusEnd -
params.timer.autofocusStart
)
config.testResults.captureNoAF
.add(
(params.timer.captureEnd - params.timer.captureStart) -
(params.timer.autofocusEnd - params.timer.autofocusStart)
)
config.testResults.capture.add(params.timer.captureEnd - params.timer.captureStart)
config.testResults.imageready.add(
params.timer.imageReaderEnd -
params.timer.imageReaderStart
)
config.testResults.capturePlusImageReady.add(
(
params.timer.captureEnd -
params.timer.captureStart
) +
(params.timer.imageReaderEnd - params.timer.imageReaderStart)
)
config.testResults.imagesave.add(
params.timer.imageSaveEnd -
params.timer.imageSaveStart
)
config.testResults.isHDRPlus.add(params.timer.isHDRPlus)
config.testResults.previewClose.add(
params.timer.previewCloseEnd -
params.timer.previewCloseStart
)
config.testResults.cameraClose.add(
params.timer.cameraCloseEnd -
params.timer.cameraCloseStart
)
config.testResults.total.add(params.timer.testEnd - params.timer.testStart)
config.testResults.totalNoPreview
.add(
(params.timer.testEnd - params.timer.testStart) -
(params.timer.previewFillEnd - params.timer.previewFillStart)
)
multiCounter = 0
} else {
logd(
"Capture " + (Math.abs(multiCounter - PrefHelper.getNumTests(activity)) + 1) +
" completed: " + lastResult + "ms"
)
multiCounter--
runMultiPhotoChainTest(activity, params, config)
return
}
}
TestType.NONE -> {}
}
multiCounter = 0
postTestResults(activity, config)
}
/**
* Calculate the percentage of repeated tests that are complete
*/
fun precentageCompleted(activity: MainActivity, testCounter: Int): Int {
return (100 * (PrefHelper.getNumTests(activity) - testCounter)) /
PrefHelper.getNumTests(activity)
}
/**
* Test is configured, begin it based on the API in the test config
*/
internal fun beginTest(activity: MainActivity, params: CameraParams?, testConfig: TestConfig) {
if (null == params)
return
when (testConfig.api) {
CameraAPI.CAMERA1 -> {
// Camera 1 doesn't have its own threading built-in
val runnable = Runnable {
camera1OpenCamera(activity, params, testConfig)
}
params.backgroundHandler?.post(runnable)
}
CameraAPI.CAMERA2 -> {
camera2OpenCamera(activity, params, testConfig)
}
CameraAPI.CAMERAX -> {
cameraXOpenCamera(activity, params, testConfig)
}
}
} | apache-2.0 | 89a4063b19795240f4cac8d506e89cd5 | 40.993789 | 100 | 0.628998 | 4.669832 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RestrictedRetentionForExpressionAnnotationFactory.kt | 1 | 5604 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
object RestrictedRetentionForExpressionAnnotationFactory : KotlinIntentionActionsFactory() {
private val sourceRetention = "${StandardNames.FqNames.annotationRetention.asString()}.${AnnotationRetention.SOURCE.name}"
private val sourceRetentionAnnotation = "@${StandardNames.FqNames.retention.asString()}($sourceRetention)"
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val annotationEntry = diagnostic.psiElement as? KtAnnotationEntry ?: return emptyList()
val containingClass = annotationEntry.containingClass() ?: return emptyList()
val retentionAnnotation = containingClass.annotation(StandardNames.FqNames.retention)
val targetAnnotation = containingClass.annotation(StandardNames.FqNames.target)
val expressionTargetArgument = if (targetAnnotation != null) findExpressionTargetArgument(targetAnnotation) else null
return listOfNotNull(
if (expressionTargetArgument != null) RemoveExpressionTargetFix(expressionTargetArgument) else null,
if (retentionAnnotation == null) AddSourceRetentionFix(containingClass) else ChangeRetentionToSourceFix(retentionAnnotation)
)
}
private fun KtClass.annotation(fqName: FqName): KtAnnotationEntry? {
return annotationEntries.firstOrNull {
it.typeReference?.text?.endsWith(fqName.shortName().asString()) == true
&& analyze()[BindingContext.TYPE, it.typeReference]?.constructor?.declarationDescriptor?.fqNameSafe == fqName
}
}
private fun findExpressionTargetArgument(targetAnnotation: KtAnnotationEntry): KtValueArgument? {
val valueArgumentList = targetAnnotation.valueArgumentList ?: return null
if (targetAnnotation.lambdaArguments.isNotEmpty()) return null
for (valueArgument in valueArgumentList.arguments) {
val argumentExpression = valueArgument.getArgumentExpression() ?: continue
if (argumentExpression.text.contains(KotlinTarget.EXPRESSION.toString())) {
return valueArgument
}
}
return null
}
private class AddSourceRetentionFix(element: KtClass) : KotlinQuickFixAction<KtClass>(element) {
override fun getText() = KotlinBundle.message("add.source.retention")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val added = element.addAnnotationEntry(KtPsiFactory(element).createAnnotationEntry(sourceRetentionAnnotation))
ShortenReferences.DEFAULT.process(added)
}
}
private class ChangeRetentionToSourceFix(retentionAnnotation: KtAnnotationEntry) :
KotlinQuickFixAction<KtAnnotationEntry>(retentionAnnotation) {
override fun getText() = KotlinBundle.message("change.existent.retention.to.source")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val retentionAnnotation = element ?: return
val psiFactory = KtPsiFactory(retentionAnnotation)
val added = if (retentionAnnotation.valueArgumentList == null) {
retentionAnnotation.add(psiFactory.createCallArguments("($sourceRetention)")) as KtValueArgumentList
} else {
if (retentionAnnotation.valueArguments.isNotEmpty()) {
retentionAnnotation.valueArgumentList?.removeArgument(0)
}
retentionAnnotation.valueArgumentList?.addArgument(psiFactory.createArgument(sourceRetention))
}
if (added != null) {
ShortenReferences.DEFAULT.process(added)
}
}
}
private class RemoveExpressionTargetFix(expressionTargetArgument: KtValueArgument) :
KotlinQuickFixAction<KtValueArgument>(expressionTargetArgument) {
override fun getText() = KotlinBundle.message("remove.expression.target")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val expressionTargetArgument = element ?: return
val argumentList = expressionTargetArgument.parent as? KtValueArgumentList ?: return
if (argumentList.arguments.size == 1) {
val annotation = argumentList.parent as? KtAnnotationEntry ?: return
annotation.delete()
} else {
argumentList.removeArgument(expressionTargetArgument)
}
}
}
}
| apache-2.0 | 7cba1bf8120148d210aa4652d7fb38b4 | 47.730435 | 136 | 0.723233 | 5.649194 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeTypeFix.kt | 3 | 2953 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.types.KotlinType
class ChangeTypeFix(element: KtTypeReference, private val type: KotlinType) : KotlinQuickFixAction<KtTypeReference>(element) {
override fun getFamilyName() = KotlinBundle.message("fix.change.type.family")
override fun getText(): String {
val currentTypeText = element?.text ?: return ""
return KotlinBundle.message(
"fix.change.type.text",
currentTypeText, renderTypeWithFqNameOnClash(type, currentTypeText)
)
}
private fun renderTypeWithFqNameOnClash(type: KotlinType, nameToCheckAgainst: String?): String {
val fqNameToCheckAgainst = FqName(nameToCheckAgainst!!)
val typeClassifierDescriptor = type.constructor.declarationDescriptor
val typeFqName = typeClassifierDescriptor?.let(DescriptorUtils::getFqNameSafe) ?: fqNameToCheckAgainst
val renderer = when {
typeFqName.shortName() == fqNameToCheckAgainst.shortName() -> IdeDescriptorRenderers.SOURCE_CODE
else -> IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS
}
return renderer.renderType(type)
}
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val newTypeRef = element.replaced(KtPsiFactory(file).createType(IdeDescriptorRenderers.SOURCE_CODE.renderType(type)))
ShortenReferences.DEFAULT.process(newTypeRef)
}
companion object : KotlinSingleIntentionActionFactoryWithDelegate<KtTypeReference, KotlinType>() {
override fun getElementOfInterest(diagnostic: Diagnostic) =
Errors.EXPECTED_PARAMETER_TYPE_MISMATCH.cast(diagnostic).psiElement.typeReference
override fun extractFixData(element: KtTypeReference, diagnostic: Diagnostic) =
Errors.EXPECTED_PARAMETER_TYPE_MISMATCH.cast(diagnostic).a
override fun createFix(originalElement: KtTypeReference, data: KotlinType) =
ChangeTypeFix(originalElement, data)
}
}
| apache-2.0 | 06d8f451201b03041a97f6c05052c628 | 49.050847 | 158 | 0.765662 | 4.872937 | false | false | false | false |
siosio/intellij-community | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/FUSEventSource.kt | 1 | 3032 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.updateSettings.impl.pluginsAdvertisement
import com.intellij.ide.BrowserUtil
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.openapi.application.IdeUrlTrackingParametersProvider
import com.intellij.openapi.project.Project
import java.util.Locale.ROOT
private const val FUS_GROUP_ID = "plugins.advertiser"
private val GROUP = EventLogGroup(
FUS_GROUP_ID,
1,
)
private val SOURCE_FIELD = EventFields.Enum(
"source",
FUSEventSource::class.java,
) { it.name.toLowerCase(ROOT) }
private val CONFIGURE_PLUGINS_EVENT = GROUP.registerEvent(
"configure.plugins",
SOURCE_FIELD,
)
private val PLUGINS_FIELD = EventFields.StringListValidatedByCustomRule(
"plugins",
"plugin",
)
private val ENABLE_PLUGINS_EVENT = GROUP.registerEvent(
"enable.plugins",
PLUGINS_FIELD,
SOURCE_FIELD,
)
private val INSTALL_PLUGINS_EVENT = GROUP.registerEvent(
"install.plugins",
PLUGINS_FIELD,
SOURCE_FIELD,
)
private val IGNORE_ULTIMATE_EVENT = GROUP.registerEvent(
"ignore.ultimate",
SOURCE_FIELD,
)
private val OPEN_DOWNLOAD_PAGE_EVENT = GROUP.registerEvent(
"open.download.page",
SOURCE_FIELD,
)
private val LEARN_MORE_EVENT = GROUP.registerEvent(
"learn.more",
SOURCE_FIELD,
)
private val IGNORE_EXTENSIONS_EVENT = GROUP.registerEvent(
"ignore.extensions",
SOURCE_FIELD,
)
private val IGNORE_UNKNOWN_FEATURES_EVENT = GROUP.registerEvent(
"ignore.unknown.features",
SOURCE_FIELD,
)
enum class FUSEventSource {
EDITOR,
NOTIFICATION;
fun doIgnoreUltimateAndLog(project: Project? = null) {
isIgnoreIdeSuggestion = true
IGNORE_ULTIMATE_EVENT.log(project, this)
}
@JvmOverloads
fun logConfigurePlugins(project: Project? = null) = CONFIGURE_PLUGINS_EVENT.log(project, this)
@JvmOverloads
fun logEnablePlugins(
plugins: List<String>,
project: Project? = null,
) = ENABLE_PLUGINS_EVENT.log(project, plugins, this)
@JvmOverloads
fun logInstallPlugins(
plugins: List<String>,
project: Project? = null,
) = INSTALL_PLUGINS_EVENT.log(project, plugins, this)
@JvmOverloads
fun openDownloadPageAndLog(project: Project? = null, url: String) {
BrowserUtil.browse(IdeUrlTrackingParametersProvider.getInstance().augmentUrl(url))
OPEN_DOWNLOAD_PAGE_EVENT.log(project, this)
}
@JvmOverloads
fun learnMoreAndLog(project: Project? = null) {
BrowserUtil.browse(IdeUrlTrackingParametersProvider.getInstance().augmentUrl("https://www.jetbrains.com/products.html#type=ide"))
LEARN_MORE_EVENT.log(project, this)
}
@JvmOverloads
fun logIgnoreExtension(project: Project? = null) = IGNORE_EXTENSIONS_EVENT.log(project, this)
@JvmOverloads
fun logIgnoreUnknownFeatures(project: Project? = null) = IGNORE_UNKNOWN_FEATURES_EVENT.log(project, this)
}
| apache-2.0 | 45616d63b437247f3413723039cb64ea | 26.315315 | 158 | 0.758245 | 3.785268 | false | false | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/settings/InlayHintsSettingsSearchableContributor.kt | 3 | 1537 | // 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.codeInsight.hints.settings
import com.intellij.codeInsight.hints.*
import com.intellij.codeInsight.hints.settings.language.SingleLanguageInlayHintsConfigurable
import com.intellij.ide.ui.search.SearchableOptionContributor
import com.intellij.ide.ui.search.SearchableOptionProcessor
private class InlayHintsSettingsSearchableContributor : SearchableOptionContributor() {
override fun processOptions(processor: SearchableOptionProcessor) {
for (providerInfo in InlayHintsProviderFactory.EP.extensions().flatMap { it.getProvidersInfo().stream() }) {
val provider = providerInfo.provider
val name = provider.name
val id = SingleLanguageInlayHintsConfigurable.getId(providerInfo.language)
addOption(processor, name, id)
val providerWithSettings = provider.withSettings(providerInfo.language, InlayHintsSettings.instance())
for (case in providerWithSettings.configurable.cases) {
addOption(processor, case.name, id)
}
}
InlayParameterHintsExtension.point?.extensions?.flatMap { it.instance.supportedOptions }?.forEach { addOption(processor, it.name, null) }
}
private fun addOption(processor: SearchableOptionProcessor, name: String, id: String?) {
if (id != null) {
processor.addOptions(name, null, null, id, null, false)
}
processor.addOptions(name, null, null, INLAY_ID, null, false)
}
} | apache-2.0 | fd8baa01cb1b26b71003678006a748e6 | 50.266667 | 141 | 0.767729 | 4.520588 | false | true | false | false |
BijoySingh/Quick-Note-Android | base/src/main/java/com/maubis/scarlet/base/core/format/MarkdownType.kt | 1 | 684 | package com.maubis.scarlet.base.core.format
enum class MarkdownType(val startToken: String, val endToken: String = "", val requiresNewLine: Boolean = false) {
BOLD(startToken = "**", endToken = "**"),
UNDERLINE(startToken = "_", endToken = "_"),
ITALICS(startToken = "*", endToken = "*"),
HEADER(startToken = "# ", requiresNewLine = true),
SUB_HEADER(startToken = "## ", requiresNewLine = true),
UNORDERED(startToken = "- ", requiresNewLine = true),
CHECKLIST_UNCHECKED(startToken = "[ ] ", requiresNewLine = true),
CODE(startToken = "`", endToken = "`"),
CODE_BLOCK(startToken = "```\n", endToken = "\n```"),
STRIKE_THROUGH(startToken = "~~", endToken = "~~"),
} | gpl-3.0 | 27c2474bc10b7bf0b915900074cbfcf3 | 47.928571 | 114 | 0.640351 | 3.5625 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-model/src/org/jetbrains/kotlin/idea/projectModel/KotlinPlatformContainer.kt | 5 | 1909 | // 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.projectModel
import java.io.Serializable
interface KotlinPlatformContainer : Serializable, Iterable<KotlinPlatform> {
/**
* Distinct collection of Platforms.
* Keeping 'Collection' as type for binary compatibility
*/
val platforms: Collection<KotlinPlatform>
val arePlatformsInitialized: Boolean
@Deprecated(
"Ambiguous semantics of 'supports' for COMMON or (ANDROID/JVM) platforms. Use 'platforms' directly to express clear intention",
level = DeprecationLevel.ERROR
)
fun supports(simplePlatform: KotlinPlatform): Boolean
@Deprecated(
"Unclear semantics: Use 'platforms' directly to express intention",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith("platforms.singleOrNull() ?: KotlinPlatform.COMMON")
)
fun getSinglePlatform() = platforms.singleOrNull() ?: KotlinPlatform.COMMON
@Deprecated(
"Unclear semantics: Use 'pushPlatform' instead",
ReplaceWith("pushPlatform"),
level = DeprecationLevel.ERROR
)
fun addSimplePlatforms(platforms: Collection<KotlinPlatform>) = pushPlatforms(platforms)
/**
* Adds the given [platforms] to this container.
* Note: If any of the pushed [platforms] is common, then this container will drop all non-common platforms and subsequent invocations
* to this function will have no further effect.
*/
fun pushPlatforms(platforms: Iterable<KotlinPlatform>)
/**
* @see pushPlatforms
*/
fun pushPlatforms(vararg platform: KotlinPlatform) {
pushPlatforms(platform.toList())
}
override fun iterator(): Iterator<KotlinPlatform> {
return platforms.toSet().iterator()
}
}
| apache-2.0 | 0f381d17030fb35307f00f3ea38ab3b9 | 36.431373 | 158 | 0.707177 | 4.997382 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/rebase/conflict/GitRebaseMergeDialogCustomizer.kt | 4 | 4774 | // 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 git4idea.rebase.conflict
import com.intellij.diff.DiffEditorTitleCustomizer
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.history.VcsRevisionNumber
import com.intellij.openapi.vcs.merge.MergeDialogCustomizer
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.log.Hash
import com.intellij.vcs.log.impl.HashImpl
import com.intellij.vcs.log.util.VcsLogUtil
import git4idea.GitRevisionNumber
import git4idea.GitUtil
import git4idea.history.GitHistoryUtils
import git4idea.i18n.GitBundleExtensions.html
import git4idea.merge.*
import git4idea.rebase.GitRebaseSpec
import git4idea.repo.GitRepository
private val LOG = logger<GitRebaseMergeDialogCustomizer>()
internal fun createRebaseDialogCustomizer(repository: GitRepository, rebaseSpec: GitRebaseSpec): MergeDialogCustomizer {
val rebaseParams = rebaseSpec.params
if (rebaseParams == null) {
return GitDefaultMergeDialogCustomizer(repository.project)
}
val currentBranchAtTheStartOfRebase = rebaseSpec.initialBranchNames[repository]
// check that upstream is HEAD to overcome a hack: passing HEAD into `git rebase HEAD branch`
// to avoid passing branch names for different repositories
val upstream = rebaseParams.upstream.takeIf { it != GitUtil.HEAD } ?: currentBranchAtTheStartOfRebase
val branch = rebaseParams.branch ?: currentBranchAtTheStartOfRebase
if (upstream == null || branch == null) {
return GitDefaultMergeDialogCustomizer(repository.project)
}
val rebaseHead = try {
HashImpl.build(GitRevisionNumber.resolve(repository.project, repository.root, GitUtil.REBASE_HEAD).asString())
}
catch (e: VcsException) {
LOG.warn(e)
null
}
val mergeBase = try {
GitHistoryUtils.getMergeBase(repository.project, repository.root, upstream, branch)?.let {
HashImpl.build(it.rev)
}
}
catch (e: VcsException) {
LOG.warn(e)
null
}
return GitRebaseMergeDialogCustomizer(repository, upstream, branch, rebaseHead, mergeBase)
}
private class GitRebaseMergeDialogCustomizer(
private val repository: GitRepository,
upstream: String,
@NlsSafe private val rebasingBranch: String,
private val ingoingCommit: Hash?,
private val mergeBase: Hash?
) : MergeDialogCustomizer() {
private val baseHash: Hash?
@NlsSafe
private val basePresentable: String?
@NlsSafe
private val baseBranch: String?
init {
if (upstream.matches("[a-fA-F0-9]{40}".toRegex())) {
basePresentable = VcsLogUtil.getShortHash(upstream)
baseBranch = null
baseHash = HashImpl.build(upstream)
}
else {
basePresentable = upstream
baseBranch = upstream
baseHash = null
}
}
override fun getMultipleFileMergeDescription(files: MutableCollection<VirtualFile>) = getDescriptionForRebase(rebasingBranch, baseBranch, baseHash)
override fun getLeftPanelTitle(file: VirtualFile) = getDefaultLeftPanelTitleForBranch(rebasingBranch)
override fun getRightPanelTitle(file: VirtualFile, revisionNumber: VcsRevisionNumber?): String {
val hash = if (revisionNumber != null) HashImpl.build(revisionNumber.asString()) else baseHash
return getDefaultRightPanelTitleForBranch(baseBranch, hash)
}
override fun getColumnNames() = listOf(
GitMergeProvider.calcColumnName(false, rebasingBranch),
GitMergeProvider.calcColumnName(true, basePresentable)
)
override fun getTitleCustomizerList(file: FilePath) = DiffEditorTitleCustomizerList(
getLeftTitleCustomizer(file),
null,
getRightTitleCustomizer(file)
)
private fun getLeftTitleCustomizer(file: FilePath): DiffEditorTitleCustomizer? {
if (ingoingCommit == null) {
return null
}
return getTitleWithCommitDetailsCustomizer(
html(
"rebase.conflict.diff.dialog.left.title",
ingoingCommit.toShortString(),
HtmlChunk.text(rebasingBranch).bold()
),
repository,
file,
ingoingCommit.asString()
)
}
private fun getRightTitleCustomizer(file: FilePath): DiffEditorTitleCustomizer? {
if (mergeBase == null) {
return null
}
val title = if (baseBranch != null) {
html("rebase.conflict.diff.dialog.right.with.branch.title", HtmlChunk.text(baseBranch).bold())
}
else {
html("rebase.conflict.diff.dialog.right.simple.title")
}
return getTitleWithCommitsRangeDetailsCustomizer(title, repository, file, Pair(mergeBase.asString(), GitUtil.HEAD))
}
}
| apache-2.0 | 96771cfab1e8429247084cc4e2135cf5 | 33.1 | 149 | 0.757855 | 4.404059 | false | false | false | false |
smmribeiro/intellij-community | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/runToolbar/RunToolbarXDebuggerAction.kt | 8 | 2178 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.xdebugger.impl.runToolbar
import com.intellij.execution.runToolbar.RTBarAction
import com.intellij.execution.runToolbar.RunToolbarMainSlotState
import com.intellij.execution.runToolbar.RunToolbarProcess
import com.intellij.execution.runToolbar.mainState
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ShortcutSet
import com.intellij.xdebugger.impl.DebuggerSupport
import com.intellij.xdebugger.impl.actions.DebuggerActionHandler
import com.intellij.xdebugger.impl.actions.XDebuggerActionBase
import com.intellij.xdebugger.impl.actions.handlers.RunToolbarPauseActionHandler
import com.intellij.xdebugger.impl.actions.handlers.RunToolbarResumeActionHandler
abstract class RunToolbarXDebuggerAction : XDebuggerActionBase(false), RTBarAction {
override fun checkMainSlotVisibility(state: RunToolbarMainSlotState): Boolean {
return state == RunToolbarMainSlotState.PROCESS
}
override fun getRightSideType(): RTBarAction.Type = RTBarAction.Type.RIGHT_FLEXIBLE
override fun update(e: AnActionEvent) {
super.update(e)
if (!RunToolbarProcess.isExperimentalUpdatingEnabled) {
e.mainState()?.let {
e.presentation.isEnabledAndVisible = e.presentation.isEnabledAndVisible && checkMainSlotVisibility(it)
}
}
}
override fun setShortcutSet(shortcutSet: ShortcutSet) {}
}
open class RunToolbarPauseAction : RunToolbarXDebuggerAction() {
private val handler = RunToolbarPauseActionHandler()
override fun getHandler(debuggerSupport: DebuggerSupport): DebuggerActionHandler {
return handler
}
init {
templatePresentation.icon = AllIcons.Actions.Pause
}
}
open class RunToolbarResumeAction : RunToolbarXDebuggerAction() {
private val handler = RunToolbarResumeActionHandler()
override fun getHandler(debuggerSupport: DebuggerSupport): DebuggerActionHandler {
return handler
}
init {
templatePresentation.icon = AllIcons.Actions.Resume
}
}
| apache-2.0 | 2e6fbb07ecdc00ea3abf00abc05cd9f9 | 35.915254 | 158 | 0.808999 | 4.905405 | false | false | false | false |
kerubistan/kerub | src/test/kotlin/com/github/kerubistan/kerub/host/HostCapabilitiesDiscovererImplTest.kt | 2 | 2800 | package com.github.kerubistan.kerub.host
import com.github.kerubistan.kerub.host.distros.Distribution
import com.github.kerubistan.kerub.model.FsStorageCapability
import com.github.kerubistan.kerub.model.SoftwarePackage
import com.github.kerubistan.kerub.model.Version
import com.github.kerubistan.kerub.model.controller.config.ControllerConfig
import com.github.kerubistan.kerub.model.controller.config.StorageTechnologiesConfig
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import io.github.kerubistan.kroki.size.GB
import org.apache.sshd.client.session.ClientSession
import org.junit.Test
import java.util.UUID
import kotlin.test.assertTrue
class HostCapabilitiesDiscovererImplTest {
@Test
fun detectAndBenchmark() {
assertTrue("just the storage capabilities unchanged if the benchmarks are disabled") {
val session = mock<ClientSession>()
val distro = mock<Distribution>()
val distribution = SoftwarePackage(name = "CentOS Linux", version = Version.fromVersionString("7.8"))
val config = ControllerConfig(
storageTechnologies = StorageTechnologiesConfig(
storageBenchmarkingEnabled = false
)
)
val packages = listOf<SoftwarePackage>()
val capability = FsStorageCapability(
id = UUID.randomUUID(),
size = 5.GB,
fsType = "ext4",
mountPoint = "/kerub")
whenever(distro.detectStorageCapabilities(eq(session), eq(distribution), eq(packages)))
.thenReturn(listOf(capability))
HostCapabilitiesDiscovererImpl
.detectAndBenchmark(distro, session, distribution, packages, config) == listOf(capability)
}
assertTrue("the storage capabilities with benchmark data if the benchmarks are enabled") {
val session = mock<ClientSession>()
val distro = mock<Distribution>()
val distribution = SoftwarePackage(name = "CentOS Linux", version = Version.fromVersionString("7.8"))
val config = ControllerConfig(
storageTechnologies = StorageTechnologiesConfig(
storageBenchmarkingEnabled = true
)
)
val packages = listOf<SoftwarePackage>()
val capability = FsStorageCapability(
id = UUID.randomUUID(),
size = 5.GB,
fsType = "ext4",
mountPoint = "/kerub")
whenever(distro.detectStorageCapabilities(eq(session), eq(distribution), eq(packages)))
.thenReturn(listOf(capability))
val updatedCapability = capability.copy(performanceInfo = "TEST DONE")
whenever(distro.storageBenchmark(
eq(session),
eq(capability),
eq(distribution),
eq(packages),
eq(config.storageTechnologies))
).thenReturn(updatedCapability)
HostCapabilitiesDiscovererImpl
.detectAndBenchmark(distro, session, distribution, packages, config) == listOf(updatedCapability)
}
}
} | apache-2.0 | f777518228a17934a83296a286c1f2d9 | 34.0125 | 104 | 0.753571 | 4.123711 | false | true | false | false |
deltadak/plep | src/main/kotlin/nl/deltadak/plep/ui/settingspane/spinners/NumberOfColumnsSpinner.kt | 1 | 1081 | package nl.deltadak.plep.ui.settingspane.spinners
import javafx.scene.control.Spinner
import javafx.scene.control.SpinnerValueFactory
import javafx.scene.layout.GridPane
import nl.deltadak.plep.database.settingsdefaults.SettingsDefaults
import nl.deltadak.plep.database.tables.Settings
import nl.deltadak.plep.ui.settingspane.SPINNER_WIDTH
/**
* This spinner allows the user to select the number of columns that the main GridPane should show.
*/
class NumberOfColumnsSpinner {
/**
* Construct a new spinner.
*/
fun getNew(): Spinner<Int> {
val spinner = Spinner<Int>()
// Get initial value from database
val initialNumberOfColumns = Settings.get(SettingsDefaults.MAX_COLUMNS)
spinner.valueFactory = SpinnerValueFactory.IntegerSpinnerValueFactory(1, 14, initialNumberOfColumns.toInt())
spinner.id = "maxColumnsSpinner"
spinner.prefWidth = SPINNER_WIDTH // TODO Check width for double digits
GridPane.setColumnIndex(spinner, 2)
GridPane.setRowIndex(spinner, 2)
return spinner
}
} | mit | 0e097efe88890afa60a83695b1b5d4b6 | 30.823529 | 116 | 0.73728 | 4.324 | false | false | false | false |
blastrock/kaqui | app/src/main/java/org/kaqui/model/LearningDbView.kt | 1 | 10179 | package org.kaqui.model
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import org.kaqui.SrsCalculator
import java.util.*
class LearningDbView(
private val database: SQLiteDatabase,
private val tableName: String,
private val knowledgeType: KnowledgeType?,
private val filter: String = "1",
private val classifier: Classifier? = null,
private val itemGetter: (id: Int, knowledgeType: KnowledgeType?) -> Item,
private val itemSearcher: ((text: String) -> List<Int>)? = null) {
var sessionId: Long? = null
fun withClassifier(classifier: Classifier) =
LearningDbView(database, tableName, knowledgeType, filter, classifier, itemGetter, itemSearcher)
fun getItem(id: Int): Item = itemGetter(id, knowledgeType)
fun search(text: String): List<Int> = itemSearcher!!(text)
fun getAllItems(): List<Int> =
if (classifier != null)
getItemsForLevel(classifier)
else
getAllItemsForAnyLevel()
private fun getAllItemsForAnyLevel(): List<Int> {
val ret = mutableListOf<Int>()
database.query(tableName, arrayOf("id"), filter, null, null, null, classifier?.orderColumn()).use { cursor ->
while (cursor.moveToNext()) {
ret.add(cursor.getInt(0))
}
}
return ret
}
private fun getItemsForLevel(classifier: Classifier): List<Int> {
val ret = mutableListOf<Int>()
database.query(tableName, arrayOf("id"), "$filter AND " + classifier.whereClause(), classifier.whereArguments(), null, null, classifier.orderColumn()).use { cursor ->
while (cursor.moveToNext()) {
ret.add(cursor.getInt(0))
}
}
return ret
}
fun setAllEnabled(enabled: Boolean) =
if (classifier != null)
setLevelEnabled(classifier, enabled)
else
setAllAnyLevelEnabled(enabled)
private fun setAllAnyLevelEnabled(enabled: Boolean) {
val cv = ContentValues()
cv.put("enabled", if (enabled) 1 else 0)
database.update(tableName, cv, filter, null)
}
private fun setLevelEnabled(classifier: Classifier, enabled: Boolean) {
val cv = ContentValues()
cv.put("enabled", if (enabled) 1 else 0)
database.update(tableName, cv, "$filter AND " + classifier.whereClause(), classifier.whereArguments())
}
fun setItemEnabled(itemId: Int, enabled: Boolean) {
val cv = ContentValues()
cv.put("enabled", if (enabled) 1 else 0)
database.update(tableName, cv, "id = ?", arrayOf(itemId.toString()))
}
fun isItemEnabled(id: Int): Boolean {
database.query(tableName, arrayOf("enabled"), "id = ?", arrayOf(id.toString()), null, null, null).use { cursor ->
cursor.moveToFirst()
return cursor.getInt(0) != 0
}
}
fun getEnabledItemsAndScores(): List<SrsCalculator.ProbabilityData> {
database.rawQuery("""
SELECT $tableName.id, ifnull(s.short_score, 0.0), ifnull(s.long_score, 0.0), ifnull(s.last_correct, 0)
FROM $tableName
LEFT JOIN ${Database.ITEM_SCORES_TABLE_NAME} s ON $tableName.id = s.id AND s.type = ${knowledgeType!!.value}
WHERE $filter AND $tableName.enabled = 1
""", null).use { cursor ->
val ret = mutableListOf<SrsCalculator.ProbabilityData>()
while (cursor.moveToNext()) {
ret.add(SrsCalculator.ProbabilityData(cursor.getInt(0), cursor.getDouble(1), 0.0, cursor.getDouble(2), 0.0, cursor.getLong(3), 0.0, 0.0))
}
return ret
}
}
fun getMinLastAsked(): Int = getLastAskedFrom(0)
private fun getLastAskedFrom(from: Int): Int {
// I couldn't find how sqlite handles null values in order by, so I use ifnull there too
database.rawQuery("""
SELECT s.last_correct
FROM $tableName
LEFT JOIN ${Database.ITEM_SCORES_TABLE_NAME} s ON $tableName.id = s.id AND s.type = ${knowledgeType!!.value}
WHERE $filter AND $tableName.enabled = 1 AND s.last_correct IS NOT NULL
ORDER BY s.last_correct ASC
LIMIT $from, 1
""", null).use { cursor ->
return if (cursor.moveToFirst())
cursor.getInt(0)
else
0
}
}
fun getEnabledCount(): Int {
database.query(tableName, arrayOf("COUNT(*)"), "$filter AND enabled = 1", null, null, null, null).use { cursor ->
cursor.moveToFirst()
return cursor.getInt(0)
}
}
fun applyScoreUpdate(scoreUpdate: SrsCalculator.ScoreUpdate) {
val cv = ContentValues()
cv.put("id", scoreUpdate.itemId)
cv.put("type", knowledgeType!!.value)
cv.put("short_score", scoreUpdate.shortScore)
cv.put("long_score", scoreUpdate.longScore)
cv.put("last_correct", scoreUpdate.lastAsked)
database.insertWithOnConflict(Database.ITEM_SCORES_TABLE_NAME, null, cv, SQLiteDatabase.CONFLICT_REPLACE)
}
fun logTestItem(testType: TestType, scoreUpdate: SrsCalculator.ScoreUpdate, certainty: Certainty, wrongAnswer: Int?) {
val cv = ContentValues()
cv.put("id_session", sessionId!!)
cv.put("test_type", testType.value)
cv.put("id_item_question", scoreUpdate.itemId)
if (wrongAnswer != null)
cv.put("id_item_wrong", wrongAnswer)
cv.put("certainty", certainty.value)
cv.put("time", Calendar.getInstance().timeInMillis / 1000)
database.insertOrThrow(Database.SESSION_ITEMS_TABLE_NAME, null, cv)
}
data class LongStats(val bad: Int, val meh: Int, val good: Int, val longScoreSum: Float, val longPartition: List<Int>)
fun getLongStats(knowledgeType: KnowledgeType): LongStats {
database.rawQuery("""
SELECT
SUM(case when short_score BETWEEN 0.0 AND $BAD_WEIGHT then 1 else 0 end),
SUM(case when short_score BETWEEN $BAD_WEIGHT AND $GOOD_WEIGHT then 1 else 0 end),
SUM(case when short_score BETWEEN $GOOD_WEIGHT AND 1.0 then 1 else 0 end),
SUM(long_score),
SUM(case when long_score BETWEEN 0.0 AND 0.2 then 1 else 0 end),
SUM(case when long_score BETWEEN 0.2 AND 0.4 then 1 else 0 end),
SUM(case when long_score BETWEEN 0.4 AND 0.6 then 1 else 0 end),
SUM(case when long_score BETWEEN 0.6 AND 0.8 then 1 else 0 end),
SUM(case when long_score BETWEEN 0.8 AND 1.0 then 1 else 0 end)
FROM (
SELECT
MAX(ifnull(s.short_score, 0.0)) as short_score,
MAX(ifnull(s.long_score, 0.0)) as long_score
FROM $tableName
LEFT JOIN ${Database.ITEM_SCORES_TABLE_NAME} s
ON $tableName.id = s.id AND s.type = ${knowledgeType.value}
WHERE $filter AND s.long_score > 0.0
GROUP BY $tableName.id
)
""", arrayOf()).use { cursor ->
cursor.moveToNext()
return LongStats(
cursor.getInt(0),
cursor.getInt(1),
cursor.getInt(2),
cursor.getFloat(3),
(4..8).map { cursor.getInt(it) }.toList())
}
}
data class Stats(val bad: Int, val meh: Int, val good: Int, val disabled: Int)
fun getStats(): Stats {
val stats = getCountsForEnabled(classifier, knowledgeType)
val disabledCount = getDisabledCount(classifier)
return Stats(stats.first, stats.second, stats.third, disabledCount)
}
private fun getCountsForEnabled(classifier: Classifier?, knowledgeType: KnowledgeType?): Triple<Int, Int, Int> {
val andWhereClause =
if (classifier != null)
" AND " + classifier.whereClause()
else
""
val joinFiterAndClause =
if (knowledgeType != null)
" AND s.type = ${knowledgeType.value}"
else
""
val selectionArgsBase = arrayOf<String>()
val selectionArgs =
if (classifier != null)
selectionArgsBase + classifier.whereArguments()
else
selectionArgsBase
database.rawQuery("""
SELECT
SUM(case when stats_score BETWEEN 0.0 AND $BAD_WEIGHT then 1 else 0 end),
SUM(case when stats_score BETWEEN $BAD_WEIGHT AND $GOOD_WEIGHT then 1 else 0 end),
SUM(case when stats_score BETWEEN $GOOD_WEIGHT AND 1.0 then 1 else 0 end)
FROM (
SELECT MAX(ifnull(s.short_score, 0.0)) as stats_score
FROM $tableName
LEFT JOIN ${Database.ITEM_SCORES_TABLE_NAME} s
ON $tableName.id = s.id
$joinFiterAndClause
WHERE $filter
AND $tableName.enabled = 1
$andWhereClause
GROUP BY $tableName.id
)
""", selectionArgs).use { cursor ->
cursor.moveToNext()
return Triple(cursor.getInt(0), cursor.getInt(1), cursor.getInt(2))
}
}
private fun getDisabledCount(classifier: Classifier?): Int {
val selection = "$filter AND enabled = 0" +
if (classifier != null)
" AND " + classifier.whereClause()
else
""
val selectionArgsBase = arrayOf<String>()
val selectionArgs =
if (classifier != null)
selectionArgsBase + classifier.whereArguments()
else
selectionArgsBase
database.query(tableName, arrayOf("COUNT(*)"), selection, selectionArgs, null, null, null).use { cursor ->
cursor.moveToNext()
return cursor.getInt(0)
}
}
}
| mit | 3c5ba33c9f2171b62a5b834501b73b25 | 40.044355 | 174 | 0.575695 | 4.429504 | false | false | false | false |
square/sqldelight | sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/lang/SqlDelightFoldingBuilder.kt | 1 | 5333 | /*
* Copyright (C) 2017 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.sqldelight.intellij.lang
import com.alecstrong.sql.psi.core.psi.SqlCreateIndexStmt
import com.alecstrong.sql.psi.core.psi.SqlCreateTriggerStmt
import com.alecstrong.sql.psi.core.psi.SqlCreateViewStmt
import com.alecstrong.sql.psi.core.psi.SqlTypes
import com.intellij.lang.ASTNode
import com.intellij.lang.folding.FoldingBuilder
import com.intellij.lang.folding.FoldingDescriptor
import com.intellij.openapi.editor.Document
import com.intellij.openapi.project.DumbAware
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.squareup.sqldelight.core.psi.SqlDelightStmtIdentifier
import com.squareup.sqldelight.core.psi.SqldelightTypes
import com.squareup.sqldelight.intellij.util.prevSiblingOfType
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
class SqlDelightFoldingBuilder : FoldingBuilder, DumbAware {
override fun buildFoldRegions(root: ASTNode, document: Document) =
root.createFoldingDescriptors()
private fun ASTNode.createFoldingDescriptors(): Array<FoldingDescriptor> {
return getChildren(null)
.filter { it.elementType == SqldelightTypes.STMT_LIST }
.flatMap {
val descriptors = mutableListOf<FoldingDescriptor>()
val statements = it.getChildren(null).toList()
for (statement in statements) {
when (statement.elementType) {
SqldelightTypes.IMPORT_STMT_LIST ->
statement.psi.toImportListDescriptor()?.let(descriptors::add)
SqlTypes.STMT -> {
val psi = statement.psi
val sqlStatement = statement.firstChildNode
when (sqlStatement?.elementType) {
SqlTypes.CREATE_TABLE_STMT ->
psi.toCreateTableDescriptor(sqlStatement?.psi)?.let(descriptors::add)
SqlTypes.CREATE_VIEW_STMT ->
psi.toCreateViewDescriptor(sqlStatement?.psi)?.let(descriptors::add)
SqlTypes.CREATE_TRIGGER_STMT ->
psi.toCreateTriggerDescriptor(sqlStatement?.psi)?.let(descriptors::add)
SqlTypes.CREATE_INDEX_STMT ->
psi.toCreateIndexDescriptor(sqlStatement?.psi)?.let(descriptors::add)
}
val stmtIdentifier = psi.prevSiblingOfType<SqlDelightStmtIdentifier>()
if (stmtIdentifier?.identifier() != null) {
psi.toStatementDescriptor(stmtIdentifier)?.let(descriptors::add)
}
}
}
}
return@flatMap descriptors
}
.toTypedArray()
}
private fun PsiElement.toCreateTableDescriptor(createTableStmt: PsiElement?): FoldingDescriptor? {
val openingBraceElement = createTableStmt?.node?.findChildByType(SqlTypes.LP) ?: return null
val start = openingBraceElement.startOffset
val end = nextSibling.endOffset
if (start >= end) return null
return FoldingDescriptor(this, start, end, null, "(...);")
}
private fun PsiElement.toCreateViewDescriptor(createViewStmt: PsiElement?): FoldingDescriptor? {
val viewNameElement = (createViewStmt as? SqlCreateViewStmt)?.viewName ?: return null
return toStatementDescriptor(viewNameElement)
}
private fun PsiElement.toCreateTriggerDescriptor(
createTriggerStmt: PsiElement?
): FoldingDescriptor? {
val triggerNameElement =
(createTriggerStmt as? SqlCreateTriggerStmt)?.triggerName ?: return null
return toStatementDescriptor(triggerNameElement)
}
private fun PsiElement.toCreateIndexDescriptor(createIndexStmt: PsiElement?): FoldingDescriptor? {
val indexNameElement = (createIndexStmt as? SqlCreateIndexStmt)?.indexName ?: return null
return toStatementDescriptor(indexNameElement)
}
private fun PsiElement.toStatementDescriptor(stmtIdentifier: PsiElement?): FoldingDescriptor? {
if (stmtIdentifier == null) return null
if (nextSibling?.node?.elementType != SqlTypes.SEMI) return null
val start = stmtIdentifier.endOffset
val end = nextSibling.endOffset
if (start >= end) return null
return FoldingDescriptor(this, start, end, null, "...")
}
private fun PsiElement.toImportListDescriptor(): FoldingDescriptor? {
if (children.size < 2) return null
val whitespaceElement = firstChild.getChildOfType<PsiWhiteSpace>() ?: return null
val start = whitespaceElement.endOffset
val end = lastChild.endOffset
if (start >= end) return null
return FoldingDescriptor(this, start, end, null, "...")
}
override fun getPlaceholderText(node: ASTNode) = "..."
override fun isCollapsedByDefault(node: ASTNode) = with(node) {
elementType == SqldelightTypes.IMPORT_STMT_LIST && getChildren(null).size > 1
}
}
| apache-2.0 | 8471b11de0e8c8ff45732490402df6f8 | 41.664 | 100 | 0.721545 | 4.621317 | false | false | false | false |
fvoichick/ColoredPlayerNames | src/main/kotlin/org/sfinnqs/cpn/PlayerSection.kt | 1 | 2485 | /**
* ColoredPlayerNames - A Bukkit plugin for changing name colors
* Copyright (C) 2019 sfinnqs
*
* This file is part of ColoredPlayerNames.
*
* ColoredPlayerNames is free software; you can redistribute it and/or modify it
* under the terms of version 3 of the GNU General Public License as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see <https://www.gnu.org/licenses>.
*/
package org.sfinnqs.cpn
import org.bukkit.Bukkit
import org.bukkit.ChatColor
import org.bukkit.configuration.ConfigurationSection
import org.bukkit.configuration.InvalidConfigurationException
import java.util.*
data class PlayerSection(val name: String, val uuid: UUID, val color: ChatColor) {
constructor(section: ConfigurationSection, colors: Colors) : this(getName(section), getUuid(section), getColor(section, colors))
constructor(name: String, color: ChatColor) : this(name, getUuid(name), color)
companion object {
@Suppress("DEPRECATION")
fun getUuid(name: String) = Bukkit.getServer().getOfflinePlayer(name).uniqueId
private fun getName(section: ConfigurationSection): String {
val uuidString = section.getString("uuid")
if (uuidString != null) {
val name = Bukkit.getServer().getOfflinePlayer(UUID.fromString(uuidString)).name
if (name != null)
return name
}
return section.name
}
private fun getUuid(section: ConfigurationSection): UUID {
val uuidString = section.getString("uuid")
return if (uuidString == null) {
getUuid(section.name)
} else {
UUID.fromString(uuidString)
}
}
private fun getColor(section: ConfigurationSection, colors: Colors): ChatColor {
val colorString = section.getString("color")
?: throw InvalidConfigurationException("No color specified for player: ${section.name}")
return colors[colorString]
?: throw InvalidConfigurationException("Unrecognized color: $colorString")
}
}
}
| mit | 092fbf7041179ca48049b6c4fd61e6ea | 37.828125 | 132 | 0.67163 | 4.769674 | false | true | false | false |
soeminnminn/EngMyanDictionary | app/src/main/java/com/s16/widget/CircularProgressDrawable.kt | 1 | 28447 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.s16.widget
import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Context
import android.content.res.Resources
import android.graphics.*
import android.graphics.Paint.Cap
import android.graphics.drawable.Animatable
import android.graphics.drawable.Drawable
import android.view.animation.Interpolator
import android.view.animation.LinearInterpolator
import androidx.annotation.IntDef
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import kotlin.math.floor
/**
* Drawable that renders the animated indeterminate progress indicator in the Material design style
* without depending on API level 11.
*
*
* While this may be used to draw an indeterminate spinner using [.start] and [ ][.stop] methods, this may also be used to draw a progress arc using [ ][.setStartEndTrim] method. CircularProgressDrawable also supports adding an arrow
* at the end of the arc by [.setArrowEnabled] and [.setArrowDimensions] methods.
*
*
* To use one of the pre-defined sizes instead of using your own, [.setStyle] should
* be called with one of the [.DEFAULT] or [.LARGE] styles as its parameter. Doing it
* so will update the arrow dimensions, ring size and stroke width to fit the one specified.
*
*
* If no center radius is set via [.setCenterRadius] or [.setStyle]
* methods, CircularProgressDrawable will fill the bounds set via [.setBounds].
*/
class CircularProgressDrawable(context: Context) : Drawable(),
Animatable {
@IntDef(LARGE, DEFAULT)
annotation class ProgressDrawableSize
/** The indicator ring, used to manage animation state. */
private val mRing: Ring
/** Canvas rotation in degrees. */
private var rotation = 0f
private val mResources: Resources = context.resources
private var mAnimator: Animator? = null
var mRotationCount = 0f
var mFinishing = false
/** Sets all parameters at once in dp. */
private fun setSizeParameters(
centerRadius: Float, strokeWidth: Float, arrowWidth: Float,
arrowHeight: Float
) {
val ring = mRing
val metrics = mResources.displayMetrics
val screenDensity = metrics.density
ring.strokeWidth = strokeWidth * screenDensity
ring.centerRadius = centerRadius * screenDensity
ring.setColorIndex(0)
ring.setArrowDimensions(arrowWidth * screenDensity, arrowHeight * screenDensity)
}
/**
* Sets the overall size for the progress spinner. This updates the radius
* and stroke width of the ring, and arrow dimensions.
*
* @param size one of [.LARGE] or [.DEFAULT]
*/
fun setStyle(@ProgressDrawableSize size: Int) {
if (size == LARGE) {
setSizeParameters(
CENTER_RADIUS_LARGE,
STROKE_WIDTH_LARGE,
ARROW_WIDTH_LARGE.toFloat(),
ARROW_HEIGHT_LARGE.toFloat()
)
} else {
setSizeParameters(
CENTER_RADIUS,
STROKE_WIDTH,
ARROW_WIDTH.toFloat(),
ARROW_HEIGHT.toFloat()
)
}
invalidateSelf()
}
/**
* Returns the stroke width for the progress spinner in pixels.
*
* @return stroke width in pixels
*/
/**
* Sets the stroke width for the progress spinner in pixels.
*
* @param strokeWidth stroke width in pixels
*/
var strokeWidth: Float
get() = mRing.strokeWidth
set(strokeWidth) {
mRing.strokeWidth = strokeWidth
invalidateSelf()
}
/**
* Returns the center radius for the progress spinner in pixels.
*
* @return center radius in pixels
*/
/**
* Sets the center radius for the progress spinner in pixels. If set to 0, this drawable will
* fill the bounds when drawn.
*
* @param centerRadius center radius in pixels
*/
var centerRadius: Float
get() = mRing.centerRadius
set(centerRadius) {
mRing.centerRadius = centerRadius
invalidateSelf()
}
/**
* Returns the stroke cap of the progress spinner.
*
* @return stroke cap
*/
/**
* Sets the stroke cap of the progress spinner. Default stroke cap is [Paint.Cap.SQUARE].
*
* @param strokeCap stroke cap
*/
var strokeCap: Cap
get() = mRing.strokeCap!!
set(strokeCap) {
mRing.strokeCap = strokeCap
invalidateSelf()
}
/**
* Returns the arrow width in pixels.
*
* @return arrow width in pixels
*/
val arrowWidth: Float
get() = mRing.arrowWidth
/**
* Returns the arrow height in pixels.
*
* @return arrow height in pixels
*/
val arrowHeight: Float
get() = mRing.arrowHeight
/**
* Sets the dimensions of the arrow at the end of the spinner in pixels.
*
* @param width width of the baseline of the arrow in pixels
* @param height distance from tip of the arrow to its baseline in pixels
*/
fun setArrowDimensions(width: Float, height: Float) {
mRing.setArrowDimensions(width, height)
invalidateSelf()
}
/**
* Returns `true` if the arrow at the end of the spinner is shown.
*
* @return `true` if the arrow is shown, `false` otherwise.
*/
/**
* Sets if the arrow at the end of the spinner should be shown.
*
* @param show `true` if the arrow should be drawn, `false` otherwise
*/
var arrowEnabled: Boolean
get() = mRing.showArrow
set(show) {
mRing.showArrow = show
invalidateSelf()
}
/**
* Returns the scale of the arrow at the end of the spinner.
*
* @return scale of the arrow
*/
/**
* Sets the scale of the arrow at the end of the spinner.
*
* @param scale scaling that will be applied to the arrow's both width and height when drawing.
*/
var arrowScale: Float
get() = mRing.arrowScale
set(scale) {
mRing.arrowScale = scale
invalidateSelf()
}
/**
* Returns the start trim for the progress spinner arc
*
* @return start trim from [0..1]
*/
val startTrim: Float
get() = mRing.startTrim
/**
* Returns the end trim for the progress spinner arc
*
* @return end trim from [0..1]
*/
val endTrim: Float
get() = mRing.endTrim
/**
* Sets the start and end trim for the progress spinner arc. 0 corresponds to the geometric
* angle of 0 degrees (3 o'clock on a watch) and it increases clockwise, coming to a full circle
* at 1.
*
* @param start starting position of the arc from [0..1]
* @param end ending position of the arc from [0..1]
*/
fun setStartEndTrim(start: Float, end: Float) {
mRing.startTrim = start
mRing.endTrim = end
invalidateSelf()
}
/**
* Returns the amount of rotation applied to the progress spinner.
*
* @return amount of rotation from [0..1]
*/
/**
* Sets the amount of rotation to apply to the progress spinner.
*
* @param rotation rotation from [0..1]
*/
var progressRotation: Float
get() = mRing.rotation
set(rotation) {
mRing.rotation = rotation
invalidateSelf()
}
/**
* Returns the background color of the circle drawn inside the drawable.
*
* @return an ARGB color
*/
/**
* Sets the background color of the circle inside the drawable. Calling [ ][.setAlpha] does not affect the visibility background color, so it should be set
* separately if it needs to be hidden or visible.
*
* @param color an ARGB color
*/
var backgroundColor: Int
get() = mRing.backgroundColor
set(color) {
mRing.backgroundColor = color
invalidateSelf()
}
/**
* Returns the colors used in the progress animation
*
* @return list of ARGB colors
*/
/**
* Sets the colors used in the progress animation from a color list. The first color will also
* be the color to be used if animation is not started yet.
*
* @param colors list of ARGB colors to be used in the spinner
*/
val colorSchemeColors: IntArray
get() = mRing.colors
fun setColorSchemeColors(vararg colors: Int) {
mRing.colors = colors
mRing.setColorIndex(0)
invalidateSelf()
}
override fun draw(canvas: Canvas) {
val bounds = bounds
canvas.save()
canvas.rotate(rotation, bounds.exactCenterX(), bounds.exactCenterY())
mRing.draw(canvas, bounds)
canvas.restore()
}
override fun setAlpha(alpha: Int) {
mRing.alpha = alpha
invalidateSelf()
}
override fun getAlpha(): Int {
return mRing.alpha
}
override fun setColorFilter(colorFilter: ColorFilter?) {
mRing.setColorFilter(colorFilter)
invalidateSelf()
}
override fun getOpacity(): Int {
return PixelFormat.TRANSLUCENT
}
override fun isRunning(): Boolean {
return mAnimator!!.isRunning
}
/**
* Starts the animation for the spinner.
*/
override fun start() {
mAnimator!!.cancel()
mRing.storeOriginals()
// Already showing some part of the ring
if (mRing.endTrim != mRing.startTrim) {
mFinishing = true
mAnimator!!.duration = ANIMATION_DURATION / 2.toLong()
mAnimator!!.start()
} else {
mRing.setColorIndex(0)
mRing.resetOriginals()
mAnimator!!.duration = ANIMATION_DURATION.toLong()
mAnimator!!.start()
}
}
/**
* Stops the animation for the spinner.
*/
override fun stop() {
mAnimator!!.cancel()
rotation = 0f
mRing.showArrow = false
mRing.setColorIndex(0)
mRing.resetOriginals()
invalidateSelf()
}
// Adapted from ArgbEvaluator.java
private fun evaluateColorChange(fraction: Float, startValue: Int, endValue: Int): Int {
val startA = startValue shr 24 and 0xff
val startR = startValue shr 16 and 0xff
val startG = startValue shr 8 and 0xff
val startB = startValue and 0xff
val endA = endValue shr 24 and 0xff
val endR = endValue shr 16 and 0xff
val endG = endValue shr 8 and 0xff
val endB = endValue and 0xff
return startA + (fraction * (endA - startA)).toInt() shl 24 or (startR + (fraction * (endR - startR)).toInt() shl 16
) or (startG + (fraction * (endG - startG)).toInt() shl 8
) or startB + (fraction * (endB - startB)).toInt()
}
/**
* Update the ring color if this is within the last 25% of the animation.
* The new ring color will be a translation from the starting ring color to
* the next color.
*/
fun /* synthetic access */updateRingColor(
interpolatedTime: Float,
ring: Ring
) {
if (interpolatedTime > COLOR_CHANGE_OFFSET) {
ring.setColor(
evaluateColorChange(
(interpolatedTime - COLOR_CHANGE_OFFSET)
/ (1f - COLOR_CHANGE_OFFSET),
ring.startingColor,
ring.nextColor
)
)
} else {
ring.setColor(ring.startingColor)
}
}
/**
* Update the ring start and end trim if the animation is finishing (i.e. it started with
* already visible progress, so needs to shrink back down before starting the spinner).
*/
private fun applyFinishTranslation(interpolatedTime: Float, ring: Ring) {
// shrink back down and complete a full rotation before
// starting other circles
// Rotation goes between [0..1].
updateRingColor(interpolatedTime, ring)
val targetRotation =
(floor(ring.startingRotation / MAX_PROGRESS_ARC.toDouble())
+ 1f).toFloat()
val startTrim = (ring.startingStartTrim
+ (ring.startingEndTrim - MIN_PROGRESS_ARC - ring.startingStartTrim)
* interpolatedTime)
ring.startTrim = startTrim
ring.endTrim = ring.startingEndTrim
val rotation = (ring.startingRotation
+ (targetRotation - ring.startingRotation) * interpolatedTime)
ring.rotation = rotation
}
/**
* Update the ring start and end trim according to current time of the animation.
*/
fun /* synthetic access */applyTransformation(
interpolatedTime: Float,
ring: Ring,
lastFrame: Boolean
) {
if (mFinishing) {
applyFinishTranslation(interpolatedTime, ring)
// Below condition is to work around a ValueAnimator issue where onAnimationRepeat is
// called before last frame (1f).
} else if (interpolatedTime != 1f || lastFrame) {
val startingRotation = ring.startingRotation
val startTrim: Float
val endTrim: Float
if (interpolatedTime < SHRINK_OFFSET) { // Expansion occurs on first half of animation
val scaledTime =
interpolatedTime / SHRINK_OFFSET
startTrim = ring.startingStartTrim
endTrim =
startTrim + ((MAX_PROGRESS_ARC - MIN_PROGRESS_ARC)
* MATERIAL_INTERPOLATOR.getInterpolation(
scaledTime
) + MIN_PROGRESS_ARC)
} else { // Shrinking occurs on second half of animation
val scaledTime =
(interpolatedTime - SHRINK_OFFSET) / (1f - SHRINK_OFFSET)
endTrim =
ring.startingStartTrim + (MAX_PROGRESS_ARC - MIN_PROGRESS_ARC)
startTrim =
endTrim - ((MAX_PROGRESS_ARC - MIN_PROGRESS_ARC)
* (1f - MATERIAL_INTERPOLATOR.getInterpolation(
scaledTime
))
+ MIN_PROGRESS_ARC)
}
var rotation =
startingRotation + RING_ROTATION * interpolatedTime
val groupRotation =
GROUP_FULL_ROTATION * (interpolatedTime + mRotationCount)
ring.startTrim = startTrim
ring.endTrim = endTrim
ring.rotation = rotation
rotation = groupRotation
}
}
private fun setupAnimators() {
val ring = mRing
val animator = ValueAnimator.ofFloat(0f, 1f)
animator.addUpdateListener { animation ->
val interpolatedTime = animation.animatedValue as Float
updateRingColor(interpolatedTime, ring)
applyTransformation(interpolatedTime, ring, false)
invalidateSelf()
}
animator.repeatCount = ValueAnimator.INFINITE
animator.repeatMode = ValueAnimator.RESTART
animator.interpolator = LINEAR_INTERPOLATOR
animator.addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animator: Animator) {
mRotationCount = 0f
}
override fun onAnimationEnd(animator: Animator) {
// do nothing
}
override fun onAnimationCancel(animation: Animator) {
// do nothing
}
override fun onAnimationRepeat(animator: Animator) {
applyTransformation(1f, ring, true)
ring.storeOriginals()
ring.goToNextColor()
if (mFinishing) {
// finished closing the last ring from the swipe gesture; go
// into progress mode
mFinishing = false
animator.cancel()
animator.duration = ANIMATION_DURATION.toLong()
animator.start()
ring.showArrow = false
} else {
mRotationCount += 1
}
}
})
mAnimator = animator
}
/**
* A private class to do all the drawing of CircularProgressDrawable, which includes background,
* progress spinner and the arrow. This class is to separate drawing from animation.
*/
class Ring internal constructor() {
private val mTempBounds = RectF()
private val mPaint = Paint()
private val mArrowPaint = Paint()
private val mCirclePaint = Paint()
var startTrim = 0f
var endTrim = 0f
var rotation = 0f
var mStrokeWidth = 5f
private lateinit var mColors: IntArray
// mColorIndex represents the offset into the available mColors that the
// progress circle should currently display. As the progress circle is
// animating, the mColorIndex moves by one to the next available color.
var mColorIndex = 0
var startingStartTrim = 0f
var startingEndTrim = 0f
/**
* @return The amount the progress spinner is currently rotated, between [0..1].
*/
var startingRotation = 0f
var mShowArrow = false
var mArrow: Path? = null
var mArrowScale = 1f
/**
* @param centerRadius inner radius in px of the circle the progress spinner arc traces
*/
var centerRadius = 0f
var mArrowWidth = 0
var mArrowHeight = 0
/**
* @return current alpha of the progress spinner and arrowhead
*/
/**
* @param alpha alpha of the progress spinner and associated arrowhead.
*/
var alpha = 255
var mCurrentColor = 0
/**
* Sets the dimensions of the arrowhead.
*
* @param width width of the hypotenuse of the arrow head
* @param height height of the arrow point
*/
fun setArrowDimensions(width: Float, height: Float) {
mArrowWidth = width.toInt()
mArrowHeight = height.toInt()
}
var strokeCap: Cap?
get() = mPaint.strokeCap
set(strokeCap) {
mPaint.strokeCap = strokeCap
}
val arrowWidth: Float
get() = mArrowWidth.toFloat()
val arrowHeight: Float
get() = mArrowHeight.toFloat()
/**
* Draw the progress spinner
*/
fun draw(c: Canvas, bounds: Rect) {
val arcBounds = mTempBounds
var arcRadius = centerRadius + mStrokeWidth / 2f
if (centerRadius <= 0) {
// If center radius is not set, fill the bounds
arcRadius =
Math.min(bounds.width(), bounds.height()) / 2f - Math.max(
mArrowWidth * mArrowScale / 2f, mStrokeWidth / 2f
)
}
arcBounds[bounds.centerX() - arcRadius, bounds.centerY() - arcRadius, bounds.centerX() + arcRadius] =
bounds.centerY() + arcRadius
val startAngle = (startTrim + rotation) * 360
val endAngle = (endTrim + rotation) * 360
val sweepAngle = endAngle - startAngle
mPaint.color = mCurrentColor
mPaint.alpha = alpha
// Draw the background first
val inset = mStrokeWidth / 2f // Calculate inset to draw inside the arc
arcBounds.inset(inset, inset) // Apply inset
c.drawCircle(
arcBounds.centerX(), arcBounds.centerY(), arcBounds.width() / 2f,
mCirclePaint
)
arcBounds.inset(-inset, -inset) // Revert the inset
c.drawArc(arcBounds, startAngle, sweepAngle, false, mPaint)
drawTriangle(c, startAngle, sweepAngle, arcBounds)
}
fun drawTriangle(
c: Canvas,
startAngle: Float,
sweepAngle: Float,
bounds: RectF
) {
if (mShowArrow) {
if (mArrow == null) {
mArrow = Path()
mArrow!!.fillType = Path.FillType.EVEN_ODD
} else {
mArrow!!.reset()
}
val centerRadius =
Math.min(bounds.width(), bounds.height()) / 2f
val inset = mArrowWidth * mArrowScale / 2f
// Update the path each time. This works around an issue in SKIA
// where concatenating a rotation matrix to a scale matrix
// ignored a starting negative rotation. This appears to have
// been fixed as of API 21.
mArrow!!.moveTo(0f, 0f)
mArrow!!.lineTo(mArrowWidth * mArrowScale, 0f)
mArrow!!.lineTo(
mArrowWidth * mArrowScale / 2, mArrowHeight
* mArrowScale
)
mArrow!!.offset(
centerRadius + bounds.centerX() - inset,
bounds.centerY() + mStrokeWidth / 2f
)
mArrow!!.close()
// draw a triangle
mArrowPaint.color = mCurrentColor
mArrowPaint.alpha = alpha
c.save()
c.rotate(
startAngle + sweepAngle, bounds.centerX(),
bounds.centerY()
)
c.drawPath(mArrow!!, mArrowPaint)
c.restore()
}
}// if colors are reset, make sure to reset the color index as well
/**
* Sets the colors the progress spinner alternates between.
*
* @param colors array of ARGB colors. Must be non-`null`.
*/
var colors: IntArray
get() = mColors
set(colors) {
mColors = colors
// if colors are reset, make sure to reset the color index as well
setColorIndex(0)
}
/**
* Sets the absolute color of the progress spinner. This is should only
* be used when animating between current and next color when the
* spinner is rotating.
*
* @param color an ARGB color
*/
fun setColor(color: Int) {
mCurrentColor = color
}
/**
* Sets the background color of the circle inside the spinner.
*/
var backgroundColor: Int
get() = mCirclePaint.color
set(color) {
mCirclePaint.color = color
}
/**
* @param index index into the color array of the color to display in
* the progress spinner.
*/
fun setColorIndex(index: Int) {
mColorIndex = index
mCurrentColor = mColors[mColorIndex]
}
/**
* @return int describing the next color the progress spinner should use when drawing.
*/
val nextColor: Int
get() = mColors[nextColorIndex]
val nextColorIndex: Int
get() = (mColorIndex + 1) % mColors.size
/**
* Proceed to the next available ring color. This will automatically
* wrap back to the beginning of colors.
*/
fun goToNextColor() {
setColorIndex(nextColorIndex)
}
fun setColorFilter(filter: ColorFilter?) {
mPaint.colorFilter = filter
}
/**
* @param strokeWidth set the stroke width of the progress spinner in pixels.
*/
var strokeWidth: Float
get() = mStrokeWidth
set(strokeWidth) {
mStrokeWidth = strokeWidth
mPaint.strokeWidth = strokeWidth
}
val startingColor: Int
get() = mColors[mColorIndex]
/**
* @param show `true` if should show the arrow head on the progress spinner
*/
var showArrow: Boolean
get() = mShowArrow
set(show) {
if (mShowArrow != show) {
mShowArrow = show
}
}
/**
* @param scale scale of the arrowhead for the spinner
*/
var arrowScale: Float
get() = mArrowScale
set(scale) {
if (scale != mArrowScale) {
mArrowScale = scale
}
}
/**
* If the start / end trim are offset to begin with, store them so that animation starts
* from that offset.
*/
fun storeOriginals() {
startingStartTrim = startTrim
startingEndTrim = endTrim
startingRotation = rotation
}
/**
* Reset the progress spinner to default rotation, start and end angles.
*/
fun resetOriginals() {
startingStartTrim = 0f
startingEndTrim = 0f
startingRotation = 0f
startTrim = 0f
endTrim = 0f
rotation = 0f
}
init {
mPaint.strokeCap = Cap.SQUARE
mPaint.isAntiAlias = true
mPaint.style = Paint.Style.STROKE
mArrowPaint.style = Paint.Style.FILL
mArrowPaint.isAntiAlias = true
mCirclePaint.color = Color.TRANSPARENT
}
}
companion object {
private val LINEAR_INTERPOLATOR: Interpolator = LinearInterpolator()
private val MATERIAL_INTERPOLATOR: Interpolator =
FastOutSlowInInterpolator()
/** Maps to ProgressBar.Large style. */
const val LARGE = 0
private const val CENTER_RADIUS_LARGE = 11f
private const val STROKE_WIDTH_LARGE = 3f
private const val ARROW_WIDTH_LARGE = 12
private const val ARROW_HEIGHT_LARGE = 6
/** Maps to ProgressBar default style. */
const val DEFAULT = 1
private const val CENTER_RADIUS = 7.5f
private const val STROKE_WIDTH = 2.5f
private const val ARROW_WIDTH = 10
private const val ARROW_HEIGHT = 5
/**
* This is the default set of colors that's used in spinner. [ ][.setColorSchemeColors] allows modifying colors.
*/
private val COLORS = intArrayOf(
Color.BLACK
)
/**
* The value in the linear interpolator for animating the drawable at which
* the color transition should start
*/
private const val COLOR_CHANGE_OFFSET = 0.75f
private const val SHRINK_OFFSET = 0.5f
/** The duration of a single progress spin in milliseconds. */
private const val ANIMATION_DURATION = 1332
/** Full rotation that's done for the animation duration in degrees. */
private const val GROUP_FULL_ROTATION = 1080f / 5f
/** Maximum length of the progress arc during the animation. */
private const val MAX_PROGRESS_ARC = .8f
/** Minimum length of the progress arc during the animation. */
private const val MIN_PROGRESS_ARC = .01f
/** Rotation applied to ring during the animation, to complete it to a full circle. */
private const val RING_ROTATION =
1f - (MAX_PROGRESS_ARC - MIN_PROGRESS_ARC)
}
/**
* @param context application context
*/
init {
mRing = Ring()
mRing.colors = COLORS
strokeWidth = STROKE_WIDTH
setupAnimators()
}
} | gpl-2.0 | e41c91f92aedd3ce38c37a3b939085d4 | 32.507656 | 233 | 0.571624 | 4.876071 | false | false | false | false |
facebook/fresco | imagepipeline/src/main/java/com/facebook/imagepipeline/producers/LocalResourceFetchProducer.kt | 1 | 1852 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.producers
import android.content.res.AssetFileDescriptor
import android.content.res.Resources
import android.content.res.Resources.NotFoundException
import com.facebook.common.memory.PooledByteBufferFactory
import com.facebook.imagepipeline.image.EncodedImage
import com.facebook.imagepipeline.request.ImageRequest
import java.io.IOException
import java.util.concurrent.Executor
/** Executes a local fetch from a resource. */
class LocalResourceFetchProducer(
executor: Executor,
pooledByteBufferFactory: PooledByteBufferFactory,
private val resources: Resources
) : LocalFetchProducer(executor, pooledByteBufferFactory) {
@Throws(IOException::class)
override fun getEncodedImage(imageRequest: ImageRequest): EncodedImage? =
getEncodedImage(
resources.openRawResource(getResourceId(imageRequest)), getLength(imageRequest))
private fun getLength(imageRequest: ImageRequest): Int {
var fd: AssetFileDescriptor? = null
return try {
fd = resources.openRawResourceFd(getResourceId(imageRequest))
fd.length.toInt()
} catch (e: NotFoundException) {
-1
} finally {
try {
fd?.close()
} catch (ignored: IOException) {
// There's nothing we can do with the exception when closing descriptor.
}
}
}
override fun getProducerName(): String = PRODUCER_NAME
companion object {
const val PRODUCER_NAME = "LocalResourceFetchProducer"
private fun getResourceId(imageRequest: ImageRequest): Int {
val path = imageRequest.sourceUri.path
checkNotNull(path)
return path!!.substring(1).toInt()
}
}
}
| mit | d8ef2bfbcf86a3a9f41fe9abc9edb4bb | 31.491228 | 90 | 0.740281 | 4.653266 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/games/Game.kt | 1 | 18950 | package ca.josephroque.bowlingcompanion.games
import android.content.Context
import android.database.Cursor
import android.os.Parcel
import ca.josephroque.bowlingcompanion.common.interfaces.IIdentifiable
import ca.josephroque.bowlingcompanion.common.interfaces.KParcelable
import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator
import ca.josephroque.bowlingcompanion.common.interfaces.readBoolean
import ca.josephroque.bowlingcompanion.common.interfaces.writeBoolean
import ca.josephroque.bowlingcompanion.database.Contract.FrameEntry
import ca.josephroque.bowlingcompanion.database.Contract.GameEntry
import ca.josephroque.bowlingcompanion.database.Contract.MatchPlayEntry
import ca.josephroque.bowlingcompanion.database.DatabaseManager
import ca.josephroque.bowlingcompanion.games.lane.arePinsCleared
import ca.josephroque.bowlingcompanion.games.lane.Ball
import ca.josephroque.bowlingcompanion.games.lane.ballValue
import ca.josephroque.bowlingcompanion.games.lane.ballValueDifference
import ca.josephroque.bowlingcompanion.games.lane.Pin
import ca.josephroque.bowlingcompanion.games.lane.value
import ca.josephroque.bowlingcompanion.games.lane.valueDifference
import ca.josephroque.bowlingcompanion.matchplay.MatchPlay
import ca.josephroque.bowlingcompanion.matchplay.MatchPlayResult
import ca.josephroque.bowlingcompanion.scoring.Fouls
import ca.josephroque.bowlingcompanion.series.Series
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.Deferred
import kotlinx.coroutines.experimental.async
/**
* Copyright (C) 2018 Joseph Roque
*
* A single game recording.
*/
class Game(
val series: Series,
override val id: Long,
/** Ordinal starts at 1 */
val ordinal: Int,
var isLocked: Boolean,
var initialScore: Int,
var isManual: Boolean,
val frames: List<Frame>,
val matchPlay: MatchPlay
) : IIdentifiable, KParcelable {
// MARK: Constructors
private constructor(p: Parcel): this(
series = p.readParcelable<Series>(Series::class.java.classLoader)!!,
id = p.readLong(),
ordinal = p.readInt(),
initialScore = p.readInt(),
isLocked = p.readBoolean(),
isManual = p.readBoolean(),
frames = arrayListOf<Frame>().apply {
val parcelableArray = p.readParcelableArray(Frame::class.java.classLoader)!!
this.addAll(parcelableArray.map {
return@map it as Frame
})
},
matchPlay = p.readParcelable<MatchPlay>(MatchPlay::class.java.classLoader)!!
)
private constructor(other: Game): this(
series = other.series,
id = other.id,
ordinal = other.ordinal,
initialScore = other.score,
isLocked = other.isLocked,
isManual = other.isManual,
frames = other.frames.map { it.deepCopy() },
matchPlay = other.matchPlay.deepCopy()
)
// MARK: Parcelable
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeParcelable(series, 0)
writeLong(id)
writeInt(ordinal)
writeInt(score)
writeBoolean(isLocked)
writeBoolean(isManual)
writeParcelableArray(frames.toTypedArray(), 0)
writeParcelable(matchPlay, 0)
}
fun deepCopy(): Game {
return Game(this)
}
val firstNewFrame: Int
get() {
val firstFrameNotAccessed = frames.indexOfFirst { frame -> !frame.isAccessed }
return if (firstFrameNotAccessed > -1) firstFrameNotAccessed else Game.LAST_FRAME
}
private var dirty: Boolean = true
var score: Int = initialScore
get() {
if (isManual) { return field }
if (dirty) { frameScores.hashCode() }
return field
}
val fouls: Int
get() = frames.asSequence().map { frame -> frame.ballFouled.count { it } }.sum()
private var _frameScores: IntArray = IntArray(frames.size)
get() {
if (!dirty) { return field }
val frameScores = IntArray(frames.size)
for (frameIdx in frames.size - 1 downTo 0) {
val frame = frames[frameIdx]
// Score last frame differently than other frames
if (frame.zeroBasedOrdinal == Game.LAST_FRAME) {
for (ballIdx in Frame.LAST_BALL downTo 0) {
if (ballIdx == Frame.LAST_BALL) {
// Always add the value of the 3rd ball
frameScores[frameIdx] = frame.pinState[ballIdx].value(false)
} else if (frame.pinState[ballIdx].arePinsCleared) {
// If all pins were knocked down in a previous ball, add the full
// value of that ball (it's a strike/spare)
frameScores[frameIdx] += frame.pinState[ballIdx].value(false)
}
}
} else {
val nextFrame = frames[frameIdx + 1]
for (ballIdx in 0 until Frame.NUMBER_OF_BALLS) {
if (ballIdx == Frame.LAST_BALL) {
// If the loop is not exited by this point, there's no strike or spare
// Add basic value of the frame
frameScores[frameIdx] += frame.pinState[ballIdx].value(false)
} else if (frame.pinState[ballIdx].arePinsCleared) {
// Either spare or strike occurred, add ball 0 of this frame and next
frameScores[frameIdx] += frame.pinState[ballIdx].value(false)
frameScores[frameIdx] += nextFrame.pinState[0].value(false)
val double = frameScores[frameIdx] == Frame.MAX_VALUE * 2
// Strike in this frame
if (ballIdx == 0) {
if (nextFrame.zeroBasedOrdinal == Game.LAST_FRAME) {
// 9th frame must get additional scoring from 10th frame only
if (double) {
frameScores[frameIdx] += nextFrame.pinState[1].value(false)
} else {
frameScores[frameIdx] += nextFrame.pinState[1].valueDifference(nextFrame.pinState[0])
}
} else if (!double) {
frameScores[frameIdx] += nextFrame.pinState[1].valueDifference(nextFrame.pinState[0])
} else {
frameScores[frameIdx] += frames[frameIdx + 2].pinState[0].value(false)
}
}
break
}
}
}
}
// Get the accumulative score for each frame
var totalScore = 0
for (i in 0 until frames.size) {
totalScore += frameScores[i]
frameScores[i] = totalScore
}
// Calculate the final score of the game
if (!isManual) {
score = maxOf(totalScore - fouls * Game.FOUL_PENALTY, 0)
dirty = false
}
field = frameScores
return frameScores
}
val frameScores: IntArray
get() = _frameScores.copyOf()
// MARK: Game
fun getBallTextForFrames(): List<Array<String>> {
return frames.mapIndexed { index, frame ->
val balls = Array(Frame.NUMBER_OF_BALLS) { "" }
if (!frame.isAccessed) {
return@mapIndexed balls
}
if (frame.zeroBasedOrdinal == Game.LAST_FRAME) {
if (frame.pinState[0].arePinsCleared) {
// If the first ball is a strike, the next two could be strikes/spares
balls[0] = Ball.Strike.toString()
if (frame.pinState[1].arePinsCleared) {
// If the second ball is a strike
balls[1] = Ball.Strike.toString()
if (frame.pinState[2].arePinsCleared) {
balls[2] = Ball.Strike.toString()
} else {
balls[2] = frame.pinState[2].ballValue(2, true, false)
}
} else {
// Second ball is not a strike
balls[1] = frame.pinState[1].ballValue(1, true, false)
balls[2] = if (frame.pinState[2].arePinsCleared)
Ball.Spare.toString()
else
frame.pinState[2].ballValueDifference(frame.pinState[1], 2, false, false)
}
} else {
// If the first ball is not a strike, check if the second ball is a spare or not and get value
balls[0] = frame.pinState[0].ballValue(0, false, false)
if (frame.pinState[1].arePinsCleared) {
balls[1] = Ball.Spare.toString()
balls[2] = frame.pinState[2].ballValue(2, true, true)
} else {
balls[1] = frame.pinState[1].ballValueDifference(frame.pinState[0], 1, false, false)
balls[2] = frame.pinState[2].ballValueDifference(frame.pinState[1], 2, false, false)
}
}
} else {
val nextFrame = frames[index + 1]
balls[0] = frame.pinState[0].ballValue(0, true, false)
if (frame.pinState[0].arePinsCleared) {
// When the first ball is a strike, show the pins knocked down in the next frame, or empty frames
if (nextFrame.isAccessed) {
balls[1] = nextFrame.pinState[0].ballValue(1, false, true)
if (nextFrame.pinState[0].arePinsCleared) {
// When the next frame is a strike, the 3rd ball will have to come from the frame after
if (frame.zeroBasedOrdinal < Game.LAST_FRAME - 1) {
val nextNextFrame = frames[index + 2]
balls[2] = if (nextNextFrame.isAccessed)
nextNextFrame.pinState[0].ballValue(2, false, true)
else
Ball.None.toString()
} else {
// In the 9th frame, the 3rd ball comes from the 10th frame's second ball
balls[2] = nextFrame.pinState[1].ballValue(2, false, true)
}
} else {
balls[2] = nextFrame.pinState[1].ballValueDifference(nextFrame.pinState[0], 2, false, true)
}
} else {
balls[1] = Ball.None.toString()
balls[2] = Ball.None.toString()
}
} else {
// When the first ball is not a strike, the second and third ball values need to be calculated
if (frame.pinState[1].arePinsCleared) {
balls[1] = Ball.Spare.toString()
balls[2] = if (nextFrame.isAccessed)
nextFrame.pinState[0].ballValue(2, false, true)
else
Ball.None.toString()
} else {
balls[1] = frame.pinState[1].ballValueDifference(frame.pinState[0], 1, false, false)
balls[2] = frame.pinState[2].ballValueDifference(frame.pinState[1], 2, false, false)
}
}
}
return@mapIndexed balls
}
}
fun getScoreTextForFrames(): List<String> {
return frameScores.mapIndexed { index, score ->
return@mapIndexed if (index <= Game.LAST_FRAME) {
if (!frames[index].isAccessed) "" else score.toString()
} else {
score.toString()
}
}
}
fun markDirty() {
dirty = true
}
companion object {
@Suppress("unused")
private const val TAG = "Game"
@Suppress("unused")
@JvmField val CREATOR = parcelableCreator(::Game)
const val NUMBER_OF_FRAMES = 10
const val LAST_FRAME = NUMBER_OF_FRAMES - 1
const val NUMBER_OF_PINS = 5
const val MAX_SCORE = 450
const val FOUL_PENALTY = 15
fun isValidScore(score: Int): Boolean {
return score in 0..MAX_SCORE
}
fun fetchSeriesGames(context: Context, series: Series): Deferred<MutableList<Game>> {
return async(CommonPool) {
val gameList: MutableList<Game> = ArrayList(series.numberOfGames)
val database = DatabaseManager.getReadableDatabase(context).await()
val query = ("SELECT " +
"game.${GameEntry._ID} AS gid, " +
"game.${GameEntry.COLUMN_GAME_NUMBER}, " +
"game.${GameEntry.COLUMN_SCORE}, " +
"game.${GameEntry.COLUMN_IS_LOCKED}, " +
"game.${GameEntry.COLUMN_IS_MANUAL}, " +
"game.${GameEntry.COLUMN_MATCH_PLAY}, " +
"match.${MatchPlayEntry._ID} as mid, " +
"match.${MatchPlayEntry.COLUMN_OPPONENT_SCORE}, " +
"match.${MatchPlayEntry.COLUMN_OPPONENT_NAME}, " +
"frame.${FrameEntry._ID} as fid, " +
"frame.${FrameEntry.COLUMN_FRAME_NUMBER}, " +
"frame.${FrameEntry.COLUMN_IS_ACCESSED}, " +
"frame.${FrameEntry.COLUMN_PIN_STATE[0]}, " +
"frame.${FrameEntry.COLUMN_PIN_STATE[1]}, " +
"frame.${FrameEntry.COLUMN_PIN_STATE[2]}, " +
"frame.${FrameEntry.COLUMN_FOULS} " +
"FROM ${GameEntry.TABLE_NAME} AS game " +
"LEFT JOIN ${MatchPlayEntry.TABLE_NAME} as match " +
"ON gid=${MatchPlayEntry.COLUMN_GAME_ID} " +
"LEFT JOIN ${FrameEntry.TABLE_NAME} as frame " +
"ON gid=${FrameEntry.COLUMN_GAME_ID} " +
"WHERE ${GameEntry.COLUMN_SERIES_ID}=? " +
"GROUP BY gid, fid " +
"ORDER BY game.${GameEntry.COLUMN_GAME_NUMBER}, frame.${FrameEntry.COLUMN_FRAME_NUMBER}")
var lastId: Long = -1
var frames: MutableList<Frame> = ArrayList(NUMBER_OF_FRAMES)
/**
* Build a game from a cursor into the database.
*
* @param cursor database accessor
* @return a new game
*/
fun buildGameFromCursor(cursor: Cursor): Game {
val id = cursor.getLong(cursor.getColumnIndex("gid"))
val gameNumber = cursor.getInt(cursor.getColumnIndex(GameEntry.COLUMN_GAME_NUMBER))
val score = cursor.getInt(cursor.getColumnIndex(GameEntry.COLUMN_SCORE))
val isLocked = cursor.getInt(cursor.getColumnIndex(GameEntry.COLUMN_IS_LOCKED)) == 1
val isManual = cursor.getInt(cursor.getColumnIndex(GameEntry.COLUMN_IS_MANUAL)) == 1
val matchPlayResult = MatchPlayResult.fromInt(cursor.getInt(cursor.getColumnIndex(GameEntry.COLUMN_MATCH_PLAY)))
return Game(
series = series,
id = id,
ordinal = gameNumber,
initialScore = score,
isLocked = isLocked,
isManual = isManual,
frames = frames,
matchPlay = MatchPlay(
gameId = id,
id = cursor.getLong(cursor.getColumnIndex("mid")),
opponentName = cursor.getString(cursor.getColumnIndex(MatchPlayEntry.COLUMN_OPPONENT_NAME)) ?: "",
opponentScore = cursor.getInt(cursor.getColumnIndex(MatchPlayEntry.COLUMN_OPPONENT_SCORE)),
result = matchPlayResult!!
)
)
}
val cursor = database.rawQuery(query, arrayOf(series.id.toString()))
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast) {
val newId = cursor.getLong(cursor.getColumnIndex("gid"))
if (newId != lastId && lastId != -1L) {
cursor.moveToPrevious()
gameList.add(buildGameFromCursor(cursor))
frames = ArrayList(NUMBER_OF_FRAMES)
cursor.moveToNext()
}
frames.add(Frame(
gameId = newId,
id = cursor.getLong(cursor.getColumnIndex("fid")),
ordinal = cursor.getInt(cursor.getColumnIndex(FrameEntry.COLUMN_FRAME_NUMBER)),
isAccessed = cursor.getInt(cursor.getColumnIndex(FrameEntry.COLUMN_IS_ACCESSED)) == 1,
pinState = Array(Frame.NUMBER_OF_BALLS) {
return@Array Pin.deckFromInt(cursor.getInt(cursor.getColumnIndex(FrameEntry.COLUMN_PIN_STATE[it])))
},
ballFouled = BooleanArray(Frame.NUMBER_OF_BALLS) {
return@BooleanArray Fouls.foulIntToString(cursor.getInt(cursor.getColumnIndex(FrameEntry.COLUMN_FOULS))).contains((it + 1).toString())
}
))
lastId = newId
cursor.moveToNext()
}
cursor.moveToPrevious()
gameList.add(buildGameFromCursor(cursor))
}
cursor.close()
return@async gameList
}
}
}
}
| mit | 66051137453c3ba8ebce1bfcf09d3824 | 45.332518 | 170 | 0.509393 | 5.043918 | false | false | false | false |
guyca/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/parse/SharedElementTransitionOptions.kt | 1 | 1430 | package com.reactnativenavigation.parse
import android.animation.TimeInterpolator
import com.reactnativenavigation.parse.params.*
import com.reactnativenavigation.parse.params.Number
import com.reactnativenavigation.parse.parsers.InterpolationParser
import com.reactnativenavigation.parse.parsers.NumberParser
import com.reactnativenavigation.parse.parsers.TextParser
import org.json.JSONObject
class SharedElementTransitionOptions {
var fromId: Text = NullText()
var toId: Text = NullText()
var duration: Number = NullNumber()
var startDelay: Number = NullNumber()
var interpolation = Interpolation.NO_VALUE
fun getDuration() = duration[0].toLong()
fun getStartDelay() = startDelay[0].toLong()
fun getInterpolator(): TimeInterpolator = interpolation.interpolator
companion object {
@JvmStatic
fun parse(json: JSONObject?): SharedElementTransitionOptions {
val transition = SharedElementTransitionOptions()
if (json == null) return transition
transition.fromId = TextParser.parse(json, "fromId")
transition.toId = TextParser.parse(json, "toId")
transition.duration = NumberParser.parse(json, "duration")
transition.startDelay = NumberParser.parse(json, "startDelay")
transition.interpolation = InterpolationParser.parse(json, "interpolation")
return transition
}
}
} | mit | f0e04df0ddf908b392f8305f7059242a | 39.885714 | 87 | 0.727972 | 5.181159 | false | false | false | false |
j-selby/kotgb | libgdx-core/src/net/jselby/kotgb/ui/FrametimeGraph.kt | 1 | 2294 | package net.jselby.kotgb.ui
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import net.jselby.kotgb.StateManager
/**
* A measurement for frametimes
*/
class FrametimeGraph(val size : Int = 120) {
// How long the CPU took
private var frameTimings = DoubleArray(size)
// How long the thread took as a whole (including CPU)
private var tickTimings = DoubleArray(size)
private var position = 0
private var tickPosition = 0
private val pixmap = Pixmap(6 * size, 100, Pixmap.Format.RGBA8888)
private val font = BitmapFont()
fun update(state: StateManager) {
System.arraycopy(state.frameTimings.data, 0, frameTimings, 0, size)
System.arraycopy(state.tickTimings.data, 0, tickTimings, 0, size)
position = state.frameTimings.pos
tickPosition = state.tickTimings.pos
}
fun render(batch: SpriteBatch) {
pixmap.setColor(0f, 0f, 0f, 0.5f)
pixmap.fill()
val maxValue = Math.max(Math.max(frameTimings.max() ?: 0.0, tickTimings.max() ?: 0.0), 20.0)
val yScale = 100.0 / maxValue
pixmap.setColor(Color.GREEN)
for (i in 0..tickTimings.size - 1) {
val value = tickTimings[i]
pixmap.fillRectangle((i * (pixmap.width.toDouble() / tickTimings.size)).toInt(),
((100 - value * yScale)).toInt(),
pixmap.width / tickTimings.size, (value * yScale).toInt())
}
pixmap.setColor(Color.RED)
for (i in 0..frameTimings.size - 1) {
val value = frameTimings[i]
pixmap.fillRectangle((i * (pixmap.width.toDouble() / frameTimings.size)).toInt(),
((100 - value * yScale)).toInt(),
pixmap.width / frameTimings.size, (value * yScale).toInt())
}
pixmap.setColor(Color.BLACK)
pixmap.fillRectangle(0, ((100 - 16.67 * yScale)).toInt(), pixmap.width, 1)
val texture = Texture(pixmap)
batch.draw(texture, 0f, 0f)
font.draw(batch, "16.67ms", 5f, (16.67f * yScale).toFloat() + 12)
batch.flush()
texture.dispose()
}
} | mit | 88f47aa80e33335331e1211d98440e8c | 33.772727 | 100 | 0.624237 | 3.71799 | false | false | false | false |
timrs2998/pdf-builder | src/test/kotlin/com/github/timrs2998/pdfbuilder/RenderUtilSpec.kt | 1 | 610 | package com.github.timrs2998.pdfbuilder
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.gherkin.Feature
object RenderUtilSpec: Spek({
Feature("render util") {
Scenario("page index") {
Then("get index of page #y / #pageHeight") {
assert(getPageIndex(100f, 0f) == 0)
assert(getPageIndex(100f, 99f) == 0)
assert(getPageIndex(100f, 100f) == 1)
assert(getPageIndex(100f, 101f) == 1)
assert(getPageIndex(100f, 199f) == 1)
assert(getPageIndex(100f, 200f) == 2)
assert(getPageIndex(100f, 201f) == 2)
}
}
}
})
| gpl-3.0 | e4e6a6d84bd862ec9f7c90e5ed59befb | 26.727273 | 52 | 0.631148 | 3.210526 | false | false | true | false |
gdgplzen/gugorg-android | app/src/main/java/cz/jacktech/gugorganizer/ui/UserLoginActivity.kt | 1 | 4806 | package cz.jacktech.gugorganizer.ui
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.widget.EditText
import android.widget.RelativeLayout
import com.afollestad.materialdialogs.MaterialDialog
import cz.jacktech.gugorganizer.R
import cz.jacktech.gugorganizer.data.User
import cz.jacktech.gugorganizer.network.GugApi
import cz.jacktech.gugorganizer.network.GugClient
import cz.jacktech.gugorganizer.network.api_objects.ApiEmbedded
import cz.jacktech.gugorganizer.network.api_objects.GugGroup
import cz.jacktech.gugorganizer.network.api_objects.GugUser
import cz.jacktech.gugorganizer.network.api_objects.GugUserGroups
import cz.jacktech.gugorganizer.storage.Settings
import retrofit.Callback
import kotlinx.android.synthetic.activity_user_login.*
import org.jetbrains.anko.intentFor
import org.jetbrains.anko.text
import retrofit.Call
import retrofit.Response
public class UserLoginActivity : AppCompatActivity() {
private var mProgressDialog: MaterialDialog? = null
private var mUser: User = User()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_user_login)
button_sign_in.setOnClickListener {
mProgressDialog = MaterialDialog.Builder(this)
.content(R.string.signing_in)
.cancelable(false)
.progress(true, 0)
.show()
checkLogin()
}
}
private fun checkLogin() {
mUser = User()
var call: retrofit.Call<GugUser> = GugClient.getApi().getMe(
input_user_email.text,
input_user_password.text
);
call.enqueue(object : retrofit.Callback<GugUser> {
override fun onFailure(t: Throwable?) {
mProgressDialog!!.dismiss()
showError(R.string.invalid_token)
}
override fun onResponse(response: Response<GugUser>?) {
var gugUser: GugUser = response!!.body();
mUser.id = gugUser.id
mUser.token = gugUser.token
mUser.fullname = gugUser.firstName + " " + gugUser.lastName
downloadNecessaryData()
}
})
}
private fun downloadNecessaryData() {
val api = GugClient.getApi()
var groupsCall: Call<ApiEmbedded<GugUserGroups>> = api.getUsersGroup(mUser.token!!)
groupsCall.enqueue(object : Callback<ApiEmbedded<GugUserGroups>> {
override fun onResponse(response: Response<ApiEmbedded<GugUserGroups>>?) {
val groups = response!!.body().embedded
if (groups != null && (groups.lastUsed != null || (groups.groups != null && groups.groups!!.size() > 0))) {
val groupString = if (groups.lastUsed != null)
groups.lastUsed!!.name!!.toLowerCase()
else
groups.groups!!.get(0).name!!.toLowerCase()
if (groupString.startsWith("gdg")) {
mUser.groupType = User.GROUP_GDG
} else if (groupString.startsWith("gbg")) {
mUser.groupType = User.GROUP_GBG
} else if (groupString.startsWith("gxg")) {
mUser.groupType = User.GROUP_GXG
} else if (groupString.startsWith("geg")) {
mUser.groupType = User.GROUP_GEG
} else {
mProgressDialog!!.dismiss()
showError(R.string.unknown_user_group)
return
}
groups.groups!!.forEach { group -> mUser.addGroup(group.name!!) }
finishLoginPhase()
} else {
mProgressDialog!!.dismiss()
showError(R.string.unknown_user_group)
Settings.setUser(null)
}
}
override fun onFailure(t: Throwable?) {
mProgressDialog!!.dismiss()
showError(R.string.failed_to_download_info)
t!!.printStackTrace()
}
})
}
private fun finishLoginPhase() {
Settings.setUser(mUser)
mProgressDialog!!.dismiss()
finish()
startActivity(intentFor<MainActivity>())
}
private fun showError(errMsg: Int) {
val error = Snackbar.make(contentLayout, errMsg, Snackbar.LENGTH_LONG)
error.getView().setBackgroundColor(Color.parseColor("#F44336"))
error.show()
}
companion object {
}
}
| gpl-2.0 | 99efc7addf9ed87247f8b1581c5d9890 | 35.135338 | 123 | 0.594881 | 4.594646 | false | false | false | false |
danirod/rectball | app/src/main/java/es/danirod/rectball/android/settings/MigrationV1.kt | 1 | 4768 | package es.danirod.rectball.android.settings
import android.content.Context
import android.content.SharedPreferences
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.utils.Base64Coder
import com.badlogic.gdx.utils.JsonReader
import org.json.JSONObject
/** Migration class for updating the schema to v1 from v0 (pre-0.4.10). */
internal class MigrationV1(private val context: Context, private val prefs: SharedPreferences) {
fun migrate() {
val editor = prefs.edit()
migratePreferences(editor)
migrateScoresFile(editor)
migrateStatsFile(editor)
bumpSchemaVersion(editor)
editor.apply()
}
private fun migratePreferences(editor: SharedPreferences.Editor) {
val legacyPrefs = context.getSharedPreferences("rectball", Context.MODE_PRIVATE)
/* If there are no keys on this file, it's empty already. */
if (legacyPrefs.all.isNotEmpty()) {
editor.putBoolean(SettingsManager.TAG_ENABLE_SOUND, legacyPrefs.getBoolean("sound", true))
editor.putBoolean(SettingsManager.TAG_ENABLE_COLORBLIND, legacyPrefs.getBoolean("colorblind", false))
editor.putBoolean(SettingsManager.TAG_ENABLE_FULLSCREEN, legacyPrefs.getBoolean("fullscreen", false))
editor.putBoolean(SettingsManager.TAG_ASKED_TUTORIAL, legacyPrefs.getBoolean("tutorialAsked", false))
/* Then remove the legacy preferences file. */
val legacyEditor = legacyPrefs.edit()
legacyEditor.clear()
legacyEditor.apply()
}
}
private fun migrateScoresFile(editor: SharedPreferences.Editor) {
if (Gdx.files.local("scores").exists()) {
/* Decode old scores file. */
val jsonData = decodeJSON("scores")
/* Migrate data to the preferences file. */
editor.putLong(SettingsManager.TAG_HIGH_SCORE, jsonData.getLong("highestScore", 0L))
editor.putLong(SettingsManager.TAG_HIGH_TIME, jsonData.getLong("highestTime", 0L))
/* Save changes and burn old file. */
Gdx.files.local("scores").delete()
}
}
private fun migrateStatsFile(editor: SharedPreferences.Editor) {
if (Gdx.files.local("stats").exists()) {
/* Decode old statistics file. */
val jsonData = decodeJSON("stats")
/* Migrate total data to the preferences file. */
val total = jsonData["total"]["values"]
editor.putLong(SettingsManager.TAG_TOTAL_SCORE, total.getLong("score", 0L))
editor.putLong(SettingsManager.TAG_TOTAL_COMBINATIONS, total.getLong("combinations", 0L))
editor.putLong(SettingsManager.TAG_TOTAL_BALLS, total.getLong("balls", 0L))
editor.putLong(SettingsManager.TAG_TOTAL_GAMES, total.getLong("games", 0L))
editor.putLong(SettingsManager.TAG_TOTAL_TIME, total.getLong("time", 0L))
editor.putLong(SettingsManager.TAG_TOTAL_PERFECTS, total.getLong("perfects", 0L))
editor.putLong(SettingsManager.TAG_TOTAL_HINTS, total.getLong("cheats", 0L))
/* Migrate color data to the preferences file. */
val colors = jsonData["colors"]["values"]
editor.putLong(SettingsManager.TAG_TOTAL_COLOR_RED, colors.getLong("red", 0L))
editor.putLong(SettingsManager.TAG_TOTAL_COLOR_GREEN, colors.getLong("green", 0L))
editor.putLong(SettingsManager.TAG_TOTAL_COLOR_BLUE, colors.getLong("blue", 0L))
editor.putLong(SettingsManager.TAG_TOTAL_COLOR_YELLOW, colors.getLong("yellow", 0L))
/* Migrate sizes data to the preferences file. */
val sizes = jsonData["sizes"]["values"]
sizes.remove("class") // This legacy field is sponsored by reflected serialization
val sizesMap = sizes.map { Pair<String, Long>(it.name, it.asLong()) }.toMap()
editor.putString(SettingsManager.TAG_STAT_SIZES, serializeSizes(sizesMap))
/* Save changes and burn old file. */
Gdx.files.local("stats").delete()
}
}
private fun bumpSchemaVersion(editor: SharedPreferences.Editor) {
if (prefs.getInt(SettingsManager.TAG_SCHEMA_VERSION, 0) < SettingsManager.SCHEMA_VERSION) {
editor.putInt(SettingsManager.TAG_SCHEMA_VERSION, SettingsManager.SCHEMA_VERSION)
editor.apply()
}
}
/** Decodes a Base64 scrambled JSON [file]. */
private fun decodeJSON(file: String) = JsonReader().parse(Base64Coder.decodeString(Gdx.files.local(file).readString()))
/** Converts a sizes [map] into a serialized JSON string that can be saved in the settings. */
private fun serializeSizes(map: Map<String, Long>): String = JSONObject(map).toString()
} | gpl-3.0 | e3781e707c9fc9bf90b5985197f0ec18 | 47.171717 | 123 | 0.665688 | 4.410731 | false | false | false | false |
klose911/klose911.github.io | src/kotlin/src/tutorial/collections/MapSample.kt | 1 | 3050 | package tutorial.collections
fun main() {
val numbersMap1 = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap1.get("one")) // 1
println(numbersMap1["one"]) // 1
println(numbersMap1.getOrDefault("four", 10)) // 10
println(numbersMap1["five"]) // null
//numbersMap.getValue("six") // exception!
println(numbersMap1.keys) // [one, two, three]
println(numbersMap1.values) // [1, 2, 3]
val numbersMap2 = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredMap = numbersMap2.filter { (key, value) ->
key.endsWith("1") && value > 10
}
println(filteredMap) // {key11=11}
val filteredKeysMap = numbersMap2.filterKeys { it.endsWith("1") }
val filteredValuesMap = numbersMap2.filterValues { it < 10 }
println(filteredKeysMap) // {key1=1, key11=11}
println(filteredValuesMap) // {key1=1, key2=2, key3=3}
val numbersMap3 = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap3 + Pair("four", 4)) // {one=1, two=2, three=3, four=4}
println(numbersMap3 + Pair("one", 10)) // {one=10, two=2, three=3}
println(numbersMap3 + mapOf("five" to 5, "one" to 11)) // {one=11, two=2, three=3, five=5}
println(numbersMap3 - "one") // {two=2, three=3}
println(numbersMap3 - listOf("two", "four")) // {one=1, three=3}
val numbersMap4 = mutableMapOf("one" to 1, "two" to 2)
numbersMap4.put("three", 3)
println(numbersMap4) // {one=1, two=2, three=3}
val numbersMap5 = mutableMapOf("one" to 1, "two" to 2, "three" to 3)
numbersMap5.putAll(setOf("four" to 4, "five" to 5))
println(numbersMap5) // {one=1, two=2, three=3, four=4, five=5}
val numbersMap6 = mutableMapOf("one" to 1, "two" to 2)
val previousValue = numbersMap6.put("one", 11)
println("value associated with 'one', before: $previousValue, after: ${numbersMap6["one"]}") // value associated with 'one', before: 1, after: 11
println(numbersMap6) // {one=11, two=2}
val numbersMap7 = mutableMapOf("one" to 1, "two" to 2)
numbersMap7["three"] = 3 // 调用 numbersMap.put("three", 3)
numbersMap7 += mapOf("four" to 4, "five" to 5)
println(numbersMap7) // {one=1, two=2, three=3, four=4, five=5}
val numbersMap8 = mutableMapOf("one" to 1, "two" to 2, "three" to 3)
numbersMap8.remove("one")
println(numbersMap8) // {two=2, three=3}
numbersMap8.remove("three", 4) //不会删除任何条目
println(numbersMap8) // {two=2, three=3}
val numbersMap9 = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "threeAgain" to 3)
numbersMap9.keys.remove("one")
println(numbersMap9) // {two=2, three=3, threeAgain=3}
numbersMap9.values.remove(3)
println(numbersMap9) // {two=2, threeAgain=3}
val numbersMap10 = mutableMapOf("one" to 1, "two" to 2, "three" to 3)
numbersMap10 -= "two"
println(numbersMap10) // {one=1, three=3}
numbersMap10 -= "five" //不会删除任何条目
println(numbersMap10) // {one=1, three=3}
} | bsd-2-clause | ef44088d86ea6a3bdf2bdf5cfcac4441 | 42.071429 | 149 | 0.621102 | 2.963618 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/ide/template/postfix/utils.kt | 1 | 2841 | package org.rust.ide.template.postfix
import com.intellij.codeInsight.template.postfix.templates.PostfixTemplateExpressionSelector
import com.intellij.codeInsight.template.postfix.templates.PostfixTemplatePsiInfo
import com.intellij.openapi.editor.Document
import com.intellij.psi.PsiElement
import com.intellij.util.Function
import org.rust.lang.core.psi.RustBlockElement
import org.rust.lang.core.psi.RustExprElement
import org.rust.lang.core.psi.RustPsiFactory
import org.rust.lang.core.psi.util.ancestors
import org.rust.lang.core.types.RustBooleanType
import org.rust.lang.core.types.RustEnumType
import org.rust.lang.core.types.util.resolvedType
import org.rust.lang.utils.negate
internal object RustPostfixTemplatePsiInfo : PostfixTemplatePsiInfo() {
override fun getNegatedExpression(element: PsiElement): PsiElement =
element.negate()
override fun createExpression(context: PsiElement, prefix: String, suffix: String): PsiElement =
RustPsiFactory(context.project).createExpression("$prefix${context.text}$suffix")
}
abstract class RustExprParentsSelectorBase(val pred: (RustExprElement) -> Boolean) : PostfixTemplateExpressionSelector {
override fun getRenderer(): Function<PsiElement, String> = Function { it.text }
abstract override fun getExpressions(context: PsiElement, document: Document, offset: Int): List<PsiElement>
}
class RustTopMostInScopeSelector(pred: (RustExprElement) -> Boolean) : RustExprParentsSelectorBase(pred) {
override fun getExpressions(context: PsiElement, document: Document, offset: Int): List<PsiElement> =
listOf(
context
.ancestors
.takeWhile { it !is RustBlockElement }
.filter { it is RustExprElement && pred(it) }
.last()
)
override fun hasExpression(context: PsiElement, copyDocument: Document, newOffset: Int): Boolean =
context
.ancestors
.takeWhile { it !is RustBlockElement }
.any { it is RustExprElement && pred(it) }
}
class RustAllParentsSelector(pred: (RustExprElement) -> Boolean) : RustExprParentsSelectorBase(pred) {
override fun getExpressions(context: PsiElement, document: Document, offset: Int): List<PsiElement> =
context
.ancestors
.takeWhile { it !is RustBlockElement }
.filter { it is RustExprElement && pred(it) }
.toList()
override fun hasExpression(context: PsiElement, copyDocument: Document, newOffset: Int): Boolean =
context
.ancestors
.takeWhile { it !is RustBlockElement }
.any { it is RustExprElement && pred(it) }
}
fun RustExprElement.isBool() = resolvedType == RustBooleanType
fun RustExprElement.isEnum() = resolvedType is RustEnumType
fun RustExprElement.any() = true
| mit | 570a5f4e9e446f0f30ea52d516c1dc77 | 42.707692 | 120 | 0.722985 | 4.502377 | false | false | false | false |
MichaelRocks/lightsaber | processor/src/main/java/io/michaelrocks/lightsaber/processor/injection/ProvidableTargetPatcher.kt | 1 | 2105 | /*
* Copyright 2019 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.processor.injection
import io.michaelrocks.lightsaber.processor.descriptors.MethodDescriptor
import io.michaelrocks.lightsaber.processor.model.InjectionTarget
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes.ACC_PRIVATE
import org.objectweb.asm.Opcodes.ACC_PROTECTED
import org.objectweb.asm.Opcodes.ACC_PUBLIC
class ProvidableTargetPatcher(
classVisitor: ClassVisitor,
private val providableTarget: InjectionTarget
) : BaseInjectionClassVisitor(classVisitor) {
override fun visit(
version: Int,
access: Int,
name: String,
signature: String?,
superName: String?,
interfaces: Array<String>?
) {
val newAccess = (access and (ACC_PRIVATE or ACC_PROTECTED).inv()) or ACC_PUBLIC
super.visit(version, access, name, signature, superName, interfaces)
if (newAccess != access) {
isDirty = true
}
}
override fun visitMethod(
access: Int,
name: String,
desc: String,
signature: String?,
exceptions: Array<String>?
): MethodVisitor? {
val method = MethodDescriptor(name, desc)
if (providableTarget.isInjectableConstructor(method)) {
val newAccess = access and ACC_PRIVATE.inv()
if (newAccess != access) {
isDirty = true
}
return super.visitMethod(newAccess, name, desc, signature, exceptions)
} else {
return super.visitMethod(access, name, desc, signature, exceptions)
}
}
}
| apache-2.0 | b761b6900c3577e51e7040a63ca5de83 | 31.384615 | 83 | 0.727316 | 4.218437 | false | false | false | false |
wakingrufus/mastodon-jfx | src/main/kotlin/com/github/wakingrufus/mastodon/ui/NotificationFragment.kt | 1 | 3402 | package com.github.wakingrufus.mastodon.ui
import com.github.wakingrufus.mastodon.ui.styles.DefaultStyles
import com.sys1yagi.mastodon4j.api.entity.Notification
import javafx.geometry.Pos
import javafx.scene.paint.Color
import mu.KLogging
import tornadofx.*
class NotificationFragment : Fragment() {
companion object : KLogging()
val server: String by param()
val notification: Notification by param()
override val root = vbox {
hbox {
style {
backgroundColor = multi(DefaultStyles.backgroundColor)
}
label(notification.account?.displayName!!) {
textFill = Color.WHITE
style {
padding = CssBox(1.px, 1.px, 1.px, 1.px)
fontSize = 1.5.em
}
}
if (notification.type == Notification.Type.Follow.value) {
label(" followed you.") {
textFill = Color.WHITE
style {
padding = CssBox(1.px, 1.px, 1.px, 1.px)
fontSize = 1.5.em
}
}
} else if (notification.type == Notification.Type.Reblog.value) {
label(" boosted your toot.") {
textFill = Color.WHITE
style {
padding = CssBox(1.px, 1.px, 1.px, 1.px)
fontSize = 1.5.em
}
}
} else if (notification.type == Notification.Type.Favourite.value) {
label(" favourited your toot") {
textFill = Color.WHITE
style {
padding = CssBox(1.px, 1.px, 1.px, 1.px)
fontSize = 1.5.em
}
}
} else if (notification.type == Notification.Type.Mention.value) {
label(" mentioned you") {
textFill = Color.WHITE
style {
padding = CssBox(1.px, 1.px, 1.px, 1.px)
fontSize = 1.5.em
}
}
}
}
hbox {
if (notification.type == Notification.Type.Follow.value
|| notification.type == Notification.Type.Mention.value)
this += find<AccountFragment>(params = mapOf(
"account" to notification.account,
"server" to server))
else {
addClass(DefaultStyles.defaultBorder)
style {
padding = CssBox(top = 1.em, bottom = 1.em, left = 1.em, right = 1.em)
alignment = Pos.TOP_LEFT
backgroundColor = multi(DefaultStyles.backgroundColor)
textFill = Color.WHITE
}
val toot = parseToot(notification.status?.content!!)
toot.style {
backgroundColor = multi(DefaultStyles.backgroundColor)
textFill = Color.WHITE
}
this += toot
}
}
label(notification.createdAt) {
textFill = Color.WHITE
style {
padding = CssBox(1.px, 1.px, 1.px, 1.px)
fontSize = 1.em
}
}
}
} | mit | 8ba70eca304db281ea4dab4617775be3 | 35.98913 | 90 | 0.460024 | 4.894964 | false | false | false | false |
shyiko/ktlint | ktlint-ruleset-standard/src/test/kotlin/com/pinterest/ktlint/ruleset/standard/CommentSpacingRuleTest.kt | 1 | 2635 | package com.pinterest.ktlint.ruleset.standard
import com.pinterest.ktlint.core.LintError
import com.pinterest.ktlint.test.format
import com.pinterest.ktlint.test.lint
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class CommentSpacingRuleTest {
@Test
fun testLintValidCommentSpacing() {
assertThat(
CommentSpacingRule().lint(
"""
//
//noinspection AndroidLintRecycle
//region
//endregion
//language=SQL
// comment
var debugging = false // comment
var debugging = false // comment//word
// comment
""".trimIndent()
)
).isEmpty()
}
@Test
fun testLintInvalidCommentSpacing() {
assertThat(
CommentSpacingRule().lint(
"""
//comment
var debugging = false// comment
var debugging = false //comment
var debugging = false//comment
//comment
""".trimIndent()
)
).isEqualTo(
listOf(
LintError(1, 1, "comment-spacing", "Missing space after //"),
LintError(2, 22, "comment-spacing", "Missing space before //"),
LintError(3, 23, "comment-spacing", "Missing space after //"),
LintError(4, 22, "comment-spacing", "Missing space before //"),
LintError(4, 22, "comment-spacing", "Missing space after //"),
LintError(5, 5, "comment-spacing", "Missing space after //")
)
)
}
@Test
fun testFormatInvalidCommentSpacing() {
assertThat(
CommentSpacingRule().format(
"""
//comment
var debugging = false// comment
var debugging = false //comment
var debugging = false//comment
fun main() {
System.out.println(//123
"test"
)
}
//comment
""".trimIndent()
)
).isEqualTo(
"""
// comment
var debugging = false // comment
var debugging = false // comment
var debugging = false // comment
fun main() {
System.out.println( // 123
"test"
)
}
// comment
""".trimIndent()
)
}
}
| mit | 121e27f514aa3c8a74de14c841bbce9a | 29.639535 | 79 | 0.457685 | 5.642398 | false | true | false | false |
skydoves/WaterDrink | app/src/main/java/com/skydoves/waterdays/consts/LocalUrls.kt | 1 | 2060 | /*
* Copyright (C) 2016 skydoves
*
* 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.skydoves.waterdays.consts
/**
* Developed by skydoves on 2017-08-18.
* Copyright (c) 2017 skydoves rights reserved.
*/
object LocalUrls {
fun getLocalUrl(index: Int): String {
when (index) {
1 -> return "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=4182025000"
2 -> return "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=4282025000"
3 -> return "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=4817074000"
4 -> return "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=4729053000"
5 -> return "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=2920054000"
6 -> return "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=2720065000"
7 -> return "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=3023052000"
8 -> return "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=2644058000"
9 -> return "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=3114056000"
10 -> return "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=2871025000"
11 -> return "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=4681025000"
12 -> return "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=4579031000"
13 -> return "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=4376031000"
14 -> return "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=4376031000"
15 -> return "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=5013025300"
else -> return "http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=1159068000"
}
}
}
| apache-2.0 | bbbc7335ace15c846c30c2384aaa4d50 | 44.777778 | 79 | 0.693689 | 2.853186 | false | false | false | false |
JetBrains/resharper-unity | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/run/UnityRunUtil.kt | 1 | 13456 | package com.jetbrains.rider.plugins.unity.run
import com.intellij.execution.configurations.CommandLineTokenizer
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.ProcessInfo
import com.intellij.execution.util.ExecUtil
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.xdebugger.XDebuggerManager
import com.jetbrains.rider.plugins.unity.util.EditorInstanceJson
import com.jetbrains.rider.plugins.unity.util.EditorInstanceJsonStatus
import com.jetbrains.rider.run.configurations.remote.RemoteConfiguration
import java.io.File
import java.nio.charset.StandardCharsets
import java.nio.file.Paths
data class UnityProcessInfo(val projectName: String?, @NlsSafe val roleName: String?)
object UnityRunUtil {
private val logger = Logger.getInstance(UnityRunUtil::class.java)
fun isUnityEditorProcess(processInfo: ProcessInfo): Boolean {
val name = processInfo.executableDisplayName
// For symlinks
val canonicalName = if (processInfo.executableCannonicalPath.isPresent) {
Paths.get(processInfo.executableCannonicalPath.get()).fileName.toString()
}
else name
logger.debug("isUnityEditorProcess: '$name', '$canonicalName'")
// Based on Unity's own VS Code debugger, we simply look for "Unity" or "Unity Editor". Java's
// ProcessInfo#executableDisplayName is the executable name with `.exe` removed. This matches the behaviour of
// .NET's Process.ProcessName
// https://github.com/Unity-Technologies/MonoDevelop.Debugger.Soft.Unity/blob/9f116ee5d344bce5888e838a75ded418bd7852c7/UnityProcessDiscovery.cs#L155
return (name.equals("Unity", true) || name.equals("Unity Editor", true)
|| canonicalName.equals("unity", true) || canonicalName.equals("Unity Editor", true))
}
fun isValidUnityEditorProcess(pid: Int, processList: Array<out ProcessInfo>): Boolean {
logger.trace("Checking Unity Process, current pid: $pid. Process count: ${processList.size}")
return processList.any { it.pid == pid && isUnityEditorProcess(it) }
}
fun getUnityProcessInfo(processInfo: ProcessInfo, project: Project): UnityProcessInfo? {
return getAllUnityProcessInfo(listOf(processInfo), project)[processInfo.pid]
}
fun getAllUnityProcessInfo(processList: List<ProcessInfo>, project: Project): Map<Int, UnityProcessInfo> {
// We might have to call external processes. Make sure we're running in the background
assertNotDispatchThread()
// We have several options to get the project name (and maybe directory, for future use):
// 1) Match pid with EditorInstance.json - it's the current project
// 2) If the editor was started from Unity Hub, use the -projectPath or -createProject parameters
// 3) If we're on Mac/Linux, use `lsof -a -p {pid},{pid},{pid} -d cwd -Fn` to get the current working directory
// This is the project directory. (It's better performance to fetch these all at once)
// Getting current directory on Windows is painful and requires JNI to read process memory
// E.g. https://stackoverflow.com/questions/16110936/read-other-process-current-directory-in-c-sharp
// 4) Scrape the main window title. This is fragile, as the format changes, and can easily break with hyphens in
// project or scene names. It also doesn't give us the project path. And it doesn't work on Mac/Linux
val processInfoMap = mutableMapOf<Int, UnityProcessInfo>()
processList.forEach {
try {
val projectName = getProjectNameFromEditorInstanceJson(it, project)
parseProcessInfoFromCommandLine(it, projectName)?.let { n -> processInfoMap[it.pid] = n }
}
catch (t: Throwable) {
logger.warn("Error fetching Unity process info: ${it.commandLine}", t)
}
}
// If we failed to get project name from the command line, try and get it from the working directory
if (processInfoMap.size != processList.size || processInfoMap.any { it.value.projectName == null }) {
fillProjectNamesFromWorkingDirectory(processList, processInfoMap)
}
return processInfoMap
}
private fun assertNotDispatchThread() {
val application = ApplicationManager.getApplication()
if (application != null && application.isInternal) {
if (application.isDispatchThread) {
throw RuntimeException("Access not allowed on event dispatch thread")
}
}
}
private fun getProjectNameFromEditorInstanceJson(processInfo: ProcessInfo, project: Project): String? {
val editorInstanceJson = EditorInstanceJson.getInstance(project)
return if (editorInstanceJson.status == EditorInstanceJsonStatus.Valid && editorInstanceJson.contents?.process_id == processInfo.pid) {
project.name
} else null
}
private fun parseProcessInfoFromCommandLine(processInfo: ProcessInfo, canonicalProjectName: String?): UnityProcessInfo? {
var projectName = canonicalProjectName
var name: String? = null
var umpProcessRole: String? = null
var umpWindowTitle: String? = null
val tokens = tokenizeCommandLine(processInfo)
var i = 0
while (i < tokens.size - 1) { // -1 for the argument + argument value
val token = tokens[i++]
if (projectName == null && (token.equals("-projectPath", true) || token.equals("-createProject", true))) {
// For an unquoted command line, the next token isn't guaranteed to be the whole path. If the path
// contains a space-hyphen-char (e.g. `-projectPath /Users/matt/Projects/space game -is great -yeah`)
// they will be split as multiple tokens. Concatenate subsequent tokens until we have the longest valid
// path. Note that the arguments and values are all separated by a single space. Any other whitespace
// is still part of the string
var path = tokens[i++]
var lastValid = if (File(path).isDirectory) path else ""
var j = i
while (j < tokens.size) {
path += " " + tokens[j++]
if (File(path).isDirectory) {
lastValid = path
i = j
}
}
projectName = getProjectNameFromPath(StringUtil.unquoteString(lastValid))
}
else if (token.equals("-name", true)) {
name = StringUtil.unquoteString(tokens[i++])
}
else if (token.equals("-ump-process-role", true)) {
umpProcessRole = StringUtil.unquoteString(tokens[i++])
}
else if (token.equals("-ump-window-title", true)) {
umpWindowTitle = StringUtil.unquoteString(tokens[i++])
}
}
if (projectName == null && name == null && umpWindowTitle == null && umpProcessRole == null) {
return null
}
return UnityProcessInfo(projectName, name ?: umpWindowTitle ?: umpProcessRole)
}
private fun tokenizeCommandLine(processInfo: ProcessInfo): List<String> {
return tokenizeQuotedCommandLine(processInfo)
?: tokenizeUnquotedCommandLine(processInfo)
}
private fun tokenizeQuotedCommandLine(processInfo: ProcessInfo): List<String>? {
return getQuotedCommandLine(processInfo)?.let {
val tokens = mutableListOf<String>()
val tokenizer = CommandLineTokenizer(it)
while(tokenizer.hasMoreTokens())
tokens.add(tokenizer.nextToken())
tokens
}
}
private fun tokenizeUnquotedCommandLine(processInfo: ProcessInfo): List<String> {
// Split the command line into arguments
// We assume an argument starts with a hyphen and has no whitespace in the name. Empirically, this is true
// So split on ^- or \s-
// Each chunk should now be an arg and an argvalue, e.g. `-name Foo`
// Split on the first whitespace. The argument value should be correct, but might require concatenating if
// the value pathologically contains a \s-[^\s] sequence
// E.g. `-createProject /Users/matt/my interesting -project` would split into the following tokens:
// "-createProject" "/Users/matt/my interesting" "-project"
// The single whitespace between arguments and between the argument and value is not captured, so must be added
// back if concatenating
val tokens = mutableListOf<String>()
processInfo.commandLine.split("(^|\\s)(?=-[^\\s])".toRegex()).forEach {
val whitespace = it.indexOf(' ')
if (whitespace == -1) {
tokens.add(it)
}
else {
tokens.add(it.substring(0, whitespace))
tokens.add(it.substring(whitespace + 1))
}
}
return tokens
}
private fun getQuotedCommandLine(processInfo: ProcessInfo): String? {
return when {
SystemInfo.isWindows -> processInfo.commandLine // Already quoted correctly
SystemInfo.isMac -> null // We can't add quotes, and can't easily get an unquoted version
SystemInfo.isUnix -> {
try {
// ProcessListUtil.getProcessListOnUnix already reads /proc/{pid}/cmdline, but doesn't quote
// arguments that contain spaces. https://youtrack.jetbrains.com/issue/IDEA-229022
val procfsCmdline = File("/proc/${processInfo.pid}/cmdline")
val cmdlineString = String(FileUtil.loadFileBytes(procfsCmdline), StandardCharsets.UTF_8)
val cmdlineParts = StringUtil.split(cmdlineString, "\u0000")
return cmdlineParts.joinToString(" ") {
var s = it
if (!StringUtil.isQuotedString(s)) {
if (s.contains('\\')) {
s = StringUtil.escapeBackSlashes(s)
}
if (s.contains('\"')) {
s = StringUtil.escapeQuotes(s)
}
if (s.contains(' ')) {
s = StringUtil.wrapWithDoubleQuote(s)
}
}
return@joinToString s
}
} catch (t: Throwable) {
logger.warn("Error while quoting command line: ${processInfo.commandLine}", t)
}
return null
}
else -> null
}
}
private fun getProjectNameFromPath(projectPath: String): String = Paths.get(projectPath).fileName.toString()
private fun fillProjectNamesFromWorkingDirectory(processList: List<ProcessInfo>, projectNames: MutableMap<Int, UnityProcessInfo>) {
// Windows requires reading process memory. Unix is so much nicer.
if (SystemInfo.isWindows) return
try {
val processIds = processList.filter { !projectNames.containsKey(it.pid) }.joinToString(",") { it.pid.toString() }
val command = when {
SystemInfo.isMac -> "/usr/sbin/lsof"
else -> "/usr/bin/lsof"
}
val output = ExecUtil.execAndGetOutput(GeneralCommandLine(command, "-a", "-p", processIds, "-d", "cwd", "-Fn"))
if (output.exitCode == 0) {
val stdout = output.stdoutLines
// p{PID}
// fcwd
// n{CWD}
for (i in 0 until stdout.size step 3) {
val pid = stdout[i].substring(1).toInt()
val cwd = getProjectNameFromPath(stdout[i + 2].substring(1))
// We might have found the project name for this process from the command line. Even if we had, the
// working directory should be the same as the command line project name
if (!projectNames.containsKey(pid)) {
projectNames[pid] = UnityProcessInfo(cwd, projectNames[pid]?.roleName)
}
}
}
}
catch (t: Throwable) {
logger.warn("Error fetching current directory", t)
}
}
fun isDebuggerAttached(host: String, port: Int, project: Project): Boolean {
val debuggerManager = XDebuggerManager.getInstance(project)
return debuggerManager.debugSessions.any {
val profile = it.runProfile
return if (profile is RemoteConfiguration) {
// Note that this is best effort - host values must match exactly. "localhost" and "127.0.0.1" are not the same
profile.address == host && profile.port == port
}
else false
}
}
}
| apache-2.0 | 796d83041b27487533fcd012b3f07f0e | 48.109489 | 156 | 0.617048 | 4.822939 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/features/automatic_machines/TileEntities.kt | 2 | 7627 | package com.cout970.magneticraft.features.automatic_machines
import com.cout970.magneticraft.api.internal.pneumatic.PneumaticBoxStorage
import com.cout970.magneticraft.api.internal.pneumatic.PneumaticBuffer
import com.cout970.magneticraft.misc.RegisterTileEntity
import com.cout970.magneticraft.misc.block.getFacing
import com.cout970.magneticraft.misc.block.getOrientation
import com.cout970.magneticraft.misc.block.getOrientationCentered
import com.cout970.magneticraft.misc.fluid.Tank
import com.cout970.magneticraft.misc.inventory.Inventory
import com.cout970.magneticraft.misc.tileentity.DoNotRemove
import com.cout970.magneticraft.misc.tileentity.TimeCache
import com.cout970.magneticraft.misc.tileentity.shouldTick
import com.cout970.magneticraft.misc.vector.*
import com.cout970.magneticraft.registry.FLUID_HANDLER
import com.cout970.magneticraft.registry.getOrNull
import com.cout970.magneticraft.systems.config.Config
import com.cout970.magneticraft.systems.tileentities.TileBase
import com.cout970.magneticraft.systems.tilemodules.*
import net.minecraft.block.Block
import net.minecraft.util.EnumFacing
import net.minecraft.util.ITickable
import net.minecraft.util.math.AxisAlignedBB
import net.minecraftforge.fluids.FluidRegistry
import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.fluids.capability.IFluidHandler
/**
* Created by cout970 on 2017/08/10.
*/
@RegisterTileEntity("feeding_trough")
class TileFeedingTrough : TileBase(), ITickable {
val facing: EnumFacing get() = getBlockState().getOrientationCentered()
val inventory = Inventory(1)
val invModule = ModuleInventory(inventory, capabilityFilter = { null })
val moduleFeedingTrough = ModuleFeedingTrough(inventory)
init {
initModules(moduleFeedingTrough, invModule)
}
@DoNotRemove
override fun update() {
super.update()
}
override fun getRenderBoundingBox(): AxisAlignedBB {
val dir = facing.toBlockPos()
return super.getRenderBoundingBox().expand(dir.xd, dir.yd, dir.zd)
}
}
@RegisterTileEntity("conveyor_belt")
class TileConveyorBelt : TileBase(), ITickable {
val facing: EnumFacing get() = getBlockState().getOrientation()
val conveyorModule = ModuleConveyorBelt({ facing })
init {
initModules(conveyorModule)
}
@DoNotRemove
override fun update() {
super.update()
}
override fun getRenderBoundingBox(): AxisAlignedBB {
return pos createAABBUsing pos.add(1, 2, 1)
}
}
@RegisterTileEntity("inserter")
class TileInserter : TileBase(), ITickable {
val facing: EnumFacing get() = getBlockState().getOrientation()
val filters = Inventory(9)
val inventory: Inventory = Inventory(3) { _, _ -> inserterModule.updateUpgrades() }
val invModule = ModuleInventory(inventory, capabilityFilter = { null })
val openGui = ModuleOpenGui()
val inserterModule = ModuleInserter({ facing }, inventory, filters)
init {
initModules(inserterModule, invModule, openGui)
}
@DoNotRemove
override fun update() {
super.update()
}
}
@RegisterTileEntity("water_generator")
class TileWaterGenerator : TileBase(), ITickable {
val cache: MutableList<IFluidHandler> = mutableListOf()
val tank = object : Tank(32_000) {
init {
onContentsChanged()
}
override fun onContentsChanged() {
fluid = FluidRegistry.getFluidStack("water", 32_000)
}
}
val fluidModule = ModuleFluidHandler(tank)
val bucketIoModule = ModuleBucketIO(tank)
init {
initModules(bucketIoModule, fluidModule)
}
@DoNotRemove
override fun update() {
super.update()
if (container.shouldTick(20)) {
cache.clear()
enumValues<EnumFacing>().forEach { dir ->
val tile = world.getTileEntity(pos.offset(dir))
val handler = tile?.getOrNull(FLUID_HANDLER, dir.opposite) ?: return@forEach
cache.add(handler)
}
}
cache.forEach { handler ->
val water = FluidStack(FluidRegistry.WATER, Config.waterGeneratorPerTickWater)
val amount = handler.fill(water, false)
if (amount > 0) {
handler.fill(FluidStack(water, amount), true)
}
}
}
}
abstract class AbstractTileTube : TileBase() {
val flow = PneumaticBoxStorage()
@Suppress("LeakingThis")
val tubeModule = ModulePneumaticTube(flow, getWeight())
val connections = TimeCache(this.ref, 10) { tubeModule.getConnections() }
val down = { connections()[0] }
val up = { connections()[1] }
val north = { connections()[2] }
val south = { connections()[3] }
val west = { connections()[4] }
val east = { connections()[5] }
abstract fun getWeight(): Int
init {
initModules(tubeModule)
}
override fun getRenderBoundingBox(): AxisAlignedBB {
return Block.FULL_BLOCK_AABB.offset(pos)
}
}
@RegisterTileEntity("pneumatic_tube")
class TilePneumaticTube : AbstractTileTube(), ITickable {
override fun getWeight(): Int = 0
@DoNotRemove
override fun update() {
super.update()
}
}
@RegisterTileEntity("pneumatic_restriction_tube")
class TilePneumaticRestrictionTube : AbstractTileTube(), ITickable {
override fun getWeight(): Int = 100
@DoNotRemove
override fun update() {
super.update()
}
}
@RegisterTileEntity("relay")
class TileRelay : TileBase(), ITickable {
val facing: EnumFacing get() = getBlockState().getFacing()
val inventory = Inventory(9)
val buffer = PneumaticBuffer()
val invModule = ModuleInventory(inventory, sideFilter = { it != facing })
val endpointModule = ModulePneumaticEndpoint(buffers = listOf(buffer), getInfo = { BufferInfo(false, facing) })
val relayModule = ModuleRelay(inventory, buffer)
init {
initModules(endpointModule, invModule, relayModule)
}
@DoNotRemove
override fun update() {
super.update()
}
}
@RegisterTileEntity("filter")
class TileFilter : TileBase(), ITickable {
val facing: EnumFacing get() = getBlockState().getFacing()
val inventory = Inventory(9)
val inputBuffer = PneumaticBuffer()
val outputBuffer = PneumaticBuffer()
val itemFilter = ModuleItemFilter(inventory)
val filterModule = ModuleFilter(inputBuffer, outputBuffer, itemFilter)
val endpointModule = ModulePneumaticEndpoint(
buffers = listOf(inputBuffer, outputBuffer),
getInfo = { buff ->
if (buff == inputBuffer) {
BufferInfo(true, facing.opposite, filterModule::canInsert)
} else {
BufferInfo(false, facing)
}
}
)
init {
initModules(endpointModule, filterModule, itemFilter)
}
@DoNotRemove
override fun update() {
super.update()
}
}
// Nice to have: filter to only extract certain items
@RegisterTileEntity("transposer")
class TileTransposer : TileBase(), ITickable {
val facing: EnumFacing get() = getBlockState().getFacing()
val buffer = PneumaticBuffer()
val inventory = Inventory(9)
val itemFilter = ModuleItemFilter(inventory)
val endpointModule = ModulePneumaticEndpoint(buffers = listOf(buffer), getInfo = { BufferInfo(false, facing) })
val transposerModule = ModuleTransposer(buffer, itemFilter, { facing })
init {
initModules(endpointModule, transposerModule, itemFilter)
}
@DoNotRemove
override fun update() {
super.update()
}
} | gpl-2.0 | cb27c4fc33b8aee691725f2e727bc179 | 28.003802 | 115 | 0.687164 | 4.363272 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/browser/integration/BrowserToolbarIntegration.kt | 1 | 16111 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.browser.integration
import android.graphics.Color
import android.widget.LinearLayout
import androidx.annotation.VisibleForTesting
import androidx.appcompat.content.res.AppCompatResources
import androidx.compose.material.Text
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.children
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.mapNotNull
import mozilla.components.browser.state.selector.findCustomTabOrSelectedTab
import mozilla.components.browser.state.store.BrowserStore
import mozilla.components.browser.toolbar.BrowserToolbar
import mozilla.components.browser.toolbar.display.DisplayToolbar.Indicators
import mozilla.components.compose.cfr.CFRPopup
import mozilla.components.compose.cfr.CFRPopupProperties
import mozilla.components.feature.customtabs.CustomTabsToolbarFeature
import mozilla.components.feature.session.SessionUseCases
import mozilla.components.feature.tabs.CustomTabsUseCases
import mozilla.components.feature.tabs.toolbar.TabCounterToolbarButton
import mozilla.components.feature.toolbar.ToolbarBehaviorController
import mozilla.components.feature.toolbar.ToolbarPresenter
import mozilla.components.lib.state.ext.flowScoped
import mozilla.components.support.base.feature.LifecycleAwareFeature
import mozilla.components.support.ktx.android.view.hideKeyboard
import mozilla.components.support.ktx.kotlinx.coroutines.flow.ifChanged
import org.mozilla.focus.GleanMetrics.TabCount
import org.mozilla.focus.GleanMetrics.TrackingProtection
import org.mozilla.focus.R
import org.mozilla.focus.ext.components
import org.mozilla.focus.ext.isCustomTab
import org.mozilla.focus.ext.isTablet
import org.mozilla.focus.ext.settings
import org.mozilla.focus.fragment.BrowserFragment
import org.mozilla.focus.menu.browser.CustomTabMenu
import org.mozilla.focus.nimbus.FocusNimbus
import org.mozilla.focus.state.AppAction
import org.mozilla.focus.telemetry.TelemetryWrapper
import org.mozilla.focus.ui.theme.focusTypography
@Suppress("LongParameterList", "LargeClass", "TooManyFunctions")
class BrowserToolbarIntegration(
private val store: BrowserStore,
private val toolbar: BrowserToolbar,
private val fragment: BrowserFragment,
controller: BrowserMenuController,
sessionUseCases: SessionUseCases,
customTabsUseCases: CustomTabsUseCases,
private val onUrlLongClicked: () -> Boolean,
private val eraseActionListener: () -> Unit,
private val tabCounterListener: () -> Unit,
private val customTabId: String? = null,
inTesting: Boolean = false,
) : LifecycleAwareFeature {
private val presenter = ToolbarPresenter(
toolbar,
store,
customTabId,
)
@VisibleForTesting
internal var securityIndicatorScope: CoroutineScope? = null
@VisibleForTesting
internal var eraseTabsCfrScope: CoroutineScope? = null
@VisibleForTesting
internal var trackingProtectionCfrScope: CoroutineScope? = null
private var tabsCounterScope: CoroutineScope? = null
private var customTabsFeature: CustomTabsToolbarFeature? = null
private var navigationButtonsIntegration: NavigationButtonsIntegration? = null
private val eraseAction = BrowserToolbar.Button(
imageDrawable = AppCompatResources.getDrawable(
toolbar.context,
R.drawable.mozac_ic_delete,
)!!,
contentDescription = toolbar.context.getString(R.string.content_description_erase),
iconTintColorResource = R.color.primaryText,
listener = {
val openedTabs = store.state.tabs.size
TabCount.eraseButtonTapped.record(TabCount.EraseButtonTappedExtra(openedTabs))
TelemetryWrapper.eraseEvent()
eraseActionListener.invoke()
},
)
private val tabsAction = TabCounterToolbarButton(
lifecycleOwner = fragment,
showTabs = {
toolbar.hideKeyboard()
tabCounterListener.invoke()
},
store = store,
)
@VisibleForTesting
internal var toolbarController = ToolbarBehaviorController(toolbar, store, customTabId)
init {
val context = toolbar.context
toolbar.display.apply {
colors = colors.copy(
hint = ContextCompat.getColor(toolbar.context, R.color.urlBarHintText),
securityIconInsecure = Color.TRANSPARENT,
text = ContextCompat.getColor(toolbar.context, R.color.primaryText),
menu = ContextCompat.getColor(toolbar.context, R.color.primaryText),
)
addTrackingProtectionIndicator()
displayIndicatorSeparator = false
setOnSiteSecurityClickedListener {
TrackingProtection.toolbarShieldClicked.add()
fragment.showTrackingProtectionPanel()
}
onUrlClicked = {
fragment.edit()
false // Do not switch to edit mode
}
setOnUrlLongClickListener { onUrlLongClicked() }
icons = icons.copy(
trackingProtectionTrackersBlocked = AppCompatResources.getDrawable(
context,
R.drawable.mozac_ic_shield,
)!!,
trackingProtectionNothingBlocked = AppCompatResources.getDrawable(
context,
R.drawable.mozac_ic_shield,
)!!,
trackingProtectionException = AppCompatResources.getDrawable(
context,
R.drawable.mozac_ic_shield_disabled,
)!!,
)
}
toolbar.display.setOnTrackingProtectionClickedListener {
TrackingProtection.toolbarShieldClicked.add()
fragment.showTrackingProtectionPanel()
}
if (customTabId != null) {
val menu = CustomTabMenu(
context = fragment.requireContext(),
store = store,
currentTabId = customTabId,
onItemTapped = { controller.handleMenuInteraction(it) },
)
customTabsFeature = CustomTabsToolbarFeature(
store,
toolbar,
sessionId = customTabId,
useCases = customTabsUseCases,
menuBuilder = menu.menuBuilder,
window = fragment.activity?.window,
menuItemIndex = menu.menuBuilder.items.size - 1,
closeListener = { fragment.closeCustomTab() },
updateToolbarBackground = true,
forceActionButtonTinting = false,
)
}
val isCustomTab = store.state.findCustomTabOrSelectedTab(customTabId)?.isCustomTab()
if (context.isTablet() && isCustomTab == false) {
navigationButtonsIntegration = NavigationButtonsIntegration(
context,
store,
toolbar,
sessionUseCases,
customTabId,
)
}
if (isCustomTab == false) {
toolbar.addNavigationAction(eraseAction)
if (!inTesting) {
setUrlBackground()
}
}
}
// Use the same background for display/edit modes.
private fun setUrlBackground() {
val urlBackground = ResourcesCompat.getDrawable(
fragment.resources,
R.drawable.toolbar_url_background,
fragment.context?.theme,
)
toolbar.display.setUrlBackground(urlBackground)
}
private fun setBrowserActionButtons() {
tabsCounterScope = store.flowScoped { flow ->
flow.ifChanged { state -> state.tabs.size > 1 }
.collect { state ->
if (state.tabs.size > 1) {
toolbar.addBrowserAction(tabsAction)
} else {
toolbar.removeBrowserAction(tabsAction)
}
}
}
}
override fun start() {
presenter.start()
toolbarController.start()
customTabsFeature?.start()
navigationButtonsIntegration?.start()
observerSecurityIndicatorChanges()
if (store.state.findCustomTabOrSelectedTab(customTabId)?.isCustomTab() == false) {
setBrowserActionButtons()
observeEraseCfr()
}
observeTrackingProtectionCfr()
}
@VisibleForTesting
internal fun observeEraseCfr() {
eraseTabsCfrScope = fragment.components?.appStore?.flowScoped { flow ->
flow.mapNotNull { state -> state.showEraseTabsCfr }
.ifChanged()
.collect { showEraseCfr ->
if (showEraseCfr) {
val eraseActionView =
toolbar.findViewById<LinearLayout>(R.id.mozac_browser_toolbar_navigation_actions)
.children
.last()
CFRPopup(
anchor = eraseActionView,
properties = CFRPopupProperties(
popupWidth = 256.dp,
popupAlignment = CFRPopup.PopupAlignment.INDICATOR_CENTERED_IN_ANCHOR,
popupBodyColors = listOf(
ContextCompat.getColor(
fragment.requireContext(),
R.color.cfr_pop_up_shape_end_color,
),
ContextCompat.getColor(
fragment.requireContext(),
R.color.cfr_pop_up_shape_start_color,
),
),
dismissButtonColor = ContextCompat.getColor(
fragment.requireContext(),
R.color.cardview_light_background,
),
popupVerticalOffset = 0.dp,
),
onDismiss = { onDismissEraseTabsCfr() },
text = {
Text(
style = focusTypography.cfrTextStyle,
text = fragment.getString(R.string.cfr_for_toolbar_delete_icon2),
color = colorResource(R.color.cfr_text_color),
)
},
).apply {
show()
}
}
}
}
}
private fun onDismissEraseTabsCfr() {
fragment.components?.appStore?.dispatch(AppAction.ShowEraseTabsCfrChange(false))
}
@VisibleForTesting
internal fun observeTrackingProtectionCfr() {
trackingProtectionCfrScope = fragment.components?.appStore?.flowScoped { flow ->
flow.mapNotNull { state -> state.showTrackingProtectionCfrForTab }
.ifChanged()
.collect { showTrackingProtectionCfrForTab ->
if (showTrackingProtectionCfrForTab[store.state.selectedTabId] == true) {
CFRPopup(
anchor = toolbar.findViewById(
R.id.mozac_browser_toolbar_tracking_protection_indicator,
),
properties = CFRPopupProperties(
popupWidth = 256.dp,
popupAlignment = CFRPopup.PopupAlignment.INDICATOR_CENTERED_IN_ANCHOR,
popupBodyColors = listOf(
ContextCompat.getColor(
fragment.requireContext(),
R.color.cfr_pop_up_shape_end_color,
),
ContextCompat.getColor(
fragment.requireContext(),
R.color.cfr_pop_up_shape_start_color,
),
),
dismissButtonColor = ContextCompat.getColor(
fragment.requireContext(),
R.color.cardview_light_background,
),
popupVerticalOffset = 0.dp,
),
onDismiss = { onDismissTrackingProtectionCfr() },
text = {
Text(
style = focusTypography.cfrTextStyle,
text = fragment.getString(R.string.cfr_for_toolbar_shield_icon2),
color = colorResource(R.color.cfr_text_color),
)
},
).apply {
show()
}
}
}
}
}
private fun onDismissTrackingProtectionCfr() {
store.state.selectedTabId?.let {
fragment.components?.appStore?.dispatch(AppAction.ShowTrackingProtectionCfrChange(mapOf(it to false)))
}
fragment.requireContext().settings.shouldShowCfrForTrackingProtection = false
FocusNimbus.features.onboarding.recordExposure()
fragment.components?.appStore?.dispatch(AppAction.ShowEraseTabsCfrChange(true))
}
@VisibleForTesting
internal fun observerSecurityIndicatorChanges() {
securityIndicatorScope = store.flowScoped { flow ->
flow.mapNotNull { state -> state.findCustomTabOrSelectedTab(customTabId) }
.ifChanged { tab -> tab.content.securityInfo }
.collect {
val secure = it.content.securityInfo.secure
val url = it.content.url
if (secure && Indicators.SECURITY in toolbar.display.indicators) {
addTrackingProtectionIndicator()
} else if (!secure && Indicators.SECURITY !in toolbar.display.indicators &&
!url.trim().startsWith("about:")
) {
addSecurityIndicator()
}
}
}
}
override fun stop() {
presenter.stop()
toolbarController.stop()
customTabsFeature?.stop()
navigationButtonsIntegration?.stop()
stopObserverSecurityIndicatorChanges()
toolbar.removeBrowserAction(tabsAction)
tabsCounterScope?.cancel()
stopObserverEraseTabsCfrChanges()
stopObserverTrackingProtectionCfrChanges()
}
@VisibleForTesting
internal fun stopObserverTrackingProtectionCfrChanges() {
trackingProtectionCfrScope?.cancel()
}
@VisibleForTesting
internal fun stopObserverEraseTabsCfrChanges() {
eraseTabsCfrScope?.cancel()
}
@VisibleForTesting
internal fun stopObserverSecurityIndicatorChanges() {
securityIndicatorScope?.cancel()
}
@VisibleForTesting
internal fun addSecurityIndicator() {
toolbar.display.indicators = listOf(Indicators.SECURITY)
}
@VisibleForTesting
internal fun addTrackingProtectionIndicator() {
toolbar.display.indicators = listOf(Indicators.TRACKING_PROTECTION)
}
}
| mpl-2.0 | 1dd46a62421e3bcc7621346c1e61fa60 | 39.684343 | 114 | 0.575942 | 5.674886 | false | false | false | false |
wireapp/wire-android | app/src/main/kotlin/com/waz/zclient/feature/backup/messages/MessagesBackUpDataMapper.kt | 1 | 2344 | package com.waz.zclient.feature.backup.messages
import com.waz.zclient.feature.backup.BackUpDataMapper
import com.waz.zclient.storage.db.messages.MessagesEntity
class MessagesBackUpDataMapper : BackUpDataMapper<MessagesBackUpModel, MessagesEntity> {
override fun fromEntity(entity: MessagesEntity): MessagesBackUpModel = MessagesBackUpModel(
id = entity.id,
conversationId = entity.conversationId,
messageType = entity.messageType,
userId = entity.userId,
clientId = entity.clientId,
errorCode = entity.errorCode,
content = entity.content,
protos = entity.protos,
time = entity.time,
firstMessage = entity.firstMessage,
members = entity.members,
recipient = entity.recipient,
email = entity.email,
name = entity.name,
messageState = entity.messageState,
contentSize = entity.contentSize,
localTime = entity.localTime,
editTime = entity.editTime,
ephemeral = entity.ephemeral,
expiryTime = entity.expiryTime,
expired = entity.expired,
duration = entity.duration,
quote = entity.quote,
quoteValidity = entity.quoteValidity,
forceReadReceipts = entity.forceReadReceipts,
assetId = entity.assetId
)
override fun toEntity(model: MessagesBackUpModel): MessagesEntity = MessagesEntity(
id = model.id,
conversationId = model.conversationId,
messageType = model.messageType,
userId = model.userId,
clientId = model.clientId,
errorCode = model.errorCode,
content = model.content,
protos = model.protos,
time = model.time,
firstMessage = model.firstMessage,
members = model.members,
recipient = model.recipient,
email = model.email,
name = model.name,
messageState = model.messageState,
contentSize = model.contentSize,
localTime = model.localTime,
editTime = model.editTime,
ephemeral = model.ephemeral,
expiryTime = model.expiryTime,
expired = model.expired,
duration = model.duration,
quote = model.quote,
quoteValidity = model.quoteValidity,
forceReadReceipts = model.forceReadReceipts,
assetId = model.assetId
)
}
| gpl-3.0 | 71de0975ab9c62c24de4db6741298e94 | 35.061538 | 95 | 0.65401 | 4.725806 | false | false | false | false |
Dreamersoul/FastHub | app/src/main/java/com/fastaccess/ui/modules/theme/ThemeActivity.kt | 1 | 3568 | package com.fastaccess.ui.modules.theme
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewAnimationUtils
import com.fastaccess.R
import com.fastaccess.data.dao.FragmentPagerAdapterModel
import com.fastaccess.helper.PrefGetter
import com.fastaccess.ui.adapter.FragmentsPagerAdapter
import com.fastaccess.ui.base.BaseActivity
import com.fastaccess.ui.base.mvp.BaseMvp
import com.fastaccess.ui.base.mvp.presenter.BasePresenter
import com.fastaccess.ui.modules.theme.fragment.ThemeFragmentMvp
import com.fastaccess.ui.widgets.CardsPagerTransformerBasic
import com.fastaccess.ui.widgets.ViewPagerView
import com.fastaccess.ui.widgets.bindView
/**
* Created by Kosh on 08 Jun 2017, 10:34 PM
*/
class ThemeActivity : BaseActivity<BaseMvp.FAView, BasePresenter<BaseMvp.FAView>>(), ThemeFragmentMvp.ThemeListener {
val pager: ViewPagerView by bindView(R.id.pager)
val parentLayout: View by bindView(R.id.parentLayout)
override fun layout(): Int {
return R.layout.theme_viewpager
}
override fun isTransparent(): Boolean {
return false
}
override fun canBack(): Boolean {
return true
}
override fun isSecured(): Boolean {
return false
}
override fun providePresenter(): BasePresenter<BaseMvp.FAView> {
return BasePresenter()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
pager.adapter = FragmentsPagerAdapter(supportFragmentManager, FragmentPagerAdapterModel.buildForTheme())
pager.clipToPadding = false
val partialWidth = resources.getDimensionPixelSize(R.dimen.spacing_s_large)
val pageMargin = resources.getDimensionPixelSize(R.dimen.spacing_normal)
val pagerPadding = partialWidth + pageMargin
pager.pageMargin = pageMargin
pager.setPageTransformer(true, CardsPagerTransformerBasic(4, 10))
pager.setPadding(pagerPadding, pagerPadding, pagerPadding, pagerPadding)
if (savedInstanceState == null) {
val theme = PrefGetter.getThemeType(this)
pager.setCurrentItem(theme - 1, true)
}
}
override fun onChangePrimaryDarkColor(color: Int, darkIcons: Boolean) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val view = window.decorView
view.systemUiVisibility = if (darkIcons) View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR else view.systemUiVisibility and View
.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
}
val cx = parentLayout.width / 2
val cy = parentLayout.height / 2
if (parentLayout.isAttachedToWindow) {
val finalRadius = Math.hypot(cx.toDouble(), cy.toDouble()).toFloat()
val anim = ViewAnimationUtils.createCircularReveal(parentLayout, cx, cy, 0f, finalRadius)
anim.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
super.onAnimationEnd(animation)
window?.statusBarColor = color
}
})
parentLayout.setBackgroundColor(color)
anim.start()
} else {
parentLayout.setBackgroundColor(color)
window.statusBarColor = color
}
}
override fun onThemeApplied() {
showMessage(R.string.success, R.string.change_theme_warning)
onThemeChanged()
}
} | gpl-3.0 | 94f32e69942e49f758a1b7276fbf57b8 | 35.793814 | 127 | 0.695908 | 4.713342 | false | false | false | false |
leandroBorgesFerreira/WizardForm | app/src/main/java/br/com/leandroferreira/wizardform/MainActivity.kt | 1 | 1214 | package br.com.leandroferreira.wizardform
import android.databinding.DataBindingUtil
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import br.com.leandroferreira.wizard_forms.contract.WizardNavigator
import br.com.leandroferreira.wizardform.databinding.ActivityMainBinding
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(), WizardNavigator{
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
binding.viewModel = MainViewModel(this)
}
override fun nextPage() {
if (viewPager.currentItem < viewPager.adapter.count) {
viewPager.currentItem = viewPager.currentItem + 1
}
}
override fun previousPage() {
if (viewPager.currentItem > 0) {
viewPager.currentItem = viewPager.currentItem - 1
}
}
override fun navigateToPage(page: Int) {
viewPager.currentItem = page
}
override fun cancelNavigation() {
finish()
}
override fun currentPage(): Int = viewPager.currentItem
}
| mit | 9ef9c0642664265dc9b27d8c0bd087af | 29.35 | 103 | 0.717463 | 4.687259 | false | false | false | false |
moxi/weather-app-demo | weather-app/src/main/java/rcgonzalezf/org/weather/list/WeatherListViewModel.kt | 1 | 6503 | package rcgonzalezf.org.weather.list
import android.app.Application
import android.content.Context
import android.util.Log
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.rcgonzalezf.weather.common.ServiceConfig
import org.rcgonzalezf.weather.common.models.WeatherInfo
import org.rcgonzalezf.weather.openweather.OpenWeatherApiCallback
import org.rcgonzalezf.weather.openweather.network.OpenWeatherApiRequestParameters
import rcgonzalezf.org.weather.R
import rcgonzalezf.org.weather.common.OnOfflineLoader
import rcgonzalezf.org.weather.common.ToggleBehavior
import rcgonzalezf.org.weather.common.analytics.AnalyticsDataCatalog
import rcgonzalezf.org.weather.common.analytics.AnalyticsEvent
import rcgonzalezf.org.weather.common.analytics.AnalyticsLifecycleObserver
import rcgonzalezf.org.weather.location.CityFromLatLongRetriever
import rcgonzalezf.org.weather.location.LocationSearch
import rcgonzalezf.org.weather.utils.UrlEncoder
import rcgonzalezf.org.weather.utils.UserNotifier
import rcgonzalezf.org.weather.utils.WeatherAppUrlEncoder
import rcgonzalezf.org.weather.utils.WeatherUtils
import java.io.UnsupportedEncodingException
import java.util.concurrent.Executor
import java.util.concurrent.Executors
class WeatherListViewModel(
private val openWeatherApiCallback: OpenWeatherApiCallback,
private val cityNameFromLatLong: CityFromLatLongRetriever,
private val toggleBehavior: ToggleBehavior,
private val app: Application,
private val userNotifier: UserNotifier,
private val serviceConfig: ServiceConfig = ServiceConfig.getInstance(),
private val urlEncoder: UrlEncoder = WeatherAppUrlEncoder(),
private val executor: Executor = Executors.newSingleThreadExecutor())
: AndroidViewModel(app), OnOfflineLoader {
companion object {
private val TAG = WeatherListViewModel::class.java.simpleName
const val OFFLINE_FILE = "OFFLINE_WEATHER"
const val FORECASTS = "FORECASTS"
}
val cityNameToSearchOnSwipe: MutableLiveData<CharSequence> by lazy {
MutableLiveData<CharSequence>()
}
val weatherInfoList: MutableLiveData<List<WeatherInfo>> by lazy {
MutableLiveData<List<WeatherInfo>>()
}
val offline: MutableLiveData<Boolean> by lazy {
MutableLiveData<Boolean>()
}
val previousForecastList: List<WeatherInfo>?
get() {
// TODO Room and LiveData?
val sharedPreferences = app.getSharedPreferences(OFFLINE_FILE, 0)
val serializedData = sharedPreferences.getString(FORECASTS, null)
var storedData: List<WeatherInfo>? = null
if (serializedData != null) {
storedData = Gson()
.fromJson(serializedData, object : TypeToken<List<WeatherInfo?>?>() {}.type)
}
return storedData
}
fun updateCityNameForSwipeToRefresh(cityName: CharSequence) {
cityNameToSearchOnSwipe.value = cityName
}
override fun loadOldData(weatherInfoList: List<WeatherInfo>?) {
this.weatherInfoList.value = weatherInfoList
this.offline.value = true
}
fun searchByQuery(query: String, userInput: CharSequence) {
toggleBehavior.toggle()
val weatherRepository = serviceConfig
.getWeatherRepository<OpenWeatherApiRequestParameters, OpenWeatherApiCallback?>()
weatherRepository.findWeather(
OpenWeatherApiRequestParameters.OpenWeatherApiRequestBuilder()
.withCityName(query)
.build(), openWeatherApiCallback)
val message = app.getString(R.string.searching) + " " + userInput + "..."
userNotifier.notify(message)
updateCityNameForSwipeToRefresh(userInput)
}
fun cityNameFromLatLon(lat: Double, lon: Double): String? {
return cityNameFromLatLong.getFromLatLong(lat, lon)
}
fun saveForecastList(weatherInfoList: List<WeatherInfo>) {
executor.execute {
// TODO Replace with Room?
val prefs = app.getSharedPreferences(OFFLINE_FILE, Context.MODE_PRIVATE)
val editor = prefs.edit()
editor.putString(FORECASTS, Gson().toJson(weatherInfoList))
editor.apply()
}
}
@VisibleForTesting
fun searchByManualInput(userInput: CharSequence) {
val query: String
query = try {
urlEncoder.encodeUtf8(userInput.toString())
} catch (e: UnsupportedEncodingException) {
Log.e(TAG, "Can't encode URL", e)
userNotifier.notify("${app.getString(R.string.invalid_input)}: $userInput...")
return
}
if (!WeatherUtils.hasInternetConnection(app)) {
userNotifier.notify(app.getString(R.string.no_internet_msg))
loadOldData(previousForecastList)
} else {
offline.value = false
searchByQuery(query, userInput)
}
}
inner class WeatherListLocationSearch(val analytics: AnalyticsLifecycleObserver) : LocationSearch {
override fun searchByLatLon(lat: Double, lon: Double) {
toggleBehavior.toggle()
val weatherRepository = serviceConfig.getWeatherRepository<
OpenWeatherApiRequestParameters, OpenWeatherApiCallback?>()
val cityName = cityNameFromLatLon(lat, lon)
if (cityName == null) {
weatherRepository.findWeather(
OpenWeatherApiRequestParameters.OpenWeatherApiRequestBuilder().withLatLon(lat, lon).build(),
openWeatherApiCallback)
analytics.trackOnActionEvent(
AnalyticsEvent(AnalyticsDataCatalog.WeatherListActivity.LOCATION_SEARCH,
"Geocoder Failure"))
} else {
weatherRepository.findWeather(
OpenWeatherApiRequestParameters.OpenWeatherApiRequestBuilder().withCityName(cityName).build(),
openWeatherApiCallback)
analytics.trackOnActionEvent(
AnalyticsEvent(
AnalyticsDataCatalog.WeatherListActivity.LOCATION_SEARCH, cityName))
updateCityNameForSwipeToRefresh(cityName)
}
}
}
}
| mit | a2e7b4709275fe324f6d77a8486be165 | 41.782895 | 118 | 0.687375 | 5.161111 | false | false | false | false |
google/horologist | media-ui/src/debug/java/com/google/android/horologist/media/ui/components/PlayPauseProgressButtonPreview.kt | 1 | 2815 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:OptIn(ExperimentalHorologistMediaUiApi::class)
package com.google.android.horologist.media.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
@Preview(
"Enabled - Playing - Progress 0%",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun PlayPauseProgressButtonPreview0() {
PlayPauseProgressButton(
onPlayClick = {},
onPauseClick = {},
enabled = true,
playing = true,
percent = 0f
)
}
@Preview(
"Disabled - Not playing - Progress 25%",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun PlayPauseProgressButtonPreview25() {
PlayPauseProgressButton(
onPlayClick = {},
onPauseClick = {},
enabled = false,
playing = false,
percent = 0.25f
)
}
@Preview(
"Disabled - Playing - Progress 75%",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun PlayPauseProgressButtonPreview75() {
PlayPauseProgressButton(
onPlayClick = {},
onPauseClick = {},
enabled = false,
playing = true,
percent = 0.75f
)
}
@Preview(
"Enabled - Not playing - Progress 100%",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun PlayPauseProgressButtonPreview100() {
PlayPauseProgressButton(
onPlayClick = {},
onPauseClick = {},
enabled = true,
playing = false,
percent = 1f
)
}
@Preview(
"On Background - Progress 50%",
backgroundColor = 0xff000000,
showBackground = true
)
@Composable
fun PlayPauseProgressButtonPreviewOnWhite() {
Box(modifier = Modifier.background(Color.DarkGray)) {
PlayPauseProgressButton(
onPlayClick = {},
onPauseClick = {},
enabled = true,
playing = false,
percent = 0.5f
)
}
}
| apache-2.0 | ae6f716aa4e54ca992c395e061a8751f | 24.825688 | 78 | 0.67389 | 4.482484 | false | false | false | false |
JavaEden/OrchidCore | plugins/OrchidKSS/src/main/kotlin/com/eden/orchid/kss/menu/StyleguidePagesMenuItemType.kt | 1 | 1697 | package com.eden.orchid.kss.menu
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.theme.menus.OrchidMenuFactory
import com.eden.orchid.api.theme.menus.MenuItem
import com.eden.orchid.kss.model.KssModel
import com.eden.orchid.kss.pages.KssPage
import javax.inject.Inject
@Description("All pages in your styleguide, optionally by section.", name = "Styleguide")
class StyleguidePagesMenuItemType
@Inject
constructor(
context: OrchidContext,
private val model: KssModel
) : OrchidMenuFactory(context, "styleguide", 100) {
@Option
@Description("The Styleguide section to get pages for.")
lateinit var section: String
override fun getMenuItems(): List<MenuItem> {
val menuItems = ArrayList<MenuItem>()
val pages = model.getSectionRoot(section)
if(pages.isNotEmpty()) {
menuItems.add(getChildMenuItem(null, pages))
}
return menuItems
}
private fun getChildMenuItem(parent: KssPage?, childPages: List<KssPage>): MenuItem {
val childMenuItems = ArrayList<MenuItem>()
val title: String?
if(parent != null) {
childMenuItems.add(MenuItem.Builder(context).page(parent).build())
title = parent.title
}
else {
title = "Styleguide Pages"
}
childPages.forEach {
childMenuItems.add(getChildMenuItem(it, it.children))
}
return MenuItem.Builder(context)
.title(title)
.children(childMenuItems)
.build()
}
}
| mit | d98eba5b71430301741a292b5684f617 | 27.762712 | 89 | 0.664113 | 4.318066 | false | false | false | false |
Commit451/YouTubeExtractor | youtubeextractor/src/main/java/com/commit451/youtubeextractor/Util.kt | 1 | 1465 | package com.commit451.youtubeextractor
import java.net.URLDecoder
import java.util.*
import java.util.regex.Pattern
internal object Util {
fun matchGroup1(pattern: String, input: String): String {
return matchGroup(pattern, input, 1)
}
fun matchGroup(pattern: String, input: String, group: Int): String {
val pat = Pattern.compile(pattern)
val mat = pat.matcher(input)
val foundMatch = mat.find()
if (foundMatch) {
return mat.group(group)
} else {
if (input.length > 1024) {
throw Exception("failed to find pattern \"$pattern")
} else {
throw Exception("failed to find pattern \"$pattern inside of $input\"")
}
}
}
fun isMatch(pattern: String, input: String): Boolean {
val pat = Pattern.compile(pattern)
val mat = pat.matcher(input)
return mat.find()
}
fun compatParseMap(input: String): Map<String, String> {
val map = HashMap<String, String>()
for (arg in input.split("&".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) {
val splitArg = arg.split("=".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (splitArg.size > 1) {
map[splitArg[0]] = URLDecoder.decode(splitArg[1], "UTF-8")
} else {
map[splitArg[0]] = ""
}
}
return map
}
} | apache-2.0 | 1c0ab8ce7c7db862cc4c289aa21615fb | 30.191489 | 97 | 0.564505 | 4.197708 | false | false | false | false |
mmartin101/GhibliAPIAndroid | app/src/mock/java/com/mmartin/ghibliapi/data/FakeFilmsRemoteDataSource.kt | 1 | 1854 | package com.mmartin.ghibliapi.data
import com.mmartin.ghibliapi.App
import com.mmartin.ghibliapi.data.model.Film
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import io.reactivex.Single
import okio.Buffer
import timber.log.Timber
import java.io.IOException
import javax.inject.Inject
/**
* Concrete implementation for getting data from the Ghibli API
*
* Created by mmartin on 9/12/17.
*/
class FakeFilmsRemoteDataSource @Inject
constructor(internal var app: App) : DataSource<Film>() {
private var moshi = Moshi.Builder().build()
private var filmList = listOf<Film>()
override val allItems: Single<List<Film>>
get() {
return Single.create<List<Film>> { sub ->
if (filmList.isEmpty()) {
try {
val inputStream = app.assets.open("json/films.json")
val type = Types.newParameterizedType(List::class.java, Film::class.java)
val jsonAdapter = moshi.adapter<List<Film>>(type)
jsonAdapter.fromJson(Buffer().readFrom(inputStream))?.let {
filmList = it
sub.onSuccess(it)
}
sub.onSuccess(filmList)
} catch (e: IOException) {
sub.onError(e)
}
} else {
Single.create<List<Film>> { emitter ->
emitter.onSuccess(filmList)
}
}
}
}
override fun getItem(id: String): Single<Film> {
return Single.create { sub ->
filmList.find { it.id == id }?.let { sub.onSuccess(it) }
?: sub.onError(NoSuchElementException("No film with that id..."))
}
}
}
| mit | 15d15fafb46cdff13eb52b01a497b9f7 | 33.981132 | 97 | 0.541532 | 4.623441 | false | false | false | false |
AllanWang/Frost-for-Facebook | app/src/main/kotlin/com/pitchedapps/frost/settings/Security.kt | 1 | 1763 | /*
* Copyright 2018 Allan Wang
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pitchedapps.frost.settings
import ca.allanwang.kau.kpref.activity.KPrefAdapterBuilder
import com.pitchedapps.frost.R
import com.pitchedapps.frost.activities.SettingsActivity
import com.pitchedapps.frost.utils.BiometricUtils
import kotlinx.coroutines.launch
/** Created by Allan Wang on 20179-05-01. */
fun SettingsActivity.getSecurityPrefs(): KPrefAdapterBuilder.() -> Unit = {
plainText(R.string.disclaimer) { descRes = R.string.security_disclaimer_info }
checkbox(
R.string.enable_biometrics,
prefs::biometricsEnabled,
{
launch {
/*
* For security, we should request authentication when:
* - enabling to ensure that it is supported
* - disabling to ensure that it is permitted
*/
BiometricUtils.authenticate(this@getSecurityPrefs, prefs, force = true).await()
prefs.biometricsEnabled = it
reloadByTitle(R.string.enable_biometrics)
}
}
) {
descRes = R.string.enable_biometrics_desc
enabler = { BiometricUtils.isSupported(this@getSecurityPrefs) }
}
}
| gpl-3.0 | 78fe2319e7694b4e164c4d0b1bcf21d8 | 35.729167 | 87 | 0.722632 | 4.227818 | false | false | false | false |
SergeyPirogov/kirk | kirk-core/src/main/kotlin/com/automation/remarks/kirk/conditions/Description.kt | 1 | 1200 | package com.automation.remarks.kirk.conditions
import com.automation.remarks.kirk.ex.DiffExtractor
/**
* Created by sergey on 24.07.17.
*/
open class Description(val actual: Any,
val expected: Any,
var diff: Boolean = true) {
open val reason: String? = "condition did not match"
open var message = """%s
expected: %s
actual: %s
"""
override fun toString(): String {
if (!diff) {
return message.format(reason, expected, actual)
}
val extractor = DiffExtractor(display(expected), display(actual))
val prefix = extractor.compactPrefix()
val suffix = extractor.compactSuffix()
return message.format(reason, "$prefix${extractor.expectedDiff()}$suffix",
"$prefix${extractor.actualDiff()}$suffix")
}
}
fun display(value: Any?): String {
return when (value) {
null -> "null"
is String -> "$value"
is Class<*> -> value.name
is Array<*> -> value.joinToString(prefix = "[", postfix = "]", transform = ::display)
is Regex -> "/$value/"
else -> value.toString()
}
} | apache-2.0 | 4f178c97da40539b4fc7d8e1c818bc12 | 27.595238 | 93 | 0.5625 | 4.411765 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/actions/styling/ToggleWrapOnTypingAction.kt | 1 | 2838 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.actions.styling
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Toggleable
import com.intellij.openapi.project.DumbAware
import com.vladsch.md.nav.actions.handlers.util.CaretContextInfo
import com.vladsch.md.nav.actions.styling.util.DisabledConditionBuilder
import com.vladsch.md.nav.actions.styling.util.MdActionUtil
import com.vladsch.md.nav.language.MdCodeStyleSettings
internal class ToggleWrapOnTypingAction : AnAction(), DumbAware, Toggleable {
override fun update(e: AnActionEvent) {
val project = e.project
val editor = MdActionUtil.findMarkdownEditor(e)
val psiFile = MdActionUtil.getPsiFile(e)
val conditionBuilder = DisabledConditionBuilder(e, this)
.notNull(project)
.notNull(editor)
.notNull(psiFile)
.and {
if (editor != null) {
CaretContextInfo.withContextOrNull(psiFile!!, editor, null, false, editor.caretModel.primaryCaret.offset) { caretContext ->
if (caretContext != null) {
val isFormatRegion = caretContext.isFormatRegion(caretContext.caretOffset)
it.and(isFormatRegion, "Caret in non-formatting region")
}
}
}
}
if (conditionBuilder.isEnabled) {
// val renderingProfile = MdRenderingProfileManager.getProfile(psiFile!!)
// val styleSettings = renderingProfile.resolvedStyleSettings
val styleSettings = MdCodeStyleSettings.getInstance(psiFile!!)
conditionBuilder.and(!(editor!!.settings.isUseSoftWraps && styleSettings.formatWithSoftWrapType.isDisabled)
, "Soft wraps are enabled"
, "Wrap on typing is disabled when soft wraps are enabled (Editor > Code Style > Markdown)"
)
Toggleable.setSelected(e.presentation, styleSettings.isWrapOnTyping)
}
conditionBuilder.done(true)
super.update(e)
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project
val psiFile = MdActionUtil.getPsiFile(e)
if (project != null && psiFile != null) {
// val renderingProfile = MdRenderingProfileManager.getProfile(psiFile)
// val styleSettings = renderingProfile.resolvedStyleSettings
val styleSettings = MdCodeStyleSettings.getInstance(psiFile)
styleSettings.isWrapOnTyping = !styleSettings.isWrapOnTyping
}
}
}
| apache-2.0 | 51e6df677f09b984a20d4d24858821c3 | 46.3 | 177 | 0.668781 | 4.901554 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/lang/core/RsPsiPattern.kt | 1 | 6367 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core
import com.intellij.patterns.*
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.patterns.StandardPatterns.or
import com.intellij.psi.*
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.ProcessingContext
import org.rust.lang.core.completion.or
import org.rust.lang.core.completion.psiElement
import org.rust.lang.core.completion.withSuperParent
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.RsElementTypes.*
import org.rust.lang.core.psi.ext.RsDocAndAttributeOwner
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.ext.RsConstantKind
import org.rust.lang.core.psi.ext.kind
/**
* Rust PSI tree patterns.
*/
object RsPsiPattern {
private val STATEMENT_BOUNDARIES = TokenSet.create(SEMICOLON, LBRACE, RBRACE)
val onStatementBeginning: PsiElementPattern.Capture<PsiElement> = psiElement().with(OnStatementBeginning())
fun onStatementBeginning(vararg startWords: String): PsiElementPattern.Capture<PsiElement> =
psiElement().with(OnStatementBeginning(*startWords))
val onStruct: PsiElementPattern.Capture<PsiElement> = onItem<RsStructItem>()
val onEnum: PsiElementPattern.Capture<PsiElement> = onItem<RsEnumItem>()
val onFn: PsiElementPattern.Capture<PsiElement> = onItem<RsFunction>()
val onMod: PsiElementPattern.Capture<PsiElement> = onItem<RsModItem>()
val onStatic: PsiElementPattern.Capture<PsiElement> = PlatformPatterns.psiElement()
.with("onStaticCondition") {
val elem = it.parent?.parent?.parent
(elem is RsConstant) && elem.kind == RsConstantKind.STATIC
}
val onStaticMut: PsiElementPattern.Capture<PsiElement> = PlatformPatterns.psiElement()
.with("onStaticMutCondition") {
val elem = it.parent?.parent?.parent
(elem is RsConstant) && elem.kind == RsConstantKind.MUT_STATIC
}
val onMacroDefinition: PsiElementPattern.Capture<PsiElement> = onItem<RsMacroDefinition>()
val onTupleStruct: PsiElementPattern.Capture<PsiElement> = PlatformPatterns.psiElement()
.withSuperParent(3, PlatformPatterns.psiElement().withChild(psiElement<RsTupleFields>()))
val onCrate: PsiElementPattern.Capture<PsiElement> = PlatformPatterns.psiElement().withSuperParent<PsiFile>(3)
.with("onCrateCondition") {
val file = it.containingFile.originalFile as RsFile
file.isCrateRoot
}
val onExternBlock: PsiElementPattern.Capture<PsiElement> = onItem<RsForeignModItem>()
val onExternBlockDecl: PsiElementPattern.Capture<PsiElement> =
onItem<RsFunction>() or //FIXME: check if this is indeed a foreign function
onItem<RsConstant>() or
onItem<RsForeignModItem>()
val onAnyItem: PsiElementPattern.Capture<PsiElement> = onItem<RsDocAndAttributeOwner>()
val onExternCrate: PsiElementPattern.Capture<PsiElement> = onItem<RsExternCrateItem>()
val onTrait: PsiElementPattern.Capture<PsiElement> = onItem<RsTraitItem>()
val onDropFn: PsiElementPattern.Capture<PsiElement> get() {
val dropTraitRef = psiElement<RsTraitRef>().withText("Drop")
val implBlock = psiElement<RsImplItem>().withChild(dropTraitRef)
return psiElement().withSuperParent(5, implBlock)
}
val onTestFn: PsiElementPattern.Capture<PsiElement> = onItem(psiElement<RsFunction>()
.withChild(psiElement<RsOuterAttr>().withText("#[test]")))
val inAnyLoop: PsiElementPattern.Capture<PsiElement> =
psiElement().inside(true,
psiElement<RsBlock>().withParent(or(
psiElement<RsForExpr>(),
psiElement<RsLoopExpr>(),
psiElement<RsWhileExpr>())),
psiElement<RsLambdaExpr>())
val whitespace: PsiElementPattern.Capture<PsiElement> = psiElement().whitespace()
val error: PsiElementPattern.Capture<PsiErrorElement> = psiElement<PsiErrorElement>()
inline fun <reified I : RsDocAndAttributeOwner> onItem(): PsiElementPattern.Capture<PsiElement> {
return psiElement().withSuperParent<I>(3)
}
private fun onItem(pattern: ElementPattern<out RsDocAndAttributeOwner>): PsiElementPattern.Capture<PsiElement> {
return psiElement().withSuperParent(3, pattern)
}
private class OnStatementBeginning(vararg startWords: String) : PatternCondition<PsiElement>("on statement beginning") {
val myStartWords = startWords
override fun accepts(t: PsiElement, context: ProcessingContext?): Boolean {
val prev = t.prevVisibleOrNewLine
return if (myStartWords.isEmpty())
prev == null || prev is PsiWhiteSpace || prev.node.elementType in STATEMENT_BOUNDARIES
else
prev != null && prev.node.text in myStartWords
}
}
}
private val PsiElement.prevVisibleOrNewLine: PsiElement?
get() = leftLeaves
.filterNot { it is PsiComment || it is PsiErrorElement }
.filter { it !is PsiWhiteSpace || it.textContains('\n') }
.firstOrNull()
val PsiElement.leftLeaves: Sequence<PsiElement> get() = generateSequence(this, PsiTreeUtil::prevLeaf).drop(1)
val PsiElement.rightSiblings: Sequence<PsiElement> get() = generateSequence(this.nextSibling) { it.nextSibling }
val PsiElement.leftSiblings: Sequence<PsiElement> get() = generateSequence(this.prevSibling) { it.prevSibling }
/**
* Similar with [TreeElementPattern.afterSiblingSkipping]
* but it uses [PsiElement.getPrevSibling] to get previous sibling elements
* instead of [PsiElement.getChildren].
*/
fun <T : PsiElement, Self : PsiElementPattern<T, Self>> PsiElementPattern<T, Self>.withPrevSiblingSkipping(
skip: ElementPattern<out T>,
pattern: ElementPattern<out T>
): Self = with("withPrevSiblingSkipping") {
val sibling = it.leftSiblings.dropWhile { skip.accepts(it) }
.firstOrNull() ?: return@with false
pattern.accepts(sibling)
}
private fun <T, Self : ObjectPattern<T, Self>> ObjectPattern<T, Self>.with(name: String, cond: (T) -> Boolean): Self =
with(object : PatternCondition<T>(name) {
override fun accepts(t: T, context: ProcessingContext?): Boolean = cond(t)
})
| mit | d6fd9f654034f17e5b0f4be795114ce3 | 41.165563 | 124 | 0.720276 | 4.427677 | false | false | false | false |
h2andp/vesta | src/main/kotlin/net/h2andp/core/util/ImageMetadataReader.kt | 1 | 3959 | package net.h2andp.core.util
import com.drew.imaging.FileType
import com.drew.imaging.FileTypeDetector
import com.drew.imaging.ImageProcessingException
import com.drew.imaging.jpeg.JpegMetadataReader
import java.io.InputStream
import com.drew.lang.annotations.NotNull
import com.drew.metadata.Metadata
import com.drew.metadata.adobe.AdobeJpegReader
import com.drew.metadata.exif.ExifReader
import com.drew.metadata.file.FileMetadataReader
import com.drew.metadata.icc.IccReader
import com.drew.metadata.iptc.IptcReader
import com.drew.metadata.jfif.JfifReader
import com.drew.metadata.jfxx.JfxxReader
import com.drew.metadata.jpeg.JpegCommentReader
import com.drew.metadata.jpeg.JpegDhtReader
import com.drew.metadata.jpeg.JpegDnlReader
import com.drew.metadata.jpeg.JpegReader
import com.drew.metadata.photoshop.DuckyReader
import com.drew.metadata.photoshop.PhotoshopReader
import java.io.BufferedInputStream
import java.io.File
import java.io.FileInputStream
/**
* Image metadata reader extracted from {@link com.drew.imaging.ImageMetadataReader} to avoid using XMP reader due to xmp core error.
*/
object ImageMetadataReader {
/**
* Reads metadata from an {@link InputStream}.
*
* @param inputStream a stream from which the file data may be read. The stream must be positioned at the
* beginning of the file's data.
* @return a populated {@link Metadata} object containing directories of tags with values and any processing errors.
* @throws ImageProcessingException if the file type is unknown, or for general processing errors.
*/
@NotNull
fun readMetadata( @NotNull inputStream: InputStream ): Metadata {
return readMetadata(inputStream, -1)
}
/**
* Reads metadata from an {@link InputStream} of known length.
*
* @param inputStream a stream from which the file data may be read. The stream must be positioned at the
* beginning of the file's data.
* @param streamLength the length of the stream, if known, otherwise -1.
* @return a populated {@link Metadata} object containing directories of tags with values and any processing errors.
* @throws ImageProcessingException if the file type is unknown, or for general processing errors.
*/
@NotNull
fun readMetadata( @NotNull inputStream: InputStream, streamLength: Long ): Metadata {
val bufferedInputStream: BufferedInputStream = inputStream as? BufferedInputStream ?: BufferedInputStream( inputStream )
val fileType: FileType = FileTypeDetector.detectFileType( bufferedInputStream )
if( fileType == FileType.Jpeg ) {
return JpegMetadataReader.readMetadata( bufferedInputStream, listOf(
JpegReader(),
JpegCommentReader(),
JfifReader(),
JfxxReader(),
ExifReader(),
IccReader(),
PhotoshopReader(),
DuckyReader(),
IptcReader(),
AdobeJpegReader(),
JpegDhtReader(),
JpegDnlReader()
) )
}
throw ImageProcessingException("File format is not supported")
}
/**
* Reads {@link Metadata} from a {@link File} object.
*
* @param file a file from which the image data may be read.
* @return a populated {@link Metadata} object containing directories of tags with values and any processing errors.
* @throws ImageProcessingException for general processing errors.
*/
@NotNull
fun readMetadata( @NotNull file: File): Metadata? {
val inputStream = FileInputStream( file )
var metadata: Metadata? = null
inputStream.use {
metadata = readMetadata( inputStream, file.length() )
FileMetadataReader().read( file, metadata )
}
return metadata
}
} | mit | fb57fb5865ce61b37a05eaf582223eff | 39.824742 | 133 | 0.682243 | 4.614219 | false | false | false | false |
requery/requery | requery-kotlin/src/main/kotlin/io/requery/sql/KotlinEntityDataStore.kt | 1 | 7472 | /*
* Copyright 2017 requery.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.requery.sql
import io.requery.RollbackException
import io.requery.Transaction
import io.requery.TransactionIsolation
import io.requery.kotlin.*
import io.requery.meta.Attribute
import io.requery.meta.EntityModel
import io.requery.query.Expression
import io.requery.query.Result
import io.requery.query.Scalar
import io.requery.query.Tuple
import io.requery.query.element.QueryType
import io.requery.query.function.Count
import java.util.Arrays
import java.util.LinkedHashSet
import kotlin.reflect.KClass
/**
* Concrete implementation of [BlockingEntityStore] connecting to SQL database.
*
* @author Nikhil Purushe
*/
class KotlinEntityDataStore<T : Any>(configuration: Configuration) : BlockingEntityStore<T> {
val data: EntityDataStore<T> = EntityDataStore(configuration)
private val context : EntityContext<T> = data.context()
private val model : EntityModel = configuration.model
override fun close() = data.close()
override fun delete(): Deletion<Scalar<Int>> =
QueryDelegate(QueryType.DELETE, model, UpdateOperation(context))
override infix fun <E : T> select(type: KClass<E>): Selection<Result<E>> {
val reader = context.read<E>(type.java)
val selection: Set<Expression<*>> = reader.defaultSelection()
val resultReader = reader.newResultReader(reader.defaultSelectionAttributes())
val query = QueryDelegate(QueryType.SELECT, model, SelectOperation(context, resultReader))
query.select(*selection.toTypedArray()).from(type)
return query
}
override fun <E : T> select(type: KClass<E>, vararg attributes: QueryableAttribute<E, *>): Selection<Result<E>> {
if (attributes.isEmpty()) {
throw IllegalArgumentException()
}
val reader = context.read<E>(type.java)
val selection: Set<Expression<*>> = LinkedHashSet(Arrays.asList<Expression<*>>(*attributes))
val resultReader = reader.newResultReader(attributes)
val query = QueryDelegate(QueryType.SELECT, model, SelectOperation(context, resultReader))
query.select(*selection.toTypedArray()).from(type.java)
return query
}
override fun select(vararg expressions: Expression<*>): Selection<Result<Tuple>> {
val reader = TupleResultReader(context)
val select = SelectOperation(context, reader)
return QueryDelegate(QueryType.SELECT, model, select).select(*expressions)
}
override fun <E : T> insert(type: KClass<E>): Insertion<Result<Tuple>> {
val selection = data.generatedExpressions(type.java)
val operation = InsertReturningOperation(context, selection)
val query = QueryDelegate<Result<Tuple>>(QueryType.INSERT, model, operation)
query.from(type)
return query
}
override fun <E : T> insert(type: KClass<E>, vararg attributes: QueryableAttribute<E, *>): InsertInto<out Result<Tuple>> {
val selection = data.generatedExpressions(type.java)
val operation = InsertReturningOperation(context, selection)
val query = QueryDelegate<Result<Tuple>>(QueryType.INSERT, model, operation)
return query.insertColumns(attributes)
}
override fun <E : T> update(type: KClass<E>): Update<Scalar<Int>> =
QueryDelegate(QueryType.UPDATE, model, UpdateOperation(context))
override fun <E : T> delete(type: KClass<E>): Deletion<Scalar<Int>> {
val query = QueryDelegate(QueryType.DELETE, model, UpdateOperation(context))
query.from(type)
return query
}
override fun <E : T> count(type: KClass<E>): Selection<Scalar<Int>> {
val operation = SelectCountOperation(context)
val query = QueryDelegate<Scalar<Int>>(QueryType.SELECT, model, operation)
query.select(Count.count(type.java)).from(type)
return query
}
override fun count(vararg attributes: QueryableAttribute<T, *>): Selection<Scalar<Int>> {
val operation = SelectCountOperation(context)
return QueryDelegate<Scalar<Int>>(QueryType.SELECT, model, operation)
.select(Count.count(*attributes))
}
override fun update(): Update<Scalar<Int>> =
QueryDelegate(QueryType.UPDATE, model, UpdateOperation(context))
override fun <E : T> insert(entity: E): E = data.insert(entity)
override fun <E : T> insert(entities: Iterable<E>): Iterable<E> = data.insert(entities)
override fun <K : Any, E : T> insert(entity: E, keyClass: KClass<K>): K =
data.insert(entity, keyClass.javaObjectType)
override fun <K : Any, E : T> insert(entities: Iterable<E>, keyClass: KClass<K>): Iterable<K> =
data.insert(entities, keyClass.javaObjectType)
override fun <E : T> update(entity: E): E = data.update(entity)
override fun <E : T> update(entities: Iterable<E>): Iterable<E> = data.update(entities)
override fun <E : T> upsert(entity: E): E = data.upsert(entity)
override fun <E : T> upsert(entities: Iterable<E>): Iterable<E> = data.upsert(entities)
override fun <E : T> refresh(entity: E): E = data.refresh(entity)
override fun <E : T> refresh(entity: E, vararg attributes: Attribute<*, *>): E =
data.refresh(entity, *attributes)
override fun <E : T> refresh(entities: Iterable<E>, vararg attributes: Attribute<*, *>): Iterable<E> =
data.refresh(entities, *attributes)
override fun <E : T> refreshAll(entity: E): E = data.refreshAll(entity)
override fun <E : T> delete(entity: E): Void? = data.delete(entity)
override fun <E : T> delete(entities: Iterable<E>): Void? = data.delete(entities)
override fun <E : T, K> findByKey(type: KClass<E>, key: K): E? = data.findByKey(type.java, key)
override fun raw(query: String, vararg parameters: Any): Result<Tuple> = data.raw(query, *parameters)
override fun <E : T> raw(type: KClass<E>, query: String, vararg parameters: Any): Result<E> =
data.raw(type.java, query, *parameters)
override fun <V> withTransaction(body: BlockingEntityStore<T>.() -> V): V {
transaction.begin()
try {
val result = body()
transaction.commit()
return result
} catch (e : Exception) {
transaction.rollback()
throw RollbackException(e)
}
}
override fun <V> withTransaction(isolation: TransactionIsolation,
body: BlockingEntityStore<T>.() -> V): V {
transaction.begin(isolation)
try {
val result = body()
transaction.commit()
return result
} catch (e : Exception) {
transaction.rollback()
throw RollbackException(e)
}
}
override val transaction: Transaction
get() = data.transaction()
override fun toBlocking(): BlockingEntityStore<T> = this
}
| apache-2.0 | d97dc3a21b14f2cc1fdb16321aed2f9f | 40.977528 | 126 | 0.672109 | 4.167317 | false | false | false | false |
pacien/tincapp | app/src/main/java/org/pacien/tincapp/commands/Tincd.kt | 1 | 1756 | /*
* Tinc App, an Android binding and user interface for the tinc mesh VPN daemon
* Copyright (C) 2017-2020 Pacien TRAN-GIRARD
*
* 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 <https://www.gnu.org/licenses/>.
*/
package org.pacien.tincapp.commands
import java8.util.concurrent.CompletableFuture
import org.pacien.tincapp.context.AppPaths
import java.io.File
/**
* @author pacien
*/
object Tincd {
fun start(netName: String, device: String, ed25519PrivateKey: File? = null, rsaPrivateKey: File? = null): CompletableFuture<Unit> =
Executor.call(Command(AppPaths.tincd().absolutePath)
.withOption("no-detach")
.withOption("config", AppPaths.confDir(netName).absolutePath)
.withOption("pidfile", AppPaths.pidFile(netName).absolutePath)
.withOption("logfile", AppPaths.logFile(netName).absolutePath)
.withOption("option", "DeviceType=fd")
.withOption("option", "Device=@$device")
.apply { if (ed25519PrivateKey != null) withOption("option", "Ed25519PrivateKeyFile=${ed25519PrivateKey.absolutePath}") }
.apply { if (rsaPrivateKey != null) withOption("option", "PrivateKeyFile=${rsaPrivateKey.absolutePath}") }
).thenApply { }
}
| gpl-3.0 | d69b3cb7d1a9b8098883d5a9040c7ee5 | 42.9 | 133 | 0.731207 | 4.009132 | false | false | false | false |
tkiapril/Weisseliste | src/main/kotlin/kotlin/dao/HistoryEntity.kt | 1 | 487 | package kotlin.dao
import org.joda.time.DateTime
public open class HistoryEntity (id: EntityID, table: HistoryTable) : Entity(id) {
public var start: DateTime by table.start
public var end: DateTime? by table.end
public open fun isValidBy (date: DateTime? = null) : Boolean {
if (date == null) return end == null
return start <= date && (end == null || date < end!!)
}
public fun close(date: DateTime = DateTime.now()) {
end = date
}
}
| agpl-3.0 | 02933093025c0cdb325e9b9bedbd5daf | 29.4375 | 82 | 0.634497 | 3.927419 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osm/mapdata/RelationDao.kt | 1 | 5506 | package de.westnordost.streetcomplete.data.osm.mapdata
import javax.inject.Inject
import de.westnordost.streetcomplete.data.Database
import de.westnordost.streetcomplete.data.osm.mapdata.RelationTables.Columns.ID
import de.westnordost.streetcomplete.data.osm.mapdata.RelationTables.Columns.INDEX
import de.westnordost.streetcomplete.data.osm.mapdata.RelationTables.Columns.LAST_SYNC
import de.westnordost.streetcomplete.data.osm.mapdata.RelationTables.Columns.REF
import de.westnordost.streetcomplete.data.osm.mapdata.RelationTables.Columns.ROLE
import de.westnordost.streetcomplete.data.osm.mapdata.RelationTables.Columns.TAGS
import de.westnordost.streetcomplete.data.osm.mapdata.RelationTables.Columns.TIMESTAMP
import de.westnordost.streetcomplete.data.osm.mapdata.RelationTables.Columns.TYPE
import de.westnordost.streetcomplete.data.osm.mapdata.RelationTables.Columns.VERSION
import de.westnordost.streetcomplete.data.osm.mapdata.RelationTables.NAME
import de.westnordost.streetcomplete.data.osm.mapdata.RelationTables.NAME_MEMBERS
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.lang.System.currentTimeMillis
/** Stores OSM relations */
class RelationDao @Inject constructor(private val db: Database) {
fun put(relation: Relation) {
putAll(listOf(relation))
}
fun get(id: Long): Relation? =
getAll(listOf(id)).firstOrNull()
fun delete(id: Long): Boolean =
deleteAll(listOf(id)) == 1
fun putAll(relations: Collection<Relation>) {
if (relations.isEmpty()) return
val idsString = relations.joinToString(",") { it.id.toString() }
val time = currentTimeMillis()
db.transaction {
db.delete(NAME_MEMBERS, "$ID IN ($idsString)")
db.insertMany(NAME_MEMBERS,
arrayOf(ID, INDEX, REF, TYPE, ROLE),
relations.flatMap { relation ->
relation.members.mapIndexed { index, member ->
arrayOf(
relation.id,
index,
member.ref,
member.type.name,
member.role
)
}
}
)
db.replaceMany(NAME,
arrayOf(ID, VERSION, TAGS, TIMESTAMP, LAST_SYNC),
relations.map { relation ->
arrayOf(
relation.id,
relation.version,
if (relation.tags.isNotEmpty()) Json.encodeToString(relation.tags) else null,
relation.timestampEdited,
time
)
}
)
}
}
fun getAll(ids: Collection<Long>): List<Relation> {
if (ids.isEmpty()) return emptyList()
val idsString = ids.joinToString(",")
return db.transaction {
val membersByRelationId = mutableMapOf<Long, MutableList<RelationMember>>()
db.query(NAME_MEMBERS, where = "$ID IN ($idsString)", orderBy = "$ID, $INDEX") { cursor ->
val members = membersByRelationId.getOrPut(cursor.getLong(ID)) { ArrayList() }
members.add(
RelationMember(
ElementType.valueOf(cursor.getString(TYPE)),
cursor.getLong(REF),
cursor.getString(ROLE)
)
)
}
db.query(NAME, where = "$ID IN ($idsString)") { cursor ->
Relation(
cursor.getLong(ID),
membersByRelationId.getValue(cursor.getLong(ID)),
cursor.getStringOrNull(TAGS)?.let { Json.decodeFromString(it) } ?: emptyMap(),
cursor.getInt(VERSION),
cursor.getLong(TIMESTAMP)
)
}
}
}
fun deleteAll(ids: Collection<Long>): Int {
if (ids.isEmpty()) return 0
val idsString = ids.joinToString(",")
return db.transaction {
db.delete(NAME_MEMBERS, "$ID IN ($idsString)")
db.delete(NAME, "$ID IN ($idsString)")
}
}
fun clear() {
db.transaction {
db.delete(NAME_MEMBERS)
db.delete(NAME)
}
}
fun getAllForNode(nodeId: Long) : List<Relation> =
getAllForElement(ElementType.NODE, nodeId)
fun getAllForWay(wayId: Long) : List<Relation> =
getAllForElement(ElementType.WAY, wayId)
fun getAllForRelation(relationId: Long) : List<Relation> =
getAllForElement(ElementType.RELATION, relationId)
fun getIdsOlderThan(timestamp: Long, limit: Int? = null): List<Long> {
if (limit != null && limit <= 0) return emptyList()
return db.query(NAME,
columns = arrayOf(ID),
where = "$LAST_SYNC < $timestamp",
limit = limit?.toString()
) { it.getLong(ID) }
}
private fun getAllForElement(elementType: ElementType, elementId: Long): List<Relation> {
return db.transaction {
val ids = db.query(NAME_MEMBERS,
columns = arrayOf(ID),
where = "$TYPE = ? AND $REF = $elementId",
args = arrayOf(elementType.name)
) { it.getLong(ID) }.toSet()
getAll(ids)
}
}
}
| gpl-3.0 | 7fa6114e73448fd31749ae029a15cb3f | 36.455782 | 102 | 0.580639 | 4.738382 | false | false | false | false |
matkoniecz/StreetComplete | buildSrc/src/main/java/UpdatePresetsTask.kt | 2 | 3854 | import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import java.io.File
import java.net.URL
import com.beust.klaxon.Parser
import com.beust.klaxon.JsonObject
import com.beust.klaxon.JsonArray
import java.io.StringWriter
/** Update the presets metadata and its translations for use with the de.westnordost:osmfeatures library */
open class UpdatePresetsTask : DefaultTask() {
@get:Input var languageCodes: Collection<String>? = null
@get:Input var targetDir: String? = null
@TaskAction fun run() {
val targetDir = targetDir ?: return
val exportLangs = languageCodes
// copy the presets.json 1:1
val presetsFile = File("$targetDir/presets.json")
presetsFile.writeText(fetchPresets())
// download each language
for (localizationMetadata in fetchLocalizationMetadata()) {
val language = localizationMetadata.languageCode
if (exportLangs != null && !exportLangs.contains(language)) continue
println(localizationMetadata.languageCode)
val presetsLocalization = fetchPresetsLocalizations(localizationMetadata)
if (presetsLocalization != null) {
val javaLanguage = bcp47LanguageTagToJavaLanguageTag(language)
File("$targetDir/${javaLanguage}.json").writeText(presetsLocalization)
}
}
}
/** Fetch iD presets */
private fun fetchPresets(): String {
val presetsUrl = "https://raw.githubusercontent.com/openstreetmap/id-tagging-schema/main/dist/presets.json"
return URL(presetsUrl).readText()
}
/** Fetch relevant meta-infos for localizations from iD */
private fun fetchLocalizationMetadata(): List<LocalizationMetadata> {
// this file contains a list with meta information for each localization of iD
val contentsUrl = "https://api.github.com/repos/openstreetmap/id-tagging-schema/contents/dist/translations"
val languagesJson = Parser.default().parse(URL(contentsUrl).openStream()) as JsonArray<JsonObject>
return languagesJson.mapNotNull {
if (it["type"] == "file") {
val name = it["name"] as String
val languageCode = name.subSequence(0, name.lastIndexOf(".")).toString()
LocalizationMetadata(languageCode, it["download_url"] as String)
} else null
}
}
/** Download and pick the localization for only the presets from iD localizations
* (the iD localizations contain everything, such as localizations of iD UI etc)*/
private fun fetchPresetsLocalizations(localization: LocalizationMetadata): String {
return URL(localization.downloadUrl).openStream().bufferedReader().use { it.readText() }.unescapeUnicode()
}
}
private data class LocalizationMetadata(val languageCode: String, val downloadUrl: String)
private fun String.unescapeUnicode(): String {
val out = StringWriter(length)
val unicode = StringBuilder(4)
var hadSlash = false
var inUnicode = false
for (ch in this) {
if (inUnicode) {
unicode.append(ch)
if (unicode.length == 4) {
val unicodeChar = unicode.toString().toInt(16).toChar()
out.write(unicodeChar.toString())
unicode.setLength(0)
inUnicode = false
hadSlash = false
}
} else if (hadSlash) {
hadSlash = false
if (ch == 'u') inUnicode = true
else {
out.write(92)
out.write(ch.toString())
}
} else if (ch == '\\') {
hadSlash = true
} else {
out.write(ch.toString())
}
}
if (hadSlash) out.write(92)
return out.toString()
}
| gpl-3.0 | 3384a4676853cd28e235a5181673b6ab | 36.417476 | 115 | 0.640114 | 4.632212 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/filterer/CollectionStatusFilterer.kt | 1 | 3704 | package com.boardgamegeek.filterer
import android.content.Context
import com.boardgamegeek.R
import com.boardgamegeek.entities.CollectionItemEntity
import com.boardgamegeek.extensions.joinTo
class CollectionStatusFilterer(context: Context) : CollectionFilterer(context) {
var shouldJoinWithOr = false
var selectedStatuses = BooleanArray(0)
override val typeResourceId = R.string.collection_filter_type_collection_status
override fun inflate(data: String) {
shouldJoinWithOr = data.substringBefore(DELIMITER, "0") == "1"
selectedStatuses = data.substringAfter(DELIMITER).split(DELIMITER).map { it == "1" }.toBooleanArray()
}
override fun deflate(): String {
return if (shouldJoinWithOr) "1" else "0" +
DELIMITER +
selectedStatuses.map { if (it) "1" else "0" }.joinTo(DELIMITER)
}
override val iconResourceId: Int
get() = R.drawable.ic_baseline_library_books_24
override fun chipText(): String {
val entries = context.resources.getStringArray(R.array.collection_status_filter_entries)
return selectedStatuses.indices
.filter { selectedStatuses[it] }
.map { entries[it] }
.joinTo(if (shouldJoinWithOr) " | " else " & ")
.toString()
}
override fun description(): String {
return context.getString(R.string.status_of_prefix, chipText())
}
override fun filter(item: CollectionItemEntity): Boolean {
val statuses = selectedStatuses.indices.filter { selectedStatuses[it] }
if (shouldJoinWithOr) {
statuses.forEach {
when (it) {
own -> if (item.own) return true
previouslyOwned -> if (item.previouslyOwned) return true
forTrade -> if (item.forTrade) return true
wantInTrade -> if (item.wantInTrade) return true
wantToBuy -> if (item.wantToBuy) return true
wishList -> if (item.wishList) return true
wantToPlay -> if (item.wantToPlay) return true
preOrdered -> if (item.preOrdered) return true
}
}
return false
} else {
statuses.forEach {
when (it) {
own -> if (!item.own) return false
previouslyOwned -> if (!item.previouslyOwned) return false
forTrade -> if (!item.forTrade) return false
wantInTrade -> if (!item.wantInTrade) return false
wantToBuy -> if (!item.wantToBuy) return false
wishList -> if (!item.wishList) return false
wantToPlay -> if (!item.wantToPlay) return false
preOrdered -> if (!item.preOrdered) return false
}
}
return true
}
}
/**
* @return a set of status values representing the statuses currently selected within this filter.
*/
fun getSelectedStatusesSet(): Set<String> {
val selectedStatusesSet = hashSetOf<String>()
val values = context.resources.getStringArray(R.array.pref_sync_status_values)
selectedStatuses.indices
.filter { selectedStatuses[it] }
.mapTo(selectedStatusesSet) { values[it] }
return selectedStatusesSet
}
companion object {
const val own = 0
const val previouslyOwned = 1
const val forTrade = 2
const val wantInTrade = 3
const val wantToBuy = 4
const val wishList = 5
const val wantToPlay = 6
const val preOrdered = 7
}
}
| gpl-3.0 | 21f7f696024f566ac701135a9fd3f387 | 37.185567 | 109 | 0.592603 | 4.712468 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.