repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
wuman/RxBinding | rxbinding-kotlin/src/main/kotlin/com/jakewharton/rxbinding/widget/RxAdapter.kt | 12 | 321 | package com.jakewharton.rxbinding.widget
import android.widget.Adapter
import rx.Observable
/**
* Create an observable of data change events for `adapter`.
*
* *Note:* A value will be emitted immediately on subscribe.
*/
public inline fun <T : Adapter> T.dataChanges(): Observable<T> = RxAdapter.dataChanges(this)
| apache-2.0 |
tinypass/piano-sdk-for-android | composer-c1x/src/main/java/io/piano/android/composer/c1x/C1xInterceptor.kt | 1 | 2514 | package io.piano.android.composer.c1x
import io.piano.android.composer.ExperienceInterceptor
import io.piano.android.composer.model.ExperienceRequest
import io.piano.android.composer.model.ExperienceResponse
import io.piano.android.composer.model.events.ExperienceExecute
import io.piano.android.cxense.CxenseSdk
import io.piano.android.cxense.model.CustomParameter
import io.piano.android.cxense.model.ExternalUserId
import io.piano.android.cxense.model.PageViewEvent
import timber.log.Timber
class C1xInterceptor(
private val siteId: String
) : ExperienceInterceptor {
override fun beforeExecute(
request: ExperienceRequest
) {
check(!request.url.isNullOrEmpty() || !request.contentId.isNullOrEmpty()) {
"URL or Content Id is required for C1X"
}
}
override fun afterExecute(request: ExperienceRequest, response: ExperienceResponse) {
response.apply {
if (cxenseCustomerPrefix == null) {
Timber.w("C1X hasn't configured")
return
}
result.events.firstOrNull {
it.eventData is ExperienceExecute
}?.eventExecutionContext?.also { experienceExecutionContext ->
val userState = when {
response.userId in listOf(null, "", "anon") -> ANON_STATE
experienceExecutionContext.accessList.isNullOrEmpty() -> REGISTERED_STATE
else -> ACTIVE_STATE
}
val externalUserId = response.userId?.let {
ExternalUserId(cxenseCustomerPrefix!!, it)
}
val event = PageViewEvent.Builder(
siteId = siteId,
location = request.url,
contentId = request.contentId,
referrer = request.referer,
customParameters = mutableListOf(CustomParameter(PARAM_USERSTATE, userState)),
).apply {
if (externalUserId != null)
addExternalUserIds(externalUserId)
}.build()
CxenseSdk.getInstance().pushEvents(event)
} ?: Timber.w("C1X can't find ExperienceExecute event")
}
}
companion object {
private const val ACTIVE_STATE = "hasActiveAccess"
private const val ANON_STATE = "anon"
private const val REGISTERED_STATE = "registered"
private const val PARAM_USERSTATE = "userState"
}
}
| apache-2.0 |
icarumbas/bagel | core/src/ru/icarumbas/bagel/view/renderer/components/TextureComponent.kt | 1 | 286 | package ru.icarumbas.bagel.view.renderer.components
import com.badlogic.ashley.core.Component
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.TextureRegion
class TextureComponent(var tex: TextureRegion? = null): Component {
var color = Color.WHITE!!
} | apache-2.0 |
pyamsoft/home-button | app/src/main/java/com/pyamsoft/homebutton/HomeButtonTheme.kt | 1 | 3668 | /*
* Copyright 2021 Peter Kenji Yamanaka
*
* 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.pyamsoft.homebutton
import android.app.Activity
import androidx.annotation.CheckResult
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Colors
import androidx.compose.material.LocalContentColor
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Shapes
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import com.google.android.material.R
import com.pyamsoft.pydroid.theme.PYDroidTheme
import com.pyamsoft.pydroid.theme.attributesFromCurrentTheme
import com.pyamsoft.pydroid.ui.theme.ThemeProvider
import com.pyamsoft.pydroid.ui.theme.Theming
@Composable
@CheckResult
private fun themeColors(activity: Activity, isDarkMode: Boolean): Colors {
val colors =
activity.attributesFromCurrentTheme(
R.attr.colorPrimary,
R.attr.colorOnPrimary,
R.attr.colorSecondary,
R.attr.colorOnSecondary,
)
val primary = colorResource(colors[0])
val onPrimary = colorResource(colors[1])
val secondary = colorResource(colors[2])
val onSecondary = colorResource(colors[3])
return if (isDarkMode)
darkColors(
primary = primary,
onPrimary = onPrimary,
secondary = secondary,
onSecondary = onSecondary,
// Must be specified for things like Switch color
primaryVariant = primary,
secondaryVariant = secondary,
)
else
lightColors(
primary = primary,
onPrimary = onPrimary,
secondary = secondary,
onSecondary = onSecondary,
// Must be specified for things like Switch color
primaryVariant = primary,
secondaryVariant = secondary,
)
}
@Composable
@CheckResult
private fun themeShapes(): Shapes {
return Shapes(
medium = RoundedCornerShape(4.dp),
)
}
@Composable
fun Activity.HomeButtonTheme(
themeProvider: ThemeProvider,
content: @Composable () -> Unit,
) {
this.HomeButtonTheme(
theme = if (themeProvider.isDarkTheme()) Theming.Mode.DARK else Theming.Mode.LIGHT,
content = content,
)
}
@Composable
fun Activity.HomeButtonTheme(
theme: Theming.Mode,
content: @Composable () -> Unit,
) {
val isDarkMode =
when (theme) {
Theming.Mode.LIGHT -> false
Theming.Mode.DARK -> true
Theming.Mode.SYSTEM -> isSystemInDarkTheme()
}
PYDroidTheme(
colors = themeColors(this, isDarkMode),
shapes = themeShapes(),
) {
// We update the LocalContentColor to match our onBackground. This allows the default
// content color to be more appropriate to the theme background
CompositionLocalProvider(
LocalContentColor provides MaterialTheme.colors.onBackground,
content = content,
)
}
}
| apache-2.0 |
siosio/upsource-kotlin-api | src/main/java/com/github/siosio/upsource/internal/CreateProjectCommand.kt | 1 | 406 | package com.github.siosio.upsource.internal
import com.github.siosio.upsource.bean.*
class CreateProjectCommand(val createProjectRequest: CreateProjectRequest) : Command<CreateProjectRequest, VoidMessage> {
override val name: String = "createProject"
override val responseType: Class<VoidMessage> = VoidMessage::class.java
override fun getRequest(): CreateProjectRequest = createProjectRequest
}
| mit |
google/ksp | test-utils/src/main/kotlin/com/google/devtools/ksp/processor/CheckOverrideProcessor.kt | 1 | 6932 | /*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.processor
import com.google.devtools.ksp.getClassDeclarationByName
import com.google.devtools.ksp.getDeclaredFunctions
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.symbol.*
class CheckOverrideProcessor : AbstractTestProcessor() {
val results = mutableListOf<String>()
override fun toResult(): List<String> {
return results
}
override fun process(resolver: Resolver): List<KSAnnotated> {
fun checkOverride(overrider: KSDeclaration, overridee: KSDeclaration, containing: KSClassDeclaration? = null) {
results.add(
"${overrider.qualifiedName?.asString()} overrides ${overridee.qualifiedName?.asString()}: " +
"${containing?.let { resolver.overrides(overrider, overridee, containing) }
?: resolver.overrides(overrider, overridee)}"
)
}
val javaList = resolver.getClassDeclarationByName(resolver.getKSNameFromString("JavaList"))
as KSClassDeclaration
val kotlinList = resolver.getClassDeclarationByName(resolver.getKSNameFromString("KotlinList"))
as KSClassDeclaration
val getFunKt = resolver.getSymbolsWithAnnotation("GetAnno").single() as KSFunctionDeclaration
val getFunJava = javaList.getAllFunctions().single { it.simpleName.asString() == "get" }
val fooFunJava = javaList.getDeclaredFunctions().single { it.simpleName.asString() == "foo" }
val fooFunKt = resolver.getSymbolsWithAnnotation("FooAnno").single() as KSFunctionDeclaration
val foooFunKt = resolver.getSymbolsWithAnnotation("BarAnno").single() as KSFunctionDeclaration
val equalFunKt = kotlinList.getDeclaredFunctions().single { it.simpleName.asString() == "equals" }
val equalFunJava = javaList.getAllFunctions().single { it.simpleName.asString() == "equals" }
val bazPropKt = resolver.getSymbolsWithAnnotation("BazAnno").single() as KSPropertyDeclaration
val baz2PropKt = resolver.getSymbolsWithAnnotation("Baz2Anno").single() as KSPropertyDeclaration
val bazzPropKt = resolver.getSymbolsWithAnnotation("BazzAnno")
.filterIsInstance<KSPropertyDeclaration>().single()
val bazz2PropKt = resolver.getSymbolsWithAnnotation("Bazz2Anno").single() as KSPropertyDeclaration
checkOverride(getFunKt, getFunJava)
checkOverride(fooFunKt, fooFunJava)
checkOverride(foooFunKt, fooFunJava)
checkOverride(fooFunKt, fooFunKt)
checkOverride(equalFunKt, equalFunJava)
checkOverride(bazPropKt, baz2PropKt)
checkOverride(bazPropKt, bazz2PropKt)
checkOverride(bazzPropKt, bazz2PropKt)
checkOverride(bazzPropKt, baz2PropKt)
checkOverride(bazPropKt, bazPropKt)
val JavaImpl = resolver.getClassDeclarationByName("JavaImpl")!!
val MyInterface = resolver.getClassDeclarationByName("MyInterface")!!
val MyInterface2 = resolver.getClassDeclarationByName("MyInterface2")!!
val MyInterface2ImplWithoutType = resolver.getClassDeclarationByName("MyInterface2ImplWithoutType")!!
val MyInterface2ImplWithType = resolver.getClassDeclarationByName("MyInterface2ImplWithType")!!
val getX = JavaImpl.getDeclaredFunctions().first { it.simpleName.asString() == "getX" }
val getY = JavaImpl.getDeclaredFunctions().first { it.simpleName.asString() == "getY" }
val setY = JavaImpl.getDeclaredFunctions().first { it.simpleName.asString() == "setY" }
val setX = JavaImpl.getDeclaredFunctions().first { it.simpleName.asString() == "setX" }
val myInterfaceX = MyInterface.declarations.first { it.simpleName.asString() == "x" }
val myInterfaceY = MyInterface.declarations.first { it.simpleName.asString() == "y" }
val myInterface2receiveList = MyInterface2.declarations.single()
val myInterface2ImplWithoutTypereceiveList = MyInterface2ImplWithoutType.declarations.single()
val myInterface2ImplWithTypereceiveList = MyInterface2ImplWithType.declarations.single()
checkOverride(getY, getX)
checkOverride(getY, myInterfaceX)
checkOverride(getX, myInterfaceX)
checkOverride(setY, myInterfaceY)
checkOverride(setX, myInterfaceX)
checkOverride(getY, getY)
checkOverride(myInterfaceX, getY)
checkOverride(myInterfaceX, getX)
checkOverride(myInterfaceY, setY)
checkOverride(myInterfaceY, myInterfaceY)
checkOverride(myInterface2receiveList, myInterface2ImplWithoutTypereceiveList)
checkOverride(myInterface2ImplWithoutTypereceiveList, myInterface2receiveList)
checkOverride(myInterface2ImplWithTypereceiveList, myInterface2receiveList)
checkOverride(myInterface2ImplWithTypereceiveList, myInterface2ImplWithoutTypereceiveList)
val JavaDifferentReturnTypes =
resolver.getClassDeclarationByName("JavaDifferentReturnType")!!
val diffGetX = JavaDifferentReturnTypes.getDeclaredFunctions()
.first { it.simpleName.asString() == "foo" }
checkOverride(diffGetX, fooFunJava)
val base = resolver.getClassDeclarationByName("Base")!!
val baseF1 = base.declarations.filter { it.simpleName.asString() == "f1" }.single()
val baseProp = base.declarations.filter { it.simpleName.asString() == "prop" }.single()
val myInterface3 = resolver.getClassDeclarationByName("MyInterface3")!!
val myInterfaceF1 = myInterface3.declarations.filter { it.simpleName.asString() == "f1" }.single()
val myInterfaceProp = myInterface3.declarations.filter { it.simpleName.asString() == "prop" }.single()
val baseOverride = resolver.getClassDeclarationByName("BaseOverride")!!
checkOverride(baseF1, myInterfaceF1, baseOverride)
checkOverride(baseProp, myInterfaceProp, baseOverride)
val jbase = resolver.getClassDeclarationByName("JBase")!!
val jBaseOverride = resolver.getClassDeclarationByName("JBaseOverride")!!
val jbaseProp = jbase.declarations.single { it.simpleName.asString() == "getProp" }
checkOverride(jbaseProp, myInterfaceProp, jBaseOverride)
return emptyList()
}
}
| apache-2.0 |
google/ksp | kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/impl/symbol/kotlin/KSTypeAliasImpl.kt | 1 | 2204 | /*
* Copyright 2022 Google LLC
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.impl.symbol.kotlin
import com.google.devtools.ksp.KSObjectCache
import com.google.devtools.ksp.symbol.KSExpectActual
import com.google.devtools.ksp.symbol.KSName
import com.google.devtools.ksp.symbol.KSTypeAlias
import com.google.devtools.ksp.symbol.KSTypeReference
import com.google.devtools.ksp.symbol.KSVisitor
import org.jetbrains.kotlin.analysis.api.symbols.KtTypeAliasSymbol
import org.jetbrains.kotlin.analysis.api.symbols.nameOrAnonymous
class KSTypeAliasImpl private constructor(private val ktTypeAliasSymbol: KtTypeAliasSymbol) :
KSTypeAlias,
AbstractKSDeclarationImpl(ktTypeAliasSymbol),
KSExpectActual by KSExpectActualImpl(ktTypeAliasSymbol) {
companion object : KSObjectCache<KtTypeAliasSymbol, KSTypeAliasImpl>() {
fun getCached(ktTypeAliasSymbol: KtTypeAliasSymbol) =
cache.getOrPut(ktTypeAliasSymbol) { KSTypeAliasImpl(ktTypeAliasSymbol) }
}
override val name: KSName by lazy {
KSNameImpl.getCached(ktTypeAliasSymbol.nameOrAnonymous.asString())
}
override val type: KSTypeReference by lazy {
KSTypeReferenceImpl.getCached(ktTypeAliasSymbol.expandedType, this)
}
override val simpleName: KSName
get() = name
override val qualifiedName: KSName? by lazy {
ktTypeAliasSymbol.classIdIfNonLocal?.asFqNameString()?.let { KSNameImpl.getCached(it) }
}
override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R {
return visitor.visitTypeAlias(this, data)
}
}
| apache-2.0 |
fnberta/PopularMovies | app/src/main/java/ch/berta/fabio/popularmovies/features/common/vdos/LoadingEmptyViewData.kt | 1 | 853 | /*
* Copyright (c) 2017 Fabio Berta
*
* 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 ch.berta.fabio.popularmovies.features.common.vdos
import android.databinding.Bindable
import android.databinding.Observable
interface LoadingEmptyViewData : Observable {
@get:Bindable var loading: Boolean
@get:Bindable var empty: Boolean
} | apache-2.0 |
noties/Markwon | app-sample/src/main/java/io/noties/markwon/app/widget/SearchBar.kt | 1 | 2681 | package io.noties.markwon.app.widget
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import io.noties.markwon.app.R
import io.noties.markwon.app.utils.KeyEventUtils
import io.noties.markwon.app.utils.KeyboardUtils
import io.noties.markwon.app.utils.TextWatcherAdapter
import io.noties.markwon.app.utils.hidden
class SearchBar(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs) {
private val focus: View
private val textField: TextField
private val clear: View
private val cancel: View
var onSearchListener: ((String?) -> Unit)? = null
init {
orientation = HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
View.inflate(context, R.layout.view_search_bar, this)
focus = findViewById(R.id.focus)
textField = findViewById(R.id.text_field)
clear = findViewById(R.id.clear)
cancel = findViewById(R.id.cancel)
// listen for text state
textField.addTextChangedListener(TextWatcherAdapter.afterTextChanged {
textFieldChanged(it)
})
fun looseFocus() {
KeyboardUtils.hide(textField)
focus.requestFocus()
}
// on back pressed - lose focus and hide keyboard
textField.onBackPressedListener = {
// hide keyboard and lose focus
looseFocus()
}
textField.setOnFocusChangeListener { _, hasFocus ->
cancel.hidden = textField.text.isEmpty() && !hasFocus
}
textField.setOnEditorActionListener { _, _, event ->
if (KeyEventUtils.isActionUp(event)) {
looseFocus()
}
return@setOnEditorActionListener true
}
clear.setOnClickListener {
textField.setText("")
// ensure that we have focus when clear is clicked
if (!textField.hasFocus()) {
textField.requestFocus()
// additionally ensure keyboard is showing
KeyboardUtils.show(textField)
}
}
cancel.setOnClickListener {
textField.setText("")
looseFocus()
}
isSaveEnabled = false
textField.isSaveEnabled = false
}
fun search(text: String) {
textField.setText(text)
}
private fun textFieldChanged(text: CharSequence) {
val isEmpty = text.isEmpty()
clear.hidden = isEmpty
cancel.hidden = isEmpty && !textField.hasFocus()
onSearchListener?.invoke(if (text.isEmpty()) null else text.toString())
}
} | apache-2.0 |
polson/MetroTripper | app/src/main/java/com/philsoft/metrotripper/app/ui/view/MapVehicleHelper.kt | 1 | 2331 | package com.philsoft.metrotripper.app.ui.view
import android.app.Activity
import android.view.View
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.philsoft.metrotripper.R
import com.philsoft.metrotripper.app.state.VehicleAction
import com.philsoft.metrotripper.model.Trip
import com.philsoft.metrotripper.utils.createBitmap
import com.philsoft.metrotripper.utils.map.fadeIn
import com.philsoft.metrotripper.utils.map.fadeOutAndRemove
import kotlinx.android.synthetic.main.vehicle.view.*
class MapVehicleHelper(private val activity: Activity, private val map: GoogleMap) {
private val vehicleMarkers = HashSet<Marker>()
companion object {
private const val FADE_DURATION = 1000
}
fun render(action: VehicleAction) {
when (action) {
is VehicleAction.ShowVehicles -> displayVehicleMarkers(action.trips)
}
}
private fun displayVehicleMarkers(trips: List<Trip>) {
// Fade out existing vehicles
for (vehicleMarker in vehicleMarkers) {
vehicleMarker.fadeOutAndRemove(FADE_DURATION)
}
vehicleMarkers.clear()
// Fade in new vehicles
for (trip in trips) {
val vehicleMarker = createVehicleMarker(trip)
vehicleMarkers.add(vehicleMarker)
vehicleMarker.fadeIn(FADE_DURATION)
}
}
private fun createVehicleMarker(trip: Trip): Marker {
val vehicleView = buildVehicleView(trip)
return map.addMarker(
MarkerOptions().anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.title(activity.getString(R.string.vehicle) + " " + trip.route + trip.terminal)
.position(LatLng(trip.vehicleLatitude.toDouble(), trip.vehicleLongitude.toDouble()))
.icon(BitmapDescriptorFactory.fromBitmap(vehicleView.createBitmap())))
}
private fun buildVehicleView(trip: Trip): View {
val view = activity.layoutInflater.inflate(R.layout.vehicle, null)
view.vehicleNumber.text = "${trip.route}${trip.terminal}"
return view
}
}
| apache-2.0 |
lskycity/AndroidTools | app/src/main/java/com/lskycity/androidtools/ui/FeedbackActivity.kt | 1 | 4175 | package com.lskycity.androidtools.ui
import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.text.*
import android.text.style.UnderlineSpan
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.res.ResourcesCompat
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.lskycity.androidtools.AppConstants
import com.lskycity.androidtools.R
import com.lskycity.androidtools.app.BaseActivity
import com.lskycity.androidtools.app.ToolApplication
import com.lskycity.androidtools.apputils.Feedback
/**
* collect feedback from user
*
* @author zhaofliu
* @since 1/6/17
*/
class FeedbackActivity : BaseActivity(), TextWatcher, View.OnClickListener {
private lateinit var feedback: EditText
private lateinit var textCount: TextView
private var clickTime: Long = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_feedback)
feedback = findViewById<View>(R.id.feedback_content) as EditText
feedback.addTextChangedListener(this)
textCount = findViewById<View>(R.id.text_count) as TextView
val checkNewVersion = findViewById<View>(R.id.check_new_version) as TextView
//link the check user guide activity.
val checkNewVersionString = getString(R.string.check_new_version)
val checkNewVersionSpannable = SpannableString(checkNewVersionString)
checkNewVersionSpannable.setSpan(UnderlineSpan(), 0, checkNewVersionString.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
checkNewVersion.text = checkNewVersionSpannable
checkNewVersion.setOnClickListener(this)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.activity_feedback, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.menu_send) {
sendFeedback(feedback.text.toString())
return true
}
return false
}
private fun sendFeedback(content: String) {
val currentTime = System.currentTimeMillis()
if (currentTime - clickTime < 2000) {
return
}
clickTime = currentTime
if (TextUtils.isEmpty(content.trim { it <= ' ' })) {
Toast.makeText(this@FeedbackActivity, R.string.send_feedback_empty, Toast.LENGTH_LONG).show()
return
}
val request = JsonObjectRequest(Request.Method.POST, AppConstants.FEEDBACK_URL, Feedback.obtain(this, content).toJSONObject(), Response.Listener {
Toast.makeText(this@FeedbackActivity, R.string.send_feedback_success, Toast.LENGTH_LONG).show()
supportFinishAfterTransition()
},
Response.ErrorListener { volleyError -> Toast.makeText(this@FeedbackActivity, getString(R.string.send_feedback_fail) + ", " + volleyError.message, Toast.LENGTH_LONG).show() })
ToolApplication.get().requestQueue.add(request)
Toast.makeText(this@FeedbackActivity, R.string.sending_feedback, Toast.LENGTH_SHORT).show()
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
}
@SuppressLint("SetTextI18n")
override fun afterTextChanged(s: Editable) {
textCount.text = s.length.toString() + "/125"
if (s.length == MAX_TEXT_COUNT) {
textCount.setTextColor(Color.RED)
} else {
textCount.setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, theme))
}
}
override fun onClick(v: View) {
if (v.id == R.id.check_new_version) {
AppConstants.startUrlWithCustomTab(this, AppConstants.MAIN_PAGE_URL)
}
}
companion object {
private val MAX_TEXT_COUNT = 125
}
}
| apache-2.0 |
rumboalla/apkupdater | app/src/main/java/com/apkupdater/model/ui/AppSearch.kt | 1 | 458 | package com.apkupdater.model.ui
import com.apkupdater.util.adapter.Id
import com.apkupdater.util.crc.crc16
data class AppSearch(
val name: String,
val url: String = "",
val iconurl: String = "",
val developer: String = "",
val source: Int = 0,
val packageName: String = "",
val versionCode: Int = 0,
override val id: Int = crc16("$name$url$iconurl$developer$source$packageName$versionCode"),
var loading: Boolean = false
): Id { companion object } | gpl-3.0 |
iluu/algs-progfun | src/main/kotlin/com/hackerrank/PickingNumbers.kt | 1 | 456 | package com.hackerrank
import java.util.*
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val n = scan.nextInt()
val arr = Array(100, { 0 })
for (i in 0..n - 1) {
val value = scan.nextInt()
arr[value]++
}
print(countPickedNumbers(arr))
}
fun countPickedNumbers(arr: Array<Int>): Int {
return (0..arr.size - 2)
.map { arr[it] + arr[it + 1] }
.max()
?: 0
}
| mit |
dataloom/conductor-client | src/main/kotlin/com/openlattice/hazelcast/serializers/PrincipalExistsEntryProcessorStreamSerializer.kt | 1 | 787 | package com.openlattice.hazelcast.serializers
import com.hazelcast.nio.ObjectDataInput
import com.openlattice.hazelcast.StreamSerializerTypeIds
import com.openlattice.principals.PrincipalExistsEntryProcessor
import org.springframework.stereotype.Component
@Component
class PrincipalExistsEntryProcessorStreamSerializer : NoOpSelfRegisteringStreamSerializer<PrincipalExistsEntryProcessor>() {
override fun getClazz(): Class<out PrincipalExistsEntryProcessor> {
return PrincipalExistsEntryProcessor::class.java
}
override fun read(`in`: ObjectDataInput?): PrincipalExistsEntryProcessor {
return PrincipalExistsEntryProcessor()
}
override fun getTypeId(): Int {
return StreamSerializerTypeIds.PRINCIPAL_EXISTS_ENTRY_PROCESSOR.ordinal
}
} | gpl-3.0 |
rahulsom/grooves | grooves-types/src/main/kotlin/com/github/rahulsom/grooves/api/events/package-info.kt | 1 | 122 | /**
* Types that deal with events that can be applied on an aggregate.
*/
package com.github.rahulsom.grooves.api.events | apache-2.0 |
googlecodelabs/fido2-codelab | android/app/src/main/java/com/example/android/fido2/ui/home/CredentialAdapter.kt | 2 | 2261 | /*
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.fido2.ui.home
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.android.fido2.api.Credential
import com.example.android.fido2.databinding.CredentialItemBinding
class CredentialAdapter(
private val onDeleteClicked: (String) -> Unit
) : ListAdapter<Credential, CredentialViewHolder>(DIFF_CALLBACK) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CredentialViewHolder {
return CredentialViewHolder(
CredentialItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
),
onDeleteClicked
)
}
override fun onBindViewHolder(holder: CredentialViewHolder, position: Int) {
holder.binding.credential = getItem(position)
}
}
private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Credential>() {
override fun areItemsTheSame(oldItem: Credential, newItem: Credential): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Credential, newItem: Credential): Boolean {
return oldItem == newItem
}
}
class CredentialViewHolder(
val binding: CredentialItemBinding,
onDeleteClicked: (String) -> Unit
) : RecyclerView.ViewHolder(binding.root) {
init {
binding.delete.setOnClickListener {
binding.credential?.let { c ->
onDeleteClicked(c.id)
}
}
}
}
| apache-2.0 |
encircled/jPut | jput-core/src/main/java/cz/encircled/jput/recorder/ResultRecorder.kt | 1 | 2386 | package cz.encircled.jput.recorder
import cz.encircled.jput.context.JPutContext
import cz.encircled.jput.context.getCollectionProperty
import cz.encircled.jput.model.PerfTestExecution
import cz.encircled.jput.trend.SelectionStrategy
import org.slf4j.LoggerFactory
/**
* @author Vlad on 21-May-17.
*/
interface ResultRecorder {
/**
* Fetch execution times sample for the given [execution]
*/
fun getSample(execution: PerfTestExecution): List<Long>
/**
* Select sub list of given [size] from [sample] according to the given [strategy]
*/
fun <T> subList(sample: List<T>, size: Int, strategy: SelectionStrategy): List<T> {
return if (sample.size > size) {
when (strategy) {
SelectionStrategy.USE_FIRST -> sample.subList(0, size)
SelectionStrategy.USE_LATEST -> sample.subList(sample.size - size, sample.size)
}
} else {
sample
}
}
/**
* Get user-defined environment parameters, which should be persisted along with test results
*/
fun getUserDefinedEnvParams(): Map<String, String> {
return getCollectionProperty(JPutContext.PROP_ENV_PARAMS)
.map { it.split(":") }
.associateBy({ it[0] }, { it[1] })
}
/**
* Append the new execution result
*/
fun appendTrendResult(execution: PerfTestExecution)
/**
* Flush appended data to the storage
*/
fun flush()
}
/**
* Primitive thread-safe abstract impl of [ResultRecorder]. Adds synchronization on append and flush.
*/
abstract class ThreadsafeResultRecorder : ResultRecorder {
private val log = LoggerFactory.getLogger(ThreadsafeResultRecorder::class.java)
private val stack = ArrayList<PerfTestExecution>()
private val flushMutex = Any()
override fun appendTrendResult(execution: PerfTestExecution) {
synchronized(stack) {
stack.add(execution)
log.info(execution.toString())
}
}
override fun flush() {
log.info("Do flush execution results")
synchronized(flushMutex) {
val copy = synchronized(stack) {
val c = ArrayList(stack)
stack.clear()
c
}
doFlush(copy)
}
}
abstract fun doFlush(data: List<PerfTestExecution>)
} | apache-2.0 |
danfma/kodando | kodando-store/src/main/kotlin/kodando/store/GlobalActionDispatcher.kt | 1 | 326 | package kodando.store
import kodando.rxjs.Observable
import kodando.rxjs.Subject
object GlobalActionDispatcher : ActionDispatcher {
private val actionS = Subject<Action>()
override fun dispatch(action: Action) {
actionS.next(action)
}
override fun asObservable(): Observable<Action> {
return actionS
}
}
| mit |
laurencegw/jenjin | jenjin-core/src/main/kotlin/com/binarymonks/jj/core/physics/PhysicsRoot.kt | 1 | 5267 | package com.binarymonks.jj.core.physics
import box2dLight.Light
import com.badlogic.gdx.math.MathUtils
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.Body
import com.badlogic.gdx.physics.box2d.Joint
import com.badlogic.gdx.physics.box2d.Transform
import com.badlogic.gdx.utils.Array
import com.binarymonks.jj.core.JJ
import com.binarymonks.jj.core.async.OneTimeTask
import com.binarymonks.jj.core.pools.Poolable
import com.binarymonks.jj.core.pools.new
import com.binarymonks.jj.core.scenes.Scene
import com.binarymonks.jj.core.utils.NamedArray
private val COLLISION_MASK_CACHE = "collision_mask_cache"
private val COLLISION_CAT_CACHE = "collision_cat_cache"
private val jointsToDestroy = Array<Joint>()
private val physicsPoolLocation = Vector2(10000f, 10000f)
private val NONE: Short = 0x0000
open class PhysicsRoot(val b2DBody: Body) {
var parent: Scene? = null
set(value) {
field = value
b2DBody.userData = value
collisionResolver.me = value
nodes.forEach { it.collisionResolver.me = value }
}
var nodes: NamedArray<PhysicsNode> = NamedArray()
var collisionResolver: CollisionResolver = CollisionResolver()
var lights: NamedArray<Light> = NamedArray()
fun position(): Vector2 {
return b2DBody.position
}
fun rotationR(): Float {
return b2DBody.angle
}
fun setPosition(x: Float, y: Float) {
b2DBody.setTransform(x, y, b2DBody.angle)
}
fun setPosition(position: Vector2) {
b2DBody.setTransform(position.x, position.y, b2DBody.angle)
}
fun setRotationR(rotation: Float) {
val position = b2DBody.position
b2DBody.setTransform(position.x, position.y, rotation)
}
val transform: Transform
get() = b2DBody.transform
fun hasProperty(propertyKey: String): Boolean {
if (parent != null) return parent!!.hasProp(propertyKey)
return false
}
fun getProperty(propertyKey: String): Any? {
if (parent != null) return parent!!.getProp(propertyKey)
return null
}
internal fun destroy(pooled: Boolean) {
collisionResolver.collisions.onRemoveFromWorld()
if (!pooled) {
JJ.B.physicsWorld.b2dworld.destroyBody(b2DBody)
} else {
neutralise()
}
}
internal fun neutralise() {
if (!JJ.B.physicsWorld.isUpdating) {
for (node in nodes) {
node.unStashFilter()
}
for (fixture in b2DBody.fixtureList) {
val sceneNode = fixture.userData as PhysicsNode
sceneNode.properties.put(COLLISION_CAT_CACHE, fixture.filterData.categoryBits)
sceneNode.properties.put(COLLISION_MASK_CACHE, fixture.filterData.maskBits)
val filterData = fixture.filterData
filterData.categoryBits = NONE
filterData.maskBits = NONE
fixture.filterData = filterData
}
jointsToDestroy.clear()
for (joint in b2DBody.jointList) {
jointsToDestroy.add(joint.joint)
}
for (joint in jointsToDestroy) {
JJ.B.physicsWorld.b2dworld.destroyJoint(joint)
}
jointsToDestroy.clear()
b2DBody.setTransform(physicsPoolLocation, 0f)
b2DBody.setLinearVelocity(Vector2.Zero)
b2DBody.setAngularVelocity(0f)
b2DBody.setActive(false)
b2DBody.setAwake(false)
for (light in lights) {
light.isActive = false
}
} else {
JJ.tasks.addPostPhysicsTask(
new(NeutralisePhysics::class)
.setRoot(this)
)
}
}
fun reset(x: Float, y: Float, rotationD: Float) {
for (fixture in b2DBody.fixtureList) {
val fixtureGameData = fixture.userData as PhysicsNode
val filterData = fixture.filterData
filterData.categoryBits = fixtureGameData.properties.get(COLLISION_CAT_CACHE) as Short
filterData.maskBits = fixtureGameData.properties.get(COLLISION_MASK_CACHE) as Short
fixture.filterData = filterData
}
b2DBody.setTransform(x, y, rotationD * MathUtils.degreesToRadians)
b2DBody.isActive = true
b2DBody.isAwake = true
for (light in lights) {
light.isActive = true
}
}
fun addNode(physicsNode: PhysicsNode) {
if(physicsNode.name != null){
nodes.add(physicsNode.name!!,physicsNode)
}else{
nodes.add(physicsNode)
}
}
fun getNode(name:String): PhysicsNode? {
return nodes.get(name)
}
fun onAddToWorld() {
collisionResolver.collisions.onAddToWorld()
}
}
class NeutralisePhysics : OneTimeTask(), Poolable {
internal var physicsRoot: PhysicsRoot? = null
fun setRoot(physicsRoot: PhysicsRoot): NeutralisePhysics {
this.physicsRoot = physicsRoot
return this
}
override fun reset() {
physicsRoot = null
}
override fun doOnce() {
checkNotNull(physicsRoot).neutralise()
}
}
| apache-2.0 |
b95505017/android-architecture-components | PagingWithNetworkSample/app/src/main/java/com/android/example/paging/pagingwithnetwork/reddit/repository/inMemory/byItem/InMemoryByItemRepository.kt | 1 | 2949 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.paging.pagingwithnetwork.reddit.repository.inMemory.byItem
import android.arch.lifecycle.Transformations
import android.arch.paging.LivePagedListBuilder
import android.arch.paging.PagedList
import android.support.annotation.MainThread
import com.android.example.paging.pagingwithnetwork.reddit.api.RedditApi
import com.android.example.paging.pagingwithnetwork.reddit.repository.Listing
import com.android.example.paging.pagingwithnetwork.reddit.repository.RedditPostRepository
import com.android.example.paging.pagingwithnetwork.reddit.vo.RedditPost
import java.util.concurrent.Executor
/**
* Repository implementation that returns a Listing that loads data directly from the network
* and uses the Item's name as the key to discover prev/next pages.
*/
class InMemoryByItemRepository(
private val redditApi: RedditApi,
private val networkExecutor: Executor) : RedditPostRepository {
@MainThread
override fun postsOfSubreddit(subredditName: String, pageSize: Int): Listing<RedditPost> {
val sourceFactory = SubRedditDataSourceFactory(redditApi, subredditName, networkExecutor)
val pagedListConfig = PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setInitialLoadSizeHint(pageSize * 2)
.setPageSize(pageSize)
.build()
val pagedList = LivePagedListBuilder(sourceFactory, pagedListConfig)
// provide custom executor for network requests, otherwise it will default to
// Arch Components' IO pool which is also used for disk access
.setBackgroundThreadExecutor(networkExecutor)
.build()
val refreshState = Transformations.switchMap(sourceFactory.sourceLiveData) {
it.initialLoad
}
return Listing(
pagedList = pagedList,
networkState = Transformations.switchMap(sourceFactory.sourceLiveData, {
it.networkState
}),
retry = {
sourceFactory.sourceLiveData.value?.retryAllFailed()
},
refresh = {
sourceFactory.sourceLiveData.value?.invalidate()
},
refreshState = refreshState
)
}
}
| apache-2.0 |
opengl-8080/kotlin-lifegame | src/main/kotlin/gl8080/lifegame/logic/definition/GameDefinition.kt | 1 | 2525 | package gl8080.lifegame.logic.definition
import gl8080.lifegame.logic.AbstractEntity
import gl8080.lifegame.logic.LifeGame
import gl8080.lifegame.logic.LifeGameCell
import gl8080.lifegame.logic.Position
import gl8080.lifegame.logic.exception.IllegalParameterException
import gl8080.lifegame.util.NestedLoop
import java.util.*
import javax.persistence.*
/**
* ゲーム定義を表すクラス。
*/
@Entity
@Table(name="GAME_DEFINITION")
class GameDefinition(
private val size: Int
): AbstractEntity(), LifeGame {
companion object {
/**ゲームのサイズに指定できる最大値*/
val MAX_SIZE = 50
}
@Version
private var version: Long? = null
@OneToMany(cascade = arrayOf(CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE))
@JoinColumn(name="GAME_DEFINITION_ID")
private val cells: Map<Position, CellDefinition>
init {
if (this.size < 1) {
throw IllegalParameterException("サイズに0以外の値は指定できません size = ${this.size}")
} else if (MAX_SIZE < this.size) {
throw IllegalParameterException("サイズに $MAX_SIZE 以上の値は指定できません size = ${this.size}")
}
this.cells = NestedLoop.collectMap(this.size, {i: Int, j: Int -> Position(i, j)}, { -> CellDefinition()})
}
/**
* 指定した位置のセル定義の状態を変更します。
*
* @param position 位置
* @param status 生存に変更する場合は {@code true}
* @throws IllegalArgumentException 位置が {@code null} の場合
* @throws IllegalParameterException 位置に指定した場所にセル定義が存在しない場合
*/
fun setStatus(position: Position, status: Boolean) {
val cell = this.cells[position]
?: throw IllegalParameterException("位置が範囲外です (size = ${this.size}, position = $position)")
cell.setStatus(status)
}
override fun getCells(): Map<Position, LifeGameCell> = HashMap(this.cells)
override fun getVersion() = this.version
fun setVersion(version: Long?) {
this.version = version
}
override fun getSize() = this.size
override fun toString(): String{
return "GameDefinition(id=${this.getId()}, size=$size, version=$version, cells=$cells)"
}
@Deprecated(message="JPA 用", level = DeprecationLevel.ERROR)
constructor() : this(1)
}
| mit |
square/duktape-android | zipline/src/commonMain/kotlin/app/cash/zipline/serializers.kt | 1 | 2779 | /*
* Copyright (C) 2022 Block, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.zipline
import app.cash.zipline.internal.bridge.ZiplineServiceAdapter
import kotlin.reflect.KClass
import kotlinx.serialization.KSerializer
/**
* Returns a [KSerializer] for [T] that performs pass-by-reference instead of pass-by-value. This is
* only necessary when a service is passed as a member of another serializable type; Zipline
* automatically does pass-by-reference for service parameters and return values.
*
* To use this, first register the serializer for your service in a
* [kotlinx.serialization.modules.SerializersModule].
*
* ```kotlin
* val mySerializersModule = SerializersModule {
* contextual(EchoService::class, ziplineServiceSerializer())
* }
* ```
*
* Next, use that [kotlinx.serialization.modules.SerializersModule] when you create your Zipline
* instance, in both the host application and the Kotlin/JS code:
*
* ```kotlin
* val zipline = Zipline.create(dispatcher, mySerializersModule)
* ```
*
* Finally, annotate the service property with [kotlinx.serialization.Contextual]. This instructs
* Kotlin serialization to use the registered serializer.
*
* ```kotlin
* @Serializable
* data class ServiceCreatedResult(
* val greeting: String,
* @Contextual val service: EchoService,
* )
* ```
*
* The caller must call [ZiplineService.close] when they are done with the returned service to
* release the held reference.
*/
fun <T : ZiplineService> ziplineServiceSerializer() : KSerializer<T> {
error("unexpected call to ziplineServiceSerializer(): is the Zipline plugin configured?")
}
/**
* Returns a [KSerializer] for [T] that performs pass-by-reference instead of pass-by-value. Use
* this when implementing contextual serialization for a parameterized type.
*/
fun <T : ZiplineService> ziplineServiceSerializer(
kClass: KClass<*>,
typeArgumentsSerializers: List<KSerializer<*>> = emptyList()
) : KSerializer<T> {
error("unexpected call to ziplineServiceSerializer(): is the Zipline plugin configured?")
}
@PublishedApi
internal fun <T : ZiplineService> ziplineServiceSerializer(
ziplineServiceAdapter: ZiplineServiceAdapter<T>
) : KSerializer<T> {
return ziplineServiceAdapter
}
| apache-2.0 |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/pages/AnkiServer.kt | 1 | 4473 | /*
* Copyright (c) 2022 Mani <[email protected]>
* Copyright (c) 2022 Brayan Oliveira <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.pages
import com.ichi2.anki.CollectionManager.withCol
import com.ichi2.anki.importCsvRaw
import com.ichi2.anki.runBlockingCatching
import com.ichi2.libanki.*
import com.ichi2.libanki.importer.getCsvMetadataRaw
import com.ichi2.libanki.stats.*
import fi.iki.elonen.NanoHTTPD
import timber.log.Timber
import java.io.ByteArrayInputStream
class AnkiServer(
hostname: String?,
port: Int,
val activity: PagesActivity
) : NanoHTTPD(hostname, port) {
override fun serve(session: IHTTPSession): Response {
val uri = session.uri
val mime = getMimeFromUri(uri)
if (session.method == Method.GET) {
Timber.d("GET: Requested %s", uri)
return newChunkedResponse(Response.Status.OK, mime, this.javaClass.classLoader!!.getResourceAsStream("web$uri"))
}
if (session.method == Method.POST) {
Timber.d("POST: Requested %s", uri)
val inputBytes = getSessionBytes(session)
if (uri.startsWith(ANKI_PREFIX)) {
val data: ByteArray? = activity.runBlockingCatching {
handlePostRequest(uri.substring(ANKI_PREFIX.length), inputBytes)
}
return newChunkedResponse(data)
}
}
return newFixedLengthResponse(null)
}
private suspend fun handlePostRequest(methodName: String, bytes: ByteArray): ByteArray? {
return when (methodName) {
"i18nResources" -> withCol { newBackend.i18nResourcesRaw(bytes) }
"getGraphPreferences" -> withCol { newBackend.getGraphPreferencesRaw() }
"setGraphPreferences" -> withCol { newBackend.setGraphPreferencesRaw(bytes) }
"graphs" -> withCol { newBackend.graphsRaw(bytes) }
"getNotetypeNames" -> withCol { newBackend.getNotetypeNamesRaw(bytes) }
"getDeckNames" -> withCol { newBackend.getDeckNamesRaw(bytes) }
"getCsvMetadata" -> withCol { newBackend.getCsvMetadataRaw(bytes) }
"importCsv" -> activity.importCsvRaw(bytes)
"getFieldNames" -> withCol { newBackend.getFieldNamesRaw(bytes) }
"cardStats" -> withCol { newBackend.cardStatsRaw(bytes) }
"getDeckConfig" -> withCol { newBackend.getDeckConfigRaw(bytes) }
"getDeckConfigsForUpdate" -> withCol { newBackend.getDeckConfigsForUpdateRaw(bytes) }
"updateDeckConfigs" -> activity.updateDeckConfigsRaw(bytes)
else -> { Timber.w("Unhandled Anki request: %s", methodName); null }
}
}
private fun getSessionBytes(session: IHTTPSession): ByteArray {
val contentLength = session.headers["content-length"]!!.toInt()
val bytes = ByteArray(contentLength)
session.inputStream.read(bytes, 0, contentLength)
return bytes
}
companion object {
/** Common prefix used on Anki requests */
const val ANKI_PREFIX = "/_anki/"
fun getMimeFromUri(uri: String): String {
return when (uri.substringAfterLast(".")) {
"ico" -> "image/x-icon"
"css" -> "text/css"
"js" -> "text/javascript"
"html" -> "text/html"
else -> "application/binary"
}
}
fun newChunkedResponse(
data: ByteArray?,
mimeType: String = "application/binary",
status: Response.IStatus = Response.Status.OK
): Response {
return if (data == null) {
newFixedLengthResponse(null)
} else {
newChunkedResponse(status, mimeType, ByteArrayInputStream(data))
}
}
}
}
| gpl-3.0 |
akvo/akvo-flow-mobile | data/src/main/java/org/akvo/flow/data/entity/form/DataSurveyMapper.kt | 1 | 1150 | /*
* Copyright (C) 2021 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Flow.
*
* Akvo Flow 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.
*
* Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>.
*/
package org.akvo.flow.data.entity.form
import org.akvo.flow.data.entity.ApiFormHeader
import javax.inject.Inject
class DataSurveyMapper @Inject constructor() {
fun map(apiFormHeader: ApiFormHeader): DataSurvey {
return DataSurvey(apiFormHeader.groupId.toLong(),
apiFormHeader.groupName,
apiFormHeader.isMonitored,
apiFormHeader.registrationSurveyId)
}
}
| gpl-3.0 |
CarrotCodes/Pellet | server/src/main/kotlin/dev/pellet/server/codec/http/HTTPHeaderConstants.kt | 1 | 356 | package dev.pellet.server.codec.http
object HTTPHeaderConstants {
const val contentLength = "Content-Length"
const val contentType = "Content-Type"
const val transferEncoding = "Transfer-Encoding"
const val chunked = "chunked"
const val connection = "Connection"
const val keepAlive = "keep-alive"
const val close = "close"
}
| apache-2.0 |
wleroux/fracturedskies | src/main/kotlin/com/fracturedskies/light/SkyLightSystem.kt | 1 | 4982 | package com.fracturedskies.light
import com.fracturedskies.api.*
import com.fracturedskies.api.block.Block
import com.fracturedskies.api.block.data.SkyLight
import com.fracturedskies.engine.api.Cause
import com.fracturedskies.engine.collections.*
import com.fracturedskies.engine.math.Vector3i
import java.lang.Integer.max
import java.util.*
import javax.enterprise.event.Observes
import javax.inject.*
import kotlin.collections.HashSet
@Singleton
class SkyLightSystem {
@Inject
lateinit var world: World
private var initialized = false
private lateinit var light: IntMutableSpace
private lateinit var opaque: BooleanMutableSpace
fun onWorldGenerated(@Observes message: WorldGenerated) {
message.blocks.forEach(this::updateLocalCache)
val sky = mutableListOf<Vector3i>()
(0 until world.width).forEach { x ->
(0 until world.depth).forEach { z ->
sky.add(Vector3i(x, world.height - 1, z))
}
}
refresh(sky)
}
fun onBlocksUpdated(@Observes message: BlocksUpdated) {
message.blocks.forEach { update -> updateLocalCache(update.position, update.target) }
refresh(message.blocks
.filter { it.original.type.opaque != it.target.type.opaque || it.original[SkyLight::class] != it.target[SkyLight::class] }
.map(BlockUpdate::position))
}
private fun updateLocalCache(position: Vector3i, target: Block) {
if (!initialized) {
light = IntMutableSpace(world.dimension, {0})
opaque = BooleanMutableSpace(world.dimension, {false})
initialized = true
}
light[position] = target[SkyLight::class]!!.value
opaque[position] = target.type.opaque
}
private fun refresh(positions: Collection<Vector3i>) {
if (positions.isEmpty()) return
val lightSources = mutableListOf<Vector3i>()
// If not opaque, propagate the light!
positions
.filter { !opaque[it] }
.toCollection(lightSources)
// If opaque, any blocks that may have been lighted by this one are updated to zero...
// Then any adjacent lights that may have lighted them are added to the list of light propagators
val darkenedCells = darken(positions.filter { opaque[it] })
darkenedCells.asSequence()
.flatMap(light::neighbors)
.toCollection(lightSources)
darkenedCells
.filter { it.y == light.height - 1 }
.toCollection(lightSources)
// Any position that is acting as a light source should propagate the light!
val lightenedCells = lighten(lightSources.filter { !opaque[it] })
// Update the world
val blocks = (darkenedCells + lightenedCells)
.filter { light[it] != world.blocks[it][SkyLight::class]!!.value }
.distinct()
.map { it to world.blocks[it].with(SkyLight(light[it])) }
.toMap()
if (blocks.isNotEmpty()) {
world.updateBlocks(blocks, Cause.of(this))
}
}
private fun darken(initialPositions: List<Vector3i>): Collection<Vector3i> {
val darkenedCells = HashSet<Vector3i>()
val unvisitedCells = LinkedList<Vector3i>()
initialPositions.asSequence().flatMap(light::neighbors)
.toCollection(unvisitedCells)
while (unvisitedCells.isNotEmpty()) {
val pos = unvisitedCells.remove()
if (light[pos] == 0) continue
light.neighbors(pos)
.filter { !darkenedCells.contains(it) }
.filter {
if (pos.y > it.y) light[pos] >= light[it]
else light[pos] > light[it]
}
.toCollection(unvisitedCells)
darkenedCells.add(pos)
light[pos] = 0
}
return darkenedCells
}
private fun targetLight(pos: Vector3i): Int {
val topPos = light.top(pos)
return when {
topPos == null -> MAX_LIGHT_LEVEL
light[topPos] == MAX_LIGHT_LEVEL -> MAX_LIGHT_LEVEL
else -> max(0, (light.neighbors(pos).map {light[it]}.max() ?: 0) - 1)
}
}
data class Lighten(val position: Vector3i, val targetLight: Int)
private fun lighten(initialPositions: List<Vector3i>): Collection<Vector3i> {
val lightenedCells = HashSet<Vector3i>()
val unvisitedCells = PriorityQueue<Lighten>({ a, b -> -a.targetLight.compareTo(b.targetLight)})
initialPositions
.asSequence()
.map { Lighten(it, targetLight(it)) }
.toCollection(unvisitedCells)
while (unvisitedCells.isNotEmpty()) {
val (pos, targetLight) = unvisitedCells.poll()
if (light[pos] >= targetLight) continue
light[pos] = targetLight
lightenedCells.add(pos)
world.neighbors(pos)
.filter { !opaque[it] }
.map {
val propagateLight = when {
targetLight == MAX_LIGHT_LEVEL && pos.y > it.y -> MAX_LIGHT_LEVEL
else -> targetLight - 1
}
Lighten(it, propagateLight)
}
.filter { light[it.position] < it.targetLight }
.filter { it.targetLight > 0 }
.toCollection(unvisitedCells)
}
return lightenedCells
}
} | unlicense |
wleroux/fracturedskies | src/main/kotlin/com/fracturedskies/engine/math/Color4.kt | 1 | 1013 | package com.fracturedskies.engine.math
import org.lwjgl.BufferUtils
data class Color4(val red: Int, val green: Int, val blue: Int, val alpha: Int) {
companion object {
val WHITE = Color4(255, 255, 255, 255)
val GREEN = Color4(142, 204, 149, 255)
val DARK_GREEN = Color4(76, 118, 81, 255)
val BROWN = Color4(178, 161, 130, 255)
val GRAY = Color4(172, 175, 174, 255)
val DARK_BROWN = Color4(114, 110, 105, 255)
val BLACK = Color4(0, 0, 0, 255)
val WATER = Color4(138, 172, 206, 200)
}
fun toFloat(): Float {
val colorBuffer = BufferUtils.createByteBuffer(4)
colorBuffer.put(red.toByte())
colorBuffer.put(green.toByte())
colorBuffer.put(blue.toByte())
colorBuffer.put(alpha.toByte())
colorBuffer.flip()
return colorBuffer.asFloatBuffer().get(0)
}
operator fun div(value: Int) = Color4(red / value, green / value, blue / value, alpha / value)
operator fun times(value: Int) = Color4(red * value, green * value, blue * value, alpha * value)
} | unlicense |
arpitkh96/AmazeFileManager | app/src/test/java/com/amaze/filemanager/asynchronous/asynctasks/SmbDeleteTaskTest.kt | 1 | 2163 | /*
* Copyright (C) 2014-2020 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.asynchronous.asynctasks
import android.os.Build.VERSION_CODES.*
import com.amaze.filemanager.filesystem.HybridFileParcelable
import com.amaze.filemanager.shadows.ShadowMultiDex
import com.amaze.filemanager.shadows.ShadowSmbUtil
import com.amaze.filemanager.shadows.ShadowSmbUtil.Companion.PATH_CANNOT_DELETE_FILE
import com.amaze.filemanager.utils.SmbUtil
import org.junit.Test
import org.robolectric.annotation.Config
@Config(shadows = [ShadowMultiDex::class, ShadowSmbUtil::class], sdk = [JELLY_BEAN, KITKAT, P])
class SmbDeleteTaskTest : AbstractDeleteTaskTestBase() {
/**
* Test case to verify delete SMB file success scenario.
*
* @see AbstractDeleteTaskTestBase.doTestDeleteFileOk
*/
@Test
fun testDeleteSmbFileOk() {
doTestDeleteFileOk(
HybridFileParcelable(SmbUtil.create("smb://user:[email protected]/just/a/file.txt"))
)
}
/**
* Test case to verify delete SSH file failure scenario.
*
* @see AbstractDeleteTaskTestBase.doTestDeleteFileAccessDenied
*/
@Test
fun testDeleteSmbFileAccessDenied() {
doTestDeleteFileAccessDenied(HybridFileParcelable(SmbUtil.create(PATH_CANNOT_DELETE_FILE)))
}
}
| gpl-3.0 |
matkoniecz/StreetComplete | app/src/test/java/de/westnordost/streetcomplete/data/osm/edits/MapDataWithEditsSourceTest.kt | 1 | 34811 | package de.westnordost.streetcomplete.data.osm.edits
import de.westnordost.streetcomplete.testutils.any
import de.westnordost.streetcomplete.data.osm.geometry.ElementGeometryCreator
import de.westnordost.streetcomplete.data.osm.geometry.ElementGeometryEntry
import de.westnordost.streetcomplete.data.osm.mapdata.*
import de.westnordost.streetcomplete.data.osm.mapdata.ElementType.*
import de.westnordost.streetcomplete.data.upload.ConflictException
import de.westnordost.streetcomplete.testutils.eq
import de.westnordost.streetcomplete.ktx.containsExactlyInAnyOrder
import de.westnordost.streetcomplete.testutils.*
import de.westnordost.streetcomplete.util.intersect
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers.anyLong
import org.mockito.Mockito.*
class MapDataWithEditsSourceTest {
private lateinit var editsCtrl: ElementEditsController
private lateinit var mapDataCtrl: MapDataController
private val geometryCreator = ElementGeometryCreator()
private lateinit var mapData: MutableMapDataWithGeometry
private lateinit var editsListener: ElementEditsSource.Listener
private lateinit var mapDataListener: MapDataController.Listener
@Before
fun setUp() {
editsCtrl = mock()
mapDataCtrl = mock()
mapData = MutableMapDataWithGeometry()
// a trick to get the edit action to apply to anything
mapData.putElement(node(-1, pos = p(60.0, 60.0)))
on(editsCtrl.getIdProvider(anyLong())).thenReturn(ElementIdProvider(listOf()))
on(mapDataCtrl.get(any(), anyLong())).thenAnswer { invocation ->
val elementType = invocation.getArgument<ElementType>(0)!!
val elementId = invocation.getArgument<Long>(1)
when(elementType) {
NODE -> mapData.getNode(elementId)
WAY -> mapData.getWay(elementId)
RELATION -> mapData.getRelation(elementId)
}
}
on(mapDataCtrl.getNode(anyLong())).thenAnswer { invocation ->
mapData.getNode(invocation.getArgument(0))
}
on(mapDataCtrl.getWay(anyLong())).thenAnswer { invocation ->
mapData.getWay(invocation.getArgument(0))
}
on(mapDataCtrl.getRelation(anyLong())).thenAnswer { invocation ->
mapData.getRelation(invocation.getArgument(0))
}
on(mapDataCtrl.getNodes(any())).thenAnswer { invocation ->
invocation.getArgument<Collection<Long>>(0).mapNotNull { mapData.getNode(it) }
}
on(mapDataCtrl.getWays(any())).thenAnswer { invocation ->
invocation.getArgument<Collection<Long>>(0).mapNotNull { mapData.getWay(it) }
}
on(mapDataCtrl.getRelations(any())).thenAnswer { invocation ->
invocation.getArgument<Collection<Long>>(0).mapNotNull { mapData.getRelation(it) }
}
on(mapDataCtrl.getAll(any())).thenAnswer { invocation ->
invocation.getArgument<Collection<ElementKey>>(0).mapNotNull {
when(it.type) {
NODE -> mapData.getNode(it.id)
WAY -> mapData.getWay(it.id)
RELATION -> mapData.getRelation(it.id)
}
}
}
on(mapDataCtrl.getWaysForNode(anyLong())).thenAnswer { invocation ->
val nodeId = invocation.getArgument<Long>(0)
mapData.ways.filter { it.nodeIds.contains(nodeId) }
}
on(mapDataCtrl.getRelationsForNode(anyLong())).thenAnswer { invocation ->
val nodeId = invocation.getArgument<Long>(0)
mapData.relations.filter { r -> r.members.any { it.ref == nodeId && it.type == NODE } }
}
on(mapDataCtrl.getRelationsForWay(anyLong())).thenAnswer { invocation ->
val wayId = invocation.getArgument<Long>(0)
mapData.relations.filter { r -> r.members.any { it.ref == wayId && it.type == WAY } }
}
on(mapDataCtrl.getRelationsForRelation(anyLong())).thenAnswer { invocation ->
val relationId = invocation.getArgument<Long>(0)
mapData.relations.filter { r -> r.members.any { it.ref == relationId && it.type == RELATION } }
}
on(mapDataCtrl.getGeometry(any(), anyLong())).thenAnswer { invocation ->
val elementType = invocation.getArgument<ElementType>(0)!!
val elementId = invocation.getArgument<Long>(1)
when(elementType) {
NODE -> mapData.getNodeGeometry(elementId)
WAY -> mapData.getWayGeometry(elementId)
RELATION -> mapData.getRelationGeometry(elementId)
}
}
on(mapDataCtrl.getGeometries(any())).thenAnswer { invocation ->
val keys = invocation.getArgument<Collection<ElementKey>>(0)!!
keys.mapNotNull { key ->
when(key.type) {
NODE -> mapData.getNodeGeometry(key.id)
WAY -> mapData.getWayGeometry(key.id)
RELATION -> mapData.getRelationGeometry(key.id)
}?.let {
ElementGeometryEntry(
key.type,
key.id,
it
)
}
}
}
on(mapDataCtrl.getMapDataWithGeometry(any())).thenAnswer { invocation ->
val bbox = invocation.getArgument<BoundingBox>(0)
val result = MutableMapDataWithGeometry()
for (element in mapData) {
val geometry = when(element.type) {
NODE -> mapData.getNodeGeometry(element.id)
WAY -> mapData.getWayGeometry(element.id)
RELATION -> mapData.getRelationGeometry(element.id)
}
if (geometry != null && geometry.getBounds().intersect(bbox)) {
result.put(element, geometry)
}
}
result
}
on(editsCtrl.addListener(any())).then { invocation ->
editsListener = invocation.getArgument(0)
Unit
}
on(mapDataCtrl.addListener(any())).then { invocation ->
mapDataListener = invocation.getArgument(0)
Unit
}
}
//region get
@Test
fun `get returns nothing`() {
thereAreNoOriginalElements()
thereAreNoMapDataChanges()
val s = create()
assertNull(s.get(NODE, 1))
}
@Test
fun `get returns original element`() {
val nd = node(1)
originalElementsAre(nd)
thereAreNoMapDataChanges()
val s = create()
assertEquals(nd, s.get(NODE, 1))
}
@Test
fun `get returns updated element`() {
val nd = node(1)
val nd2 = node(1, tags = mapOf("bla" to "blub"))
originalElementsAre(nd)
mapDataChangesAre(modifications = listOf(nd2))
val s = create()
assertEquals(nd2, s.get(NODE, 1))
}
@Test
fun `get returns updated element updated from updated element`() {
val nd = node(1)
val nd2 = node(1, tags = mapOf("bla" to "blub"))
val nd3 = node(1, tags = mapOf("bla" to "flop"))
originalElementsAre(nd)
val action2 = mock<ElementEditAction>()
on(action2.createUpdates(any(), eq(nd), any(), any())).thenReturn(MapDataChanges(modifications = listOf(nd2)))
val action3 = mock<ElementEditAction>()
on(action3.createUpdates(any(), eq(nd2), any(), any())).thenReturn(MapDataChanges(modifications = listOf(nd3)))
on(editsCtrl.getAllUnsynced()).thenReturn(listOf(
edit(element = nd, action = action2),
edit(element = nd, action = action3),
))
val s = create()
assertEquals(nd3, s.get(NODE, 1))
}
@Test
fun `get returns null if updated element was deleted`() {
val nd = node(1)
val nd2 = node(1)
originalElementsAre(nd)
mapDataChangesAre(deletions = listOf(nd2))
val s = create()
assertNull(s.get(NODE, 1))
}
@Test
fun `conflict on applying edit is ignored`() {
val nd = node(1)
originalElementsAre(nd)
val action = mock<ElementEditAction>()
on(action.createUpdates(eq(nd), eq(nd), any(), any())).thenThrow(ConflictException())
on(editsCtrl.getAllUnsynced()).thenReturn(listOf(edit(element = nd, action = action)))
val s = create()
assertEquals(nd, s.get(NODE, 1))
}
//endregion
//region getGeometry
@Test
fun `getGeometry returns nothing`() {
thereAreNoOriginalGeometries()
thereAreNoMapDataChanges()
val s = create()
assertNull(s.getGeometry(NODE, 1))
assertEquals(emptyList<ElementGeometryEntry>(), s.getGeometries(listOf(ElementKey(NODE, 1))))
}
@Test
fun `getGeometry returns original geometry`() {
val p = pGeom(0.0, 0.0)
originalGeometriesAre(ElementGeometryEntry(NODE, 1, p))
thereAreNoMapDataChanges()
val s = create()
assertEquals(p, s.getGeometry(NODE, 1))
assertEquals(
listOf(ElementGeometryEntry(NODE, 1, p)),
s.getGeometries(listOf(ElementKey(NODE, 1)))
)
}
@Test
fun `getGeometry returns updated geometry`() {
val nd = node(1, pos = p(0.0, 0.0))
val p = pGeom(0.0, 0.0)
val nd2 = node(1, pos = p(1.0, 2.0))
val p2 = pGeom(1.0, 2.0)
originalElementsAre(nd)
originalGeometriesAre(ElementGeometryEntry(NODE, 1, p))
mapDataChangesAre(modifications = listOf(nd2))
val s = create()
assertEquals(p2, s.getGeometry(NODE, 1))
assertEquals(
listOf(ElementGeometryEntry(NODE, 1, p2)),
s.getGeometries(listOf(ElementKey(NODE, 1)))
)
}
@Test
fun `getGeometry returns updated geometry updated from updated element`() {
val nd = node(1)
val nd2 = node(1, pos = p(1.0,2.0))
val nd3 = node(1, pos = p(55.0,56.0))
val p = pGeom(0.0, 0.0)
val p3 = pGeom(55.0, 56.0)
originalElementsAre(nd)
originalGeometriesAre(ElementGeometryEntry(NODE, 1, p))
val action2 = mock<ElementEditAction>()
on(action2.createUpdates(any(), eq(nd), any(), any())).thenReturn(MapDataChanges(modifications = listOf(nd2)))
val action3 = mock<ElementEditAction>()
on(action3.createUpdates(any(), eq(nd2), any(), any())).thenReturn(MapDataChanges(modifications = listOf(nd3)))
on(editsCtrl.getAllUnsynced()).thenReturn(listOf(
edit(element = nd, action = action2),
edit(element = nd, action = action3)
))
val s = create()
assertEquals(p3, s.getGeometry(NODE, 1))
assertEquals(
listOf(ElementGeometryEntry(NODE, 1, p3)),
s.getGeometries(listOf(ElementKey(NODE, 1)))
)
}
@Test
fun `getGeometry returns null if element was deleted`() {
val nd = node(1)
val nd2 = node(1)
val p = pGeom(0.0, 0.0)
originalElementsAre(nd)
originalGeometriesAre(ElementGeometryEntry(NODE, 1, p))
mapDataChangesAre(deletions = listOf(nd2))
val s = create()
assertNull(s.getGeometry(NODE, 1))
assertEquals(
emptyList<ElementGeometryEntry>(),
s.getGeometries(listOf(ElementKey(NODE, 1)))
)
}
@Test
fun `getGeometry returns null if element was updated with invalid geometry`() {
val way = way(1, listOf(1,2))
val wayNew = way(1, listOf())
val p1 = pGeom(0.0, 0.0)
val p2 = pGeom(1.0, 0.0)
originalElementsAre(way)
originalGeometriesAre(
ElementGeometryEntry(NODE, 1, p1),
ElementGeometryEntry(NODE, 2, p2)
)
mapDataChangesAre(modifications = listOf(wayNew))
val s = create()
assertNull(s.getGeometry(WAY, 1))
assertEquals(
emptyList<ElementGeometryEntry>(),
s.getGeometries(listOf(ElementKey(WAY, 1)))
)
}
//endregion
//region getWayComplete
@Test
fun `getWayComplete returns null`() {
thereAreNoOriginalElements()
thereAreNoMapDataChanges()
val s = create()
assertNull(s.getWayComplete(1))
}
@Test
fun `getWayComplete returns null because it is not complete`() {
val w = way(1, listOf(1,2,3))
originalElementsAre(w, node(1), node(2))
thereAreNoMapDataChanges()
val s = create()
assertNull(s.getWayComplete(1))
}
@Test
fun `getWayComplete returns original way with original node ids`() {
val w = way(1, listOf(1,2,3))
val n1 = node(1)
val n2 = node(2)
val n3 = node(3)
originalElementsAre(w, n1, n2, n3)
thereAreNoMapDataChanges()
val s = create()
val data = s.getWayComplete(1)!!
assertEquals(w, data.ways.single())
assertTrue(data.nodes.containsExactlyInAnyOrder(listOf(n1,n2,n3)))
}
@Test
fun `getWayComplete returns original way with updated node ids`() {
val w = way(1, listOf(1,2,3))
val nd1 = node(1)
val nd2 = node(2)
val nd3 = node(3)
val nd1New = node(1, tags = mapOf("foo" to "bar"))
originalElementsAre(nd1, nd2, nd3, w)
mapDataChangesAre(modifications = listOf(nd1New))
val s = create()
val data = s.getWayComplete(1)!!
assertEquals(w, data.ways.single())
assertTrue(data.nodes.containsExactlyInAnyOrder(listOf(nd1New, nd2, nd3)))
}
@Test
fun `getWayComplete returns updated way with updated node ids`() {
val w = way(1, listOf(1,2))
val wNew = way(1, listOf(3, 1))
val nd1 = node(1)
val nd2 = node(2)
val nd1New = node(1, tags = mapOf("foo" to "bar"))
val nd2NewDeleted = node(2)
val nd3New = node(3)
originalElementsAre(nd1, nd2, w)
mapDataChangesAre(modifications = listOf(nd1New, nd3New, wNew), deletions = listOf(nd2NewDeleted))
val s = create()
val data = s.getWayComplete(1)!!
assertEquals(wNew, data.ways.single())
assertTrue(data.nodes.containsExactlyInAnyOrder(listOf(nd1New, nd3New)))
}
@Test
fun `getWayComplete returns null because a node of the way was deleted`() {
val w = way(1, listOf(1,2))
val nd1 = node(1)
val nd1NewDeleted = node(1)
originalElementsAre(w, nd1)
mapDataChangesAre(deletions = listOf(nd1NewDeleted))
val s = create()
assertNull(s.getWayComplete(1))
}
//endregion
//region getRelationComplete
@Test
fun `getRelationComplete returns null`() {
thereAreNoOriginalElements()
thereAreNoMapDataChanges()
val s = create()
assertNull(s.getRelationComplete(1))
}
@Test
fun `getRelationComplete returns incomplete relation`() {
val r = rel(1, listOf(
member(WAY, 1),
member(WAY, 2),
))
val w = way(1, listOf(1,2))
val n1 = node(1)
val n2 = node(2)
originalElementsAre(r, w, n1, n2)
thereAreNoMapDataChanges()
val s = create()
val data = s.getRelationComplete(1)!!
assertEquals(w, data.ways.single())
assertEquals(r, data.relations.single())
}
@Test
fun `getRelationComplete returns original relation with original members`() {
val n1 = node(1)
val n2 = node(2)
val n3 = node(3)
val n4 = node(4)
val n5 = node(5)
val w1 = way(1, listOf(1,2))
val w2 = way(2, listOf(3,4))
val r = rel(1, listOf(
member(WAY, 1),
member(WAY, 2),
member(NODE, 5),
member(RELATION, 2),
))
val r2 = rel(2)
originalElementsAre(r, r2, w1, w2, n1, n2, n3, n4, n5)
thereAreNoMapDataChanges()
val s = create()
val data = s.getRelationComplete(1)!!
assertTrue(data.relations.containsExactlyInAnyOrder(listOf(r, r2)))
assertTrue(data.ways.containsExactlyInAnyOrder(listOf(w1,w2)))
assertTrue(data.nodes.containsExactlyInAnyOrder(listOf(n1,n2,n3,n4,n5)))
}
@Test
fun `getRelationComplete returns relation with updated members`() {
val n1 = node(1)
val n2 = node(2)
val n3 = node(3)
val w = way(1, listOf(1,2))
val r = rel(1, listOf(
member(WAY, 1),
member(NODE, 3),
member(RELATION,2),
))
val r2 = rel(2)
originalElementsAre(r, r2, w, n1, n2, n3)
val n4 = node(4)
val n1New = node(1, tags = mapOf("ha" to "huff"))
val wNew = way(1, listOf(1, 4))
val r2NewDeleted = rel(2)
mapDataChangesAre(modifications = listOf(n4, wNew, n1New), deletions = listOf(r2NewDeleted))
val s = create()
val data = s.getRelationComplete(1)!!
assertTrue(data.relations.containsExactlyInAnyOrder(listOf(r)))
assertTrue(data.ways.containsExactlyInAnyOrder(listOf(wNew)))
assertTrue(data.nodes.containsExactlyInAnyOrder(listOf(n1New,n4,n3)))
}
//endregion
//region getWaysForNode
@Test
fun `getWaysForNode returns nothing`() {
thereAreNoOriginalElements()
thereAreNoMapDataChanges()
val s = create()
val ways = s.getWaysForNode(1)
assertTrue(ways.isEmpty())
}
@Test
fun `getWaysForNode returns an original way`() {
val w = way(1, listOf(1, 2))
originalElementsAre(w)
thereAreNoMapDataChanges()
val s = create()
val ways = s.getWaysForNode(1)
assertEquals(w, ways.single())
}
@Test
fun `getWaysForNode returns nothing because the updated way has been deleted`() {
val w = way(1, listOf(1, 2))
val wNewDeleted = way(1, listOf(1, 2))
originalElementsAre(w)
mapDataChangesAre(deletions = listOf(wNewDeleted))
val s = create()
val ways = s.getWaysForNode(1)
assertTrue(ways.isEmpty())
}
@Test
fun `getWaysForNode returns an updated way`() {
val w = way(1, listOf(1, 2))
val wNew = way(1, listOf(1, 2, 3))
originalElementsAre(w)
mapDataChangesAre(modifications = listOf(wNew))
val s = create()
val ways = s.getWaysForNode(1)
assertEquals(wNew, ways.single())
}
@Test
fun `getWaysForNode returns nothing because the updated way does not contain the node anymore`() {
val w = way(1, listOf(1, 2))
val wNew = way(1, listOf(2, 3))
originalElementsAre(w)
mapDataChangesAre(modifications = listOf(wNew))
val s = create()
val ways = s.getWaysForNode(1)
assertTrue(ways.isEmpty())
}
@Test
fun `getWaysForNode returns an updated way that didn't contain the node before`() {
val wNew = way(1,listOf(1, 2))
thereAreNoOriginalElements()
mapDataChangesAre(modifications = listOf(wNew))
val s = create()
val ways = s.getWaysForNode(1)
assertEquals(wNew, ways.single())
}
//endregion
//region getRelationsForElement
@Test
fun `getRelationsForElement returns nothing`() {
thereAreNoOriginalElements()
thereAreNoMapDataChanges()
val s = create()
val relations = s.getRelationsForElement(NODE, 1)
assertTrue(relations.isEmpty())
}
@Test
fun `getRelationsForElement returns original relation`() {
val r = rel(1, listOf(member(NODE, 1)))
originalElementsAre(r)
thereAreNoMapDataChanges()
val s = create()
val relations = s.getRelationsForElement(NODE, 1)
assertEquals(r, relations.single())
}
@Test
fun `getRelationsForElement returns updated relation`() {
val r = rel(1, listOf(member(NODE, 1)))
val rNew = rel(1, listOf(
member(NODE, 1),
member(NODE, 2)
))
originalElementsAre(r)
mapDataChangesAre(modifications = listOf(rNew))
val s = create()
val relations = s.getRelationsForElement(NODE, 1)
assertEquals(rNew, relations.single())
}
@Test
fun `getRelationsForElement returns nothing because the updated relation has been deleted`() {
val r = rel(1, listOf(member(NODE, 1)))
val rNewDeleted = rel(1, listOf(member(NODE, 1)))
originalElementsAre(r)
mapDataChangesAre(deletions = listOf(rNewDeleted))
val s = create()
val relations = s.getRelationsForElement(NODE, 1)
assertTrue(relations.isEmpty())
}
@Test
fun `getRelationsForElement returns nothing because the updated relation does not contain the element anymore`() {
val r = rel(1, listOf(member(NODE, 1)))
val rNew = rel(1, listOf(member(NODE, 2)))
originalElementsAre(r)
mapDataChangesAre(modifications = listOf(rNew))
val s = create()
val relations = s.getRelationsForElement(NODE, 1)
assertTrue(relations.isEmpty())
}
@Test
fun `getRelationsForElement returns an updated relation that didn't contain the element before`() {
val r = rel(1, listOf(member(NODE, 2)))
val rNew = rel(1, listOf(member(NODE, 1)))
originalElementsAre(r)
mapDataChangesAre(modifications = listOf(rNew))
val s = create()
val relations = s.getRelationsForElement(NODE, 1)
assertEquals(rNew, relations.single())
}
//endregion
//region getMapDataWithGeometry
@Test fun `getMapDataWithGeometry returns nothing`() {
thereAreNoOriginalElements()
thereAreNoOriginalGeometries()
val s = create()
val data = s.getMapDataWithGeometry(bbox())
assertTrue(data.toList().isEmpty())
}
@Test fun `getMapDataWithGeometry returns original elements`() {
val nd = node(1, p(0.5,0.5))
val p = pGeom(0.5, 0.5)
originalElementsAre(nd)
originalGeometriesAre(ElementGeometryEntry(NODE, 1, p))
val s = create()
val data = s.getMapDataWithGeometry(bbox())
assertTrue(data.nodes.containsExactlyInAnyOrder(listOf(nd)))
}
@Test fun `getMapDataWithGeometry returns updated elements`() {
val nd = node(1, p(-0.5,0.5))
val p = pGeom(0.5, 0.5)
originalElementsAre(nd)
originalGeometriesAre(
ElementGeometryEntry(NODE, 1, p)
)
val ndInside = node(1, pos = p(0.1,0.1))
val ndOutside = node(2, pos = p(-0.5,0.1))
mapDataChangesAre(modifications = listOf(ndInside, ndOutside))
val s = create()
val data = s.getMapDataWithGeometry(bbox())
assertTrue(data.nodes.containsExactlyInAnyOrder(listOf(ndInside)))
}
@Test fun `getMapDataWithGeometry returns nothing because updated element is not in bbox anymore`() {
val nd = node(1, p(0.5,0.5))
val p = pGeom(0.5, 0.5)
originalElementsAre(nd)
originalGeometriesAre(
ElementGeometryEntry(NODE, 1, p)
)
val ndNew = node(1, p(-0.1,0.1))
mapDataChangesAre(modifications = listOf(ndNew))
val s = create()
val data = s.getMapDataWithGeometry(bbox())
assertTrue(data.nodes.isEmpty())
}
@Test fun `getMapDataWithGeometry returns nothing because element was deleted`() {
val nd = node(1, p(0.5,0.5))
val p = pGeom(0.5, 0.5)
originalElementsAre(nd)
originalGeometriesAre(
ElementGeometryEntry(NODE, 1, p)
)
val ndNewDeleted = node(1, p(-0.1,0.1))
mapDataChangesAre(deletions = listOf(ndNewDeleted))
val s = create()
val data = s.getMapDataWithGeometry(bbox())
assertTrue(data.nodes.isEmpty())
}
//endregion
//region ElementEditsSource.Listener ::onAddedEdit
@Test
fun `onAddedEdit does not relay if no elements were updated`() {
val s = create()
val listener = mock<MapDataWithEditsSource.Listener>()
s.addListener(listener)
editsControllerNotifiesMapDataChangesAdded()
verifyNoInteractions(listener)
}
@Test
fun `onAddedEdit relays updated elements`() {
val s = create()
val listener = mock<MapDataWithEditsSource.Listener>()
s.addListener(listener)
val n = node(1, p(1.0,10.0))
val p = ElementGeometryEntry(elementType = NODE, elementId = 1, geometry = pGeom(1.0,10.0))
editsControllerNotifiesMapDataChangesAdded(modifications = listOf(n))
val expectedMapData = MutableMapDataWithGeometry(
listOf(n),
listOf(p)
)
verify(listener).onUpdated(updated = eq(expectedMapData), deleted = eq(listOf()))
assertEquals(n, s.get(NODE, 1))
assertEquals(p.geometry, s.getGeometry(NODE, 1))
}
@Test
fun `onAddedEdit relays deleted elements`() {
val s = create()
val listener = mock<MapDataWithEditsSource.Listener>()
s.addListener(listener)
val n = node(1, p(1.0,10.0))
editsControllerNotifiesMapDataChangesAdded(deletions = listOf(n))
verify(listener).onUpdated(
updated = eq(MutableMapDataWithGeometry()),
deleted = eq(listOf(ElementKey(NODE, 1)))
)
assertNull(s.get(NODE, 1))
assertNull(s.getGeometry(NODE, 1))
}
//endregion
//region ElementEditsSource.Listener ::onDeletedEdit
@Test
fun `onDeletedEdit relays updated element`() {
val s = create()
val listener = mock<MapDataWithEditsSource.Listener>()
s.addListener(listener)
val n = node(1, p(1.0,10.0))
val p = ElementGeometryEntry(NODE, 1, pGeom(1.0,10.0))
mapDataChangesAre(modifications = listOf(n))
editsControllerNotifiesDeletedEdit(n, listOf())
verify(listener).onUpdated(
updated = eq(MutableMapDataWithGeometry(listOf(n), listOf(p))),
deleted = eq(listOf())
)
}
@Test
fun `onDeletedEdit relays elements created by edit as deleted elements`() {
val s = create()
val listener = mock<MapDataWithEditsSource.Listener>()
s.addListener(listener)
val n = node(1, p(1.0,10.0))
val p = ElementGeometryEntry(NODE, 1, pGeom(1.0,10.0))
val delElements = listOf(
ElementKey(NODE, -10),
ElementKey(WAY, -10),
ElementKey(RELATION, -10),
)
mapDataChangesAre(modifications = listOf(n))
editsControllerNotifiesDeletedEdit(n, delElements)
verify(listener).onUpdated(
updated = eq(MutableMapDataWithGeometry(listOf(n), listOf(p))),
deleted = eq(delElements)
)
}
//endregion
//region MapDataController.Listener ::onUpdate
@Test
fun `onUpdate passes through mapData because there are no edits`() {
val ndNewOriginal = node(1, p(0.2,0.0), mapOf("Iam" to "server version"))
val pNew = ElementGeometryEntry(NODE, 1, pGeom(0.2,0.0))
val s = create()
val listener = mock<MapDataWithEditsSource.Listener>()
s.addListener(listener)
val updatedMapData = MutableMapDataWithGeometry(
elements = listOf(ndNewOriginal),
geometryEntries = listOf(pNew)
)
val deletions = listOf(
ElementKey(NODE, 2)
)
mapDataListener.onUpdated(updatedMapData, deletions)
val expectedMapDataWithGeometry = MutableMapDataWithGeometry(
elements = listOf(ndNewOriginal),
geometryEntries = listOf(pNew),
)
val expectedDeletions = listOf(
ElementKey(NODE, 2)
)
verify(listener).onUpdated(eq(expectedMapDataWithGeometry), eq(expectedDeletions))
}
@Test
fun `onUpdate applies edits on top of passed mapData`() {
// 1 is modified,
// 2 is modified to be deleted,
// 3 is deleted,
// 4 was deleted but was modified to be not
val ndNewOriginal = node(1, p(0.2,0.0))
val pNew = ElementGeometryEntry(NODE, 1, pGeom(0.2,0.0))
val ndNewOriginal2 = node(2, p(0.2,1.0))
val pNew2 = ElementGeometryEntry(NODE, 1, pGeom(0.2,1.0))
val ndModified = node(1, p(0.3,0.0))
val pModified = ElementGeometryEntry(NODE, 1, pGeom(0.3,0.0))
val ndModifiedDeleted2 = node(2)
val ndModified4 = node(4, p(0.5,0.4))
val pModified4 = ElementGeometryEntry(NODE, 4, pGeom(0.5,0.4))
mapDataChangesAre(modifications = listOf(ndModified, ndModified4), deletions = listOf(ndModifiedDeleted2))
val s = create()
val listener = mock<MapDataWithEditsSource.Listener>()
s.addListener(listener)
val updatedMapData = MutableMapDataWithGeometry(
elements = listOf(ndNewOriginal, ndNewOriginal2),
geometryEntries = listOf(pNew, pNew2)
)
val deletions = listOf(
ElementKey(NODE, 3),
ElementKey(NODE, 4)
)
mapDataListener.onUpdated(updatedMapData, deletions)
val expectedMapDataWithGeometry = MutableMapDataWithGeometry(
elements = listOf(ndModified, ndModified4),
geometryEntries = listOf(pModified,pModified4),
)
val expectedDeletions = listOf(
ElementKey(NODE, 2),
ElementKey(NODE, 3)
)
verify(listener).onUpdated(eq(expectedMapDataWithGeometry), eq(expectedDeletions))
}
//endregion
//region MapDataController.Listener ::onReplacedForBBox
@Test
fun `onReplacedForBBox passes through mapData because there are no edits`() {
val ndNewOriginal = node(1, p(0.2,0.0), mapOf("Iam" to "server version"))
val pNew = ElementGeometryEntry(NODE, 1, pGeom(0.2,0.0))
val s = create()
val listener = mock<MapDataWithEditsSource.Listener>()
s.addListener(listener)
val bbox = bbox()
val updatedMapData = MutableMapDataWithGeometry(
elements = listOf(ndNewOriginal),
geometryEntries = listOf(pNew)
)
mapDataListener.onReplacedForBBox(bbox, updatedMapData)
val expectedMapDataWithGeometry = MutableMapDataWithGeometry(
elements = listOf(ndNewOriginal),
geometryEntries = listOf(pNew),
)
verify(listener).onReplacedForBBox(eq(bbox), eq(expectedMapDataWithGeometry))
}
@Test
fun `onReplacedForBBox applies edits on top of passed mapData`() {
val ndModified = node(1, p(0.3,0.2), mapOf("Iam" to "modified"))
val pModified = ElementGeometryEntry(NODE, 1, pGeom(0.3,0.2))
val ndNewOriginal = node(1, p(0.2,0.0), mapOf("Iam" to "server version"))
val pNew = ElementGeometryEntry(NODE, 1, pGeom(0.2,0.0))
val ndNewOriginal2 = node(2, p(0.8,0.1), mapOf("Iam" to "server version"))
val pNew2 = ElementGeometryEntry(NODE, 2, pGeom(0.8,0.1))
val s = create()
val listener = mock<MapDataWithEditsSource.Listener>()
s.addListener(listener)
mapDataChangesAre(modifications = listOf(ndModified))
val bbox = bbox()
val updatedMapData = MutableMapDataWithGeometry(
elements = listOf(ndNewOriginal, ndNewOriginal2),
geometryEntries = listOf(pNew, pNew2)
)
mapDataListener.onReplacedForBBox(bbox, updatedMapData)
val expectedMapDataWithGeometry = MutableMapDataWithGeometry(
elements = listOf(ndModified, ndNewOriginal2),
geometryEntries = listOf(pModified, pNew2),
)
verify(listener).onReplacedForBBox(eq(bbox), eq(expectedMapDataWithGeometry))
}
// I spare myself more tests for onReplacedForBBox here because it internally does the same as
// getMapDataWithGeometry
//endregion
//region MapDataController.Listener ::onCleared
@Test
fun `onCleared is passed on`() {
val s = create()
val listener = mock<MapDataWithEditsSource.Listener>()
s.addListener(listener)
mapDataListener.onCleared()
verify(listener).onCleared()
}
//endregion
private fun create() = MapDataWithEditsSource(mapDataCtrl, editsCtrl, geometryCreator)
/** Feed mock MapDataController the data */
private fun originalGeometriesAre(vararg elementGeometryEntries: ElementGeometryEntry) {
for (entry in elementGeometryEntries) {
mapData.putGeometry(entry.elementType, entry.elementId, entry.geometry)
}
}
private fun thereAreNoOriginalGeometries() {
originalGeometriesAre()
}
/** Feed mock MapDataController the data */
private fun originalElementsAre(vararg elements: Element) {
for (element in elements) {
mapData.putElement(element)
}
}
private fun thereAreNoOriginalElements() {
originalElementsAre()
}
private fun mapDataChangesAre(
creations: Collection<Element> = emptyList(),
modifications: Collection<Element> = emptyList(),
deletions: Collection<Element> = emptyList()
) {
val action = mock<ElementEditAction>()
on(action.createUpdates(any(), any(), any(), any())).thenReturn(MapDataChanges(creations, modifications, deletions))
on(editsCtrl.getAllUnsynced()).thenReturn(listOf(edit(
element = node(-1),
action = action
)))
}
private fun thereAreNoMapDataChanges() {
mapDataChangesAre()
}
private fun editsControllerNotifiesMapDataChangesAdded(
creations: Collection<Element> = emptyList(),
modifications: Collection<Element> = emptyList(),
deletions: Collection<Element> = emptyList()
) {
val action = mock<ElementEditAction>()
on(action.createUpdates(any(), any(), any(), any())).thenReturn(MapDataChanges(creations, modifications, deletions))
editsListener.onAddedEdit(edit(
element = node(-1),
action = action
))
}
private fun editsControllerNotifiesDeletedEdit(element: Element, createdElementKeys: List<ElementKey>) {
on(editsCtrl.getIdProvider(anyLong())).thenReturn(ElementIdProvider(createdElementKeys))
editsListener.onDeletedEdits(listOf(edit(element = element)))
}
}
| gpl-3.0 |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/entities/GeekListCommentEntity.kt | 1 | 288 | package com.boardgamegeek.entities
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class GeekListCommentEntity(
val postDate: Long,
val editDate: Long,
val numberOfThumbs: Int,
val username: String,
val content: String
) : Parcelable
| gpl-3.0 |
shkschneider/android_Skeleton | core/src/main/kotlin/me/shkschneider/skeleton/datax/CsvReader.kt | 1 | 3633 | package me.shkschneider.skeleton.datax
import me.shkschneider.skeleton.helperx.Logger
import java.io.BufferedReader
import java.io.IOException
// <http://opencsv.sourceforge.net>
open class CsvReader(
private val bufferedReader: BufferedReader,
private val separator: Char = ',',
private val quote: Char = '"',
skip: Int = 0
) {
private var hasNext = false
@Throws(IOException::class)
private fun getNextLine(): String {
val nextLine = bufferedReader.readLine()
nextLine ?: run {
hasNext = false
throw IOException("EOF")
}
return nextLine
}
fun hasNext(): Boolean {
return hasNext
}
fun readNext(): List<String>? {
try {
val nextLine = getNextLine()
return parseLine(nextLine)
} catch (e: IOException) {
return null
}
}
@Throws(IOException::class)
private fun parseLine(nextLine: String): List<String>? {
var line: String = nextLine
val tokensOnThisLine = ArrayList<String>()
var stringBuffer = StringBuffer()
var inQuotes = false
do {
if (inQuotes) {
// continuing a quoted section, re-append newline
stringBuffer.append("\n")
line = getNextLine()
}
var i = 0
while (i < line.length) {
val c = line[i]
if (c == quote) {
// this gets complex... the quote may end a quoted block, or escape another quote.
// do a 1-char lookahead:
if (inQuotes // we are in quotes, therefore there can be escaped quotes in here.
&& line.length > i + 1 // there is indeed another character to check.
&& line[i + 1] == quote) { // ..and that char. is a quote also.
// we have two quote chars in a row == one quote char, so consume them both and
// put one on the token. we do *not* exit the quoted text.
stringBuffer.append(line[i + 1])
i++
} else {
inQuotes = !inQuotes
// the tricky case of an embedded quote in the middle: a,bc"d"ef,g
if (i > 2 // not on the beginning of the line
&& line[i - 1] != separator // not at the beginning of an escape sequence
&& line.length > i + 1
&& line[i + 1] != separator) { // not at the end of an escape sequence
stringBuffer.append(c)
}
}
} else if (c == separator && !inQuotes) {
tokensOnThisLine.add(stringBuffer.toString())
stringBuffer = StringBuffer() // start work on next token
} else {
stringBuffer.append(c)
}
i++
}
} while (inQuotes)
tokensOnThisLine.add(stringBuffer.toString())
return tokensOnThisLine
}
@Throws(IOException::class)
fun close() {
bufferedReader.close()
}
init {
hasNext = true
if (skip > 0) {
try {
for (i in 0 until skip) {
bufferedReader.readLine()
}
} catch (e: IOException) {
Logger.warning(e.toString())
}
}
}
}
| apache-2.0 |
android/topeka | categories/src/main/java/com/google/samples/apps/topeka/activity/CategorySelectionActivity.kt | 1 | 4904 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.topeka.activity
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.transition.TransitionInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import com.google.samples.apps.topeka.R as baseR
import com.google.samples.apps.topeka.categories.R
import com.google.samples.apps.topeka.fragment.CategorySelectionFragment
import com.google.samples.apps.topeka.helper.ActivityLaunchHelper
import com.google.samples.apps.topeka.helper.ApiLevelHelper
import com.google.samples.apps.topeka.helper.REQUEST_LOGIN
import com.google.samples.apps.topeka.helper.REQUEST_SAVE
import com.google.samples.apps.topeka.helper.database
import com.google.samples.apps.topeka.helper.findFragmentById
import com.google.samples.apps.topeka.helper.logout
import com.google.samples.apps.topeka.helper.onSmartLockResult
import com.google.samples.apps.topeka.helper.replaceFragment
import com.google.samples.apps.topeka.helper.requestLogin
import com.google.samples.apps.topeka.model.Player
import com.google.samples.apps.topeka.widget.AvatarView
class CategorySelectionActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_category_selection)
initializePlayer()
setUpToolbar()
if (savedInstanceState == null) {
attachCategoryGridFragment()
} else {
setProgressBarVisibility(View.GONE)
}
supportPostponeEnterTransition()
}
private fun updatePlayerViews(player: Player) {
findViewById<TextView>(R.id.title).text = player.toString()
player.avatar?.run { findViewById<AvatarView>(R.id.avatar).setAvatar(this) }
}
private fun initializePlayer() = requestLogin { updatePlayerViews(it) }
private fun setUpToolbar() {
setSupportActionBar(findViewById(R.id.toolbar_player))
supportActionBar?.setDisplayShowTitleEnabled(false)
}
private fun attachCategoryGridFragment() {
replaceFragment(R.id.category_container,
findFragmentById(R.id.category_container) ?: CategorySelectionFragment())
setProgressBarVisibility(View.GONE)
}
private fun setProgressBarVisibility(visibility: Int) {
findViewById<View>(R.id.progress).visibility = visibility
}
override fun onResume() {
super.onResume()
(findViewById<TextView>(R.id.score)).text =
getString(com.google.samples.apps.topeka.base.R.string.x_points,
database().getScore())
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(baseR.menu.menu_category, menu)
return true
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == CategorySelectionFragment.REQUEST_CATEGORY) {
data?.let {
findFragmentById(R.id.category_container)?.run {
onActivityResult(requestCode, resultCode, data)
}
}
} else if (requestCode == REQUEST_LOGIN || requestCode == REQUEST_SAVE) {
onSmartLockResult(
requestCode,
resultCode,
data,
success = { },
failure = { requestLogin { updatePlayerViews(it) } })
} else {
super.onActivityResult(requestCode, resultCode, data)
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return if (item.itemId == baseR.id.sign_out) {
handleSignOut()
true
} else super.onOptionsItemSelected(item)
}
@SuppressLint("NewApi")
private fun handleSignOut() {
if (ApiLevelHelper.isAtLeast(Build.VERSION_CODES.LOLLIPOP)) {
window.exitTransition = TransitionInflater.from(this)
.inflateTransition(R.transition.category_enter)
}
logout()
ActivityLaunchHelper.launchSignIn(this, true)
supportFinishAfterTransition()
}
}
| apache-2.0 |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/ext/ParticleEffectExt.kt | 1 | 2871 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
@file:Suppress("FunctionName", "NOTHING_TO_INLINE")
package org.lanternpowered.server.ext
import org.lanternpowered.api.util.optional.orNull
import org.spongepowered.api.block.BlockState
import org.spongepowered.api.block.BlockType
import org.spongepowered.api.data.type.NotePitch
import org.spongepowered.api.effect.particle.ParticleEffect
import org.spongepowered.api.effect.particle.ParticleOption
import org.spongepowered.api.effect.particle.ParticleOptions
import org.spongepowered.api.effect.particle.ParticleType
import org.spongepowered.api.item.ItemType
import org.spongepowered.api.item.inventory.ItemStack
import org.spongepowered.api.item.inventory.ItemStackSnapshot
import org.spongepowered.api.util.Color
import org.spongepowered.api.util.Direction
inline fun <V> ParticleEffect.option(option: ParticleOption<V>): V? = getOption(option).orNull()
inline fun <V> ParticleEffect.optionOrDefault(option: ParticleOption<V>): V? = getOptionOrDefault(option).orNull()
inline fun ParticleEffect(type: ParticleType, fn: ParticleEffect.Builder.() -> Unit = {}): ParticleEffect =
ParticleEffect.builder().type(type).apply(fn).build()
inline fun ParticleEffect.Builder.block(block: BlockState): ParticleEffect.Builder = option(ParticleOptions.BLOCK_STATE, block)
inline fun ParticleEffect.Builder.block(block: BlockType): ParticleEffect.Builder = option(ParticleOptions.BLOCK_STATE, block.defaultState)
inline fun ParticleEffect.Builder.item(item: ItemStackSnapshot): ParticleEffect.Builder = option(ParticleOptions.ITEM_STACK_SNAPSHOT, item)
inline fun ParticleEffect.Builder.item(item: ItemStack): ParticleEffect.Builder = option(ParticleOptions.ITEM_STACK_SNAPSHOT, item.createSnapshot())
inline fun ParticleEffect.Builder.item(item: ItemType): ParticleEffect.Builder =
option(ParticleOptions.ITEM_STACK_SNAPSHOT, ItemStack.of(item, 1).createSnapshot())
inline fun ParticleEffect.Builder.color(color: Color): ParticleEffect.Builder = option(ParticleOptions.COLOR, color)
inline fun ParticleEffect.Builder.direction(direction: Direction): ParticleEffect.Builder = option(ParticleOptions.DIRECTION, direction)
inline fun ParticleEffect.Builder.note(notePitch: NotePitch): ParticleEffect.Builder = option(ParticleOptions.NOTE, notePitch)
inline fun ParticleEffect.Builder.scale(scale: Double): ParticleEffect.Builder = option(ParticleOptions.SCALE, scale)
inline fun ParticleEffect.Builder.slowHorizontalVelocity(slow: Boolean = true): ParticleEffect.Builder =
option(ParticleOptions.SLOW_HORIZONTAL_VELOCITY, slow)
| mit |
mediathekview/MediathekView | src/main/java/mediathek/update/ServerProgramInformation.kt | 1 | 311 | package mediathek.update
import mediathek.tool.Version
data class ServerProgramInformation(val version: Version) {
class ParserTags {
companion object {
const val INFO = "Info"
const val VERSION = "Program_Version"
const val INFO_NO = "number"
}
}
} | gpl-3.0 |
WindSekirun/RichUtilsKt | demo/src/main/java/pyxis/uzuki/live/richutilskt/demo/MainApplication.kt | 1 | 395 | package pyxis.uzuki.live.richutilskt.demo
import android.app.Application
import pyxis.uzuki.live.richutilskt.module.crash.CrashCollector
/**
* RichUtilsKt1
* Class: MainApplication
* Created by pyxis on 19/11/2017.
*
* Description:
*/
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
CrashCollector.initCrashCollector(this)
}
} | apache-2.0 |
Ruben-Sten/TeXiFy-IDEA | test/nl/hannahsten/texifyidea/reference/CommandDefinitionReferenceTest.kt | 1 | 978 | package nl.hannahsten.texifyidea.reference
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import nl.hannahsten.texifyidea.file.LatexFileType
class CommandDefinitionReferenceTest : BasePlatformTestCase() {
fun testRename() {
myFixture.configureByText(LatexFileType, """\newcommand{\joepsie}{} \joepsie<caret>""")
myFixture.renameElementAtCaret("\\mooizo")
myFixture.checkResult("""\newcommand{\mooizo}{} \mooizo""")
}
fun testResolveInDefinition() {
myFixture.configureByText(LatexFileType, """
\newcommand{\MyCommand}{Hello World!}
\newcommand{\AnotherCommand}{\MyCommand<caret>}
\AnotherCommand
""".trimIndent())
myFixture.renameElementAtCaret("\\floep")
myFixture.checkResult("""
\newcommand{\floep}{Hello World!}
\newcommand{\AnotherCommand}{\floep<caret>}
\AnotherCommand
""".trimIndent())
}
} | mit |
minjaesong/terran-basic-java-vm | src/net/torvald/terranvm/runtime/TerranVMReferenceBIOS.kt | 1 | 6674 | package net.torvald.terranvm.runtime
import net.torvald.terranvm.assets.Loader
import net.torvald.terranvm.toBytesBin
import net.torvald.terranvm.toReadableBin
import net.torvald.terrarum.virtualcomputer.terranvmadapter.PeriMDA
import java.io.IOException
/**
* Created by minjaesong on 2018-04-14.
*/
class TerranVMReferenceBIOS(val vm: TerranVM) : VMPeripheralHardware {
override fun inquireBootstrapper(): ByteArray? {
TODO("Boot from ROM BASIC")
}
/**
* Puts `prg` into the memory and moves program counter to its starting position.
*/
private fun eatShitAndPoop(prg: ByteArray) {
val ptr = vm.malloc(prg.size)
System.arraycopy(prg, 0, vm.memory, ptr.memAddr, prg.size)
vm.pc = ptr.memAddr
}
private fun Int.KB() = this shl 10
override fun call(arg: Int) {
val upper8Bits = arg.ushr(24)
val midHigh8Bits = arg.and(0xFF0000).ushr(16)
val midLow8Bits = arg.and(0xFF00).ushr(8)
val lower8Bits = arg.and(0xFF)
//println("BIOS called with arg: ${arg.toBytesBin()}")
when (upper8Bits) {
// various
0 -> when (midLow8Bits) {
// boot from device
0 -> {
when (lower8Bits) {
// load BIOS Setup Utility
TerranVM.IRQ_BIOS -> eatShitAndPoop(vm.parametreRAM.sliceArray(4.KB()..6.KB()))
TerranVM.IRQ_KEYBOARD -> {
val asm = Assembler(vm)
val prg = asm(Loader.invoke())
eatShitAndPoop(prg.bytes)
}
0 -> {
val bootOrder = vm.parametreRAM.sliceArray(0..3)
// try to boot using Boot Order
for (ord in 0..3) {
try {
if (bootOrder[ord] == 0.toByte()) throw IllegalArgumentException()
call(bootOrder[ord].toUint())
}
catch (e: IllegalArgumentException) {
}
catch (e: Exception) {
e.printStackTrace()
return
}
}
// boot ROM BASIC
try {
eatShitAndPoop(vm.parametreRAM.sliceArray(6.KB()..8.KB()))
}
catch (e: Exception) {
e.printStackTrace()
throw IOException("No bootable medium")
}
}
else -> {
val dev = vm.peripherals[lower8Bits]
if (dev == null) throw IllegalArgumentException("No such device: $lower8Bits")
else {
val prg = dev.inquireBootstrapper()
if (prg == null) throw IllegalArgumentException("Medium not bootable: $lower8Bits")
else eatShitAndPoop(prg)
}
}
}
}
// getchar from keyboard
1 -> {
(vm.peripherals[1] as VMPeripheralWrapper).call(lower8Bits and 0b111)
}
// printchar immediate
2 -> {
(vm.peripherals[3] as VMPeripheralWrapper).call(0x0800 or lower8Bits)
}
// printchar from register
3 -> {
val data = vm.readregInt(arg.and(0b111))
(vm.peripherals[3] as VMPeripheralWrapper).call(0x0800 or data)
}
// DMA Copy
in 0b010_0000_0..0b010_1111_1 -> {
val rParams = midLow8Bits.ushr(1).and(15)
val rFromAddr = lower8Bits.ushr(4).and(15)
val rToAddr = lower8Bits.and(15)
val params = vm.readregInt(rParams)
val src = params.and(0xFF)
val dest = params.ushr(8).and(0xFF)
var len = params.ushr(16).and(0xFFFF)
if (len == 0) len = 65536
val srcMem = if (src == 0) vm.memory else vm.peripherals[src]!!.memory
val destMem = if (dest == 0) vm.memory else vm.peripherals[dest]!!.memory
val fromAddr = vm.readregInt(rFromAddr)
val toAddr = vm.readregInt(rToAddr)
System.arraycopy(srcMem, fromAddr, destMem, toAddr, len)
}
}
// file operations
1 -> {
val fileOp = midHigh8Bits.ushr(3)
val targetRegister = midHigh8Bits.and(0b111)
val argument = midLow8Bits
val device = lower8Bits
when (fileOp) {
}
}
// print string
2 -> {
val dbAddr = arg.shl(2).and(0xFFFFFF)
var strLen = 0 // length INCLUSIVE to the null terminator
var _readByte: Byte
do {
_readByte = vm.memory[dbAddr + strLen]
strLen++
} while (_readByte != 0.toByte())
val mda = vm.peripherals[3]!! as PeriMDA
//if (strLen > 1) {
mda.printStream.write(vm.memSliceBySize(dbAddr, strLen - 1))
//}
}
// get file by name
4, 5 -> {
val rDest = arg.ushr(22).and(0b111)
val dbAddr = arg.shl(2).and(0xFFFFFF)
}
// compatible BIOS private use area -- ReferenceBIOS will ignore it
in 128..255 -> {
}
else -> {
throw UnsupportedOperationException("Unsupported op: ${arg.toReadableBin().replace('_', 0.toChar())}")
}
}
}
}
/* LOADER commands
CASE INSENSITIVE
0..9, A..F: hex literal
K: peek what byte is in the current address (example output: "0003DC : 3F")
P: put a byte to memory and increment program counter
R: run
T: move program counter
SYNTAX
000100L09P3EP45P00P
As soon as you hit a key, the command is entered, no RETURN key required.
*/ | mit |
asamm/locus-api | locus-api-core/src/main/java/locus/api/objects/styles/GeoDataStyle.kt | 1 | 8210 | /*
* Copyright 2012, Asamm Software, s. r. o.
*
* This file is part of LocusAPI.
*
* LocusAPI is free software: you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* LocusAPI 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
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the Lesser GNU General Public
* License along with LocusAPI. If not, see
* <http://www.gnu.org/licenses/lgpl.html/>.
*/
package locus.api.objects.styles
import locus.api.objects.Storable
import locus.api.objects.extra.KmlVec2
import locus.api.objects.styles.deprecated.LineStyleOld
import locus.api.objects.styles.deprecated.OldStyleHelper
import locus.api.objects.styles.deprecated.PolyStyleOld
import locus.api.utils.DataReaderBigEndian
import locus.api.utils.DataWriterBigEndian
import locus.api.utils.Logger
import java.io.IOException
/**
* Create new instance of style container.
*/
class GeoDataStyle() : Storable() {
/**
* ID in style tag.
*/
var id: String = ""
/**
* name of the style.
*/
var name: String = ""
/**
* Style for popup balloons.
*/
var balloonStyle: BalloonStyle? = null
/**
* Style for icons.
*/
var iconStyle: IconStyle? = null
/**
* Style of label.
*/
var labelStyle: LabelStyle? = null
/**
* Style of lists.
*/
var listStyle: ListStyle? = null
/**
* Style for line and polygons.
*/
var lineStyle: LineStyle? = null
//*************************************************
// SETTERS & GETTERS
//*************************************************
/**
* Get style Url for an icon.
*
* @return style Url/href parameter
*/
val iconStyleIconUrl: String?
get() = if (iconStyle == null) {
null
} else iconStyle!!.iconHref
/**
* Create new instance of style container with defined name.
*
* @param name name of style container
*/
constructor(name: String?) : this() {
// set name
if (name != null) {
this.name = name
}
}
fun setIconStyle(iconUrl: String, scale: Float) {
setIconStyle(iconUrl, COLOR_DEFAULT, 0.0f, scale)
}
fun setIconStyle(iconUrl: String, color: Int, heading: Float, scale: Float) {
// set style
iconStyle = IconStyle().apply {
this.iconHref = iconUrl
this.color = color
this.heading = heading
this.scale = scale
}
// set hot spot
setIconStyleHotSpot(HOTSPOT_BOTTOM_CENTER)
}
fun setIconStyleHotSpot(hotspot: Int) {
setIconStyleHotSpot(when (hotspot) {
HOTSPOT_TOP_LEFT -> {
KmlVec2(0.0, KmlVec2.Units.FRACTION, 1.0, KmlVec2.Units.FRACTION)
}
HOTSPOT_CENTER_CENTER -> {
KmlVec2(0.5, KmlVec2.Units.FRACTION, 0.5, KmlVec2.Units.FRACTION)
}
else -> {
// HOTSPOT_BOTTOM_CENTER
generateDefaultHotSpot()
}
})
}
fun setIconStyleHotSpot(vec2: KmlVec2) {
if (iconStyle == null) {
Logger.logW(TAG, "setIconStyleHotSpot($vec2), " +
"initialize IconStyle before settings hotSpot or hotSpot is null!")
return
}
// set hotSpot
iconStyle!!.hotSpot = vec2
}
/**
* Set parameters for style that draw a lines.
*
* @param color color of lines
* @param width width of lines in pixels
*/
fun setLineStyle(color: Int, width: Float) {
// check if style exists
if (lineStyle == null) {
lineStyle = LineStyle()
}
// set parameters
lineStyle!!.colorBase = color
lineStyle!!.width = width
}
/**
* Set line style for drawing a polygons.
*
* @param color color of inner area
*/
fun setPolyStyle(color: Int) {
if (lineStyle == null) {
lineStyle = LineStyle().apply {
this.drawBase = false
}
}
lineStyle?.drawFill = true
lineStyle?.colorFill = color
}
//*************************************************
// STORABLE
//*************************************************
override fun getVersion(): Int {
return 2
}
@Throws(IOException::class)
override fun readObject(version: Int, dr: DataReaderBigEndian) {
// read core
id = dr.readString()
name = dr.readString()
// ignore old version, not compatible anymore
if (version == 0) {
return
}
// read styles
var lineStyleOld: LineStyleOld? = null
var polyStyleOld: PolyStyleOld? = null
try {
if (dr.readBoolean()) {
balloonStyle = read(BalloonStyle::class.java, dr)
}
if (dr.readBoolean()) {
iconStyle = read(IconStyle::class.java, dr)
}
if (dr.readBoolean()) {
labelStyle = read(LabelStyle::class.java, dr)
}
if (dr.readBoolean()) {
lineStyleOld = read(LineStyleOld::class.java, dr)
}
if (dr.readBoolean()) {
listStyle = read(ListStyle::class.java, dr)
}
if (dr.readBoolean()) {
polyStyleOld = read(PolyStyleOld::class.java, dr)
}
} catch (e: Exception) {
e.printStackTrace()
}
// convert old style to new system
lineStyle = OldStyleHelper.convertToNewLineStyle(lineStyleOld, polyStyleOld)
// V2
if (version >= 2) {
if (dr.readBoolean()) {
lineStyle = LineStyle()
lineStyle!!.read(dr)
}
}
}
@Throws(IOException::class)
override fun writeObject(dw: DataWriterBigEndian) {
// write core
dw.writeString(id)
dw.writeString(name)
// balloon style
if (balloonStyle == null) {
dw.writeBoolean(false)
} else {
dw.writeBoolean(true)
balloonStyle!!.write(dw)
}
// icon style
if (iconStyle == null) {
dw.writeBoolean(false)
} else {
dw.writeBoolean(true)
iconStyle!!.write(dw)
}
// label style
if (labelStyle == null) {
dw.writeBoolean(false)
} else {
dw.writeBoolean(true)
labelStyle!!.write(dw)
}
// line style (removed)
dw.writeBoolean(false)
// list style
if (listStyle == null) {
dw.writeBoolean(false)
} else {
dw.writeBoolean(true)
listStyle!!.write(dw)
}
// poly style (removed)
dw.writeBoolean(false)
// V2
if (lineStyle == null) {
dw.writeBoolean(false)
} else {
dw.writeBoolean(true)
lineStyle!!.write(dw)
}
}
companion object {
// tag for logger
private const val TAG = "GeoDataStyle"
// definition of hotSpot of icon to bottom center
const val HOTSPOT_BOTTOM_CENTER = 0
const val HOTSPOT_TOP_LEFT = 1
const val HOTSPOT_CENTER_CENTER = 2
fun generateDefaultHotSpot(): KmlVec2 {
// HOTSPOT_BOTTOM_CENTER
return KmlVec2(
0.5, KmlVec2.Units.FRACTION,
0.0, KmlVec2.Units.FRACTION)
}
// STYLES
// shortcut to simple black color
const val BLACK = -0x1000000
// shortcut to simple white color
const val WHITE = -0x1
// default basic color
const val COLOR_DEFAULT = WHITE
}
}
| mit |
jamieadkins95/Roach | data/src/main/java/com/jamieadkins/gwent/data/update/repository/NotificationsRepository.kt | 1 | 4055 | package com.jamieadkins.gwent.data.update.repository
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.res.Resources
import android.os.Build
import com.f2prateek.rx.preferences2.RxSharedPreferences
import com.google.firebase.messaging.FirebaseMessaging
import com.jamieadkins.gwent.data.BuildConfig
import com.jamieadkins.gwent.data.R
import com.jamieadkins.gwent.domain.update.repository.UpdateRepository
import io.reactivex.Completable
import io.reactivex.Observable
import timber.log.Timber
import java.util.*
import javax.inject.Inject
class NotificationsRepository @Inject constructor(
private val preferences: RxSharedPreferences,
private val resources: Resources,
private val notificationManager: NotificationManager
) : UpdateRepository {
override fun isUpdateAvailable(): Observable<Boolean> {
// No work to do.
return Observable.just(false)
}
override fun performUpdate(): Completable {
// No work to do.
return Completable.complete()
}
override fun hasDoneFirstTimeSetup(): Observable<Boolean> {
return preferences.getBoolean(KEY_NEWS_NOTIFCATIONS_SETUP).asObservable()
}
override fun performFirstTimeSetup(): Completable {
return hasDoneFirstTimeSetup()
.first(false)
.flatMapCompletable { doneSetup ->
if (!doneSetup) {
Completable.fromCallable {
setupNotificationChannel()
setupNewsNotifications()
setupPatchNotifications()
}
} else {
Completable.complete()
}
}
}
private fun setupNewsNotifications() {
val language = Locale.getDefault().language
val newsLanguage = resources.getStringArray(R.array.locales_news).firstOrNull { it.contains(language) } ?: "en"
preferences.getString(resources.getString(R.string.pref_news_notifications_key)).set(newsLanguage)
preferences.getBoolean(KEY_NEWS_NOTIFCATIONS_SETUP).set(true)
unsubscribeFromAllNews(resources)
val topic = "news-$newsLanguage"
Timber.i("Subscribing to $topic")
FirebaseMessaging.getInstance().subscribeToTopic(topic)
.addOnCompleteListener { Timber.i("Subscribed to $topic") }
if (BuildConfig.DEBUG) {
Timber.i("Subscribing to $DEBUG_NEWS_TOPIC")
FirebaseMessaging.getInstance().subscribeToTopic(DEBUG_NEWS_TOPIC)
.addOnCompleteListener { Timber.i("Subscribed to $DEBUG_NEWS_TOPIC") }
}
}
private fun unsubscribeFromAllNews(resources: Resources) {
for (key in resources.getStringArray(R.array.locales_news)) {
FirebaseMessaging.getInstance().unsubscribeFromTopic("news-$key")
}
if (BuildConfig.DEBUG) {
Timber.i("Unsubscribing from $DEBUG_NEWS_TOPIC")
FirebaseMessaging.getInstance().unsubscribeFromTopic(DEBUG_NEWS_TOPIC)
}
}
private fun setupNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create channel to show notifications.
val channelId = resources.getString(R.string.notification_channel_id)
val channelName = resources.getString(R.string.notification_channel_name)
notificationManager.createNotificationChannel(NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW))
}
}
private fun setupPatchNotifications() {
val topic = "patch-" + BuildConfig.CARD_DATA_VERSION
FirebaseMessaging.getInstance().subscribeToTopic(topic)
val key = resources.getString(R.string.pref_patch_notifications_topic_key)
preferences.getString(key).set(topic)
}
private companion object {
const val KEY_NEWS_NOTIFCATIONS_SETUP = "com.jamieadkins.gwent.news.locale.setup"
const val DEBUG_NEWS_TOPIC = "news-debug"
}
} | apache-2.0 |
jamieadkins95/Roach | app/src/main/java/com/jamieadkins/gwent/deck/list/DeckListPresenter.kt | 1 | 1324 | package com.jamieadkins.gwent.deck.list
import com.jamieadkins.gwent.bus.RxBus
import com.jamieadkins.gwent.base.BaseDisposableObserver
import com.jamieadkins.gwent.bus.GwentDeckClickEvent
import com.jamieadkins.gwent.domain.deck.GetDecksUseCase
import com.jamieadkins.gwent.domain.deck.model.GwentDeck
import com.jamieadkins.gwent.base.BasePresenter
import javax.inject.Inject
class DeckListPresenter @Inject constructor(
private val view: DeckListContract.View,
private val getDecksUseCase: GetDecksUseCase
) : BasePresenter(), DeckListContract.Presenter {
override fun onAttach() {
getDecksUseCase.get()
.doOnSubscribe { view.showLoadingIndicator(true) }
.subscribeWith(object : BaseDisposableObserver<List<GwentDeck>>() {
override fun onNext(decks: List<GwentDeck>) {
view.showDecks(decks)
view.showLoadingIndicator(false)
}
})
.addToComposite()
RxBus.register(GwentDeckClickEvent::class.java)
.subscribeWith(object : BaseDisposableObserver<GwentDeckClickEvent>() {
override fun onNext(event: GwentDeckClickEvent) {
view.showDeckDetails(event.data)
}
})
.addToComposite()
}
}
| apache-2.0 |
alfiewm/Keddit | app/src/main/java/meng/keddit/commons/adapter/LoadingDelegateAdapter.kt | 1 | 616 | package meng.keddit.commons.adapter
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import meng.keddit.R
import meng.keddit.commons.extensions.inflate
/**
* Created by meng on 2017/7/31.
*/
class LoadingDelegateAdapter : ViewTypeDelegateAdapter {
override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder = TurnsViewHolder(parent)
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: ViewType) {
}
class TurnsViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
parent.inflate(R.layout.news_item_loading)) {
}
} | mit |
FHannes/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaDumbUElement.kt | 2 | 1057 | /*
* 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.java
import com.intellij.psi.PsiElement
import org.jetbrains.uast.UElement
import org.jetbrains.uast.internal.log
class JavaDumbUElement(
override val psi: PsiElement?,
override val uastParent: UElement?,
private val customRenderString: String? = null
) : JavaAbstractUElement(), UElement {
override fun asLogString() = log()
override fun asRenderString() = customRenderString ?: "<stub@$psi>"
} | apache-2.0 |
thm-projects/arsnova-backend | gateway/src/main/kotlin/de/thm/arsnova/service/httpgateway/service/AnnouncementService.kt | 1 | 3122 | package de.thm.arsnova.service.httpgateway.service
import de.thm.arsnova.service.httpgateway.config.HttpGatewayProperties
import de.thm.arsnova.service.httpgateway.exception.ForbiddenException
import de.thm.arsnova.service.httpgateway.model.Announcement
import de.thm.arsnova.service.httpgateway.model.AnnouncementState
import de.thm.arsnova.service.httpgateway.model.Room
import de.thm.arsnova.service.httpgateway.model.User
import de.thm.arsnova.service.httpgateway.security.AuthProcessor
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.springframework.web.reactive.function.client.WebClient
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import java.util.Optional
@Service
class AnnouncementService(
private val webClient: WebClient,
private val httpGatewayProperties: HttpGatewayProperties,
private val authProcessor: AuthProcessor,
private val roomAccessService: RoomAccessService,
private val roomService: RoomService
) {
private val logger = LoggerFactory.getLogger(javaClass)
fun getByUserId(userId: String): Flux<Announcement> {
return authProcessor.getAuthentication()
.filter { authentication ->
authentication.principal == userId
}
.switchIfEmpty(Mono.error(ForbiddenException()))
.flatMapMany { auth ->
val jwt: String = auth.credentials.toString()
roomAccessService.getRoomAccessByUser(userId).map {
it.roomId
}.collectList().flatMapMany { roomIds ->
val roomIdsStr = roomIds.joinToString(",")
val url = "${httpGatewayProperties.httpClient.core}/room/-/announcement/?roomIds=$roomIdsStr"
logger.trace("Querying core for announcements with url: {}", url)
webClient.get()
.uri(url)
.header("Authorization", jwt)
.retrieve().bodyToFlux(Announcement::class.java).cache()
.checkpoint("Request failed in ${this::class.simpleName}::${::getByUserId.name}.")
}
}
.sort { a, b ->
(b.updateTimestamp ?: b.creationTimestamp).compareTo(a.updateTimestamp ?: a.creationTimestamp)
}
}
fun getByUserIdWithRoomName(userId: String): Flux<Announcement> {
return getByUserId(userId).collectList().flatMapMany { announcements ->
roomService.get(announcements.map { it.roomId }.distinct())
.filter(Optional<Room>::isPresent)
.map(Optional<Room>::get)
.collectMap { it.id }
.flatMapIterable { rooms ->
announcements.map {
it.copy(roomName = rooms[it.roomId]?.name)
}
}
}
}
fun getStateByUser(user: User): Mono<AnnouncementState> {
return getByUserId(user.id).collectList().map { announcements ->
AnnouncementState(
announcements.count(),
announcements
.filter { it.creatorId != user.id }
.count { a ->
user.announcementReadTimestamp == null ||
(a.updateTimestamp ?: a.creationTimestamp) > user.announcementReadTimestamp
},
user.announcementReadTimestamp
)
}
}
}
| gpl-3.0 |
gotev/android-upload-service | examples/app/demoapp/src/main/java/net/gotev/uploadservicedemo/ExampleSingleNotificationHandler.kt | 2 | 893 | package net.gotev.uploadservicedemo
import android.app.NotificationManager
import androidx.core.app.NotificationCompat
import net.gotev.uploadservice.UploadService
import net.gotev.uploadservice.observer.task.AbstractSingleNotificationHandler
class ExampleSingleNotificationHandler(service: UploadService) :
AbstractSingleNotificationHandler(service) {
override fun updateNotification(
notificationManager: NotificationManager,
notificationBuilder: NotificationCompat.Builder,
tasks: Map<String, TaskData>
): NotificationCompat.Builder? {
// Return null to not update the notification
return notificationBuilder
.setContentTitle("${tasks.size} Uploads")
.setContentText("${tasks.values.count { it.status == TaskStatus.InProgress }} in progress")
.setSmallIcon(android.R.drawable.ic_menu_upload)
}
}
| apache-2.0 |
bravelocation/yeltzland-android | app/src/main/java/com/bravelocation/yeltzlandnew/views/LeagueTableActivityView.kt | 1 | 2979 | package com.bravelocation.yeltzlandnew.views
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.material.MaterialTheme.colors
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.outlined.Refresh
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.navigation.NavController
import com.bravelocation.yeltzlandnew.models.LeagueTable
import com.bravelocation.yeltzlandnew.models.LoadingState
import com.bravelocation.yeltzlandnew.ui.YeltzlandTheme
import com.bravelocation.yeltzlandnew.viewmodels.LeagueTableViewModel
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
@Composable
fun LeagueTableActivityView(
model: LeagueTableViewModel,
navController: NavController
) {
val table: LeagueTable? by model.table.collectAsState()
val loadingState: LoadingState by model.loadingState.observeAsState(LoadingState.LOADING)
val swipeRefreshState = rememberSwipeRefreshState(false)
YeltzlandTheme {
Scaffold(topBar = {
TopAppBar(
title = {
Text(text = "League Table", maxLines = 1, overflow = TextOverflow.Ellipsis)
},
navigationIcon = {
IconButton(onClick = {
navController.popBackStack()
}) {
Icon(Icons.Filled.ArrowBack,"Back", tint = colors.onPrimary)
}
},
actions = {
IconButton(onClick = {
model.load()
}) {
Icon(Icons.Outlined.Refresh,"Reload", tint = colors.onPrimary)
}
},
backgroundColor = colors.primary,
contentColor = colors.onPrimary
)
}) { padding ->
SwipeRefresh(
state = swipeRefreshState,
onRefresh = { model.load() }
) {
Box(modifier = Modifier
.fillMaxSize()
.background(colors.background)
.padding(padding)
) {
table?.let { it1 -> LeagueTableView(it1) }
LoadingOverlay(loadingState == LoadingState.LOADING)
ErrorMessageOverlay(isDisplayed = loadingState == LoadingState.ERROR)
}
}
}
}
} | mit |
AoEiuV020/PaNovel | app/src/main/java/cc/aoeiuv020/panovel/booklist/BookListFragmentAdapter.kt | 1 | 2136 | package cc.aoeiuv020.panovel.booklist
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cc.aoeiuv020.panovel.R
import cc.aoeiuv020.panovel.data.entity.BookList
import kotlinx.android.synthetic.main.book_list_item.view.*
/**
*
* Created by AoEiuV020 on 2017.11.22-14:33:36.
*/
class BookListFragmentAdapter(
private val itemListener: ItemListener
) : androidx.recyclerview.widget.RecyclerView.Adapter<BookListFragmentAdapter.ViewHolder>() {
private var _data: MutableList<BookList> = mutableListOf()
var data: List<BookList>
get() = _data
set(value) {
_data = value.toMutableList()
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.book_list_item, parent, false)
return ViewHolder(itemView, itemListener)
}
override fun getItemCount(): Int = data.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = data[position]
holder.apply(item)
}
class ViewHolder(itemView: View, itemListener: ItemListener) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
private val name = itemView.ivName
private val count = itemView.ivCount
// 提供外面的加调方法使用,
lateinit var bookList: BookList
private set
val ctx: Context = itemView.context
init {
itemView.setOnClickListener {
itemListener.onClick(this)
}
itemView.setOnLongClickListener {
itemListener.onLongClick(this)
}
}
fun apply(bookList: BookList) {
this.bookList = bookList
name.text = bookList.name
// TODO: 改改,顺便要查到数量,
count.text = ""
}
}
interface ItemListener {
fun onClick(vh: ViewHolder)
fun onLongClick(vh: ViewHolder): Boolean
}
} | gpl-3.0 |
free5ty1e/primestationone-control-android | app/src/main/java/com/chrisprime/primestationonecontrol/views/FoundPrimestationsRecyclerViewAdapter.kt | 1 | 2608 | package com.chrisprime.primestationonecontrol.views
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.chrisprime.primestationonecontrol.PrimeStationOneControlApplication
import com.chrisprime.primestationonecontrol.R
import com.chrisprime.primestationonecontrol.model.PrimeStationOne
import com.chrisprime.primestationonecontrol.utilities.FileUtilities
import kotlinx.android.synthetic.main.recyclerview_found_primestations_item.view.*
/**
* Created by cpaian on 7/18/15.
*/
class FoundPrimestationsRecyclerViewAdapter(private val mPrimeStationOneList: List<PrimeStationOne>?) : RecyclerView.Adapter<FoundPrimestationsRecyclerViewAdapter.FoundPrimeStationsRecyclerViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): FoundPrimeStationsRecyclerViewHolder {
val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.recyclerview_found_primestations_item, viewGroup, false)
return FoundPrimeStationsRecyclerViewHolder(view)
}
override fun onBindViewHolder(foundPrimeStationsRecyclerViewHolder: FoundPrimeStationsRecyclerViewHolder, i: Int) {
val primeStationOne = mPrimeStationOneList!![i]
foundPrimeStationsRecyclerViewHolder.primeStationOne = primeStationOne
//Setting text view title
foundPrimeStationsRecyclerViewHolder.itemView.found_primestation_title.text = primeStationOne.ipAddress +
"\n" + primeStationOne.hostname + "\n" + primeStationOne.version + "\n" +
primeStationOne.piUser + ":" + primeStationOne.piPassword + "\n" +
primeStationOne.mac
}
override fun getItemCount(): Int {
return if (null != mPrimeStationOneList) mPrimeStationOneList.size else 0
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
class FoundPrimeStationsRecyclerViewHolder(view: View) : RecyclerView.ViewHolder(view), View.OnClickListener {
var primeStationOne: PrimeStationOne? = null
init {
itemView.isClickable = true
itemView.setOnClickListener(this)
}
override fun onClick(v: View) {
PrimeStationOneControlApplication.instance.currentPrimeStationOne = primeStationOne
Toast.makeText(v.context, "Current PrimeStation One set to: " + primeStationOne!!.toString(), Toast.LENGTH_LONG).show()
FileUtilities.storeCurrentPrimeStationToJson(v.context, primeStationOne!!)
}
}
}
| mit |
tasks/tasks | app/src/main/java/org/tasks/auth/IdentityProvider.kt | 1 | 645 | package org.tasks.auth
import android.net.Uri
import androidx.core.net.toUri
data class IdentityProvider(
val name: String,
val discoveryEndpoint: Uri,
val clientId: String,
val redirectUri: Uri,
val scope: String
) {
companion object {
val MICROSOFT = IdentityProvider(
"Microsoft",
"https://login.microsoftonline.com/consumers/v2.0/.well-known/openid-configuration".toUri(),
"9d4babd5-e7ba-4286-ba4b-17274495a901",
"msauth://org.tasks/8wnYBRqh5nnQgFzbIXfxXSs41xE%3D".toUri(),
"user.read Tasks.ReadWrite openid offline_access email"
)
}
} | gpl-3.0 |
develodroid/kotlin-testing | app/src/androidTest/java/com/example/android/testing/notes/notes/AppNavigationTest.kt | 1 | 3604 | /*
* Copyright 2015, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.testing.notes.notes
import android.support.test.InstrumentationRegistry
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.action.ViewActions.click
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.contrib.DrawerActions.open
import android.support.test.espresso.contrib.DrawerMatchers.isClosed
import android.support.test.espresso.contrib.DrawerMatchers.isOpen
import android.support.test.espresso.contrib.NavigationViewActions.navigateTo
import android.support.test.espresso.matcher.ViewMatchers.*
import android.support.test.filters.LargeTest
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import android.support.v4.widget.DrawerLayout
import android.view.Gravity
import com.example.android.testing.notes.R
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* Tests for the [DrawerLayout] layout component in [NotesActivity] which manages
* navigation within the app.
*/
@RunWith(AndroidJUnit4::class)
@LargeTest
class AppNavigationTest {
/**
* [ActivityTestRule] is a JUnit [@Rule][Rule] to launch your activity under test.
*
*
* Rules are interceptors which are executed for each test method and are important building
* blocks of Junit tests.
*
* @get:Rule
public val mActivityRule: ActivityTestRule<MainActivity> = ActivityTestRule(javaClass<MainActivity>())
*/
@Rule @JvmField
val mActivityTestRule: ActivityTestRule<NotesActivity> = ActivityTestRule(NotesActivity::class.java)
@Test
fun clickOnStatisticsNavigationItem_ShowsStatisticsScreen() {
// Open Drawer to click on navigation.
onView(withId(R.id.drawer_layout)).check(matches(isClosed(Gravity.LEFT))) // Left Drawer should be closed.
.perform(open())
// Open Drawer
// Start statistics screen.
onView(withId(R.id.nav_view)).perform(navigateTo(R.id.statistics_navigation_menu_item))
// Check that statistics Activity was opened.
val expectedNoStatisticsText = InstrumentationRegistry.getTargetContext().getString(R.string.no_statistics_available)
onView(withId(R.id.no_statistics)).check(matches(withText(expectedNoStatisticsText)))
}
@Test
fun clickOnAndroidHomeIcon_OpensNavigation() {
// Check that left drawer is closed at startup
onView(withId(R.id.drawer_layout)).check(matches(isClosed(Gravity.LEFT))) // Left Drawer should be closed.
// Open Drawer
val navigateUpDesc = mActivityTestRule.activity.getString(android.support.v7.appcompat.R.string.abc_action_bar_up_description)
onView(withContentDescription(navigateUpDesc)).perform(click())
// Check if drawer is open
onView(withId(R.id.drawer_layout)).check(matches(isOpen(Gravity.LEFT))) // Left drawer is open open.
}
} | apache-2.0 |
ExMCL/ExMCL | ExMCL Mod Installer/src/main/kotlin/com/n9mtq4/exmcl/modinstaller/InitModInstaller.kt | 1 | 2488 | /*
* MIT License
*
* Copyright (c) 2016 Will (n9Mtq4) Bresnahan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
@file:Suppress("unused", "UNUSED_PARAMETER")
package com.n9mtq4.exmcl.modinstaller
import com.n9mtq4.exmcl.api.hooks.events.MinecraftLauncherEvent
import com.n9mtq4.exmcl.api.tabs.events.CreateTabEvent
import com.n9mtq4.exmcl.api.tabs.events.SafeForTabCreationEvent
import com.n9mtq4.exmcl.modinstaller.ui.ModsTab
import com.n9mtq4.exmcl.modinstaller.utils.il
import com.n9mtq4.kotlin.extlib.pst
import com.n9mtq4.logwindow.BaseConsole
import com.n9mtq4.logwindow.annotation.Async
import com.n9mtq4.logwindow.annotation.ListensFor
import com.n9mtq4.logwindow.listener.GenericListener
import net.minecraft.launcher.Launcher
/**
* Created by will on 2/17/16 at 5:22 PM.
*
* @author Will "n9Mtq4" Bresnahan
*/
class InitModInstaller : GenericListener {
private lateinit var minecraftLauncher: Launcher
@Suppress("unused", "UNUSED_PARAMETER")
@ListensFor
fun listenForMinecraftLauncher(e: MinecraftLauncherEvent, baseConsole: BaseConsole) {
this.minecraftLauncher = e.minecraftLauncher
}
@Suppress("unused")
@Async
@ListensFor
fun listenForTabSafe(e: SafeForTabCreationEvent, baseConsole: BaseConsole) {
il { pst {
val modsTab = ModsTab(minecraftLauncher, baseConsole)
baseConsole.pushEvent(CreateTabEvent("Jar Mods", modsTab, baseConsole))
} }
baseConsole.disableListenerAttribute(this)
}
}
| mit |
Light-Team/ModPE-IDE-Source | app/src/main/kotlin/com/brackeys/ui/feature/explorer/dialogs/ProgressDialog.kt | 1 | 7168 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.brackeys.ui.feature.explorer.dialogs
import android.app.Dialog
import android.os.Bundle
import android.widget.TextView
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.navArgs
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.brackeys.ui.R
import com.brackeys.ui.databinding.DialogProgressBinding
import com.brackeys.ui.feature.explorer.utils.Operation
import com.brackeys.ui.feature.explorer.viewmodel.ExplorerViewModel
import com.brackeys.ui.filesystem.base.model.FileModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import java.text.SimpleDateFormat
import java.util.*
@AndroidEntryPoint
class ProgressDialog : DialogFragment() {
private val viewModel: ExplorerViewModel by activityViewModels()
private val navArgs: ProgressDialogArgs by navArgs()
private lateinit var binding: DialogProgressBinding
private var dialogTitle: Int = -1
private var dialogMessage: Int = -1
private var dialogAction: () -> Unit = {} // Действие, которое запустится при открытии диалога
private var onCloseAction: () -> Unit = {} // Действие, которое выполнится при закрытии диалога
private var indeterminate: Boolean = false // Загрузка без отображения реального прогресса
private var tempFiles: List<FileModel> = emptyList() // Список файлов для отображения информации
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
collectData()
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return MaterialDialog(requireContext()).show {
title(dialogTitle)
customView(R.layout.dialog_progress)
cancelOnTouchOutside(false)
positiveButton(R.string.action_run_in_background) {
onCloseAction.invoke()
}
negativeButton(R.string.action_cancel) {
viewModel.currentJob?.cancel()
onCloseAction.invoke()
}
binding = DialogProgressBinding.bind(getCustomView())
formatElapsedTime(binding.textElapsedTime, 0L) // 00:00
val then = System.currentTimeMillis()
lifecycleScope.launchWhenStarted {
repeat(1000) {
val difference = System.currentTimeMillis() - then
formatElapsedTime(binding.textElapsedTime, difference)
delay(1000)
}
}
val totalProgress = tempFiles.size
binding.progressIndicator.max = totalProgress
binding.progressIndicator.isIndeterminate = indeterminate
val progressObserver = Observer<Int> { currentProgress ->
if (currentProgress < tempFiles.size) {
val fileModel = tempFiles[currentProgress]
binding.textDetails.text = getString(dialogMessage, fileModel.path)
binding.textOfTotal.text = getString(
R.string.message_of_total,
currentProgress + 1,
totalProgress
)
binding.progressIndicator.progress = currentProgress + 1
}
if (currentProgress >= totalProgress) {
onCloseAction.invoke()
dismiss()
}
}
setOnShowListener {
viewModel.progressEvent.observe(this@ProgressDialog, progressObserver)
dialogAction.invoke()
}
setOnDismissListener {
viewModel.progressEvent.removeObservers(this@ProgressDialog)
}
}
}
private fun formatElapsedTime(textView: TextView, timeInMillis: Long) {
val formatter = SimpleDateFormat("mm:ss", Locale.getDefault())
val elapsedTime = getString(
R.string.message_elapsed_time,
formatter.format(timeInMillis)
)
textView.text = elapsedTime
}
private fun collectData() {
tempFiles = viewModel.tempFiles.toList()
viewModel.tempFiles.clear() // Clear immediately
when (viewModel.operation) {
Operation.DELETE -> {
dialogTitle = R.string.dialog_title_deleting
dialogMessage = R.string.message_deleting
dialogAction = {
viewModel.deleteFiles(tempFiles)
}
}
Operation.COPY -> {
dialogTitle = R.string.dialog_title_copying
dialogMessage = R.string.message_copying
dialogAction = {
viewModel.copyFiles(tempFiles, navArgs.parentPath)
}
onCloseAction = {
viewModel.allowPasteFiles.value = false
}
}
Operation.CUT -> {
dialogTitle = R.string.dialog_title_copying
dialogMessage = R.string.message_copying
dialogAction = {
viewModel.cutFiles(tempFiles, navArgs.parentPath)
}
onCloseAction = {
viewModel.allowPasteFiles.value = false
}
}
Operation.COMPRESS -> {
dialogTitle = R.string.dialog_title_compressing
dialogMessage = R.string.message_compressing
dialogAction = {
viewModel.compressFiles(
source = tempFiles,
destPath = navArgs.parentPath,
archiveName = navArgs.archiveName ?: tempFiles.first().name + ".zip"
)
}
}
Operation.EXTRACT -> {
dialogTitle = R.string.dialog_title_extracting
dialogMessage = R.string.message_extracting
dialogAction = {
viewModel.extractAll(tempFiles.first(), navArgs.parentPath)
}
indeterminate = true
}
}
}
} | apache-2.0 |
Light-Team/ModPE-IDE-Source | app/src/main/kotlin/com/brackeys/ui/feature/editor/fragments/EditorFragment.kt | 1 | 26941 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.brackeys.ui.feature.editor.fragments
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.core.widget.TextViewCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.color.ColorPalette
import com.afollestad.materialdialogs.color.colorChooser
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.brackeys.ui.R
import com.brackeys.ui.data.converter.DocumentConverter
import com.brackeys.ui.data.utils.toHexString
import com.brackeys.ui.databinding.FragmentEditorBinding
import com.brackeys.ui.domain.model.documents.DocumentParams
import com.brackeys.ui.domain.model.editor.DocumentContent
import com.brackeys.ui.editorkit.exception.LineException
import com.brackeys.ui.editorkit.listener.OnChangeListener
import com.brackeys.ui.editorkit.listener.OnShortcutListener
import com.brackeys.ui.editorkit.listener.OnUndoRedoChangedListener
import com.brackeys.ui.editorkit.widget.TextScroller
import com.brackeys.ui.feature.editor.adapters.AutoCompleteAdapter
import com.brackeys.ui.feature.editor.adapters.DocumentAdapter
import com.brackeys.ui.feature.editor.utils.Panel
import com.brackeys.ui.feature.editor.utils.TabController
import com.brackeys.ui.feature.editor.utils.ToolbarManager
import com.brackeys.ui.feature.editor.viewmodel.EditorViewModel
import com.brackeys.ui.feature.main.adapters.TabAdapter
import com.brackeys.ui.feature.main.utils.OnBackPressedHandler
import com.brackeys.ui.feature.main.viewmodel.MainViewModel
import com.brackeys.ui.feature.settings.activities.SettingsActivity
import com.brackeys.ui.utils.event.SettingsEvent
import com.brackeys.ui.utils.extensions.*
import com.google.android.material.textfield.TextInputEditText
import dagger.hilt.android.AndroidEntryPoint
import net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEvent
@AndroidEntryPoint
class EditorFragment : Fragment(R.layout.fragment_editor), OnBackPressedHandler,
ToolbarManager.OnPanelClickListener, DocumentAdapter.TabInteractor {
companion object {
private const val ALPHA_FULL = 255
private const val ALPHA_SEMI = 90
private const val TAB_LIMIT = 10
}
private val sharedViewModel: MainViewModel by activityViewModels()
private val viewModel: EditorViewModel by viewModels()
private val toolbarManager: ToolbarManager by lazy { ToolbarManager(this) }
private val tabController: TabController by lazy { TabController() }
private lateinit var binding: FragmentEditorBinding
private lateinit var adapter: DocumentAdapter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentEditorBinding.bind(view)
observeViewModel()
toolbarManager.bind(binding)
binding.tabLayout.setHasFixedSize(true)
binding.tabLayout.adapter = DocumentAdapter(this).also { adapter ->
adapter.setOnTabSelectedListener(object : TabAdapter.OnTabSelectedListener {
override fun onTabUnselected(position: Int) = saveDocument(position)
override fun onTabSelected(position: Int) = loadDocument(position)
})
adapter.setOnDataRefreshListener(object : TabAdapter.OnDataRefreshListener {
override fun onDataRefresh() {
viewModel.emptyView.value = adapter.currentList.isEmpty()
}
})
this.adapter = adapter
}
tabController.attachToRecyclerView(binding.tabLayout)
binding.extendedKeyboard.setKeyListener { char -> binding.editor.insert(char) }
binding.extendedKeyboard.setHasFixedSize(true)
binding.scroller.attachTo(binding.editor)
binding.editor.suggestionAdapter = AutoCompleteAdapter(requireContext())
binding.editor.onUndoRedoChangedListener = OnUndoRedoChangedListener {
val canUndo = binding.editor.canUndo()
val canRedo = binding.editor.canRedo()
binding.actionUndo.isClickable = canUndo
binding.actionRedo.isClickable = canRedo
binding.actionUndo.imageAlpha = if (canUndo) ALPHA_FULL else ALPHA_SEMI
binding.actionRedo.imageAlpha = if (canRedo) ALPHA_FULL else ALPHA_SEMI
}
binding.editor.clearText()
binding.editor.onChangeListener = OnChangeListener {
val position = adapter.selectedPosition
if (position > -1) {
val isModified = adapter.currentList[position].modified
if (!isModified) {
adapter.currentList[position].modified = true
adapter.notifyItemChanged(position)
}
}
}
binding.actionTab.setOnClickListener {
binding.editor.insert(binding.editor.tab())
}
// region SHORTCUTS
binding.editor.onShortcutListener = OnShortcutListener { (ctrl, shift, alt, keyCode) ->
when {
ctrl && shift && keyCode == KeyEvent.KEYCODE_Z -> onUndoButton()
ctrl && shift && keyCode == KeyEvent.KEYCODE_S -> onSaveAsButton()
ctrl && keyCode == KeyEvent.KEYCODE_X -> onCutButton()
ctrl && keyCode == KeyEvent.KEYCODE_C -> onCopyButton()
ctrl && keyCode == KeyEvent.KEYCODE_V -> onPasteButton()
ctrl && keyCode == KeyEvent.KEYCODE_A -> onSelectAllButton()
ctrl && keyCode == KeyEvent.KEYCODE_DEL -> onDeleteLineButton()
ctrl && keyCode == KeyEvent.KEYCODE_D -> onDuplicateLineButton()
ctrl && keyCode == KeyEvent.KEYCODE_Z -> onUndoButton()
ctrl && keyCode == KeyEvent.KEYCODE_Y -> onRedoButton()
ctrl && keyCode == KeyEvent.KEYCODE_S -> onSaveButton()
ctrl && keyCode == KeyEvent.KEYCODE_P -> onPropertiesButton()
ctrl && keyCode == KeyEvent.KEYCODE_W -> onCloseButton()
ctrl && keyCode == KeyEvent.KEYCODE_F -> onOpenFindButton()
ctrl && keyCode == KeyEvent.KEYCODE_R -> onOpenReplaceButton()
ctrl && keyCode == KeyEvent.KEYCODE_G -> onGoToLineButton()
ctrl && keyCode == KeyEvent.KEYCODE_DPAD_LEFT -> binding.editor.moveCaretToStartOfLine()
ctrl && keyCode == KeyEvent.KEYCODE_DPAD_RIGHT -> binding.editor.moveCaretToEndOfLine()
alt && keyCode == KeyEvent.KEYCODE_DPAD_LEFT -> binding.editor.moveCaretToPrevWord()
alt && keyCode == KeyEvent.KEYCODE_DPAD_RIGHT -> binding.editor.moveCaretToNextWord()
alt && keyCode == KeyEvent.KEYCODE_A -> onSelectLineButton()
alt && keyCode == KeyEvent.KEYCODE_S -> onSettingsButton()
keyCode == KeyEvent.KEYCODE_TAB -> { binding.editor.insert(binding.editor.tab()); true }
else -> false
}
}
// endregion SHORTCUTS
viewModel.loadFiles()
}
override fun onPause() {
super.onPause()
saveDocument(adapter.selectedPosition)
}
override fun onResume() {
super.onResume()
loadDocument(adapter.selectedPosition)
viewModel.fetchSettings()
}
override fun handleOnBackPressed(): Boolean {
if (toolbarManager.panel != Panel.DEFAULT) {
onCloseFindButton()
return true
}
return false
}
private fun observeViewModel() {
viewModel.toastEvent.observe(viewLifecycleOwner) {
context?.showToast(it)
}
viewModel.loadFilesEvent.observe(viewLifecycleOwner) { documents ->
adapter.submitList(documents)
val position = viewModel.findRecentTab(documents)
if (position > -1) {
adapter.select(position)
}
}
viewModel.loadingBar.observe(viewLifecycleOwner) { isVisible ->
binding.loadingBar.isVisible = isVisible
if (isVisible) {
binding.editor.isInvisible = isVisible
} else {
if (!binding.emptyViewImage.isVisible) {
binding.editor.isInvisible = isVisible
}
}
}
viewModel.emptyView.observe(viewLifecycleOwner) { isVisible ->
binding.emptyViewImage.isVisible = isVisible
binding.emptyViewText.isVisible = isVisible
binding.editor.isInvisible = isVisible
}
viewModel.parseEvent.observe(viewLifecycleOwner) { model ->
model.exception?.let {
binding.editor.setErrorLine(it.lineNumber)
}
}
viewModel.contentEvent.observe(viewLifecycleOwner) { (content, textParams) ->
binding.scroller.state = TextScroller.STATE_HIDDEN
binding.editor.language = content.language
binding.editor.undoStack = content.undoStack
binding.editor.redoStack = content.redoStack
binding.editor.setTextContent(textParams)
binding.editor.scrollX = content.documentModel.scrollX
binding.editor.scrollY = content.documentModel.scrollY
binding.editor.setSelection(
content.documentModel.selectionStart,
content.documentModel.selectionEnd
)
binding.editor.requestFocus()
}
sharedViewModel.openEvent.observe(viewLifecycleOwner) { documentModel ->
if (!adapter.currentList.contains(documentModel)) {
if (adapter.currentList.size < TAB_LIMIT) {
viewModel.openFile(adapter.currentList + documentModel)
} else {
context?.showToast(R.string.message_tab_limit_achieved)
}
} else {
val position = adapter.currentList.indexOf(documentModel)
adapter.select(position)
}
}
// region PREFERENCES
viewModel.settingsEvent.observe(viewLifecycleOwner) { queue ->
val config = binding.editor.editorConfig
while (!queue.isNullOrEmpty()) {
when (val event = queue.poll()) {
is SettingsEvent.ThemePref -> {
binding.editor.colorScheme = event.value.colorScheme
}
is SettingsEvent.FontSize -> config.fontSize = event.value
is SettingsEvent.FontType -> {
config.fontType = requireContext().createTypefaceFromPath(event.value)
}
is SettingsEvent.WordWrap -> config.wordWrap = event.value
is SettingsEvent.CodeCompletion -> config.codeCompletion = event.value
is SettingsEvent.ErrorHighlight -> {
if (event.value) {
binding.editor.debounce(
coroutineScope = viewLifecycleOwner.lifecycleScope,
waitMs = 1500
) { text ->
if (text.isNotEmpty()) {
val position = adapter.selectedPosition
if (position > -1) {
viewModel.parse(
adapter.currentList[position],
binding.editor.language,
binding.editor.text.toString()
)
}
}
}
}
}
is SettingsEvent.PinchZoom -> config.pinchZoom = event.value
is SettingsEvent.CurrentLine -> config.highlightCurrentLine = event.value
is SettingsEvent.Delimiters -> config.highlightDelimiters = event.value
is SettingsEvent.ExtendedKeys -> {
KeyboardVisibilityEvent.setEventListener(requireActivity(), viewLifecycleOwner) { isOpen ->
binding.keyboardContainer.isVisible = event.value && isOpen
}
}
is SettingsEvent.KeyboardPreset -> {
binding.extendedKeyboard.submitList(event.value)
}
is SettingsEvent.SoftKeys -> config.softKeyboard = event.value
is SettingsEvent.AutoIndent -> config.autoIndentation = event.value
is SettingsEvent.AutoBrackets -> config.autoCloseBrackets = event.value
is SettingsEvent.AutoQuotes -> config.autoCloseQuotes = event.value
is SettingsEvent.UseSpacesNotTabs -> config.useSpacesInsteadOfTabs = event.value
is SettingsEvent.TabWidth -> config.tabWidth = event.value
}
}
binding.editor.editorConfig = config
}
// endregion PREFERENCES
}
// region TABS
override fun close(position: Int) {
val isModified = adapter.currentList[position].modified
if (isModified) {
MaterialDialog(requireContext()).show {
title(text = adapter.currentList[position].name)
message(R.string.dialog_message_close_tab)
negativeButton(R.string.action_cancel)
positiveButton(R.string.action_close) {
closeTabImpl(position)
}
}
} else {
closeTabImpl(position)
}
}
override fun closeOthers(position: Int) {
val tabCount = adapter.itemCount - 1
for (index in tabCount downTo 0) {
if (index != position) {
closeTabImpl(index)
}
}
}
override fun closeAll(position: Int) {
closeOthers(position)
closeTabImpl(adapter.selectedPosition)
}
private fun closeTabImpl(position: Int) {
if (position == adapter.selectedPosition) {
binding.scroller.state = TextScroller.STATE_HIDDEN
binding.editor.clearText() // TTL Exception bypass
if (adapter.itemCount == 1) {
activity?.closeKeyboard()
}
}
removeDocument(position)
adapter.close(position)
}
private fun loadDocument(position: Int) {
if (position > -1) {
val document = adapter.currentList[position]
viewModel.loadFile(document, TextViewCompat.getTextMetricsParams(binding.editor))
}
}
private fun saveDocument(position: Int) {
if (position > -1) {
viewModel.loadingBar.value = true // show loading indicator
val document = adapter.currentList[position].apply {
scrollX = binding.editor.scrollX
scrollY = binding.editor.scrollY
selectionStart = binding.editor.selectionStart
selectionEnd = binding.editor.selectionEnd
}
val text = binding.editor.text.toString()
if (text.isNotEmpty()) {
val documentContent = DocumentContent(
documentModel = document,
language = binding.editor.language,
undoStack = binding.editor.undoStack.clone(),
redoStack = binding.editor.redoStack.clone(),
text = text
)
val params = DocumentParams(
local = viewModel.autoSaveFiles,
cache = true
)
viewModel.saveFile(documentContent, params)
}
binding.editor.clearText() // TTL Exception bypass
adapter.currentList.forEachIndexed { index, model ->
viewModel.updateDocument(model.copy(position = index))
}
}
}
private fun removeDocument(position: Int) {
if (position > -1) {
val documentModel = adapter.currentList[position]
viewModel.deleteDocument(documentModel)
}
}
// endregion TABS
// region TOOLBAR
override fun onDrawerButton() {
sharedViewModel.openDrawerEvent.call()
}
override fun onNewButton() {
onDrawerButton() // TODO 27/02/21 Add Dialog
}
override fun onOpenButton() {
onDrawerButton()
context?.showToast(R.string.message_select_file)
}
override fun onSaveButton(): Boolean {
val position = adapter.selectedPosition
if (position > -1) {
val isModified = adapter.currentList[position].modified
if (isModified) {
adapter.currentList[position].modified = false
adapter.notifyItemChanged(position)
}
val documentContent = DocumentContent(
documentModel = adapter.currentList[position],
language = binding.editor.language,
undoStack = binding.editor.undoStack.clone(),
redoStack = binding.editor.redoStack.clone(),
text = binding.editor.text.toString()
)
val params = DocumentParams(
local = true,
cache = true
)
viewModel.saveFile(documentContent, params)
} else {
context?.showToast(R.string.message_no_open_files)
}
return true
}
override fun onSaveAsButton(): Boolean {
val position = adapter.selectedPosition
if (position > -1) {
val document = adapter.currentList[position]
MaterialDialog(requireContext()).show {
title(R.string.dialog_title_save_as)
customView(R.layout.dialog_save_as, scrollable = true)
negativeButton(R.string.action_cancel)
positiveButton(R.string.action_save) {
val enterFilePath = findViewById<TextInputEditText>(R.id.input)
val filePath = enterFilePath.text?.toString()?.trim()
if (!filePath.isNullOrBlank()) {
val updateDocument = document.copy(
uuid = "whatever",
path = filePath
)
val documentContent = DocumentContent(
documentModel = updateDocument,
language = binding.editor.language,
undoStack = binding.editor.undoStack.clone(),
redoStack = binding.editor.redoStack.clone(),
text = binding.editor.text.toString()
)
val params = DocumentParams(
local = true,
cache = false
)
viewModel.saveFile(documentContent, params)
} else {
context.showToast(R.string.message_invalid_file_path)
}
}
val enterFilePath = findViewById<TextInputEditText>(R.id.input)
enterFilePath.setText(document.path)
}
} else {
context?.showToast(R.string.message_no_open_files)
}
return true
}
override fun onPropertiesButton(): Boolean {
val position = adapter.selectedPosition
if (position > -1) {
val document = adapter.currentList[position]
sharedViewModel.propertiesEvent.value = DocumentConverter.toModel(document)
} else {
context?.showToast(R.string.message_no_open_files)
}
return true
}
override fun onCloseButton(): Boolean {
val position = adapter.selectedPosition
if (position > -1) {
close(position)
} else {
context?.showToast(R.string.message_no_open_files)
}
return true
}
override fun onCutButton(): Boolean {
if (binding.editor.hasSelection()) {
binding.editor.cut()
} else {
context?.showToast(R.string.message_nothing_to_cut)
}
return true
}
override fun onCopyButton(): Boolean {
if (binding.editor.hasSelection()) {
binding.editor.copy()
} else {
context?.showToast(R.string.message_nothing_to_copy)
}
return true
}
override fun onPasteButton(): Boolean {
val position = adapter.selectedPosition
if (binding.editor.hasPrimaryClip() && position > -1) {
binding.editor.paste()
} else {
context?.showToast(R.string.message_nothing_to_paste)
}
return true
}
override fun onSelectAllButton(): Boolean {
binding.editor.selectAll()
return true
}
override fun onSelectLineButton(): Boolean {
binding.editor.selectLine()
return true
}
override fun onDeleteLineButton(): Boolean {
binding.editor.deleteLine()
return true
}
override fun onDuplicateLineButton(): Boolean {
binding.editor.duplicateLine()
return true
}
override fun onOpenFindButton(): Boolean {
val position = adapter.selectedPosition
if (position > -1) {
toolbarManager.panel = Panel.FIND
} else {
context?.showToast(R.string.message_no_open_files)
}
return true
}
override fun onCloseFindButton() {
toolbarManager.panel = Panel.DEFAULT
binding.inputFind.setText("")
binding.editor.clearFindResultSpans()
}
override fun onOpenReplaceButton(): Boolean {
val position = adapter.selectedPosition
if (position > -1) {
toolbarManager.panel = Panel.FIND_REPLACE
} else {
context?.showToast(R.string.message_no_open_files)
}
return true
}
override fun onCloseReplaceButton() {
toolbarManager.panel = Panel.FIND
binding.inputReplace.setText("")
}
override fun onGoToLineButton(): Boolean {
val position = adapter.selectedPosition
if (position > -1) {
MaterialDialog(requireContext()).show {
title(R.string.dialog_title_goto_line)
customView(R.layout.dialog_goto_line)
negativeButton(R.string.action_cancel)
positiveButton(R.string.action_go_to) {
val input = getCustomView().findViewById<TextInputEditText>(R.id.input)
val inputNumber = input.text.toString()
try {
val lineNumber = inputNumber.toIntOrNull() ?: 0
binding.editor.gotoLine(lineNumber)
} catch (e: LineException) {
context.showToast(R.string.message_line_not_exists)
}
}
}
} else {
context?.showToast(R.string.message_no_open_files)
}
return true
}
override fun onReplaceButton(replaceText: String) {
binding.editor.replaceFindResult(replaceText)
}
override fun onReplaceAllButton(replaceText: String) {
binding.editor.replaceAllFindResults(replaceText)
}
override fun onNextResultButton() {
binding.editor.findNext()
}
override fun onPreviousResultButton() {
binding.editor.findPrevious()
}
override fun onFindInputChanged(findText: String) {
binding.editor.clearFindResultSpans()
binding.editor.find(findText, toolbarManager.findParams())
}
override fun onErrorCheckingButton() {
val position = adapter.selectedPosition
if (position > -1) {
MaterialDialog(requireContext()).show {
title(R.string.dialog_title_result)
message(R.string.message_no_errors_detected)
viewModel.parseEvent.value?.let { model ->
model.exception?.let {
message(text = it.message)
binding.editor.setErrorLine(it.lineNumber)
}
}
positiveButton(R.string.action_ok)
}
} else {
context?.showToast(R.string.message_no_open_files)
}
}
override fun onInsertColorButton() {
val position = adapter.selectedPosition
if (position > -1) {
MaterialDialog(requireContext()).show {
title(R.string.dialog_title_color_picker)
colorChooser(
colors = ColorPalette.Primary,
subColors = ColorPalette.PrimarySub,
allowCustomArgb = true,
showAlphaSelector = true
) { _, color ->
binding.editor.insert(color.toHexString())
}
positiveButton(R.string.action_insert)
negativeButton(R.string.action_cancel)
}
} else {
context?.showToast(R.string.message_no_open_files)
}
}
override fun onUndoButton(): Boolean {
if (binding.editor.canUndo()) {
binding.editor.undo()
}
return true
}
override fun onRedoButton(): Boolean {
if (binding.editor.canRedo()) {
binding.editor.redo()
}
return true
}
override fun onSettingsButton(): Boolean {
val intent = Intent(context, SettingsActivity::class.java)
startActivity(intent)
return true
}
// endregion TOOLBAR
} | apache-2.0 |
nemerosa/ontrack | ontrack-extension-casc/src/test/java/net/nemerosa/ontrack/extension/casc/graphql/CascGraphQLIT.kt | 1 | 4750 | package net.nemerosa.ontrack.extension.casc.graphql
import net.nemerosa.ontrack.extension.casc.CascConfigurationProperties
import net.nemerosa.ontrack.graphql.AbstractQLKTITJUnit4Support
import net.nemerosa.ontrack.model.settings.HomePageSettings
import net.nemerosa.ontrack.test.assertJsonNotNull
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class CascGraphQLIT : AbstractQLKTITJUnit4Support() {
@Autowired
private lateinit var cascConfigurationProperties: CascConfigurationProperties
@Test
fun `Accessing the Casc schema`() {
asAdmin {
run("""
{
casc {
schema
}
}
""").let { data ->
val schema = data.path("casc").path("schema")
assertJsonNotNull(schema)
}
}
}
@Test
fun `Accessing the Casc resources`() {
cascConfigurationProperties.apply {
locations = listOf(
"classpath:casc/settings-security.yaml",
"classpath:casc/settings-home-page.yaml",
)
}
asAdmin {
run("""
{
casc {
locations
}
}
""").let { data ->
val locations = data.path("casc").path("locations").map { it.asText() }
assertEquals(
listOf(
"classpath:casc/settings-security.yaml",
"classpath:casc/settings-home-page.yaml",
),
locations
)
}
}
}
@Test
fun `YAML rendering`() {
asAdmin {
withSettings<HomePageSettings> {
settingsManagerService.saveSettings(
HomePageSettings(
maxBranches = 2,
maxProjects = 200,
)
)
run("""
{
casc {
yaml
}
}
""").let { data ->
val yaml = data.path("casc").path("yaml").asText()
assertTrue("maxBranches: 2" in yaml)
assertTrue("maxProjects: 200" in yaml)
}
}
}
}
@Test
fun `Rendering as JSON`() {
asAdmin {
withSettings<HomePageSettings> {
settingsManagerService.saveSettings(
HomePageSettings(
maxBranches = 2,
maxProjects = 200,
)
)
run("""
{
casc {
json
}
}
""").let { data ->
val json = data.path("casc").path("json")
assertEquals(2,
json.path("ontrack").path("config").path("settings").path("home-page").path("maxBranches").asInt())
assertEquals(200,
json.path("ontrack").path("config").path("settings").path("home-page").path("maxProjects").asInt())
}
}
}
}
@Test
fun `Reloading the configuration as code`() {
asAdmin {
withSettings<HomePageSettings> {
// Configuration
cascConfigurationProperties.locations = listOf(
"classpath:casc/settings-home-page.yaml",
)
// Initial values
settingsManagerService.saveSettings(
HomePageSettings(
maxBranches = 2,
maxProjects = 200,
)
)
// Reloading
val data = run("""
mutation {
reloadCasc {
errors {
message
}
}
}
""")
// Checks there are no error
assertNoUserError(data, "reloadCasc")
// Checks the values have been updated
val settings = cachedSettingsService.getCachedSettings(HomePageSettings::class.java)
assertEquals(10, settings.maxBranches)
assertEquals(100, settings.maxProjects)
}
}
}
} | mit |
nemerosa/ontrack | ontrack-service/src/main/java/net/nemerosa/ontrack/service/metrics/MetricsReexportJob.kt | 1 | 1763 | package net.nemerosa.ontrack.service.metrics
import net.nemerosa.ontrack.extension.api.ExtensionManager
import net.nemerosa.ontrack.extension.api.MetricsExportExtension
import net.nemerosa.ontrack.job.*
import net.nemerosa.ontrack.model.metrics.MetricsReexportJobProvider
import net.nemerosa.ontrack.model.support.JobProvider
import org.springframework.stereotype.Component
/**
* Job which re-exports all existing metrics.
*/
@Component
class MetricsReexportJob(
private val extensionManager: ExtensionManager,
private val metricsReexportJobProviders: List<MetricsReexportJobProvider>,
private val jobScheduler: JobScheduler,
) : JobProvider, Job {
override fun getStartingJobs() = listOf(
JobRegistration(
this,
Schedule.NONE
)
)
override fun getKey(): JobKey =
JobCategory.CORE.getType("metrics").withName("Metrics jobs").getKey("restoration")
override fun getTask() = JobRun { listener ->
listener.message("Preparing all the metrics extensions...")
extensionManager.getExtensions(MetricsExportExtension::class.java).forEach { extension ->
listener.message("Preparing ${extension::class.java.name}...")
extension.prepareReexport()
}
listener.message("Launching all the re-exportations...")
metricsReexportJobProviders.forEach { metricsReexportJobProvider ->
val key = metricsReexportJobProvider.getReexportJobKey()
listener.message("Launching (asynchronously) the re-exportation for $key...")
jobScheduler.fireImmediately(key).orElse(null)
}
}
override fun getDescription(): String = "Re-export of all metrics"
override fun isDisabled(): Boolean = false
} | mit |
marciogranzotto/mqtt-painel-kotlin | app/src/main/java/com/granzotto/mqttpainel/MyApplication.kt | 1 | 603 | package com.granzotto.mqttpainel
import android.app.Application
import com.granzotto.mqttpainel.utils.MyConstants
import io.realm.Realm
import io.realm.RealmConfiguration
/**
* Created by marciogranzotto on 5/11/16.
*/
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
Realm.init(this)
val realmConfiguration = RealmConfiguration.Builder()
.schemaVersion(MyConstants.SCHEMA_VERSION)
.deleteRealmIfMigrationNeeded()
.build()
Realm.setDefaultConfiguration(realmConfiguration)
}
} | gpl-3.0 |
rsiebert/TVHClient | data/src/main/java/org/tvheadend/data/entity/Input.kt | 1 | 693 | package org.tvheadend.data.entity
data class Input(
var uuid: String = "",
var input: String = "",
var username: String = "",
var stream: String = "",
var numberOfSubscriptions: Int = 0,
var weight: Int = 0,
var signalStrength: Int = 0, // Shown as percentage from a range between 0 to 65535)
var bitErrorRate: Int = 0,
var uncorrectedBlocks: Int = 0,
var signalNoiseRatio: Int = 0, // Shown as percentage from a range between 0 to 65535)
var bandWidth: Int = 0, // bits/second
var continuityErrors: Int = 0,
var transportErrors: Int = 0,
var connectionId: Int = 0
)
| gpl-3.0 |
LarsKrogJensen/graphql-kotlin | src/main/kotlin/graphql/validation/rules/FieldsOnCorrectType.kt | 1 | 834 | package graphql.validation.rules
import graphql.language.Field
import graphql.validation.IValidationContext
import graphql.validation.ValidationError
import graphql.validation.ValidationErrorType
import graphql.validation.*
class FieldsOnCorrectType(validationContext: IValidationContext,
validationErrorCollector: ValidationErrorCollector)
: AbstractRule(validationContext, validationErrorCollector) {
override fun checkField(field: Field) {
if (validationContext.parentType == null)
return
val fieldDef = validationContext.fieldDef
if (fieldDef == null) {
val message = String.format("Field %s is undefined", field.name)
addError(ValidationError(ValidationErrorType.FieldUndefined, field.sourceLocation, message))
}
}
}
| mit |
nickbutcher/plaid | designernews/src/main/java/io/plaidapp/designernews/domain/GetCommentsWithRepliesUseCase.kt | 1 | 3945 | /*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.designernews.domain
import io.plaidapp.core.data.Result
import io.plaidapp.core.designernews.domain.model.CommentWithReplies
import io.plaidapp.designernews.data.comments.CommentsRepository
import io.plaidapp.designernews.data.comments.model.CommentResponse
import io.plaidapp.designernews.data.comments.model.toCommentsWithReplies
import java.io.IOException
import javax.inject.Inject
/**
* Use case that constructs the entire comments and replies tree for a list of comments. Works
* with the [CommentsRepository] to get the data.
*/
class GetCommentsWithRepliesUseCase @Inject constructor(
private val commentsRepository: CommentsRepository
) {
/**
* Get all comments and their replies. If we get an error on any reply depth level, ignore it
* and just use the comments retrieved until that point.
*/
suspend operator fun invoke(parentIds: List<Long>): Result<List<CommentWithReplies>> {
val replies = mutableListOf<List<CommentResponse>>()
// get the first level of comments
var parentComments = commentsRepository.getComments(parentIds)
// as long as we could get comments or replies to comments
while (parentComments is Result.Success) {
val parents = parentComments.data
// add the replies
replies.add(parents)
// check if we have another level of replies
val replyIds = parents.flatMap { comment -> comment.links.comments }
if (!replyIds.isEmpty()) {
parentComments = commentsRepository.getComments(replyIds)
} else {
// we don't have any other level of replies match the replies to the comments
// they belong to and return the first level of comments.
if (replies.isNotEmpty()) {
return Result.Success(matchComments(replies))
}
}
}
// the last request was unsuccessful
// if we already got some comments and replies, then use that data and ignore the error
return when {
replies.isNotEmpty() -> Result.Success(matchComments(replies))
parentComments is Result.Error -> parentComments
else -> Result.Error(IOException("Unable to get comments"))
}
}
/**
* Build up the replies tree, by matching the replies from lower levels to the level above they
* belong to
*/
private fun matchComments(comments: List<List<CommentResponse>>): List<CommentWithReplies> {
var commentsWithReplies = emptyList<CommentWithReplies>()
for (index in comments.size - 1 downTo 0) {
commentsWithReplies = matchCommentsWithReplies(comments[index], commentsWithReplies)
}
return commentsWithReplies
}
private fun matchCommentsWithReplies(
comments: List<CommentResponse>,
replies: List<CommentWithReplies>
): List<CommentWithReplies> {
val commentReplyMapping = replies.groupBy { it.parentId }
// for every comment construct the CommentWithReplies based on the comment properties and
// the list of replies
return comments.map {
val commentReplies = commentReplyMapping[it.id].orEmpty()
it.toCommentsWithReplies(commentReplies)
}
}
}
| apache-2.0 |
d9n/intellij-rust | src/test/kotlin/org/rust/ide/annotator/RsHighlightingAnnotatorTest.kt | 1 | 4095 | package org.rust.ide.annotator
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl
class RsHighlightingAnnotatorTest : RsAnnotatorTestBase() {
fun testAttributes() = checkInfo("""
<info>#[cfg_attr(foo)]</info>
fn <info>main</info>() {
<info>#![crate_type = <info>"lib"</info>]</info>
}
""")
fun testFieldsAndMethods() = checkInfo("""
struct <info>T</info>(<info>i32</info>);
struct <info>S</info>{ <info>field</info>: <info>T</info>}
fn <info>main</info>() {
let s = <info>S</info>{ <info>field</info>: <info>T</info>(92) };
s.<info>field</info>.0;
}
""")
fun testFunctions() = checkInfo("""
fn <info>main</info>() {}
struct <info>S</info>;
impl <info>S</info> {
fn <info>foo</info>() {}
}
trait <info>T</info> {
fn <info>foo</info>();
fn <info>bar</info>() {}
}
impl <info>T</info> for <info>S</info> {
fn <info>foo</info>() {}
}
""")
private val `$` = '$'
fun testMacro() = checkInfo("""
fn <info>main</info>() {
<info>println!</info>["Hello, World!"];
<info>unreachable!</info>();
}
<info>macro_rules!</info> foo {
(x => $`$`<info>e</info>:expr) => (println!("mode X: {}", $`$`<info>e</info>));
(y => $`$`<info>e</info>:expr) => (println!("mode Y: {}", $`$`<info>e</info>));
}
impl T {
<info>foo!</info>();
}
""")
fun testMutBinding() = checkInfo("""
fn <info>main</info>() {
let mut <info>a</info> = 1;
let b = <info>a</info>;
let Some(ref mut <info>c</info>) = Some(10);
let d = <info>c</info>;
}
""")
fun testTypeParameters() = checkInfo("""
trait <info>MyTrait</info> {
type <info>AssocType</info>;
fn <info>some_fn</info>(&<info>self</info>);
}
struct <info>MyStruct</info><<info>N</info>: ?<info>Sized</info>+<info>Debug</info>+<info><info>MyTrait</info></info>> {
<info>N</info>: my_field
}
""")
fun testFunctionArguments() = checkInfo("""
struct <info>Foo</info> {}
impl <info>Foo</info> {
fn <info>bar</info>(&<info>self</info>, (<info>i</info>, <info>j</info>): (<info>i32</info>, <info>i32</info>)) {}
}
fn <info>baz</info>(<info>u</info>: <info>u32</info>) {}
""")
fun testContextualKeywords() = checkInfo("""
trait <info>T</info> {
fn <info>foo</info>();
}
<info>union</info> <info>U</info> { }
impl <info>T</info> for <info>U</info> {
<info>default</info> fn <info>foo</info>() {}
}
""")
fun testQOperator() = checkInfo("""
fn <info>foo</info>() -> Result<<info>i32</info>, ()>{
Ok(Ok(1)<info>?</info> * 2)
}
""")
fun testTypeAlias() = checkInfo("""
type <info>Bar</info> = <info>u32</info>;
fn <info>main</info>() {
let a: <info>Bar</info> = 10;
}
""")
fun testSelfIsNotOverAnnotated() = checkInfo("""
pub use self::<info>foo</info>;
mod <info>foo</info> {
pub use self::<info>bar</info>;
pub mod <info>bar</info> {}
}
""")
fun testDontTouchAstInOtherFiles() {
val files = ProjectFile.parseFileCollection("""
//- main.rs
mod aux;
fn <info>main</info>() {
let _ = aux::<info>S</info>;
}
//- aux.rs
pub struct S;
""")
for ((path, text) in files) {
myFixture.tempDirFixture.createFile(path, text)
}
(myFixture as CodeInsightTestFixtureImpl) // meh
.setVirtualFileFilter { !it.path.endsWith(files[0].path) }
myFixture.configureFromTempProjectFile(files[0].path)
myFixture.testHighlighting(false, true, false)
}
}
| mit |
genobis/tornadofx | src/main/java/tornadofx/Validation.kt | 1 | 7076 | @file:Suppress("unused")
package tornadofx
import javafx.beans.binding.BooleanExpression
import javafx.beans.property.BooleanProperty
import javafx.beans.property.ReadOnlyBooleanProperty
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.value.ObservableValue
import javafx.collections.FXCollections
import javafx.scene.Node
import javafx.scene.control.TextInputControl
import kotlin.concurrent.thread
enum class ValidationSeverity { Error, Warning, Info, Success }
sealed class ValidationTrigger {
object OnBlur : ValidationTrigger()
class OnChange(val delay: Long = 0) : ValidationTrigger()
object None : ValidationTrigger()
}
class ValidationMessage(val message: String?, val severity: ValidationSeverity)
class ValidationContext {
val validators = FXCollections.observableArrayList<Validator<*>>()
/**
* The decoration provider decides what kind of decoration should be applied to
* a control when validation fails. The default decorator will paint a small triangle
* in the top left corner and display a Tooltip with the error message.
*/
var decorationProvider: (ValidationMessage) -> Decorator? = { SimpleMessageDecorator(it.message, it.severity) }
/**
* Add the given validator to the given property. The supplied node will be decorated by
* the current decorationProvider for this context if validation fails.
*
* The validator function is executed in the scope of this ValidationContex to give
* access to other fields and shortcuts like the error and warning functions.
*
* The validation trigger decides when the validation is applied. ValidationTrigger.OnBlur
* tracks focus on the supplied node while OnChange tracks changes to the property itself.
*/
inline fun <reified T> addValidator(
node: Node,
property: ObservableValue<T>,
trigger: ValidationTrigger = ValidationTrigger.OnChange(),
noinline validator: ValidationContext.(T?) -> ValidationMessage?) = addValidator(Validator(node, property, trigger, validator))
fun <T> addValidator(validator: Validator<T>, decorateErrors: Boolean = true): Validator<T> {
when (validator.trigger) {
is ValidationTrigger.OnChange -> {
var delayActive = false
validator.property.onChange {
if (validator.trigger.delay == 0L) {
validator.validate(decorateErrors)
} else {
if (!delayActive) {
delayActive = true
thread(true) {
Thread.sleep(validator.trigger.delay)
FX.runAndWait {
validator.validate(decorateErrors)
}
delayActive = false
}
}
}
}
}
is ValidationTrigger.OnBlur -> {
validator.node.focusedProperty().onChange {
if (!it) validator.validate(decorateErrors)
}
}
}
validators.add(validator)
return validator
}
/**
* A boolean indicating the current validation status.
*/
val valid: ReadOnlyBooleanProperty = SimpleBooleanProperty(true)
val isValid by valid
/**
* Rerun all validators (or just the ones passed in) and return a boolean indicating if validation passed.
*/
fun validate(vararg fields: ObservableValue<*>) = validate(true, true, fields = *fields)
/**
* Rerun all validators (or just the ones passed in) and return a boolean indicating if validation passed.
* It is allowed to pass inn fields that has no corresponding validator. They will register as validated.
*/
fun validate(focusFirstError: Boolean = true, decorateErrors: Boolean = true, vararg fields: ObservableValue<*>): Boolean {
var firstErrorFocused = false
var validationSucceeded = true
val validateThese = if (fields.isEmpty()) validators else validators.filter {
val facade = it.property.viewModelFacade
facade != null && facade in fields
}
for (validator in validateThese) {
if (!validator.validate(decorateErrors)) {
validationSucceeded = false
if (focusFirstError && !firstErrorFocused) {
firstErrorFocused = true
validator.node.requestFocus()
}
}
}
return validationSucceeded
}
/**
* Add validator for a TextInputControl and validate the control's textProperty. Useful when
* you don't bind against a ViewModel or other backing property.
*/
fun addValidator(node: TextInputControl, trigger: ValidationTrigger = ValidationTrigger.OnChange(), validator: ValidationContext.(String?) -> ValidationMessage?) =
addValidator<String>(node, node.textProperty(), trigger, validator)
fun error(message: String? = null) = ValidationMessage(message, ValidationSeverity.Error)
fun info(message: String? = null) = ValidationMessage(message, ValidationSeverity.Info)
fun warning(message: String? = null) = ValidationMessage(message, ValidationSeverity.Warning)
fun success(message: String? = null) = ValidationMessage(message, ValidationSeverity.Success)
/**
* Update the valid property state. If the calling validator was valid we need to see if any of the other properties are invalid.
* If the calling validator is invalid, we know the state is invalid so no need to check the other validators.
*/
internal fun updateValidState(callingValidatorState: Boolean) {
(valid as BooleanProperty).value = if (callingValidatorState) validators.find { !it.isValid } == null else false
}
inner class Validator<T>(
val node: Node,
val property: ObservableValue<T>,
val trigger: ValidationTrigger = ValidationTrigger.OnChange(),
val validator: ValidationContext.(T?) -> ValidationMessage?) {
var result: ValidationMessage? = null
var decorator: Decorator? = null
val valid: BooleanExpression = SimpleBooleanProperty(true)
val isValid: Boolean get() = valid.value
fun validate(decorateErrors: Boolean = true): Boolean {
decorator?.apply { undecorate(node) }
decorator = null
result = validator(this@ValidationContext, property.value)
(valid as BooleanProperty).value = result == null || result!!.severity != ValidationSeverity.Error
if (decorateErrors) {
result?.apply {
decorator = decorationProvider(this)
decorator!!.decorate(node)
}
}
updateValidState(isValid)
return isValid
}
}
} | apache-2.0 |
goodwinnk/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/generators/Generators.kt | 1 | 35309 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused")
package com.intellij.testGuiFramework.generators
import com.intellij.icons.AllIcons
import com.intellij.ide.plugins.PluginTable
import com.intellij.ide.projectView.impl.ProjectViewTree
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.actionSystem.impl.ActionMenu
import com.intellij.openapi.actionSystem.impl.ActionMenuItem
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.editor.impl.EditorComponentImpl
import com.intellij.openapi.ui.*
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.openapi.wm.impl.ToolWindowImpl
import com.intellij.openapi.wm.impl.ToolWindowManagerImpl
import com.intellij.openapi.wm.impl.WindowManagerImpl
import com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame
import com.intellij.testGuiFramework.cellReader.ExtendedJListCellReader
import com.intellij.testGuiFramework.cellReader.ExtendedJTableCellReader
import com.intellij.testGuiFramework.driver.CheckboxTreeDriver
import com.intellij.testGuiFramework.fixtures.MainToolbarFixture
import com.intellij.testGuiFramework.fixtures.MessagesFixture
import com.intellij.testGuiFramework.fixtures.NavigationBarFixture
import com.intellij.testGuiFramework.fixtures.SettingsTreeFixture
import com.intellij.testGuiFramework.fixtures.extended.getPathStrings
import com.intellij.testGuiFramework.framework.GuiTestUtil
import com.intellij.testGuiFramework.generators.Utils.clicks
import com.intellij.testGuiFramework.generators.Utils.convertSimpleTreeItemToPath
import com.intellij.testGuiFramework.generators.Utils.findBoundedText
import com.intellij.testGuiFramework.generators.Utils.getCellText
import com.intellij.testGuiFramework.generators.Utils.getJTreePath
import com.intellij.testGuiFramework.generators.Utils.getJTreePathItemsString
import com.intellij.testGuiFramework.generators.Utils.withRobot
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.getComponentText
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.isTextComponent
import com.intellij.testGuiFramework.impl.GuiTestUtilKt.onHeightCenter
import com.intellij.ui.CheckboxTree
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.HyperlinkLabel
import com.intellij.ui.InplaceButton
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBList
import com.intellij.ui.components.JBTabbedPane
import com.intellij.ui.components.labels.ActionLink
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.messages.SheetController
import com.intellij.ui.tabs.impl.TabLabel
import com.intellij.ui.treeStructure.SimpleTree
import com.intellij.ui.treeStructure.treetable.TreeTable
import com.intellij.util.ui.tree.TreeUtil
import org.fest.reflect.core.Reflection.field
import org.fest.swing.core.BasicRobot
import org.fest.swing.core.ComponentMatcher
import org.fest.swing.core.GenericTypeMatcher
import org.fest.swing.core.Robot
import org.fest.swing.exception.ComponentLookupException
import java.awt.*
import java.awt.event.MouseEvent
import java.io.File
import java.net.URI
import java.nio.file.Paths
import java.util.*
import java.util.jar.JarFile
import javax.swing.*
import javax.swing.plaf.basic.BasicArrowButton
import javax.swing.tree.TreeNode
import javax.swing.tree.TreePath
//**********COMPONENT GENERATORS**********
private val leftButton = MouseEvent.BUTTON1
private val rightButton = MouseEvent.BUTTON3
private fun MouseEvent.isLeftButton() = (this.button == leftButton)
private fun MouseEvent.isRightButton() = (this.button == rightButton)
class JButtonGenerator : ComponentCodeGenerator<JButton> {
override fun accept(cmp: Component): Boolean = cmp is JButton
override fun generate(cmp: JButton, me: MouseEvent, cp: Point): String = """button("${cmp.text}").click()"""
}
class InplaceButtonGenerator : ComponentCodeGenerator<InplaceButton> {
override fun accept(cmp: Component): Boolean = cmp is InplaceButton
override fun generate(cmp: InplaceButton, me: MouseEvent, cp: Point): String = """inplaceButton(${getIconClassName(cmp)}).click()"""
private fun getIconClassName(inplaceButton: InplaceButton): String {
val icon = inplaceButton.icon
val iconField = AllIcons::class.java.classes.flatMap { it.fields.filter { it.type == Icon::class.java } }.firstOrNull {
it.get(null) is Icon && (it.get(null) as Icon) == icon
} ?: return "REPLACE IT WITH ICON $icon"
return "${iconField.declaringClass?.canonicalName}.${iconField.name}"
}
}
class JSpinnerGenerator : ComponentCodeGenerator<JButton> {
override fun accept(cmp: Component): Boolean = cmp.parent is JSpinner
override fun priority(): Int = 1
override fun generate(cmp: JButton, me: MouseEvent, cp: Point): String {
val labelText = Utils.getBoundedLabel(cmp.parent).text
return if (cmp.name.contains("nextButton"))
"""spinner("$labelText").increment()"""
else
"""spinner("$labelText").decrement()"""
}
}
class TreeTableGenerator : ComponentCodeGenerator<TreeTable> {
override fun accept(cmp: Component): Boolean = cmp is TreeTable
override fun generate(cmp: TreeTable, me: MouseEvent, cp: Point): String {
val path = cmp.tree.getClosestPathForLocation(cp.x, cp.y)
val treeStringPath = getJTreePath(cmp.tree, path)
val column = cmp.columnAtPoint(cp)
return """treeTable().clickColumn($column, $treeStringPath)"""
}
override fun priority(): Int = 10
}
class ComponentWithBrowseButtonGenerator : ComponentCodeGenerator<FixedSizeButton> {
override fun accept(cmp: Component): Boolean {
return cmp.parent.parent is ComponentWithBrowseButton<*>
}
override fun generate(cmp: FixedSizeButton, me: MouseEvent, cp: Point): String {
val componentWithBrowseButton = cmp.parent.parent
val labelText = Utils.getBoundedLabel(componentWithBrowseButton).text
return """componentWithBrowseButton("$labelText").clickButton()"""
}
}
class ActionButtonGenerator : ComponentCodeGenerator<ActionButton> {
override fun accept(cmp: Component): Boolean = cmp is ActionButton
override fun generate(cmp: ActionButton, me: MouseEvent, cp: Point): String {
val text = cmp.action.templatePresentation.text
val simpleClassName = cmp.action.javaClass.simpleName
val result: String = if (text.isNullOrEmpty())
"""actionButtonByClass("$simpleClassName").click()"""
else
"""actionButton("$text").click()"""
return result
}
}
class ActionLinkGenerator : ComponentCodeGenerator<ActionLink> {
override fun priority(): Int = 1
override fun accept(cmp: Component): Boolean = cmp is ActionLink
override fun generate(cmp: ActionLink, me: MouseEvent, cp: Point): String = """actionLink("${cmp.text}").click()"""
}
class JTextFieldGenerator : ComponentCodeGenerator<JTextField> {
override fun accept(cmp: Component): Boolean = cmp is JTextField
override fun generate(cmp: JTextField, me: MouseEvent, cp: Point): String = """textfield("${findBoundedText(cmp).orEmpty()}").${clicks(
me)}"""
}
class JBListGenerator : ComponentCodeGenerator<JBList<*>> {
override fun priority(): Int = 1
override fun accept(cmp: Component): Boolean = cmp is JBList<*>
private fun JBList<*>.isPopupList() = this.javaClass.name.toLowerCase().contains("listpopup")
private fun JBList<*>.isFrameworksTree() = this.javaClass.name.toLowerCase().contains("AddSupportForFrameworksPanel".toLowerCase())
override fun generate(cmp: JBList<*>, me: MouseEvent, cp: Point): String {
val cellText = getCellText(cmp, cp).orEmpty()
if (cmp.isPopupList()) return """popupMenu("$cellText").clickSearchedItem()"""
if (me.button == MouseEvent.BUTTON2) return """jList("$cellText").item("$cellText").rightClick()"""
if (me.clickCount == 2) return """jList("$cellText").doubleClickItem("$cellText")"""
return """jList("$cellText").clickItem("$cellText")"""
}
}
class BasicComboPopupGenerator : ComponentCodeGenerator<JList<*>> {
override fun accept(cmp: Component): Boolean = cmp is JList<*> && cmp.javaClass.name.contains("BasicComboPopup")
override fun generate(cmp: JList<*>, me: MouseEvent, cp: Point): String {
val cellText = getCellText(cmp, cp).orEmpty()
return """.selectItem("$cellText")""" // check that combobox is open
}
}
class CheckboxTreeGenerator : ComponentCodeGenerator<CheckboxTree> {
override fun accept(cmp: Component): Boolean = cmp is CheckboxTree
private fun JTree.getPath(cp: Point): TreePath = this.getClosestPathForLocation(cp.x, cp.y)
private fun wasClickOnCheckBox(cmp: CheckboxTree, cp: Point): Boolean {
val treePath = cmp.getPath(cp)
println("CheckboxTreeGenerator.wasClickOnCheckBox: treePath = ${treePath.path.joinToString()}")
return withRobot {
val checkboxComponent = CheckboxTreeDriver(it).getCheckboxComponent(cmp, treePath) ?: throw Exception(
"Checkbox component from cell renderer is null")
val pathBounds = cmp.getPathBounds(treePath)
val checkboxTreeBounds = Rectangle(pathBounds.x + checkboxComponent.x, pathBounds.y + checkboxComponent.y, checkboxComponent.width,
checkboxComponent.height)
checkboxTreeBounds.contains(cp)
}
}
override fun generate(cmp: CheckboxTree, me: MouseEvent, cp: Point): String {
val path = getJTreePath(cmp, cmp.getPath(cp))
return if (wasClickOnCheckBox(cmp, cp))
"checkboxTree($path).clickCheckbox()"
else
"checkboxTree($path).clickPath()"
}
}
class SimpleTreeGenerator : ComponentCodeGenerator<SimpleTree> {
override fun accept(cmp: Component): Boolean = cmp is SimpleTree
private fun SimpleTree.getPath(cp: Point) = convertSimpleTreeItemToPath(this, this.getDeepestRendererComponentAt(cp.x, cp.y).toString())
override fun generate(cmp: SimpleTree, me: MouseEvent, cp: Point): String {
val path = cmp.getPath(cp)
if (me.isRightButton()) return """jTree("$path").rightClickPath("$path")"""
return """jTree("$path").selectPath("$path")"""
}
}
class JTableGenerator : ComponentCodeGenerator<JTable> {
override fun accept(cmp: Component): Boolean = cmp is JTable
override fun generate(cmp: JTable, me: MouseEvent, cp: Point): String {
val row = cmp.rowAtPoint(cp)
val col = cmp.columnAtPoint(cp)
val cellText = ExtendedJTableCellReader().valueAt(cmp, row, col)
return """table("$cellText").cell("$cellText")""".addClick(me)
}
}
class JBCheckBoxGenerator : ComponentCodeGenerator<JBCheckBox> {
override fun priority(): Int = 1
override fun accept(cmp: Component): Boolean = cmp is JBCheckBox
override fun generate(cmp: JBCheckBox, me: MouseEvent, cp: Point): String = """checkbox("${cmp.text}").click()"""
}
class JCheckBoxGenerator : ComponentCodeGenerator<JCheckBox> {
override fun accept(cmp: Component): Boolean = cmp is JCheckBox
override fun generate(cmp: JCheckBox, me: MouseEvent, cp: Point): String = """checkbox("${cmp.text}").click()"""
}
class JComboBoxGenerator : ComponentCodeGenerator<JComboBox<*>> {
override fun accept(cmp: Component): Boolean = cmp is JComboBox<*>
override fun generate(cmp: JComboBox<*>, me: MouseEvent, cp: Point): String = """combobox("${findBoundedText(cmp).orEmpty()}")"""
}
class BasicArrowButtonDelegatedGenerator : ComponentCodeGenerator<BasicArrowButton> {
override fun priority(): Int = 1 //make sense if we challenge with simple jbutton
override fun accept(cmp: Component): Boolean = (cmp is BasicArrowButton) && (cmp.parent is JComboBox<*>)
override fun generate(cmp: BasicArrowButton, me: MouseEvent, cp: Point): String =
JComboBoxGenerator().generate(cmp.parent as JComboBox<*>, me, cp)
}
class JRadioButtonGenerator : ComponentCodeGenerator<JRadioButton> {
override fun accept(cmp: Component): Boolean = cmp is JRadioButton
override fun generate(cmp: JRadioButton, me: MouseEvent, cp: Point): String = """radioButton("${cmp.text}").select()"""
}
class LinkLabelGenerator : ComponentCodeGenerator<LinkLabel<*>> {
override fun accept(cmp: Component): Boolean = cmp is LinkLabel<*>
override fun generate(cmp: LinkLabel<*>, me: MouseEvent, cp: Point): String = """linkLabel("${cmp.text}").click()"""
}
class HyperlinkLabelGenerator : ComponentCodeGenerator<HyperlinkLabel> {
override fun accept(cmp: Component): Boolean = cmp is HyperlinkLabel
override fun generate(cmp: HyperlinkLabel, me: MouseEvent, cp: Point): String {
//we assume, that hyperlink label has only one highlighted region
val linkText = cmp.highlightedRegionsBoundsMap.keys.toList().firstOrNull() ?: "null"
return """hyperlinkLabel("${cmp.text}").clickLink("$linkText")"""
}
}
class HyperlinkLabelInNotificationPanelGenerator : ComponentCodeGenerator<HyperlinkLabel> {
override fun accept(cmp: Component): Boolean = cmp is HyperlinkLabel && cmp.hasInParents(EditorNotificationPanel::class.java)
override fun priority(): Int = 1
override fun generate(cmp: HyperlinkLabel, me: MouseEvent, cp: Point): String {
//we assume, that hyperlink label has only one highlighted region
val linkText = cmp.highlightedRegionsBoundsMap.keys.toList().firstOrNull() ?: "null"
return """editor { notificationPanel().clickLink("$linkText") }"""
}
}
class JTreeGenerator : ComponentCodeGenerator<JTree> {
override fun accept(cmp: Component): Boolean = cmp is JTree
private fun JTree.getPath(cp: Point) = this.getClosestPathForLocation(cp.x, cp.y)
override fun generate(cmp: JTree, me: MouseEvent, cp: Point): String {
val path = getJTreePath(cmp, cmp.getPath(cp))
if (me.isRightButton()) return "jTree($path).rightClickPath()"
return "jTree($path).clickPath()"
}
}
class ProjectViewTreeGenerator : ComponentCodeGenerator<ProjectViewTree> {
override fun priority(): Int = 1
override fun accept(cmp: Component): Boolean = cmp is ProjectViewTree
private fun JTree.getPath(cp: Point) = this.getClosestPathForLocation(cp.x, cp.y)
override fun generate(cmp: ProjectViewTree, me: MouseEvent, cp: Point): String {
val path = if(cmp.getPath(cp) != null) getJTreePathItemsString(cmp, cmp.getPath(cp)) else ""
if (me.isRightButton()) return "path($path).rightClick()"
if (me.clickCount == 2) return "path($path).doubleClick()"
return "path($path).click()"
}
}
class PluginTableGenerator : ComponentCodeGenerator<PluginTable> {
override fun accept(cmp: Component): Boolean = cmp is PluginTable
override fun generate(cmp: PluginTable, me: MouseEvent, cp: Point): String {
val row = cmp.rowAtPoint(cp)
val ideaPluginDescriptor = cmp.getObjectAt(row)
return """pluginTable().selectPlugin("${ideaPluginDescriptor.name}")"""
}
}
class EditorComponentGenerator : ComponentSelectionCodeGenerator<EditorComponentImpl> {
override fun generateSelection(cmp: EditorComponentImpl, firstPoint: Point, lastPoint: Point): String {
val editor = cmp.editor
val firstOffset = editor.logicalPositionToOffset(editor.xyToLogicalPosition(firstPoint))
val lastOffset = editor.logicalPositionToOffset(editor.xyToLogicalPosition(lastPoint))
return "select($firstOffset, $lastOffset)"
}
override fun accept(cmp: Component): Boolean = cmp is EditorComponentImpl
override fun generate(cmp: EditorComponentImpl, me: MouseEvent, cp: Point): String {
val editor = cmp.editor
val logicalPos = editor.xyToLogicalPosition(cp)
val offset = editor.logicalPositionToOffset(logicalPos)
return when (me.button) {
leftButton -> "moveTo($offset)"
rightButton -> "rightClick($offset)"
else -> "//not implemented editor action"
}
}
}
class ActionMenuItemGenerator : ComponentCodeGenerator<ActionMenuItem> {
override fun accept(cmp: Component): Boolean = cmp is ActionMenuItem
override fun generate(cmp: ActionMenuItem, me: MouseEvent, cp: Point): String =
"menu(${buildPath(activatedActionMenuItem = cmp).joinToString(separator = ", ") { str -> "\"$str\"" }}).click()"
//for buildnig a path of actionMenus and actionMenuItem we need to scan all JBPopup and find a consequence of actions from a tail. Each discovered JBPopupMenu added to hashSet to avoid double sacnning and multiple component finding results
private fun buildPath(activatedActionMenuItem: ActionMenuItem): List<String> {
val jbPopupMenuSet = HashSet<Int>()
jbPopupMenuSet.add(activatedActionMenuItem.parent.hashCode())
val path = ArrayList<String>()
var actionItemName = activatedActionMenuItem.text
path.add(actionItemName)
var window = activatedActionMenuItem.getNextPopupSHeavyWeightWindow()
while (window?.getNextPopupSHeavyWeightWindow() != null) {
window = window.getNextPopupSHeavyWeightWindow()
actionItemName = window!!.findJBPopupMenu(jbPopupMenuSet).findParentActionMenu(jbPopupMenuSet)
path.add(0, actionItemName)
}
return path
}
private fun Component.getNextPopupSHeavyWeightWindow(): JWindow? {
if (this.parent == null) return null
var cmp = this.parent
while (cmp != null && !cmp.javaClass.name.endsWith("Popup\$HeavyWeightWindow")) cmp = cmp.parent
if (cmp == null) return null
return cmp as JWindow
}
private fun JWindow.findJBPopupMenu(jbPopupHashSet: MutableSet<Int>): JBPopupMenu {
return withRobot { robot ->
val resultJBPopupMenu = robot.finder().find(this, ComponentMatcher { component ->
(component is JBPopupMenu)
&& component.isShowing
&& component.isVisible
&& !jbPopupHashSet.contains(component.hashCode())
}) as JBPopupMenu
jbPopupHashSet.add(resultJBPopupMenu.hashCode())
resultJBPopupMenu
}
}
private fun JBPopupMenu.findParentActionMenu(jbPopupHashSet: MutableSet<Int>): String {
val actionMenu = this.subElements
.filterIsInstance(ActionMenu::class.java)
.find { actionMenu ->
actionMenu.subElements != null && actionMenu.subElements.isNotEmpty() && actionMenu.subElements.any { menuElement ->
menuElement is JBPopupMenu && jbPopupHashSet.contains(menuElement.hashCode())
}
} ?: throw Exception("Unable to find a proper ActionMenu")
return actionMenu.text
}
}
//**********GLOBAL CONTEXT GENERATORS**********
class WelcomeFrameGenerator : GlobalContextCodeGenerator<FlatWelcomeFrame>() {
override fun priority(): Int = 1
override fun accept(cmp: Component): Boolean = cmp is JComponent && cmp.rootPane?.parent is FlatWelcomeFrame
override fun generate(cmp: FlatWelcomeFrame): String {
return "welcomeFrame {"
}
}
class JDialogGenerator : GlobalContextCodeGenerator<JDialog>() {
override fun accept(cmp: Component): Boolean {
if (cmp !is JComponent || cmp.rootPane == null || cmp.rootPane.parent == null || cmp.rootPane.parent !is JDialog) return false
val dialog = cmp.rootPane.parent as JDialog
if (dialog.title == "This should not be shown") return false //do not add context for a SheetMessages on Mac
return true
}
override fun generate(cmp: JDialog): String = """dialog("${cmp.title}") {"""
}
class IdeFrameGenerator : GlobalContextCodeGenerator<JFrame>() {
override fun accept(cmp: Component): Boolean {
if (cmp !is JComponent) return false
val parent = cmp.rootPane.parent
return (parent is JFrame) && parent.title != "GUI Script Editor"
}
override fun generate(cmp: JFrame): String = "ideFrame {"
}
class TabbedPaneGenerator : ComponentCodeGenerator<Component> {
override fun priority(): Int = 2
override fun generate(cmp: Component, me: MouseEvent, cp: Point): String {
val tabbedPane = when {
cmp.parent.parent is JBTabbedPane -> cmp.parent.parent as JTabbedPane
else -> cmp.parent as JTabbedPane
}
val selectedTabIndex = tabbedPane.indexAtLocation(me.locationOnScreen.x - tabbedPane.locationOnScreen.x,
me.locationOnScreen.y - tabbedPane.locationOnScreen.y)
val title = tabbedPane.getTitleAt(selectedTabIndex)
return """tab("${title}").selectTab()"""
}
override fun accept(cmp: Component): Boolean = cmp.parent.parent is JBTabbedPane || cmp.parent is JBTabbedPane
}
//**********LOCAL CONTEXT GENERATORS**********
class ProjectViewGenerator : LocalContextCodeGenerator<JPanel>() {
override fun priority(): Int = 0
override fun isLastContext(): Boolean = true
override fun acceptor(): (Component) -> Boolean = { component -> component.javaClass.name.endsWith("ProjectViewImpl\$MyPanel") }
override fun generate(cmp: JPanel): String = "projectView {"
}
class ToolWindowGenerator : LocalContextCodeGenerator<Component>() {
override fun priority(): Int = 0
private fun Component.containsLocationOnScreen(locationOnScreen: Point): Boolean {
val rectangle = this.bounds
rectangle.location = this.locationOnScreen
return rectangle.contains(locationOnScreen)
}
private fun Component.centerOnScreen(): Point? {
val rectangle = this.bounds
rectangle.location = try {
this.locationOnScreen
}
catch (e: IllegalComponentStateException) {
return null
}
return Point(rectangle.centerX.toInt(), rectangle.centerY.toInt())
}
private fun getToolWindow(pointOnScreen: Point): ToolWindowImpl? {
if (WindowManagerImpl.getInstance().findVisibleFrame() !is IdeFrameImpl) return null
val ideFrame = WindowManagerImpl.getInstance().findVisibleFrame() as IdeFrameImpl
ideFrame.project ?: return null
val toolWindowManager = ToolWindowManagerImpl.getInstance(ideFrame.project!!)
val visibleToolWindows = toolWindowManager.toolWindowIds
.map { toolWindowId -> toolWindowManager.getToolWindow(toolWindowId) }
.filter { toolwindow -> toolwindow.isVisible }
return visibleToolWindows.filterIsInstance<ToolWindowImpl>().find { it.component.containsLocationOnScreen(pointOnScreen) }
}
override fun acceptor(): (Component) -> Boolean = { component ->
val centerOnScreen = component.centerOnScreen()
if (centerOnScreen != null) {
val tw = getToolWindow(centerOnScreen)
tw != null && component == tw.component
}
else false
}
override fun generate(cmp: Component): String {
val pointOnScreen = cmp.centerOnScreen() ?: throw IllegalComponentStateException("Unable to get center on screen for component: $cmp")
val toolWindow: ToolWindowImpl = getToolWindow(pointOnScreen)!!
return """toolwindow(id = "${toolWindow.id}") {"""
}
}
class ToolWindowContextGenerator : LocalContextCodeGenerator<Component>() {
override fun priority(): Int = 2
private fun Component.containsLocationOnScreen(locationOnScreen: Point): Boolean {
val rectangle = this.bounds
rectangle.location = this.locationOnScreen
return rectangle.contains(locationOnScreen)
}
private fun Component.centerOnScreen(): Point? {
val rectangle = this.bounds
rectangle.location = try {
this.locationOnScreen
}
catch (e: IllegalComponentStateException) {
return null
}
return Point(rectangle.centerX.toInt(), rectangle.centerY.toInt())
}
private fun Component.contains(component: Component): Boolean {
return this.contains(Point(component.bounds.x, component.bounds.y)) &&
this.contains(Point(component.bounds.x + component.width, component.bounds.y + component.height))
}
private fun getToolWindow(pointOnScreen: Point): ToolWindowImpl? {
if (WindowManagerImpl.getInstance().findVisibleFrame() !is IdeFrameImpl) return null
val ideFrame = WindowManagerImpl.getInstance().findVisibleFrame() as IdeFrameImpl
ideFrame.project ?: return null
val toolWindowManager = ToolWindowManagerImpl.getInstance(ideFrame.project!!)
val visibleToolWindows = toolWindowManager.toolWindowIds
.map { toolWindowId -> toolWindowManager.getToolWindow(toolWindowId) }
.filter { toolwindow -> toolwindow.isVisible }
return visibleToolWindows.filterIsInstance<ToolWindowImpl>().find { it.component.containsLocationOnScreen(pointOnScreen) }
}
override fun acceptor(): (Component) -> Boolean = { component ->
val pointOnScreen = component.centerOnScreen()
if (pointOnScreen != null) {
val tw = getToolWindow(pointOnScreen)
tw != null && tw.contentManager.selectedContent!!.component == component
}
else false
}
override fun generate(cmp: Component): String {
val toolWindow: ToolWindowImpl = getToolWindow(cmp.centerOnScreen()!!)!!
val tabName = toolWindow.contentManager.selectedContent?.tabName
return if (tabName != null) """content(tabName = "${tabName}") {"""
else "content {"
}
}
class MacMessageGenerator : LocalContextCodeGenerator<JButton>() {
override fun priority(): Int = 2
private fun acceptMacSheetPanel(cmp: Component): Boolean {
if (cmp !is JComponent) return false
if (!(Messages.canShowMacSheetPanel() && cmp.rootPane.parent is JDialog)) return false
val panel = cmp.rootPane.contentPane as JPanel
if (panel.javaClass.name.startsWith(SheetController::class.java.name) && panel.isShowing) {
val controller = MessagesFixture.findSheetController(panel)
val sheetPanel = field("mySheetPanel").ofType(JPanel::class.java).`in`(controller).get()
if (sheetPanel === panel) {
return true
}
}
return false
}
override fun acceptor(): (Component) -> Boolean = { component -> acceptMacSheetPanel(component) }
override fun generate(cmp: JButton): String {
val panel = cmp.rootPane.contentPane as JPanel
val title = withRobot { robot -> MessagesFixture.getTitle(panel, robot) }
return """message("$title") {"""
}
}
class MessageGenerator : LocalContextCodeGenerator<JDialog>() {
override fun priority(): Int = 2
override fun acceptor(): (Component) -> Boolean = { cmp ->
cmp is JDialog && MessagesFixture.isMessageDialog(cmp)
}
override fun generate(cmp: JDialog): String {
return """message("${cmp.title}") {"""
}
}
class EditorGenerator : LocalContextCodeGenerator<EditorComponentImpl>() {
override fun priority(): Int = 3
override fun acceptor(): (Component) -> Boolean = { component -> component is EditorComponentImpl }
override fun generate(cmp: EditorComponentImpl): String = "editor {"
}
class MainToolbarGenerator : LocalContextCodeGenerator<ActionToolbarImpl>() {
override fun acceptor(): (Component) -> Boolean = { component ->
component is ActionToolbarImpl
&& MainToolbarFixture.isMainToolbar(component)
}
override fun generate(cmp: ActionToolbarImpl): String = "toolbar {"
}
class NavigationBarGenerator : LocalContextCodeGenerator<JPanel>() {
override fun acceptor(): (Component) -> Boolean = { component ->
component is JPanel
&& NavigationBarFixture.isNavBar(component)
}
override fun generate(cmp: JPanel): String = "navigationBar {"
}
class TabGenerator : LocalContextCodeGenerator<TabLabel>() {
override fun acceptor(): (Component) -> Boolean = { component ->
component is TabLabel
}
override fun generate(cmp: TabLabel): String = "editor(\"" + cmp.info.text + "\") {"
}
//class JBPopupMenuGenerator: LocalContextCodeGenerator<JBPopupMenu>() {
//
// override fun acceptor(): (Component) -> Boolean = { component -> component is JBPopupMenu}
// override fun generate(cmp: JBPopupMenu, me: MouseEvent, cp: Point) = "popupMenu {"
//}
object Generators {
fun getGenerators(): List<ComponentCodeGenerator<*>> {
val generatorClassPaths = getSiblingsList().filter { path -> path.endsWith("Generator.class") }
val classLoader = Generators.javaClass.classLoader
return generatorClassPaths
.map { clzPath -> classLoader.loadClass("${Generators.javaClass.`package`.name}.${File(clzPath).nameWithoutExtension}") }
.filter { clz -> ComponentCodeGenerator::class.java.isAssignableFrom(clz) && !clz.isInterface }
.map(Class<*>::newInstance)
.filterIsInstance(ComponentCodeGenerator::class.java)
}
fun getGlobalContextGenerators(): List<GlobalContextCodeGenerator<*>> {
val generatorClassPaths = getSiblingsList().filter { path -> path.endsWith("Generator.class") }
val classLoader = Generators.javaClass.classLoader
return generatorClassPaths
.map { clzPath -> classLoader.loadClass("${Generators.javaClass.`package`.name}.${File(clzPath).nameWithoutExtension}") }
.filter { clz -> clz.superclass == GlobalContextCodeGenerator::class.java }
.map(Class<*>::newInstance)
.filterIsInstance(GlobalContextCodeGenerator::class.java)
}
fun getLocalContextCodeGenerator(): List<LocalContextCodeGenerator<*>> {
val generatorClassPaths = getSiblingsList().filter { path -> path.endsWith("Generator.class") }
val classLoader = Generators.javaClass.classLoader
return generatorClassPaths
.map { clzPath -> classLoader.loadClass("${Generators.javaClass.`package`.name}.${File(clzPath).nameWithoutExtension}") }
.filter { clz -> clz.superclass == LocalContextCodeGenerator::class.java }
.map(Class<*>::newInstance)
.filterIsInstance(LocalContextCodeGenerator::class.java)
}
private fun getSiblingsList(): List<String> {
val path = "/${Generators.javaClass.`package`.name.replace(".", "/")}"
val url = Generators.javaClass.getResource(path)
if (url.path.contains(".jar!")) {
val jarFile = JarFile(Paths.get(URI(url.file.substringBefore(".jar!").plus(".jar"))).toString())
val entries = jarFile.entries()
val genPath = url.path.substringAfter(".jar!").removePrefix("/")
return entries.toList().filter { entry -> entry.name.contains(genPath) }.map { entry -> entry.name }
}
else return File(url.toURI()).listFiles().map { file -> file.toURI().path }
}
}
object Utils {
fun getLabel(container: Container, jTextField: JTextField): JLabel? {
return withRobot { robot -> GuiTestUtil.findBoundedLabel(container, jTextField, robot) }
}
fun getLabel(jTextField: JTextField): JLabel? {
val parentContainer = jTextField.rootPane.parent
return withRobot { robot -> GuiTestUtil.findBoundedLabel(parentContainer, jTextField, robot) }
}
fun clicks(me: MouseEvent): String {
if (me.clickCount == 1) return "click()"
if (me.clickCount == 2) return "doubleClick()"
return ""
}
fun getCellText(jList: JList<*>, pointOnList: Point): String? {
return withRobot { robot ->
val extCellReader = ExtendedJListCellReader()
val index = jList.locationToIndex(pointOnList)
extCellReader.valueAt(jList, index)
}
}
fun convertSimpleTreeItemToPath(tree: SimpleTree, itemName: String): String {
val searchableNodeRef = Ref.create<TreeNode>()
val searchableNode: TreeNode?
TreeUtil.traverse(tree.model.root as TreeNode) { node ->
val valueFromNode = SettingsTreeFixture.getValueFromNode(tree, node)
if (valueFromNode != null && valueFromNode == itemName) {
assert(node is TreeNode)
searchableNodeRef.set(node as TreeNode)
}
true
}
searchableNode = searchableNodeRef.get()
val path = TreeUtil.getPathFromRoot(searchableNode!!)
return (0 until path.pathCount).map { path.getPathComponent(it).toString() }.filter(String::isNotEmpty).joinToString("/")
}
fun getBoundedLabel(component: Component): JLabel {
return getBoundedLabelRecursive(component, component.parent)
}
private fun getBoundedLabelRecursive(component: Component, parent: Component): JLabel {
val boundedLabel = findBoundedLabel(component, parent)
if (boundedLabel != null) return boundedLabel
else {
if (parent.parent == null) throw ComponentLookupException("Unable to find bounded label")
return getBoundedLabelRecursive(component, parent.parent)
}
}
private fun findBoundedLabel(component: Component, componentParent: Component): JLabel? {
return withRobot { robot ->
var resultLabel: JLabel?
if (componentParent is LabeledComponent<*>) resultLabel = componentParent.label
else {
try {
resultLabel = robot.finder().find(componentParent as Container, object : GenericTypeMatcher<JLabel>(JLabel::class.java) {
override fun isMatching(label: JLabel) = (label.labelFor != null && label.labelFor == component)
})
}
catch (e: ComponentLookupException) {
resultLabel = null
}
}
resultLabel
}
}
fun findBoundedText(target: Component): String? {
//let's try to find bounded label firstly
try {
return getBoundedLabel(target).text
}
catch (_: ComponentLookupException) {
}
return findBoundedTextRecursive(target, target.parent)
}
private fun findBoundedTextRecursive(target: Component, parent: Component): String? {
val boundedText = findBoundedText(target, parent)
if (boundedText != null)
return boundedText
else
if (parent.parent != null) return findBoundedTextRecursive(target, parent.parent)
else return null
}
private fun findBoundedText(target: Component, container: Component): String? {
val textComponents = withRobot { robot ->
robot.finder().findAll(container as Container, ComponentMatcher { component ->
component!!.isShowing && component.isTextComponent() && target.onHeightCenter(component, true)
})
}
if (textComponents.isEmpty()) return null
//if more than one component is found let's take the righter one
return textComponents.sortedBy { it.bounds.x + it.bounds.width }.last().getComponentText()
}
fun getJTreePath(cmp: JTree, path: TreePath): String {
val pathArray = path.getPathStrings(cmp)
return pathArray.joinToString(separator = ", ", transform = { str -> "\"$str\"" })
}
fun getJTreePathItemsString(cmp: JTree, path: TreePath): String {
return path.getPathStrings(cmp)
.map { StringUtil.wrapWithDoubleQuote(it) }
.reduceRight { s, s1 -> "$s, $s1" }
}
fun <ReturnType> withRobot(robotFunction: (Robot) -> ReturnType): ReturnType {
val robot = BasicRobot.robotWithCurrentAwtHierarchyWithoutScreenLock()
return robotFunction(robot)
}
}
private fun String.addClick(me: MouseEvent): String {
return when {
me.isLeftButton() && me.clickCount == 2 -> "$this.doubleClick()"
me.isRightButton() -> "$this.rightClick()"
else -> "$this.click()"
}
}
private fun Component.hasInParents(componentType: Class<out Component>): Boolean {
var component = this
while (component.parent != null) {
if (componentType.isInstance(component)) return true
component = component.parent
}
return false
}
| apache-2.0 |
dbrant/unitconverter-android | app/src/main/java/com/defianttech/convertme/SingleUnit.kt | 1 | 268 | package com.defianttech.convertme
/*
* Copyright (c) 2014-2018 Dmitry Brant
*/
class SingleUnit(val id: Int, val name: String, val multiplier: Double, val offset: Double) {
var isEnabled = true
override fun toString(): String {
return name
}
}
| gpl-2.0 |
REBOOTERS/AndroidAnimationExercise | imitate/src/main/java/com/engineer/imitate/ui/widget/view/AnimRoundLayout.kt | 1 | 552 | package com.engineer.imitate.ui.widget.view
import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
/**
*
* @authro: Rookie
* @since: 2019-01-28
*/
class AnimRoundLayout : FrameLayout {
constructor(context: Context):super(context)
constructor(context: Context,attrs: AttributeSet):super(context,attrs)
constructor(context: Context,attrs: AttributeSet,style:Int):super(context,attrs,style)
public fun update(offset: Float) {
if (offset < 2) {
return
}
}
} | apache-2.0 |
bozaro/git-as-svn | src/main/kotlin/svnserver/VersionInfo.kt | 1 | 1807 | /*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver
import java.io.IOException
import java.util.*
/**
* Version information.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class VersionInfo private constructor() {
private var revision: String? = null
private var tag: String? = null
companion object {
private val s_instance: VersionInfo = VersionInfo()
val versionInfo: String
get() {
if (s_instance.revision == null) return "none version info"
if (s_instance.tag == null) return s_instance.revision!!
return s_instance.tag + ", " + s_instance.revision
}
private fun getProperty(props: Properties, name: String, defaultValue: String?): String {
val value: String? = props.getProperty(name)
return if (value != null && !value.startsWith("\${")) value else (defaultValue)!!
}
}
init {
try {
javaClass.getResourceAsStream("VersionInfo.properties").use { stream ->
if (stream == null) {
throw IllegalStateException()
}
val props = Properties()
props.load(stream)
revision = getProperty(props, "revision", null)
tag = getProperty(props, "tag", null)
}
} catch (e: IOException) {
throw IllegalStateException(e)
}
}
}
| gpl-2.0 |
arturbosch/TiNBo | tinbo-finance/src/main/kotlin/io/gitlab/arturbosch/tinbo/finance/FinanceCommands.kt | 1 | 6058 | package io.gitlab.arturbosch.tinbo.finance
import io.gitlab.arturbosch.tinbo.api.TinboTerminal
import io.gitlab.arturbosch.tinbo.api.commands.EditableCommands
import io.gitlab.arturbosch.tinbo.api.config.Defaults
import io.gitlab.arturbosch.tinbo.api.config.ModeManager
import io.gitlab.arturbosch.tinbo.api.marker.Summarizable
import io.gitlab.arturbosch.tinbo.api.nullIfEmpty
import io.gitlab.arturbosch.tinbo.api.orDefaultMonth
import io.gitlab.arturbosch.tinbo.api.orThrow
import io.gitlab.arturbosch.tinbo.api.orValue
import io.gitlab.arturbosch.tinbo.api.utils.dateFormatter
import io.gitlab.arturbosch.tinbo.api.utils.dateTimeFormatter
import org.joda.money.Money
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.shell.core.annotation.CliAvailabilityIndicator
import org.springframework.shell.core.annotation.CliCommand
import org.springframework.shell.core.annotation.CliOption
import org.springframework.stereotype.Component
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.Month
import java.time.format.DateTimeParseException
/**
* @author artur
*/
@Component
class FinanceCommands @Autowired constructor(private val financeExecutor: FinanceExecutor,
private val configProvider: ConfigProvider,
terminal: TinboTerminal) :
EditableCommands<FinanceEntry, FinanceData, DummyFinance>(financeExecutor, terminal), Summarizable {
override val id: String = FinanceMode.id
private val successMessage = "Successfully added a finance entry."
@CliAvailabilityIndicator("year", "mean", "deviation", "loadFinance")
fun isAvailable(): Boolean {
return ModeManager.isCurrentMode(FinanceMode)
}
@CliCommand("loadFinance", help = "Loads/Creates an other data set. Finance data sets are stored under ~/tinbo/finance/*.")
fun loadTasks(@CliOption(key = ["", "name"], mandatory = true,
specifiedDefaultValue = Defaults.FINANCE_NAME,
unspecifiedDefaultValue = Defaults.FINANCE_NAME) name: String) {
executor.loadData(name)
}
@CliCommand("year", "yearSummary", help = "Sums up the year by providing expenditure per month.")
fun yearSummary(@CliOption(key = ["last"], mandatory = false,
specifiedDefaultValue = "true", unspecifiedDefaultValue = "false") lastYear: Boolean,
@CliOption(key = [""], mandatory = false,
specifiedDefaultValue = "-1", unspecifiedDefaultValue = "-1") year: Int): String {
return withValidDate(year, lastYear) {
financeExecutor.yearSummary(it)
}
}
@CliCommand("mean", help = "Provides the mean expenditure per month for current or specified year.")
fun means(@CliOption(key = ["last"], mandatory = false,
specifiedDefaultValue = "true", unspecifiedDefaultValue = "false") lastYear: Boolean,
@CliOption(key = [""], mandatory = false,
specifiedDefaultValue = "-1", unspecifiedDefaultValue = "-1") year: Int): String {
return withValidDate(year, lastYear) {
financeExecutor.yearSummaryMean(it)
}
}
@CliCommand("deviation", help = "Provides the expenditure deviation per month for current or specified year.")
fun deviation(@CliOption(key = ["last"], mandatory = false,
specifiedDefaultValue = "true", unspecifiedDefaultValue = "false") lastYear: Boolean,
@CliOption(key = [""], mandatory = false,
specifiedDefaultValue = "-1", unspecifiedDefaultValue = "-1") year: Int): String {
return withValidDate(year, lastYear) {
financeExecutor.yearSummaryDeviation(it)
}
}
private fun withValidDate(year: Int, lastYear: Boolean, block: (LocalDate) -> String): String {
val now = LocalDate.now()
if (year != -1 && (year < 2000 || year > now.year + 20)) {
return "Entered date must be not too far in the past (> 2000) or in the future ( < now + 20)!"
}
val date = if (lastYear) now.minusYears(1) else if (year == -1) now else LocalDate.of(year, 1, 1)
return block.invoke(date)
}
override fun sum(categories: Set<String>, categoryFilters: Set<String>): String =
financeExecutor.sumCategories(categories, categoryFilters)
override fun add(): String {
return whileNotInEditMode {
val month = Month.of(console.readLine("Enter a month as number from 1-12 (empty if this month): ").orDefaultMonth())
val category = console.readLine("Enter a category: ").orValue(configProvider.categoryName)
val message = console.readLine("Enter a message: ")
val money = Money.of(configProvider.currencyUnit, console.readLine("Enter a money value: ").orThrow().toDouble())
val dateString = console.readLine("Enter a end time (yyyy-MM-dd HH:mm): ")
val dateTime = parseDateTime(dateString)
executor.addEntry(FinanceEntry(month, category, message, money, dateTime))
successMessage
}
}
private fun parseDateTime(dateString: String): LocalDateTime {
return if (dateString.isEmpty()) {
LocalDateTime.now()
} else {
try {
LocalDateTime.parse(dateString, dateTimeFormatter)
} catch (ex: DateTimeParseException) {
LocalDate.parse(dateString, dateFormatter).atTime(0, 0)
}
}
}
override fun edit(index: Int): String {
return withinListMode {
val i = index - 1
enterEditModeWithIndex(i) {
val monthString = console.readLine("Enter a month as number from 1-12 (empty if this month) (leave empty if unchanged): ")
val month = if (monthString.isEmpty()) null else Month.of(monthString.orDefaultMonth())
val category = console.readLine("Enter a category (leave empty if unchanged): ").nullIfEmpty()
val message = console.readLine("Enter a message (leave empty if unchanged): ").nullIfEmpty()
val moneyString = console.readLine("Enter a money value (leave empty if unchanged): ")
val money = if (moneyString.isEmpty()) null else Money.of(configProvider.currencyUnit, moneyString.toDouble())
val dateString = console.readLine("Enter a end time (yyyy-MM-dd HH:mm) (leave empty if unchanged): ")
val dateTime = parseDateTime(dateString)
executor.editEntry(i, DummyFinance(category, message, month, money, dateTime))
"Successfully edited a finance entry."
}
}
}
}
| apache-2.0 |
synyx/calenope | modules/organizer/src/main/kotlin/de/synyx/calenope/organizer/component/Layouts.kt | 1 | 6608 | package de.synyx.calenope.organizer.component
import android.support.design.widget.AppBarLayout
import android.support.design.widget.AppBarLayout.Behavior
import android.support.design.widget.CollapsingToolbarLayout
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.FloatingActionButton
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.Toolbar
import android.view.Gravity
import android.widget.LinearLayout
import de.synyx.calenope.organizer.R
import trikita.anvil.DSL.MATCH
import trikita.anvil.DSL.WRAP
import trikita.anvil.DSL.dip
import trikita.anvil.DSL.id
import trikita.anvil.DSL.layoutParams
import trikita.anvil.DSL.margin
import trikita.anvil.DSL.onClick
import trikita.anvil.DSL.onLongClick
import trikita.anvil.DSL.orientation
import trikita.anvil.DSL.size
import trikita.anvil.DSL.visibility
import trikita.anvil.appcompat.v7.AppCompatv7DSL.popupTheme
import trikita.anvil.appcompat.v7.AppCompatv7DSL.toolbar
import trikita.anvil.design.DesignDSL.appBarLayout
import trikita.anvil.design.DesignDSL.collapsingToolbarLayout
import trikita.anvil.design.DesignDSL.coordinatorLayout
import trikita.anvil.design.DesignDSL.expanded
import trikita.anvil.design.DesignDSL.floatingActionButton
import trikita.anvil.design.DesignDSL.title
import trikita.anvil.design.DesignDSL.titleEnabled
import trikita.anvil.support.v4.Supportv4DSL.onRefresh
import trikita.anvil.support.v4.Supportv4DSL.swipeRefreshLayout
/**
* @author clausen - [email protected]
*/
object Layouts {
private val scrolling by lazy {
val params = CoordinatorLayout.LayoutParams (MATCH, MATCH)
params.behavior = AppBarLayout.ScrollingViewBehavior ()
params
}
class Regular (
private val fab : Element<FloatingActionButton>.() -> Unit = {},
private val content : Element<SwipeRefreshLayout>.() -> Unit = {},
private val toolbar : Element<Toolbar>.() -> Unit = {}
) : Component () {
override fun view () = pin ("layout") {
Collapsible (
fab = fab,
content = content,
toolbar = toolbar,
collapsible = {
always += {
title ("")
titleEnabled (false)
}
}
)
}
}
class Collapsible (
private val draggable : Boolean = false,
private val fab : Element<FloatingActionButton>.() -> Unit = {},
private val content : Element<SwipeRefreshLayout>.() -> Unit = {},
private val appbar : Element<AppBarLayout>.() -> Unit = {},
private val toolbar : Element<Toolbar>.() -> Unit = {},
private val collapsible : Element<CollapsingToolbarLayout>.() -> Unit = {}
) : Component () {
override fun view () {
coordinatorLayout {
size (MATCH, MATCH)
orientation (LinearLayout.VERTICAL)
appBarLayout {
configure<AppBarLayout> {
once += {
val behavior = Behavior ()
behavior.setDragCallback (drag (draggable))
val params = layoutParams as CoordinatorLayout.LayoutParams
params.behavior = behavior
}
always += {
size (MATCH, WRAP)
expanded (false)
}
appbar (this)
}
collapsingToolbarLayout {
configure<CollapsingToolbarLayout> {
once += {
val params = layoutParams as AppBarLayout.LayoutParams
params.scrollFlags = params.scrollFlags or AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED
}
always += {
size (MATCH, MATCH)
titleEnabled (true)
}
collapsible (this)
}
toolbar {
configure<Toolbar> {
once += {
val params = layoutParams as CollapsingToolbarLayout.LayoutParams
params.collapseMode = CollapsingToolbarLayout.LayoutParams.COLLAPSE_MODE_PIN
elevation = -1.0f
}
always += {
size (MATCH, dip (56))
popupTheme (R.style.AppTheme_PopupOverlay)
}
toolbar (this)
}
}
}
}
swipeRefreshLayout {
configure<SwipeRefreshLayout> {
always += {
id ("content".viewID ())
layoutParams (scrolling)
size (MATCH, MATCH)
onRefresh {}
}
content (this)
}
}
floatingActionButton {
configure<FloatingActionButton> {
once += {
val params = layoutParams as CoordinatorLayout.LayoutParams
params.anchorId = "content".viewID ()
params.anchorGravity = Gravity.BOTTOM or Gravity.END
}
always += {
visibility (false)
size (WRAP, WRAP)
margin (dip (16))
onClick {}
onLongClick { false }
}
fab (this)
}
}
}
}
}
private fun drag (draggable : Boolean) : Behavior.DragCallback {
return object : Behavior.DragCallback () {
override fun canDrag (layout : AppBarLayout) : Boolean = draggable
}
}
} | apache-2.0 |
MimiReader/mimi-reader | mimi-app/src/main/java/com/emogoth/android/phone/mimi/event/ShowRepliesEvent.kt | 1 | 196 | package com.emogoth.android.phone.mimi.event
data class ShowRepliesEvent(
val boardName: String,
var threadId: Long,
var id: Long = -1,
var replies: List<String> = emptyList()
)
| apache-2.0 |
Karumi/Shot | shot-consumer-compose/app/src/androidTest/java/com/karumi/shotconsumercompose/RoundedCornersBoxScreenshotTest.kt | 1 | 730 | package com.karumi.shotconsumercompose
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onRoot
import com.karumi.shot.ScreenshotTest
import com.karumi.shotconsumercompose.ui.ShotConsumerComposeTheme
import org.junit.Rule
import org.junit.Test
class RoundedCornersBoxScreenshotTest : ScreenshotTest {
@get:Rule
val composeRule = createComposeRule()
@Test
fun rendersTheDefaultComponent() {
renderComponent()
compareScreenshot(composeRule.onRoot())
}
private fun renderComponent(greeting: String? = null) {
composeRule.setContent {
ShotConsumerComposeTheme {
RoundedCornersBox()
}
}
}
} | apache-2.0 |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/bitmapfont/BitmapFontExt.kt | 1 | 2934 | package com.soywiz.korge.bitmapfont
import com.soywiz.korge.html.*
import com.soywiz.korge.internal.*
import com.soywiz.korge.render.*
import com.soywiz.korge.view.*
import com.soywiz.korim.color.*
import com.soywiz.korim.font.*
import com.soywiz.korma.geom.*
import kotlin.math.*
fun Font.getBounds(text: String, format: Html.Format, out: Rectangle = Rectangle()): Rectangle {
//val font = getBitmapFont(format.computedFace, format.computedSize)
val font = this
val textSize = format.computedSize.toDouble()
var width = 0.0
var height = 0.0
var dy = 0.0
var dx = 0.0
val glyph = GlyphMetrics()
val fmetrics = font.getFontMetrics(textSize)
for (n in 0 until text.length) {
val c1 = text[n].toInt()
if (c1 == '\n'.toInt()) {
dx = 0.0
dy += fmetrics.lineHeight
height = max(height, dy)
continue
}
var c2: Int = ' '.toInt()
if (n + 1 < text.length) c2 = text[n + 1].toInt()
val kerningOffset = font.getKerning(textSize, c1, c2)
val glyph = font.getGlyphMetrics(textSize, c1, glyph)
dx += glyph.xadvance + kerningOffset
width = max(width, dx)
}
height += fmetrics.lineHeight
//val scale = textSize / font.fontSize.toDouble()
//out.setTo(0.0, 0.0, width * scale, height * scale)
out.setTo(0.0, 0.0, width, height)
return out
}
fun BitmapFont.drawText(
ctx: RenderContext,
textSize: Double,
str: String,
x: Int,
y: Int,
m: Matrix = Matrix(),
colMul: RGBA = Colors.WHITE,
colAdd: ColorAdd = ColorAdd.NEUTRAL,
blendMode: BlendMode = BlendMode.INHERIT,
filtering: Boolean = true
) {
val m2 = m.clone()
val scale = textSize / fontSize.toDouble()
m2.pretranslate(x.toDouble(), y.toDouble())
m2.prescale(scale, scale)
var dx = 0.0
var dy = 0.0
ctx.useBatcher { batch ->
for (n in str.indices) {
val c1 = str[n].toInt()
if (c1 == '\n'.toInt()) {
dx = 0.0
dy += fontSize
continue
}
val c2 = str.getOrElse(n + 1) { ' ' }.toInt()
val glyph = this[c1]
val tex = glyph.texture
batch.drawQuad(
ctx.getTex(tex),
(dx + glyph.xoffset).toFloat(),
(dy + glyph.yoffset).toFloat(),
m = m2,
colorMul = colMul,
colorAdd = colAdd,
blendFactors = blendMode.factors,
filtering = filtering
)
val kerningOffset = kernings[BitmapFont.Kerning.buildKey(c1, c2)]?.amount ?: 0
dx += glyph.xadvance + kerningOffset
}
}
}
fun RenderContext.drawText(
font: BitmapFont,
textSize: Double,
str: String,
x: Int,
y: Int,
m: Matrix = Matrix(),
colMul: RGBA = Colors.WHITE,
colAdd: ColorAdd = ColorAdd.NEUTRAL,
blendMode: BlendMode = BlendMode.INHERIT,
filtering: Boolean = true
) {
font.drawText(this, textSize, str, x, y, m, colMul, colAdd, blendMode, filtering)
}
| apache-2.0 |
StoneMain/Shortranks | ShortranksBukkit/src/main/kotlin/eu/mikroskeem/shortranks/bukkit/hooks/LibsDisguisesHook.kt | 1 | 6385 | /*
* This file is part of project Shortranks, licensed under the MIT License (MIT).
*
* Copyright (c) 2017-2019 Mark Vainomaa <[email protected]>
* Copyright (c) Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package eu.mikroskeem.shortranks.bukkit.hooks
import eu.mikroskeem.shortranks.api.ScoreboardHook
import eu.mikroskeem.shortranks.api.ScoreboardTeam
import eu.mikroskeem.shortranks.api.ScoreboardTeamProcessor
import eu.mikroskeem.shortranks.bukkit.Shortranks
import eu.mikroskeem.shortranks.bukkit.common.asPlayer
import eu.mikroskeem.shortranks.bukkit.common.sbStrip
import eu.mikroskeem.shortranks.common.debug
import eu.mikroskeem.shortranks.common.warning
import me.libraryaddict.disguise.DisguiseAPI
import me.libraryaddict.disguise.LibsDisguises
import me.libraryaddict.disguise.events.DisguiseEvent
import me.libraryaddict.disguise.events.UndisguiseEvent
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import java.util.WeakHashMap
/**
* LibsDisguises plugin hook
*
* @author Mark Vainomaa
*/
class LibsDisguisesHook(private val plugin: Shortranks): ScoreboardHook, ScoreboardTeamProcessor, Listener {
private val disguisedPlayers = WeakHashMap<Player, Boolean>()
override fun hook() {
plugin.server.pluginManager.registerEvents(this, plugin)
checkLibsDisguisesSettings {
warning("** LibsDisguises's 'SelfDisguisesScoreboard' was not 'IGNORE_SCOREBOARD'!")
warning("Changing it to 'IGNORE_SCOREBOARD' to avoid Shortranks breakage, as " +
"Shortranks has proper workaround for LibsDisguises")
warning("Don't forget to change that setting by hand in plugin configuration, as " +
"altering configuration file by Shortranks gets rid of comments and LibsDisguises reload " +
"causes modified setting to reset.")
}
}
override fun unhook() {
DisguiseEvent.getHandlerList().unregister(this)
UndisguiseEvent.getHandlerList().unregister(this)
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
fun on(event: DisguiseEvent) {
checkLibsDisguisesSettings {}
if(event.entity is Player && !event.entity.hasMetadata("NPC")) {
val player = event.entity as Player
val team = plugin.scoreboardManager.getTeam(player.uniqueId)
if(DisguiseAPI.isDisguised(player)) {
// UndisguiseEvent is not fired when player tries to disguise itself if already disguised.
// So clean up old entity id
DisguiseAPI.getDisguise(player)!!.run {
debug("Cleaning up old disguise ${entity.entityId} from team $team")
team.removeMember("${entity.entityId}")
}
}
// Mark player disguised
disguisedPlayers.compute(player) { _, _ -> true }
// Add disguised entity's id to team
val disguiseId = event.disguise.entity.entityId
debug("Adding disguised entity id $disguiseId to team $team, as player disguised")
team.addMember("$disguiseId")
plugin.sbManager.updateTeam(team)
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
fun on(event: UndisguiseEvent) {
checkLibsDisguisesSettings {}
if(event.entity is Player && !event.entity.hasMetadata("NPC")) {
val player = event.entity as Player
if(!player.isOnline) return // Can be fired after player disconnects
val team = plugin.scoreboardManager.getTeam(player.uniqueId)
// Mark player undisguised
disguisedPlayers.compute(player) { _, _ -> false }
// Remove disguised entity's id from team
val disguiseId = event.disguise.entity.entityId
debug("Removing disguised entity id $disguiseId from team $team, as player undisguised")
team.removeMember("$disguiseId")
plugin.sbManager.updateTeam(team)
}
}
// Does not actually process teams, listens for changes instead
override fun accept(team: ScoreboardTeam) {
val player = team.teamOwnerPlayer.asPlayer
disguisedPlayers.computeIfPresent(player) compute@ { _, value ->
player.setPlayerListName(if(value) formatPlayerListName(team, player) else null)
return@compute value
}
}
override fun getName(): String = "LibsDisguises hook"
override fun getDescription(): String = "Built in LibsDisguises hook"
override fun getAuthors(): List<String> = listOf("mikroskeem")
override fun getScoreboardTeamProcessors()= listOf(this)
override fun getProcessorPriority(): Int = 1000
private inline fun checkLibsDisguisesSettings(callback: () -> Unit) {
LibsDisguises.getInstance().run {
if(config.get("SelfDisguisesScoreboard", "MODIFY_SCOREBOARD") != "IGNORE_SCOREBOARD") {
config.set("SelfDisguisesScoreboard", "IGNORE_SCOREBOARD")
callback()
}
}
}
private fun formatPlayerListName(team: ScoreboardTeam, player: Player) = (team.prefix + player.name + team.suffix).sbStrip()
} | mit |
cashapp/sqldelight | dialects/mysql/src/main/kotlin/app/cash/sqldelight/dialects/mysql/grammar/mixins/AlterTableAddColumnMixin.kt | 1 | 934 | package app.cash.sqldelight.dialects.mysql.grammar.mixins
import app.cash.sqldelight.dialects.mysql.grammar.psi.MySqlAlterTableAddColumn
import com.alecstrong.sql.psi.core.psi.AlterTableApplier
import com.alecstrong.sql.psi.core.psi.LazyQuery
import com.alecstrong.sql.psi.core.psi.QueryElement
import com.alecstrong.sql.psi.core.psi.impl.SqlAlterTableAddColumnImpl
import com.intellij.lang.ASTNode
internal abstract class AlterTableAddColumnMixin(
node: ASTNode,
) : SqlAlterTableAddColumnImpl(node),
MySqlAlterTableAddColumn,
AlterTableApplier {
override fun applyTo(lazyQuery: LazyQuery): LazyQuery {
return LazyQuery(
tableName = lazyQuery.tableName,
query = {
val columns = placementClause.placeInQuery(
columns = lazyQuery.query.columns,
column = QueryElement.QueryColumn(columnDef.columnName),
)
lazyQuery.query.copy(columns = columns)
},
)
}
}
| apache-2.0 |
karollewandowski/aem-intellij-plugin | src/test/kotlin/co/nums/intellij/aem/htl/completion/HtlBlocksCompletionTest.kt | 1 | 861 | package co.nums.intellij.aem.htl.completion
import co.nums.intellij.aem.htl.definitions.HtlBlock
class HtlBlocksCompletionTest : HtlCompletionTestBase() {
private val allBlocks = HtlBlock.values().map { it.type }.toTypedArray()
fun testAllHtlBlocksWhenDataTyped() = checkContainsAll(
"""<div data<caret>""",
*allBlocks)
fun testAllHtlBlocksWhenSlyTyped() = checkContainsAll(
"""<div sly<caret>""",
*allBlocks)
fun testHtlBlocksFilteredByNamePart() = checkContainsAll(
"""<div te<caret>""",
"data-sly-template", "data-sly-test", "data-sly-text", "data-sly-attribute")
fun testShouldNotCompleteAlreadyTypedBlocks() = checkContainsAll(
"""<div data-sly-text="any" te<caret>""",
"data-sly-template", "data-sly-test", "data-sly-attribute")
}
| gpl-3.0 |
curtcox/FarTap | flutter/far_tap/android/app/src/main/kotlin/com/curtcox/fartap/MainActivity.kt | 1 | 336 | package com.curtcox.fartap
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
class MainActivity(): FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
}
}
| gpl-3.0 |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/dataclient/mwapi/UserContribution.kt | 1 | 999 | package org.wikipedia.dataclient.mwapi
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import org.wikipedia.util.DateUtil
import java.text.ParseException
import java.util.*
@Serializable
class UserContribution {
val userid: Int = 0
val user: String = ""
val pageid: Int = 0
val revid: Long = 0
val parentid: Long = 0
val ns: Int = 0
val title: String = ""
private val timestamp: String = ""
@Transient private var parsedDate: Date? = null
val comment: String = ""
val new: Boolean = false
val minor: Boolean = false
val top: Boolean = false
val size: Int = 0
val sizediff: Int = 0
val tags: List<String> = Collections.emptyList()
fun date(): Date {
if (parsedDate == null) {
try {
parsedDate = DateUtil.iso8601DateParse(timestamp)
} catch (e: ParseException) {
// ignore
}
}
return parsedDate!!
}
}
| apache-2.0 |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/AddStatusFilterDialogFragment.kt | 1 | 9705 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.fragment
import android.app.Dialog
import android.content.ContentValues
import android.os.Bundle
import android.support.v4.app.FragmentManager
import android.support.v7.app.AlertDialog
import com.twitter.Extractor
import org.mariotaku.kpreferences.get
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_STATUS
import de.vanita5.twittnuker.constant.nameFirstKey
import de.vanita5.twittnuker.extension.applyTheme
import de.vanita5.twittnuker.extension.onShow
import de.vanita5.twittnuker.model.ParcelableStatus
import de.vanita5.twittnuker.model.ParcelableUserMention
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.provider.TwidereDataStore.Filters
import de.vanita5.twittnuker.util.ContentValuesCreator
import de.vanita5.twittnuker.util.HtmlEscapeHelper
import de.vanita5.twittnuker.util.ParseUtils
import de.vanita5.twittnuker.util.UserColorNameManager
import de.vanita5.twittnuker.util.content.ContentResolverUtils
import java.util.*
class AddStatusFilterDialogFragment : BaseDialogFragment() {
private val extractor = Extractor()
private var filterItems: Array<FilterItemInfo>? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(context)
filterItems = filterItemsInfo
val entries = arrayOfNulls<String>(filterItems!!.size)
val nameFirst = preferences[nameFirstKey]
for (i in 0 until entries.size) {
val info = filterItems!![i]
when (info.type) {
FilterItemInfo.FILTER_TYPE_USER -> {
entries[i] = getString(R.string.user_filter_name, getName(userColorNameManager,
info.value, nameFirst))
}
FilterItemInfo.FILTER_TYPE_KEYWORD -> {
entries[i] = getString(R.string.keyword_filter_name, getName(userColorNameManager,
info.value, nameFirst))
}
FilterItemInfo.FILTER_TYPE_SOURCE -> {
entries[i] = getString(R.string.source_filter_name, getName(userColorNameManager,
info.value, nameFirst))
}
}
}
builder.setTitle(R.string.action_add_to_filter)
builder.setMultiChoiceItems(entries, null, null)
builder.setPositiveButton(android.R.string.ok) { dialog, _ ->
val alertDialog = dialog as AlertDialog
val checkPositions = alertDialog.listView.checkedItemPositions
val userKeys = HashSet<UserKey>()
val keywords = HashSet<String>()
val sources = HashSet<String>()
val userValues = ArrayList<ContentValues>()
val keywordValues = ArrayList<ContentValues>()
val sourceValues = ArrayList<ContentValues>()
loop@ for (i in 0 until checkPositions.size()) {
if (!checkPositions.valueAt(i)) {
continue@loop
}
val info = filterItems!![checkPositions.keyAt(i)]
val value = info.value
if (value is ParcelableUserMention) {
userKeys.add(value.key)
userValues.add(ContentValuesCreator.createFilteredUser(value))
} else if (value is UserItem) {
userKeys.add(value.key)
userValues.add(createFilteredUser(value))
} else if (info.type == FilterItemInfo.FILTER_TYPE_KEYWORD) {
val keyword = ParseUtils.parseString(value)
keywords.add(keyword)
val values = ContentValues()
values.put(Filters.Keywords.VALUE, "#$keyword")
keywordValues.add(values)
} else if (info.type == FilterItemInfo.FILTER_TYPE_SOURCE) {
val source = ParseUtils.parseString(value)
sources.add(source)
val values = ContentValues()
values.put(Filters.Sources.VALUE, source)
sourceValues.add(values)
}
}
val resolver = context.contentResolver
ContentResolverUtils.bulkDelete(resolver, Filters.Users.CONTENT_URI,
Filters.Users.USER_KEY, false, userKeys, null, null)
ContentResolverUtils.bulkDelete(resolver, Filters.Keywords.CONTENT_URI,
Filters.Keywords.VALUE, false, keywords, null, null)
ContentResolverUtils.bulkDelete(resolver, Filters.Sources.CONTENT_URI,
Filters.Sources.VALUE, false, sources, null, null)
ContentResolverUtils.bulkInsert(resolver, Filters.Users.CONTENT_URI, userValues)
ContentResolverUtils.bulkInsert(resolver, Filters.Keywords.CONTENT_URI, keywordValues)
ContentResolverUtils.bulkInsert(resolver, Filters.Sources.CONTENT_URI, sourceValues)
}
builder.setNegativeButton(android.R.string.cancel, null)
val dialog = builder.create()
dialog.onShow { it.applyTheme() }
return dialog
}
private val filterItemsInfo: Array<FilterItemInfo>
get() {
val args = arguments
if (args == null || !args.containsKey(EXTRA_STATUS)) return emptyArray()
val status = args.getParcelable<ParcelableStatus>(EXTRA_STATUS) ?: return emptyArray()
val list = ArrayList<FilterItemInfo>()
if (status.is_retweet && status.retweeted_by_user_key != null) {
list.add(FilterItemInfo(FilterItemInfo.FILTER_TYPE_USER,
UserItem(status.retweeted_by_user_key!!, status.retweeted_by_user_name,
status.retweeted_by_user_screen_name)))
}
if (status.is_quote && status.quoted_user_key != null) {
list.add(FilterItemInfo(FilterItemInfo.FILTER_TYPE_USER,
UserItem(status.quoted_user_key!!, status.quoted_user_name,
status.quoted_user_screen_name)))
}
list.add(FilterItemInfo(FilterItemInfo.FILTER_TYPE_USER, UserItem(status.user_key,
status.user_name, status.user_screen_name)))
val mentions = status.mentions
if (mentions != null) {
for (mention in mentions) {
if (mention.key != status.user_key) {
list.add(FilterItemInfo(FilterItemInfo.FILTER_TYPE_USER, mention))
}
}
}
val hashtags = HashSet<String>()
hashtags.addAll(extractor.extractHashtags(status.text_plain))
for (hashtag in hashtags) {
list.add(FilterItemInfo(FilterItemInfo.FILTER_TYPE_KEYWORD, hashtag))
}
val source = status.source?.let(HtmlEscapeHelper::toPlainText)
if (source != null) {
list.add(FilterItemInfo(FilterItemInfo.FILTER_TYPE_SOURCE, source))
}
return list.toTypedArray()
}
private fun getName(manager: UserColorNameManager, value: Any, nameFirst: Boolean): String {
if (value is ParcelableUserMention) {
return manager.getDisplayName(value.key, value.name, value.screen_name, nameFirst)
} else if (value is UserItem) {
return manager.getDisplayName(value.key, value.name, value.screen_name, nameFirst)
} else
return ParseUtils.parseString(value)
}
internal data class FilterItemInfo(
val type: Int,
val value: Any
) {
companion object {
internal const val FILTER_TYPE_USER = 1
internal const val FILTER_TYPE_KEYWORD = 2
internal const val FILTER_TYPE_SOURCE = 3
}
}
internal data class UserItem(
val key: UserKey,
val name: String,
val screen_name: String
)
companion object {
val FRAGMENT_TAG = "add_status_filter"
private fun createFilteredUser(item: UserItem): ContentValues {
val values = ContentValues()
values.put(Filters.Users.USER_KEY, item.key.toString())
values.put(Filters.Users.NAME, item.name)
values.put(Filters.Users.SCREEN_NAME, item.screen_name)
return values
}
fun show(fm: FragmentManager, status: ParcelableStatus): AddStatusFilterDialogFragment {
val args = Bundle()
args.putParcelable(EXTRA_STATUS, status)
val f = AddStatusFilterDialogFragment()
f.arguments = args
f.show(fm, FRAGMENT_TAG)
return f
}
}
} | gpl-3.0 |
BilledTrain380/sporttag-psa | app/shared/src/main/kotlin/ch/schulealtendorf/psa/shared/rulebook/SkippingRuleSet.kt | 1 | 2677 | /*
* Copyright (c) 2019 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA 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.
*
* Sporttag PSA 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 Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.shared.rulebook
import ch.schulealtendorf.psa.dto.participation.GenderDto
import ch.schulealtendorf.psa.dto.participation.athletics.SEILSPRINGEN
import ch.schulealtendorf.psa.shared.rulebook.rules.RuleSet
/**
* Defines all the rules that can be applied to a skipping.
*
* @author nmaerchy
* @version 1.0.0
*/
class SkippingRuleSet : RuleSet<FormulaModel, Int>() {
/**
* @return true if the rules of this rule set can be used, otherwise false
*/
override val whenever: (FormulaModel) -> Boolean = { it.discipline == SEILSPRINGEN }
init {
addRule(
object : FormulaRule() {
override val formula: (Double) -> Int = { (1 * ((it - 0) pow 1.245)).toInt() }
override val whenever: (FormulaModel) -> Boolean = { it.gender == GenderDto.FEMALE }
}
)
addRule(
object : FormulaRule() {
override val formula: (Double) -> Int = { (1.4 * ((it - 0) pow 1.18)).toInt() }
override val whenever: (FormulaModel) -> Boolean = { it.gender == GenderDto.MALE }
}
)
}
}
| gpl-3.0 |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/task/AbsAccountRequestTask.kt | 1 | 4082 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.task
import android.accounts.AccountManager
import android.content.Context
import android.widget.Toast
import org.mariotaku.ktextension.toLongOr
import de.vanita5.microblog.library.MicroBlogException
import de.vanita5.twittnuker.exception.AccountNotFoundException
import de.vanita5.twittnuker.extension.getErrorMessage
import de.vanita5.twittnuker.extension.insert
import de.vanita5.twittnuker.model.AccountDetails
import de.vanita5.twittnuker.model.Draft
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.util.AccountUtils
import de.vanita5.twittnuker.provider.TwidereDataStore.Drafts
import de.vanita5.twittnuker.task.twitter.UpdateStatusTask
abstract class AbsAccountRequestTask<Params, Result, Callback>(context: Context, val accountKey: UserKey?) :
ExceptionHandlingAbstractTask<Params, Result, MicroBlogException, Callback>(context) {
override final val exceptionClass = MicroBlogException::class.java
override final fun onExecute(params: Params): Result {
val am = AccountManager.get(context)
val account = accountKey?.let { AccountUtils.getAccountDetails(am, it, true) } ?:
throw AccountNotFoundException()
val draft = createDraft()
var draftId = -1L
if (draft != null) {
val uri = context.contentResolver.insert(Drafts.CONTENT_URI, draft)
draftId = uri?.lastPathSegment.toLongOr(-1)
}
if (draftId != -1L) {
microBlogWrapper.addSendingDraftId(draftId)
}
try {
val result = onExecute(account, params)
onCleanup(account, params, result, null)
if (draftId != -1L) {
UpdateStatusTask.deleteDraft(context, draftId)
}
return result
} catch (e: MicroBlogException) {
onCleanup(account, params, null, e)
if (draftId != 1L && deleteDraftOnException(account, params, e)) {
UpdateStatusTask.deleteDraft(context, draftId)
}
throw e
} finally {
if (draftId != -1L) {
microBlogWrapper.removeSendingDraftId(draftId)
}
}
}
protected abstract fun onExecute(account: AccountDetails, params: Params): Result
protected open fun onCleanup(account: AccountDetails, params: Params, result: Result?, exception: MicroBlogException?) {
if (result != null) {
onCleanup(account, params, result)
} else if (exception != null) {
onCleanup(account, params, exception)
}
}
protected open fun onCleanup(account: AccountDetails, params: Params, result: Result) {}
protected open fun onCleanup(account: AccountDetails, params: Params, exception: MicroBlogException) {}
protected open fun createDraft(): Draft? = null
protected open fun deleteDraftOnException(account: AccountDetails, params: Params, exception: MicroBlogException): Boolean = false
override fun onException(callback: Callback?, exception: MicroBlogException) {
Toast.makeText(context, exception.getErrorMessage(context), Toast.LENGTH_SHORT).show()
}
} | gpl-3.0 |
slartus/4pdaClient-plus | qms/qms-api/src/main/java/ru/softeg/slartus/qms/api/repositories/QmsThreadsRepository.kt | 1 | 466 | package ru.softeg.slartus.qms.api.repositories
import kotlinx.coroutines.flow.Flow
import ru.softeg.slartus.qms.api.models.QmsThread
interface QmsThreadsRepository {
val threads: Flow<List<QmsThread>?>
suspend fun load(contactId: String)
suspend fun delete(contactId: String, threadIds: List<String>)
suspend fun createNewThread(
contactId: String,
userNick: String,
subject: String,
message: String
): String?
} | apache-2.0 |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/PlatformConstraint.kt | 1 | 545 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Constraints put in place by a social media platform on uploading videos.
*
* @param duration The max length in seconds of a video for the corresponding platform.
* @param size The max file size in gigabytes of a video for the corresponding platform.
*/
@JsonClass(generateAdapter = true)
data class PlatformConstraint(
@Json(name = "duration")
val duration: Int? = null,
@Json(name = "size")
val size: Long? = null
)
| mit |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/settings/language/command/MythicGiveTomeMessages.kt | 1 | 2238 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.tealcube.minecraft.bukkit.mythicdrops.settings.language.command
import com.squareup.moshi.JsonClass
import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.language.command.GiveTomeMessages
import com.tealcube.minecraft.bukkit.mythicdrops.getNonNullString
import org.bukkit.configuration.ConfigurationSection
@JsonClass(generateAdapter = true)
data class MythicGiveTomeMessages internal constructor(
override val receiverSuccess: String = "",
override val receiverFailure: String = "",
override val senderSuccess: String = "",
override val senderFailure: String = ""
) : GiveTomeMessages {
companion object {
fun fromConfigurationSection(configurationSection: ConfigurationSection) = MythicGiveTomeMessages(
configurationSection.getNonNullString("receiver-success"),
configurationSection.getNonNullString("receiver-failure"),
configurationSection.getNonNullString("sender-success"),
configurationSection.getNonNullString("sender-failure")
)
}
}
| mit |
visiolink-android-dev/visiolink-app-plugin | src/main/kotlin/com/visiolink/app/VisiolinkAppPlugin.kt | 1 | 5197 | package com.visiolink.app
import com.android.build.gradle.AppExtension
import com.android.build.gradle.api.ApkVariantOutput
import com.android.build.gradle.api.ApplicationVariant
import com.visiolink.app.task.*
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.Plugin
import org.gradle.api.internal.plugins.DefaultExtraPropertiesExtension
import java.io.FileInputStream
import java.util.*
open class VisiolinkAppPlugin : Plugin<Project> {
override fun apply(project: Project) {
with(project.tasks) {
val verifyVersionControl = create("verifyVersionControl", VerifyVersionControlTask::class.java)
val verifyBuildServer = create("verifyBuildServer", VerifyBuildServerTask::class.java)
val verifyNoStageUrl = create("verifyNoStageUrl", VerifyNoStageUrlTask::class.java)
val verifiers = listOf(verifyVersionControl, verifyBuildServer, verifyNoStageUrl)
val generateProjectChangeLog = create("generateProjectChangeLog", GenerateProjectChangeLogTask::class.java).setMustRunAfter(verifiers)
create("generateGenericChangeLog", GenerateGenericChangeLogTask::class.java).setMustRunAfter(verifiers)
create("increaseMajorVersionName", IncreaseMajorVersionNameTask::class.java)
create("increaseMinorVersionName", IncreaseMinorVersionNameTask::class.java)
create("increaseBuildVersionName", IncreaseBuildVersionNameTask::class.java)
create("getFlavors", GetFlavorsTask::class.java)
create("addAdtechModule", AddAdtechModuleTask::class.java)
create("addAndroidTvModule", AddAndroidTvModuleTask::class.java)
create("addCxenseModule", AddCxenseModuleTask::class.java)
create("addDfpModule", AddDfpModuleTask::class.java)
create("addInfosoftModule", AddInfosoftModuleTask::class.java)
create("addKindleModule", AddKindleModuleTask::class.java)
create("addSpidModule", AddSpidModuleTask::class.java)
create("addTnsDkModule", AddTnsGallupDkModuleTask::class.java)
create("addTnsNoModule", AddTnsGallupNoModuleTask::class.java)
create("addComScoreModule", AddComScoreModuleTask::class.java)
create("tagProject", TagProjectTask::class.java).setMustRunAfter(verifiers + generateProjectChangeLog)
whenTaskAdded { task ->
if (task.name.startsWith("generate")
&& task.name.endsWith("ReleaseBuildConfig")
&& !project.hasProperty("ignoreChecks")) {
//println("Task name: ${task.name}")
task.dependsOn("tagProject")
task.dependsOn("generateProjectChangeLog")
task.dependsOn("verifyBuildServer")
task.dependsOn("verifyVersionControl")
task.dependsOn("verifyNoStageUrl")
}
if (task.name == "preDevReleaseBuild") {
//println("Task name: ${task.name}")
task.dependsOn("generateGenericChangeLog")
}
}
}
//Set output file name for release builds
val android = project.extensions.getByName("android") as AppExtension
android.applicationVariants.all { variant ->
if (variant.buildType.name == "release") {
//If apkPath has been defined in ~/.gradle/gradle.properties or local.properties
if (project.hasProperty("apkPath")) {
//TODO:
//releaseDir = apkPath + "/" + rootProject.name
}
variant.outputs.filterIsInstance(ApkVariantOutput::class.java).forEach {
it.outputFileName = with(variant) { "${flavorName}_${versionNameNoDots}_$versionCode.apk" }
}
}
}
val ext = project.extensions.getByName("ext") as DefaultExtraPropertiesExtension
//Equivalent to project.ext.getVersionCodeTimestamp = { -> }
ext.set("getVersionCodeTimestamp", closure {
if (project.hasProperty("devBuild")) {
1
} else {
dateFormat("yyMMddHHmm").format(Date()).toInt()
}
})
//Equivalent to project.ext.getVersionNameFromFile = { -> }
ext.set("getVersionNameFromFile", closure {
val versionPropsFile = project.file("version.properties")
if (versionPropsFile.canRead()) {
val versionProps = Properties()
versionProps.load(FileInputStream(versionPropsFile))
val versionMajor = versionProps.getProperty("versionMajor").trim()
val versionMinor = versionProps.getProperty("versionMinor").trim()
val versionBuild = versionProps.getProperty("versionBuild").trim()
"$versionMajor.$versionMinor.$versionBuild"
} else {
throw GradleException("Could not read version.properties!")
}
})
}
}
val ApplicationVariant.versionNameNoDots
get() = versionName.replace(".", "") | apache-2.0 |
AndroidX/androidx | compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/statetransition/MultiDimensionalAnimationDemo.kt | 3 | 3299 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.demos.statetransition
import androidx.compose.animation.animateColor
import androidx.compose.animation.core.animateRect
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
@Preview
@Composable
fun MultiDimensionalAnimationDemo() {
var currentState by remember { mutableStateOf(AnimState.Collapsed) }
val onClick = {
// Cycle through states when clicked.
currentState = when (currentState) {
AnimState.Collapsed -> AnimState.Expanded
AnimState.Expanded -> AnimState.PutAway
AnimState.PutAway -> AnimState.Collapsed
}
}
var width by remember { mutableStateOf(0f) }
var height by remember { mutableStateOf(0f) }
val transition = updateTransition(currentState)
val rect by transition.animateRect(transitionSpec = { spring(stiffness = 100f) }) {
when (it) {
AnimState.Collapsed -> Rect(600f, 600f, 900f, 900f)
AnimState.Expanded -> Rect(0f, 400f, width, height - 400f)
AnimState.PutAway -> Rect(width - 300f, height - 300f, width, height)
}
}
val color by transition.animateColor(transitionSpec = { tween(durationMillis = 500) }) {
when (it) {
AnimState.Collapsed -> Color.LightGray
AnimState.Expanded -> Color(0xFFd0fff8)
AnimState.PutAway -> Color(0xFFe3ffd9)
}
}
Canvas(
modifier = Modifier.fillMaxSize().clickable(
onClick = onClick,
indication = null,
interactionSource = remember { MutableInteractionSource() }
)
) {
width = size.width
height = size.height
drawRect(
color,
topLeft = Offset(rect.left, rect.top),
size = Size(rect.width, rect.height)
)
}
}
private enum class AnimState {
Collapsed,
Expanded,
PutAway
} | apache-2.0 |
satamas/fortran-plugin | src/main/kotlin/org/jetbrains/fortran/ide/completion/KeywordCompletionContributor.kt | 1 | 3283 | package org.jetbrains.fortran.ide.completion
import com.intellij.codeInsight.completion.CompletionContributor
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.patterns.PlatformPatterns.psiElement
import org.jetbrains.fortran.lang.FortranTypes
import org.jetbrains.fortran.lang.psi.FortranBlock
import org.jetbrains.fortran.lang.psi.FortranBlockData
class KeywordCompletionContributor : CompletionContributor() {
private val typeStatementsBeginning = setOf(
"byte", "character", "complex", "double", "integer", "logical", "real"
)
private val blockDataStatementsBeginning = setOf(
"common", "data", "dimension", "equivalence", "implicit", "parameter", "record", "save", "structure"
) + typeStatementsBeginning
private val allKeywords = blockDataStatementsBeginning + setOf("abstract", "accept", "all", "allocate",
"allocatable", "assign",
"assignment", "associate", "asynchronous", "backspace", "bind", "block", "blockdata",
"call", "case", "class", "close", "codimension", "concurrent", "contains", "contiguous", "continue",
"critical", "cycle", "deallocate", "decode", "default", "deferred", "do",
"doubleprecision", "doublecomplex", "elemental", "else", "elseif", "elsewhere", "encode",
"end", "endassociate", "endblock", "endblockdata", "endcritical", "enddo", "endenum",
"endfile", "endforall", "endfunction", "endif", "endinterface", "endmodule", "endprocedure",
"endprogram", "endselect", "endsubmodule", "endsubroutine", "endtype", "endwhere", "entry",
"enum", "enumerator", "error", "exit", "extends", "external", "final", "flush",
"forall", "format", "formatted", "function", "generic", "go", "goto", "if", "images",
"import", "impure", "in", "include", "inout", "intent", "interface", "intrinsic",
"inquire", "iolength", "is", "kind", "len", "lock", "memory", "module", "name",
"namelist", "none", "nonintrinsic", "nonoverridable", "nopass", "nullify", "only", "open",
"operator", "optional", "out", "pass", "pause", "pointer", "precision", "print",
"private", "procedure", "program", "protected", "public", "pure", "read", "recursive",
"result", "return", "rewind", "select", "sequence", "stop", "sync", "syncall",
"syncimages", "syncmemory", "subroutine", "submodule", "target", "then", "to", "type",
"unformatted", "unlock", "use", "value", "volatile", "wait", "where", "while", "write", "unit")
init {
extend(CompletionType.BASIC, blockDataStatementStart(), KeywordCompletionProvider(blockDataStatementsBeginning))
extend(CompletionType.BASIC, defaultStatementStart(), KeywordCompletionProvider(allKeywords))
}
private fun defaultStatementStart() = statementStart()
.andNot(psiElement()
.inside(FortranBlockData::class.java))
private fun blockDataStatementStart() = statementStart()
.inside(psiElement(FortranBlock::class.java))
.inside(psiElement(FortranBlockData::class.java))
private fun statementStart() = psiElement(FortranTypes.IDENTIFIER).afterLeaf(psiElement(FortranTypes.EOL))
} | apache-2.0 |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/annotator/fixes/RemoveReprValueFixTest.kt | 3 | 872 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator.fixes
import org.rust.ide.annotator.RsAnnotatorTestBase
import org.rust.ide.annotator.RsErrorAnnotator
class RemoveReprValueFixTest : RsAnnotatorTestBase(RsErrorAnnotator::class) {
fun `test fix E0517 remove wrong repr value`() = checkFixByText("Remove", """
#[repr(<error descr="C attribute should be applied to struct, enum, or union [E0517]">C/*caret*/</error>)]
type Test = i32;
""", """
#[repr()]
type Test = i32;
""")
fun `test fix E0552 unrecognized repr`() = checkFixByText("Remove", """
#[repr(<error descr="Unrecognized representation CD [E0552]">CD/*caret*/</error>)]
struct Test(i32);
""", """
#[repr()]
struct Test(i32);
""")
}
| mit |
MeilCli/Twitter4HK | library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/api/statuses/Lookup.kt | 1 | 1293 | package com.twitter.meil_mitu.twitter4hk.api.statuses
import com.twitter.meil_mitu.twitter4hk.AbsGet
import com.twitter.meil_mitu.twitter4hk.AbsOauth
import com.twitter.meil_mitu.twitter4hk.OauthType
import com.twitter.meil_mitu.twitter4hk.ResponseList
import com.twitter.meil_mitu.twitter4hk.converter.IStatusConverter
import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException
class Lookup<TStatus>(
oauth: AbsOauth,
protected val json: IStatusConverter<TStatus>,
id: LongArray) : AbsGet<ResponseList<TStatus>>(oauth) {
var id: LongArray? by longArrayParam("id")
var includeEntities: Boolean? by booleanParam("include_entities")
/**
* must not use in JsonConverter for User
*/
var trimUser: Boolean? by booleanParam("trim_user")
/**
* must not use in JsonConverter for Status
*/
var map: Boolean? by booleanParam("map")
override val url = "https://api.twitter.com/1.1/statuses/lookup.json"
override val allowOauthType = OauthType.oauth1 or OauthType.oauth2
override val isAuthorization: Boolean = true
init {
this.id = id
}
@Throws(Twitter4HKException::class)
override fun call(): ResponseList<TStatus> {
return json.toStatusResponseList(oauth.get(this))
}
}
| mit |
charleskorn/batect | app/src/main/kotlin/batect/execution/model/events/TemporaryDirectoryDeletedEvent.kt | 1 | 839 | /*
Copyright 2017-2020 Charles Korn.
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 batect.execution.model.events
import java.nio.file.Path
data class TemporaryDirectoryDeletedEvent(val directoryPath: Path) : TaskEvent() {
override fun toString() = "${this::class.simpleName}(directory path: '$directoryPath')"
}
| apache-2.0 |
DemonWav/StatCraft | src/main/kotlin/com/demonwav/statcraft/commands/sc/SCToolsBroken.kt | 1 | 1980 | /*
* StatCraft Bukkit Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft.commands.sc
import com.demonwav.statcraft.StatCraft
import com.demonwav.statcraft.commands.ResponseBuilder
import com.demonwav.statcraft.querydsl.QPlayers
import com.demonwav.statcraft.querydsl.QToolsBroken
import org.bukkit.command.CommandSender
import java.sql.Connection
class SCToolsBroken(plugin: StatCraft) : SCTemplate(plugin) {
init {
plugin.baseCommand.registerCommand("toolsbroken", this)
}
override fun hasPermission(sender: CommandSender, args: Array<out String>?) = sender.hasPermission("statcraft.user.toolsbroken")
override fun playerStatResponse(name: String, args: List<String>, connection: Connection): String {
val id = getId(name) ?: return ResponseBuilder.build(plugin) {
playerName { name }
statName { "Tools Broken" }
stats["Total"] = "0"
}
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val t = QToolsBroken.toolsBroken
val result = query.from(t).where(t.id.eq(id)).uniqueResult(t.amount.sum())
return ResponseBuilder.build(plugin) {
playerName { name }
statName { "Tools Broken" }
stats["Total"] = df.format(result)
}
}
override fun serverStatListResponse(num: Long, args: List<String>, connection: Connection): String {
val query = plugin.databaseManager.getNewQuery(connection) ?: return databaseError
val t = QToolsBroken.toolsBroken
val p = QPlayers.players
val list = query
.from(t)
.innerJoin(p)
.on(t.id.eq(p.id))
.groupBy(p.name)
.orderBy(t.amount.sum().desc())
.limit(num)
.list(p.name, t.amount.sum())
return topListResponse("Tools Broken", list)
}
}
| mit |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opengles/templates/OES_texture_view.kt | 1 | 2151 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengles.templates
import org.lwjgl.generator.*
import org.lwjgl.opengles.*
val OES_texture_view = "OESTextureView".nativeClassGLES("OES_texture_view", postfix = OES) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension allows a texture's data store to be "viewed" in multiple ways, either reinterpreting the data format/type as a different format/ type
with the same element size, or by clamping the mipmap level range or array slice range.
The goals of this extension are to avoid having these alternate views become shared mutable containers of shared mutable objects, and to add the views
to the API in a minimally invasive way.
No new object types are added. Conceptually, a texture object is split into the following parts:
${ul(
"A data store holding texel data.",
"State describing which portions of the data store to use, and how to interpret the data elements.",
"An embedded sampler object.",
"Various other texture parameters."
)}
With this extension, multiple textures can share a data store and have different state describing which portions of the data store to use and how to
interpret the data elements. The data store is refcounted and not destroyed until the last texture sharing it is deleted.
This extension leverages the concept of an "immutable texture". Views can only be created of textures created with TexStorage*.
Requires ${GLES31.core}.
"""
IntConstant(
"Accepted by the {@code pname} parameters of GetTexParameterfv and GetTexParameteriv.",
"TEXTURE_VIEW_MIN_LEVEL_OES"..0x82DB,
"TEXTURE_VIEW_NUM_LEVELS_OES"..0x82DC,
"TEXTURE_VIEW_MIN_LAYER_OES"..0x82DD,
"TEXTURE_VIEW_NUM_LAYERS_OES"..0x82DE,
"TEXTURE_IMMUTABLE_LEVELS"..0x82DF
)
void(
"TextureViewOES",
"",
GLuint.IN("texture", ""),
GLenum.IN("target", ""),
GLuint.IN("origtexture", ""),
GLenum.IN("internalformat", ""),
GLuint.IN("minlevel", ""),
GLuint.IN("numlevels", ""),
GLuint.IN("minlayer", ""),
GLuint.IN("numlayers", "")
)
} | bsd-3-clause |
robohorse/RoboPOJOGenerator | generator/src/main/kotlin/com/robohorse/robopojogenerator/properties/templates/ClassTemplate.kt | 1 | 3316 | package com.robohorse.robopojogenerator.properties.templates
internal object ClassTemplate {
const val KOTLIN_DATA_CLASS = "data"
const val NEW_LINE = "\n"
const val TAB = "\t"
const val CLASS_BODY = "public class %1\$s" +
"{" + NEW_LINE +
"%2\$s" + NEW_LINE +
"}"
const val CLASS_BODY_ABSTRACT = "public abstract class %1\$s" +
"{" + NEW_LINE +
"%2\$s" + NEW_LINE +
"}"
const val CLASS_BODY_RECORDS = "public record %1\$s(\n%2\$s\n)" + " {\n}"
const val CLASS_BODY_KOTLIN_DTO = "$KOTLIN_DATA_CLASS class %1\$s" +
"(" + NEW_LINE +
"%2\$s" + NEW_LINE +
")"
const val CLASS_BODY_KOTLIN_DTO_PARCELABLE = "@Parcelize\n$KOTLIN_DATA_CLASS class %1\$s" +
"(" + NEW_LINE +
"%2\$s" + NEW_LINE +
") : Parcelable"
const val CLASS_BODY_ANNOTATED = "%1\$s" + NEW_LINE +
"%2\$s"
const val CLASS_ROOT_IMPORTS = (
"package %1\$s;" + NEW_LINE + NEW_LINE +
"%2\$s" + NEW_LINE +
"%3\$s"
)
const val CLASS_ROOT_IMPORTS_WITHOUT_SEMICOLON = (
"package %1\$s" + NEW_LINE + NEW_LINE +
"%2\$s" + NEW_LINE +
"%3\$s"
)
const val CLASS_ROOT = "package %1\$s;" + NEW_LINE + NEW_LINE +
"%2\$s" + NEW_LINE
const val CLASS_ROOT_WITHOUT_SEMICOLON = "package %1\$s" + NEW_LINE + NEW_LINE +
"%2\$s" + NEW_LINE
const val CLASS_ROOT_NO_PACKAGE = "%1\$s" + NEW_LINE
const val FIELD = "$TAB%1\$s %2\$s;$NEW_LINE"
const val FIELD_WITH_VISIBILITY = "$TAB%1\$s %2\$s %3\$s;$NEW_LINE"
const val FIELD_AUTO_VALUE = TAB + "public abstract %1\$s %2\$s();" + NEW_LINE
const val FIELD_KOTLIN_DTO = TAB + "val %1\$s: %2\$s? = null" + "," + NEW_LINE
const val FIELD_KOTLIN_DTO_NON_NULL = TAB + "val %1\$s: %2\$s" + "," + NEW_LINE
const val FIELD_JAVA_RECORD = "$TAB%1\$s %2\$s,$NEW_LINE"
const val FIELD_KOTLIN_DOT_DEFAULT = TAB + "val any: Any? = null"
const val FIELD_ANNOTATED = "$NEW_LINE$TAB%1\$s$NEW_LINE%2\$s"
const val TYPE_ADAPTER = (
TAB + "public static TypeAdapter<%1\$s> typeAdapter(Gson gson) {" +
NEW_LINE +
TAB + TAB + "return new AutoValue_%1\$s.GsonTypeAdapter(gson);" + NEW_LINE +
TAB + "}" + NEW_LINE
)
const val SETTER = (
TAB + "public void set%1\$s(%2\$s %3\$s){" + NEW_LINE +
TAB + TAB + "this.%3\$s = %3\$s;" + NEW_LINE +
TAB + "}" + NEW_LINE
)
const val GETTER = (
TAB + "public %3\$s get%1\$s(){" + NEW_LINE +
TAB + TAB + "return %2\$s;" + NEW_LINE +
TAB + "}" + NEW_LINE
)
const val GETTER_BOOLEAN = (
TAB + "public %3\$s is%1\$s(){" + NEW_LINE +
TAB + TAB + "return %2\$s;" + NEW_LINE +
TAB + "}" + NEW_LINE
)
const val TO_STRING = (
TAB + "@Override" + NEW_LINE + " " + TAB +
"public String toString(){" + NEW_LINE +
TAB + TAB + "return " + NEW_LINE +
TAB + TAB + TAB + "\"%1\$s{\" + " + NEW_LINE +
"%2\$s" +
TAB + TAB + TAB + "\"}\";" + NEW_LINE +
TAB + TAB + "}"
)
const val TO_STRING_LINE = "$TAB$TAB$TAB\"%3\$s%1\$s = \'\" + %2\$s + \'\\\'\' + $NEW_LINE"
}
| mit |
robohorse/RoboPOJOGenerator | generator/src/test/kotlin/com/robohorse/robopojogenerator/parser/InputDataParserTest.kt | 1 | 6463 | package com.robohorse.robopojogenerator.parser
import com.robohorse.robopojogenerator.properties.ClassItem
import com.robohorse.robopojogenerator.properties.JsonModel.JsonItem
import com.robohorse.robopojogenerator.utils.ClassGenerateHelper
import com.robohorse.robopojogenerator.utils.JsonReader
import org.json.JSONObject
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
/**
* Integration test to verify that parsing logic is correct.
*/
internal class InputDataParserTest {
private val jsonReader: JsonReader = JsonReader()
private val classGenerateHelper = ClassGenerateHelper()
private val jsonObjectParser = JsonObjectParser(classGenerateHelper)
private val jsonArrayParser = JsonArrayParser(classGenerateHelper)
private val inputDataParser = InputDataParser(
classGenerateHelper,
jsonObjectParser,
jsonArrayParser
)
@Test
fun testSingleObjectGeneration_isCorrect() {
val jsonObject = jsonReader.read("single_object.json") as JSONObject
val name = "Response"
val classItemMap: LinkedHashMap<String?, ClassItem> = LinkedHashMap()
val jsonItem = JsonItem(name, jsonObject)
inputDataParser.parse(jsonItem, classItemMap)
assertTrue(classItemMap.size == 1)
val iterator = classItemMap.values.iterator()
val (className, _, _, _, fields) = iterator.next()
assertEquals(className, name)
assertNotNull(fields)
for (key in jsonObject.keySet()) {
assertTrue(fields.containsKey(key))
}
}
@Test
fun testInnerObjectGeneration_isCorrect() {
val jsonObject = jsonReader.read("inner_json_object.json") as JSONObject
val innerJsonObject = jsonObject.optJSONObject("data")
val name = "Response"
val classItemMap: LinkedHashMap<String?, ClassItem> = LinkedHashMap()
val jsonItem = JsonItem(name, jsonObject)
inputDataParser.parse(jsonItem, classItemMap)
assertTrue(classItemMap.size == 2)
for ((className, _, _, _, fields) in classItemMap.values) {
assertNotNull(fields)
if (name.equals(className, ignoreCase = true)) {
for (key in jsonObject.keySet()) {
assertTrue(fields.containsKey(key))
}
} else {
for (key in innerJsonObject.keySet()) {
assertTrue(fields.containsKey(key))
}
}
}
}
@Test
fun testEmptyArrayGeneration_isCorrect() {
val jsonObject = jsonReader.read("empty_array.json") as JSONObject
val name = "Response"
val classItemMap: LinkedHashMap<String?, ClassItem> = LinkedHashMap()
val jsonItem = JsonItem(name, jsonObject)
inputDataParser.parse(jsonItem, classItemMap)
assertTrue(classItemMap.size == 1)
val iterator: Iterator<*> = classItemMap.values.iterator()
val (className, _, _, _, fields) = iterator.next() as ClassItem
assertEquals(className, name)
assertNotNull(fields)
for (key in jsonObject.keySet()) {
assertTrue(fields.containsKey(key))
}
val targetObjectType = fields["data"]
assertEquals("List<Object>", targetObjectType!!.getJavaItem())
}
@Test
fun testIntegerArrayGeneration_isCorrect() {
val jsonObject = jsonReader.read("array_with_primitive.json") as JSONObject
val name = "Response"
val targetType = "List<Integer>"
val classItemMap: LinkedHashMap<String?, ClassItem> = LinkedHashMap()
val jsonItem = JsonItem(name, jsonObject)
inputDataParser.parse(jsonItem, classItemMap)
assertTrue(classItemMap.size == 1)
val iterator: Iterator<*> = classItemMap.values.iterator()
val (className, _, _, _, fields) = iterator.next() as ClassItem
assertEquals(className, name)
assertNotNull(fields)
for (key in jsonObject.keySet()) {
assertTrue(fields.containsKey(key))
}
val actualType = fields["data"]
assertEquals(targetType, actualType!!.getJavaItem())
}
@Test
fun testInnerArrayObjectGeneration_isCorrect() {
val jsonObject = jsonReader.read("array_with_jsonobject.json") as JSONObject
val innerJsonArray = jsonObject.optJSONArray("data")
val innerJsonObject = innerJsonArray.getJSONObject(0)
val name = "Response"
val targetType = "List<DataItem>"
val classItemMap: LinkedHashMap<String?, ClassItem> = LinkedHashMap()
val jsonItem = JsonItem(name, jsonObject)
inputDataParser.parse(jsonItem, classItemMap)
assertTrue(classItemMap.size == 2)
for ((className, _, _, _, fields) in classItemMap.values) {
assertNotNull(fields)
if (name.equals(className, ignoreCase = true)) {
for (key in jsonObject.keySet()) {
assertTrue(fields.containsKey(key))
val actualType = fields["data"]
val javaItem = actualType!!.getJavaItem()
assertEquals(targetType, javaItem)
}
} else {
for (key in innerJsonObject.keySet()) {
assertTrue(fields.containsKey(key))
}
}
}
}
@Test
fun testNestedArrayElementsConsolidateObjectProperties() {
val jsonObject = jsonReader.read("nested_array_elements.json") as JSONObject
val name = "Response"
val classItemMap: LinkedHashMap<String?, ClassItem> = LinkedHashMap()
val jsonItem = JsonItem(name, jsonObject)
inputDataParser.parse(jsonItem, classItemMap)
val classFields = hashSetOf<String>()
classItemMap.values.forEach { classFields.addAll(it.classFields.keys) }
assertNotNull(classFields)
val targetResult = listOf("Outsides", "Outside", "Insides", "Inside", "A", "B", "C")
assertEquals(targetResult.size, classFields.size)
// when using "itemMap.putAll(innerItemsMap);" element "C" will be missing as newer instances of objects in
// innerItemsMap of the same name/type overwrite existing map (itemMap) entries
targetResult.listIterator().forEach {
assertTrue(classFields.contains(it), "Missing element: $it")
}
}
}
| mit |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/exception/NotLoggedInException.kt | 2 | 104 | package me.proxer.app.exception
/**
* @author Ruben Gees
*/
class NotLoggedInException : Exception()
| gpl-3.0 |
crabzilla/crabzilla | crabzilla-stack/src/test/kotlin/io/github/crabzilla/stack/subscription/internal/QuerySpecificationTest.kt | 1 | 2350 | package io.github.crabzilla.stack.subscription.internal
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
@DisplayName("Specifying events query")
internal class QuerySpecificationTest {
@Test
fun `all events`() {
val expected = """
SELECT event_type, state_type, state_id, event_payload, sequence, id, causation_id, correlation_id, version
FROM events
WHERE sequence > (select sequence from subscriptions where name = ${'$'}1)
ORDER BY sequence
LIMIT ${'$'}2"""
val q = QuerySpecification.query(emptyList(), emptyList())
assertEquals(expected.trimIndent(), q.trimIndent())
}
@Test
fun `by aggregate root`() {
val expected = """
SELECT event_type, state_type, state_id, event_payload, sequence, id, causation_id, correlation_id, version
FROM events
WHERE sequence > (select sequence from subscriptions where name = ${'$'}1)
AND state_type IN ('Customer')
ORDER BY sequence
LIMIT ${'$'}2"""
val q = QuerySpecification.query(listOf("Customer"), emptyList())
assertEquals(expected.trimIndent(), q.trimIndent())
}
@Test
fun `by events`() {
val expected = """
SELECT event_type, state_type, state_id, event_payload, sequence, id, causation_id, correlation_id, version
FROM events
WHERE sequence > (select sequence from subscriptions where name = ${'$'}1)
AND event_type IN ('CustomerRegistered','CustomerActivated','CustomerDeactivated')
ORDER BY sequence
LIMIT ${'$'}2"""
val q = QuerySpecification.query(
emptyList(),
listOf("CustomerRegistered", "CustomerActivated", "CustomerDeactivated")
)
assertEquals(expected.trimIndent(), q.trimIndent())
}
@Test
fun `by aggregate root and events`() {
val expected = """
SELECT event_type, state_type, state_id, event_payload, sequence, id, causation_id, correlation_id, version
FROM events
WHERE sequence > (select sequence from subscriptions where name = $1)
AND state_type IN ('Customer')
AND event_type IN ('CustomerRegistered','CustomerActivated','CustomerDeactivated')
ORDER BY sequence
LIMIT $2""".trimIndent()
val q = QuerySpecification.query(
listOf("Customer"),
listOf("CustomerRegistered", "CustomerActivated", "CustomerDeactivated")
)
assertEquals(expected, q.trimIndent())
}
}
| apache-2.0 |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/syncadapter/SyncAdapter.kt | 1 | 2056 | /*
* Copyright (C) 2014 yvolk (Yuri Volkov), http://yurivolkov.com
* Based on the sample: com.example.android.samplesync.syncadapter
* Copyright (C) 2010 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 org.andstatus.app.syncadapter
import android.accounts.Account
import android.content.AbstractThreadedSyncAdapter
import android.content.ContentProviderClient
import android.content.Context
import android.content.SyncResult
import android.os.Bundle
import org.andstatus.app.context.MyContext
import org.andstatus.app.context.MyContextHolder
import org.andstatus.app.service.MyServiceCommandsRunner
import org.andstatus.app.service.MyServiceManager
import org.andstatus.app.util.MyLog
class SyncAdapter(private val mContext: Context, autoInitialize: Boolean) : AbstractThreadedSyncAdapter(mContext, autoInitialize) {
override fun onPerformSync(account: Account, extras: Bundle?, authority: String?,
provider: ContentProviderClient?, syncResult: SyncResult) {
if (!MyServiceManager.isServiceAvailable()) {
MyLog.d(this, account.name + " Service unavailable")
return
}
val myContext: MyContext = MyContextHolder.myContextHolder.initialize(mContext, this).getBlocking()
MyServiceCommandsRunner(myContext).autoSyncAccount(
myContext.accounts.fromAccountName(account.name), syncResult)
}
init {
MyLog.v(this) { "created, context:" + mContext.javaClass.canonicalName }
}
}
| apache-2.0 |
saschpe/PlanningPoker | mobile/src/main/java/saschpe/poker/activity/HelpActivity.kt | 1 | 4447 | /*
* Copyright 2016 Sascha Peilicke
*
* 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 saschpe.poker.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.google.android.gms.oss.licenses.OssLicensesMenuActivity
import com.google.android.material.tabs.TabLayout
import kotlinx.android.synthetic.main.activity_help.*
import saschpe.android.socialfragment.app.SocialFragment
import saschpe.android.versioninfo.widget.VersionInfoDialogFragment
import saschpe.poker.BuildConfig
import saschpe.poker.R
import saschpe.poker.application.Application
import saschpe.poker.customtabs.CustomTabs
class HelpActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (intent != null) {
if (intent?.scheme == Application.INTENT_SCHEME) {
if (intent?.data?.host == "about") {
when (intent?.data?.path) {
"/privacy" -> {
CustomTabs.startPrivacyPolicy(this)
finish()
}
}
}
}
}
setContentView(R.layout.activity_help)
// Set up toolbar
setSupportActionBar(toolbar)
supportActionBar?.title = null
supportActionBar?.setDisplayHomeAsUpEnabled(true)
// Set up nested scrollview
nested_scroll.isFillViewport = true
// Set up view pager
view_pager.adapter = MyFragmentPagerAdapter(this, supportFragmentManager)
// Set up tab layout
tab_layout.tabMode = TabLayout.MODE_FIXED
tab_layout.setupWithViewPager(view_pager)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.help, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
R.id.privacy_policy -> CustomTabs.startPrivacyPolicy(this)
R.id.open_source_licenses -> startActivity(Intent(this, OssLicensesMenuActivity::class.java))
R.id.version_info -> {
VersionInfoDialogFragment
.newInstance(
getString(R.string.app_name),
BuildConfig.VERSION_NAME,
"Sascha Peilicke",
R.mipmap.ic_launcher
)
.show(supportFragmentManager, "version_info")
return true
}
}
return super.onOptionsItemSelected(item)
}
private class MyFragmentPagerAdapter(context: Context, fm: FragmentManager) : FragmentPagerAdapter(fm) {
private val pageTitles = arrayOf(context.getString(R.string.social))
private val applicationName = context.getString(R.string.app_name)
override fun getItem(position: Int): Fragment = SocialFragment.Builder()
// Mandatory
.setApplicationId(BuildConfig.APPLICATION_ID)
// Optional
.setApplicationName(applicationName)
.setContactEmailAddress("[email protected]")
.setGithubProject("saschpe/PlanningPoker")
.setTwitterProfile("saschpe")
// Visual customization
.setHeaderTextColor(R.color.accent)
.setIconTint(android.R.color.white)
.build()
override fun getPageTitle(position: Int): String = pageTitles[position]
override fun getCount() = 1
}
}
| apache-2.0 |
wordpress-mobile/AztecEditor-Android | aztec/src/main/kotlin/org/wordpress/aztec/formatting/BlockFormatter.kt | 1 | 58755 | package org.wordpress.aztec.formatting
import android.text.Editable
import android.text.Layout
import android.text.Spanned
import android.text.TextUtils
import androidx.core.text.TextDirectionHeuristicsCompat
import org.wordpress.android.util.AppLog
import org.wordpress.aztec.AlignmentRendering
import org.wordpress.aztec.AztecAttributes
import org.wordpress.aztec.AztecText
import org.wordpress.aztec.AztecTextFormat
import org.wordpress.aztec.Constants
import org.wordpress.aztec.ITextFormat
import org.wordpress.aztec.handlers.BlockHandler
import org.wordpress.aztec.handlers.HeadingHandler
import org.wordpress.aztec.handlers.ListItemHandler
import org.wordpress.aztec.spans.AztecHeadingSpan
import org.wordpress.aztec.spans.AztecHorizontalRuleSpan
import org.wordpress.aztec.spans.AztecListItemSpan
import org.wordpress.aztec.spans.AztecListSpan
import org.wordpress.aztec.spans.AztecMediaSpan
import org.wordpress.aztec.spans.AztecOrderedListSpan
import org.wordpress.aztec.spans.AztecPreformatSpan
import org.wordpress.aztec.spans.AztecQuoteSpan
import org.wordpress.aztec.spans.AztecTaskListSpan
import org.wordpress.aztec.spans.AztecUnorderedListSpan
import org.wordpress.aztec.spans.IAztecAlignmentSpan
import org.wordpress.aztec.spans.IAztecBlockSpan
import org.wordpress.aztec.spans.IAztecCompositeBlockSpan
import org.wordpress.aztec.spans.IAztecLineBlockSpan
import org.wordpress.aztec.spans.IAztecNestable
import org.wordpress.aztec.spans.ParagraphSpan
import org.wordpress.aztec.spans.createAztecQuoteSpan
import org.wordpress.aztec.spans.createHeadingSpan
import org.wordpress.aztec.spans.createListItemSpan
import org.wordpress.aztec.spans.createOrderedListSpan
import org.wordpress.aztec.spans.createParagraphSpan
import org.wordpress.aztec.spans.createPreformatSpan
import org.wordpress.aztec.spans.createTaskListSpan
import org.wordpress.aztec.spans.createUnorderedListSpan
import org.wordpress.aztec.util.SpanWrapper
import kotlin.reflect.KClass
class BlockFormatter(editor: AztecText,
private val listStyle: ListStyle,
private val listItemStyle: ListItemStyle,
private val quoteStyle: QuoteStyle,
private val headerStyle: HeaderStyles,
private val preformatStyle: PreformatStyle,
private val alignmentRendering: AlignmentRendering,
private val exclusiveBlockStyles: ExclusiveBlockStyles,
private val paragraphStyle: ParagraphStyle
) : AztecFormatter(editor) {
private val listFormatter = ListFormatter(editor)
private val indentFormatter = IndentFormatter(editor)
data class ListStyle(val indicatorColor: Int, val indicatorMargin: Int, val indicatorPadding: Int, val indicatorWidth: Int, val verticalPadding: Int) {
fun leadingMargin(): Int {
return indicatorMargin + 2 * indicatorWidth + indicatorPadding
}
}
data class QuoteStyle(val quoteBackground: Int, val quoteColor: Int, val quoteTextColor: Int, val quoteBackgroundAlpha: Float, val quoteMargin: Int, val quotePadding: Int, val quoteWidth: Int, val verticalPadding: Int)
data class PreformatStyle(val preformatBackground: Int, val preformatBackgroundAlpha: Float, val preformatColor: Int, val verticalPadding: Int, val leadingMargin: Int, val preformatBorderColor: Int, val preformatBorderRadius: Int, val preformatBorderThickness: Int, val preformatTextSize: Int)
data class ListItemStyle(val strikeThroughCheckedItems: Boolean, val checkedItemsTextColor: Int)
data class HeaderStyles(val verticalPadding: Int, val styles: Map<AztecHeadingSpan.Heading, HeadingStyle>) {
data class HeadingStyle(val fontSize: Int, val fontColor: Int)
}
data class ExclusiveBlockStyles(val enabled: Boolean = false, val verticalParagraphMargin: Int)
data class ParagraphStyle(val verticalMargin: Int)
fun indent() {
listFormatter.indentList()
indentFormatter.indent()
}
fun outdent() {
listFormatter.outdentList()
indentFormatter.outdent()
}
fun isIndentAvailable(): Boolean {
if (listFormatter.isIndentAvailable()) return true
return indentFormatter.isIndentAvailable()
}
fun isOutdentAvailable(): Boolean {
if (listFormatter.isOutdentAvailable()) return true
return indentFormatter.isOutdentAvailable()
}
fun toggleOrderedList() {
toggleList(AztecTextFormat.FORMAT_ORDERED_LIST)
}
fun toggleUnorderedList() {
toggleList(AztecTextFormat.FORMAT_UNORDERED_LIST)
}
fun toggleTaskList() {
toggleList(AztecTextFormat.FORMAT_TASK_LIST)
}
private val availableLists = setOf(AztecTextFormat.FORMAT_TASK_LIST, AztecTextFormat.FORMAT_ORDERED_LIST, AztecTextFormat.FORMAT_UNORDERED_LIST)
private fun toggleList(toggledList: AztecTextFormat) {
val otherLists = availableLists.filter { it != toggledList }
if (!containsList(toggledList)) {
if (otherLists.any { containsList(it) }) {
switchListType(toggledList)
editor.addRefreshListenersToTaskLists(editableText, selectionStart, selectionEnd)
} else {
applyBlockStyle(toggledList)
editor.addRefreshListenersToTaskLists(editableText, selectionStart, selectionEnd)
}
} else {
if (otherLists.any { containsList(it) }) {
switchListType(toggledList)
editor.addRefreshListenersToTaskLists(editableText, selectionStart, selectionEnd)
} else {
removeBlockStyle(toggledList)
}
}
}
fun toggleQuote() {
if (!containsQuote()) {
applyBlockStyle(AztecTextFormat.FORMAT_QUOTE)
} else {
removeEntireBlock(AztecQuoteSpan::class.java)
}
}
fun togglePreformat() {
if (!containsPreformat()) {
if (containsOtherHeadings(AztecTextFormat.FORMAT_PREFORMAT) && !exclusiveBlockStyles.enabled) {
switchHeadingToPreformat()
} else {
applyBlockStyle(AztecTextFormat.FORMAT_PREFORMAT)
}
} else {
removeEntireBlock(AztecPreformatSpan::class.java)
}
}
fun toggleHeading(textFormat: ITextFormat) {
when (textFormat) {
AztecTextFormat.FORMAT_HEADING_1,
AztecTextFormat.FORMAT_HEADING_2,
AztecTextFormat.FORMAT_HEADING_3,
AztecTextFormat.FORMAT_HEADING_4,
AztecTextFormat.FORMAT_HEADING_5,
AztecTextFormat.FORMAT_HEADING_6 -> {
if (!containsHeadingOnly(textFormat)) {
if (containsPreformat() && !exclusiveBlockStyles.enabled) {
switchPreformatToHeading(textFormat)
} else if (containsOtherHeadings(textFormat)) {
switchHeaderType(textFormat)
} else {
applyBlockStyle(textFormat)
}
}
}
AztecTextFormat.FORMAT_PARAGRAPH -> {
val span = editableText.getSpans(selectionStart, selectionEnd, AztecHeadingSpan::class.java).firstOrNull()
if (span != null) {
removeBlockStyle(span.textFormat)
}
removeBlockStyle(AztecTextFormat.FORMAT_PREFORMAT)
}
else -> {
}
}
}
fun toggleTextAlignment(textFormat: ITextFormat) {
when (alignmentRendering) {
AlignmentRendering.VIEW_LEVEL -> {
val message = "cannot toggle text alignment when ${AlignmentRendering.VIEW_LEVEL} is being used"
AppLog.d(AppLog.T.EDITOR, message)
}
AlignmentRendering.SPAN_LEVEL -> {
when (textFormat) {
AztecTextFormat.FORMAT_ALIGN_LEFT,
AztecTextFormat.FORMAT_ALIGN_CENTER,
AztecTextFormat.FORMAT_ALIGN_RIGHT ->
if (containsAlignment(textFormat)) {
removeTextAlignment(textFormat)
} else {
applyTextAlignment(textFormat)
}
}
}
}
}
fun removeTextAlignment(textFormat: ITextFormat) {
getAlignedSpans(textFormat).forEach { changeAlignment(it, null) }
}
fun tryRemoveBlockStyleFromFirstLine(): Boolean {
val selectionStart = editor.selectionStart
if (selectionStart != 0) {
// only handle the edge case of start of text
return false
}
var changed = false
// try to remove block styling when pressing backspace at the beginning of the text
editableText.getSpans(0, 0, IAztecBlockSpan::class.java).forEach { it ->
val spanEnd = editableText.getSpanEnd(it)
val indexOfNewline = editableText.indexOf('\n').let { if (it != -1) it else editableText.length }
if (spanEnd <= indexOfNewline + 1) {
// block will collapse so, just remove it
editableText.removeSpan(it)
changed = true
return@forEach
}
editableText.setSpan(it, indexOfNewline + 1, spanEnd, editableText.getSpanFlags(it))
changed = true
}
return changed
}
/**
* This method makes sure only one block style is ever applied to part of the text. The following block styles are
* made exclusive if the option is enabled:
* - all the lists
* - all the headings
* - quote
* - preformat
*/
private fun removeBlockStylesFromSelectedLine(appliedClass: IAztecBlockSpan) {
// We only want to remove the previous block styles if this option is enabled
if (!exclusiveBlockStyles.enabled) {
return
}
val selectionStart = editor.selectionStart
var newSelStart = if (selectionStart > selectionEnd) selectionEnd else selectionStart
var newSelEnd = selectionEnd
if (newSelStart == 0 && newSelEnd == 0) {
newSelEnd++
} else if (newSelStart == newSelEnd && editableText.length > selectionStart && editableText[selectionStart - 1] == Constants.NEWLINE) {
newSelEnd++
} else if (newSelStart > 0 && !editor.isTextSelected()) {
newSelStart--
}
// try to remove block styling when pressing backspace at the beginning of the text
editableText.getSpans(newSelStart, newSelEnd, IAztecBlockSpan::class.java).forEach {
// We want to remove any list item span that's being converted to another block
if (it is AztecListItemSpan) {
editableText.removeSpan(it)
return@forEach
}
// We don't mind the paragraph blocks which wrap everything
if (it is ParagraphSpan) {
return@forEach
}
// Only these supported blocks will be split/removed on block change
val format = it.textFormat ?: return@forEach
// We do not want to handle cases where the applied style is already existing on a span
if (it.javaClass == appliedClass.javaClass) {
return@forEach
}
val spanStart = editableText.getSpanStart(it)
val spanEnd = editableText.getSpanEnd(it)
val spanFlags = editableText.getSpanFlags(it)
val nextLineLength = "\n".length
// Defines end of a line in a block
val previousLineBreak = editableText.indexOf("\n", newSelEnd)
val lineEnd = if (previousLineBreak > -1) {
previousLineBreak + nextLineLength
} else spanEnd
// Defines start of a line in a block
val nextLineBreak = if (lineEnd == newSelStart + nextLineLength) {
editableText.lastIndexOf("\n", newSelStart - 1)
} else {
editableText.lastIndexOf("\n", newSelStart)
}
val lineStart = if (nextLineBreak > -1) {
nextLineBreak + nextLineLength
} else spanStart
val spanStartsBeforeLineStart = spanStart < lineStart
val spanEndsAfterLineEnd = spanEnd > lineEnd
if (spanStartsBeforeLineStart && spanEndsAfterLineEnd) {
// The line is fully inside of the span so we want to split span in two around the selected line
val copy = makeBlock(format, it.nestingLevel, it.attributes).first()
editableText.removeSpan(it)
editableText.setSpan(it, spanStart, lineStart, spanFlags)
editableText.setSpan(copy, lineEnd, spanEnd, spanFlags)
} else if (!spanStartsBeforeLineStart && spanEndsAfterLineEnd) {
// If the selected line is at the beginning of a span, move the span start to the end of the line
editableText.removeSpan(it)
editableText.setSpan(it, lineEnd, spanEnd, spanFlags)
} else if (spanStartsBeforeLineStart && !spanEndsAfterLineEnd) {
// If the selected line is at the end of a span, move the span end to the start of the line
editableText.removeSpan(it)
editableText.setSpan(it, spanStart, lineStart, spanFlags)
} else {
// In this case the line fully covers the span so we just want to remove the span
editableText.removeSpan(it)
}
}
}
fun moveSelectionIfImageSelected() {
if (selectionStart == selectionEnd && selectionStart > 0 &&
(hasImageRightAfterSelection() || hasHorizontalRuleRightAfterSelection())) {
editor.setSelection(selectionStart - 1)
}
}
private fun hasImageRightAfterSelection() =
editableText.getSpans(selectionStart, selectionEnd, AztecMediaSpan::class.java).any {
editableText.getSpanStart(it) == selectionStart
}
private fun hasHorizontalRuleRightAfterSelection() =
editableText.getSpans(selectionStart, selectionEnd, AztecHorizontalRuleSpan::class.java).any {
editableText.getSpanStart(it) == selectionStart
}
fun removeBlockStyle(textFormat: ITextFormat) {
removeBlockStyle(textFormat, selectionStart, selectionEnd, makeBlock(textFormat, 0).map { it.javaClass })
}
fun <T : IAztecBlockSpan> removeEntireBlock(type: Class<T>) {
editableText.getSpans(selectionStart, selectionEnd, type).forEach {
IAztecNestable.pullUp(editableText, selectionStart, selectionEnd, it.nestingLevel)
editableText.removeSpan(it)
}
}
fun removeBlockStyle(textFormat: ITextFormat, originalStart: Int, originalEnd: Int,
spanTypes: List<Class<IAztecBlockSpan>> = listOf(IAztecBlockSpan::class.java),
ignoreLineBounds: Boolean = false) {
var start = originalStart
var end = originalEnd
// if splitting block set a range that would be excluded from it
val boundsOfSelectedText = if (ignoreLineBounds) {
IntRange(start, end)
} else {
getBoundsOfText(editableText, start, end)
}
var startOfBounds = boundsOfSelectedText.first
var endOfBounds = boundsOfSelectedText.last
if (ignoreLineBounds) {
val hasPrecedingSpans = spanTypes.any { spanType ->
editableText.getSpans(start, end, spanType)
.any { span -> editableText.getSpanStart(span) < startOfBounds }
}
if (hasPrecedingSpans) {
// let's make sure there's a newline before bounds start
if (editableText[startOfBounds - 1] != Constants.NEWLINE) {
// insert a newline in the start of (inside) the bounds
editableText.insert(startOfBounds, "" + Constants.NEWLINE)
// the insertion will have pushed everything forward so, adjust indices
start++
end++
startOfBounds++
endOfBounds++
}
}
val hasExtendingBeyondSpans = spanTypes.any { spanType ->
editableText.getSpans(start, end, spanType)
.any { span -> endOfBounds < editableText.getSpanEnd(span) }
}
if (hasExtendingBeyondSpans) {
// let's make sure there's a newline before bounds end
if (editableText[endOfBounds] != Constants.NEWLINE) {
// insert a newline before the bounds
editableText.insert(endOfBounds, "" + Constants.NEWLINE)
// the insertion will have pushed the end forward so, adjust the indices
end++
endOfBounds++
if (selectionEnd == endOfBounds) {
// apparently selection end moved along when we inserted the newline but we need it to stay
// back in order to save the newline from potential removal
editor.setSelection(if (selectionStart != selectionEnd) selectionStart else selectionEnd - 1,
selectionEnd - 1)
}
}
}
}
spanTypes.forEach { spanType ->
// when removing style from multiple selected lines, if the last selected line is empty
// or at the end of editor the selection wont include the trailing newline/EOB marker
// that will leave us with orphan <li> tag, so we need to shift index to the right
val hasLingeringEmptyListItem = AztecListItemSpan::class.java.isAssignableFrom(spanType)
&& editableText.length > end
&& (editableText[end] == '\n' || editableText[end] == Constants.END_OF_BUFFER_MARKER)
val endModifier = if (hasLingeringEmptyListItem) 1 else 0
val spans = editableText.getSpans(start, end + endModifier, spanType)
spans.forEach { span ->
val spanStart = editableText.getSpanStart(span)
val spanEnd = editableText.getSpanEnd(span)
val spanPrecedesLine = spanStart < startOfBounds
val spanExtendsBeyondLine = endOfBounds < spanEnd
if (spanPrecedesLine && !spanExtendsBeyondLine) {
// pull back the end of the block span
BlockHandler.set(editableText, span, spanStart, startOfBounds)
} else if (spanExtendsBeyondLine && !spanPrecedesLine) {
// push the start of the block span
BlockHandler.set(editableText, span, endOfBounds, spanEnd)
} else if (spanPrecedesLine && spanExtendsBeyondLine) {
// we need to split the span into two parts
// first, let's pull back the end of the existing span
BlockHandler.set(editableText, span, spanStart, startOfBounds)
// now, let's "clone" the span and set it
BlockHandler.set(editableText, makeBlockSpan(span::class, textFormat, span.nestingLevel, span.attributes), endOfBounds, spanEnd)
} else {
// tough luck. The span is fully inside the line so it gets axed.
IAztecNestable.pullUp(editableText, editableText.getSpanStart(span), editableText.getSpanEnd(span), span.nestingLevel)
editableText.removeSpan(span)
}
}
}
}
// TODO: Come up with a better way to init spans and get their classes (all the "make" methods)
fun makeBlock(textFormat: ITextFormat, nestingLevel: Int, attrs: AztecAttributes = AztecAttributes()): List<IAztecBlockSpan> {
return when (textFormat) {
AztecTextFormat.FORMAT_ORDERED_LIST -> listOf(createOrderedListSpan(nestingLevel, alignmentRendering, attrs, listStyle), createListItemSpan(nestingLevel + 1, alignmentRendering))
AztecTextFormat.FORMAT_UNORDERED_LIST -> listOf(createUnorderedListSpan(nestingLevel, alignmentRendering, attrs, listStyle), createListItemSpan(nestingLevel + 1, alignmentRendering))
AztecTextFormat.FORMAT_TASK_LIST -> listOf(createTaskListSpan(nestingLevel, alignmentRendering, attrs, editor.context, listStyle), createListItemSpan(nestingLevel + 1, alignmentRendering, listItemStyle = listItemStyle))
AztecTextFormat.FORMAT_QUOTE -> listOf(createAztecQuoteSpan(nestingLevel, attrs, alignmentRendering, quoteStyle))
AztecTextFormat.FORMAT_HEADING_1,
AztecTextFormat.FORMAT_HEADING_2,
AztecTextFormat.FORMAT_HEADING_3,
AztecTextFormat.FORMAT_HEADING_4,
AztecTextFormat.FORMAT_HEADING_5,
AztecTextFormat.FORMAT_HEADING_6 -> listOf(createHeadingSpan(nestingLevel, textFormat, attrs, alignmentRendering, headerStyle))
AztecTextFormat.FORMAT_PREFORMAT -> listOf(createPreformatSpan(nestingLevel, alignmentRendering, attrs, preformatStyle))
else -> listOf(createParagraphSpan(nestingLevel, alignmentRendering, attrs, paragraphStyle))
}
}
fun getAlignment(textFormat: ITextFormat?, text: CharSequence): Layout.Alignment? {
val direction = TextDirectionHeuristicsCompat.FIRSTSTRONG_LTR
val isRtl = direction.isRtl(text, 0, text.length)
return when (textFormat) {
AztecTextFormat.FORMAT_ALIGN_LEFT -> if (!isRtl) Layout.Alignment.ALIGN_NORMAL else Layout.Alignment.ALIGN_OPPOSITE
AztecTextFormat.FORMAT_ALIGN_CENTER -> Layout.Alignment.ALIGN_CENTER
AztecTextFormat.FORMAT_ALIGN_RIGHT -> if (isRtl) Layout.Alignment.ALIGN_NORMAL else Layout.Alignment.ALIGN_OPPOSITE
else -> null
}
}
fun makeBlockSpan(textFormat: ITextFormat, nestingLevel: Int, attrs: AztecAttributes = AztecAttributes()): IAztecBlockSpan {
return when (textFormat) {
AztecTextFormat.FORMAT_ORDERED_LIST -> makeBlockSpan(AztecOrderedListSpan::class, textFormat, nestingLevel, attrs)
AztecTextFormat.FORMAT_UNORDERED_LIST -> makeBlockSpan(AztecUnorderedListSpan::class, textFormat, nestingLevel, attrs)
AztecTextFormat.FORMAT_TASK_LIST -> makeBlockSpan(AztecTaskListSpan::class, textFormat, nestingLevel, attrs)
AztecTextFormat.FORMAT_QUOTE -> makeBlockSpan(AztecQuoteSpan::class, textFormat, nestingLevel, attrs)
AztecTextFormat.FORMAT_HEADING_1,
AztecTextFormat.FORMAT_HEADING_2,
AztecTextFormat.FORMAT_HEADING_3,
AztecTextFormat.FORMAT_HEADING_4,
AztecTextFormat.FORMAT_HEADING_5,
AztecTextFormat.FORMAT_HEADING_6 -> makeBlockSpan(AztecHeadingSpan::class, textFormat, nestingLevel, attrs)
AztecTextFormat.FORMAT_PREFORMAT -> makeBlockSpan(AztecPreformatSpan::class, textFormat, nestingLevel, attrs)
else -> createParagraphSpan(nestingLevel, alignmentRendering, attrs, paragraphStyle)
}
}
private fun <T : KClass<out IAztecBlockSpan>> makeBlockSpan(type: T, textFormat: ITextFormat, nestingLevel: Int, attrs: AztecAttributes = AztecAttributes()): IAztecBlockSpan {
val typeIsAssignableTo = { clazz: KClass<out Any> -> clazz.java.isAssignableFrom(type.java) }
return when {
typeIsAssignableTo(AztecOrderedListSpan::class) -> createOrderedListSpan(nestingLevel, alignmentRendering, attrs, listStyle)
typeIsAssignableTo(AztecUnorderedListSpan::class) -> createUnorderedListSpan(nestingLevel, alignmentRendering, attrs, listStyle)
typeIsAssignableTo(AztecTaskListSpan::class) -> createTaskListSpan(nestingLevel, alignmentRendering, attrs, editor.context, listStyle)
typeIsAssignableTo(AztecListItemSpan::class) -> createListItemSpan(nestingLevel, alignmentRendering, attrs, listItemStyle)
typeIsAssignableTo(AztecQuoteSpan::class) -> createAztecQuoteSpan(nestingLevel, attrs, alignmentRendering, quoteStyle)
typeIsAssignableTo(AztecHeadingSpan::class) -> createHeadingSpan(nestingLevel, textFormat, attrs, alignmentRendering, headerStyle)
typeIsAssignableTo(AztecPreformatSpan::class) -> createPreformatSpan(nestingLevel, alignmentRendering, attrs, preformatStyle)
else -> createParagraphSpan(nestingLevel, alignmentRendering, attrs, paragraphStyle)
}
}
fun setBlockStyle(blockElement: IAztecBlockSpan) {
when (blockElement) {
is AztecOrderedListSpan -> blockElement.listStyle = listStyle
is AztecUnorderedListSpan -> blockElement.listStyle = listStyle
is AztecTaskListSpan -> blockElement.listStyle = listStyle
is AztecQuoteSpan -> blockElement.quoteStyle = quoteStyle
is ParagraphSpan -> blockElement.paragraphStyle = paragraphStyle
is AztecPreformatSpan -> blockElement.preformatStyle = preformatStyle
is AztecHeadingSpan -> blockElement.headerStyle = headerStyle
}
}
fun getTopBlockDelimiters(start: Int, end: Int): List<Int> {
val delimiters = arrayListOf(start, end)
val bounds = hashMapOf<Int, Int>()
val startNesting = IAztecNestable.getMinNestingLevelAt(editableText, start)
bounds[start] = startNesting
val endNesting = IAztecNestable.getMinNestingLevelAt(editableText, end)
bounds[end] = endNesting
val blockSpans = editableText.getSpans(start, end, IAztecBlockSpan::class.java)
.filter { editableText.getSpanStart(it) >= start && editableText.getSpanEnd(it) <= end }
.sortedBy { editableText.getSpanStart(it) }
blockSpans.forEach {
var spanIndex = editableText.getSpanStart(it)
var nesting = IAztecNestable.getMinNestingLevelAt(editableText, spanIndex)
bounds[spanIndex] = nesting
spanIndex = editableText.getSpanEnd(it)
nesting = IAztecNestable.getMinNestingLevelAt(editableText, spanIndex)
bounds[spanIndex] = nesting
if (it is IAztecCompositeBlockSpan) {
val wrapper = SpanWrapper(editableText, it)
val parent = IAztecNestable.getParent(editableText, wrapper)
parent?.let {
if (parent.start < start || parent.end > end) {
delimiters.add(wrapper.start)
delimiters.add(wrapper.end)
}
}
}
}
if (bounds.isNotEmpty()) {
var lastIndex: Int = bounds.keys.first()
bounds.keys.forEach { key ->
val last = checkBound(bounds, key, delimiters, lastIndex)
if (last > -1) {
lastIndex = last
}
}
lastIndex = bounds.keys.last()
bounds.keys.reversed().forEach { key ->
val last = checkBound(bounds, key, delimiters, lastIndex)
if (last > -1) {
lastIndex = last
}
}
}
return delimiters.distinct().sorted()
}
private fun checkBound(bounds: HashMap<Int, Int>, key: Int, delimiters: ArrayList<Int>, lastIndex: Int): Int {
if (bounds[key]!! != bounds[lastIndex]!!) {
if (bounds[key]!! < bounds[lastIndex]!!) {
delimiters.add(key)
return key
}
}
return -1
}
/**
* Returns paragraph bounds (\n) to the left and to the right of selection.
*/
fun getBoundsOfText(editable: Editable, selectionStart: Int, selectionEnd: Int): IntRange {
val startOfBlock: Int
val endOfBlock: Int
val selectionStartIsOnTheNewLine = selectionStart != selectionEnd && selectionStart > 0
&& selectionStart < editableText.length
&& editable[selectionStart] == '\n'
val selectionStartIsBetweenNewlines = selectionStartIsOnTheNewLine
&& selectionStart > 0
&& selectionStart < editableText.length
&& editable[selectionStart - 1] == '\n'
val isTrailingNewlineAtTheEndOfSelection = selectionStart != selectionEnd
&& selectionEnd > 0
&& editableText.length > selectionEnd
&& editableText[selectionEnd] != Constants.END_OF_BUFFER_MARKER
&& editableText[selectionEnd] != '\n'
&& editableText[selectionEnd - 1] == '\n'
val indexOfFirstLineBreak: Int
var indexOfLastLineBreak = editable.indexOf("\n", selectionEnd)
if (selectionStartIsBetweenNewlines) {
indexOfFirstLineBreak = selectionStart
} else if (selectionStartIsOnTheNewLine) {
val isSingleCharacterLine = (selectionStart > 1 && editableText[selectionStart - 1] != '\n' && editableText[selectionStart - 2] == '\n') || selectionStart == 1
indexOfFirstLineBreak = if (isSingleCharacterLine) {
selectionStart - 1
} else {
editable.lastIndexOf("\n", selectionStart - 1) + 1
}
if (isTrailingNewlineAtTheEndOfSelection) {
indexOfLastLineBreak = editable.indexOf("\n", selectionEnd - 1)
}
} else if (isTrailingNewlineAtTheEndOfSelection) {
indexOfFirstLineBreak = editable.lastIndexOf("\n", selectionStart - 1) + 1
indexOfLastLineBreak = editable.indexOf("\n", selectionEnd - 1)
} else if (indexOfLastLineBreak > 0) {
indexOfFirstLineBreak = editable.lastIndexOf("\n", selectionStart - 1) + 1
} else if (indexOfLastLineBreak == -1) {
indexOfFirstLineBreak = if (selectionStart == 0) 0 else {
editable.lastIndexOf("\n", selectionStart) + 1
}
} else {
indexOfFirstLineBreak = editable.lastIndexOf("\n", selectionStart)
}
startOfBlock = if (indexOfFirstLineBreak != -1) indexOfFirstLineBreak else 0
endOfBlock = if (indexOfLastLineBreak != -1) (indexOfLastLineBreak + 1) else editable.length
return IntRange(startOfBlock, endOfBlock)
}
fun applyTextAlignment(textFormat: ITextFormat, start: Int = selectionStart, end: Int = selectionEnd) {
if (editableText.isEmpty()) {
editableText.append("" + Constants.END_OF_BUFFER_MARKER)
}
val boundsOfSelectedText = getBoundsOfText(editableText, start, end)
var spans = getAlignedSpans(null, boundsOfSelectedText.first, boundsOfSelectedText.last)
if (start == end) {
if (start == boundsOfSelectedText.first && spans.size > 1) {
spans = spans.filter { editableText.getSpanEnd(it) != start }
} else if (start == boundsOfSelectedText.last && spans.size > 1) {
spans = spans.filter { editableText.getSpanStart(it) != start }
}
}
if (spans.isNotEmpty()) {
spans.filter { it !is AztecListSpan }.forEach { changeAlignment(it, textFormat) }
} else {
val nestingLevel = IAztecNestable.getNestingLevelAt(editableText, boundsOfSelectedText.first)
val alignment = getAlignment(textFormat,
editableText.subSequence(boundsOfSelectedText.first until boundsOfSelectedText.last))
editableText.setSpan(createParagraphSpan(nestingLevel, alignment, paragraphStyle = paragraphStyle),
boundsOfSelectedText.first, boundsOfSelectedText.last, Spanned.SPAN_PARAGRAPH)
}
}
private fun changeAlignment(it: IAztecAlignmentSpan, blockElementType: ITextFormat?) {
val wrapper = SpanWrapper(editableText, it)
it.align = getAlignment(blockElementType, editableText.substring(wrapper.start until wrapper.end))
editableText.setSpan(it, wrapper.start, wrapper.end, wrapper.flags)
}
fun applyBlockStyle(blockElementType: ITextFormat, start: Int = selectionStart, end: Int = selectionEnd) {
if (editableText.isEmpty()) {
editableText.append("" + Constants.END_OF_BUFFER_MARKER)
}
val boundsOfSelectedText = getBoundsOfText(editableText, start, end)
val nestingLevel = IAztecNestable.getNestingLevelAt(editableText, start) + 1
val spanToApply = makeBlockSpan(blockElementType, nestingLevel)
removeBlockStylesFromSelectedLine(spanToApply)
if (start != end) {
// we want to push line blocks as deep as possible, because they can't contain other block elements (e.g. headings)
if (spanToApply is IAztecLineBlockSpan) {
applyLineBlock(blockElementType, boundsOfSelectedText.first, boundsOfSelectedText.last)
} else {
val delimiters = getTopBlockDelimiters(boundsOfSelectedText.first, boundsOfSelectedText.last)
for (i in 0 until delimiters.size - 1) {
pushNewBlock(delimiters[i], delimiters[i + 1], blockElementType)
}
}
editor.setSelection(editor.selectionStart)
} else {
val startOfLine = boundsOfSelectedText.first
val endOfLine = boundsOfSelectedText.last
// we can't add blocks around partial block elements (i.e. list items), everything must go inside
val isWithinPartialBlock = editableText.getSpans(boundsOfSelectedText.first,
boundsOfSelectedText.last, IAztecCompositeBlockSpan::class.java)
.any { it.nestingLevel == nestingLevel - 1 }
val startOfBlock = mergeWithBlockAbove(startOfLine, endOfLine, spanToApply, nestingLevel, isWithinPartialBlock, blockElementType)
val endOfBlock = mergeWithBlockBelow(endOfLine, startOfBlock, spanToApply, nestingLevel, isWithinPartialBlock, blockElementType)
if (spanToApply is IAztecLineBlockSpan) {
applyBlock(spanToApply, startOfBlock, endOfBlock)
} else {
pushNewBlock(startOfBlock, endOfBlock, blockElementType)
}
}
editor.setSelection(editor.selectionStart, editor.selectionEnd)
}
private fun pushNewBlock(start: Int, end: Int, blockElementType: ITextFormat) {
var nesting = IAztecNestable.getMinNestingLevelAt(editableText, start, end) + 1
// we can't add blocks around composite block elements (i.e. list items), everything must go inside
val isListItem = editableText.getSpans(start, end, IAztecCompositeBlockSpan::class.java)
.any { it.nestingLevel == nesting }
if (isListItem) {
nesting++
}
val newBlock = makeBlockSpan(blockElementType, nesting)
val pushBy = if (newBlock is AztecListSpan) 2 else 1
val spans = IAztecNestable.pushDeeper(editableText, start, end, nesting, pushBy)
spans.forEach {
it.remove()
}
applyBlock(newBlock, start, end)
spans.forEach {
it.reapply()
}
}
private fun mergeWithBlockAbove(startOfLine: Int, endOfLine: Int, spanToApply: IAztecBlockSpan, nestingLevel: Int, isWithinList: Boolean, blockElementType: ITextFormat): Int {
var startOfBlock = startOfLine
if (startOfLine != 0) {
val spansOnPreviousLine = editableText.getSpans(startOfLine - 1, startOfLine - 1, spanToApply.javaClass)
.firstOrNull()
if (spansOnPreviousLine == null) {
// no similar blocks before us so, don't expand
} else if (spansOnPreviousLine.nestingLevel != nestingLevel) {
// other block is at a different nesting level so, don't expand
} else if (spansOnPreviousLine is AztecHeadingSpan && spanToApply is AztecHeadingSpan) {
// Heading span is of different style so, don't expand
} else if (!isWithinList) {
// expand the start
startOfBlock = editableText.getSpanStart(spansOnPreviousLine)
liftBlock(blockElementType, startOfBlock, endOfLine)
}
}
return startOfBlock
}
private fun mergeWithBlockBelow(endOfLine: Int, startOfBlock: Int, spanToApply: IAztecBlockSpan, nestingLevel: Int, isWithinList: Boolean, blockElementType: ITextFormat): Int {
var endOfBlock = endOfLine
if (endOfLine != editableText.length) {
val spanOnNextLine = editableText.getSpans(endOfLine + 1, endOfLine + 1, spanToApply.javaClass)
.firstOrNull()
if (spanOnNextLine == null) {
// no similar blocks after us so, don't expand
} else if (spanOnNextLine.nestingLevel != nestingLevel) {
// other block is at a different nesting level so, don't expand
} else if (spanOnNextLine is AztecHeadingSpan && spanToApply is AztecHeadingSpan) {
// Heading span is of different style so, don't expand
} else if (!isWithinList) {
// expand the end
endOfBlock = editableText.getSpanEnd(spanOnNextLine)
liftBlock(blockElementType, startOfBlock, endOfBlock)
}
}
return endOfBlock
}
private fun applyBlock(blockSpan: IAztecBlockSpan, start: Int, end: Int) {
when (blockSpan) {
is AztecOrderedListSpan -> applyListBlock(blockSpan, start, end)
is AztecUnorderedListSpan -> applyListBlock(blockSpan, start, end)
is AztecTaskListSpan -> applyListBlock(blockSpan, start, end)
is AztecQuoteSpan -> applyQuote(blockSpan, start, end)
is AztecHeadingSpan -> applyHeadingBlock(blockSpan, start, end)
is AztecPreformatSpan -> BlockHandler.set(editableText, blockSpan, start, end)
else -> editableText.setSpan(blockSpan, start, end, Spanned.SPAN_PARAGRAPH)
}
}
private fun applyQuote(blockSpan: AztecQuoteSpan, start: Int, end: Int) {
BlockHandler.set(editableText, blockSpan, start, end)
}
private fun applyListBlock(listSpan: AztecListSpan, start: Int, end: Int) {
BlockHandler.set(editableText, listSpan, start, end)
// special case for styling single empty lines
if (end - start == 1 && (editableText[end - 1] == '\n' || editableText[end - 1] == Constants.END_OF_BUFFER_MARKER)) {
ListItemHandler.newListItem(editableText, start, end, listSpan.nestingLevel + 1, alignmentRendering, listItemStyle)
} else {
val listEnd = if (end == editableText.length) end else end - 1
val listContent = editableText.substring(start, listEnd)
val lines = TextUtils.split(listContent, "\n")
for (i in lines.indices) {
val lineLength = lines[i].length
val lineStart = (0 until i).sumOf { lines[it].length + 1 }
val lineEnd = (lineStart + lineLength).let {
if ((start + it) != editableText.length) it + 1 else it // include the newline or not
}
ListItemHandler.newListItem(
editableText,
start + lineStart,
start + lineEnd,
listSpan.nestingLevel + 1,
alignmentRendering, listItemStyle)
}
}
}
private fun applyLineBlock(format: ITextFormat, start: Int, end: Int) {
val lines = TextUtils.split(editableText.substring(start, end), "\n")
for (i in lines.indices) {
val splitLength = lines[i].length
val lineStart = start + (0 until i).sumOf { lines[it].length + 1 }
val lineEnd = (lineStart + splitLength + 1).coerceAtMost(end) // +1 to include the newline
val lineLength = lineEnd - lineStart
if (lineLength == 0) continue
val nesting = IAztecNestable.getNestingLevelAt(editableText, lineStart) + 1
val block = makeBlockSpan(format, nesting)
applyBlock(block, lineStart, lineEnd)
}
}
private fun applyHeadingBlock(headingSpan: AztecHeadingSpan, start: Int, end: Int) {
val lines = TextUtils.split(editableText.substring(start, end), "\n")
for (i in lines.indices) {
val splitLength = lines[i].length
val lineStart = start + (0 until i).sumOf { lines[it].length + 1 }
val lineEnd = (lineStart + splitLength + 1).coerceAtMost(end) // +1 to include the newline
val lineLength = lineEnd - lineStart
if (lineLength == 0) continue
HeadingHandler.cloneHeading(editableText, headingSpan, alignmentRendering, lineStart, lineEnd)
}
}
private fun liftBlock(textFormat: ITextFormat, start: Int, end: Int) {
when (textFormat) {
AztecTextFormat.FORMAT_ORDERED_LIST -> liftListBlock(AztecOrderedListSpan::class.java, start, end)
AztecTextFormat.FORMAT_UNORDERED_LIST -> liftListBlock(AztecUnorderedListSpan::class.java, start, end)
AztecTextFormat.FORMAT_TASK_LIST -> liftListBlock(AztecTaskListSpan::class.java, start, end)
AztecTextFormat.FORMAT_QUOTE -> editableText.getSpans(start, end, AztecQuoteSpan::class.java).forEach {
IAztecNestable.pullUp(editableText, start, end, it.nestingLevel)
editableText.removeSpan(it)
}
else -> editableText.getSpans(start, end, ParagraphSpan::class.java).forEach {
IAztecNestable.pullUp(editableText, start, end, it.nestingLevel)
editableText.removeSpan(it)
}
}
}
private fun liftListBlock(listSpan: Class<out AztecListSpan>, start: Int, end: Int) {
editableText.getSpans(start, end, listSpan).forEach { it ->
val wrapper = SpanWrapper(editableText, it)
editableText.getSpans(wrapper.start, wrapper.end, AztecListItemSpan::class.java).forEach { editableText.removeSpan(it) }
IAztecNestable.pullUp(editableText, start, end, wrapper.span.nestingLevel)
wrapper.remove()
}
}
fun containsList(format: ITextFormat, selStart: Int = selectionStart, selEnd: Int = selectionEnd): Boolean {
val lines = TextUtils.split(editableText.toString(), "\n")
val list = ArrayList<Int>()
for (i in lines.indices) {
val lineStart = (0 until i).sumOf { lines[it].length + 1 }
val lineEnd = lineStart + lines[i].length
if (lineStart > lineEnd) {
continue
}
/**
* lineStart >= selStart && selEnd >= lineEnd // single line, current entirely selected OR
* multiple lines (before and/or after), current entirely selected
* lineStart <= selEnd && selEnd <= lineEnd // single line, current partially or entirely selected OR
* multiple lines (after), current partially or entirely selected
* lineStart <= selStart && selStart <= lineEnd // single line, current partially or entirely selected OR
* multiple lines (before), current partially or entirely selected
*/
if ((lineStart >= selStart && selEnd >= lineEnd)
|| (selEnd in lineStart..lineEnd)
|| (selStart in lineStart..lineEnd)) {
list.add(i)
}
}
if (list.isEmpty()) return false
return list.any { index ->
val listSpans = getBlockElement(index, editableText, AztecListSpan::class.java)
val maxNestingLevel = listSpans.maxByOrNull { span -> span.nestingLevel }?.nestingLevel
listSpans.filter { it.nestingLevel == maxNestingLevel }.any { listSpan ->
when (listSpan) {
is AztecUnorderedListSpan -> format == AztecTextFormat.FORMAT_UNORDERED_LIST
is AztecOrderedListSpan -> format == AztecTextFormat.FORMAT_ORDERED_LIST
is AztecTaskListSpan -> format == AztecTextFormat.FORMAT_TASK_LIST
else -> {
false
}
}
}
}
}
private fun <T> getBlockElement(index: Int, text: Editable, blockClass: Class<T>): List<T> {
val lines = TextUtils.split(text.toString(), "\n")
if (index < 0 || index >= lines.size) {
return emptyList()
}
val start = (0 until index).sumOf { lines[it].length + 1 }
val end = start + lines[index].length
if (start > end) {
return emptyList()
}
return editableText.getSpans(start, end, blockClass).toList()
}
fun containsQuote(selStart: Int = selectionStart, selEnd: Int = selectionEnd): Boolean {
if (selStart < 0 || selEnd < 0) return false
return editableText.getSpans(selStart, selEnd, AztecQuoteSpan::class.java)
.any {
val spanStart = editableText.getSpanStart(it)
val spanEnd = editableText.getSpanEnd(it)
if (selStart == selEnd) {
if (editableText.length == selStart) {
selStart in spanStart..spanEnd
} else {
(spanEnd != selStart) && selStart in spanStart..spanEnd
}
} else {
(selStart in spanStart..spanEnd || selEnd in spanStart..spanEnd) ||
(spanStart in selStart..selEnd || spanEnd in spanStart..spanEnd)
}
}
}
fun containsHeading(textFormat: ITextFormat, selStart: Int = selectionStart, selEnd: Int = selectionEnd): Boolean {
val lines = TextUtils.split(editableText.toString(), "\n")
val list = ArrayList<Int>()
for (i in lines.indices) {
val lineStart = (0 until i).sumOf { lines[it].length + 1 }
val lineEnd = lineStart + lines[i].length
if (lineStart >= lineEnd) {
continue
}
/**
* lineStart >= selStart && selEnd >= lineEnd // single line, current entirely selected OR
* multiple lines (before and/or after), current entirely selected
* lineStart <= selEnd && selEnd <= lineEnd // single line, current partially or entirely selected OR
* multiple lines (after), current partially or entirely selected
* lineStart <= selStart && selStart <= lineEnd // single line, current partially or entirely selected OR
* multiple lines (before), current partially or entirely selected
*/
if ((lineStart >= selStart && selEnd >= lineEnd)
|| (selEnd in lineStart..lineEnd)
|| (selStart in lineStart..lineEnd)) {
list.add(i)
}
}
if (list.isEmpty()) return false
return list.any { containHeadingType(textFormat, it) }
}
private fun containHeadingType(textFormat: ITextFormat, index: Int): Boolean {
val lines = TextUtils.split(editableText.toString(), "\n")
if (index < 0 || index >= lines.size) {
return false
}
val start = (0 until index).sumOf { lines[it].length + 1 }
val end = start + lines[index].length
if (start >= end) {
return false
}
val spans = editableText.getSpans(start, end, AztecHeadingSpan::class.java)
for (span in spans) {
return when (textFormat) {
AztecTextFormat.FORMAT_HEADING_1 ->
span.heading == AztecHeadingSpan.Heading.H1
AztecTextFormat.FORMAT_HEADING_2 ->
span.heading == AztecHeadingSpan.Heading.H2
AztecTextFormat.FORMAT_HEADING_3 ->
span.heading == AztecHeadingSpan.Heading.H3
AztecTextFormat.FORMAT_HEADING_4 ->
span.heading == AztecHeadingSpan.Heading.H4
AztecTextFormat.FORMAT_HEADING_5 ->
span.heading == AztecHeadingSpan.Heading.H5
AztecTextFormat.FORMAT_HEADING_6 ->
span.heading == AztecHeadingSpan.Heading.H6
else -> false
}
}
return false
}
fun containsOtherHeadings(textFormat: ITextFormat, selStart: Int = selectionStart, selEnd: Int = selectionEnd): Boolean {
arrayOf(AztecTextFormat.FORMAT_HEADING_1,
AztecTextFormat.FORMAT_HEADING_2,
AztecTextFormat.FORMAT_HEADING_3,
AztecTextFormat.FORMAT_HEADING_4,
AztecTextFormat.FORMAT_HEADING_5,
AztecTextFormat.FORMAT_HEADING_6,
AztecTextFormat.FORMAT_PREFORMAT)
.filter { it != textFormat }
.forEach {
if (containsHeading(it, selStart, selEnd)) {
return true
}
}
return false
}
fun containsHeadingOnly(textFormat: ITextFormat, selStart: Int = selectionStart, selEnd: Int = selectionEnd): Boolean {
val otherHeadings = arrayOf(
AztecTextFormat.FORMAT_HEADING_1,
AztecTextFormat.FORMAT_HEADING_2,
AztecTextFormat.FORMAT_HEADING_3,
AztecTextFormat.FORMAT_HEADING_4,
AztecTextFormat.FORMAT_HEADING_5,
AztecTextFormat.FORMAT_HEADING_6,
AztecTextFormat.FORMAT_PREFORMAT)
.filter { it != textFormat }
return containsHeading(textFormat, selStart, selEnd) && otherHeadings.none { containsHeading(it, selStart, selEnd) }
}
fun containsAlignment(textFormat: ITextFormat, selStart: Int = selectionStart, selEnd: Int = selectionEnd): Boolean {
return getAlignedSpans(textFormat, selStart, selEnd).isNotEmpty()
}
private fun getAlignedSpans(textFormat: ITextFormat?, selStart: Int = selectionStart, selEnd: Int = selectionEnd): List<IAztecAlignmentSpan> {
if (selStart < 0 || selEnd < 0) return emptyList()
return editableText.getSpans(selStart, selEnd, IAztecAlignmentSpan::class.java)
.filter {
textFormat == null || it.align == getAlignment(textFormat,
editableText.substring(editableText.getSpanStart(it) until editableText.getSpanEnd(it)))
}
.filter {
val spanStart = editableText.getSpanStart(it)
val spanEnd = editableText.getSpanEnd(it)
if (selStart == selEnd) {
if (editableText.length == selStart) {
selStart in spanStart..spanEnd
} else {
(spanEnd != selStart) && selStart in spanStart..spanEnd
}
} else {
(selStart in spanStart..spanEnd || selEnd in spanStart..spanEnd) ||
(spanStart in selStart..selEnd || spanEnd in selStart..selEnd)
}
}
}
fun containsPreformat(selStart: Int = selectionStart, selEnd: Int = selectionEnd): Boolean {
val lines = TextUtils.split(editableText.toString(), "\n")
val list = ArrayList<Int>()
for (i in lines.indices) {
val lineStart = (0 until i).sumOf { lines[it].length + 1 }
val lineEnd = lineStart + lines[i].length
if (lineStart > lineEnd) {
continue
}
if (lineStart <= selectionEnd && lineEnd >= selectionStart) {
list.add(i)
}
}
if (list.isEmpty()) return false
return list.any { containsPreformat(it) }
}
fun containsPreformat(index: Int): Boolean {
val lines = TextUtils.split(editableText.toString(), "\n")
if (index < 0 || index >= lines.size) {
return false
}
val start = (0 until index).sumOf { lines[it].length + 1 }
val end = start + lines[index].length
if (start > end) {
return false
}
val spans = editableText.getSpans(start, end, AztecPreformatSpan::class.java)
return spans.any {
val spanEnd = editableText.getSpanEnd(it)
spanEnd != start || editableText[spanEnd] != '\n'
}
}
private fun switchListType(listTypeToSwitchTo: ITextFormat, start: Int = selectionStart, end: Int = selectionEnd, attrs: AztecAttributes = AztecAttributes()) {
var spans = editableText.getSpans(start, end, AztecListSpan::class.java)
val maxNestingLevel = spans.maxByOrNull { it.nestingLevel }?.nestingLevel
if (start == end && spans.filter { it.nestingLevel == maxNestingLevel }.size > 1) {
spans = spans.filter { editableText.getSpanStart(it) == start }.toTypedArray()
}
val maxSpanStart = spans.map { editableText.getSpanStart(it) }.filter {
it <= selectionStart
}.maxByOrNull { it } ?: selectionStart
spans.filter { editableText.getSpanStart(it) >= maxSpanStart }.forEach { existingListSpan ->
if (existingListSpan != null) {
val spanStart = editableText.getSpanStart(existingListSpan)
val spanEnd = editableText.getSpanEnd(existingListSpan)
val spanFlags = editableText.getSpanFlags(existingListSpan)
editableText.removeSpan(existingListSpan)
cleanupTaskItems(existingListSpan, listTypeToSwitchTo, spanStart, spanEnd)
editableText.setSpan(makeBlockSpan(listTypeToSwitchTo, existingListSpan.nestingLevel, attrs), spanStart, spanEnd, spanFlags)
editor.onSelectionChanged(start, end)
}
}
}
private fun cleanupTaskItems(existingListSpan: AztecListSpan?, listTypeToSwitchTo: ITextFormat, spanStart: Int, spanEnd: Int) {
val isTaskListSpan = existingListSpan is AztecTaskListSpan
val isSwitchingToTaskListSpan = listTypeToSwitchTo == AztecTextFormat.FORMAT_TASK_LIST
editableText.getSpans(spanStart, spanEnd, AztecListItemSpan::class.java).forEach {
if (isTaskListSpan) {
it.attributes.removeAttribute(AztecListItemSpan.CHECKED)
} else if (isSwitchingToTaskListSpan) {
it.attributes.setValue(AztecListItemSpan.CHECKED, "false")
}
}
}
fun switchHeaderType(headerTypeToSwitchTo: ITextFormat, start: Int = selectionStart, end: Int = selectionEnd) {
var spans = editableText.getSpans(start, end, AztecHeadingSpan::class.java)
if (start == end && spans.size > 1) {
spans = spans.filter { editableText.getSpanStart(it) == start }.toTypedArray()
}
spans.forEach { existingHeaderSpan ->
if (existingHeaderSpan != null) {
val spanStart = editableText.getSpanStart(existingHeaderSpan)
val spanEnd = editableText.getSpanEnd(existingHeaderSpan)
val spanFlags = editableText.getSpanFlags(existingHeaderSpan)
existingHeaderSpan.textFormat = headerTypeToSwitchTo
editableText.setSpan(existingHeaderSpan, spanStart, spanEnd, spanFlags)
editor.onSelectionChanged(start, end)
}
}
}
fun switchHeadingToPreformat(start: Int = selectionStart, end: Int = selectionEnd) {
var spans = editableText.getSpans(start, end, AztecHeadingSpan::class.java)
if (start == end && spans.size > 1) {
spans = spans.filter { editableText.getSpanStart(it) == start }.toTypedArray()
}
spans.forEach { heading ->
if (heading != null) {
val spanStart = editableText.getSpanStart(heading)
val spanEnd = editableText.getSpanEnd(heading)
val spanFlags = editableText.getSpanFlags(heading)
val spanType = makeBlock(heading.textFormat, 0).map { it.javaClass }
removeBlockStyle(heading.textFormat, spanStart, spanEnd, spanType)
editableText.setSpan(AztecPreformatSpan(heading.nestingLevel, heading.attributes, preformatStyle), spanStart, spanEnd, spanFlags)
editor.onSelectionChanged(start, end)
}
}
}
fun switchPreformatToHeading(headingTextFormat: ITextFormat, start: Int = selectionStart, end: Int = selectionEnd) {
var spans = editableText.getSpans(start, end, AztecPreformatSpan::class.java)
if (start == end && spans.size > 1) {
spans = spans.filter { editableText.getSpanStart(it) == start }.toTypedArray()
}
spans.forEach { preformat ->
if (preformat != null) {
val spanStart = editableText.getSpanStart(preformat)
val spanEnd = editableText.getSpanEnd(preformat)
val spanFlags = editableText.getSpanFlags(preformat)
val spanType = makeBlock(AztecTextFormat.FORMAT_PREFORMAT, 0).map { it.javaClass }
removeBlockStyle(AztecTextFormat.FORMAT_PREFORMAT, spanStart, spanEnd, spanType)
val headingSpan = createHeadingSpan(
preformat.nestingLevel,
headingTextFormat,
preformat.attributes,
alignmentRendering)
editableText.setSpan(headingSpan, spanStart, spanEnd, spanFlags)
editor.onSelectionChanged(start, end)
}
}
}
}
| mpl-2.0 |
CruGlobal/android-gto-support | gto-support-fluidsonic-locale/src/jsMain/kotlin/org/ccci/gto/support/fluidsonic/locale/PlatformLocale.js.kt | 1 | 335 | package org.ccci.gto.support.fluidsonic.locale
import io.fluidsonic.locale.Intl
import io.fluidsonic.locale.Locale
import io.fluidsonic.locale.toCommon
import io.fluidsonic.locale.toPlatform
actual typealias PlatformLocale = Intl.Locale
actual fun Locale.toPlatform() = toPlatform()
actual fun PlatformLocale.toCommon() = toCommon()
| mit |
bazelbuild/rules_kotlin | src/test/kotlin/io/bazel/kotlin/builder/utils/ArgMapTest.kt | 1 | 2165 | /*
* Copyright 2020 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.bazel.kotlin.builder.utils
import com.google.common.truth.Truth
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class ArgMapTest {
@Test
fun optionalSingleIfExistsDespiteCondition() {
val key = object : Flag {
override val flag = "mirror mirror"
}
val value = listOf("on the wall")
val args = ArgMap(mapOf(Pair(key.flag, value)))
Truth.assertThat(args.optionalSingleIf(key) { false }).isEqualTo(value[0])
Truth.assertThat(args.optionalSingleIf(key) { true }).isEqualTo(value[0])
}
@Test
fun optionalSingleIfMandatoryOnConditionFalse() {
val key = object : Flag {
override val flag = "mirror mirror"
}
val args = ArgMap(mapOf())
Assert.assertThrows("Option is mandatory when condition is false",
IllegalArgumentException::class.java) {
args.optionalSingleIf(key) { false }
}
Truth.assertThat(args.optionalSingleIf(key) { true }).isNull();
}
@Test
fun hasAll() {
val empty = object : Flag {
override val flag = "pessimist"
}
val full = object : Flag {
override val flag = "optimist"
}
val args = ArgMap(mapOf(
Pair(empty.flag, emptyList()),
Pair(full.flag, listOf("half"))
))
Truth.assertThat(args.hasAll(full)).isTrue()
Truth.assertThat(args.hasAll(empty, full)).isFalse()
Truth.assertThat(args.hasAll(object : Flag {
override val flag = "immaterial"
})).isFalse()
}
}
| apache-2.0 |
CoderLine/alphaTab | src.kotlin/alphaTab/alphaTab/src/androidMain/kotlin/alphaTab/platform/android/SuspendableScrollView.kt | 1 | 845 | package alphaTab.platform.android
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.ScrollView
internal class SuspendableScrollView(context: Context, attributeSet: AttributeSet) :
ScrollView(context, attributeSet) {
public var isUserScrollingEnabled = true
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(ev: MotionEvent): Boolean {
return when (ev.action) {
MotionEvent.ACTION_DOWN ->
isUserScrollingEnabled && super.onTouchEvent(ev)
else ->
super.onTouchEvent(ev)
}
}
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
return isUserScrollingEnabled && super.onInterceptTouchEvent(ev)
}
}
| mpl-2.0 |
revbingo/SPIFF | src/main/java/com/revbingo/spiff/events/EventListeners.kt | 1 | 2980 | package com.revbingo.spiff.events
import com.revbingo.spiff.ExecutionException
import com.revbingo.spiff.datatypes.Datatype
import java.util.*
interface EventListener {
fun notifyData(ins: Datatype)
fun notifyGroup(groupName: String, start: Boolean)
}
class ClassBindingEventListener<T>(val clazz:Class<T>): EventListener {
private val rootBinding: T
private var currentBinding: Any
private val bindingStack: Stack<Any> = Stack()
private val bindingFactory = BindingFactory()
private var skipCount = 0
var skipUnboundGroups = false
var isStrict = true
init {
try {
rootBinding = clazz.newInstance()
currentBinding = rootBinding as Any
} catch (e: InstantiationException) {
throw ExecutionException("Could not instantiate ${clazz.getCanonicalName()}", e);
} catch (e: IllegalAccessException) {
throw ExecutionException("Could not access ${clazz.getCanonicalName()}", e);
}
}
override fun notifyData(ins: Datatype) {
if(skipUnboundGroups && skipCount > 0) return
val binder = bindingFactory.getBindingFor(ins.name, currentBinding.javaClass)
if(binder != null) {
binder.bind(currentBinding, ins.value)
} else {
if(isStrict) throw ExecutionException("Could not get binding for instruction ${ins.name}")
}
}
override fun notifyGroup(groupName: String, start: Boolean) {
if(start) {
bindingStack.push(currentBinding)
val binder = bindingFactory.getBindingFor(groupName, currentBinding.javaClass)
if(binder != null) {
currentBinding = binder.createAndBind(currentBinding)
} else {
if(isStrict) {
throw ExecutionException("Cound not get binding for group ${groupName}")
} else {
if(skipUnboundGroups) skipCount++
}
}
} else {
if(skipUnboundGroups && skipCount > 0) skipCount--
currentBinding = bindingStack.pop()
}
}
fun getResult(): T = rootBinding
}
class DebugEventListener(val wrappedListener: EventListener): EventListener {
var tabCount = 0
constructor(): this(object: EventListener {
override fun notifyData(ins: Datatype) { }
override fun notifyGroup(groupName: String, start: Boolean) {}
})
override fun notifyData(ins: Datatype) {
repeat(tabCount, { print("\t") })
println("[${ins.name}] ${ins.value}")
wrappedListener.notifyData(ins)
}
override fun notifyGroup(groupName: String, start: Boolean) {
if(!start) {
tabCount--
}
repeat(tabCount, { print("\t") })
val leader = if(start) ">>" else "<<"
println("${leader} [$groupName]")
if(start) tabCount++
wrappedListener.notifyGroup(groupName, start)
}
} | mit |
Zeyad-37/GenericUseCase | sampleApp/src/main/java/com/zeyad/usecases/app/components/VerticalDividerItemDecoration.kt | 2 | 1630 | package com.zeyad.usecases.app.components
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.View
class VerticalDividerItemDecoration : RecyclerView.ItemDecoration {
private val mDivider: Drawable?
/**
* Default divider will be used
*/
constructor(context: Context) {
val styledAttributes = context.obtainStyledAttributes(ATTRS)
mDivider = styledAttributes.getDrawable(0)
styledAttributes.recycle()
}
/**
* Custom divider will be used
*/
constructor(context: Context, resId: Int) {
mDivider = ContextCompat.getDrawable(context, resId)
}
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
val childCount = parent.childCount
for (i in 0 until childCount) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin
val bottom = top + mDivider!!.intrinsicHeight
mDivider.setBounds(parent.paddingLeft, top, parent.width - parent.paddingRight,
bottom)
mDivider.draw(c)
}
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
outRect.bottom = 1
}
companion object {
private val ATTRS = intArrayOf(android.R.attr.listDivider)
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.