repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
KentVu/vietnamese-t9-ime | lib/src/main/java/com/vutrankien/t9vietnamese/lib/TrieDb.kt | 1 | 2321 | package com.vutrankien.t9vietnamese.lib
import kentvu.dawgjava.DawgTrie
import kentvu.dawgjava.Trie
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
class TrieDb(
lg: LogFactory,
private val env: Env,
dawgFile: String = "T9Engine.dawg",
/** set `true` to force recreate dawgFile. */
private val overwriteDawgFile: Boolean = false
) : Db {
companion object {
private const val DEFAULT_REPORT_PROGRESS_INTERVAL = 10
}
private val dawgPath = "${env.workingDir}/$dawgFile"
private val log = lg.newLog("TrieDb")
private lateinit var trie: Trie
override var initialized: Boolean = false
private set
private fun canReuse(): Boolean {
env.fileExists(dawgPath).let {
log.d("canReuseDb: $it")
return it
}
}
/**
* Init from built db.
* Visible for test only.
*/
fun load() {
log.d("load")
trie = DawgTrie.load(dawgPath)
}
override fun search(prefix: String): Map<String, Int> = trie.search(prefix)/*.also {
log.v("search:$prefix:return $it")
}*/
override suspend fun initOrLoad(
seed: Seed,
onBytes: suspend (Int) -> Unit
) {
if (overwriteDawgFile || !canReuse()) {
log.i("init: initialized=$initialized from seed")
init(seed, onBytes)
} else {
log.d("init: initialized=$initialized,canReuse -> load")
load()
}
initialized = true
}
suspend fun init(
seed: Seed,
onBytes: suspend (Int) -> Unit
) {
coroutineScope {
log.d("load")
val channel = Channel<Int>()
launch (Dispatchers.IO) {
trie = DawgTrie.build(dawgPath, seed.sequence(), channel)
}
var markPos = 0
val count = 0
for (bytes in channel) {
if (count - markPos == DEFAULT_REPORT_PROGRESS_INTERVAL) {
onBytes.invoke(bytes)
//print("progress $count/${sortedWords.size}: ${bytes.toFloat() / size * 100}%\r")
markPos = count
}
}
}
}
} | gpl-3.0 | ae8ce23d9a4d9442bbb5dbfd15ba0a9f | 27.317073 | 102 | 0.560534 | 4.050611 | false | false | false | false |
msebire/intellij-community | plugins/github/src/org/jetbrains/plugins/github/util/GithubUIUtil.kt | 1 | 2084 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.util
import com.intellij.ui.ColorUtil
import com.intellij.ui.JBColor
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.UIUtil
import org.jetbrains.plugins.github.api.data.GithubIssueLabel
import java.awt.Color
import javax.swing.JList
object GithubUIUtil {
object List {
object WithTallRow {
private val selectionBackground = JBColor(0xE9EEF5, 0x464A4D)
private val unfocusedSelectionBackground = JBColor(0xF5F5F5, 0x464A4D)
fun foreground(list: JList<*>, isSelected: Boolean): Color {
val default = UIUtil.getListForeground()
return if (isSelected) {
if (list.hasFocus()) JBColor.namedColor("Table.lightSelectionForeground", default)
else JBColor.namedColor("Table.lightSelectionInactiveForeground", default)
}
else JBColor.namedColor("Table.foreground", default)
}
fun secondaryForeground(list: JList<*>, isSelected: Boolean): Color {
return if (isSelected) {
foreground(list, true)
}
else JBColor.namedColor("Component.infoForeground", UIUtil.getContextHelpForeground())
}
fun background(list: JList<*>, isSelected: Boolean): Color {
return if (isSelected) {
if (list.hasFocus()) JBColor.namedColor("Table.lightSelectionBackground", selectionBackground)
else JBColor.namedColor("Table.lightSelectionInactiveBackground", unfocusedSelectionBackground)
}
else list.background
}
}
}
fun createIssueLabelLabel(label: GithubIssueLabel): JBLabel = JBLabel(" ${label.name} ", UIUtil.ComponentStyle.MINI).apply {
val apiColor = ColorUtil.fromHex(label.color)
background = JBColor(apiColor, ColorUtil.darker(apiColor, 3))
foreground = computeForeground(background)
}.andOpaque()
private fun computeForeground(bg: Color) = if (ColorUtil.isDark(bg)) Color.white else Color.black
} | apache-2.0 | e7e321bb77b4f88172747fe5d1bb7c71 | 39.882353 | 140 | 0.71881 | 4.387368 | false | false | false | false |
vitoling/HiWeather | src/main/kotlin/com/vito/work/weather/config/Enums.kt | 1 | 639 | package com.vito.work.weather.config
/**
* Created by lingzhiyuan.
* Date : 16/4/17.
* Time : 下午5:02.
* Description:
*
*/
enum class AQIPrimaryType(val code: Int, val name_1: String, val name_2: String = "NONE") {
PM25(1, "PM2.5", "P2.5"),
PM10(2, "PM10", "P10"),
O3(3, "臭氧"),
SO2(4, "二氧化硫"),
NO2(5, "二氧化氮"),
CO(6, "一氧化碳"),
UNKNOWN(10, "无", "暂无数据");
}
fun getAQITypeCodeByName(name: String): AQIPrimaryType {
return AQIPrimaryType.values().firstOrNull { it -> it.name_1 == name.trim() || it.name_2 == name.trim() }
?: AQIPrimaryType.UNKNOWN
} | gpl-3.0 | 44519b8ab418cf2a070389c5d7cefe56 | 21.148148 | 109 | 0.582915 | 2.446721 | false | false | false | false |
google/kiosk-app-reference-implementation | app/src/main/java/com/ape/apps/sample/baypilot/ui/home/HomeActivity.kt | 1 | 7367 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ape.apps.sample.baypilot.ui.home
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.ape.apps.sample.baypilot.R
import com.ape.apps.sample.baypilot.data.creditplan.CreditPlanInfo
import com.ape.apps.sample.baypilot.data.sharedprefs.SharedPreferencesManager
import com.ape.apps.sample.baypilot.databinding.ActivityHomeBinding
import com.ape.apps.sample.baypilot.util.date.DateTimeHelper
import com.ape.apps.sample.baypilot.util.extension.setTint
import com.ape.apps.sample.baypilot.util.network.InternetConnectivity
import com.ape.apps.sample.baypilot.util.network.InternetStatus
import com.ape.apps.sample.baypilot.util.worker.DatabaseSyncWorker
class HomeActivity : AppCompatActivity() {
companion object {
private const val TAG = "BayPilotHomeActivity"
}
private lateinit var binding: ActivityHomeBinding
private val viewModel: HomeViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
Log.d(TAG, "onCreate() called with: savedInstanceState")
super.onCreate(savedInstanceState)
binding = ActivityHomeBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.buttonSettings.setOnClickListener {
startActivity(Intent(Settings.ACTION_SETTINGS))
}
binding.buttonInternetSetting.setOnClickListener {
startActivity(Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY))
}
binding.buttonMakeACall.setOnClickListener {
startActivity(Intent(Intent.ACTION_DIAL))
}
binding.buttonRefresh.setOnClickListener {
// Check is device is online.
if (InternetConnectivity.isConnectedToInternet(applicationContext)) {
// Schedule Database Sync using WorkManager
DatabaseSyncWorker.scheduleSync(applicationContext)
} else {
// Display message to connect to internet for refresh.
Toast.makeText(
baseContext, R.string.connect_to_internet_welcome,
Toast.LENGTH_SHORT
).show()
}
}
// Observe changes to credit plan details stored in device locally in sharedPreferences.
viewModel.creditPlanInfo.observe(this) {
updateUI(it)
}
viewModel.observeCreditPlanInfo(applicationContext)
InternetConnectivity(this@HomeActivity).observe(this) {
binding.buttonInternetSetting.isVisible = it == InternetStatus.OFFLINE
binding.textViewInternetStatus.isVisible = it == InternetStatus.OFFLINE
}
}
// Update UI accordingly to LOCK status of device.
private fun updateUI(creditPlanInfo: CreditPlanInfo?) {
Log.d(TAG, "updateUI() called with: creditPlanInfo = $creditPlanInfo")
binding.relativeDeviceReleased.isVisible = false
binding.relativeLayoutLoading.isVisible = false
binding.relativeLayoutMissingImei.isVisible = false
val sharedPreferencesManager = SharedPreferencesManager(applicationContext)
if (sharedPreferencesManager.isDeviceReleased()) {
Log.d(TAG, "updateUI() called with: sharedPreferencesManager.isDeviceReleased() = true")
binding.relativeDeviceReleased.isVisible = true
return
}
if (sharedPreferencesManager.isCreditPlanSaved().not()) {
Log.d(TAG, "updateUI() called with: sharedPreferencesManager.isCreditPlanSaved() = false")
binding.relativeLayoutLoading.isVisible = true
return
}
if (sharedPreferencesManager.isValidCreditPlan().not()) {
Log.d(TAG, "updateUI() called with: sharedPreferencesManager.isValidCreditPlan() = false")
binding.relativeLayoutMissingImei.isVisible = true
return
}
if (creditPlanInfo == null) {
Log.d(TAG, "updateUI() called with: creditPlanInfo = null. Returning")
return
}
// Get Credit Plan details.
val totalAmount = creditPlanInfo.totalAmount ?: 0
val nextDueAmount = creditPlanInfo.nextDueAmount ?: 0
val totalPaidAmount: Int = creditPlanInfo.totalPaidAmount ?: 0
val totalDueAmount: Int = totalAmount - totalPaidAmount
// Populate Ui components with credit plan details.
binding.textViewTotalCost.text = getString(R.string.total_cost, totalAmount)
binding.textViewPaid.text = getString(R.string.paid_so_far, totalPaidAmount)
binding.textViewRemaining.text = getString(R.string.remaining, (totalAmount - totalPaidAmount))
binding.progressIndicatorOwedNow.progress = (totalDueAmount.toDouble() / totalAmount.toDouble() * 100).toInt()
binding.progressIndicatorPaid.progress = (totalPaidAmount.toDouble() / totalAmount.toDouble() * 100).toInt()
// Get next due date.
val dueDateTime = DateTimeHelper.getDeviceZonedDueDateTime(creditPlanInfo.dueDate ?: "")
val timeLeft = DateTimeHelper.getTimeDiff(applicationContext, dueDateTime)
// Get formatted due date to display in UI.
val formattedDueDateTime = DateTimeHelper.formattedDateTime(dueDateTime)
// Device must be unlocked if due date is in future.
if (DateTimeHelper.isInFuture(dueDateTime)) {
// Show unlocked device UI
unlockUI(nextDueAmount, timeLeft, formattedDueDateTime)
} else {
// Show locked device UI
lockUI(nextDueAmount, timeLeft, formattedDueDateTime)
}
}
private fun unlockUI(nextDueAmount: Int, remainingTime: String, formattedDate: String) {
binding.textViewNextPayment.text = getString(R.string.installment_due_on, nextDueAmount, formattedDate)
binding.textViewPaymentDue.text = getString(R.string.due_in, nextDueAmount, remainingTime)
// If due date is in less than an hour set background color to red.
if (remainingTime == "0 hours") {
binding.frameLayoutPaymentDue.setBackgroundColor(ContextCompat.getColor(this@HomeActivity, R.color.red))
} else {
binding.frameLayoutPaymentDue.setBackgroundColor(ContextCompat.getColor(this@HomeActivity, R.color.green))
}
binding.imageViewDeviceStatus.setTint(R.color.green)
binding.textViewDeviceStatus.text = getString(R.string.device_unlocked)
}
private fun lockUI(nextDueAmount: Int, remainingTime: String, formattedDate: String) {
binding.textViewNextPayment.text = getString(R.string.installment_was_due_on, nextDueAmount, formattedDate)
binding.textViewPaymentDue.text = getString(R.string.overdue_by, nextDueAmount, remainingTime)
binding.frameLayoutPaymentDue.setBackgroundColor(ContextCompat.getColor(this@HomeActivity, R.color.red))
binding.imageViewDeviceStatus.setTint(R.color.red)
binding.textViewDeviceStatus.text = getString(R.string.device_locked_payment_overdue)
}
} | apache-2.0 | 9316effff757b2075a3c35896d74b367 | 39.707182 | 114 | 0.756482 | 4.379905 | false | false | false | false |
gmarques33/anvil | buildSrc/src/main/kotlin/trikita/anvilgen/AnvilGenPlugin.kt | 1 | 5842 | package trikita.anvilgen
import com.squareup.javapoet.ClassName
import groovy.lang.Closure
import org.gradle.api.Plugin
import org.gradle.api.Project
import java.io.File
import java.util.*
class AnvilGenPlugin : Plugin<Project> {
override fun apply(project: Project) {
// Add the 'anvilgen' extension object
project.extensions.create("anvilgen", AnvilGenPluginExtension::class.java)
project.afterEvaluate { generateTasks(it) }
}
fun generateTasks(project: Project) {
val extension = project.extensions.getByName("anvilgen") as AnvilGenPluginExtension
val type = extension.type
if (type == "sdk") {
// Most practical API versions according to Android Dashboards:
// - newer than API level 15 (ICS 4.0.3, 97.3% of devices)
// - newer than API level 19 (KK 4.0.3, 72.7% of devices)
// - newer than API level 21 (LP 5.0, 38.4% of devices)
project.task(mapOf("type" to DSLGeneratorTask::class.java), "generateSDK21DSL", getSDKClosure(project, 21))
project.task(mapOf("type" to DSLGeneratorTask::class.java), "generateSDK19DSL", getSDKClosure(project, 19))
project.task(mapOf("type" to DSLGeneratorTask::class.java), "generateSDK15DSL", getSDKClosure(project, 15))
project.task(mapOf("dependsOn" to arrayOf("generateSDK15DSL", "generateSDK19DSL", "generateSDK21DSL")), "generateSDKDSL")
} else {
val supportClosure = getSupportClosure(project, extension.camelCaseName,
extension.libraryName, extension.version, extension.superclass, extension.dependencies)
project.task(mapOf("type" to DSLGeneratorTask::class.java, "dependsOn" to listOf("prepareReleaseDependencies")),
"generate${extension.camelCaseName}DSL",
supportClosure)
}
}
fun getSDKClosure(project: Project, apiLevel: Int): Closure<Any> {
return object : Closure<Any>(this) {
init {
maximumNumberOfParameters = 1
}
override fun call(arguments: Any?): Any? {
(arguments as DSLGeneratorTask).apply {
taskName = "generateSDK${apiLevel}DSL"
javadocContains = "It contains views and their setters from API level $apiLevel"
outputDirectory = "sdk$apiLevel"
jarFile = getAndroidJar(project, apiLevel)
dependencies = listOf()
outputClassName = "DSL"
packageName = "trikita.anvil"
superclass = ClassName.get("trikita.anvil", "BaseDSL")
}
return null
}
}
}
fun getSupportClosure(project: Project,
camelCaseName: String,
libraryName: String,
version: String,
superclassName: String,
rawDeps: Map<String, List<String?>>): Closure<Any> {
return object : Closure<Any>(this) {
init {
maximumNumberOfParameters = 1
}
override fun call(arguments: Any?): Any? {
(arguments as DSLGeneratorTask).apply {
taskName = "generate${camelCaseName}DSL"
javadocContains = "It contains views and their setters from the library $libraryName"
outputDirectory = "main"
jarFile = getSupportJar(project, libraryName, version)
dependencies = getSupportDependencies(project, version, rawDeps)
outputClassName = "${camelCaseName}DSL"
packageName = "trikita.anvil." + dashToDot(libraryName)
if (superclassName.isNotEmpty()) {
superclass = ClassName.get(packageName, superclassName)
}
}
return null
}
}
}
fun dashToDot(libraryName: String?): String {
if (libraryName == null || libraryName.isBlank()) {
return ""
}
return libraryName.replace('-', '.')
}
fun getSupportDependencies(project: Project, version: String, rawDeps: Map<String, List<String?>>): List<File> {
val list = rawDeps.flatMap { entry ->
entry.value.map {
getInternalSupportJar(project, entry.key, version, it ?: "classes")
}
}
val arrayList = ArrayList(list)
arrayList.add(getAndroidJar(project, 19))
return arrayList
}
fun getAndroidJar(project: Project, api: Int): File {
val rootDir = project.rootDir
val localProperties = File(rootDir, "local.properties")
val sdkDir: String
if (localProperties.exists()) {
val properties = Properties()
localProperties.inputStream().use { properties.load(it) }
sdkDir = properties.getProperty("sdk.dir")
} else {
sdkDir = System.getenv("ANDROID_HOME")
}
return File("$sdkDir/platforms/android-$api/android.jar")
}
fun getSupportJar(project: Project, libraryName: String, version: String): File {
return File(project.buildDir.absoluteFile,
"intermediates/exploded-aar/com.android.support/$libraryName/$version/jars/classes.jar")
}
fun getInternalSupportJar(project: Project,
libraryName: String,
version: String,
internalJar: String): File {
return File(project.buildDir.absoluteFile,
"intermediates/exploded-aar/com.android.support/$libraryName/$version/jars/$internalJar.jar")
}
} | mit | 88098b1b29aa00c8ff33c96ce9774e20 | 41.035971 | 133 | 0.580452 | 4.917508 | false | false | false | false |
yujintao529/android_practice | MyPractice/app/src/main/java/com/demon/yu/view/recyclerview/FakeLayoutCoorExchangeUtils.kt | 1 | 1489 | package com.demon.yu.view.recyclerview
import android.graphics.Point
import android.view.View
object FakeLayoutCoorExchangeUtils {
fun shiftingLayout(
view: View,
positionCenterPoint: Point,
block: (left: Int, top: Int) -> Unit
) {
if (view is IFakeLayoutView) {
val left = positionCenterPoint.x - view.measuredWidth / 2
val top = positionCenterPoint.y - view.measuredHeight / 2
block(left, top - view.getFakeTop() / 2)
} else {
block.invoke(
positionCenterPoint.x - view.measuredWidth / 2,
positionCenterPoint.y - view.measuredHeight / 2
)
}
}
fun setCenterPivot(view: View) {
if (view is IFakeLayoutView) {
view.pivotX = (view.getFakeLeft() + view.getFakeWidth() / 2).toFloat()
view.pivotY = (view.getFakeTop() + view.getFakeHeight() / 2).toFloat()
} else {
view.pivotX = (view.width / 2).toFloat()
view.pivotY = (view.height / 2).toFloat()
}
}
fun getFakeWidth(view: IFakeLayoutView): Int {
return view.getFakeWidth()
}
fun getFakeHeight(view: IFakeLayoutView): Int {
return view.getFakeHeight()
}
fun getCenterPoint(
view: View,
): Point {
if (view is IFakeLayoutView) {
return view.getCenterPoint()
} else {
return view.getCenterPoint()
}
}
} | apache-2.0 | 9ca2a497327366bfdda0abc902634094 | 26.090909 | 82 | 0.568167 | 4.03523 | false | false | false | false |
WijayaPrinting/wp-javafx | openpss-client-javafx/src/com/hendraanggrian/openpss/ui/main/ChangePasswordDialog.kt | 1 | 1703 | package com.hendraanggrian.openpss.ui.main
import com.hendraanggrian.openpss.FxComponent
import com.hendraanggrian.openpss.R
import com.hendraanggrian.openpss.R2
import com.hendraanggrian.openpss.ui.ResultableDialog
import javafx.scene.Node
import javafx.scene.control.PasswordField
import ktfx.controls.gap
import ktfx.jfoenix.layouts.jfxPasswordField
import ktfx.layouts.gridPane
import ktfx.layouts.label
import ktfx.neq
import ktfx.or
import ktfx.toBooleanBinding
class ChangePasswordDialog(component: FxComponent) : ResultableDialog<String>(component, R2.string.change_password) {
private val changePasswordField: PasswordField
private val confirmPasswordField: PasswordField
override val focusedNode: Node? get() = changePasswordField
init {
gridPane {
gap = getDouble(R.value.padding_medium)
label { text = getString(R2.string._change_password) } col (0 to 2) row 0
label(getString(R2.string.password)) col 0 row 1
changePasswordField = jfxPasswordField { promptText = getString(R2.string.password) } col 1 row 1
label(getString(R2.string.confirm_password)) col 0 row 2
confirmPasswordField = jfxPasswordField { promptText = getString(R2.string.confirm_password) } col 1 row 2
}
defaultButton.disableProperty().bind(
changePasswordField.textProperty().toBooleanBinding { it!!.isBlank() }
or confirmPasswordField.textProperty().toBooleanBinding { it!!.isBlank() }
or changePasswordField.textProperty().neq(confirmPasswordField.textProperty())
)
}
override val nullableResult: String? get() = changePasswordField.text
}
| apache-2.0 | 3cdb6d9a8ecfaa6dd75a8d8a1b0ba086 | 40.536585 | 118 | 0.733999 | 4.493404 | false | false | false | false |
yujintao529/android_practice | MyPractice/app/src/main/java/com/demon/yu/view/fresco/FrescoAvatarUtils.kt | 1 | 5807 | package com.demon.yu.view.fresco
import android.graphics.*
import android.net.Uri
import androidx.annotation.DrawableRes
import com.demon.yu.view.FrescoWebpViewAct
import com.example.mypractice.Logger
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.generic.RoundingParams
import com.facebook.drawee.interfaces.DraweeController
import com.facebook.drawee.view.SimpleDraweeView
import com.facebook.imagepipeline.common.ImageDecodeOptions
import com.facebook.imagepipeline.common.ImageDecodeOptionsBuilder
import com.facebook.imagepipeline.common.ResizeOptions
import com.facebook.imagepipeline.listener.BaseRequestListener
import com.facebook.imagepipeline.request.BasePostprocessor
import com.facebook.imagepipeline.request.ImageRequest
import com.facebook.imagepipeline.request.ImageRequestBuilder
object FrescoAvatarUtils {
fun bindAvatar(simpleDraweeView: SimpleDraweeView, @DrawableRes resourceID: Int) {
val imageRequestBuilder =
ImageRequestBuilder.newBuilderWithResourceId(resourceID)
.setRequestListener(object : BaseRequestListener() {
override fun onRequestFailure(
request: ImageRequest,
requestId: String,
throwable: Throwable,
isPrefetch: Boolean
) {
super.onRequestFailure(request, requestId, throwable, isPrefetch)
Logger.error(FrescoWebpViewAct.TAG, "onRequestFailure ", throwable)
}
})
val controller: DraweeController = Fresco.newDraweeControllerBuilder()
.setAutoPlayAnimations(true)
.setImageRequest(imageRequestBuilder.build())
.build()
simpleDraweeView.controller = controller
}
fun bindAvatar(simpleDraweeView: SimpleDraweeView, uri: String, width: Int, height: Int) {
val imageDecodeOptions = ImageDecodeOptions.newBuilder()
.setForceStaticImage(true)
.build()
val imageRequestBuilder =
ImageRequestBuilder.newBuilderWithSource(Uri.parse(uri))
.setRequestListener(object : BaseRequestListener() {
override fun onRequestFailure(
request: ImageRequest,
requestId: String,
throwable: Throwable,
isPrefetch: Boolean
) {
super.onRequestFailure(request, requestId, throwable, isPrefetch)
Logger.error(FrescoWebpViewAct.TAG, "onRequestFailure ", throwable)
}
}).setResizeOptions(ResizeOptions(width, height))
.setPostprocessor(object : BasePostprocessor() {
override fun process(destBitmap: Bitmap, sourceBitmap: Bitmap) {
super.process(destBitmap, sourceBitmap)
val canvas = Canvas(sourceBitmap)
val paint = Paint(Paint.FILTER_BITMAP_FLAG)
paint.colorFilter = PorterDuffColorFilter(
0x313031,
PorterDuff.Mode.SRC_IN
)
canvas.drawBitmap(destBitmap, Matrix(), paint)
}
})
.setCacheChoice(ImageRequest.CacheChoice.SMALL)
.setImageDecodeOptions(imageDecodeOptions)
val controller: DraweeController = Fresco.newDraweeControllerBuilder()
.setAutoPlayAnimations(true)
.setOldController(simpleDraweeView.controller)
.setImageRequest(imageRequestBuilder.build())
.build()
simpleDraweeView.controller = controller
}
fun bindIconWithTint(simpleDraweeView: SimpleDraweeView, drawable: Int) {
val imageRequestBuilder =
ImageRequestBuilder.newBuilderWithResourceId(drawable)
.setRequestListener(object : BaseRequestListener() {
override fun onRequestFailure(
request: ImageRequest,
requestId: String,
throwable: Throwable,
isPrefetch: Boolean
) {
super.onRequestFailure(request, requestId, throwable, isPrefetch)
Logger.error(FrescoWebpViewAct.TAG, "onRequestFailure ", throwable)
}
})
.setPostprocessor(object : BasePostprocessor() {
override fun process(destBitmap: Bitmap, sourceBitmap: Bitmap) {
// super.process(destBitmap, sourceBitmap)
val canvas = Canvas(destBitmap)
val paint = Paint(Paint.FILTER_BITMAP_FLAG)
paint.colorFilter = PorterDuffColorFilter(
Color.WHITE,
PorterDuff.Mode.SRC_IN
)
canvas.drawBitmap(sourceBitmap, Matrix(), paint)
}
})
.setCacheChoice(ImageRequest.CacheChoice.SMALL)
val controller: DraweeController = Fresco.newDraweeControllerBuilder()
.setAutoPlayAnimations(true)
.setOldController(simpleDraweeView.controller)
.setImageRequest(imageRequestBuilder.build())
.build()
simpleDraweeView.controller = controller
}
fun asCircle(simpleDraweeView: SimpleDraweeView) {
val roundingParams = RoundingParams()
roundingParams.roundAsCircle = true
simpleDraweeView.hierarchy.roundingParams = roundingParams
}
} | apache-2.0 | 505103c50acf519a3856a8aeca7d02b0 | 44.375 | 94 | 0.60031 | 5.883485 | false | false | false | false |
BasinMC/Basin | faucet/src/main/kotlin/org/basinmc/faucet/math/Vector3Float.kt | 1 | 3890 | /*
* Copyright 2019 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* 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.basinmc.faucet.math
import kotlin.math.roundToInt
import kotlin.math.roundToLong
import kotlin.math.sqrt
/**
* @author <a href="mailto:[email protected]">Johannes Donath</a>
*/
data class Vector3Float(override val x: Float = 0f, override val y: Float = 0f,
override val z: Float = 0f) : Vector3<Float> {
override val length: Double by lazy {
sqrt(Math.pow(this.x.toDouble(), 2.0) + Math.pow(this.y.toDouble(), 2.0) + Math.pow(
this.z.toDouble(), 2.0))
}
override val normalized: Vector3Float by lazy {
Vector3Float((this.x / this.length).toFloat(), (this.y / this.length).toFloat(),
(this.z / this.length).toFloat())
}
override val int: Vector3<Int>
get() = Vector3Int(this.x.roundToInt(), this.y.roundToInt(), this.z.roundToInt())
override val long: Vector3<Long>
get() = Vector3Long(this.x.roundToLong(), this.y.roundToLong(), this.z.roundToLong())
override val float: Vector3Float
get() = this
override fun plus(addend: Float) = Vector3Float(this.x + addend, this.y + addend, this.z + addend)
override fun plus(addend: Vector2<Float>) = Vector3Float(this.x + addend.x, this.y + addend.y,
this.z)
override fun plus(addend: Vector3<Float>) = Vector3Float(this.x + addend.x, this.y + addend.y,
this.z + addend.z)
override fun minus(subtrahend: Float) = Vector3Float(this.x - subtrahend, this.y - subtrahend,
this.z - subtrahend)
override fun minus(subtrahend: Vector2<Float>) = Vector3Float(this.x - subtrahend.x,
this.y - subtrahend.y, this.z)
override fun minus(subtrahend: Vector3<Float>) = Vector3Float(this.x - subtrahend.x,
this.y - subtrahend.y, this.z - subtrahend.z)
override fun times(factor: Float) = Vector3Float(this.x * factor, this.y * factor,
this.z * factor)
override fun times(factor: Vector2<Float>) = Vector3Float(this.x * factor.x, this.y * factor.y,
this.z)
override fun times(factor: Vector3<Float>) = Vector3Float(this.x * factor.x, this.y * factor.y,
this.z * factor.z)
override fun div(divisor: Float) = Vector3Float(this.x / divisor, this.y / divisor,
this.z / divisor)
override fun div(divisor: Vector2<Float>) = Vector3Float(this.x / divisor.x, this.y / divisor.y,
this.z)
override fun div(divisor: Vector3<Float>) = Vector3Float(this.x / divisor.x, this.y / divisor.y,
this.z / divisor.z)
override fun rem(divisor: Float) = Vector3Float(this.x % divisor, this.y % divisor,
this.z % divisor)
override fun rem(divisor: Vector2<Float>) = Vector3Float(this.x % divisor.x, this.y % divisor.y,
this.z)
override fun rem(divisor: Vector3<Float>) = Vector3Float(this.x % divisor.x, this.y % divisor.y,
this.z % divisor.z)
companion object : Vector3.Definition<Float> {
override val zero = Vector3Float()
override val one = Vector3Float(1f, 1f, 1f)
override val up = Vector3Float(0f, 1f, 0f)
override val right = Vector3Float(1f, 0f, 0f)
override val down = Vector3Float(0f, -1f, 0f)
override val left = Vector3Float(-1f, 0f, 0f)
override val forward = Vector3Float(0f, 0f, 1f)
override val backward = Vector3Float(0f, 0f, -1f)
}
}
| apache-2.0 | d75780469b81cd972761755d26a9d6c3 | 38.292929 | 100 | 0.688175 | 3.313458 | false | false | false | false |
Team-Antimatter-Mod/AntiMatterMod | src/main/java/antimattermod/core/Fluid/tank/BlockBasicTank.kt | 1 | 6020 | package antimattermod.core.Fluid.tank
import antimattermod.core.AntiMatterModCore
import antimattermod.core.AntiMatterModRegistry
import antimattermod.core.Energy.Item.Wrench.ItemWrench
import c6h2cl2.YukariLib.Util.BlockPos
import com.sun.org.apache.xpath.internal.operations.Bool
import cpw.mods.fml.relauncher.Side
import cpw.mods.fml.relauncher.SideOnly
import net.minecraft.block.BlockContainer
import net.minecraft.block.material.Material
import net.minecraft.client.renderer.texture.IIconRegister
import net.minecraft.entity.item.EntityItem
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.IIcon
import net.minecraft.world.World
import net.minecraftforge.common.util.ForgeDirection
import net.minecraftforge.fluids.Fluid
import net.minecraftforge.fluids.FluidContainerRegistry
import net.minecraftforge.fluids.FluidStack
/**
* @author kojin15.
*/
class BlockBasicTank : BlockContainer(Material.iron) {
init {
setBlockName("BasicTank")
setCreativeTab(AntiMatterModRegistry.tabMachines)
setBlockBounds(0.125F, 0.0F, 0.125F, 0.875F, 1.0F, 0.875F)
}
@SideOnly(Side.CLIENT)
var topIcon: IIcon? = null
@SideOnly(Side.CLIENT)
var sideIcon: IIcon? = null
override fun onBlockActivated(world: World, x: Int, y: Int, z: Int, player: EntityPlayer, side: Int, hitX: Float, hitY: Float, hitZ: Float): Boolean {
//nullならreturn
val currentItem: ItemStack? = player.inventory.getCurrentItem()
currentItem ?: return true
//requireNotNull()を使うことで、強制的にNotNullに
val tile: TileBasicTank = requireNotNull(world.getTileEntity(x, y, z) as TileBasicTank?)
val blockPos: BlockPos = BlockPos(x, y, z)
//事前にnullチェックをしておくと、if分のネストが減るので可読性が上がる。
//nullの時に何かする気が無いのなら、if(something != null){}ではなく、if(something == null) returnもしくは、something?:returnを使う方がよい。
//多重ネストは醜くなるので、できるだけ減らすこと。
val tankFluid = tile.productTank.fluid
val currentFluid = FluidContainerRegistry.getFluidForFilledItem(currentItem)
if (isNotNull(currentFluid)) {
val put: Int = tile.fill(ForgeDirection.UNKNOWN, currentFluid, false)
if (put == currentFluid.amount) {
tile.fill(ForgeDirection.UNKNOWN, currentFluid, true)
val usedContainer: ItemStack = FluidContainerRegistry.drainFluidContainer(currentItem)
if (!player.inventory.addItemStackToInventory(usedContainer.copy())) {
player.entityDropItem(usedContainer.copy(), 1f)
}
if (!player.capabilities.isCreativeMode && currentItem.stackSize-- <= 0) {
player.inventory.setInventorySlotContents(player.inventory.currentItem, null)
}
markDirty(world, player, tile, blockPos)
return true
}
//ItemWrenchを持っている時にこの処理を行う。アイテムとしてドロップ。
} else if (currentItem.item is ItemWrench/* && player.isSneaking*/) {
val tankStack = ItemStack(this)
if (tankStack.hasTagCompound()) {
tile.writeToNBT(tankStack.tagCompound)
} else {
val tagCompound = NBTTagCompound()
tile.writeToNBT(tagCompound)
tankStack.tagCompound = tagCompound
}
if(!player.inventory.addItemStackToInventory(tankStack)){
world.spawnEntityInWorld(EntityItem(world, x.toDouble(), y.toDouble(), z.toDouble(), tankStack))
}
world.setBlockToAir(x, y, z)
} else {
if (isNotNull(tankFluid)) {
if (tankFluid.amount < 1000) return true
val get: ItemStack? = FluidContainerRegistry.fillFluidContainer(FluidStack(tankFluid.getFluid(), 1000), currentItem)
if (get != null) {
tile.drain(ForgeDirection.UNKNOWN, 1000, true)
if (!player.inventory.addItemStackToInventory(get.copy())) {
player.entityDropItem(get.copy(), 1f)
}
if (!player.capabilities.isCreativeMode && currentItem.stackSize-- <= 0) {
player.inventory.setInventorySlotContents(player.inventory.currentItem, null)
}
markDirty(world, player, tile, blockPos)
return true
}
} else return true
}
return true
}
override fun createNewTileEntity(p_149915_1_: World?, p_149915_2_: Int): TileEntity {
return TileBasicTank()
}
override fun isNormalCube(): Boolean {
return false
}
override fun isOpaqueCube(): Boolean {
return false
}
override fun renderAsNormalBlock(): Boolean {
return false
}
override fun getIcon(side: Int, meta: Int): IIcon? {
when (side) {
0, 1 -> return topIcon
else -> return sideIcon
}
}
override fun registerBlockIcons(register: IIconRegister?) {
topIcon = register!!.registerIcon("${AntiMatterModCore.MOD_ID}:tank/tank_basic_top")
sideIcon = register.registerIcon("${AntiMatterModCore.MOD_ID}:tank/tank_basic_side")
}
fun markDirty(world: World, player: EntityPlayer, tile: TileEntity, blockPos: BlockPos) {
tile.markDirty()
player.inventory.markDirty()
world.markBlockForUpdate(blockPos.getX(), blockPos.getY(), blockPos.getZ())
}
fun isNotNull(fluid: FluidStack?): Boolean {
return fluid != null && fluid.getFluid() != null
}
} | gpl-3.0 | 3a64f43f1538277e0076799796a545e7 | 39.556338 | 154 | 0.650226 | 4.145428 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/world/chunk/ChunkManager.kt | 1 | 5543 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.world.chunk
import org.lanternpowered.api.util.collections.concurrentHashMapOf
import org.lanternpowered.api.util.collections.concurrentHashSetOf
import org.lanternpowered.api.world.World
import org.lanternpowered.api.world.chunk.ChunkLoadingTicket
import org.lanternpowered.api.world.chunk.ChunkPosition
import org.lanternpowered.server.world.LanternChunk
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutorService
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
/**
* Manages all the chunks in a world.
*
* @property world The world this manager belongs to
* @property ioExecutor The executor which is used to handle IO
*/
class ChunkManager(
val world: World,
val ioExecutor: ExecutorService
) {
/**
* All the chunk loading tickets that are currently
* allocated and hold references.
*/
private val tickets = concurrentHashSetOf<LanternChunkLoadingTicket>()
/**
* All the chunk entries.
*/
private val entries = concurrentHashMapOf<Long, ChunkEntry>()
/**
* References to either a loaded or unloaded chunk,
* and all the states in between.
*/
class ChunkEntry(val position: ChunkPosition) {
/**
* A lock for modifications to the chunk entry.
*/
val lock = ReentrantReadWriteLock()
/**
* The number of references that are held by
* different tickets.
*/
var references: Int = 0
/**
* The current state.
*/
var state: State = State.Unloaded
/**
* Represents the state a chunk entry can be in.
*/
sealed class State {
/**
* The chunk is being loaded. The [future] will be called
* when the chunk finishes loading.
*
* Loading can also involve generation if the chunk didn't
* exist before.
*/
class Loading(val future: CompletableFuture<LanternChunk>) : State()
/**
* The chunk is loaded.
*/
class Loaded(val chunk: LanternChunk) : State()
/**
* The chunk is unloaded, no data related to the
* chunk is currently in memory.
*/
object Unloaded : State()
/**
* The chunk is being unloaded. The [future] will be called
* when the chunk finishes unloading.
*
* Unloading also includes saving.
*/
class Unloading(val future: CompletableFuture<Unit>) : State()
/**
* The chunk is being saved, without unloading. The [future]
* will be called when the chunk finishes loading.
*/
class Saving(val future: CompletableFuture<Unit>) : State()
}
}
private fun queueLoad(entry: ChunkEntry) {
}
private fun queueUnload(entry: ChunkEntry) {
}
/**
* Creates a new chunk loading ticket.
*/
fun createTicket(): ChunkLoadingTicket =
LanternChunkLoadingTicket(this)
/**
* Adds the ticket.
*/
fun add(ticket: LanternChunkLoadingTicket) {
this.tickets.add(ticket)
}
/**
* Removes the ticket.
*/
fun remove(ticket: LanternChunkLoadingTicket) {
this.tickets.remove(ticket)
}
/**
* Gets whether there are references for the chunk
* at the given [ChunkPosition].
*/
fun hasReference(position: ChunkPosition): Boolean {
val entry = this.entries[position.packed] ?: return false
return entry.lock.read { entry.references > 0 }
}
/**
* Acquires a reference to the given chunk at
* the [ChunkPosition].
*/
fun acquireReference(position: ChunkPosition) {
val entry = this.entries.computeIfAbsent(position.packed) { ChunkEntry(position) }
entry.lock.write {
entry.references++
if (entry.references == 1)
this.queueLoad(entry)
}
}
/**
* Releases a reference to the given chunk at
* the [ChunkPosition].
*/
fun releaseReference(position: ChunkPosition) {
val entry = this.entries[position.packed]
?: throw IllegalStateException("The entry for $position doesn't exist.")
entry.lock.write {
entry.references--
if (entry.references == 0)
this.queueUnload(entry)
}
}
/**
* Cleanup entries that are no longer relevant. This is the case
* when the chunk is unloaded and there are no references to try
* to load it.
*/
private fun cleanupEntries() {
val entries = this.entries.toMap()
for ((key, entry) in entries) {
entry.lock.write {
if (entry.state is ChunkEntry.State.Unloaded && entry.references == 0)
this.entries.remove(key)
}
}
}
fun getChunkIfLoaded(position: ChunkPosition): LanternChunk {
TODO()
}
}
| mit | 69b37802bd6d1355ffd92adb68ea56d0 | 27.869792 | 90 | 0.600938 | 4.717447 | false | false | false | false |
mskonovalov/intellij-hidpi-profiles | src/main/java/ms/konovalov/intellij/hidpi/FontSizeForm.kt | 1 | 2686 | package ms.konovalov.intellij.hidpi
import com.intellij.openapi.ui.Messages
import javax.swing.*
import java.awt.*
class FontSizeForm internal constructor(private val component: FontSizeComponent) {
internal var panel: JPanel? = null
private var profilesList: JList<FontProfile>? = null
private var addCurrentButton: JButton? = null
private var deleteButton: JButton? = null
private val profiles = FontProfileManager.profiles
init {
profilesList!!.model = setModel()
profilesList!!.selectedIndex = 0
profilesList!!.cellRenderer = object : DefaultListCellRenderer() {
override fun getListCellRendererComponent(list: JList<*>, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component {
val label = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus) as JLabel
label.text = (value as FontProfile).name
return label
}
}
deleteButton!!.addActionListener { _ ->
val idx = profilesList!!.selectedIndex
if (idx != -1) {
(profilesList!!.model as DefaultListModel).remove(idx)
setModified(true)
if (profilesList!!.model.size == 0) {
return@addActionListener
}
if (idx > profilesList!!.model.size - 1) {
profilesList!!.setSelectedIndex(idx - 1)
} else {
profilesList!!.setSelectedIndex(idx)
}
}
}
addCurrentButton!!.addActionListener { _ ->
val profileName = Messages.showInputDialog("Provide name for new Profile", "HDPI Profile ", null) ?: return@addActionListener
val activeProfile = FontProfileManager.readCurrentProfile(profileName, false)
(profilesList!!.model as DefaultListModel<FontProfile>).addElement(activeProfile)
profilesList!!.selectedIndex = profilesList!!.model.size - 1
setModified(true)
}
}
private fun setModel(): DefaultListModel<FontProfile> {
val model = DefaultListModel<FontProfile>()
profiles.forEach { fp -> model.addElement(fp) }
return model
}
internal fun reset() {
profilesList!!.model = setModel()
setModified(false)
}
internal fun apply() {
profiles.clear()
val model = profilesList!!.model
(0 until model.size).mapTo(profiles) { model.getElementAt(it) }
setModified(false)
}
private fun setModified(modified: Boolean) {
component.isModified = modified
}
}
| mit | 0dc6867632cc23b3b94027fea76cd05a | 35.794521 | 151 | 0.614669 | 5.106464 | false | false | false | false |
googleapis/gapic-generator-kotlin | example-api-cloud-clients/src/main/kotlin/example/Speech.kt | 1 | 2022 | /*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example
import com.google.cloud.speech.v1.RecognitionConfig
import com.google.cloud.speech.v1.SpeechClient
import com.google.cloud.speech.v1.longRunningRecognizeRequest
import com.google.cloud.speech.v1.recognitionAudio
import com.google.cloud.speech.v1.recognitionConfig
import com.google.common.io.ByteStreams
import com.google.protobuf.ByteString
import kotlinx.coroutines.runBlocking
/**
* Simple example of calling the Logging API with a generated Kotlin gRPC client.
*
* Run this example using your service account as follows:
*
* ```
* $ GOOGLE_APPLICATION_CREDENTIALS=<path_to_your_service_account.json> ./gradlew run --args speech
* ```
*/
fun speechExample() = runBlocking {
// create a client
val client = SpeechClient.fromEnvironment()
// get audio
val audioData = Main::class.java.getResourceAsStream("/audio.raw").use {
ByteString.copyFrom(ByteStreams.toByteArray(it))
}
// call the API
val operation = client.longRunningRecognize(longRunningRecognizeRequest {
audio = recognitionAudio {
content = audioData
}
config = recognitionConfig {
encoding = RecognitionConfig.AudioEncoding.LINEAR16
sampleRateHertz = 16000
languageCode = "en-US"
}
})
// wait for the result
println("The response is: ${operation.await()}")
// shutdown
client.shutdownChannel()
}
| apache-2.0 | 753c5aeab41992d12af58f3c77ea68a7 | 31.095238 | 99 | 0.715628 | 4.230126 | false | true | false | false |
lukashaertel/megal-vm | src/main/kotlin/org/softlang/util/Strings.kt | 1 | 587 | package org.softlang.util
/**
* Simple indentation method.
*/
fun String.indent(indentation: String) =
indentation + replace(Regex("\\r?\\n|\\r"), "$0$indentation")
/**
* Concatenates strings if both are not null, otherwise returns an empty string.
*/
infix fun String?.cat(next: String?) = when {
this == null -> ""
next == null -> ""
else -> "$this$next"
}
/**
* Concatenates strings if both are not null, otherwise returns null.
*/
infix fun String?.ncat(next: String?) = when {
this == null -> null
next == null -> null
else -> "$this$next"
} | mit | 88eab90488bbd131c1fb7d8fa7da1f6a | 22.52 | 80 | 0.614991 | 3.601227 | false | false | false | false |
FHannes/intellij-community | uast/uast-common/src/org/jetbrains/uast/baseElements/UExpression.kt | 7 | 3096 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import org.jetbrains.uast.internal.log
import org.jetbrains.uast.visitor.UastTypedVisitor
import org.jetbrains.uast.visitor.UastVisitor
/**
* Represents an expression or statement (which is considered as an expression in Uast).
*/
interface UExpression : UElement, UAnnotated {
/**
* Returns the expression value or null if the value can't be calculated.
*/
fun evaluate(): Any? = null
/**
* Returns expression type, or null if type can not be inferred, or if this expression is a statement.
*/
fun getExpressionType(): PsiType? = null
override fun accept(visitor: UastVisitor) {
visitor.visitElement(this)
visitor.afterVisitElement(this)
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D) = visitor.visitExpression(this, data)
}
/**
* Represents an annotated element.
*/
interface UAnnotated : UElement {
/**
* Returns the list of annotations applied to the current element.
*/
val annotations: List<UAnnotation>
/**
* Looks up for annotation element using the annotation qualified name.
*
* @param fqName the qualified name to search
* @return the first annotation element with the specified qualified name, or null if there is no annotation with such name.
*/
fun findAnnotation(fqName: String): UAnnotation? = annotations.firstOrNull { it.qualifiedName == fqName }
}
/**
* Represents a labeled element.
*/
interface ULabeled : UElement {
/**
* Returns the label name, or null if the label is empty.
*/
val label: String?
/**
* Returns the label identifier, or null if the label is empty.
*/
val labelIdentifier: UIdentifier?
}
/**
* In some cases (user typing, syntax error) elements, which are supposed to exist, are missing.
* The obvious example - the lack of the condition expression in [UIfExpression], e.g. 'if () return'.
* [UIfExpression.condition] is required to return not-null values,
* and Uast implementation should return something instead of 'null' in this case.
*
* Use [UastEmptyExpression] in this case.
*/
object UastEmptyExpression : UExpression {
override val uastParent: UElement?
get() = null
override val annotations: List<UAnnotation>
get() = emptyList()
override val psi: PsiElement?
get() = null
override fun asLogString() = log()
} | apache-2.0 | b8a89f6a5686dd76676c7f3810a1d6d1 | 30.602041 | 128 | 0.700581 | 4.366714 | false | false | false | false |
lfkdsk/JustDB | src/sql/parser/SqlParser.kt | 1 | 3486 | package sql.parser
import sql.ast.*
import sql.literal.EnumLeaf
import sql.literal.IdLeaf
import sql.literal.NumLeaf
import sql.literal.StrLeaf
import sql.token.SqlToken
import utils.parsertools.ast.AstNode
import utils.parsertools.combinators.Bnf
import utils.parsertools.exception.ParseException
import utils.parsertools.lex.Lexer
/**
* Created by liufengkai on 2017/4/25.
*/
class SqlParser {
// word set
var reserved: HashSet<String> = HashSet()
var typeDefSet: HashSet<String> = HashSet()
val number = Bnf.rule().number(NumLeaf::class.java)
val string = Bnf.rule().string(StrLeaf::class.java)
var id = Bnf.rule().identifier(reserved, IdLeaf::class.java)
val enum = Bnf.rule().enum(typeDefSet, EnumLeaf::class.java)
val constant = Bnf.rule().or(number, string)
val constantList = Bnf.rule(ConstantList::class.java)
.ast(constant)
.repeat(Bnf.rule().sep(",").ast(constant))
val field = id
val expr = Bnf.rule().or(field, constant)
val term = Bnf.rule(Term::class.java)
.ast(expr).sep("=").ast(expr)
val fieldList = Bnf.rule()
.identifier(reserved)
.repeat(Bnf.rule().sep(",").identifier(reserved))
// val typeDef = Bnf.rule().enum(reserved)
val fieldDef = Bnf.rule(FieldList::class.java).identifier(reserved)
.ast(enum)
val fieldDefList = Bnf.rule(FieldDefList::class.java)
.ast(fieldDef)
.repeat(Bnf.rule().sep(",").ast(fieldDef))
val createTable = Bnf.rule(CreateTable::class.java)
.sep("create")
.sep("table")
.identifier(reserved)
.sep("(")
.ast(fieldDefList)
.sep(")")
val insert = Bnf.rule(Insert::class.java)
.sep("insert", "into")
.identifier(reserved)
.sep("(")
.ast(fieldList)
.sep(")")
.sep("values")
.sep("(")
.ast(constantList)
.sep(")")
val predicate = Bnf.rule(Predicate::class.java)
.ast(term)
.repeat(Bnf.rule().sep("and").ast(term))
val tableNameList = Bnf.rule(TableNameList::class.java)
.identifier(reserved)
.repeat(Bnf.rule().sep(",").identifier(reserved))
val selectList = Bnf.rule(SelectList::class.java)
.ast(field)
.repeat(Bnf.rule().sep(",").ast(field))
val query = Bnf.rule(Query::class.java)
.sep("select")
.ast(selectList)
.sep("from")
.ast(tableNameList)
.maybe(Bnf.rule().sep("where").ast(predicate))
val createView = Bnf.rule(CreateView::class.java)
.sep("create", "view")
.identifier(reserved)
.sep("as")
.ast(query)
val createIndex = Bnf.rule(CreateIndex::class.java)
.sep("create", "index")
.identifier(reserved)
.sep("on")
.identifier(reserved)
.sep("(")
.ast(field) // TODO fields?
.sep(")")
val delete = Bnf.rule(Delete::class.java)
.sep("delete", "from")
.identifier(reserved)
.maybe(Bnf.rule().sep("where").ast(predicate))
val update = Bnf.rule(Update::class.java)
.sep("update")
.identifier(reserved)
.sep("set")
.ast(field)
.sep("=")
.ast(expr)
.maybe(Bnf.rule().sep("where").ast(predicate))
val create = Bnf.rule().or(
createTable.sep(";"),
createIndex.sep(";"),
createView.sep(";")
)
val modify = Bnf.rule().or(
insert.sep(";"),
delete.sep(";"),
update.sep(";"),
query.sep(";")
)
val singleCommand = Bnf.rule().or(create, modify)
val program = Bnf.rule().ast(singleCommand).sep(SqlToken.EOL)
init {
// init type def params
typeDefSet.add("VARCHAR")
typeDefSet.add("INT")
}
@Throws(ParseException::class)
fun parse(lexer: Lexer): AstNode {
return program.parse(lexer)
}
} | apache-2.0 | 2883946fad1c5c95ec8738c156e6b313 | 21.496774 | 68 | 0.656913 | 2.924497 | false | false | false | false |
ahmedeltaher/MVP-Sample | app/src/main/java/com/task/ui/base/BaseFragment.kt | 1 | 1564 | package com.task.ui.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.task.R
import com.task.ui.base.listeners.BaseView
/**
* Created by AhmedEltaher on 5/12/2016
*/
abstract class BaseFragment : Fragment(), BaseView {
protected var presenter: Presenter<*>? = null
abstract val layoutId: Int
private val toolbarTitleKey: String? = null
protected abstract fun initializeDagger()
protected abstract fun initializePresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initializeDagger()
initializePresenter()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(layoutId, container, false)
presenter?.initialize(arguments)
return view
}
override fun onStart() {
super.onStart()
presenter?.start()
}
override fun onStop() {
super.onStop()
presenter?.finalizeView()
}
fun setTitle(title: String) {
val actionBar = (activity as BaseActivity).supportActionBar
if (actionBar != null) {
val titleTextView = activity?.findViewById<TextView>(R.id.txt_toolbar_title)
if (!title.isEmpty()) {
titleTextView?.text = title
}
}
}
}
| apache-2.0 | 5a392915eaa1a42ca4f2574680c465a9 | 24.225806 | 88 | 0.65601 | 4.842105 | false | false | false | false |
JVMDeveloperID/kotlin-android-example | app/src/main/kotlin/com/gojek/sample/kotlin/internal/data/remote/response/ContactsResponse.kt | 1 | 530 | package com.gojek.sample.kotlin.internal.data.remote.response
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
@JsonIgnoreProperties(ignoreUnknown = true)
class ContactsResponse {
@JsonProperty(value = "id")
var id: Int? = 0
@JsonProperty(value = "first_name")
lateinit var firstName: String
@JsonProperty(value = "last_name")
lateinit var lastName: String
@JsonProperty(value = "profile_pic")
lateinit var profilePic: String
} | apache-2.0 | 6e0de08b37da54ffccc6c13b9f5580de | 25.55 | 61 | 0.749057 | 4.308943 | false | false | false | false |
QuickBlox/quickblox-android-sdk | sample-chat-kotlin/app/src/main/java/com/quickblox/sample/chat/kotlin/utils/SystemPermissionHelper.kt | 1 | 1959 | package com.quickblox.sample.chat.kotlin.utils
import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.util.*
private const val PERMISSIONS_FOR_SAVE_FILE_IMAGE_REQUEST = 1010
class SystemPermissionHelper(private var activity: Activity) {
fun isSaveImagePermissionGranted(): Boolean {
return isPermissionGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)
&& isPermissionGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)
&& isPermissionGranted(Manifest.permission.CAMERA)
}
private fun isPermissionGranted(permission: String): Boolean {
return ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED
}
fun requestPermissionsForSaveFileImage() {
val permissions = ArrayList<String>()
permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
permissions.add(Manifest.permission.CAMERA)
checkAndRequestPermissions(PERMISSIONS_FOR_SAVE_FILE_IMAGE_REQUEST, permissions)
}
private fun checkAndRequestPermissions(requestCode: Int, permissions: ArrayList<String>) {
if (collectDeniedPermissions(permissions).isNotEmpty()) {
requestPermissions(requestCode, *collectDeniedPermissions(permissions))
}
}
private fun collectDeniedPermissions(permissions: ArrayList<String>): Array<String> {
val deniedPermissionsList = ArrayList<String>()
for (permission in permissions) {
if (!isPermissionGranted(permission)) {
deniedPermissionsList.add(permission)
}
}
return deniedPermissionsList.toTypedArray()
}
private fun requestPermissions(requestCode: Int, vararg permissions: String) {
ActivityCompat.requestPermissions(activity, permissions, requestCode)
}
} | bsd-3-clause | b62b4670b322327250582eeeb6363b70 | 37.431373 | 107 | 0.732517 | 5.237968 | false | false | false | false |
kamatama41/embulk-test-helpers | src/main/kotlin/org/embulk/test/EmbulkTestExtension.kt | 1 | 2107 | package org.embulk.test
import org.junit.jupiter.api.extension.AfterEachCallback
import org.junit.jupiter.api.extension.ExtensionContext
import org.junit.jupiter.api.extension.TestInstancePostProcessor
import org.junit.platform.commons.support.AnnotationSupport.findAnnotation
import org.junit.platform.commons.support.AnnotationSupport.findPublicAnnotatedFields
import java.lang.AssertionError
class EmbulkTestExtension : TestInstancePostProcessor, AfterEachCallback {
override fun postProcessTestInstance(testInstance: Any, context: ExtensionContext) {
val annotation = findAnnotation(context.testClass, EmbulkTest::class.java)
.orElseThrow { AssertionError("@EmbulkTest not found") }
val embulk = createNewEmbulk(annotation)
val embulkFields = findPublicAnnotatedFields(testInstance.javaClass, ExtendedTestingEmbulk::class.java, Embulk::class.java)
embulkFields.forEach {
it.isAccessible = true
it.set(testInstance, embulk)
}
context.getStore(NAMESPACE).put(KEY, embulk)
}
override fun afterEach(context: ExtensionContext) {
var parent = context.parent
while (parent.isPresent && parent.get() != context.root) {
val parentContext = parent.get()
val embulk = parentContext.getStore(NAMESPACE).remove(KEY, ExtendedTestingEmbulk::class.java)
embulk?.destroy()
parent = parentContext.parent
}
}
private fun createNewEmbulk(annotation: EmbulkTest): ExtendedTestingEmbulk {
val builder = ExtendedTestingEmbulk.builder()
annotation.value.forEach {
if (annotation.name.isEmpty()) {
builder.registerPlugin(impl = it)
} else {
builder.registerPlugin(impl = it, name = annotation.name)
}
}
return builder.build() as ExtendedTestingEmbulk
}
companion object {
@JvmStatic
private val NAMESPACE = ExtensionContext.Namespace.create(EmbulkTestExtension::class.java)
private val KEY = "embulk"
}
}
| mit | c61c5e93295917c4511cb788bcb72031 | 39.519231 | 131 | 0.693878 | 4.651214 | false | true | false | false |
tasks/tasks | app/src/main/java/org/tasks/compose/Banner.kt | 1 | 5236 | package org.tasks.compose
import android.content.res.Configuration
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.expandVertically
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.google.android.material.composethemeadapter.MdcTheme
import org.tasks.R
import org.tasks.Tasks
@ExperimentalAnimationApi
@Composable
fun AnimatedBanner(
visible: Boolean,
content: @Composable () -> Unit,
buttons: @Composable () -> Unit,
) {
AnimatedVisibility(
visible = visible,
enter = expandVertically(),
exit = shrinkVertically(),
) {
Column(
modifier = Modifier
.fillMaxWidth(),
) {
Divider()
Spacer(modifier = Modifier.height(16.dp))
content()
Row(
modifier = Modifier
.padding(vertical = 8.dp, horizontal = 16.dp)
.align(Alignment.End),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
buttons()
}
Divider()
}
}
}
@ExperimentalAnimationApi
@Composable
fun SubscriptionNagBanner(
visible: Boolean,
subscribe: () -> Unit,
dismiss: () -> Unit,
) {
AnimatedBanner(
visible = visible,
content = {
Text(
text = stringResource(
id = if (Tasks.IS_GENERIC) {
R.string.enjoying_tasks
} else {
R.string.tasks_needs_your_support
}
),
style = MaterialTheme.typography.body1,
modifier = Modifier.padding(horizontal = 16.dp),
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = stringResource(
id = if (Tasks.IS_GENERIC) {
R.string.tasks_needs_your_support
} else {
R.string.support_development_subscribe
}
),
style = MaterialTheme.typography.body2,
modifier = Modifier.padding(horizontal = 16.dp),
)
},
buttons = {
BannerTextButton(text = R.string.dismiss, dismiss)
val res = if (Tasks.IS_GENERIC) {
R.string.TLA_menu_donate
} else {
R.string.button_subscribe
}
BannerTextButton(text = res, subscribe)
}
)
}
@ExperimentalAnimationApi
@Composable
fun BeastModeBanner(
visible: Boolean,
showSettings: () -> Unit,
dismiss: () -> Unit,
) {
AnimatedBanner(
visible = visible,
content = {
Text(
text = stringResource(id = R.string.hint_customize_edit_title),
style = MaterialTheme.typography.body1,
modifier = Modifier.padding(horizontal = 16.dp),
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = stringResource(id = R.string.hint_customize_edit_body),
style = MaterialTheme.typography.body2,
modifier = Modifier.padding(horizontal = 16.dp),
)
},
buttons = {
BannerTextButton(text = R.string.dismiss, onClick = dismiss)
BannerTextButton(text = R.string.TLA_menu_settings, onClick = showSettings)
}
)
}
@Composable
fun BannerTextButton(text: Int, onClick: () -> Unit) {
TextButton(onClick = onClick) {
Text(
text = stringResource(id = text),
style = MaterialTheme.typography.button.copy(
color = MaterialTheme.colors.secondary
),
)
}
}
@ExperimentalAnimationApi
@Preview(showBackground = true)
@Preview(showBackground = true, backgroundColor = 0x202124, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun BeastModePreview() = MdcTheme {
BeastModeBanner(visible = true, showSettings = {}, dismiss = {})
}
@ExperimentalAnimationApi
@Preview(showBackground = true)
@Preview(showBackground = true, backgroundColor = 0x202124, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun SubscriptionNagPreview() = MdcTheme {
SubscriptionNagBanner(visible = true, subscribe = {}, dismiss = {})
}
| gpl-3.0 | 6c4c5358c61ea82c66c7fbeaf970fabe | 31.122699 | 101 | 0.608671 | 4.717117 | false | false | false | false |
AoEiuV020/PaNovel | app/src/main/java/cc/aoeiuv020/panovel/text/NovelContentsAdapter.kt | 1 | 2263 | package cc.aoeiuv020.panovel.text
import android.content.Context
import android.text.format.DateUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import cc.aoeiuv020.panovel.R
import cc.aoeiuv020.panovel.api.NovelChapter
import cc.aoeiuv020.panovel.data.entity.Novel
import cc.aoeiuv020.panovel.settings.OtherSettings
import cc.aoeiuv020.panovel.util.hide
import cc.aoeiuv020.panovel.util.show
import kotlinx.android.synthetic.main.novel_chapter_item.view.*
import java.util.concurrent.TimeUnit
/**
*
* Created by AoEiuV020 on 2017.10.22-17:26:00.
*/
class NovelContentsAdapter(
val context: Context,
val novel: Novel,
val chapters: List<NovelChapter>,
// 只用contains方法判断章节是否已经缓存,
private var cachedList: Collection<String>
) : BaseAdapter() {
// 颜色列表,只读一次设置,
private val chapterColorList = OtherSettings.chapterColorList
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val view = convertView
?: LayoutInflater.from(context).inflate(R.layout.novel_chapter_item, parent, false).apply {
name.setTextColor(chapterColorList)
}
val nameTextView = view.name
val tvUpdateTime = view.tvUpdateTime
val chapter = getItem(position)
nameTextView.apply {
text = chapter.name
// isChecked代表阅读到的章节,
isChecked = novel.readAtChapterIndex == position
// isSelected代表已经缓存的章节,
isSelected = cachedList.contains(chapter.extra)
}
tvUpdateTime.apply {
val update = chapter.update
if (update == null) {
hide()
} else {
text = DateUtils.getRelativeTimeSpanString(update.time, System.currentTimeMillis(), TimeUnit.SECONDS.toMillis(1))
show()
}
}
return view
}
override fun getItem(position: Int): NovelChapter = chapters[position]
override fun getItemId(position: Int): Long = 0L
override fun getCount(): Int = chapters.size
} | gpl-3.0 | 156d39b51d1cc036aa412791fa43e6a8 | 32.9375 | 129 | 0.667895 | 4.324701 | false | false | false | false |
Light-Team/ModPE-IDE-Source | data/src/test/kotlin/com/brackeys/ui/data/converter/ThemeConverterTest.kt | 1 | 18994 | /*
* 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.data.converter
import androidx.core.graphics.toColorInt
import com.brackeys.ui.data.model.themes.ExternalScheme
import com.brackeys.ui.data.model.themes.ExternalTheme
import com.brackeys.ui.data.storage.database.entity.theme.ThemeEntity
import com.brackeys.ui.domain.model.themes.ThemeModel
import com.brackeys.ui.editorkit.model.ColorScheme
import com.brackeys.ui.language.base.model.SyntaxScheme
import org.junit.Assert.assertEquals
import org.junit.Test
class ThemeConverterTest {
@Test
fun `convert ThemeEntity to ThemeModel`() {
val themeEntity = ThemeEntity(
uuid = "0",
name = "Test",
author = "Brackeys IDE",
description = "Default color scheme",
textColor = "#FFFFFF",
backgroundColor = "#303030",
gutterColor = "#F0F0F0",
gutterDividerColor = "#FFFFFF",
gutterCurrentLineNumberColor = "#FEFEFE",
gutterTextColor = "#FFFFFF",
selectedLineColor = "#EEEEEE",
selectionColor = "#FF3000",
suggestionQueryColor = "#FF9000",
findResultBackgroundColor = "#FEFEFE",
delimiterBackgroundColor = "#FEFEFE",
numberColor = "#FF3000",
operatorColor = "#FF3000",
keywordColor = "#FF3000",
typeColor = "#FF3000",
langConstColor = "#FF3000",
preprocessorColor = "FF3000",
variableColor = "#FF3000",
methodColor = "#FF3000",
stringColor = "#FF3000",
commentColor = "#FF3000",
tagColor = "#FF3000",
tagNameColor = "#FF3000",
attrNameColor = "#FF3000",
attrValueColor = "#FF3000",
entityRefColor = "#FF3000"
)
val themeModel = ThemeModel(
uuid = "0",
name = "Test",
author = "Brackeys IDE",
description = "Default color scheme",
isExternal = true,
colorScheme = ColorScheme(
textColor = "#FFFFFF".toColorInt(),
backgroundColor = "#303030".toColorInt(),
gutterColor = "#F0F0F0".toColorInt(),
gutterDividerColor = "#FFFFFF".toColorInt(),
gutterCurrentLineNumberColor = "#FEFEFE".toColorInt(),
gutterTextColor = "#FFFFFF".toColorInt(),
selectedLineColor = "#EEEEEE".toColorInt(),
selectionColor = "#FF3000".toColorInt(),
suggestionQueryColor = "#FF9000".toColorInt(),
findResultBackgroundColor = "#FEFEFE".toColorInt(),
delimiterBackgroundColor = "#FEFEFE".toColorInt(),
syntaxScheme = SyntaxScheme(
numberColor = "#FF3000".toColorInt(),
operatorColor = "#FF3000".toColorInt(),
keywordColor = "#FF3000".toColorInt(),
typeColor = "#FF3000".toColorInt(),
langConstColor = "#FF3000".toColorInt(),
preprocessorColor = "FF3000".toColorInt(),
variableColor = "FF3000".toColorInt(),
methodColor = "#FF3000".toColorInt(),
stringColor = "#FF3000".toColorInt(),
commentColor = "#FF3000".toColorInt(),
tagColor = "#FF3000".toColorInt(),
tagNameColor = "#FF3000".toColorInt(),
attrNameColor = "#FF3000".toColorInt(),
attrValueColor = "#FF3000".toColorInt(),
entityRefColor = "#FF3000".toColorInt()
)
)
)
val convert = ThemeConverter.toModel(themeEntity)
assertEquals(themeModel.uuid, convert.uuid)
assertEquals(themeModel.name, convert.name)
assertEquals(themeModel.author, convert.author)
assertEquals(themeModel.description, convert.description)
assertEquals(themeModel.isExternal, convert.isExternal)
assertEquals(themeModel.colorScheme.textColor, convert.colorScheme.textColor)
assertEquals(themeModel.colorScheme.backgroundColor, convert.colorScheme.backgroundColor)
assertEquals(themeModel.colorScheme.gutterColor, convert.colorScheme.gutterColor)
assertEquals(themeModel.colorScheme.gutterDividerColor, convert.colorScheme.gutterDividerColor)
assertEquals(themeModel.colorScheme.gutterCurrentLineNumberColor, convert.colorScheme.gutterCurrentLineNumberColor)
assertEquals(themeModel.colorScheme.gutterTextColor, convert.colorScheme.gutterTextColor)
assertEquals(themeModel.colorScheme.selectedLineColor, convert.colorScheme.selectedLineColor)
assertEquals(themeModel.colorScheme.selectionColor, convert.colorScheme.selectionColor)
assertEquals(themeModel.colorScheme.suggestionQueryColor, convert.colorScheme.suggestionQueryColor)
assertEquals(themeModel.colorScheme.findResultBackgroundColor, convert.colorScheme.findResultBackgroundColor)
assertEquals(themeModel.colorScheme.delimiterBackgroundColor, convert.colorScheme.delimiterBackgroundColor)
assertEquals(themeModel.colorScheme.syntaxScheme.numberColor, convert.colorScheme.syntaxScheme.numberColor)
assertEquals(themeModel.colorScheme.syntaxScheme.operatorColor, convert.colorScheme.syntaxScheme.operatorColor)
assertEquals(themeModel.colorScheme.syntaxScheme.keywordColor, convert.colorScheme.syntaxScheme.keywordColor)
assertEquals(themeModel.colorScheme.syntaxScheme.typeColor, convert.colorScheme.syntaxScheme.typeColor)
assertEquals(themeModel.colorScheme.syntaxScheme.langConstColor, convert.colorScheme.syntaxScheme.langConstColor)
assertEquals(themeModel.colorScheme.syntaxScheme.preprocessorColor, convert.colorScheme.syntaxScheme.preprocessorColor)
assertEquals(themeModel.colorScheme.syntaxScheme.variableColor, convert.colorScheme.syntaxScheme.variableColor)
assertEquals(themeModel.colorScheme.syntaxScheme.methodColor, convert.colorScheme.syntaxScheme.methodColor)
assertEquals(themeModel.colorScheme.syntaxScheme.stringColor, convert.colorScheme.syntaxScheme.stringColor)
assertEquals(themeModel.colorScheme.syntaxScheme.commentColor, convert.colorScheme.syntaxScheme.commentColor)
assertEquals(themeModel.colorScheme.syntaxScheme.tagColor, convert.colorScheme.syntaxScheme.tagColor)
assertEquals(themeModel.colorScheme.syntaxScheme.tagNameColor, convert.colorScheme.syntaxScheme.tagNameColor)
assertEquals(themeModel.colorScheme.syntaxScheme.attrNameColor, convert.colorScheme.syntaxScheme.attrNameColor)
assertEquals(themeModel.colorScheme.syntaxScheme.attrValueColor, convert.colorScheme.syntaxScheme.attrValueColor)
assertEquals(themeModel.colorScheme.syntaxScheme.entityRefColor, convert.colorScheme.syntaxScheme.entityRefColor)
}
/*@Test
fun `convert ThemeModel to ThemeEntity`() {
val themeModel = ThemeModel(
uuid = "0",
name = "Test",
author = "Brackeys IDE",
description = "Default color scheme",
isExternal = true,
colorScheme = ColorScheme(
textColor = "#FFFFFF".toColorInt(),
backgroundColor = "#303030".toColorInt(),
gutterColor = "#F0F0F0".toColorInt(),
gutterDividerColor = "#FFFFFF".toColorInt(),
gutterCurrentLineNumberColor = "#FEFEFE".toColorInt(),
gutterTextColor = "#FFFFFF".toColorInt(),
selectedLineColor = "#EEEEEE".toColorInt(),
selectionColor = "#FF3000".toColorInt(),
suggestionQueryColor = "#FF9000".toColorInt(),
findResultBackgroundColor = "#FEFEFE".toColorInt(),
delimiterBackgroundColor = "#FEFEFE".toColorInt(),
syntaxScheme = SyntaxScheme(
numberColor = "#FF3000".toColorInt(),
operatorColor = "#FF3000".toColorInt(),
keywordColor = "#FF3000".toColorInt(),
typeColor = "#FF3000".toColorInt(),
langConstColor = "#FF3000".toColorInt(),
preprocessorColor = "FF3000".toColorInt(),
variableColor = "#FF3000".toColorInt(),
methodColor = "#FF3000".toColorInt(),
stringColor = "#FF3000".toColorInt(),
commentColor = "#FF3000".toColorInt()
)
)
)
val themeEntity = ThemeEntity(
uuid = "0",
name = "Test",
author = "Brackeys IDE",
description = "Default color scheme",
textColor = "#FFFFFF",
backgroundColor = "#303030",
gutterColor = "#F0F0F0",
gutterDividerColor = "#FFFFFF",
gutterCurrentLineNumberColor = "#FEFEFE",
gutterTextColor = "#FFFFFF",
selectedLineColor = "#EEEEEE",
selectionColor = "#FF3000",
suggestionQueryColor = "#FF9000",
findResultBackgroundColor = "#FEFEFE",
delimiterBackgroundColor = "#FEFEFE",
numberColor = "#FF3000",
operatorColor = "#FF3000",
keywordColor = "#FF3000",
typeColor = "#FF3000",
langConstColor = "#FF3000",
preprocessorColor = "FF3000",
variableColor = "#FF3000",
methodColor = "#FF3000",
stringColor = "#FF3000",
commentColor = "#FF3000"
)
val convert = ThemeConverter.toEntity(themeModel)
assertEquals(themeEntity.uuid, convert.uuid)
assertEquals(themeEntity.name, convert.name)
assertEquals(themeEntity.author, convert.author)
assertEquals(themeEntity.description, convert.description)
assertEquals(themeEntity.isExternal, convert.isExternal)
assertEquals(themeEntity.textColor, convert.textColor)
assertEquals(themeEntity.backgroundColor, convert.backgroundColor)
assertEquals(themeEntity.gutterColor, convert.gutterColor)
assertEquals(themeEntity.gutterDividerColor, convert.gutterDividerColor)
assertEquals(themeEntity.gutterCurrentLineNumberColor, convert.gutterCurrentLineNumberColor)
assertEquals(themeEntity.gutterTextColor, convert.gutterTextColor)
assertEquals(themeEntity.selectedLineColor, convert.selectedLineColor)
assertEquals(themeEntity.selectionColor, convert.selectionColor)
assertEquals(themeEntity.suggestionQueryColor, convert.suggestionQueryColor)
assertEquals(themeEntity.findResultBackgroundColor, convert.findResultBackgroundColor)
assertEquals(themeEntity.delimiterBackgroundColor, convert.delimiterBackgroundColor)
assertEquals(themeEntity.numberColor, convert.numberColor)
assertEquals(themeEntity.operatorColor, convert.operatorColor)
assertEquals(themeEntity.keywordColor, convert.keywordColor)
assertEquals(themeEntity.typeColor, convert.typeColor)
assertEquals(themeEntity.langConstColor, convert.langConstColor)
assertEquals(themeEntity.preprocessorColor, convert.preprocessorColor)
assertEquals(themeEntity.variableColor, convert.variableColor)
assertEquals(themeEntity.methodColor, convert.methodColor)
assertEquals(themeEntity.stringColor, convert.stringColor)
assertEquals(themeEntity.commentColor, convert.commentColor)
}*/
@Test
fun `convert ExternalTheme to ThemeModel`() {
val externalTheme = ExternalTheme(
uuid = "0",
name = "Test",
author = "Brackeys IDE",
description = "Default color scheme",
externalScheme = ExternalScheme(
textColor = "#FFFFFF",
backgroundColor = "#303030",
gutterColor = "#F0F0F0",
gutterDividerColor = "#FFFFFF",
gutterCurrentLineNumberColor = "#FEFEFE",
gutterTextColor = "#FFFFFF",
selectedLineColor = "#EEEEEE",
selectionColor = "#FF3000",
suggestionQueryColor = "#FF9000",
findResultBackgroundColor = "#FEFEFE",
delimiterBackgroundColor = "#FEFEFE",
numberColor = "#FF3000",
operatorColor = "#FF3000",
keywordColor = "#FF3000",
typeColor = "#FF3000",
langConstColor = "#FF3000",
preprocessorColor = "FF3000",
variableColor = "#FF3000",
methodColor = "#FF3000",
stringColor = "#FF3000",
commentColor = "#FF3000",
tagColor = "#FF3000",
tagNameColor = "#FF3000",
attrNameColor = "#FF3000",
attrValueColor = "#FF3000",
entityRefColor = "#FF3000"
)
)
val themeModel = ThemeModel(
uuid = "0",
name = "Test",
author = "Brackeys IDE",
description = "Default color scheme",
isExternal = true,
colorScheme = ColorScheme(
textColor = "#FFFFFF".toColorInt(),
backgroundColor = "#303030".toColorInt(),
gutterColor = "#F0F0F0".toColorInt(),
gutterDividerColor = "#FFFFFF".toColorInt(),
gutterCurrentLineNumberColor = "#FEFEFE".toColorInt(),
gutterTextColor = "#FFFFFF".toColorInt(),
selectedLineColor = "#EEEEEE".toColorInt(),
selectionColor = "#FF3000".toColorInt(),
suggestionQueryColor = "#FF9000".toColorInt(),
findResultBackgroundColor = "#FEFEFE".toColorInt(),
delimiterBackgroundColor = "#FEFEFE".toColorInt(),
syntaxScheme = SyntaxScheme(
numberColor = "#FF3000".toColorInt(),
operatorColor = "#FF3000".toColorInt(),
keywordColor = "#FF3000".toColorInt(),
typeColor = "#FF3000".toColorInt(),
langConstColor = "#FF3000".toColorInt(),
preprocessorColor = "FF3000".toColorInt(),
variableColor = "#FF3000".toColorInt(),
methodColor = "#FF3000".toColorInt(),
stringColor = "#FF3000".toColorInt(),
commentColor = "#FF3000".toColorInt(),
tagColor = "#FF3000".toColorInt(),
tagNameColor = "#FF3000".toColorInt(),
attrNameColor = "#FF3000".toColorInt(),
attrValueColor = "#FF3000".toColorInt(),
entityRefColor = "#FF3000".toColorInt()
)
)
)
val convert = ThemeConverter.toModel(externalTheme)
assertEquals(themeModel.uuid, convert.uuid)
assertEquals(themeModel.name, convert.name)
assertEquals(themeModel.author, convert.author)
assertEquals(themeModel.description, convert.description)
assertEquals(themeModel.isExternal, convert.isExternal)
assertEquals(themeModel.colorScheme.textColor, convert.colorScheme.textColor)
assertEquals(themeModel.colorScheme.backgroundColor, convert.colorScheme.backgroundColor)
assertEquals(themeModel.colorScheme.gutterColor, convert.colorScheme.gutterColor)
assertEquals(themeModel.colorScheme.gutterDividerColor, convert.colorScheme.gutterDividerColor)
assertEquals(themeModel.colorScheme.gutterCurrentLineNumberColor, convert.colorScheme.gutterCurrentLineNumberColor)
assertEquals(themeModel.colorScheme.gutterTextColor, convert.colorScheme.gutterTextColor)
assertEquals(themeModel.colorScheme.selectedLineColor, convert.colorScheme.selectedLineColor)
assertEquals(themeModel.colorScheme.selectionColor, convert.colorScheme.selectionColor)
assertEquals(themeModel.colorScheme.suggestionQueryColor, convert.colorScheme.suggestionQueryColor)
assertEquals(themeModel.colorScheme.findResultBackgroundColor, convert.colorScheme.findResultBackgroundColor)
assertEquals(themeModel.colorScheme.delimiterBackgroundColor, convert.colorScheme.delimiterBackgroundColor)
assertEquals(themeModel.colorScheme.syntaxScheme.numberColor, convert.colorScheme.syntaxScheme.numberColor)
assertEquals(themeModel.colorScheme.syntaxScheme.operatorColor, convert.colorScheme.syntaxScheme.operatorColor)
assertEquals(themeModel.colorScheme.syntaxScheme.keywordColor, convert.colorScheme.syntaxScheme.keywordColor)
assertEquals(themeModel.colorScheme.syntaxScheme.typeColor, convert.colorScheme.syntaxScheme.typeColor)
assertEquals(themeModel.colorScheme.syntaxScheme.langConstColor, convert.colorScheme.syntaxScheme.langConstColor)
assertEquals(themeModel.colorScheme.syntaxScheme.preprocessorColor, convert.colorScheme.syntaxScheme.preprocessorColor)
assertEquals(themeModel.colorScheme.syntaxScheme.variableColor, convert.colorScheme.syntaxScheme.variableColor)
assertEquals(themeModel.colorScheme.syntaxScheme.methodColor, convert.colorScheme.syntaxScheme.methodColor)
assertEquals(themeModel.colorScheme.syntaxScheme.stringColor, convert.colorScheme.syntaxScheme.stringColor)
assertEquals(themeModel.colorScheme.syntaxScheme.commentColor, convert.colorScheme.syntaxScheme.commentColor)
assertEquals(themeModel.colorScheme.syntaxScheme.tagColor, convert.colorScheme.syntaxScheme.tagColor)
assertEquals(themeModel.colorScheme.syntaxScheme.tagNameColor, convert.colorScheme.syntaxScheme.tagNameColor)
assertEquals(themeModel.colorScheme.syntaxScheme.attrNameColor, convert.colorScheme.syntaxScheme.attrNameColor)
assertEquals(themeModel.colorScheme.syntaxScheme.attrValueColor, convert.colorScheme.syntaxScheme.attrValueColor)
assertEquals(themeModel.colorScheme.syntaxScheme.entityRefColor, convert.colorScheme.syntaxScheme.entityRefColor)
}
} | apache-2.0 | 9e13fa44d1404f62a1740704c3b2daa2 | 55.701493 | 127 | 0.65347 | 5.464327 | false | false | false | false |
chimbori/crux | src/test/kotlin/com/chimbori/crux/common/HttpUrlExtensionsTest.kt | 1 | 3965 | package com.chimbori.crux.common
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Test
class HttpUrlExtensionsTest {
@Test
fun testIsLikelyType() {
assertEquals(true, "http://example.com/video.mp4".toHttpUrl().isLikelyVideo())
assertEquals(true, "http://example.com/video.mpg".toHttpUrl().isLikelyVideo())
assertEquals(true, "http://example.com/video.avi".toHttpUrl().isLikelyVideo())
assertEquals(false, "http://example.com/test.txt".toHttpUrl().isLikelyVideo())
assertEquals(false, "http://example.com/test.tmp".toHttpUrl().isLikelyVideo())
assertEquals(false, "http://example.com/test.log".toHttpUrl().isLikelyVideo())
}
@Test
fun testURLsRejectedByJavaNetURIsStrictParser() {
assertNotNull("http://example.com/?parameter={invalid-character}".toHttpUrlOrNull())
}
@Test
fun testNoOpRedirects() {
val exampleNoRedirects = "http://example.com".toHttpUrl().resolveRedirects()
assertEquals("http://example.com/", exampleNoRedirects.toString())
assertEquals(true, exampleNoRedirects.isLikelyArticle())
}
@Test
fun testRedirects() {
assertEquals(
"http://www.bet.com/collegemarketingreps",
"http://www.facebook.com/l.php?u=http%3A%2F%2Fwww.bet.com%2Fcollegemarketingreps&h=42263"
.toHttpUrl().resolveRedirects().toString()
)
assertEquals(
"https://www.wired.com/2014/08/maryam-mirzakhani-fields-medal/",
"https://lm.facebook.com/l.php?u=https%3A%2F%2Fwww.wired.com%2F2014%2F08%2Fmaryam-mirzakhani-fields-medal%2F&h=ATMfLBdoriaBcr9HOvzkEe68VZ4hLhTiFINvMmq5_e6fC9yi3xe957is3nl8VJSWhUO_7BdOp7Yv9CHx6MwQaTkwbZ1CKgSQCt45CROzUw0C37Tp4V-2EvDSBuBM2H-Qew&enc=AZPhspzfaWR0HGkmbExT_AfCFThsP829S0z2UWadB7ponM3YguqyJXgtn2E9BAv_-IdZvW583OnNC9M6WroEsV1jlilk3FXS4ppeydAzaJU_o9gq6HvoGMj0N_SiIKHRE_Gamq8xVdEGPnCJi078X8fTEW_jrkwpPC6P6p5Z3gv6YkFZfskU6J9qe3YRyarG4dgM25dJFnVgxxH-qyHlHsYbMD69i2MF8QNreww1J6S84y6VbIxXC-m9dVfFlNQVmtWMUvJKDLcPmYNysyQSYvkknfZ9SgwBhimurLFmKWhf39nNNVYjjCszCJ1XT57xX0Q&s=1"
.toHttpUrl().resolveRedirects().toString()
)
assertEquals(
"http://www.cnn.com/2017/01/25/politics/scientists-march-dc-trnd/index.html",
"http://lm.facebook.com/l.php?u=http%3A%2F%2Fwww.cnn.com%2F2017%2F01%2F25%2Fpolitics%2Fscientists-march-dc-trnd%2Findex.html&h=ATO7Ln_rl7DAjRcqSo8yfpOvrFlEmKZmgeYHsOforgXsUYPLDy3nC1KfCYE-hev5oJzz1zydvvzI4utABjHqU1ruwDfw49jiDGCTrjFF-EyE6xfcbWRmDacY_6_R-lSi9g&enc=AZP1hkQfMXuV0vOHa1VeY8kdip2N73EjbXMKx3Zf4Ytdb1MrGHL48by4cl9_DShGYj9nZXvNt9xad9_4jphO9QBpRJLNGoyrRMBHI09eoFyPmxxjw7hHBy5Ouez0q7psi1uvjiphzOKVxjxyYBWnTJKD7m8rvhFz0HespmfvCf-fUiCpi6NDpxwYEw7vZ99fcjOpkiQqaFM_Gvqeat7r0e8axnqM-pJGY0fkjgWvgwTyfiB4fNMRhH3IaAmyL7DXl0xeYMoYSHuITkjTY9aU5dkiETfDVwBABOO9FJi2nTnRMw92E-gMMbiHFoHENlaSVJc&s=1"
.toHttpUrl().resolveRedirects().toString()
)
assertEquals(
"https://arstechnica.com/business/2017/01/before-the-760mph-hyperloop-dream-there-was-the-atmospheric-railway/",
"https://plus.url.google.com/url?q=https://arstechnica.com/business/2017/01/before-the-760mph-hyperloop-dream-there-was-the-atmospheric-railway/&rct=j&ust=1485739059621000&usg=AFQjCNH6Cgp4iU0NB5OoDpT3OtOXds7HQg"
.toHttpUrl().resolveRedirects().toString()
)
}
@Test
fun testGoogleRedirectors() {
assertEquals(
"https://www.facebook.com/permalink.php?id=111262459538815&story_fbid=534292497235807",
"https://www.google.com/url?q=https://www.google.com/url?rct%3Dj%26sa%3Dt%26url%3Dhttps://www.facebook.com/permalink.php%253Fid%253D111262459538815%2526story_fbid%253D534292497235807%26ct%3Dga%26cd%3DCAEYACoTOTQxMTQ5NzcyMzExMjAwMTEyMzIcZWNjZWI5M2YwM2E5ZDJiODpjb206ZW46VVM6TA%26usg%3DAFQjCNFSwGsQjcbeVCaSO2rg90RgBpQvzA&source=gmail&ust=1589164930980000&usg=AFQjCNF37pEGpMAz7azFCry-Ib-hwR0VVw"
.toHttpUrl().resolveRedirects().toString()
)
}
}
| apache-2.0 | 94ba6b00d9e371e7e0ba35a54d452b72 | 60.953125 | 596 | 0.793443 | 2.387116 | false | true | false | false |
ibaton/3House | mobile/src/main/java/treehou/se/habit/ui/adapter/ControllerAdapter.kt | 1 | 3182 | package treehou.se.habit.ui.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import treehou.se.habit.R
import treehou.se.habit.core.db.model.controller.ControllerDB
import java.util.*
class ControllerAdapter(private val context: Context) : RecyclerView.Adapter<ControllerAdapter.ControllerHolder>() {
private val items = ArrayList<ControllerDB>()
private var itemListener: ItemListener = DummyItemListener()
inner class ControllerHolder(view: View) : RecyclerView.ViewHolder(view) {
val lblName: TextView
init {
lblName = view.findViewById<View>(R.id.lbl_controller) as TextView
}
}
override fun onCreateViewHolder(viewGroup: ViewGroup, position: Int): ControllerHolder {
val inflater = LayoutInflater.from(context)
val itemView = inflater.inflate(R.layout.item_controller, viewGroup, false)
return ControllerHolder(itemView)
}
override fun onBindViewHolder(controllerHolder: ControllerHolder, position: Int) {
val controller = items[position]
controllerHolder.lblName.text = controller.name
controllerHolder.itemView.setOnClickListener { v -> itemListener.itemClickListener(controllerHolder) }
controllerHolder.itemView.setOnLongClickListener { v -> itemListener.itemLongClickListener(controllerHolder) }
}
override fun getItemCount(): Int {
return items.size
}
interface ItemListener {
fun itemCountUpdated(itemCount: Int)
fun itemClickListener(controllerHolder: ControllerHolder)
fun itemLongClickListener(controllerHolder: ControllerHolder): Boolean
}
internal inner class DummyItemListener : ItemListener {
override fun itemCountUpdated(itemCount: Int) {}
override fun itemClickListener(controllerHolder: ControllerHolder) {}
override fun itemLongClickListener(controllerHolder: ControllerHolder): Boolean {
return false
}
}
fun setItemListener(itemListener: ItemListener?) {
if (itemListener == null) {
this.itemListener = DummyItemListener()
return
}
this.itemListener = itemListener
}
fun getItem(position: Int): ControllerDB {
return items[position]
}
fun removeItem(position: Int) {
Log.d(TAG, "removeItem: " + position)
items.removeAt(position)
notifyItemRemoved(position)
itemListener.itemCountUpdated(items.size)
}
fun addItem(controller: ControllerDB) {
items.add(0, controller)
notifyItemInserted(0)
itemListener.itemCountUpdated(items.size)
}
fun addAll(controllers: List<ControllerDB>) {
for (controller in controllers) {
items.add(0, controller)
notifyItemRangeInserted(0, controllers.size)
}
itemListener.itemCountUpdated(items.size)
}
companion object {
private val TAG = ControllerAdapter::class.java.simpleName
}
}
| epl-1.0 | 2fa84dd5fa586bc35818b7d7019cb82c | 30.196078 | 118 | 0.699874 | 4.843227 | false | false | false | false |
bbodi/KotlinReactSpringBootstrap | frontend/src/hu/nevermind/reakt/bootstrap/react_bootstrap.kt | 1 | 10623 | package hu.nevermind.reakt.bootstrap
import com.github.andrewoma.react.*
fun <P> Component.externalReactClass(thisComp: ReactComponent<P, *>,
prop: P,
properties: P.() -> Unit = {},
init: Component.() -> Unit = {}) {
this.constructAndInsert(Component({
val children = {
if (it.children.isEmpty()) null else it.transformChildren()
}
react.createElement(thisComp, initProps(prop, properties), children())
}), init)
}
fun createReactElement(init: Component.() -> Unit): Any {
return Component({ 0 }).run {
this.init()
require(this.children.size == 1, {"You can only return one node!"})
this.children[0].transform()
}
}
object BsStyle {
val Primary: BsStyle = js("'primary'")
val Default: BsStyle = js("'default'")
val Success: BsStyle = js("'success'")
val Info: BsStyle = js("'info'")
val Warning: BsStyle = js("'warning'")
val Danger: BsStyle = js("'danger'")
val Error: BsStyle = js("'error'")
val Link: BsStyle = js("'link'")
}
object BsButtonType {
val Button: BsButtonType = js("'button'")
val Reset: BsButtonType = js("'reset'")
val Submit: BsButtonType = js("'submit'")
}
object BsSize {
val Large: BsStyle = js("'large'")
val Small: BsStyle = js("'small'")
val ExtraSmall: BsStyle = js("'xsmall'")
}
class MenuItemProperties : HtmlGlobalProperties() {
var eventKey: Any by Property()
var href: String by Property()
var active: Boolean by Property()
var divider: Boolean by Property()
}
fun Component.bsMenuItem(
properties: MenuItemProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass(
js("ReactBootstrap.MenuItem"),
MenuItemProperties(), properties,
init)
}
fun Component.bsMenuItemDivider(
properties: MenuItemProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass(
js("ReactBootstrap.MenuItem"),
MenuItemProperties(), properties,
init)
}
class ButtonToolbarProperties {
}
fun Component.bsButtonToolbar(
properties: ButtonToolbarProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass<ButtonToolbarProperties>(
js("ReactBootstrap.ButtonToolbar"),
ButtonToolbarProperties(), properties,
init)
}
class ButtonGroupProperties {
var bsSize: BsStyle by Property()
var vertical: Boolean by Property()
var block: Boolean by Property()
var justified: Boolean by Property()
}
fun Component.bsButtonGroup(
properties: ButtonGroupProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass(
js("ReactBootstrap.ButtonGroup"),
ButtonGroupProperties(), properties,
init)
}
class ButtonProperties : HtmlGlobalProperties() {
var bsStyle: BsStyle by Property()
var bsSize: BsStyle by Property()
var type: BsButtonType by Property()
var block: Boolean by Property()
var active: Boolean by Property()
var disabled: Boolean by Property()
var href: String by Property()
}
fun Component.bsButton(
properties: ButtonProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass(
js("ReactBootstrap.Button"),
ButtonProperties(), properties,
init)
}
class DropdownButtonProperties {
var bsStyle: BsStyle by Property()
var bsSize: BsStyle by Property()
var block: Boolean by Property()
var active: Boolean by Property()
var disabled: Boolean by Property()
var href: String by Property()
var title: String by Property()
}
fun Component.bsDropdownButton(
properties: DropdownButtonProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass(
js("ReactBootstrap.DropdownButton"),
DropdownButtonProperties(), properties,
init)
}
class GridProperties : HtmlGlobalProperties() {
var fluid: Boolean by Property()
}
fun Component.bsGrid(
properties: GridProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass(
js("ReactBootstrap.Grid"),
GridProperties(), properties,
init)
}
class RowProperties {
}
fun Component.bsRow(
properties: RowProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass<RowProperties>(
js("ReactBootstrap.Row"),
RowProperties(), properties,
init)
}
class ColProperties {
var lg: Int by Property()
var lgHidden: Boolean by Property()
var lgOffset: Int by Property()
var lgPush: Int by Property()
var lgPull: Int by Property()
var md: Int by Property()
var mdHidden: Boolean by Property()
var mdOffset: Int by Property()
var mdPush: Int by Property()
var mdPull: Int by Property()
var sm: Int by Property()
var smHidden: Boolean by Property()
var smOffset: Int by Property()
var smPush: Int by Property()
var smPull: Int by Property()
var xs: Int by Property()
var xsHidden: Boolean by Property()
var xsOffset: Int by Property()
var xsPush: Int by Property()
var xsPull: Int by Property()
}
fun Component.bsCol(
properties: ColProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass<ColProperties>(
js("ReactBootstrap.Col"),
ColProperties(), properties,
init)
}
class NavbarProperties() {
}
class HeaderProperties() {
}
class BrandProperties() {
}
fun Component.bsNavbarHeader(
properties: HeaderProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass<HeaderProperties>(
js("ReactBootstrap.Navbar. Header"),
HeaderProperties(), properties,
init)
}
fun Component.bsNavbarBrand(
properties: BrandProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass<BrandProperties>(
js("ReactBootstrap.Navbar. Brand"),
BrandProperties(), properties,
init)
}
fun Component.bsNavbar(
properties: NavbarProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass<NavbarProperties>(
js("ReactBootstrap.Navbar"),
NavbarProperties(), properties,
init)
}
class NavProperties {
var pullRight: Boolean by Property()
var activeKey: Any by Property()
}
fun Component.bsNav(
properties: NavProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass<NavProperties>(
js("ReactBootstrap.Nav"),
NavProperties(), properties,
init)
}
val nullHref = js("'javascript:;'")
class NavItemProperties : HtmlGlobalProperties() {
var eventKey: Any by Property()
var href: String by Property()
var active: Boolean by Property()
var divider: Boolean by Property()
}
fun Component.bsNavItem(
properties: NavItemProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass<NavItemProperties>(
js("ReactBootstrap.NavItem"),
NavItemProperties(), properties,
init)
}
class NavDropdownProperties : HtmlGlobalProperties() {
var eventKey: Any by Property()
var title: String by Property()
}
fun Component.bsNavDropdown(
properties: NavDropdownProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass<NavDropdownProperties>(
js("ReactBootstrap.NavDropdown"),
NavDropdownProperties(), properties,
init)
}
class ModalProperties : HtmlGlobalProperties() {
var show: Boolean by Property()
var onHide: () -> Unit by Property()
}
fun Component.bsModal(
properties: ModalProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass<ModalProperties>(
js("ReactBootstrap.Modal"),
ModalProperties(), properties,
init)
}
class ModalHeaderProperties {
var closeButton: Boolean by Property()
}
fun Component.bsModalHeader(
properties: ModalHeaderProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass<ModalHeaderProperties>(
js("ReactBootstrap.ModalHeader"),
ModalHeaderProperties(), properties,
init)
}
class ModalFooterProperties {
var closeButton: Boolean by Property()
}
fun Component.bsModalFooter(
properties: ModalFooterProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass<ModalFooterProperties>(
js("ReactBootstrap.ModalFooter"),
ModalFooterProperties(), properties,
init)
}
class ModalBodyProperties {
var closeButton: Boolean by Property()
}
fun Component.bsModalBody(
properties: ModalBodyProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass<ModalBodyProperties>(
js("ReactBootstrap.ModalBody"),
ModalBodyProperties(), properties,
init)
}
class ModalTitleProperties {
var closeButton: Boolean by Property()
}
fun Component.bsModalTitle(
properties: ModalTitleProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass<ModalTitleProperties>(
js("ReactBootstrap.ModalTitle"),
ModalTitleProperties(), properties,
init)
}
class BsInputProperties : InputProperties() {
var label: String by Property()
var bsStyle: BsStyle by Property()
var help: String by Property()
var wrapperClassName: String by Property()
var labelClassName: String by Property()
}
fun Component.bsInput(
properties: BsInputProperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass(
js("ReactBootstrap.Input"),
BsInputProperties(), properties,
init)
}
class BsLabelproperties {
var bsStyle: BsStyle by Property()
}
fun Component.bsLabel(
properties: BsLabelproperties.() -> Unit = {},
init: Component.() -> Unit = {}) {
externalReactClass(
js("ReactBootstrap.Label"),
BsLabelproperties(), properties,
init)
} | mit | 7d884a98a4dfead7db2597acf03c4a61 | 26.523316 | 78 | 0.609903 | 4.487959 | false | false | false | false |
mockk/mockk | modules/mockk/src/jsMain/kotlin/io/mockk/impl/instantiation/JsMockFactory.kt | 1 | 4491 | package io.mockk.impl.instantiation
import io.mockk.MethodDescription
import io.mockk.impl.log.Logger
import io.mockk.impl.stub.Stub
import io.mockk.impl.stub.StubGatewayAccess
import io.mockk.impl.stub.StubRepository
import kotlin.reflect.KClass
class JsMockFactory(
stubRepository: StubRepository,
instantiator: JsInstantiator,
gatewayAccess: StubGatewayAccess
) :
AbstractMockFactory(
stubRepository,
instantiator,
gatewayAccess
) {
@Suppress("UNCHECKED_CAST")
override fun <T : Any> newProxy(
cls: KClass<out T>,
moreInterfaces: Array<out KClass<*>>,
stub: Stub,
useDefaultConstructor: Boolean,
instantiate: Boolean
): T {
val stubProxyTarget = js("function () {}")
stubProxyTarget.toString = { stub.toStr() }
return Proxy(
stubProxyTarget,
StubProxyHandler(stub, cls)
) as T
}
companion object {
val log = Logger<JsMockFactory>()
}
}
internal external interface ProxyHandler {
fun get(target: dynamic, name: String, receiver: dynamic): Any?
fun apply(target: dynamic, thisValue: dynamic, args: Array<*>): Any?
}
internal abstract class EmptyProxyHandler : ProxyHandler {
protected fun isJsNativeMethods(name: String) =
name in listOf(
"kotlinHashCodeValue\$",
"\$metadata\$",
"prototype",
"constructor",
"equals",
"hashCode",
"toString",
"stub",
"length"
)
override fun get(target: dynamic, name: String, receiver: dynamic): Any? =
throw UnsupportedOperationException("get")
override fun apply(target: dynamic, thisValue: dynamic, args: Array<*>): Any? =
throw UnsupportedOperationException("apply")
}
internal external class Proxy(target: dynamic, handler: ProxyHandler)
internal class StubProxyHandler(
val stub: Stub,
val cls: KClass<*>
) : EmptyProxyHandler() {
override fun get(target: dynamic, name: String, receiver: dynamic): Any? {
if (isJsNativeMethods(name)) {
return target[name]
}
return stub.handleInvocation(
receiver,
MethodDescription(
"get_$name",
Any::class,
false,
false,
false,
false,
cls,
listOf(),
-1,
false
),
{ originalCall(target, receiver, arrayOf<Any>()) },
arrayOf(),
{ null }
)
// return super.get(target, name, receiver)
}
fun originalCall(target: dynamic, thisValue: dynamic, args: Array<*>): Any? {
return js("target.apply(thisValue, args)")
}
override fun apply(target: dynamic, thisValue: dynamic, args: Array<*>): Any? {
return stub.handleInvocation(
thisValue,
MethodDescription(
"apply",
Any::class,
false,
false,
false,
false,
cls,
listOf(),
-1,
false
),
{ originalCall(target, thisValue, args) },
args.map { unboxChar(it) }.toTypedArray(),
{ null }
)
}
private fun unboxChar(value: Any?): Any? {
if (value is Char) {
return value.toInt()
} else {
return value
}
}
}
//internal class StubProxyHandler(val cls: KClass<*>, val stub: Stub) : EmptyProxyHandler() {
// override fun get(target: dynamic, name: String, receiver: dynamic): Any {
// if (isJsNativeMethods(name) || name == "stub") {
// return target[name]
// }
//
// val targetMember = if (checkKeyExists(name, target)) {
// if (checkJsFunction(target[name])) {
// target[name]
// } else {
// return target[name]
// }
// } else {
// js("function (){}")
// }
// return Proxy(
// targetMember,
// OperationProxyHandler(name, stub, cls, receiver)
// )
// }
//
// private fun checkKeyExists(name: String, target: dynamic): Boolean = js("name in target")
// private fun checkJsFunction(value: dynamic): Boolean = js("value instanceof Function")
//}
| apache-2.0 | 99f09fb31aee5bf0d999b2f76915af9d | 26.89441 | 95 | 0.541305 | 4.582653 | false | false | false | false |
rhdunn/marklogic-intellij-plugin | src/main/java/uk/co/reecedunn/intellij/plugin/marklogic/ui/log/MarkLogicLogViewFactory.kt | 1 | 1517 | /*
* Copyright (C) 2017 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.marklogic.ui.log
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.ui.content.ContentFactory
class MarkLogicLogViewFactory : ToolWindowFactory, DumbAware {
private var mLogView: MarkLogicLogViewUI? = null
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
if (mLogView == null) {
mLogView = MarkLogicLogViewUI(project)
}
val content = ContentFactory.SERVICE.getInstance().createContent(mLogView!!.panel, null, false)
val contentManager = toolWindow.contentManager
contentManager.removeAllContents(true)
contentManager.addContent(content)
contentManager.setSelectedContent(content)
toolWindow.show(null)
}
}
| apache-2.0 | 9e9cb3614d56cd01ac11f90ee8c47e18 | 37.897436 | 103 | 0.748187 | 4.409884 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-Coroutines/src/main/kotlin/core/concurrency/01_ConcurrencyProblem.kt | 2 | 1256 | package core.concurrency
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.system.measureTimeMillis
/*
协程可用多线程调度器(比如默认的 Dispatchers.Default)并发执行。这样就可以提出所有常见的并发问题。主要的问题是同步访问共享的可变状态。
协程领域对这个问题的一些解决方案类似于多线程领域中的解决方案, 但其它解决方案则是独一无二的。
常见的并发问题如下,不安全的累加一个数,得不到预期的结果
*/
private suspend fun CoroutineScope.massiveRun(action: suspend () -> Unit) {
val n = 100 // number of coroutines to launch
val k = 1000 // times an action is repeated by each coroutine
val time = measureTimeMillis {
val jobs = List(n) {
launch {
repeat(k) { action() }
}
}
jobs.forEach { it.join() }
}
println("Completed ${n * k} actions in $time ms")
}
private var counter = 0
fun main() = runBlocking<Unit> {
//sampleStart
GlobalScope.massiveRun {
counter++
}
println("Counter = $counter")
//sampleEnd
} | apache-2.0 | f5de028cef6da114450a34bdf38a780d | 25.184211 | 77 | 0.686117 | 3.33557 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/ParcelableStatusLoader.kt | 1 | 3894 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.loader
import android.accounts.AccountManager
import android.content.Context
import android.os.Bundle
import android.support.v4.content.FixedAsyncTaskLoader
import org.mariotaku.ktextension.set
import de.vanita5.microblog.library.MicroBlogException
import de.vanita5.microblog.library.twitter.model.ErrorInfo
import org.mariotaku.restfu.http.RestHttpClient
import de.vanita5.twittnuker.constant.IntentConstants
import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_ACCOUNT
import de.vanita5.twittnuker.extension.model.updateExtraInformation
import de.vanita5.twittnuker.model.ParcelableStatus
import de.vanita5.twittnuker.model.SingleResponse
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.util.AccountUtils
import de.vanita5.twittnuker.util.DataStoreUtils
import de.vanita5.twittnuker.util.UserColorNameManager
import de.vanita5.twittnuker.util.dagger.GeneralComponent
import de.vanita5.twittnuker.util.deleteActivityStatus
import javax.inject.Inject
class ParcelableStatusLoader(
context: Context,
private val omitIntentExtra: Boolean,
private val extras: Bundle?,
private val accountKey: UserKey?,
private val statusId: String?
) : FixedAsyncTaskLoader<SingleResponse<ParcelableStatus>>(context) {
@Inject
internal lateinit var userColorNameManager: UserColorNameManager
@Inject
internal lateinit var restHttpClient: RestHttpClient
init {
GeneralComponent.get(context).inject(this)
}
override fun loadInBackground(): SingleResponse<ParcelableStatus> {
if (accountKey == null || statusId == null) {
return SingleResponse(IllegalArgumentException())
}
val details = AccountUtils.getAccountDetails(AccountManager.get(context), accountKey, true)
if (!omitIntentExtra && extras != null) {
val cache: ParcelableStatus? = extras.getParcelable(IntentConstants.EXTRA_STATUS)
if (cache != null) {
val response = SingleResponse(cache)
response.extras[EXTRA_ACCOUNT] = details
return response
}
}
if (details == null) return SingleResponse(MicroBlogException("No account"))
try {
val status = DataStoreUtils.findStatus(context, accountKey, statusId)
status.updateExtraInformation(details)
val response = SingleResponse(status)
response.extras[EXTRA_ACCOUNT] = details
return response
} catch (e: MicroBlogException) {
if (e.errorCode == ErrorInfo.STATUS_NOT_FOUND) {
// Delete all deleted status
val cr = context.contentResolver
DataStoreUtils.deleteStatus(cr, accountKey, statusId, null)
cr.deleteActivityStatus(accountKey, statusId, null)
}
return SingleResponse(e)
}
}
override fun onStartLoading() {
forceLoad()
}
} | gpl-3.0 | c3e236fb730ddf5bd532c6be21dc4fc8 | 37.95 | 99 | 0.716744 | 4.714286 | false | false | false | false |
cjkent/osiris | core/src/test/kotlin/ws/osiris/core/ContentTypeTest.kt | 1 | 2207 | package ws.osiris.core
import org.testng.annotations.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
@Test
class ContentTypeTest {
fun parseSimple() {
val (mimeType, charset) = ContentType.parse("text/plain; charset=UTF-8")
assertEquals("text/plain", mimeType)
assertEquals(Charsets.UTF_8, charset)
}
fun parseWithWhitespace() {
val (mimeType, charset) = ContentType.parse(" text/plain ; charset=UTF-8 ")
assertEquals("text/plain", mimeType)
assertEquals(Charsets.UTF_8, charset)
}
fun parseNoWhitespace() {
val (mimeType, charset) = ContentType.parse("text/plain;charset=UTF-8")
assertEquals("text/plain", mimeType)
assertEquals(Charsets.UTF_8, charset)
}
fun parseUppercaseCharset() {
val (mimeType, charset) = ContentType.parse("text/plain; CHARSET=UTF-8")
assertEquals("text/plain", mimeType)
assertEquals(Charsets.UTF_8, charset)
}
fun parseNoCharset() {
val (mimeType, charset) = ContentType.parse("text/plain")
assertEquals("text/plain", mimeType)
assertNull(charset)
}
fun header() {
assertEquals("text/plain; charset=UTF-8", ContentType("text/plain", Charsets.UTF_8).header)
}
fun headerNoCharset() {
assertEquals("text/plain", ContentType("text/plain").header)
assertEquals("text/plain", ContentType(" text/plain ").header)
}
fun multipartForm() {
val contentType = ContentType.parse("multipart/form-data;boundary=abc123")
assertEquals(contentType.mimeType, "multipart/form-data")
assertEquals(contentType.header, "multipart/form-data; boundary=abc123")
assertEquals(contentType.boundary, "abc123")
assertNull(contentType.charset)
}
fun multipartFormWithWhitespace() {
val contentType = ContentType.parse(" multipart/form-data ; boundary=abc123 ")
assertEquals(contentType.mimeType, "multipart/form-data")
assertEquals(contentType.header, "multipart/form-data; boundary=abc123")
assertEquals(contentType.boundary, "abc123")
assertNull(contentType.charset)
}
}
| apache-2.0 | 83e35c64b022293e8aec699af167828b | 33.484375 | 99 | 0.667875 | 4.244231 | false | true | false | false |
AndroidX/androidx | compose/ui/ui-text/src/androidMain/kotlin/androidx/compose/ui/text/AndroidParagraph.android.kt | 3 | 24889 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text
import java.util.Locale as JavaLocale
import android.os.Build
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import androidx.annotation.VisibleForTesting
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.graphics.asComposePath
import androidx.compose.ui.graphics.drawscope.DrawStyle
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.text.android.InternalPlatformTextApi
import androidx.compose.ui.text.android.LayoutCompat.ALIGN_CENTER
import androidx.compose.ui.text.android.LayoutCompat.ALIGN_LEFT
import androidx.compose.ui.text.android.LayoutCompat.ALIGN_NORMAL
import androidx.compose.ui.text.android.LayoutCompat.ALIGN_OPPOSITE
import androidx.compose.ui.text.android.LayoutCompat.ALIGN_RIGHT
import androidx.compose.ui.text.android.LayoutCompat.BREAK_STRATEGY_BALANCED
import androidx.compose.ui.text.android.LayoutCompat.BREAK_STRATEGY_HIGH_QUALITY
import androidx.compose.ui.text.android.LayoutCompat.BREAK_STRATEGY_SIMPLE
import androidx.compose.ui.text.android.LayoutCompat.DEFAULT_ALIGNMENT
import androidx.compose.ui.text.android.LayoutCompat.DEFAULT_HYPHENATION_FREQUENCY
import androidx.compose.ui.text.android.LayoutCompat.DEFAULT_BREAK_STRATEGY
import androidx.compose.ui.text.android.LayoutCompat.DEFAULT_JUSTIFICATION_MODE
import androidx.compose.ui.text.android.LayoutCompat.DEFAULT_LINESPACING_MULTIPLIER
import androidx.compose.ui.text.android.LayoutCompat.HYPHENATION_FREQUENCY_NONE
import androidx.compose.ui.text.android.LayoutCompat.HYPHENATION_FREQUENCY_NORMAL
import androidx.compose.ui.text.android.LayoutCompat.HYPHENATION_FREQUENCY_NORMAL_FAST
import androidx.compose.ui.text.android.LayoutCompat.DEFAULT_LINE_BREAK_STYLE
import androidx.compose.ui.text.android.LayoutCompat.DEFAULT_LINE_BREAK_WORD_STYLE
import androidx.compose.ui.text.android.LayoutCompat.JUSTIFICATION_MODE_INTER_WORD
import androidx.compose.ui.text.android.LayoutCompat.LINE_BREAK_STYLE_LOOSE
import androidx.compose.ui.text.android.LayoutCompat.LINE_BREAK_STYLE_NONE
import androidx.compose.ui.text.android.LayoutCompat.LINE_BREAK_STYLE_NORMAL
import androidx.compose.ui.text.android.LayoutCompat.LINE_BREAK_STYLE_STRICT
import androidx.compose.ui.text.android.LayoutCompat.LINE_BREAK_WORD_STYLE_NONE
import androidx.compose.ui.text.android.LayoutCompat.LINE_BREAK_WORD_STYLE_PHRASE
import androidx.compose.ui.text.android.TextLayout
import androidx.compose.ui.text.android.selection.WordBoundary
import androidx.compose.ui.text.android.style.IndentationFixSpan
import androidx.compose.ui.text.android.style.PlaceholderSpan
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.platform.AndroidParagraphIntrinsics
import androidx.compose.ui.text.platform.AndroidTextPaint
import androidx.compose.ui.text.platform.extensions.setSpan
import androidx.compose.ui.text.platform.isIncludeFontPaddingEnabled
import androidx.compose.ui.text.platform.style.ShaderBrushSpan
import androidx.compose.ui.text.style.Hyphens
import androidx.compose.ui.text.style.LineBreak
import androidx.compose.ui.text.style.ResolvedTextDirection
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.sp
/**
* Android specific implementation for [Paragraph]
*/
// NOTE(text-perf-review): I see most of the APIs in this class just delegate to TextLayout or to
// AndroidParagraphIntrinsics. Should we consider just having one TextLayout class which
// implements Paragraph and ParagraphIntrinsics? it seems like all of these types are immutable
// and have similar sets of responsibilities.
@OptIn(InternalPlatformTextApi::class, ExperimentalTextApi::class)
internal class AndroidParagraph(
val paragraphIntrinsics: AndroidParagraphIntrinsics,
val maxLines: Int,
val ellipsis: Boolean,
val constraints: Constraints
) : Paragraph {
constructor(
text: String,
style: TextStyle,
spanStyles: List<AnnotatedString.Range<SpanStyle>>,
placeholders: List<AnnotatedString.Range<Placeholder>>,
maxLines: Int,
ellipsis: Boolean,
constraints: Constraints,
fontFamilyResolver: FontFamily.Resolver,
density: Density
) : this(
paragraphIntrinsics = AndroidParagraphIntrinsics(
text = text,
style = style,
placeholders = placeholders,
spanStyles = spanStyles,
fontFamilyResolver = fontFamilyResolver,
density = density
),
maxLines = maxLines,
ellipsis = ellipsis,
constraints = constraints
)
private val layout: TextLayout
@VisibleForTesting
internal val charSequence: CharSequence
init {
require(constraints.minHeight == 0 && constraints.minWidth == 0) {
"Setting Constraints.minWidth and Constraints.minHeight is not supported, " +
"these should be the default zero values instead."
}
require(maxLines >= 1) { "maxLines should be greater than 0" }
val style = paragraphIntrinsics.style
charSequence = if (shouldAttachIndentationFixSpan(style, ellipsis)) {
// When letter spacing, align and ellipsize applied to text, the ellipsized line is
// indented wrong. This function adds the IndentationFixSpan in order to fix the issue
// with best effort. b/228463206
paragraphIntrinsics.charSequence.attachIndentationFixSpan()
} else {
paragraphIntrinsics.charSequence
}
val alignment = toLayoutAlign(style.textAlign)
val justificationMode = when (style.textAlign) {
TextAlign.Justify -> JUSTIFICATION_MODE_INTER_WORD
else -> DEFAULT_JUSTIFICATION_MODE
}
val hyphens = toLayoutHyphenationFrequency(style.paragraphStyle.hyphens)
val breakStrategy = toLayoutBreakStrategy(style.lineBreak?.strategy)
val lineBreakStyle = toLayoutLineBreakStyle(style.lineBreak?.strictness)
val lineBreakWordStyle = toLayoutLineBreakWordStyle(style.lineBreak?.wordBreak)
val ellipsize = if (ellipsis) {
TextUtils.TruncateAt.END
} else {
null
}
val firstLayout = constructTextLayout(
alignment = alignment,
justificationMode = justificationMode,
ellipsize = ellipsize,
maxLines = maxLines,
hyphens = hyphens,
breakStrategy = breakStrategy,
lineBreakStyle = lineBreakStyle,
lineBreakWordStyle = lineBreakWordStyle
)
// Ellipsize if there's not enough vertical space to fit all lines
if (ellipsis && firstLayout.height > constraints.maxHeight && maxLines > 1) {
val calculatedMaxLines =
firstLayout.numberOfLinesThatFitMaxHeight(constraints.maxHeight)
layout = if (calculatedMaxLines >= 0 && calculatedMaxLines != maxLines) {
constructTextLayout(
alignment = alignment,
justificationMode = justificationMode,
ellipsize = ellipsize,
// When we can't fully fit even a single line, measure with one line anyway.
// This will allow to have an ellipsis on that single line. If we measured with
// 0 maxLines, it would measure all lines with no ellipsis even though the first
// line might be partially visible
maxLines = calculatedMaxLines.coerceAtLeast(1),
hyphens = hyphens,
breakStrategy = breakStrategy,
lineBreakStyle = lineBreakStyle,
lineBreakWordStyle = lineBreakWordStyle
)
} else {
firstLayout
}
} else {
layout = firstLayout
}
// Brush is not fully realized on text until layout is complete and size information
// is known. Brush can now be applied to the overall textpaint and all the spans.
textPaint.setBrush(style.brush, Size(width, height), style.alpha)
layout.getShaderBrushSpans().forEach { shaderBrushSpan ->
shaderBrushSpan.size = Size(width, height)
}
}
override val width: Float
get() = constraints.maxWidth.toFloat()
override val height: Float
get() = layout.height.toFloat()
override val maxIntrinsicWidth: Float
get() = paragraphIntrinsics.maxIntrinsicWidth
override val minIntrinsicWidth: Float
get() = paragraphIntrinsics.minIntrinsicWidth
override val firstBaseline: Float
get() = getLineBaseline(0)
override val lastBaseline: Float
get() = getLineBaseline(lineCount - 1)
override val didExceedMaxLines: Boolean
get() = layout.didExceedMaxLines
@VisibleForTesting
internal val textLocale: JavaLocale
get() = paragraphIntrinsics.textPaint.textLocale
/**
* Resolved line count. If maxLines smaller than the real number of lines in the text, this
* property will return the minimum between the two
*/
override val lineCount: Int
get() = layout.lineCount
override val placeholderRects: List<Rect?> =
with(charSequence) {
if (this !is Spanned) return@with listOf()
getSpans(0, length, PlaceholderSpan::class.java).map { span ->
val start = getSpanStart(span)
val end = getSpanEnd(span)
// The line index of the PlaceholderSpan. In the case where PlaceholderSpan is
// truncated due to maxLines limitation. It will return the index of last line.
val line = layout.getLineForOffset(start)
val exceedsMaxLines = line >= maxLines
val isPlaceholderSpanEllipsized = layout.getLineEllipsisCount(line) > 0 &&
end > layout.getLineEllipsisOffset(line)
val isPlaceholderSpanTruncated = end > layout.getLineEnd(line)
// This Placeholder is ellipsized or truncated, return null instead.
if (isPlaceholderSpanEllipsized || isPlaceholderSpanTruncated || exceedsMaxLines) {
return@map null
}
val direction = getBidiRunDirection(start)
val left = when (direction) {
ResolvedTextDirection.Ltr ->
getHorizontalPosition(start, true)
ResolvedTextDirection.Rtl ->
getHorizontalPosition(start, true) - span.widthPx
}
val right = left + span.widthPx
val top = with(layout) {
when (span.verticalAlign) {
PlaceholderSpan.ALIGN_ABOVE_BASELINE ->
getLineBaseline(line) - span.heightPx
PlaceholderSpan.ALIGN_TOP -> getLineTop(line)
PlaceholderSpan.ALIGN_BOTTOM -> getLineBottom(line) - span.heightPx
PlaceholderSpan.ALIGN_CENTER ->
(getLineTop(line) + getLineBottom(line) - span.heightPx) / 2
PlaceholderSpan.ALIGN_TEXT_TOP ->
span.fontMetrics.ascent + getLineBaseline(line)
PlaceholderSpan.ALIGN_TEXT_BOTTOM ->
span.fontMetrics.descent + getLineBaseline(line) - span.heightPx
PlaceholderSpan.ALIGN_TEXT_CENTER ->
with(span.fontMetrics) {
(ascent + descent - span.heightPx) / 2 + getLineBaseline(line)
}
else -> throw IllegalStateException("unexpected verticalAlignment")
}
}
val bottom = top + span.heightPx
Rect(left, top, right, bottom)
}
}
@VisibleForTesting
internal val textPaint: AndroidTextPaint
get() = paragraphIntrinsics.textPaint
override fun getLineForVerticalPosition(vertical: Float): Int {
return layout.getLineForVertical(vertical.toInt())
}
override fun getOffsetForPosition(position: Offset): Int {
val line = layout.getLineForVertical(position.y.toInt())
return layout.getOffsetForHorizontal(line, position.x)
}
/**
* Returns the bounding box as Rect of the character for given character offset. Rect includes
* the top, bottom, left and right of a character.
*/
override fun getBoundingBox(offset: Int): Rect {
val rectF = layout.getBoundingBox(offset)
return with(rectF) { Rect(left = left, top = top, right = right, bottom = bottom) }
}
/**
* Fills the bounding boxes for characters provided in the [range] into [array]. The array is
* filled starting from [arrayStart] (inclusive). The coordinates are in local text layout
* coordinates.
*
* The returned information consists of left/right of a character; line top and bottom for the
* same character.
*
* For the grapheme consists of multiple code points, e.g. ligatures, combining marks, the first
* character has the total width and the remaining are returned as zero-width.
*
* The array divided into segments of four where each index in that segment represents left,
* top, right, bottom of the character.
*
* The size of the provided [array] should be greater or equal than the four times * [TextRange]
* length.
*
* The final order of characters in the [array] is from [TextRange.min] to [TextRange.max].
*
* @param range the [TextRange] representing the start and end indices in the [Paragraph].
* @param array the array to fill in the values. The array divided into segments of four where
* each index in that segment represents left, top, right, bottom of the character.
* @param arrayStart the inclusive start index in the array where the function will start
* filling in the values from
*/
fun fillBoundingBoxes(
range: TextRange,
array: FloatArray,
arrayStart: Int
) {
layout.fillBoundingBoxes(range.min, range.max, array, arrayStart)
}
override fun getPathForRange(start: Int, end: Int): Path {
if (start !in 0..end || end > charSequence.length) {
throw AssertionError(
"Start($start) or End($end) is out of Range(0..${charSequence.length})," +
" or start > end!"
)
}
val path = android.graphics.Path()
layout.getSelectionPath(start, end, path)
return path.asComposePath()
}
override fun getCursorRect(offset: Int): Rect {
if (offset !in 0..charSequence.length) {
throw AssertionError("offset($offset) is out of bounds (0,${charSequence.length}")
}
val horizontal = layout.getPrimaryHorizontal(offset)
val line = layout.getLineForOffset(offset)
// The width of the cursor is not taken into account. The callers of this API should use
// rect.left to get the start X position and then adjust it according to the width if needed
return Rect(
horizontal,
layout.getLineTop(line),
horizontal,
layout.getLineBottom(line)
)
}
private val wordBoundary: WordBoundary by lazy(LazyThreadSafetyMode.NONE) {
WordBoundary(textLocale, layout.text)
}
override fun getWordBoundary(offset: Int): TextRange {
return TextRange(wordBoundary.getWordStart(offset), wordBoundary.getWordEnd(offset))
}
override fun getLineLeft(lineIndex: Int): Float = layout.getLineLeft(lineIndex)
override fun getLineRight(lineIndex: Int): Float = layout.getLineRight(lineIndex)
override fun getLineTop(lineIndex: Int): Float = layout.getLineTop(lineIndex)
internal fun getLineAscent(lineIndex: Int): Float = layout.getLineAscent(lineIndex)
internal fun getLineBaseline(lineIndex: Int): Float = layout.getLineBaseline(lineIndex)
internal fun getLineDescent(lineIndex: Int): Float = layout.getLineDescent(lineIndex)
override fun getLineBottom(lineIndex: Int): Float = layout.getLineBottom(lineIndex)
override fun getLineHeight(lineIndex: Int): Float = layout.getLineHeight(lineIndex)
override fun getLineWidth(lineIndex: Int): Float = layout.getLineWidth(lineIndex)
override fun getLineStart(lineIndex: Int): Int = layout.getLineStart(lineIndex)
override fun getLineEnd(lineIndex: Int, visibleEnd: Boolean): Int =
if (visibleEnd) {
layout.getLineVisibleEnd(lineIndex)
} else {
layout.getLineEnd(lineIndex)
}
override fun isLineEllipsized(lineIndex: Int): Boolean = layout.isLineEllipsized(lineIndex)
override fun getLineForOffset(offset: Int): Int = layout.getLineForOffset(offset)
override fun getHorizontalPosition(offset: Int, usePrimaryDirection: Boolean): Float =
if (usePrimaryDirection) {
layout.getPrimaryHorizontal(offset)
} else {
layout.getSecondaryHorizontal(offset)
}
override fun getParagraphDirection(offset: Int): ResolvedTextDirection {
val lineIndex = layout.getLineForOffset(offset)
val direction = layout.getParagraphDirection(lineIndex)
return if (direction == 1) ResolvedTextDirection.Ltr else ResolvedTextDirection.Rtl
}
override fun getBidiRunDirection(offset: Int): ResolvedTextDirection {
return if (layout.isRtlCharAt(offset))
ResolvedTextDirection.Rtl
else
ResolvedTextDirection.Ltr
}
private fun TextLayout.getShaderBrushSpans(): Array<ShaderBrushSpan> {
if (text !is Spanned) return emptyArray()
val brushSpans = (text as Spanned).getSpans(
0, text.length, ShaderBrushSpan::class.java
)
if (brushSpans.isEmpty()) return emptyArray()
return brushSpans
}
override fun paint(
canvas: Canvas,
color: Color,
shadow: Shadow?,
textDecoration: TextDecoration?
) {
with(textPaint) {
setColor(color)
setShadow(shadow)
setTextDecoration(textDecoration)
}
paint(canvas)
}
@OptIn(ExperimentalTextApi::class)
override fun paint(
canvas: Canvas,
color: Color,
shadow: Shadow?,
textDecoration: TextDecoration?,
drawStyle: DrawStyle?
) {
with(textPaint) {
setColor(color)
setShadow(shadow)
setTextDecoration(textDecoration)
setDrawStyle(drawStyle)
}
paint(canvas)
}
@OptIn(ExperimentalTextApi::class)
override fun paint(
canvas: Canvas,
brush: Brush,
alpha: Float,
shadow: Shadow?,
textDecoration: TextDecoration?,
drawStyle: DrawStyle?
) {
with(textPaint) {
setBrush(brush, Size(width, height), alpha)
setShadow(shadow)
setTextDecoration(textDecoration)
setDrawStyle(drawStyle)
}
paint(canvas)
}
private fun paint(canvas: Canvas) {
val nativeCanvas = canvas.nativeCanvas
if (didExceedMaxLines) {
nativeCanvas.save()
nativeCanvas.clipRect(0f, 0f, width, height)
}
layout.paint(nativeCanvas)
if (didExceedMaxLines) {
nativeCanvas.restore()
}
}
private fun constructTextLayout(
alignment: Int,
justificationMode: Int,
ellipsize: TextUtils.TruncateAt?,
maxLines: Int,
hyphens: Int,
breakStrategy: Int,
lineBreakStyle: Int,
lineBreakWordStyle: Int
) =
TextLayout(
charSequence = charSequence,
width = width,
textPaint = textPaint,
ellipsize = ellipsize,
alignment = alignment,
textDirectionHeuristic = paragraphIntrinsics.textDirectionHeuristic,
lineSpacingMultiplier = DEFAULT_LINESPACING_MULTIPLIER,
maxLines = maxLines,
justificationMode = justificationMode,
layoutIntrinsics = paragraphIntrinsics.layoutIntrinsics,
includePadding = paragraphIntrinsics.style.isIncludeFontPaddingEnabled(),
fallbackLineSpacing = true,
hyphenationFrequency = hyphens,
breakStrategy = breakStrategy,
lineBreakStyle = lineBreakStyle,
lineBreakWordStyle = lineBreakWordStyle
)
}
/**
* Converts [TextAlign] into [TextLayout] alignment constants.
*/
@OptIn(InternalPlatformTextApi::class)
private fun toLayoutAlign(align: TextAlign?): Int = when (align) {
TextAlign.Left -> ALIGN_LEFT
TextAlign.Right -> ALIGN_RIGHT
TextAlign.Center -> ALIGN_CENTER
TextAlign.Start -> ALIGN_NORMAL
TextAlign.End -> ALIGN_OPPOSITE
else -> DEFAULT_ALIGNMENT
}
@OptIn(ExperimentalTextApi::class, InternalPlatformTextApi::class)
private fun toLayoutHyphenationFrequency(hyphens: Hyphens?): Int = when (hyphens) {
Hyphens.Auto -> if (Build.VERSION.SDK_INT <= 32) {
HYPHENATION_FREQUENCY_NORMAL
} else {
HYPHENATION_FREQUENCY_NORMAL_FAST
}
Hyphens.None -> HYPHENATION_FREQUENCY_NONE
else -> DEFAULT_HYPHENATION_FREQUENCY
}
@OptIn(ExperimentalTextApi::class, InternalPlatformTextApi::class)
private fun toLayoutBreakStrategy(breakStrategy: LineBreak.Strategy?): Int = when (breakStrategy) {
LineBreak.Strategy.Simple -> BREAK_STRATEGY_SIMPLE
LineBreak.Strategy.HighQuality -> BREAK_STRATEGY_HIGH_QUALITY
LineBreak.Strategy.Balanced -> BREAK_STRATEGY_BALANCED
else -> DEFAULT_BREAK_STRATEGY
}
@OptIn(ExperimentalTextApi::class, InternalPlatformTextApi::class)
private fun toLayoutLineBreakStyle(lineBreakStrictness: LineBreak.Strictness?): Int =
when (lineBreakStrictness) {
LineBreak.Strictness.Default -> LINE_BREAK_STYLE_NONE
LineBreak.Strictness.Loose -> LINE_BREAK_STYLE_LOOSE
LineBreak.Strictness.Normal -> LINE_BREAK_STYLE_NORMAL
LineBreak.Strictness.Strict -> LINE_BREAK_STYLE_STRICT
else -> DEFAULT_LINE_BREAK_STYLE
}
@OptIn(ExperimentalTextApi::class, InternalPlatformTextApi::class)
private fun toLayoutLineBreakWordStyle(lineBreakWordStyle: LineBreak.WordBreak?): Int =
when (lineBreakWordStyle) {
LineBreak.WordBreak.Default -> LINE_BREAK_WORD_STYLE_NONE
LineBreak.WordBreak.Phrase -> LINE_BREAK_WORD_STYLE_PHRASE
else -> DEFAULT_LINE_BREAK_WORD_STYLE
}
@OptIn(InternalPlatformTextApi::class)
private fun TextLayout.numberOfLinesThatFitMaxHeight(maxHeight: Int): Int {
for (lineIndex in 0 until lineCount) {
if (getLineBottom(lineIndex) > maxHeight) return lineIndex
}
return lineCount
}
private fun shouldAttachIndentationFixSpan(textStyle: TextStyle, ellipsis: Boolean) =
with(textStyle) {
ellipsis && (letterSpacing != 0.sp && letterSpacing != TextUnit.Unspecified) &&
(textAlign != null && textAlign != TextAlign.Start && textAlign != TextAlign.Justify)
}
@OptIn(InternalPlatformTextApi::class)
private fun CharSequence.attachIndentationFixSpan(): CharSequence {
if (isEmpty()) return this
val spannable = if (this is Spannable) this else SpannableString(this)
spannable.setSpan(IndentationFixSpan(), spannable.length - 1, spannable.length - 1)
return spannable
} | apache-2.0 | 5f1e34c20f8fd9e2546255e90c46c48c | 39.803279 | 100 | 0.676484 | 4.776243 | false | false | false | false |
Jonatino/JOGL2D | src/main/kotlin/org/anglur/joglext/jogl2d/impl/SimplePathVisitor.kt | 1 | 4067 | /*
* Copyright 2016 Jonathan Beaudoin <https://github.com/Jonatino>
*
* 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.anglur.joglext.jogl2d.impl
import org.anglur.joglext.cacheable.CachedFloatArray
import org.anglur.joglext.jogl2d.PathVisitor
/**
* This is a fast Bzier curve implementation. I can't use OpenGL's
* built-in evaluators because subclasses need to do something with the points,
* not just pass them directly to glVertex2f. This algorithm uses forward
* differencing. Most of this is taken from [http://www.niksula.hut.fi/~hkankaan/Homepages/bezierfast.html](http://www.niksula.hut.fi/~hkankaan/Homepages/bezierfast.html). I derived
* the implementation for the quadratic on my own, but it's simple.
*/
abstract class SimplePathVisitor : PathVisitor {
/**
* Gets the number of steps to take in a quadratic or cubic curve spline.
*/
/**
* Sets the number of steps to take in a quadratic or cubic curve spline.
*/
var numCurveSteps = CURVE_STEPS
override fun quadTo(previousVertex: FloatArray, control: FloatArray) {
val p = CachedFloatArray(2)
var xd: Float
val xdd: Float
val xdd_per_2: Float
var yd: Float
val ydd: Float
val ydd_per_2: Float
val t = 1f / numCurveSteps
val tt = t * t
// x
p[0] = previousVertex[0]
xd = 2f * (control[0] - previousVertex[0]) * t
xdd_per_2 = 1f * (previousVertex[0] - 2 * control[0] + control[2]) * tt
xdd = xdd_per_2 + xdd_per_2
// y
p[1] = previousVertex[1]
yd = 2f * (control[1] - previousVertex[1]) * t
ydd_per_2 = 1f * (previousVertex[1] - 2 * control[1] + control[3]) * tt
ydd = ydd_per_2 + ydd_per_2
for (loop in 0..numCurveSteps - 1) {
lineTo(p)
p[0] = p[0] + xd + xdd_per_2
xd += xdd
p[1] = p[1] + yd + ydd_per_2
yd += ydd
}
// use exactly the last point
p[0] = control[2]
p[1] = control[3]
lineTo(p)
}
override fun cubicTo(previousVertex: FloatArray, control: FloatArray) {
val p = CachedFloatArray(2)
var xd: Float
var xdd: Float
val xddd: Float
var xdd_per_2: Float
val xddd_per_2: Float
val xddd_per_6: Float
var yd: Float
var ydd: Float
val yddd: Float
var ydd_per_2: Float
val yddd_per_2: Float
val yddd_per_6: Float
val t = 1f / numCurveSteps
val tt = t * t
// x
p[0] = previousVertex[0]
xd = 3f * (control[0] - previousVertex[0]) * t
xdd_per_2 = 3f * (previousVertex[0] - 2 * control[0] + control[2]) * tt
xddd_per_2 = 3f * (3 * (control[0] - control[2]) + control[4] - previousVertex[0]) * tt * t
xddd = xddd_per_2 + xddd_per_2
xdd = xdd_per_2 + xdd_per_2
xddd_per_6 = xddd_per_2 / 3
// y
p[1] = previousVertex[1]
yd = 3f * (control[1] - previousVertex[1]) * t
ydd_per_2 = 3f * (previousVertex[1] - 2 * control[1] + control[3]) * tt
yddd_per_2 = 3f * (3 * (control[1] - control[3]) + control[5] - previousVertex[1]) * tt * t
yddd = yddd_per_2 + yddd_per_2
ydd = ydd_per_2 + ydd_per_2
yddd_per_6 = yddd_per_2 / 3
for (loop in 0..numCurveSteps - 1) {
lineTo(p)
p[0] = p[0] + xd + xdd_per_2 + xddd_per_6
xd += xdd + xddd_per_2
xdd += xddd
xdd_per_2 += xddd_per_2
p[1] = p[1] + yd + ydd_per_2 + yddd_per_6
yd += ydd + yddd_per_2
ydd += yddd
ydd_per_2 += yddd_per_2
}
// use exactly the last point
p[0] = control[4]
p[1] = control[5]
lineTo(p)
}
companion object {
/**
* Just a guess. Would be nice to make a better guess based on what's visually
* acceptable.
*/
val CURVE_STEPS = 30
}
}
| apache-2.0 | c2781da76af59fb01d4a7c3f4f6095ce | 27.243056 | 181 | 0.635358 | 2.689815 | false | false | false | false |
androidx/androidx | compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/snapshots/SnapshotStateList.kt | 3 | 15998 | /*
* 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.runtime.snapshots
import androidx.compose.runtime.Stable
import androidx.compose.runtime.external.kotlinx.collections.immutable.PersistentList
import androidx.compose.runtime.external.kotlinx.collections.immutable.persistentListOf
import androidx.compose.runtime.synchronized
import kotlin.jvm.JvmName
/**
* An implementation of [MutableList] that can be observed and snapshot. This is the result type
* created by [androidx.compose.runtime.mutableStateListOf].
*
* This class closely implements the same semantics as [ArrayList].
*
* @see androidx.compose.runtime.mutableStateListOf
*/
@Stable
class SnapshotStateList<T> : MutableList<T>, StateObject {
override var firstStateRecord: StateRecord =
StateListStateRecord<T>(persistentListOf())
private set
override fun prependStateRecord(value: StateRecord) {
value.next = firstStateRecord
@Suppress("UNCHECKED_CAST")
firstStateRecord = value as StateListStateRecord<T>
}
/**
* Return a list containing all the elements of this list.
*
* The list returned is immutable and returned will not change even if the content of the list
* is changed in the same snapshot. It also will be the same instance until the content is
* changed. It is not, however, guaranteed to be the same instance for the same list as adding
* and removing the same item from the this list might produce a different instance with the
* same content.
*
* This operation is O(1) and does not involve a physically copying the list. It instead
* returns the underlying immutable list used internally to store the content of the list.
*
* It is recommended to use [toList] when using returning the value of this list from
* [androidx.compose.runtime.snapshotFlow].
*/
fun toList(): List<T> = readable.list
internal val modification: Int get() = withCurrent { modification }
@Suppress("UNCHECKED_CAST")
internal val readable: StateListStateRecord<T> get() =
(firstStateRecord as StateListStateRecord<T>).readable(this)
/**
* This is an internal implementation class of [SnapshotStateList]. Do not use.
*/
internal class StateListStateRecord<T> internal constructor(
internal var list: PersistentList<T>
) : StateRecord() {
internal var modification = 0
override fun assign(value: StateRecord) {
synchronized(sync) {
@Suppress("UNCHECKED_CAST")
list = (value as StateListStateRecord<T>).list
modification = value.modification
}
}
override fun create(): StateRecord = StateListStateRecord(list)
}
override val size: Int get() = readable.list.size
override fun contains(element: T) = readable.list.contains(element)
override fun containsAll(elements: Collection<T>) = readable.list.containsAll(elements)
override fun get(index: Int) = readable.list[index]
override fun indexOf(element: T): Int = readable.list.indexOf(element)
override fun isEmpty() = readable.list.isEmpty()
override fun iterator(): MutableIterator<T> = listIterator()
override fun lastIndexOf(element: T) = readable.list.lastIndexOf(element)
override fun listIterator(): MutableListIterator<T> = StateListIterator(this, 0)
override fun listIterator(index: Int): MutableListIterator<T> = StateListIterator(this, index)
override fun subList(fromIndex: Int, toIndex: Int): MutableList<T> {
require(fromIndex in 0..toIndex && toIndex <= size)
return SubList(this, fromIndex, toIndex)
}
override fun add(element: T) = conditionalUpdate { it.add(element) }
override fun add(index: Int, element: T) = update { it.add(index, element) }
override fun addAll(index: Int, elements: Collection<T>) = mutateBoolean {
it.addAll(index, elements)
}
override fun addAll(elements: Collection<T>) = conditionalUpdate { it.addAll(elements) }
override fun clear() {
synchronized(sync) {
writable {
list = persistentListOf()
modification++
}
}
}
override fun remove(element: T) = conditionalUpdate { it.remove(element) }
override fun removeAll(elements: Collection<T>) = conditionalUpdate { it.removeAll(elements) }
override fun removeAt(index: Int): T = get(index).also { update { it.removeAt(index) } }
override fun retainAll(elements: Collection<T>) = mutateBoolean { it.retainAll(elements) }
override fun set(index: Int, element: T): T = get(index).also {
update { it.set(index, element) }
}
fun removeRange(fromIndex: Int, toIndex: Int) {
mutate {
it.subList(fromIndex, toIndex).clear()
}
}
internal fun retainAllInRange(elements: Collection<T>, start: Int, end: Int): Int {
val startSize = size
mutate<Unit> {
it.subList(start, end).retainAll(elements)
}
return startSize - size
}
/**
* An internal function used by the debugger to display the value of the current list without
* triggering read observers.
*/
@Suppress("unused")
internal val debuggerDisplayValue: List<T>
@JvmName("getDebuggerDisplayValue")
get() = withCurrent { list }
private inline fun <R> writable(block: StateListStateRecord<T>.() -> R): R =
@Suppress("UNCHECKED_CAST")
(firstStateRecord as StateListStateRecord<T>).writable(this, block)
private inline fun <R> withCurrent(block: StateListStateRecord<T>.() -> R): R =
@Suppress("UNCHECKED_CAST")
(firstStateRecord as StateListStateRecord<T>).withCurrent(block)
private fun mutateBoolean(block: (MutableList<T>) -> Boolean): Boolean = mutate(block)
private inline fun <R> mutate(block: (MutableList<T>) -> R): R {
var result: R
while (true) {
var oldList: PersistentList<T>? = null
var currentModification = 0
synchronized(sync) {
val current = withCurrent { this }
currentModification = current.modification
oldList = current.list
}
val builder = oldList!!.builder()
result = block(builder)
val newList = builder.build()
if (newList == oldList || synchronized(sync) {
writable {
if (modification == currentModification) {
list = newList
modification++
true
} else false
}
}
) break
}
return result
}
private inline fun update(block: (PersistentList<T>) -> PersistentList<T>) {
conditionalUpdate(block)
}
private inline fun conditionalUpdate(block: (PersistentList<T>) -> PersistentList<T>) =
run {
val result: Boolean
while (true) {
var oldList: PersistentList<T>? = null
var currentModification = 0
synchronized(sync) {
val current = withCurrent { this }
currentModification = current.modification
oldList = current.list
}
val newList = block(oldList!!)
if (newList == oldList) {
result = false
break
}
if (synchronized(sync) {
writable {
if (modification == currentModification) {
list = newList
modification++
true
} else false
}
}
) {
result = true
break
}
}
result
}
}
/**
* This lock is used to ensure that the value of modification and the list in the state record,
* when used together, are atomically read and written.
*
* A global sync object is used to avoid having to allocate a sync object and initialize a monitor
* for each instance the list. This avoid additional allocations but introduces some contention
* between lists. As there is already contention on the global snapshot lock to write so the
* additional contention introduced by this lock is nominal.
*
* In code the requires this lock and calls `writable` (or other operation that acquires the
* snapshot global lock), this lock *MUST* be acquired first to avoid deadlocks.
*/
private val sync = Any()
private fun modificationError(): Nothing =
error("Cannot modify a state list through an iterator")
private fun validateRange(index: Int, size: Int) {
if (index !in 0 until size) {
throw IndexOutOfBoundsException("index ($index) is out of bound of [0, $size)")
}
}
private class StateListIterator<T>(
val list: SnapshotStateList<T>,
offset: Int
) : MutableListIterator<T> {
private var index = offset - 1
private var modification = list.modification
override fun hasPrevious() = index >= 0
override fun nextIndex() = index + 1
override fun previous(): T {
validateModification()
validateRange(index, list.size)
return list[index].also { index-- }
}
override fun previousIndex(): Int = index
override fun add(element: T) {
validateModification()
list.add(index + 1, element)
index++
modification = list.modification
}
override fun hasNext() = index < list.size - 1
override fun next(): T {
validateModification()
val newIndex = index + 1
validateRange(newIndex, list.size)
return list[newIndex].also { index = newIndex }
}
override fun remove() {
validateModification()
list.removeAt(index)
index--
modification = list.modification
}
override fun set(element: T) {
validateModification()
list.set(index, element)
modification = list.modification
}
private fun validateModification() {
if (list.modification != modification) {
throw ConcurrentModificationException()
}
}
}
private class SubList<T>(
val parentList: SnapshotStateList<T>,
fromIndex: Int,
toIndex: Int
) : MutableList<T> {
private val offset = fromIndex
private var modification = parentList.modification
override var size = toIndex - fromIndex
private set
override fun contains(element: T): Boolean = indexOf(element) >= 0
override fun containsAll(elements: Collection<T>): Boolean = elements.all { contains(it) }
override fun get(index: Int): T {
validateModification()
validateRange(index, size)
return parentList[offset + index]
}
override fun indexOf(element: T): Int {
validateModification()
(offset until offset + size).forEach {
if (element == parentList[it]) return it - offset
}
return -1
}
override fun isEmpty(): Boolean = size == 0
override fun iterator(): MutableIterator<T> = listIterator()
override fun lastIndexOf(element: T): Int {
validateModification()
var index = offset + size - 1
while (index >= offset) {
if (element == parentList[index]) return index - offset
index--
}
return -1
}
override fun add(element: T): Boolean {
validateModification()
parentList.add(offset + size, element)
size++
modification = parentList.modification
return true
}
override fun add(index: Int, element: T) {
validateModification()
parentList.add(offset + index, element)
size++
modification = parentList.modification
}
override fun addAll(index: Int, elements: Collection<T>): Boolean {
validateModification()
val result = parentList.addAll(index + offset, elements)
if (result) {
size += elements.size
modification = parentList.modification
}
return result
}
override fun addAll(elements: Collection<T>): Boolean = addAll(size, elements)
override fun clear() {
if (size > 0) {
validateModification()
parentList.removeRange(offset, offset + size)
size = 0
modification = parentList.modification
}
}
override fun listIterator(): MutableListIterator<T> = listIterator(0)
override fun listIterator(index: Int): MutableListIterator<T> {
validateModification()
var current = index - 1
return object : MutableListIterator<T> {
override fun hasPrevious() = current >= 0
override fun nextIndex(): Int = current + 1
override fun previous(): T {
val oldCurrent = current
validateRange(oldCurrent, size)
current = oldCurrent - 1
return this@SubList[oldCurrent]
}
override fun previousIndex(): Int = current
override fun add(element: T) = modificationError()
override fun hasNext(): Boolean = current < size - 1
override fun next(): T {
val newCurrent = current + 1
validateRange(newCurrent, size)
current = newCurrent
return this@SubList[newCurrent]
}
override fun remove() = modificationError()
override fun set(element: T) = modificationError()
}
}
override fun remove(element: T): Boolean {
val index = indexOf(element)
return if (index >= 0) {
removeAt(index)
true
} else false
}
override fun removeAll(elements: Collection<T>): Boolean {
var removed = false
for (element in elements) {
removed = remove(element) || removed
}
return removed
}
override fun removeAt(index: Int): T {
validateModification()
return parentList.removeAt(offset + index).also {
size--
modification = parentList.modification
}
}
override fun retainAll(elements: Collection<T>): Boolean {
validateModification()
val removed = parentList.retainAllInRange(elements, offset, offset + size)
if (removed > 0) {
modification = parentList.modification
size -= removed
}
return removed > 0
}
override fun set(index: Int, element: T): T {
validateRange(index, size)
validateModification()
val result = parentList.set(index + offset, element)
modification = parentList.modification
return result
}
override fun subList(fromIndex: Int, toIndex: Int): MutableList<T> {
require(fromIndex in 0..toIndex && toIndex <= size)
validateModification()
return SubList(parentList, fromIndex + offset, toIndex + offset)
}
private fun validateModification() {
if (parentList.modification != modification) {
throw ConcurrentModificationException()
}
}
}
| apache-2.0 | c67be9e693faf07ca95984740d5663cc | 34.083333 | 98 | 0.616327 | 4.824487 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/jobs/MultiDeviceContactSyncJob.kt | 1 | 5753 | package org.thoughtcrime.securesms.jobs
import org.signal.core.util.logging.Log
import org.signal.libsignal.protocol.InvalidMessageException
import org.thoughtcrime.securesms.database.IdentityDatabase.VerifiedStatus
import org.thoughtcrime.securesms.database.SignalDatabase
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.jobmanager.Data
import org.thoughtcrime.securesms.jobmanager.Job
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.net.NotPushRegisteredException
import org.thoughtcrime.securesms.profiles.AvatarHelper
import org.thoughtcrime.securesms.providers.BlobProvider
import org.thoughtcrime.securesms.recipients.Recipient
import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentPointer
import org.whispersystems.signalservice.api.messages.multidevice.DeviceContact
import org.whispersystems.signalservice.api.messages.multidevice.DeviceContactsInputStream
import org.whispersystems.signalservice.api.messages.multidevice.VerifiedMessage.VerifiedState
import org.whispersystems.signalservice.api.push.SignalServiceAddress
import org.whispersystems.signalservice.api.push.exceptions.MissingConfigurationException
import org.whispersystems.signalservice.api.util.AttachmentPointerUtil
import java.io.File
import java.io.IOException
import java.io.InputStream
/**
* Sync contact data from primary device.
*/
class MultiDeviceContactSyncJob(parameters: Parameters, private val attachmentPointer: ByteArray) : BaseJob(parameters) {
constructor(contactsAttachment: SignalServiceAttachmentPointer) : this(
Parameters.Builder()
.setQueue("MultiDeviceContactSyncJob")
.build(),
AttachmentPointerUtil.createAttachmentPointer(contactsAttachment).toByteArray()
)
override fun serialize(): Data {
return Data.Builder()
.putBlobAsString(KEY_ATTACHMENT_POINTER, attachmentPointer)
.build()
}
override fun getFactoryKey(): String {
return KEY
}
override fun onRun() {
if (!Recipient.self().isRegistered) {
throw NotPushRegisteredException()
}
if (SignalStore.account().isPrimaryDevice) {
Log.i(TAG, "Not linked device, aborting...")
return
}
val contactAttachment: SignalServiceAttachmentPointer = AttachmentPointerUtil.createSignalAttachmentPointer(attachmentPointer)
try {
val contactsFile: File = BlobProvider.getInstance().forNonAutoEncryptingSingleSessionOnDisk(context)
ApplicationDependencies.getSignalServiceMessageReceiver()
.retrieveAttachment(contactAttachment, contactsFile, MAX_ATTACHMENT_SIZE)
.use(this::processContactFile)
} catch (e: MissingConfigurationException) {
throw IOException(e)
} catch (e: InvalidMessageException) {
throw IOException(e)
}
}
private fun processContactFile(inputStream: InputStream) {
val deviceContacts = DeviceContactsInputStream(inputStream)
val recipients = SignalDatabase.recipients
val threads = SignalDatabase.threads
var contact: DeviceContact? = deviceContacts.read()
while (contact != null) {
val recipient = Recipient.externalPush(SignalServiceAddress(contact.address.serviceId, contact.address.number.orElse(null)))
if (recipient.isSelf) {
contact = deviceContacts.read()
continue
}
if (contact.name.isPresent) {
recipients.setSystemContactName(recipient.id, contact.name.get())
}
if (contact.expirationTimer.isPresent) {
recipients.setExpireMessages(recipient.id, contact.expirationTimer.get())
}
if (contact.profileKey.isPresent) {
val profileKey = contact.profileKey.get()
recipients.setProfileKey(recipient.id, profileKey)
}
if (contact.verified.isPresent) {
val verifiedStatus: VerifiedStatus = when (contact.verified.get().verified) {
VerifiedState.VERIFIED -> VerifiedStatus.VERIFIED
VerifiedState.UNVERIFIED -> VerifiedStatus.UNVERIFIED
else -> VerifiedStatus.DEFAULT
}
ApplicationDependencies.getProtocolStore().aci().identities().saveIdentityWithoutSideEffects(
recipient.id,
contact.verified.get().identityKey,
verifiedStatus,
false,
contact.verified.get().timestamp,
true
)
}
recipients.setBlocked(recipient.id, contact.isBlocked)
val threadRecord = threads.getThreadRecord(threads.getThreadIdFor(recipient.id))
if (threadRecord != null && contact.isArchived != threadRecord.isArchived) {
if (contact.isArchived) {
threads.archiveConversation(threadRecord.threadId)
} else {
threads.unarchiveConversation(threadRecord.threadId)
}
}
if (contact.avatar.isPresent) {
try {
AvatarHelper.setSyncAvatar(context, recipient.id, contact.avatar.get().inputStream)
} catch (e: IOException) {
Log.w(TAG, "Unable to set sync avatar for ${recipient.id}")
}
}
contact = deviceContacts.read()
}
}
override fun onShouldRetry(e: Exception): Boolean = false
override fun onFailure() = Unit
class Factory : Job.Factory<MultiDeviceContactSyncJob> {
override fun create(parameters: Parameters, data: Data): MultiDeviceContactSyncJob {
return MultiDeviceContactSyncJob(parameters, data.getStringAsBlob(KEY_ATTACHMENT_POINTER))
}
}
companion object {
const val KEY = "MultiDeviceContactSyncJob"
const val KEY_ATTACHMENT_POINTER = "attachment_pointer"
private const val MAX_ATTACHMENT_SIZE: Long = 100 * 1024 * 1024
private val TAG = Log.tag(MultiDeviceContactSyncJob::class.java)
}
}
| gpl-3.0 | 4722f57f66dbfb876cde11b364da51ec | 36.116129 | 130 | 0.741874 | 4.639516 | false | false | false | false |
androidx/androidx | compose/ui/ui-inspection/src/androidTest/java/androidx/compose/ui/inspection/testdata/TestLambdas.kt | 3 | 1361 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.inspection.testdata
import androidx.compose.ui.unit.IntOffset
object TestLambdas {
val short = { s: String -> s.length }
val long = { a: Int, b: Int ->
val sum = a + b
val count = a - b
sum / count
}
val inlined = { a: Int, b: Int ->
val sum = a + fct(b) { it * it }
sum - a
}
val inlinedParameter = { o: IntOffset ->
o.x * 2
}
val unnamed: (Int, Int) -> Float = { _, _ -> 0f }
/**
* This inline function will appear at a line numbers
* past the end of this file for JVMTI.
*/
private inline fun fct(n: Int, op: (Int) -> Int): Int {
val a = op(n)
val b = n * a + 3
return b - a
}
}
| apache-2.0 | 43733b892a91d00d44d844eae6e70be1 | 28.586957 | 75 | 0.611315 | 3.718579 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/lang/core/types/TypeReplacement.kt | 1 | 11084 | package org.elm.lang.core.types
/**
* This class performs deep replacement of a set of [TyVar]s in a [Ty] with a set of new types,
* which could also be [TyVar]s.
*
* It relies on the fact that [TyVar]s can be compared by identity. Vars in different scopes must
* compare unequal, even if they have the same name.
*
* The constructor takes a map of vars to the ty to replace them with.
*/
class TypeReplacement(
// A map of variables that should be replaced to the ty to replace them with
replacements: Map<TyVar, Ty>,
private val freshen: Boolean,
private val varsToRemainRigid: Collection<TyVar>?,
private val keepRecordsMutable: Boolean
) {
companion object {
/**
* Replace vars in [ty] according to [replacements].
*
* @param varsToRemainRigid If given, all [TyVar]s will be replaced with flexible copies,
* except for vars that occur in this collection, which will be left unchanged.
* @param keepRecordsMutable If false, [MutableTyRecord]s will be replaces with [TyRecord]s
*/
fun replace(
ty: Ty,
replacements: Map<TyVar, Ty>,
varsToRemainRigid: Collection<TyVar>? = null,
keepRecordsMutable: Boolean = false
): Ty {
if (varsToRemainRigid == null && replacements.isEmpty()) return ty
return TypeReplacement(
replacements,
freshen = false,
varsToRemainRigid = varsToRemainRigid,
keepRecordsMutable = keepRecordsMutable
).replace(ty)
}
fun replace(
ty: Ty,
replacements: DisjointSet,
varsToRemainRigid: Collection<TyVar>? = null,
keepRecordsMutable: Boolean = false
): Ty = replace(ty, replacements.asMap(), varsToRemainRigid, keepRecordsMutable)
/**
* Replace all [TyVar]s in a [ty] with new copies with the same names.
*
* This is important because tys are cached, and [TyVar]s are compared by instance to be
* able to differentiate them by scope. Each time you call a function or reference a type,
* its vars are distinct, even though they share a name with vars from the previous
* reference. If we use the cached tys, there's no way to distinguish between vars in one
* call from another.
*
* Note that rigid vars are never freshened. In a function with an annotation like
* `f : (a -> b) -> a -> b`, every time you call the `(a -> b)` parameter within the body of
* `f`, the ty of `a` and `b` have to be the same.
*/
fun freshenVars(ty: Ty): Ty {
return TypeReplacement(emptyMap(), freshen = true, varsToRemainRigid = null, keepRecordsMutable = false).replace(ty)
}
/**
* Make all type variables in a [ty] flexible.
*
* Type variables in function annotations are rigid when bound to parameters; in all other
* cases vars are flexible. This function is used to make vars inferred as rigid into flexible
* when calling functions.
*/
fun flexify(ty: Ty): Ty {
return TypeReplacement(emptyMap(), freshen = false, varsToRemainRigid = emptyList(), keepRecordsMutable = false).replace(ty)
}
/**
* Freeze any fields references present in records in a [ty].
*
* Use this to prevent cached values from being altered. Note that this is an in-place
* change rather than a copy.
*/
fun freeze(ty: Ty) {
when (ty) {
is TyVar -> Unit
is TyTuple -> ty.types.forEach { freeze(it) }
is TyRecord -> {
(ty.baseTy as? TyRecord)?.fieldReferences?.freeze()
ty.fields.values.forEach { freeze(it) }
ty.fieldReferences.freeze()
}
is MutableTyRecord -> {
(ty.baseTy as? TyRecord)?.fieldReferences?.freeze()
ty.fields.values.forEach { freeze(it) }
ty.fieldReferences.freeze()
}
is TyUnion -> ty.parameters.forEach { freeze(it) }
is TyFunction -> {
freeze(ty.ret)
ty.parameters.forEach { freeze(it) }
}
is TyUnit -> Unit
is TyUnknown -> Unit
TyInProgressBinding -> Unit
}
ty.alias?.parameters?.forEach { freeze(it) }
}
}
private fun wouldChange(ty: Ty): Boolean {
val changeAllVars = freshen || varsToRemainRigid != null
fun Ty.f(): Boolean = when (this) {
is TyVar -> changeAllVars || this in replacements
is TyTuple -> types.any { it.f() }
is TyRecord -> fields.values.any { it.f() } || baseTy?.f() == true
is MutableTyRecord -> !keepRecordsMutable || fields.values.any { it.f() } || baseTy?.f() == true
is TyUnion -> parameters.any { it.f() }
is TyFunction -> ret.f() || parameters.any { it.f() }
is TyUnit, is TyUnknown, TyInProgressBinding -> false
} || alias?.parameters?.any { it.f() } == true
return ty.f()
}
/** A map of var to (has been accessed, ty) */
private val replacements = replacements.mapValuesTo(mutableMapOf()) { (_, v) -> false to v }
fun replace(ty: Ty): Ty {
// If we wouldn't change anything, return the original ty to avoid duplicating the object
if (!wouldChange(ty)) return ty
return when (ty) {
is TyVar -> getReplacement(ty) ?: ty
is TyTuple -> replaceTuple(ty)
is TyFunction -> replaceFunction(ty)
is TyUnknown -> TyUnknown(replace(ty.alias))
is TyUnion -> replaceUnion(ty)
is TyRecord -> replaceRecord(ty.fields, ty.baseTy, ty.alias, ty.fieldReferences, wasMutable = false)
is TyUnit, TyInProgressBinding -> ty
is MutableTyRecord -> replaceRecord(ty.fields, ty.baseTy, null, ty.fieldReferences, wasMutable = true)
}
}
/*
* Although aliases are not used in ty comparisons, we still need to do replacement on them to
* render their call sites correctly.
* e.g.
* type alias A a = ...
* main : A ()
* We replace the parameter of the AliasInfo in the return value of the main function with
* TyUnit so that it renders as `A ()` rather than `A a`.
*/
private fun replace(aliasInfo: AliasInfo?) = aliasInfo?.let { info ->
info.copy(parameters = info.parameters.map { replace(it) }.optimizeReadOnlyList())
}
private fun replaceTuple(ty: TyTuple): TyTuple {
return TyTuple(ty.types.map { replace(it) }.optimizeReadOnlyList(), replace(ty.alias))
}
private fun replaceFunction(ty: TyFunction): TyFunction {
val parameters = ty.parameters.map { replace(it) }.optimizeReadOnlyList()
return TyFunction(parameters, replace(ty.ret), replace(ty.alias)).uncurry()
}
private fun replaceUnion(ty: TyUnion): TyUnion {
// fast path for common cases like Basics.Int
if (ty.parameters.isEmpty() && ty.alias == null) return ty
val parameters = ty.parameters.map { replace(it) }.optimizeReadOnlyList()
return TyUnion(ty.module, ty.name, parameters, replace(ty.alias))
}
private fun replaceRecord(
fields: Map<String, Ty>,
baseTy: Ty?,
alias: AliasInfo?,
fieldReferences: RecordFieldReferenceTable,
wasMutable: Boolean
): Ty {
val oldBase = if (baseTy == null || baseTy !is TyVar) null else getReplacement(baseTy)
val newBase = when (oldBase) {
// If the base ty of the argument is a record, use its base ty, which might be null.
is TyRecord -> oldBase.baseTy
// If it wasn't substituted, leave it as-is
null -> when {
// Although if it's a record, we might need to make it immutable
baseTy is MutableTyRecord && !keepRecordsMutable -> replace(baseTy)
else -> baseTy
}
// If it's another variable, use it
else -> oldBase
}
val baseFields = (oldBase as? TyRecord)?.fields.orEmpty()
val baseFieldRefs = (oldBase as? TyRecord)?.fieldReferences
// Make the new map as small as we can for these fields. HashMap always uses a power of two
// element array, so we can't avoid all wasted memory.
val initialCapacity = baseFields.size + fields.keys.count { it !in baseFields }
val newFields = LinkedHashMap<String, Ty>(initialCapacity, 1f)
// Don't use putAll here, since that function will resize the table to hold (size + 1) elements
baseFields.forEach { (k, v) -> newFields[k] = v }
fields.mapValuesTo(newFields) { (_, it) -> replace(it) }
val newFieldReferences = when {
baseFieldRefs == null || baseFieldRefs.isEmpty() -> fieldReferences
fieldReferences.frozen -> fieldReferences + baseFieldRefs
else -> {
// The new record shares its references table with the old record. That allows us to track
// references back to expressions inside nested declarations even when the record has been
// freshened or replaced.
fieldReferences.apply { addAll(baseFieldRefs) }
}
}
return if (wasMutable && keepRecordsMutable) MutableTyRecord(newFields, newBase, newFieldReferences)
else TyRecord(newFields, newBase, replace(alias), newFieldReferences)
}
// When we replace a var, the new ty may itself contain vars, and so we need to recursively
// replace the ty before we can replace the var we were given as an argument.
// After the recursive replacement, we avoid repeating work by storing the final ty and tracking
// of the fact that its replacement is complete with the `hasBeenAccessed` flag.
private fun getReplacement(key: TyVar): Ty? {
val (hasBeenAccessed, storedTy) = replacements[key] ?: return when {
freshen || varsToRemainRigid != null -> {
if (key.rigid && (varsToRemainRigid == null || key in varsToRemainRigid)) null // never freshen rigid vars
else TyVar(key.name, rigid = false).also { replacements[key] = true to it }
}
else -> null
}
if (hasBeenAccessed) return storedTy
val replacedVal = replace(storedTy)
replacements[key] = true to replacedVal
return replacedVal
}
}
// Copied from the stdlib, which doesn't apply this for `map` and `filter`
private fun <T> List<T>.optimizeReadOnlyList() = when (size) {
0 -> emptyList()
1 -> listOf(this[0])
else -> this
}
| mit | 509ba8cd1dd620d5f99d638ba22b9d71 | 44.056911 | 136 | 0.594551 | 4.593452 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/translations/inspections/NoTranslationInspection.kt | 1 | 2922 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.inspections
import com.demonwav.mcdev.translations.TranslationFiles
import com.demonwav.mcdev.translations.identification.LiteralTranslationIdentifier
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiLiteralExpression
import com.intellij.util.IncorrectOperationException
class NoTranslationInspection : TranslationInspection() {
override fun getStaticDescription() =
"Checks whether a translation key used in calls to <code>StatCollector.translateToLocal()</code>, " +
"<code>StatCollector.translateToLocalFormatted()</code> or <code>I18n.format()</code> exists."
override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder)
private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() {
override fun visitLiteralExpression(expression: PsiLiteralExpression) {
val result = LiteralTranslationIdentifier().identify(expression)
if (result != null && result.text == null) {
holder.registerProblem(
expression,
"The given translation key does not exist",
ProblemHighlightType.GENERIC_ERROR,
CreateTranslationQuickFix,
ChangeTranslationQuickFix("Use existing translation")
)
}
}
}
private object CreateTranslationQuickFix : LocalQuickFix {
override fun getName() = "Create translation"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
try {
val literal = descriptor.psiElement as PsiLiteralExpression
val translation = LiteralTranslationIdentifier().identify(literal)
val literalValue = literal.value as String
val key = translation?.key?.copy(infix = literalValue)?.full ?: literalValue
val result = Messages.showInputDialog(
"Enter default value for \"$key\":",
"Create Translation",
Messages.getQuestionIcon()
)
if (result != null) {
TranslationFiles.add(literal, key, result)
}
} catch (ignored: IncorrectOperationException) {
}
}
override fun startInWriteAction() = false
override fun getFamilyName() = name
}
}
| mit | a3ac3950dbe9a7a73854f91f82e9fa66 | 39.027397 | 109 | 0.667351 | 5.630058 | false | false | false | false |
MaTriXy/android-topeka | app/src/main/java/com/google/samples/apps/topeka/adapter/AvatarAdapter.kt | 2 | 1839 | /*
* 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.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import com.google.samples.apps.topeka.R
import com.google.samples.apps.topeka.model.Avatar
import com.google.samples.apps.topeka.widget.AvatarView
/**
* Adapter to display [Avatar] icons.
*/
class AvatarAdapter(context: Context) : BaseAdapter() {
private val layoutInflater = LayoutInflater.from(context)
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
return ((convertView ?:
layoutInflater.inflate(R.layout.item_avatar, parent, false)) as AvatarView)
.also { setAvatar(it, avatars[position]) }
}
private fun setAvatar(view: AvatarView, avatar: Avatar) {
with(view) {
setAvatar(avatar.drawableId)
contentDescription = avatar.nameForAccessibility
}
}
override fun getCount() = avatars.size
override fun getItem(position: Int) = avatars[position]
override fun getItemId(position: Int) = position.toLong()
companion object {
private val avatars = Avatar.values()
}
}
| apache-2.0 | 4f89ca7fb1369574cb09da0cdd9d3099 | 30.169492 | 91 | 0.713431 | 4.296729 | false | false | false | false |
tasomaniac/OpenLinkWith | redirect/src/test/kotlin/com/tasomaniac/openwith/redirect/RedirectFixerTest.kt | 1 | 3720 | package com.tasomaniac.openwith.redirect
import com.tasomaniac.openwith.test.testScheduling
import io.reactivex.observers.TestObserver
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.mockwebserver.Dispatcher
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.RecordedRequest
import org.junit.Rule
import org.junit.Test
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
class RedirectFixerTest {
@Rule @JvmField val server = MockWebServer()
@Rule @JvmField val mockito: MockitoRule = MockitoJUnit.rule()
private val redirectFixer: RedirectFixer =
RedirectFixer(OkHttpClient(), testScheduling(), 1)
@Test
fun givenNoRedirectShouldReturnOriginalUrl() {
given {
enqueue(noRedirect())
}.then {
assertUrlWithPath("original")
}
}
@Test
fun givenRedirectShouldFollowRedirect() {
given {
enqueue(redirectTo("redirect"))
enqueue(noRedirect())
}.then {
assertUrlWithPath("redirect")
}
}
@Test
fun givenTwoRedirectsShouldReturnTheLastRedirect() {
given {
enqueue(redirectTo("redirect"))
enqueue(redirectTo("redirect/2"))
enqueue(noRedirect())
}.then {
assertUrlWithPath("redirect/2")
}
}
@Test
fun givenNetworkErrorReturnOriginal() {
given {
enqueue(redirectTo("redirect"))
shutdown()
enqueue(noRedirect())
}.then {
assertUrlWithPath("original")
.assertNoErrors()
}
}
@Test
fun givenNetworkTimeoutReturnOriginal() {
given {
dispatcher = object : Dispatcher() {
override fun dispatch(request: RecordedRequest): MockResponse {
Thread.sleep(1500)
return redirectTo("redirect")
}
}
}.then {
assertUrlWithPath("original")
.assertNoErrors()
}
}
@Test
fun givenWithinNetworkTimeoutLimitReturnRedirect() {
given {
dispatcher = object : Dispatcher() {
override fun dispatch(request: RecordedRequest): MockResponse {
Thread.sleep(500)
return redirectTo("redirect")
}
}
}.then {
assertUrlWithPath("redirect")
.assertNoErrors()
}
}
@Test
fun givenNetworkIsInterruptedReturnOriginal() {
given {
dispatcher = object : Dispatcher() {
override fun dispatch(request: RecordedRequest): MockResponse {
throw InterruptedException()
}
}
}.then {
assertUrlWithPath("original")
.assertNoErrors()
}
}
private fun TestObserver<HttpUrl>.assertUrlWithPath(path: String) = apply { assertValue(server.url(path)) }
private fun noRedirect() = MockResponse()
private fun redirectTo(path: String) = MockResponse().addHeader("Location", server.url(path))
private infix fun given(given: MockWebServer.() -> Unit): Then {
server.given()
return Then()
}
inner class Then {
@Suppress("MemberNameEqualsClassName")
infix fun then(assert: TestObserver<HttpUrl>.() -> Unit) {
test().assert()
}
private fun test(): TestObserver<HttpUrl> {
return redirectFixer
.followRedirects(server.url("original"))
.test()
}
}
}
| apache-2.0 | 09292447dc7ea6b03c56eb768bf6b2e4 | 26.761194 | 111 | 0.58172 | 5.276596 | false | true | false | false |
mwolfson/android-historian | app/src/main/java/com/designdemo/uaha/util/Constants.kt | 1 | 877 | @file:Suppress("NewLineAtEndOfFile")
@file:JvmName("Constants")
package com.designdemo.uaha.util
// Notification Channel constants
@JvmField val NOTIFICATION_CHANNEL_NAME: CharSequence = "Historian Notifications"
const val NOTIFICATION_CHANNEL_DESCRIPTION = "Notifications with info about OS or Devices"
@JvmField val NOTIFICATION_TITLE: CharSequence = "Historian Notification"
const val CHANNEL_ID = "HISTORIAN_NOTIFICATION"
const val NOTIFICATION_ID = 1
const val KEY_NOTIF_LASTDATE = "WORKRESP_LASTDATE"
const val TAG_WORK_NOTIF = "TagWorkNotif"
// Validation Constants
const val PASSWORD_MIN = 8
const val NAME_MIN = 4
const val NAME_MAX = 10
const val PHONE_LENGTH = 14
// Bottom Sheet Constants
const val PEEK_HEIGHT_PIXEL = 300
const val ROTATION_180 = -180
// SharedPreferences
const val PREF_DARK_MODE = "sharedPrefDarkMode"
const val PREF_FILE = "sharedPrefsFile" | apache-2.0 | f10de0b9f9b433847f0287084eafc593 | 32.769231 | 90 | 0.786773 | 3.863436 | false | false | false | false |
inorichi/tachiyomi-extensions | multisrc/overrides/madara/wuxiaworld/src/WuxiaWorld.kt | 1 | 768 | package eu.kanade.tachiyomi.extension.en.wuxiaworld
import eu.kanade.tachiyomi.multisrc.madara.Madara
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.FilterList
import okhttp3.Request
class WuxiaWorld : Madara("WuxiaWorld", "https://wuxiaworld.site", "en") {
override fun popularMangaRequest(page: Int): Request = GET("$baseUrl/tag/webcomic/page/$page/?m_orderby=views", headers)
override fun latestUpdatesRequest(page: Int): Request = GET("$baseUrl/tag/webcomic/page/$page/?m_orderby=latest", headers)
override fun searchMangaRequest(page: Int, query: String, filters: FilterList) = super.searchMangaRequest(page, "$query comics", filters)
override fun popularMangaNextPageSelector() = "div.nav-previous.float-left"
}
| apache-2.0 | 9e1d2141a2d5de2cdd8b5c06561c9355 | 58.076923 | 141 | 0.776042 | 3.728155 | false | true | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/service/FcmReceiverService.kt | 1 | 4928 | package de.tum.`in`.tumcampusapp.service
import android.os.Bundle
import androidx.annotation.IntDef
import com.google.firebase.iid.FirebaseInstanceId
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import de.tum.`in`.tumcampusapp.api.app.TUMCabeClient
import de.tum.`in`.tumcampusapp.component.other.general.UpdatePushNotification
import de.tum.`in`.tumcampusapp.component.other.generic.PushNotification
import de.tum.`in`.tumcampusapp.component.ui.alarm.AlarmPushNotification
import de.tum.`in`.tumcampusapp.component.ui.chat.ChatPushNotification
import de.tum.`in`.tumcampusapp.utils.Const
import de.tum.`in`.tumcampusapp.utils.Utils
import org.jetbrains.anko.notificationManager
import java.io.IOException
/**
* This `IntentService` does the actual handling of the FCM message.
* `FcmBroadcastReceiver` (a `WakefulBroadcastReceiver`) holds a
* partial wake lock for this service while the service does its work. When the
* service is finished, it calls `completeWakefulIntent()` to release the
* wake lock.
*/
class FcmReceiverService : FirebaseMessagingService() {
override fun onMessageReceived(message: RemoteMessage) {
val data = message.data ?: return
Utils.log("Notification received: $data")
// Legacy messages need to be handled - maybe some data is missing?
if (!data.containsKey(PAYLOAD) || !data.containsKey("type")) {
handleLegacyNotification(data)
return
}
val notificationId = data["notificationId"]?.toInt() ?: return
val type = data["type"]?.toInt() ?: return
val payload = data[PAYLOAD] ?: return
createPushNotificationOfType(type, notificationId, payload)?.let {
postNotification(it)
try {
it.sendConfirmation()
} catch (e: IOException) {
Utils.log(e)
}
}
}
/**
* Try to map the given parameters to a notification.
* We handle type specific actions in the respective classes
* See: https://github.com/TCA-Team/TumCampusApp/wiki/GCM-Message-format
*/
private fun createPushNotificationOfType(
type: Int,
notificationId: Int,
payload: String
): PushNotification? {
// Apparently, using the service context can cause issues here:
// https://stackoverflow.com/questions/48770750/strange-crash-when-starting-notification
val appContext = applicationContext
return when (type) {
CHAT_NOTIFICATION -> ChatPushNotification.fromJson(payload, appContext, notificationId)
UPDATE -> UpdatePushNotification(payload, appContext, notificationId)
ALERT -> AlarmPushNotification(payload, appContext, notificationId)
else -> {
// Nothing to do, just confirm the retrieved notificationId
try {
TUMCabeClient
.getInstance(this)
.confirm(notificationId)
} catch (e: IOException) {
Utils.log(e)
}
null
}
}
}
/**
* Try to support old notifications by matching it as a legacy chat notificationId
* TODO(kordianbruck): do we still need this?
*/
private fun handleLegacyNotification(data: Map<String, String>) {
try {
val bundle = Bundle().apply {
data.entries.forEach { entry -> putString(entry.key, entry.value) }
}
ChatPushNotification.fromBundle(bundle, this, -1)?.also {
postNotification(it)
}
} catch (e: Exception) {
Utils.log(e)
}
}
override fun onNewToken(token: String) {
super.onNewToken(token)
Utils.log("new FCM token received")
Utils.setSetting(this, Const.FCM_INSTANCE_ID, FirebaseInstanceId.getInstance().id)
Utils.setSetting(this, Const.FCM_TOKEN_ID, token ?: "")
}
/**
* Post the corresponding local android notification for the received PushNotification (if any)
* @param pushNotification the PushNotification containing a notification to post
*/
private fun postNotification(pushNotification: PushNotification) {
pushNotification.notification?.let {
val manager = applicationContext.notificationManager
manager.notify(pushNotification.displayNotificationId, it)
}
}
companion object {
/**
* The possible Notification types
*/
@Retention(AnnotationRetention.SOURCE)
@IntDef(CHAT_NOTIFICATION, UPDATE, ALERT)
annotation class PushNotificationType
const val CHAT_NOTIFICATION = 1
const val UPDATE = 2
const val ALERT = 3
private const val PAYLOAD = "payload"
}
}
| gpl-3.0 | 89d197a6b451521e04433866e6f9e829 | 36.333333 | 99 | 0.645901 | 4.923077 | false | false | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/dashboard/feedback/list/FeedbackListFragment.kt | 1 | 3066 | package com.intfocus.template.dashboard.feedback.list
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.intfocus.template.R
import com.intfocus.template.dashboard.feedback.FeedbackInputActivity
import com.intfocus.template.dashboard.feedback.FeedbackModelImpl
import com.intfocus.template.model.response.mine_page.FeedbackList
import com.intfocus.template.ui.BaseFragment
import com.intfocus.template.ui.view.RecyclerItemDecoration
import com.intfocus.template.util.ToastUtils
import kotlinx.android.synthetic.main.fragment_feedback_list.*
/**
* @author liuruilin
* @data 2017/12/4
* @describe
*/
class FeedbackListFragment : BaseFragment(), FeedbackListContract.View {
override lateinit var presenter: FeedbackListContract.Presenter
private var rootView: View? = null
private var mLayoutManager: LinearLayoutManager? = null
lateinit var feedbackListAdapter: FeedbackListAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// if (rootView == null) {
rootView = inflater.inflate(R.layout.fragment_feedback_list, container, false)
feedbackListAdapter = FeedbackListAdapter(ctx)
mLayoutManager = LinearLayoutManager(ctx)
mLayoutManager!!.orientation = LinearLayoutManager.VERTICAL
// }
showDialog(ctx)
return rootView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initView()
}
override fun onResume() {
super.onResume()
if (this::presenter.isInitialized) {
presenter.getList()
} else {
presenter = FeedbackListPresenter(FeedbackModelImpl.getInstance(), this)
presenter.getList()
}
// srl_feedback_list.isRefreshing = true
}
fun initView() {
rv_feedback_list.layoutManager = mLayoutManager
rv_feedback_list.adapter = feedbackListAdapter
if (rv_feedback_list.itemDecorationCount == 0) {
rv_feedback_list.addItemDecoration(RecyclerItemDecoration(ctx))
}
btn_submit.setOnClickListener { startFeedbackInput() }
srl_feedback_list.setColorSchemeResources(R.color.co1_syr)
srl_feedback_list.setOnRefreshListener {
presenter.getList()
}
}
override fun showList(data: FeedbackList) {
srl_feedback_list.isRefreshing = false
hideLoading()
data.data?.let {
feedbackListAdapter.setData(it)
}
}
private fun startFeedbackInput() {
val intent = Intent(ctx, FeedbackInputActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
startActivity(intent)
}
override fun showNullPage() {
srl_feedback_list.isRefreshing = false
ToastUtils.show(ctx, "暂无数据")
}
}
| gpl-3.0 | dc9540c0dc6d6b76a26aab024053c77d | 32.977778 | 116 | 0.705363 | 4.719136 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/RTTIGenerator.kt | 1 | 8700 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.konan.llvm
import llvm.*
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.backend.konan.descriptors.*
import org.jetbrains.kotlin.backend.konan.isExternalObjCClassMethod
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.resolve.constants.StringValue
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassOrAny
internal class RTTIGenerator(override val context: Context) : ContextUtils {
private inner class FieldTableRecord(val nameSignature: LocalHash, val fieldOffset: Int) :
Struct(runtime.fieldTableRecordType, nameSignature, Int32(fieldOffset))
private inner class MethodTableRecord(val nameSignature: LocalHash, val methodEntryPoint: ConstValue) :
Struct(runtime.methodTableRecordType, nameSignature, methodEntryPoint)
private inner class TypeInfo(val name: ConstValue, val size: Int,
val superType: ConstValue,
val objOffsets: ConstValue,
val objOffsetsCount: Int,
val interfaces: ConstValue,
val interfacesCount: Int,
val methods: ConstValue,
val methodsCount: Int,
val fields: ConstValue,
val fieldsCount: Int) :
Struct(
runtime.typeInfoType,
name,
Int32(size),
superType,
objOffsets,
Int32(objOffsetsCount),
interfaces,
Int32(interfacesCount),
methods,
Int32(methodsCount),
fields,
Int32(fieldsCount)
)
private fun exportTypeInfoIfRequired(classDesc: ClassDescriptor, typeInfoGlobal: LLVMValueRef?) {
val annot = classDesc.annotations.findAnnotation(FqName("konan.ExportTypeInfo"))
if (annot != null) {
val nameValue = annot.allValueArguments.values.single() as StringValue
// TODO: use LLVMAddAlias?
val global = addGlobal(nameValue.value, pointerType(runtime.typeInfoType), isExported = true)
LLVMSetInitializer(global, typeInfoGlobal)
}
}
private val arrayClasses = mapOf(
"kotlin.Array" to -LLVMABISizeOfType(llvmTargetData, kObjHeaderPtr).toInt(),
"kotlin.ByteArray" to -1,
"kotlin.CharArray" to -2,
"kotlin.ShortArray" to -2,
"kotlin.IntArray" to -4,
"kotlin.LongArray" to -8,
"kotlin.FloatArray" to -4,
"kotlin.DoubleArray" to -8,
"kotlin.BooleanArray" to -1,
"kotlin.String" to -2,
"konan.ImmutableBinaryBlob" to -1
)
private fun getInstanceSize(classType: LLVMTypeRef?, className: FqName) : Int {
val arraySize = arrayClasses.get(className.asString());
if (arraySize != null) return arraySize;
return LLVMStoreSizeOfType(llvmTargetData, classType).toInt()
}
fun generate(classDesc: ClassDescriptor) {
val className = classDesc.fqNameSafe
val llvmDeclarations = context.llvmDeclarations.forClass(classDesc)
val bodyType = llvmDeclarations.bodyType
val name = className.globalHash
val size = getInstanceSize(bodyType, className)
val superTypeOrAny = classDesc.getSuperClassOrAny()
val superType = if (KotlinBuiltIns.isAny(classDesc)) NullPointer(runtime.typeInfoType)
else superTypeOrAny.typeInfoPtr
val interfaces = classDesc.implementedInterfaces.map { it.typeInfoPtr }
val interfacesPtr = staticData.placeGlobalConstArray("kintf:$className",
pointerType(runtime.typeInfoType), interfaces)
// TODO: reuse offsets obtained for 'fields' below
val objOffsets = getStructElements(bodyType).mapIndexedNotNull { index, type ->
if (isObjectType(type)) {
LLVMOffsetOfElement(llvmTargetData, bodyType, index)
} else {
null
}
}
val objOffsetsPtr = staticData.placeGlobalConstArray("krefs:$className", int32Type,
objOffsets.map { Int32(it.toInt()) })
val fields = llvmDeclarations.fields.mapIndexed { index, field ->
// Note: using FQ name because a class may have multiple fields with the same name due to property overriding
val nameSignature = field.fqNameSafe.localHash // FIXME: add signature
val fieldOffset = LLVMOffsetOfElement(llvmTargetData, bodyType, index)
FieldTableRecord(nameSignature, fieldOffset.toInt())
}.sortedBy { it.nameSignature.value }
val fieldsPtr = staticData.placeGlobalConstArray("kfields:$className",
runtime.fieldTableRecordType, fields)
val methods = if (classDesc.isAbstract()) {
emptyList()
} else {
val functionNames = mutableMapOf<Long, OverriddenFunctionDescriptor>()
context.getVtableBuilder(classDesc).methodTableEntries.map {
val functionName = it.overriddenDescriptor.functionName
val nameSignature = functionName.localHash
val previous = functionNames.putIfAbsent(nameSignature.value, it)
if (previous != null)
throw AssertionError("Duplicate method table entry: functionName = '$functionName', hash = '${nameSignature.value}', entry1 = $previous, entry2 = $it")
// TODO: compile-time resolution limits binary compatibility
val methodEntryPoint = it.implementation.entryPointAddress
MethodTableRecord(nameSignature, methodEntryPoint)
}.sortedBy { it.nameSignature.value }
}
val methodsPtr = staticData.placeGlobalConstArray("kmethods:$className",
runtime.methodTableRecordType, methods)
val typeInfo = TypeInfo(name, size,
superType,
objOffsetsPtr, objOffsets.size,
interfacesPtr, interfaces.size,
methodsPtr, methods.size,
fieldsPtr, if (classDesc.isInterface) -1 else fields.size)
val typeInfoGlobal = llvmDeclarations.typeInfoGlobal
val typeInfoGlobalValue = if (!classDesc.typeInfoHasVtableAttached) {
typeInfo
} else {
// TODO: compile-time resolution limits binary compatibility
val vtableEntries = context.getVtableBuilder(classDesc).vtableEntries.map {
val implementation = it.implementation
if (implementation.isExternalObjCClassMethod()) {
NullPointer(int8Type)
} else {
implementation.entryPointAddress
}
}
val vtable = ConstArray(int8TypePtr, vtableEntries)
Struct(typeInfo, vtable)
}
typeInfoGlobal.setInitializer(typeInfoGlobalValue)
typeInfoGlobal.setConstant(true)
exportTypeInfoIfRequired(classDesc, classDesc.llvmTypeInfoPtr)
}
internal val OverriddenFunctionDescriptor.implementation: FunctionDescriptor
get() {
val target = descriptor.target
if (!needBridge) return target
val bridgeOwner = if (inheritsBridge) {
target // Bridge is inherited from superclass.
} else {
descriptor
}
return context.specialDeclarationsFactory.getBridgeDescriptor(OverriddenFunctionDescriptor(bridgeOwner, overriddenDescriptor))
}
}
| apache-2.0 | d03a833e40eb93a850aab18591e8d919 | 41.647059 | 171 | 0.625747 | 5.259976 | false | false | false | false |
jiaminglu/kotlin-native | runtime/src/main/kotlin/konan/internal/Coroutines.kt | 1 | 4085 | package konan.internal
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
@Intrinsic
@PublishedApi
internal fun <T> getContinuation(): Continuation<T> = throw AssertionError("Call to getContinuation should've been lowered")
@Intrinsic
@PublishedApi
internal suspend fun <T> returnIfSuspended(@Suppress("UNUSED_PARAMETER") argument: Any?): T
= throw AssertionError("Call to returnIfSuspended should've been lowered")
// Single-threaded continuation.
class SafeContinuation<in T>
constructor(
private val delegate: Continuation<T>,
initialResult: Any?
) : Continuation<T> {
constructor(delegate: Continuation<T>) : this(delegate, UNDECIDED)
public override val context: CoroutineContext
get() = delegate.context
private var result: Any? = initialResult
companion object {
private val UNDECIDED: Any? = Any()
private val RESUMED: Any? = Any()
}
private class Fail(val exception: Throwable)
override fun resume(value: T) {
when {
result === UNDECIDED -> result = value
result === COROUTINE_SUSPENDED -> {
result = RESUMED
delegate.resume(value)
}
else -> throw IllegalStateException("Already resumed")
}
}
override fun resumeWithException(exception: Throwable) {
when {
result === UNDECIDED -> result = Fail(exception)
result === COROUTINE_SUSPENDED -> {
result = RESUMED
delegate.resumeWithException(exception)
}
else -> throw IllegalStateException("Already resumed")
}
}
fun getResult(): Any? {
if (this.result === UNDECIDED) this.result = COROUTINE_SUSPENDED
val result = this.result
when {
result === RESUMED -> return COROUTINE_SUSPENDED // already called continuation, indicate COROUTINE_SUSPENDED upstream
result is Fail -> throw result.exception
else -> return result // either COROUTINE_SUSPENDED or data
}
}
}
@ExportForCompiler
internal fun <T> interceptContinuationIfNeeded(
context: CoroutineContext,
continuation: Continuation<T>
) = context[ContinuationInterceptor]?.interceptContinuation(continuation) ?: continuation
/**
* @suppress
*/
@ExportForCompiler
@PublishedApi
internal fun <T> normalizeContinuation(continuation: Continuation<T>): Continuation<T> =
(continuation as? CoroutineImpl)?.facade ?: continuation
/**
* @suppress
*/
@ExportForCompiler
abstract internal class CoroutineImpl(
protected var completion: Continuation<Any?>?
) : Continuation<Any?> {
// label == -1 when coroutine cannot be started (it is just a factory object) or has already finished execution
// label == 0 in initial part of the coroutine
protected var label: NativePtr = if (completion != null) NativePtr.NULL else NativePtr.NULL + (-1L)
private val _context: CoroutineContext? = completion?.context
override val context: CoroutineContext
get() = _context!!
private var _facade: Continuation<Any?>? = null
val facade: Continuation<Any?> get() {
if (_facade == null) _facade = interceptContinuationIfNeeded(_context!!, this)
return _facade!!
}
override fun resume(value: Any?) {
processBareContinuationResume(completion!!) {
doResume(value, null)
}
}
override fun resumeWithException(exception: Throwable) {
processBareContinuationResume(completion!!) {
doResume(null, exception)
}
}
protected abstract fun doResume(data: Any?, exception: Throwable?): Any?
open fun create(completion: Continuation<*>): Continuation<Unit> {
throw IllegalStateException("create(Continuation) has not been overridden")
}
open fun create(value: Any?, completion: Continuation<*>): Continuation<Unit> {
throw IllegalStateException("create(Any?;Continuation) has not been overridden")
}
}
| apache-2.0 | 4886300ed3ac3a4ec2d97a383d7d1dd7 | 30.914063 | 130 | 0.6612 | 4.951515 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android | app/src/test/java/com/vmenon/mpo/core/usecases/UpdateAllShowsTest.kt | 1 | 3226 | package com.vmenon.mpo.core.usecases
import com.vmenon.mpo.downloads.domain.DownloadRequest
import com.vmenon.mpo.downloads.domain.DownloadRequestType
import com.vmenon.mpo.downloads.domain.DownloadsService
import com.vmenon.mpo.my_library.domain.MyLibraryService
import com.vmenon.mpo.system.domain.Logger
import com.vmenon.mpo.test.TestCoroutineRule
import com.vmenon.mpo.test.TestData
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.junit.Rule
import org.junit.Test
import org.mockito.kotlin.*
@ExperimentalCoroutinesApi
class UpdateAllShowsTest {
@get:Rule
val testCoroutineRule = TestCoroutineRule()
val myLibraryService: MyLibraryService = mock()
val downloadsService: DownloadsService = mock()
val logger: Logger = mock()
val updateAllShows = UpdateAllShows(myLibraryService, downloadsService, logger)
@Test
fun testShowsThatNeedUpdateNull() {
testCoroutineRule.runBlockingTest {
whenever(myLibraryService.getShowsSubscribedAndLastUpdatedBefore(any())).thenReturn(null)
updateAllShows.invoke()
verify(myLibraryService, times(0)).saveEpisode(any())
verify(downloadsService, times(0)).queueDownload(any())
}
}
@Test
fun testShowsThatNeedUpdateEmpty() {
testCoroutineRule.runBlockingTest {
whenever(myLibraryService.getShowsSubscribedAndLastUpdatedBefore(any())).thenReturn(
emptyList()
)
updateAllShows.invoke()
verify(myLibraryService, times(0)).saveEpisode(any())
verify(downloadsService, times(0)).queueDownload(any())
}
}
@Test
fun testShowsThatNeedUpdateHasUpdate() {
testCoroutineRule.runBlockingTest {
val show = TestData.show
val showUpdate = TestData.showUpdate
val savedEpisode = showUpdate.newEpisode.copy(id = 100L)
whenever(myLibraryService.getShowsSubscribedAndLastUpdatedBefore(any())).thenReturn(
listOf(show)
)
whenever(myLibraryService.getShowUpdate(show)).thenReturn(showUpdate)
whenever(myLibraryService.saveEpisode(showUpdate.newEpisode)).thenReturn(savedEpisode)
updateAllShows.invoke()
verify(downloadsService).queueDownload(
DownloadRequest(
downloadUrl = savedEpisode.downloadUrl,
downloadRequestType = DownloadRequestType.EPISODE,
name = savedEpisode.name,
imageUrl = savedEpisode.artworkUrl,
requesterId = savedEpisode.id
)
)
}
}
@Test
fun testShowsThatNeedUpdateNullUpdate() {
testCoroutineRule.runBlockingTest {
val show = TestData.show
whenever(myLibraryService.getShowsSubscribedAndLastUpdatedBefore(any())).thenReturn(
listOf(show)
)
whenever(myLibraryService.getShowUpdate(show)).thenReturn(null)
updateAllShows.invoke()
verify(myLibraryService, times(0)).saveEpisode(any())
verify(downloadsService, times(0)).queueDownload(any())
}
}
} | apache-2.0 | 80db735eab4fe903f61fe7425ae89399 | 36.523256 | 101 | 0.66832 | 4.925191 | false | true | false | false |
GKZX-HN/MyGithub | app/src/main/java/com/gkzxhn/mygithub/ui/adapter/AvatarListAdapter.kt | 1 | 1455 | package com.gkzxhn.mygithub.ui.adapter
import android.util.Log
import android.view.ViewTreeObserver
import android.widget.ImageView
import android.widget.LinearLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.gkzxhn.mygithub.R
import com.gkzxhn.mygithub.bean.entity.Icon2Name
import com.gkzxhn.mygithub.extension.loadRoundConner
/**
* Created by 方 on 2017/10/27.
*/
class AvatarListAdapter(datas : ArrayList<Icon2Name>?) : BaseQuickAdapter<Icon2Name, BaseViewHolder>(R.layout.item_avatar, datas) {
override fun convert(helper: BaseViewHolder?, item: Icon2Name?) {
helper!!.setText(R.id.tv_name, item!!.name)
val imageView = helper!!.getView<ImageView>(R.id.iv_avatar)
imageView
.let { it.loadRoundConner(it.context, item!!.avatarUrl!!) }
imageView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener{
override fun onGlobalLayout() {
val measuredHeight = imageView.measuredHeight
val layoutParams = imageView.layoutParams as LinearLayout.LayoutParams
layoutParams.width = measuredHeight
imageView.layoutParams = layoutParams
Log.i(javaClass.simpleName, measuredHeight.toString())
imageView.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
})
}
} | gpl-3.0 | cb57ea3dc8ef13984db59bec77f703b9 | 41.764706 | 131 | 0.71576 | 4.763934 | false | false | false | false |
exponentjs/exponent | packages/expo-system-ui/android/src/main/java/expo/modules/systemui/SystemUIModule.kt | 2 | 2423 | package expo.modules.systemui
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.util.Log
import expo.modules.core.ExportedModule
import expo.modules.core.ModuleRegistry
import expo.modules.core.Promise
import expo.modules.core.errors.CurrentActivityNotFoundException
import expo.modules.core.interfaces.ActivityProvider
import expo.modules.core.interfaces.ExpoMethod
class SystemUIModule(context: Context) : ExportedModule(context) {
private lateinit var activityProvider: ActivityProvider
override fun getName(): String {
return NAME
}
override fun onCreate(moduleRegistry: ModuleRegistry) {
activityProvider = moduleRegistry.getModule(ActivityProvider::class.java)
?: throw IllegalStateException("Could not find implementation for ActivityProvider.")
}
// Ensure that rejections are passed up to JS rather than terminating the native client.
private fun safeRunOnUiThread(promise: Promise, block: (activity: Activity) -> Unit) {
val activity = activityProvider.currentActivity
if (activity == null) {
promise.reject(CurrentActivityNotFoundException())
return
}
activity.runOnUiThread {
block(activity)
}
}
@ExpoMethod
fun setBackgroundColorAsync(color: Int, promise: Promise) {
safeRunOnUiThread(promise) {
var rootView = it.window.decorView
var colorString = colorToHex(color)
try {
val color = Color.parseColor(colorString)
rootView.setBackgroundColor(color)
promise.resolve(null)
} catch (e: Throwable) {
Log.e(ERROR_TAG, e.toString())
rootView.setBackgroundColor(Color.WHITE)
promise.reject(ERROR_TAG, "Invalid color: \"$color\"")
}
}
}
@ExpoMethod
fun getBackgroundColorAsync(promise: Promise) {
safeRunOnUiThread(promise) {
var mBackground = it.window.decorView.background
if (mBackground is ColorDrawable) {
promise.resolve(colorToHex((mBackground.mutate() as ColorDrawable).color))
} else {
promise.resolve(null)
}
}
}
companion object {
private const val NAME = "ExpoSystemUI"
private const val ERROR_TAG = "ERR_SYSTEM_UI"
fun colorToHex(color: Int): String {
return String.format("#%02x%02x%02x", Color.red(color), Color.green(color), Color.blue(color))
}
}
}
| bsd-3-clause | d87b7b5d3167447e72df4d277dbd65c4 | 30.467532 | 100 | 0.720182 | 4.454044 | false | false | false | false |
hurricup/intellij-community | platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebServer.kt | 1 | 13616 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.builtInWebServer
import com.google.common.cache.CacheBuilder
import com.google.common.net.InetAddresses
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationType
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.catchAndLog
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.endsWithName
import com.intellij.openapi.util.io.setOwnerPermissions
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.*
import com.intellij.util.io.URLUtil
import com.intellij.util.net.NetUtils
import io.netty.channel.Channel
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.*
import io.netty.handler.codec.http.cookie.DefaultCookie
import io.netty.handler.codec.http.cookie.ServerCookieDecoder
import io.netty.handler.codec.http.cookie.ServerCookieEncoder
import org.jetbrains.ide.BuiltInServerManagerImpl
import org.jetbrains.ide.HttpRequestHandler
import org.jetbrains.io.*
import org.jetbrains.notification.SingletonNotificationManager
import java.awt.datatransfer.StringSelection
import java.io.IOException
import java.math.BigInteger
import java.net.InetAddress
import java.nio.file.Path
import java.nio.file.Paths
import java.security.SecureRandom
import java.util.*
import java.util.concurrent.TimeUnit
import javax.swing.SwingUtilities
internal val LOG = Logger.getInstance(BuiltInWebServer::class.java)
// name is duplicated in the ConfigImportHelper
private const val IDE_TOKEN_FILE = "user.web.token"
private val notificationManager by lazy {
SingletonNotificationManager(BuiltInServerManagerImpl.NOTIFICATION_GROUP.value, NotificationType.INFORMATION, null)
}
class BuiltInWebServer : HttpRequestHandler() {
override fun isAccessible(request: HttpRequest) = request.isLocalOrigin(onlyAnyOrLoopback = false, hostsOnly = true)
override fun isSupported(request: FullHttpRequest) = super.isSupported(request) || request.method() == HttpMethod.POST
override fun process(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): Boolean {
var host = request.host
if (host.isNullOrEmpty()) {
return false
}
val portIndex = host!!.indexOf(':')
if (portIndex > 0) {
host = host.substring(0, portIndex)
}
val projectName: String?
val isIpv6 = host[0] == '[' && host.length > 2 && host[host.length - 1] == ']'
if (isIpv6) {
host = host.substring(1, host.length - 1)
}
if (isIpv6 || InetAddresses.isInetAddress(host) || isOwnHostName(host) || host.endsWith(".ngrok.io")) {
if (urlDecoder.path().length < 2) {
return false
}
projectName = null
}
else {
projectName = host
}
return doProcess(urlDecoder, request, context, projectName)
}
}
internal fun isActivatable() = Registry.`is`("ide.built.in.web.server.activatable", false)
internal const val TOKEN_PARAM_NAME = "_ijt"
const val TOKEN_HEADER_NAME = "x-ijt"
private val STANDARD_COOKIE by lazy {
val productName = ApplicationNamesInfo.getInstance().lowercaseProductName
val configPath = PathManager.getConfigPath()
val file = Paths.get(configPath, IDE_TOKEN_FILE)
var token: String? = null
if (file.exists()) {
try {
token = UUID.fromString(file.readText()).toString()
}
catch (e: Exception) {
LOG.warn(e)
}
}
if (token == null) {
token = UUID.randomUUID().toString()
file.write(token!!)
file.setOwnerPermissions()
}
// explicit setting domain cookie on localhost doesn't work for chrome
// http://stackoverflow.com/questions/8134384/chrome-doesnt-create-cookie-for-domain-localhost-in-broken-https
val cookie = DefaultCookie(productName + "-" + Integer.toHexString(configPath.hashCode()), token!!)
cookie.isHttpOnly = true
cookie.setMaxAge(TimeUnit.DAYS.toSeconds(365 * 10))
cookie.setPath("/")
cookie
}
// expire after access because we reuse tokens
private val tokens = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build<String, Boolean>()
fun acquireToken(): String {
var token = tokens.asMap().keys.firstOrNull()
if (token == null) {
token = TokenGenerator.generate()
tokens.put(token, java.lang.Boolean.TRUE)
}
return token
}
// http://stackoverflow.com/a/41156 - shorter than UUID, but secure
private object TokenGenerator {
private val random = SecureRandom()
fun generate(): String = BigInteger(130, random).toString(32)
}
private fun doProcess(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext, projectNameAsHost: String?): Boolean {
val decodedPath = URLUtil.unescapePercentSequences(urlDecoder.path())
var offset: Int
var isEmptyPath: Boolean
val isCustomHost = projectNameAsHost != null
var projectName: String
if (isCustomHost) {
projectName = projectNameAsHost!!
// host mapped to us
offset = 0
isEmptyPath = decodedPath.isEmpty()
}
else {
offset = decodedPath.indexOf('/', 1)
projectName = decodedPath.substring(1, if (offset == -1) decodedPath.length else offset)
isEmptyPath = offset == -1
}
var candidateByDirectoryName: Project? = null
val project = ProjectManager.getInstance().openProjects.firstOrNull(fun(project: Project): Boolean {
if (project.isDisposed) {
return false
}
val name = project.name
if (isCustomHost) {
// domain name is case-insensitive
if (projectName.equals(name, ignoreCase = true)) {
if (!SystemInfoRt.isFileSystemCaseSensitive) {
// may be passed path is not correct
projectName = name
}
return true
}
}
else {
// WEB-17839 Internal web server reports 404 when serving files from project with slashes in name
if (decodedPath.regionMatches(1, name, 0, name.length, !SystemInfoRt.isFileSystemCaseSensitive)) {
val isEmptyPathCandidate = decodedPath.length == (name.length + 1)
if (isEmptyPathCandidate || decodedPath[name.length + 1] == '/') {
projectName = name
offset = name.length + 1
isEmptyPath = isEmptyPathCandidate
return true
}
}
}
if (candidateByDirectoryName == null && compareNameAndProjectBasePath(projectName, project)) {
candidateByDirectoryName = project
}
return false
}) ?: candidateByDirectoryName ?: return false
if (isActivatable() && !PropertiesComponent.getInstance().getBoolean("ide.built.in.web.server.active")) {
notificationManager.notify("Built-in web server is deactivated, to activate, please use Open in Browser", null)
return false
}
if (isEmptyPath) {
// we must redirect "jsdebug" to "jsdebug/" as nginx does, otherwise browser will treat it as a file instead of a directory, so, relative path will not work
redirectToDirectory(request, context.channel(), projectName, null)
return true
}
val path = toIdeaPath(decodedPath, offset)
if (path == null) {
HttpResponseStatus.BAD_REQUEST.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(context.channel(), request)
return true
}
for (pathHandler in WebServerPathHandler.EP_NAME.extensions) {
LOG.catchAndLog {
if (pathHandler.process(path, project, request, context, projectName, decodedPath, isCustomHost)) {
return true
}
}
}
return false
}
internal fun HttpRequest.isSignedRequest(): Boolean {
if (BuiltInServerOptions.getInstance().allowUnsignedRequests) {
return true
}
// we must check referrer - if html cached, browser will send request without query
val token = headers().get(TOKEN_HEADER_NAME)
?: QueryStringDecoder(uri()).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull()
?: referrer?.let { QueryStringDecoder(it).parameters().get(TOKEN_PARAM_NAME)?.firstOrNull() }
// we don't invalidate token — allow to make subsequent requests using it (it is required for our javadoc DocumentationComponent)
return token != null && tokens.getIfPresent(token) != null
}
@JvmOverloads
internal fun validateToken(request: HttpRequest, channel: Channel, isSignedRequest: Boolean = request.isSignedRequest()): HttpHeaders? {
if (BuiltInServerOptions.getInstance().allowUnsignedRequests) {
return EmptyHttpHeaders.INSTANCE
}
request.headers().get(HttpHeaderNames.COOKIE)?.let {
for (cookie in ServerCookieDecoder.STRICT.decode(it)) {
if (cookie.name() == STANDARD_COOKIE.name()) {
if (cookie.value() == STANDARD_COOKIE.value()) {
return EmptyHttpHeaders.INSTANCE
}
break
}
}
}
if (isSignedRequest) {
return DefaultHttpHeaders().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(STANDARD_COOKIE) + "; SameSite=strict")
}
val urlDecoder = QueryStringDecoder(request.uri())
if (!urlDecoder.path().endsWith("/favicon.ico")) {
val url = "${channel.uriScheme}://${request.host!!}${urlDecoder.path()}"
SwingUtilities.invokeAndWait {
ProjectUtil.focusProjectWindow(null, true)
if (MessageDialogBuilder
.yesNo("", "Page '" + StringUtil.trimMiddle(url, 50) + "' requested without authorization, " +
"\nyou can copy URL and open it in browser to trust it.")
.icon(Messages.getWarningIcon())
.yesText("Copy authorization URL to clipboard")
.show() == Messages.YES) {
CopyPasteManager.getInstance().setContents(StringSelection(url + "?" + TOKEN_PARAM_NAME + "=" + acquireToken()))
}
}
}
HttpResponseStatus.UNAUTHORIZED.orInSafeMode(HttpResponseStatus.NOT_FOUND).send(channel, request)
return null
}
private fun toIdeaPath(decodedPath: String, offset: Int): String? {
// must be absolute path (relative to DOCUMENT_ROOT, i.e. scheme://authority/) to properly canonicalize
val path = decodedPath.substring(offset)
if (!path.startsWith('/')) {
return null
}
return FileUtil.toCanonicalPath(path, '/').substring(1)
}
fun compareNameAndProjectBasePath(projectName: String, project: Project): Boolean {
val basePath = project.basePath
return basePath != null && endsWithName(basePath, projectName)
}
fun findIndexFile(basedir: VirtualFile): VirtualFile? {
val children = basedir.children
if (children == null || children.isEmpty()) {
return null
}
for (indexNamePrefix in arrayOf("index.", "default.")) {
var index: VirtualFile? = null
val preferredName = indexNamePrefix + "html"
for (child in children) {
if (!child.isDirectory) {
val name = child.name
//noinspection IfStatementWithIdenticalBranches
if (name == preferredName) {
return child
}
else if (index == null && name.startsWith(indexNamePrefix)) {
index = child
}
}
}
if (index != null) {
return index
}
}
return null
}
fun findIndexFile(basedir: Path): Path? {
val children = basedir.directoryStreamIfExists({
val name = it.fileName.toString()
name.startsWith("index.") || name.startsWith("default.")
}) { it.toList() } ?: return null
for (indexNamePrefix in arrayOf("index.", "default.")) {
var index: Path? = null
val preferredName = "${indexNamePrefix}html"
for (child in children) {
if (!child.isDirectory()) {
val name = child.fileName.toString()
if (name == preferredName) {
return child
}
else if (index == null && name.startsWith(indexNamePrefix)) {
index = child
}
}
}
if (index != null) {
return index
}
}
return null
}
// is host loopback/any or network interface address (i.e. not custom domain)
// must be not used to check is host on local machine
internal fun isOwnHostName(host: String): Boolean {
if (NetUtils.isLocalhost(host)) {
return true
}
try {
val address = InetAddress.getByName(host)
if (host == address.hostAddress || host.equals(address.canonicalHostName, ignoreCase = true)) {
return true
}
val localHostName = InetAddress.getLocalHost().hostName
// WEB-8889
// develar.local is own host name: develar. equals to "develar.labs.intellij.net" (canonical host name)
return localHostName.equals(host, ignoreCase = true) || (host.endsWith(".local") && localHostName.regionMatches(0, host, 0, host.length - ".local".length, true))
}
catch (ignored: IOException) {
return false
}
} | apache-2.0 | f046acb1893ccb2f36f12894d647092d | 34.272021 | 165 | 0.710078 | 4.473874 | false | false | false | false |
prt2121/android-workspace | ContentProvider/app/src/main/kotlin/com/prt2121/contentprovider/InviteContract.kt | 1 | 685 | package com.prt2121.contentprovider
import android.content.ContentResolver
import android.content.UriMatcher
import android.net.Uri
/**
* Created by pt2121 on 1/6/16.
*/
object InviteContract {
val AUTHORITY = "com.prt2121.summon.provider"
val BASE_PATH = "invite"
val INVITE_DIR = 10
val INVITE_ITEM = 20
val CONTENT_URI = Uri.parse("content://$AUTHORITY/$BASE_PATH")
val DIR = ContentResolver.CURSOR_DIR_BASE_TYPE + "/invites"
val ITEM = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/invite"
val MATCHER = UriMatcher(UriMatcher.NO_MATCH)
init {
MATCHER.addURI(AUTHORITY, BASE_PATH, INVITE_DIR)
MATCHER.addURI(AUTHORITY, BASE_PATH + "/#", INVITE_ITEM)
}
} | apache-2.0 | 38dc7544865848a896798feb4d81ec8b | 27.583333 | 64 | 0.722628 | 3.425 | false | false | false | false |
dgngulcan/nytclient-android | app/src/main/java/com/nytclient/module/news/NewsViewModel.kt | 1 | 2123 | package com.nytclient.module.news
import android.arch.lifecycle.*
import android.databinding.ObservableBoolean
import com.nytclient.data.Resource
import com.nytclient.data.Status
import com.nytclient.data.model.NewsApiResponse
import com.nytclient.data.model.NewsItem
import com.nytclient.data.repo.NewsRepo
import com.nytclient.ui.common.BaseViewModel
import com.nytclient.ui.common.SingleLiveEvent
@Suppress("UNCHECKED_CAST")
/**
* ViewModel for [NewsFragment].
*
* Created by Dogan Gulcan on 9/12/17.
*/
class NewsViewModel constructor(newsRepo: NewsRepo) : BaseViewModel() {
var isLoadingNews = ObservableBoolean(false)
var loadingFailedevent = SingleLiveEvent<Boolean>()
var openNewsDetailEvent = SingleLiveEvent<NewsItem>()
val newsItemClickCallback = object : NewsItemClickCallback {
override fun onClick(newsItem: NewsItem) {
openNewsDetailEvent.setValue(newsItem)
}
}
private var newsApiResponse: LiveData<Resource<NewsApiResponse>> = newsRepo.getNews(0) // todo paginate
var newsListData: LiveData<List<NewsItem>> =
Transformations.switchMap(newsApiResponse, { response ->
when (response.status) {
Status.LOADING -> isLoadingNews.set(true)
Status.SUCCESS -> isLoadingNews.set(false)
Status.ERROR -> {
isLoadingNews.set(false)
loadingFailedevent.setValue(true)
}
}
val result = MutableLiveData<List<NewsItem>>()
result.value = (response as Resource<List<NewsItem>>).data
result
})
/**
* Factory class for [ViewModelProvider]. Used to pass values to constructor of the [ViewModel].
*/
class Factory(private val newsRepo: NewsRepo) : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return NewsViewModel(newsRepo) as T
}
}
interface NewsItemClickCallback {
fun onClick(newsItem: NewsItem)
}
} | apache-2.0 | 72e442a18dabdfaf26c1406632a5075f | 32.714286 | 107 | 0.658973 | 4.635371 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/interpret/test/TestInterpret15.kt | 1 | 3590 | package com.bajdcc.LALR1.interpret.test
import com.bajdcc.LALR1.grammar.Grammar
import com.bajdcc.LALR1.grammar.runtime.RuntimeCodePage
import com.bajdcc.LALR1.grammar.runtime.RuntimeException
import com.bajdcc.LALR1.interpret.Interpreter
import com.bajdcc.LALR1.syntax.handler.SyntaxException
import com.bajdcc.util.lexer.error.RegexException
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
object TestInterpret15 {
@JvmStatic
fun main(args: Array<String>) {
try {
val codes = arrayOf("""
import "sys.base";
import "sys.proc";
g_proc_exec("
import \"user.base\";
g_fork();
for (var i = 1; i <= 10; i++) {
var w = g_window(g_guid());
var width = 80 * i;
var height = 60 * i;
var border = 10;
w.\"msg\"(0, width, height);
w.\"svg\"('M', border, border);
w.\"svg\"('L', width - border, border);
w.\"svg\"('L', width - border, height - border);
w.\"svg\"('L', border, height - border);
w.\"svg\"('L', border, border);
g_sleep_s(1);
w.\"destroy\"();
}
");
""".trimIndent(), """
import "sys.base";
import "sys.proc";
g_proc_exec("
import \"user.base\";
g_fork();
for (var i = 0; i < 2; i++) {
var w = g_window(g_guid());
var width = 800;
var height = 600;
var border = 10;
w.\"msg\"(0, width, height);
w.\"svg\"('M', border, border);
w.\"svg\"('L', width - border, border);
w.\"svg\"('L', width - border, height - border);
w.\"svg\"('L', border, height - border);
w.\"svg\"('L', border, border);
w.\"svg\"('M', border * 2, border * 2);
w.\"svg\"('S', width - border * 4, height - border * 4);
w.\"str\"(1, g_string_rep(\"Hello world! \", 20));
w.\"svg\"('m', 0, 200);
w.\"str\"(1, g_string_rep(\"Hello world! \", 20));
w.\"svg\"('m', 0, 200);
w.\"str\"(0, g_string_rep(\"Hello world! \", 20));
g_sleep_s(1);
w.\"msg\"(2, 0, 0);
}
");
""".trimIndent(), """
import "sys.base";
import "sys.proc";
g_proc_exec("
import \"user.base\";
if (g_fork() == -1) {
g_printn(g_http_get(\"http://www.baidu.com\"));
} else {
var w = g_window(\"test\");
var width = 400;
var height = 300;
w.\"msg\"(0, width, height);
w.\"msg\"(2, 0, 0);
}
");
""".trimIndent())
println(codes[codes.size - 1])
val interpreter = Interpreter()
val grammar = Grammar(codes[codes.size - 1])
println(grammar.toString())
val page = grammar.codePage
//System.out.println(page.toString());
val baos = ByteArrayOutputStream()
RuntimeCodePage.exportFromStream(page, baos)
val bais = ByteArrayInputStream(baos.toByteArray())
interpreter.run("test_1", bais)
System.exit(0)
} catch (e: RegexException) {
System.err.println()
System.err.println(e.position.toString() + "," + e.message)
e.printStackTrace()
} catch (e: SyntaxException) {
System.err.println()
System.err.println(String.format("模块名:%s. 位置:%s. 错误:%s-%s(%s:%d)",
e.pageName, e.position, e.message,
e.info, e.fileName, e.position.line + 1))
e.printStackTrace()
} catch (e: RuntimeException) {
System.err.println()
System.err.println(e.position.toString() + ": " + e.info)
e.printStackTrace()
} catch (e: Exception) {
System.err.println()
System.err.println(e.message)
e.printStackTrace()
}
}
}
| mit | c063c769cf10e0552d3d2a922734b3d6 | 29.512821 | 78 | 0.551541 | 3.393536 | false | false | false | false |
nearbydelta/KoreanAnalyzer | komoran/src/main/kotlin/kr/bydelta/koala/kmr/dict.kt | 1 | 6047 | @file:JvmName("Util")
@file:JvmMultifileClass
package kr.bydelta.koala.kmr
import kr.bydelta.koala.POS
import kr.bydelta.koala.proc.CanCompileDict
import kr.bydelta.koala.proc.CanExtractResource
import kr.bydelta.koala.proc.DicEntry
import kr.co.shineware.ds.aho_corasick.model.AhoCorasickNode
import kr.co.shineware.nlp.komoran.constant.FILENAME
import kr.co.shineware.nlp.komoran.model.ScoredTag
import kr.co.shineware.nlp.komoran.modeler.model.Observation
import kr.co.shineware.nlp.komoran.parser.KoreanUnitParser
import java.io.File
import java.io.FileOutputStream
import java.util.*
/**
* 코모란 분석기 사용자사전 인터페이스를 제공합니다.
*
* @since 1.x
*/
object Dictionary : CanExtractResource(), CanCompileDict {
/**
* 사용자사전을 저장할 파일의 위치.
*
* @since 1.x
*/
@JvmStatic
internal val userDict by lazy {
val file = File(extractResource(), "koala.dict")
file.createNewFile()
file.deleteOnExit()
file
}
/**
* 시스템 사전
*
* @since 1.x
*/
@JvmStatic
private val systemdic by lazy {
val o = Observation()
o.load(o::class.java.classLoader.getResourceAsStream("${FILENAME.FULL_MODEL}/${FILENAME.OBSERVATION}"))
o
}
/** 한글 분해/합성 */
@JvmStatic
private val unitparser by lazy { KoreanUnitParser() }
/** 사용자 사전 버퍼 */
@JvmStatic
private val userBuffer = mutableListOf<DicEntry>()
/** 사전 항목 버퍼 */
@JvmStatic
private var baseEntries = mutableListOf<Pair<String, List<POS>>>()
/**
* 사용자 사전에, (표면형,품사)의 여러 순서쌍을 추가합니다.
*
* @since 1.x
* @param dict 추가할 (표면형, 품사)의 순서쌍들 (가변인자). 즉, [Pair]<[String], [POS]>들
*/
override fun addUserDictionary(vararg dict: DicEntry) = synchronized(userDict) {
userDict.parentFile.mkdirs()
FileOutputStream(userDict, true).bufferedWriter().use { bw ->
dict.forEach {
val (str, pos) = it
bw.write("$str\t${pos.fromSejongPOS()}\n")
}
}
}
/**
* 사전에 등재되어 있는지 확인하고, 사전에 없는단어만 반환합니다.
*
* @since 1.x
* @param onlySystemDic 시스템 사전에서만 검색할지 결정합니다.
* @param word 확인할 (형태소, 품사)들.
* @return 사전에 없는 단어들, 즉, [Pair]<[String], [POS]>들.
*/
override fun getNotExists(onlySystemDic: Boolean, vararg word: DicEntry): Array<DicEntry> {
// Filter out existing morphemes!
val (_, system) =
if (onlySystemDic) Pair(emptyList(), word.toList())
else word.partition { getItems().contains(it) }
return system.groupBy { it.first }.flatMap { entry ->
val (w, tags) = entry
val searched =
try {
systemdic.trieDictionary.get(unitparser.parse(w))
} catch (_: NullPointerException) {
emptyMap<String, List<ScoredTag>>()
}
// Filter out existing morphemes!
if (searched.isEmpty()) tags // For the case of not found.
else {
val found = searched.map {
val (units, scoredtag) = it
val surface = unitparser.combine(units)
val tag = scoredtag.map { t -> t.tag }
surface to tag
}.filter { it.first == w }.flatMap { it.second }.toList()
tags.filterNot { found.contains(it.second.fromSejongPOS()) }
}
}.toTypedArray()
}
/**
* 사용자 사전에 등재된 모든 Item을 불러옵니다.
*
* @since 1.x
* @return (형태소, 통합품사)의 Sequence.
*/
override fun getItems(): Set<DicEntry> = synchronized(userDict) {
userBuffer.clear()
userBuffer.addAll(userDict.bufferedReader().lines().iterator().asSequence().map {
val segs = it.split('\t')
segs[0] to segs[1].toSejongPOS()
})
userBuffer.toSet()
}
/**
* 원본 사전에 등재된 항목 중에서, 지정된 형태소의 항목만을 가져옵니다. (복합 품사 결합 형태는 제외)
*
* @since 1.x
* @param filter 가져올 품사인지 판단하는 함수.
* @return (형태소, 품사)의 Iterator.
*/
override fun getBaseEntries(filter: (POS) -> Boolean): Iterator<DicEntry> {
return extractBaseEntries().flatMap { pair ->
val (word, tags) = pair
tags.filter(filter).map { word to it }
}.iterator()
}
/** 사전 등재 항목 디코딩 */
@JvmStatic
private fun extractBaseEntries(): List<Pair<String, List<POS>>> =
if (baseEntries.isNotEmpty()) baseEntries
else synchronized(this) {
val stack = Stack<Pair<List<Char>, AhoCorasickNode<List<ScoredTag?>>>>()
stack.push(emptyList<Char>() to systemdic.trieDictionary.newFindContext().currentNode)
while (stack.isNotEmpty()) {
val (prefix, top) = stack.pop()
val word = if (top.parent == null) prefix else prefix + top.key
val value = top.value ?: emptyList()
if (value.any { it != null }) {
val wordstr = unitparser.combine(word.joinToString(""))
baseEntries.add(wordstr to value.mapNotNull { it?.tag.toSejongPOS() })
}
top.children?.forEach {
stack.push(word to it)
}
}
baseEntries
}
/**
* 모델의 명칭입니다.
*
* @since 1.x
*/
override val modelName: String = "komoran"
}
| gpl-3.0 | 5c5abc873dc111b06f9d7606dc57ea17 | 30.335227 | 111 | 0.550317 | 3.517219 | false | false | false | false |
Hexworks/zircon | zircon.jvm.libgdx/src/main/kotlin/org/hexworks/zircon/internal/tileset/LibgdxImageDictionaryTileset.kt | 1 | 2348 | /**
* WIP
*/
/*package org.hexworks.zircon.internal.tileset
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.github.benmanes.caffeine.cache.Caffeine
import org.hexworks.cobalt.core.platform.factory.UUIDFactory
import org.hexworks.zircon.api.data.ImageTile
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.internal.resource.TileType.IMAGE_TILE
import org.hexworks.zircon.api.resource.TilesetResource
import org.hexworks.zircon.api.tileset.TileTexture
import org.hexworks.zircon.api.tileset.Tileset
import org.hexworks.zircon.internal.tileset.impl.DefaultTileTexture
import java.util.concurrent.TimeUnit
class LibgdxImageDictionaryTileset(resource: TilesetResource)
: Tileset<SpriteBatch> {
override val id = UUIDFactory.randomUUID()
override val targetType = SpriteBatch::class
override val width = 1
override val height = 1
private val cache = Caffeine.newBuilder()
.initialCapacity(100)
.maximumSize(5000)
.expireAfterAccess(1, TimeUnit.MINUTES)
.build<String, TileTexture<BufferedImage>>()
private val images = File(resource.path).listFiles().map {
it.name to it
}.toMap()
init {
require(resource.tileType == IMAGE_TILE) {
"Can't use a ${resource.tileType.name}-based TilesetResource for" +
" an ImageTile-based tileset."
}
}
override fun drawTile(tile: Tile, surface: Graphics2D, position: Position) {
val texture = fetchTextureForTile(tile)
val x = position.x * width
val y = position.y * height
surface.drawImage(texture.texture, x, y, null)
}
private fun fetchTextureForTile(tile: Tile): TileTexture<BufferedImage> {
tile as? ImageTile ?: throw IllegalArgumentException("Wrong tile type")
val maybeRegion = cache.getIfPresent(tile.name)
val file = images[tile.name]!!
return if (maybeRegion != null) {
maybeRegion
} else {
val texture = ImageIO.read(file)
val image = DefaultTileTexture(
width = texture.width,
height = texture.height,
texture = texture)
cache.put(tile.name, image)
image
}
}
}*/
| apache-2.0 | f3283ce7b6195ee61670c927a3ecc761 | 34.044776 | 80 | 0.666525 | 4.332103 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/prefs/timezone/TimezoneAdapter.kt | 1 | 1832 | package org.wordpress.android.ui.prefs.timezone
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import org.wordpress.android.R
import org.wordpress.android.ui.prefs.timezone.TimezonesList.TimezoneHeader
import org.wordpress.android.ui.prefs.timezone.TimezonesList.TimezoneItem
class TimezoneAdapter(
private val onClick: (timezone: TimezoneItem) -> Unit
) : ListAdapter<TimezonesList, ViewHolder>(DIFF_CALLBACK) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return when (viewType) {
R.layout.site_settings_timezone_bottom_sheet_list_header -> TimezoneHeaderViewHolder.from(parent)
else -> TimezoneViewHolder.from(parent)
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = getItem(position)
when (holder) {
is TimezoneHeaderViewHolder -> holder.bind(item as TimezoneHeader)
is TimezoneViewHolder -> holder.bind(item as TimezoneItem, onClick)
}
}
override fun getItemViewType(position: Int): Int {
return when (getItem(position)) {
is TimezoneHeader -> R.layout.site_settings_timezone_bottom_sheet_list_header
else -> R.layout.site_settings_timezone_bottom_sheet_list_item
}
}
companion object {
val DIFF_CALLBACK = object : DiffUtil.ItemCallback<TimezonesList>() {
override fun areItemsTheSame(oldItem: TimezonesList, newItem: TimezonesList) =
oldItem.label == newItem.label
override fun areContentsTheSame(oldItem: TimezonesList, newItem: TimezonesList) =
oldItem == newItem
}
}
}
| gpl-2.0 | f4ef188c5c7d50e30f2c9f6a82b191c7 | 40.636364 | 109 | 0.700873 | 4.490196 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/core/functionalities/decaymethods/HyperbolicDecay.kt | 1 | 1501 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.core.functionalities.decaymethods
/**
* HyperbolicDecay defines an hyperbolic decay depending on the time step => LR = LRinit / (1 + decay * t).
*
* @property decay the learning rate decay applied at each time step (must be >= 0)
* @property initLearningRate the initial learning rate (must be >= [finalLearningRate])
* @property finalLearningRate the final value which the learning rate will reach (must be >= 0)
*/
class HyperbolicDecay(
val decay: Double,
val initLearningRate: Double = 0.0,
val finalLearningRate: Double = 0.0
) : DecayMethod {
/**
*
*/
init { require(this.initLearningRate > this.finalLearningRate) }
/**
* Update the learning rate given a time step.
*
* @param learningRate the learning rate to decrease
* @param timeStep the current time step
*
* @return the updated learning rate
*/
override fun update(learningRate: Double, timeStep: Int): Double {
return if (learningRate > this.finalLearningRate && this.decay > 0.0 && timeStep > 1) {
this.initLearningRate / (1.0 + this.decay * timeStep)
} else {
learningRate
}
}
}
| mpl-2.0 | c21e45d40a1f18965b42324584839a56 | 33.906977 | 107 | 0.663558 | 4.024129 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/repository/PlaylistRepositoryImpl.kt | 1 | 1577 | package com.kelsos.mbrc.repository
import com.kelsos.mbrc.data.Playlist
import com.kelsos.mbrc.di.modules.AppDispatchers
import com.kelsos.mbrc.repository.data.LocalPlaylistDataSource
import com.kelsos.mbrc.repository.data.RemotePlaylistDataSource
import com.raizlabs.android.dbflow.list.FlowCursorList
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.withContext
import org.threeten.bp.Instant
import javax.inject.Inject
class PlaylistRepositoryImpl
@Inject constructor(
private val localDataSource: LocalPlaylistDataSource,
private val remoteDataSource: RemotePlaylistDataSource,
private val dispatchers: AppDispatchers
) : PlaylistRepository {
override suspend fun getAllCursor(): FlowCursorList<Playlist> = localDataSource.loadAllCursor()
override suspend fun getAndSaveRemote(): FlowCursorList<Playlist> {
getRemote()
return localDataSource.loadAllCursor()
}
override suspend fun getRemote() {
val epoch = Instant.now().epochSecond
withContext(dispatchers.io) {
remoteDataSource.fetch()
.onCompletion {
localDataSource.removePreviousEntries(epoch)
}
.collect { list ->
val data = list.map { it.apply { dateAdded = epoch } }
localDataSource.saveAll(data)
}
}
}
override suspend fun search(term: String): FlowCursorList<Playlist> = localDataSource.search(term)
override suspend fun cacheIsEmpty(): Boolean = localDataSource.isEmpty()
override suspend fun count(): Long = localDataSource.count()
}
| gpl-3.0 | cf041c3123e1ae6698067115aeab28a6 | 33.282609 | 100 | 0.765377 | 4.693452 | false | false | false | false |
SimpleMobileTools/Simple-Music-Player | app/src/main/kotlin/com/simplemobiletools/musicplayer/adapters/ArtistsAdapter.kt | 1 | 7024 | package com.simplemobiletools.musicplayer.adapters
import android.content.ContentUris
import android.net.Uri
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.qtalk.recyclerviewfastscroller.RecyclerViewFastScroller
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.adapters.MyRecyclerViewAdapter
import com.simplemobiletools.commons.dialogs.ConfirmationDialog
import com.simplemobiletools.commons.extensions.highlightTextPart
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import com.simplemobiletools.commons.views.MyRecyclerView
import com.simplemobiletools.musicplayer.R
import com.simplemobiletools.musicplayer.extensions.*
import com.simplemobiletools.musicplayer.models.Artist
import com.simplemobiletools.musicplayer.models.Track
import kotlinx.android.synthetic.main.item_artist.view.*
class ArtistsAdapter(activity: BaseSimpleActivity, var artists: ArrayList<Artist>, recyclerView: MyRecyclerView, itemClick: (Any) -> Unit) :
MyRecyclerViewAdapter(activity, recyclerView, itemClick), RecyclerViewFastScroller.OnPopupTextUpdate {
private var textToHighlight = ""
private val placeholder = resources.getSmallPlaceholder(textColor)
private val cornerRadius = resources.getDimension(R.dimen.rounded_corner_radius_small).toInt()
init {
setupDragListener(true)
}
override fun getActionMenuId() = R.menu.cab_artists
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = createViewHolder(R.layout.item_artist, parent)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val artist = artists.getOrNull(position) ?: return
holder.bindView(artist, true, true) { itemView, layoutPosition ->
setupView(itemView, artist)
}
bindViewHolder(holder)
}
override fun getItemCount() = artists.size
override fun prepareActionMode(menu: Menu) {}
override fun actionItemPressed(id: Int) {
if (selectedKeys.isEmpty()) {
return
}
when (id) {
R.id.cab_add_to_playlist -> addToPlaylist()
R.id.cab_add_to_queue -> addToQueue()
R.id.cab_delete -> askConfirmDelete()
R.id.cab_select_all -> selectAll()
}
}
override fun getSelectableItemCount() = artists.size
override fun getIsItemSelectable(position: Int) = true
override fun getItemSelectionKey(position: Int) = artists.getOrNull(position)?.hashCode()
override fun getItemKeyPosition(key: Int) = artists.indexOfFirst { it.hashCode() == key }
override fun onActionModeCreated() {}
override fun onActionModeDestroyed() {}
private fun addToPlaylist() {
ensureBackgroundThread {
val allSelectedTracks = getAllSelectedTracks()
activity.runOnUiThread {
activity.addTracksToPlaylist(allSelectedTracks) {
finishActMode()
notifyDataSetChanged()
}
}
}
}
private fun addToQueue() {
ensureBackgroundThread {
activity.addTracksToQueue(getAllSelectedTracks()) {
finishActMode()
}
}
}
private fun getAllSelectedTracks(): ArrayList<Track> {
val tracks = ArrayList<Track>()
getSelectedArtists().forEach { artist ->
val albums = activity.getAlbumsSync(artist)
albums.forEach {
tracks.addAll(activity.getAlbumTracksSync(it.id))
}
}
return tracks
}
private fun askConfirmDelete() {
ConfirmationDialog(activity) {
ensureBackgroundThread {
val positions = ArrayList<Int>()
val selectedArtists = getSelectedArtists()
val tracks = ArrayList<Track>()
selectedArtists.forEach { artist ->
val position = artists.indexOfFirst { it.id == artist.id }
if (position != -1) {
positions.add(position)
}
val albums = activity.getAlbumsSync(artist)
albums.forEach { album ->
tracks.addAll(activity.getAlbumTracksSync(album.id))
}
activity.artistDAO.deleteArtist(artist.id)
}
activity.deleteTracks(tracks) {
activity.runOnUiThread {
positions.sortDescending()
removeSelectedItems(positions)
positions.forEach {
if (artists.size > it) {
artists.removeAt(it)
}
}
}
}
}
}
}
private fun getSelectedArtists(): List<Artist> = artists.filter { selectedKeys.contains(it.hashCode()) }.toList()
fun updateItems(newItems: ArrayList<Artist>, highlightText: String = "", forceUpdate: Boolean = false) {
if (forceUpdate || newItems.hashCode() != artists.hashCode()) {
artists = newItems.clone() as ArrayList<Artist>
textToHighlight = highlightText
notifyDataSetChanged()
finishActMode()
} else if (textToHighlight != highlightText) {
textToHighlight = highlightText
notifyDataSetChanged()
}
}
private fun setupView(view: View, artist: Artist) {
view.apply {
artist_frame?.isSelected = selectedKeys.contains(artist.hashCode())
artist_title.text = if (textToHighlight.isEmpty()) artist.title else artist.title.highlightTextPart(textToHighlight, properPrimaryColor)
artist_title.setTextColor(textColor)
val albums = resources.getQuantityString(R.plurals.albums_plural, artist.albumCnt, artist.albumCnt)
val tracks = resources.getQuantityString(R.plurals.tracks_plural, artist.trackCnt, artist.trackCnt)
artist_albums_tracks.text = "$albums, $tracks"
artist_albums_tracks.setTextColor(textColor)
val artworkUri = Uri.parse("content://media/external/audio/albumart")
val albumArtUri = ContentUris.withAppendedId(artworkUri, artist.albumArtId)
val options = RequestOptions()
.error(placeholder)
.transform(CenterCrop(), RoundedCorners(cornerRadius))
Glide.with(activity)
.load(albumArtUri)
.apply(options)
.into(findViewById(R.id.artist_image))
}
}
override fun onChange(position: Int) = artists.getOrNull(position)?.getBubbleText() ?: ""
}
| gpl-3.0 | 567880b6fc37154dea18db1f79beeca3 | 37.382514 | 148 | 0.637528 | 5.281203 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/core/overrideImplement/KtOverrideMembersHandler.kt | 1 | 5955 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.core.overrideImplement
import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.lifetime.KtLifetimeOwner
import org.jetbrains.kotlin.analysis.api.lifetime.KtLifetimeToken
import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtClassKind
import org.jetbrains.kotlin.analysis.api.symbols.KtClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithModality
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.idea.KtIconProvider.getIcon
import org.jetbrains.kotlin.idea.core.util.KotlinIdeaCoreBundle
import org.jetbrains.kotlin.name.StandardClassIds
import org.jetbrains.kotlin.psi.KtClassOrObject
internal open class KtOverrideMembersHandler : KtGenerateMembersHandler(false) {
@OptIn(KtAllowAnalysisOnEdt::class)
override fun collectMembersToGenerate(classOrObject: KtClassOrObject): Collection<KtClassMember> {
return allowAnalysisOnEdt {
analyze(classOrObject) {
collectMembers(classOrObject)
}
}
}
fun KtAnalysisSession.collectMembers(classOrObject: KtClassOrObject): List<KtClassMember> {
val classOrObjectSymbol = classOrObject.getClassOrObjectSymbol()
return getOverridableMembers(classOrObjectSymbol).map { (symbol, bodyType, containingSymbol) ->
KtClassMember(
KtClassMemberInfo(
symbol,
symbol.render(renderOption),
getIcon(symbol),
containingSymbol?.classIdIfNonLocal?.asSingleFqName()?.toString() ?: containingSymbol?.name?.asString(),
containingSymbol?.let { getIcon(it) },
),
bodyType,
preferConstructorParameter = false,
)
}
}
@OptIn(ExperimentalStdlibApi::class)
private fun KtAnalysisSession.getOverridableMembers(classOrObjectSymbol: KtClassOrObjectSymbol): List<OverrideMember> {
return buildList {
classOrObjectSymbol.getMemberScope().getCallableSymbols().forEach { symbol ->
if (!symbol.isVisibleInClass(classOrObjectSymbol)) return@forEach
val implementationStatus = symbol.getImplementationStatus(classOrObjectSymbol) ?: return@forEach
if (!implementationStatus.isOverridable) return@forEach
val intersectionSymbols = symbol.getIntersectionOverriddenSymbols()
val symbolsToProcess = if (intersectionSymbols.size <= 1) {
listOf(symbol)
} else {
val nonAbstractMembers = intersectionSymbols.filter { (it as? KtSymbolWithModality)?.modality != Modality.ABSTRACT }
// If there are non-abstract members, we only want to show override for these non-abstract members. Otherwise, show any
// abstract member to override.
nonAbstractMembers.ifEmpty {
listOf(intersectionSymbols.first())
}
}
val hasNoSuperTypesExceptAny = classOrObjectSymbol.superTypes.singleOrNull()?.isAny == true
for (symbolToProcess in symbolsToProcess) {
val originalOverriddenSymbol = symbolToProcess.originalOverriddenSymbol
val containingSymbol = originalOverriddenSymbol?.originalContainingClassForOverride
val bodyType = when {
classOrObjectSymbol.classKind == KtClassKind.INTERFACE && containingSymbol?.classIdIfNonLocal == StandardClassIds.Any -> {
if (hasNoSuperTypesExceptAny) {
// If an interface does not extends any other interfaces, FE1.0 simply skips members of `Any`. So we mimic
// the same behavior. See idea/testData/codeInsight/overrideImplement/noAnyMembersInInterface.kt
continue
} else {
BodyType.NO_BODY
}
}
(originalOverriddenSymbol as? KtSymbolWithModality)?.modality == Modality.ABSTRACT ->
BodyType.FROM_TEMPLATE
symbolsToProcess.size > 1 ->
BodyType.QUALIFIED_SUPER
else ->
BodyType.SUPER
}
// Ideally, we should simply create `KtClassMember` here and remove the intermediate `OverrideMember` data class. But
// that doesn't work because this callback function is holding a read lock and `symbol.render(renderOption)` requires
// the write lock.
// Hence, we store the data in an intermediate `OverrideMember` data class and do the rendering later in the `map` call.
add(OverrideMember(symbolToProcess, bodyType, containingSymbol, token))
}
}
}
}
private data class OverrideMember(
val symbol: KtCallableSymbol,
val bodyType: BodyType,
val containingSymbol: KtClassOrObjectSymbol?,
override val token: KtLifetimeToken
) : KtLifetimeOwner
override fun getChooserTitle() = KotlinIdeaCoreBundle.message("override.members.handler.title")
override fun getNoMembersFoundHint() = KotlinIdeaCoreBundle.message("override.members.handler.no.members.hint")
} | apache-2.0 | 30d74625139027468996b1d608e04353 | 53.145455 | 146 | 0.647691 | 5.978916 | false | false | false | false |
penneryu/penneryu-android | app/src/main/kotlin/com/penner/android/model/main/MainRecyclerAdapter.kt | 1 | 3401 | package com.penner.android.model.main
import android.app.Activity
import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.penner.android.*
/**
* Created by PennerYu on 15/10/10.
*/
class MainRecyclerAdapter(var context: Activity, var list: List<String>) : RecyclerView.Adapter<MainRecyclerAdapter.CellViewHodler>() {
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): CellViewHodler? {
val view = LayoutInflater.from(context).inflate(R.layout.penner_recycler_item, parent, false);
val viewHolder = CellViewHodler(view)
return viewHolder
}
override fun onBindViewHolder(holder: CellViewHodler?, position: Int) {
val value = list.get(position)
holder?.title?.text = value
holder?.itemView?.setOnClickListener({
if (position == 0) {
context.startActivity(Intent(context, FrescoActivity::class.java))
} else if (position == 1) {
context.startActivity(Intent(context, KotlinActivity::class.java))
} else if (position == 2) {
context.startActivity(Intent(context, LoginActivity::class.java))
} else if (position == 3) {
context.startActivity(Intent(context, BottomTabActivity::class.java))
} else if (position == 4) {
context.startActivity(Intent(context, ServiceActivity::class.java))
} else if (position == 5) {
context.startActivity(Intent(context, MaterialActivity::class.java))
} else if (position == 6) {
context.startActivity(Intent(context, DatabindingActivity::class.java))
} else if (position == 7) {
context.startActivity(Intent(context, LargeImageActivity::class.java))
} else if (position == 8) {
context.startActivity(Intent(context, ScaleGestureActivity::class.java))
} else if (position == 9) {
context.startActivity(Intent(context, RxJavaActivity::class.java))
} else if (position == 10) {
context.startActivity(Intent(context, NdkActivity::class.java))
} else if (position == 11) {
context.startActivity(Intent(context, AshmenActivity::class.java))
} else if (position == 12) {
context.startActivity(Intent(context, WebViewActivity::class.java))
} else if (position == 13) {
context.startActivity(Intent(context, EmojiActivity::class.java))
} else if (position == 14) {
context.startActivity(Intent(context, PdfActivity::class.java))
} else if (position == 15) {
context.startActivity(Intent(context, MyNativeActivity::class.java))
} else if (position == 16) {
context.startActivity(Intent(context, TestActivity::class.java))
}
})
}
override fun getItemCount(): Int {
return list.size
}
class CellViewHodler : RecyclerView.ViewHolder {
var title: TextView? = null
constructor(itemView: View) : super(itemView) {
title = itemView.findViewById(R.id.penner_recycler_txt_tile) as TextView
}
}
} | apache-2.0 | 858db13494081445744b172cc6a2c705 | 43.181818 | 135 | 0.625992 | 4.475 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceManualRangeWithIndicesCallsInspection.kt | 2 | 6774 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.inspections.collections.isMap
import org.jetbrains.kotlin.idea.intentions.getArguments
import org.jetbrains.kotlin.idea.intentions.receiverTypeIfSelectorIsSizeOrLength
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.RangeKtExpressionType
import org.jetbrains.kotlin.idea.util.RangeKtExpressionType.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
/**
* Tests:
* [org.jetbrains.kotlin.idea.inspections.LocalInspectionTestGenerated.ReplaceManualRangeWithIndicesCalls]
*/
class ReplaceManualRangeWithIndicesCallsInspection : AbstractRangeInspection() {
override fun visitRange(range: KtExpression, context: Lazy<BindingContext>, type: RangeKtExpressionType, holder: ProblemsHolder) {
val (left, right) = range.getArguments() ?: return
if (left == null) return
if (right == null) return
if (left.toIntConstant() != 0) return
val sizeOrLengthCall = right.sizeOrLengthCall(type) ?: return
val collection = sizeOrLengthCall.safeAs<KtQualifiedExpression>()?.receiverExpression
if (collection != null && collection !is KtSimpleNameExpression && collection !is KtThisExpression) return
val parent = range.parent.parent
if (parent is KtForExpression) {
val paramElement = parent.loopParameter?.originalElement ?: return
val usageElement = ReferencesSearch.search(paramElement).singleOrNull()?.element
val arrayAccess = usageElement?.parent?.parent as? KtArrayAccessExpression
if (arrayAccess != null &&
arrayAccess.indexExpressions.singleOrNull() == usageElement &&
(arrayAccess.arrayExpression as? KtSimpleNameExpression)?.mainReference?.resolve() == collection?.mainReference?.resolve()
) {
val arrayAccessParent = arrayAccess.parent
if (arrayAccessParent !is KtBinaryExpression ||
arrayAccessParent.left != arrayAccess ||
arrayAccessParent.operationToken !in KtTokens.ALL_ASSIGNMENTS
) {
holder.registerProblem(
range,
KotlinBundle.message("for.loop.over.indices.could.be.replaced.with.loop.over.elements"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceIndexLoopWithCollectionLoopQuickFix(type)
)
return
}
}
}
holder.registerProblem(
range,
KotlinBundle.message("range.could.be.replaced.with.indices.call"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
ReplaceManualRangeWithIndicesCallQuickFix()
)
}
}
class ReplaceManualRangeWithIndicesCallQuickFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.manual.range.with.indices.call.quick.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as KtExpression
val receiver = when (val secondArg = element.getArguments()?.second) {
is KtBinaryExpression -> (secondArg.left as? KtDotQualifiedExpression)?.receiverExpression
is KtDotQualifiedExpression -> secondArg.receiverExpression
else -> null
}
val psiFactory = KtPsiFactory(project)
val newExpression = if (receiver != null && receiver !is KtThisExpression) {
psiFactory.createExpressionByPattern("$0.indices", receiver)
} else {
psiFactory.createExpression("indices")
}
element.replace(newExpression)
}
}
class ReplaceIndexLoopWithCollectionLoopQuickFix(private val type: RangeKtExpressionType) : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.index.loop.with.collection.loop.quick.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement.getStrictParentOfType<KtForExpression>() ?: return
val loopParameter = element.loopParameter ?: return
val loopRange = element.loopRange ?: return
val collectionParent = when (loopRange) {
is KtDotQualifiedExpression -> (loopRange.parent as? KtCallExpression)?.valueArguments?.firstOrNull()?.getArgumentExpression()
is KtBinaryExpression -> loopRange.right
else -> null
} ?: return
val sizeOrLengthCall = collectionParent.sizeOrLengthCall(type) ?: return
val collection = (sizeOrLengthCall as? KtDotQualifiedExpression)?.receiverExpression
val paramElement = loopParameter.originalElement ?: return
val usageElement = ReferencesSearch.search(paramElement).singleOrNull()?.element ?: return
val arrayAccessElement = usageElement.parent.parent as? KtArrayAccessExpression ?: return
val factory = KtPsiFactory(project)
val newParameter = factory.createLoopParameter("element")
val newReferenceExpression = factory.createExpression("element")
arrayAccessElement.replace(newReferenceExpression)
loopParameter.replace(newParameter)
loopRange.replace(collection ?: factory.createThisExpression())
}
}
private fun KtExpression.toIntConstant(): Int? {
return (this as? KtConstantExpression)?.text?.toIntOrNull()
}
private fun KtExpression.sizeOrLengthCall(type: RangeKtExpressionType): KtExpression? {
val expression = when (type) {
UNTIL, RANGE_UNTIL -> this
RANGE_TO -> (this as? KtBinaryExpression)
?.takeIf { operationToken == KtTokens.MINUS && right?.toIntConstant() == 1 }
?.left
DOWN_TO -> return null
}
val receiverType = expression.receiverTypeIfSelectorIsSizeOrLength() ?: return null
if (receiverType.isMap()) return null
return expression
}
| apache-2.0 | 2ed18a32230c746924327f2bc98af0b2 | 48.445255 | 138 | 0.707411 | 5.288056 | false | false | false | false |
jimandreas/UIandOpenGLthreading | app/src/main/java/com/jimandreas/handlerstudy/opengl/Square.kt | 1 | 5554 | /*
* Copyright (C) 2011 The Android Open Source Project
* Copyright (c) 2018 Jim Andreas
* 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.jimandreas.handlerstudy.opengl
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import java.nio.ShortBuffer
import android.opengl.GLES20
/**
* A two-dimensional square for use as a drawn object in OpenGL ES 2.0.
*/
class Square {
private val vertexShaderCode = "uniform mat4 uMVPMatrix;" +
"attribute vec4 vPosition;" +
"void main() {" +
// The matrix must be included as a modifier of gl_Position.
// Note that the uMVPMatrix factor *must be first* in order
// for the matrix multiplication product to be correct.
" gl_Position = uMVPMatrix * vPosition;" +
"}"
private val fragmentShaderCode = "precision mediump float;" +
"uniform vec4 vColor;" +
"void main() {" +
" gl_FragColor = vColor;" +
"}"
private val vertexBuffer: FloatBuffer
private val drawListBuffer: ShortBuffer
private val mProgram: Int
private var mPositionHandle: Int = 0
private var mColorHandle: Int = 0
private var mMVPMatrixHandle: Int = 0
private val drawOrder = shortArrayOf(0, 1, 2, 0, 2, 3) // order to draw vertices
private val vertexStride = COORDS_PER_VERTEX * 4 // 4 bytes per vertex
internal var color = floatArrayOf(0.2f, 0.709803922f, 0.898039216f, 1.0f)
/**
* Sets up the drawing object data for use in an OpenGL ES context.
*/
init {
// initialize vertex byte buffer for shape coordinates
val bb = ByteBuffer.allocateDirect(
// (# of coordinate values * 4 bytes per float)
squareCoords.size * 4)
bb.order(ByteOrder.nativeOrder())
vertexBuffer = bb.asFloatBuffer()
vertexBuffer.put(squareCoords)
vertexBuffer.position(0)
// initialize byte buffer for the draw list
val dlb = ByteBuffer.allocateDirect(
// (# of coordinate values * 2 bytes per short)
drawOrder.size * 2)
dlb.order(ByteOrder.nativeOrder())
drawListBuffer = dlb.asShortBuffer()
drawListBuffer.put(drawOrder)
drawListBuffer.position(0)
// prepare shaders and OpenGL program
val vertexShader = MyGLRenderer.loadShader(
GLES20.GL_VERTEX_SHADER,
vertexShaderCode)
val fragmentShader = MyGLRenderer.loadShader(
GLES20.GL_FRAGMENT_SHADER,
fragmentShaderCode)
mProgram = GLES20.glCreateProgram() // create empty OpenGL Program
GLES20.glAttachShader(mProgram, vertexShader) // add the vertex shader to program
GLES20.glAttachShader(mProgram, fragmentShader) // add the fragment shader to program
GLES20.glLinkProgram(mProgram) // create OpenGL program executables
}
/**
* Encapsulates the OpenGL ES instructions for drawing this shape.
*
* @param mvpMatrix - The Model View Project matrix in which to draw
* this shape.
*/
fun draw(mvpMatrix: FloatArray) {
// Add program to OpenGL environment
GLES20.glUseProgram(mProgram)
// get handle to vertex shader's vPosition member
mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition")
// Enable a handle to the triangle vertices
GLES20.glEnableVertexAttribArray(mPositionHandle)
// Prepare the triangle coordinate data
GLES20.glVertexAttribPointer(
mPositionHandle, COORDS_PER_VERTEX,
GLES20.GL_FLOAT, false,
vertexStride, vertexBuffer)
// get handle to fragment shader's vColor member
mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor")
// Set color for drawing the triangle
GLES20.glUniform4fv(mColorHandle, 1, color, 0)
// get handle to shape's transformation matrix
mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix")
MyGLRenderer.checkGlError("glGetUniformLocation")
// Apply the projection and view transformation
GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0)
MyGLRenderer.checkGlError("glUniformMatrix4fv")
// Draw the square
GLES20.glDrawElements(
GLES20.GL_TRIANGLES, drawOrder.size,
GLES20.GL_UNSIGNED_SHORT, drawListBuffer)
// Disable vertex array
GLES20.glDisableVertexAttribArray(mPositionHandle)
}
companion object {
// number of coordinates per vertex in this array
internal const val COORDS_PER_VERTEX = 3
internal var squareCoords = floatArrayOf(-0.5f, 0.5f, 0.0f, // top left
-0.5f, -0.5f, 0.0f, // bottom left
0.5f, -0.5f, 0.0f, // bottom right
0.5f, 0.5f, 0.0f) // top right
}
} | apache-2.0 | df2930612ecc0aaab73326c3743a8dc7 | 36.281879 | 93 | 0.646741 | 4.537582 | false | false | false | false |
marius-m/wt4 | models/src/main/java/lt/markmerkk/utils/LogUtils.kt | 1 | 2371 | package lt.markmerkk.utils
import lt.markmerkk.entities.Log
import org.joda.time.*
object LogUtils {
const val NO_NUMBER = -1
private val ticketRegex = "([a-zA-Z0-9]+)-([0-9]+)".toRegex()
/**
* Inspects id for a valid type
* @param message
*/
fun validateTaskTitle(message: String): String {
val result = ticketRegex.find(message) ?: return ""
return result
.groupValues
.firstOrNull()
?.toUpperCase() ?: ""
}
/**
* Splits task title and returns it
*/
fun splitTaskTitle(message: String): String {
val result = ticketRegex.find(message) ?: return ""
if (result.groupValues.size > 1) {
return result.groupValues[1]
.toUpperCase()
}
return ""
}
/**
* Splits task title into
*/
fun splitTaskNumber(message: String): Int {
val ticketMatch: MatchResult = ticketRegex.find(message) ?: return NO_NUMBER
if (ticketMatch.groupValues.size > 1)
return ticketMatch.groupValues[2].toInt()
return NO_NUMBER
}
/**
* Formats duration time into pretty and short string format
* @param duration provided duration to format
* *
* @return formatted duration
*/
fun formatShortDuration(duration: Duration): String {
return LogFormatters.humanReadableDurationShort(duration)
}
/**
* Formats duration time into pretty and short string format
* @param durationMillis provided duration to format
* *
* @return formatted duration
*/
fun formatShortDurationMillis(durationMillis: Long): String {
val duration = Duration(durationMillis)
return LogFormatters.humanReadableDurationShort(duration)
}
fun firstLine(input: String): String {
return input.split("\n")
.first()
}
/**
* Formats log as a pretty text
*/
@JvmStatic fun formatLogToText(log: Log): String {
val timeFrom = LogFormatters.formatTime.print(log.time.start)
val timeTo = LogFormatters.formatTime.print(log.time.end)
val duration = formatShortDurationMillis(log.time.duration.millis)
return "${log.code.code} ($timeFrom - $timeTo = $duration) ${firstLine(log.comment)}"
.trim()
}
} | apache-2.0 | b63fbf06e6496a5adfb68f650af7308c | 27.926829 | 93 | 0.605652 | 4.473585 | false | false | false | false |
marius-m/wt4 | database2/src/main/java/lt/markmerkk/migrations/Migration7To8.kt | 1 | 1259 | package lt.markmerkk.migrations
import lt.markmerkk.DBConnProvider
import lt.markmerkk.Tags
import org.slf4j.LoggerFactory
import java.sql.Connection
import java.sql.SQLException
class Migration7To8(
private val database: DBConnProvider
) : DBMigration {
override val migrateVersionFrom: Int = 7
override val migrateVersionTo: Int = 8
override fun migrate(conn: Connection) {
val sql = "" +
"CREATE TABLE `ticket_use_history` (\n" +
" `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
" `code_project` VARCHAR(50) DEFAULT '' NOT NULL,\n" +
" `code_number` VARCHAR(50) DEFAULT '' NOT NULL,\n" +
" `code` VARCHAR(50) DEFAULT '' NOT NULL,\n" +
" `lastUsed` BIGINT NOT NULL DEFAULT 0\n" +
");"
try {
val createTableStatement = conn.createStatement()
logger.debug("Creating new table: $sql")
createTableStatement.execute(sql)
} catch (e: SQLException) {
logger.error("Error executing migration from $migrateVersionFrom to $migrateVersionTo", e)
}
}
companion object {
private val logger = LoggerFactory.getLogger(Tags.DB)!!
}
} | apache-2.0 | 4c7aaaee1dd4cd5c7e1bdcc23b42d358 | 33.054054 | 102 | 0.606037 | 4.296928 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-core/jvmAndNix/src/io/ktor/server/plugins/Errors.kt | 1 | 3851 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.plugins
import io.ktor.http.*
import io.ktor.server.application.internal.*
import io.ktor.util.internal.*
import kotlinx.coroutines.*
import kotlin.reflect.*
/**
* Base exception to indicate that the request is not correct due to
* wrong/missing request parameters, body content or header values.
* Throwing this exception in a handler will lead to 400 Bad Request response
* unless a custom [io.ktor.plugins.StatusPages] handler registered.
*/
public open class BadRequestException(message: String, cause: Throwable? = null) : Exception(message, cause)
/**
* This exception means that the requested resource is not found.
* HTTP status 404 Not found will be replied when this exception is thrown and not caught.
* 404 status page could be configured by registering a custom [io.ktor.plugins.StatusPages] handler.
*/
public class NotFoundException(message: String? = "Resource not found") : Exception(message)
/**
* This exception is thrown when a required parameter with name [parameterName] is missing
* @property parameterName of missing request parameter
*/
@OptIn(ExperimentalCoroutinesApi::class)
public class MissingRequestParameterException(
public val parameterName: String
) : BadRequestException("Request parameter $parameterName is missing"),
CopyableThrowable<MissingRequestParameterException> {
override fun createCopy(): MissingRequestParameterException = MissingRequestParameterException(parameterName).also {
it.initCauseBridge(this)
}
}
/**
* This exception is thrown when a required parameter with name [parameterName] couldn't be converted to the [type]
* @property parameterName of missing request parameter
* @property type this parameter is unable to convert to
*/
@OptIn(ExperimentalCoroutinesApi::class)
public class ParameterConversionException(
public val parameterName: String,
public val type: String,
cause: Throwable? = null
) : BadRequestException("Request parameter $parameterName couldn't be parsed/converted to $type", cause),
CopyableThrowable<ParameterConversionException> {
override fun createCopy(): ParameterConversionException =
ParameterConversionException(parameterName, type, this).also {
it.initCauseBridge(this)
}
}
/**
* Thrown when content cannot be transformed to the desired type.
* It is not defined which status code will be replied when an exception of this type is thrown and not caught.
* Depending on child type it could be 4xx or 5xx status code. By default it will be 500 Internal Server Error.
*/
public abstract class ContentTransformationException(message: String) : Exception(message)
@OptIn(ExperimentalCoroutinesApi::class)
public class CannotTransformContentToTypeException(
private val type: KType
) : ContentTransformationException("Cannot transform this request's content to $type"),
CopyableThrowable<CannotTransformContentToTypeException> {
override fun createCopy(): CannotTransformContentToTypeException =
CannotTransformContentToTypeException(type).also {
it.initCauseBridge(this)
}
}
/**
* Thrown when there is no conversion for a content type configured.
* HTTP status 415 Unsupported Media Type will be replied when this exception is thrown and not caught.
*/
@OptIn(ExperimentalCoroutinesApi::class)
public class UnsupportedMediaTypeException(
private val contentType: ContentType
) : ContentTransformationException("Content type $contentType is not supported"),
CopyableThrowable<UnsupportedMediaTypeException> {
override fun createCopy(): UnsupportedMediaTypeException = UnsupportedMediaTypeException(contentType).also {
it.initCauseBridge(this)
}
}
| apache-2.0 | 008727db539d2aa6a96a0072bc118c4f | 39.968085 | 120 | 0.772267 | 4.868521 | false | false | false | false |
oldergod/android-architecture | app/src/main/java/com/example/android/architecture/blueprints/todoapp/statistics/StatisticsViewModel.kt | 1 | 6284 | /*
* Copyright 2016, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp.statistics
import android.arch.lifecycle.ViewModel
import com.example.android.architecture.blueprints.todoapp.mvibase.MviAction
import com.example.android.architecture.blueprints.todoapp.mvibase.MviIntent
import com.example.android.architecture.blueprints.todoapp.mvibase.MviResult
import com.example.android.architecture.blueprints.todoapp.mvibase.MviView
import com.example.android.architecture.blueprints.todoapp.mvibase.MviViewModel
import com.example.android.architecture.blueprints.todoapp.mvibase.MviViewState
import com.example.android.architecture.blueprints.todoapp.statistics.StatisticsAction.LoadStatisticsAction
import com.example.android.architecture.blueprints.todoapp.statistics.StatisticsResult.LoadStatisticsResult
import com.example.android.architecture.blueprints.todoapp.statistics.StatisticsResult.LoadStatisticsResult.Failure
import com.example.android.architecture.blueprints.todoapp.statistics.StatisticsResult.LoadStatisticsResult.InFlight
import com.example.android.architecture.blueprints.todoapp.statistics.StatisticsResult.LoadStatisticsResult.Success
import com.example.android.architecture.blueprints.todoapp.util.notOfType
import io.reactivex.Observable
import io.reactivex.ObservableTransformer
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.functions.BiFunction
import io.reactivex.subjects.PublishSubject
/**
* Listens to user actions from the UI ([StatisticsFragment]), retrieves the data and updates
* the UI as required.
*
* @property actionProcessorHolder Contains and executes the business logic of all emitted actions.
*/
class StatisticsViewModel(
private val actionProcessorHolder: StatisticsActionProcessorHolder
) : ViewModel(), MviViewModel<StatisticsIntent, StatisticsViewState> {
/**
* Proxy subject used to keep the stream alive even after the UI gets recycled.
* This is basically used to keep ongoing events and the last cached State alive
* while the UI disconnects and reconnects on config changes.
*/
private val intentsSubject: PublishSubject<StatisticsIntent> = PublishSubject.create()
private val statesObservable: Observable<StatisticsViewState> = compose()
private val disposables = CompositeDisposable()
/**
* take only the first ever InitialIntent and all intents of other types
* to avoid reloading data on config changes
*/
private val intentFilter: ObservableTransformer<StatisticsIntent, StatisticsIntent>
get() = ObservableTransformer { intents ->
intents.publish { shared ->
Observable.merge<StatisticsIntent>(
shared.ofType(StatisticsIntent.InitialIntent::class.java).take(1),
shared.notOfType(StatisticsIntent.InitialIntent::class.java)
)
}
}
override fun processIntents(intents: Observable<StatisticsIntent>) {
disposables.add(intents.subscribe(intentsSubject::onNext))
}
override fun states(): Observable<StatisticsViewState> = statesObservable
/**
* Compose all components to create the stream logic
*/
private fun compose(): Observable<StatisticsViewState> {
return intentsSubject
.compose<StatisticsIntent>(intentFilter)
.map<StatisticsAction>(this::actionFromIntent)
.compose(actionProcessorHolder.actionProcessor)
// Cache each state and pass it to the reducer to create a new state from
// the previous cached one and the latest Result emitted from the action processor.
// The Scan operator is used here for the caching.
.scan(StatisticsViewState.idle(), reducer)
// When a reducer just emits previousState, there's no reason to call render. In fact,
// redrawing the UI in cases like this can cause jank (e.g. messing up snackbar animations
// by showing the same snackbar twice in rapid succession).
.distinctUntilChanged()
// Emit the last one event of the stream on subscription.
// Useful when a View rebinds to the ViewModel after rotation.
.replay(1)
// Create the stream on creation without waiting for anyone to subscribe
// This allows the stream to stay alive even when the UI disconnects and
// match the stream's lifecycle to the ViewModel's one.
.autoConnect(0)
}
/**
* Translate an [MviIntent] to an [MviAction].
* Used to decouple the UI and the business logic to allow easy testings and reusability.
*/
private fun actionFromIntent(intent: StatisticsIntent): StatisticsAction {
return when (intent) {
is StatisticsIntent.InitialIntent -> LoadStatisticsAction
}
}
override fun onCleared() {
disposables.dispose()
}
companion object {
/**
* The Reducer is where [MviViewState], that the [MviView] will use to
* render itself, are created.
* It takes the last cached [MviViewState], the latest [MviResult] and
* creates a new [MviViewState] by only updating the related fields.
* This is basically like a big switch statement of all possible types for the [MviResult]
*/
private val reducer = BiFunction { previousState: StatisticsViewState, result: StatisticsResult ->
when (result) {
is LoadStatisticsResult -> when (result) {
is Success ->
previousState.copy(
isLoading = false,
activeCount = result.activeCount,
completedCount = result.completedCount
)
is Failure -> previousState.copy(isLoading = false, error = result.error)
is InFlight -> previousState.copy(isLoading = true)
}
}
}
}
}
| apache-2.0 | 5f71d0822904f6eedb05969bcc042890 | 44.208633 | 116 | 0.743794 | 4.845027 | false | false | false | false |
McMoonLakeDev/MoonLake | API/src/main/kotlin/com/mcmoonlake/api/MoonLakeAPI.kt | 1 | 29857 | /*
* Copyright (C) 2016-Present The MoonLake ([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/>.
*/
@file:JvmName("MoonLakeAPI")
package com.mcmoonlake.api
import com.mcmoonlake.api.anvil.AnvilWindow
import com.mcmoonlake.api.anvil.AnvilWindows
import com.mcmoonlake.api.chat.ChatAction
import com.mcmoonlake.api.chat.ChatComponent
import com.mcmoonlake.api.chat.ChatSerializer
import com.mcmoonlake.api.depend.DependPlugin
import com.mcmoonlake.api.depend.DependPluginException
import com.mcmoonlake.api.depend.DependPlugins
import com.mcmoonlake.api.event.MoonLakeEvent
import com.mcmoonlake.api.event.MoonLakeListener
import com.mcmoonlake.api.exception.MoonLakeException
import com.mcmoonlake.api.funs.Function
import com.mcmoonlake.api.item.ItemBuilder
import com.mcmoonlake.api.nbt.NBTCompound
import com.mcmoonlake.api.nbt.NBTFactory
import com.mcmoonlake.api.nbt.NBTList
import com.mcmoonlake.api.packet.PacketListener
import com.mcmoonlake.api.packet.PacketListeners
import com.mcmoonlake.api.packet.PacketOutChat
import com.mcmoonlake.api.packet.PacketOutTitle
import com.mcmoonlake.api.player.MoonLakePlayer
import com.mcmoonlake.api.player.MoonLakePlayerCached
import com.mcmoonlake.api.region.*
import com.mcmoonlake.api.task.MoonLakeRunnable
import com.mcmoonlake.api.util.Enums
import com.mcmoonlake.api.version.MinecraftBukkitVersion
import com.mcmoonlake.api.version.MinecraftVersion
import org.bukkit.*
import org.bukkit.command.CommandSender
import org.bukkit.command.PluginCommand
import org.bukkit.configuration.Configuration
import org.bukkit.configuration.serialization.ConfigurationSerializable
import org.bukkit.entity.Entity
import org.bukkit.entity.Item
import org.bukkit.entity.LivingEntity
import org.bukkit.entity.Player
import org.bukkit.event.Event
import org.bukkit.event.EventPriority
import org.bukkit.event.HandlerList
import org.bukkit.event.Listener
import org.bukkit.event.inventory.InventoryType
import org.bukkit.inventory.Inventory
import org.bukkit.inventory.InventoryHolder
import org.bukkit.inventory.ItemStack
import org.bukkit.plugin.EventExecutor
import org.bukkit.plugin.Plugin
import org.bukkit.plugin.PluginManager
import org.bukkit.plugin.ServicesManager
import org.bukkit.plugin.messaging.Messenger
import org.bukkit.scheduler.BukkitScheduler
import org.bukkit.scheduler.BukkitTask
import org.bukkit.scoreboard.Scoreboard
import java.io.Closeable
import java.io.IOException
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.text.MessageFormat
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Future
import java.util.concurrent.FutureTask
/** MoonLake API Extended Function */
private var moonlake: MoonLake? = null
@Throws(MoonLakeException::class)
fun setMoonLake(obj: MoonLake) {
if(moonlake != null)
throw MoonLakeException("无法再次设置 MoonLakeAPI 的内部实例.")
moonlake = obj
}
fun getMoonLake(): MoonLake
= moonlake.notNull()
/** type aliases */
typealias Predicate<T> = (T) -> Boolean
/** extended function */
@JvmOverloads
fun <T> T?.notNull(message: String = "验证的对象值为 null 时异常."): T
= this ?: throw IllegalArgumentException(message)
@Throws(IOException::class)
fun Closeable?.ioClose(swallow: Boolean) {
if(this == null)
return
try {
close()
} catch(e: IOException) {
if(!swallow)
throw e
}
}
fun <T, C: Comparable<T>> C.isLater(other: T): Boolean
= compareTo(other) > 0
fun <T, C: Comparable<T>> C.isOrLater(other: T): Boolean
= compareTo(other) >= 0
fun <T, C: Comparable<T>> C.isRange(min: T, max: T): Boolean
= compareTo(min) > 0 && compareTo(max) < 0
fun <T, C: Comparable<T>> C.isOrRange(min: T, max: T): Boolean
= compareTo(min) >= 0 && compareTo(max) <= 0
@JvmOverloads
inline fun <V, reified T> ofValuable(value: V?, def: T? = null): T? where T: Enum<T>, T: Valuable<V>
= Enums.ofValuable(T::class.java, value, def)
@Throws(IllegalArgumentException::class)
inline fun <V, reified T> ofValuableNotNull(value: V?): T where T: Enum<T>, T: Valuable<V>
= ofValuable(value) ?: throw IllegalArgumentException("未知的枚举 ${T::class.java.canonicalName} 类型值: $value")
inline fun <E> Iterable<E>.except(block: () -> E): List<E>
{ val element = block(); return filter { it != element } }
/** version function */
fun currentMCVersion(): MinecraftVersion
= MinecraftVersion.currentVersion()
fun currentBukkitVersion(): MinecraftBukkitVersion
= MinecraftBukkitVersion.currentVersion()
/** util function */
private val combatOrLaterVer = currentBukkitVersion().isOrLater(MinecraftBukkitVersion.V1_9_R1)
private val frostburnOrLaterVer = currentBukkitVersion().isOrLater(MinecraftBukkitVersion.V1_10_R1)
private val explorationOrLaterVer = currentBukkitVersion().isOrLater(MinecraftBukkitVersion.V1_11_R1)
private val colorWorldOrLaterVer = currentBukkitVersion().isOrLater(MinecraftBukkitVersion.V1_12_R1)
private val javaEditionOrLaterVer = currentMCVersion().isOrLater(MinecraftVersion(1, 12, 2))
private val aquaticOrLaterVer = currentBukkitVersion().isOrLater(MinecraftBukkitVersion.V1_13_R1)
/**
* Returns if the server version is 1.9 or later.
*/
val isCombatOrLaterVer: Boolean
get() = combatOrLaterVer
/**
* Returns if the server version is 1.10 or later.
*/
val isFrostburnOrLaterVer: Boolean
get() = frostburnOrLaterVer
/**
* Returns if the server version is 1.11 or later.
*/
val isExplorationOrLaterVer: Boolean
get() = explorationOrLaterVer
/**
* Returns if the server version is 1.12 or later.
*/
val isColorWorldOrLaterVer: Boolean
get() = colorWorldOrLaterVer
/**
* Returns if the server version is 1.12.2 or later.
*/
val isJavaEditionOrLaterVer: Boolean
get() = javaEditionOrLaterVer
/**
* Returns if the server version is 1.13 or later.
*/
val isAquaticOrLaterVer: Boolean
get() = aquaticOrLaterVer
private val spigotServer: Boolean by lazy {
try {
Class.forName("org.spigotmc.SpigotConfig")
true
} catch(e: Exception) {
false
}
}
/**
* Returns true if the server is spigot.
*/
val isSpigotServer: Boolean
get() = spigotServer
fun String.toColor(): String
= com.mcmoonlake.api.chat.ChatColor.translateAlternateColorCodes('&', this)
fun String.toColor(altColorChar: Char): String
= com.mcmoonlake.api.chat.ChatColor.translateAlternateColorCodes(altColorChar, this)
fun Array<out String>.toColor(): Array<out String>
= toList().map { it.toColor() }.toTypedArray()
fun Array<out String>.toColor(altColorChar: Char): Array<out String>
= toList().map { it.toColor(altColorChar) }.toTypedArray()
fun Iterable<String>.toColor(): List<String>
= map { it.toColor() }.let { ArrayList(it) }
fun Iterable<String>.toColor(altColorChar: Char): List<String>
= map { it.toColor(altColorChar) }
fun String.stripColor(): String
= com.mcmoonlake.api.chat.ChatColor.stripColor(this)
fun Array<out String>.stripColor(): Array<out String>
= toList().map { it.stripColor() }.toTypedArray()
fun Iterable<String>.stripColor(): List<String>
= map { it.stripColor() }
fun String.messageFormat(vararg args: Any?): String
= MessageFormat.format(this, args)
@Throws(MoonLakeException::class)
fun Throwable.throwMoonLake(): Nothing = when(this is MoonLakeException) {
true -> throw this
else -> throw MoonLakeException(this)
}
@Throws(Throwable::class)
inline fun <T: Throwable, reified R: Throwable> T.throwGiven(block: (T) -> R): Nothing
= when(R::class.java.isInstance(this)) {
true -> throw this
else -> throw block(this)
}
/**
* Returns true if this is null or true
*/
fun Boolean?.orTrue(): Boolean
= this == null || this == true
/**
* Returns false if this is null or false
*/
fun Boolean?.orFalse(): Boolean
= !(this == null || this == false)
inline fun <reified T> T.consumer(block: (T) -> Unit)
= block(this)
fun String.isInteger(): Boolean = when(isNullOrEmpty()) {
true -> false
else -> try {
toInt()
true
} catch (e: NumberFormatException) {
false
}
}
fun String.isDouble(): Boolean = when(isNullOrEmpty()) {
true -> false
else -> try {
toDouble()
true
} catch (e: NumberFormatException) {
false
}
}
@JvmOverloads
fun Any.parseInt(def: Int = 0): Int = when(this is Number) {
true -> (this as Number).toInt()
else -> try {
toString().toInt()
} catch (e: NumberFormatException) {
def
}
}
@JvmOverloads
fun Any.parseLong(def: Long = 0L): Long = when(this is Number) {
true -> (this as Number).toLong()
else -> try {
toString().toLong()
} catch (e: NumberFormatException) {
def
}
}
@JvmOverloads
fun Any.parseFloat(def: Float = .0f): Float = when(this is Number) {
true -> (this as Number).toFloat()
else -> try {
toString().toFloat()
} catch (e: NumberFormatException) {
def
}
}
@JvmOverloads
fun Any.parseDouble(def: Double = .0): Double = when(this is Number) {
true -> (this as Number).toDouble()
else -> try {
toString().toDouble()
} catch (e: NumberFormatException) {
def
}
}
@JvmOverloads
fun Any.parseBoolean(def: Boolean = false): Boolean = when(this is Boolean) {
true -> this as Boolean
else -> try {
toString().toBoolean()
} catch (e: Exception) {
def
}
}
@JvmOverloads
@Throws(MoonLakeException::class)
fun <T: ConfigurationSerializable> Class<T>.deserialize(configuration: Configuration, key: String, def: T? = null): T? = configuration.get(key).let {
when(it == null) {
true -> def
else -> when {
isInstance(it) -> cast(it)
it is Map<*, *> -> try {
var method: Method? = getDeclaredMethod("deserialize", Map::class.java)
if(method == null) method = getDeclaredMethod("valueOf", Map::class.java)
if(method == null || !Modifier.isStatic(method.modifiers)) throw MoonLakeException("值为 Map 实例, 但是序列化类不存在 'deserialize' 或 'valueOf' 静态函数.")
@Suppress("UNCHECKED_CAST")
method.invoke(null, it) as T
} catch (e: Exception) {
e.throwMoonLake()
}
else -> def
}
}
}
@JvmOverloads
@Throws(MoonLakeException::class)
fun <T: ConfigurationSerializable> Configuration.deserialize(clazz: Class<T>, key: String, def: T? = null): T?
= clazz.deserialize(this, key, def)
fun getOnlinePlayers(): Collection<Player>
= Bukkit.getOnlinePlayers()
fun getOnlinePlayersExcept(player: Player): Collection<Player>
= Bukkit.getOnlinePlayers().except { player }
fun createInventory(holder: InventoryHolder?, type: InventoryType): Inventory
= Bukkit.createInventory(holder, type)
fun createInventory(holder: InventoryHolder?, type: InventoryType, title: String): Inventory
= Bukkit.createInventory(holder, type, title)
fun createInventory(holder: InventoryHolder?, size: Int): Inventory
= Bukkit.createInventory(holder, size)
fun createInventory(holder: InventoryHolder?, size: Int, title: String): Inventory
= Bukkit.createInventory(holder, size, title)
fun getScoreboardMain(): Scoreboard
= Bukkit.getScoreboardManager().mainScoreboard
fun getScoreboardNew(): Scoreboard
= Bukkit.getScoreboardManager().newScoreboard
fun getMessenger(): Messenger
= Bukkit.getMessenger()
fun getServicesManager(): ServicesManager
= Bukkit.getServicesManager()
fun getPluginManager(): PluginManager
= Bukkit.getPluginManager()
fun getPlugin(name: String): Plugin?
= Bukkit.getPluginManager().getPlugin(name)
fun getScheduler(): BukkitScheduler
= Bukkit.getScheduler()
fun getPluginCommand(name: String): PluginCommand
= Bukkit.getPluginCommand(name)
fun dispatchCommand(sender: CommandSender, command: String): Boolean
= Bukkit.dispatchCommand(sender, command)
fun dispatchConsoleCmd(command: String): Boolean
= Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command)
/** converter function */
fun UUID.toBukkitWorld(): World?
= Bukkit.getWorld(this)
fun String.toBukkitWorld(): World?
= Bukkit.getWorld(this)
fun UUID.toEntity(): Entity?
= Bukkit.getEntity(this)
fun UUID.toPlayer(): Player?
= Bukkit.getPlayer(this)
fun String.toPlayer(): Player?
= Bukkit.getPlayer(this)
fun String.toPlayerExact(): Player?
= Bukkit.getPlayerExact(this)
fun Player.toMoonLakePlayer(): MoonLakePlayer
= MoonLakePlayerCached.of(this)
fun UUID.toMoonLakePlayer(): MoonLakePlayer?
= toPlayer()?.toMoonLakePlayer()
fun String.toMoonLakePlayer(): MoonLakePlayer?
= toPlayer()?.toMoonLakePlayer()
fun Location.toRegionVector(): RegionVector
= RegionVector(x, y, z)
fun Location.toRegionVectorBlock(): RegionVectorBlock
= RegionVectorBlock(x, y, z)
fun Location.toRegionVector2D(): RegionVector2D
= RegionVector2D(x, z)
fun <T, R> ((T) -> R).toFunction(): Function<T, R> = object: Function<T, R> {
override fun apply(param: T): R
= this@toFunction(param)
}
fun <T> (() -> T).toCallable(): Callable<T>
= Callable { this@toCallable() }
/** event function */
fun Event.callEvent()
= Bukkit.getServer().pluginManager.callEvent(this)
fun Event.callEventAsync(plugin: Plugin)
= plugin.runTaskAsync(Runnable { Bukkit.getServer().pluginManager.callEvent(this) })
fun MoonLakeEvent.callEvent()
= Bukkit.getServer().pluginManager.callEvent(this)
fun MoonLakeEvent.callEventAsync(plugin: Plugin)
= plugin.runTaskAsync(Runnable { Bukkit.getServer().pluginManager.callEvent(this) })
fun Listener.registerEvent(plugin: Plugin)
= Bukkit.getServer().pluginManager.registerEvents(this, plugin)
fun MoonLakeListener.registerEvent(plugin: Plugin)
= Bukkit.getServer().pluginManager.registerEvents(this, plugin)
fun <T: Event> Class<out T>.registerEvent(listener: Listener, priority: EventPriority, executor: EventExecutor, plugin: Plugin, ignoreCancelled: Boolean = false)
= Bukkit.getServer().pluginManager.registerEvent(this, listener, priority, executor, plugin, ignoreCancelled)
fun <T: MoonLakeEvent> Class<out T>.registerEvent(listener: MoonLakeListener, priority: EventPriority, executor: EventExecutor, plugin: Plugin, ignoreCancelled: Boolean = false)
= Bukkit.getServer().pluginManager.registerEvent(this, listener, priority, executor, plugin, ignoreCancelled)
fun unregisterAll()
= HandlerList.unregisterAll()
fun Plugin.unregisterAll()
= HandlerList.unregisterAll(this)
fun Listener.unregisterAll()
= HandlerList.unregisterAll(this)
fun MoonLakeListener.unregisterAll()
= HandlerList.unregisterAll(this)
/** task function */
fun Plugin.runTask(task: Runnable): BukkitTask
= Bukkit.getScheduler().runTask(this, task)
fun Plugin.runTaskLater(task: Runnable, delay: Long): BukkitTask
= Bukkit.getScheduler().runTaskLater(this, task, delay)
fun Plugin.runTaskTimer(task: Runnable, delay: Long, period: Long): BukkitTask
= Bukkit.getScheduler().runTaskTimer(this, task, delay, period)
fun Plugin.runTaskAsync(task: Runnable): BukkitTask
= Bukkit.getScheduler().runTaskAsynchronously(this, task)
fun Plugin.runTaskLaterAsync(task: Runnable, delay: Long): BukkitTask
= Bukkit.getScheduler().runTaskLaterAsynchronously(this, task, delay)
fun Plugin.runTaskTimerAsync(task: Runnable, delay: Long, period: Long): BukkitTask
= Bukkit.getScheduler().runTaskTimerAsynchronously(this, task, delay, period)
fun Plugin.runTask(task: MoonLakeRunnable): BukkitTask
= task.runTask(this)
fun Plugin.runTaskLater(task: MoonLakeRunnable, delay: Long): BukkitTask
= task.runTaskLater(this, delay)
fun Plugin.runTaskTimer(task: MoonLakeRunnable, delay: Long, period: Long): BukkitTask
= task.runTaskTimer(this, delay, period)
fun Plugin.runTaskAsync(task: MoonLakeRunnable): BukkitTask
= task.runTaskAsynchronously(this)
fun Plugin.runTaskLaterAsync(task: MoonLakeRunnable, delay: Long): BukkitTask
= task.runTaskLaterAsynchronously(this, delay)
fun Plugin.runTaskTimerAsync(task: MoonLakeRunnable, delay: Long, period: Long): BukkitTask
= task.runTaskTimerAsynchronously(this, delay, period)
fun Plugin.runTask(task: () -> Unit): BukkitTask
= Bukkit.getScheduler().runTask(this, task)
fun Plugin.runTaskLater(task: () -> Unit, delay: Long): BukkitTask
= Bukkit.getScheduler().runTaskLater(this, task, delay)
fun Plugin.runTaskTimer(task: () -> Unit, delay: Long, period: Long): BukkitTask
= Bukkit.getScheduler().runTaskTimer(this, task, delay, period)
fun Plugin.runTaskAsync(task: () -> Unit): BukkitTask
= Bukkit.getScheduler().runTaskAsynchronously(this, task)
fun Plugin.runTaskLaterAsync(task: () -> Unit, delay: Long): BukkitTask
= Bukkit.getScheduler().runTaskLaterAsynchronously(this, task, delay)
fun Plugin.runTaskTimerAsync(task: () -> Unit, delay: Long, period: Long): BukkitTask
= Bukkit.getScheduler().runTaskTimerAsynchronously(this, task, delay, period)
fun <T> Plugin.callTaskSyncMethod(callback: Callable<T>): Future<T>
= Bukkit.getScheduler().callSyncMethod(this, callback)
fun <T> Plugin.callTaskSyncMethod(callback: () -> T): Future<T>
= Bukkit.getScheduler().callSyncMethod(this, callback.toCallable())
fun <T> Plugin.callTaskSyncFuture(callback: Callable<T>): CompletableFuture<T>
= callTaskFuture0(callback)
fun <T> Plugin.callTaskSyncFuture(callback: () -> T): CompletableFuture<T>
= callTaskFuture0(callback.toCallable())
fun <T> Plugin.callTaskAsyncFuture(callback: Callable<T>): CompletableFuture<T>
= callTaskFuture0(callback, -1, true)
fun <T> Plugin.callTaskAsyncFuture(callback: () -> T): CompletableFuture<T>
= callTaskFuture0(callback.toCallable(), -1, true)
fun <T> Plugin.callTaskLaterSyncFuture(delay: Long, callback: Callable<T>): CompletableFuture<T>
= callTaskFuture0(callback, delay, false)
fun <T> Plugin.callTaskLaterSyncFuture(delay: Long, callback: () -> T): CompletableFuture<T>
= callTaskFuture0(callback.toCallable(), delay, false)
fun <T> Plugin.callTaskLaterAsyncFuture(delay: Long, callback: Callable<T>): CompletableFuture<T>
= callTaskFuture0(callback, delay, true)
fun <T> Plugin.callTaskLaterAsyncFuture(delay: Long, callback: () -> T): CompletableFuture<T>
= callTaskFuture0(callback.toCallable(), delay, true)
private fun <T> Plugin.callTaskFuture0(callback: Callable<T>, delay: Long = -1, async: Boolean = false): CompletableFuture<T> {
val future = CompletableFuture<T>()
val futureTask = FutureTask(callback)
val runnable = Runnable {
try {
futureTask.run()
future.complete(futureTask.get())
} catch(e: Exception) {
future.completeExceptionally(e)
}
}
when(delay <= 0) {
true -> {
if(async) runTaskAsync(runnable)
else runnable.run() // Blocking of synchronization futures
}
else -> {
if(async) runTaskLaterAsync(runnable, delay)
else runTaskLater(runnable, delay)
}
}
return future
}
fun cancelTask(task: BukkitTask?)
= task?.cancel()
fun cancelTask(taskId: Int)
= Bukkit.getScheduler().cancelTask(taskId)
fun Plugin.cancelTasks()
= Bukkit.getScheduler().cancelTasks(this)
fun cancelAllTasks()
= Bukkit.getScheduler().cancelAllTasks()
/** location target function */
fun Location.isInFront(target: Location): Boolean {
val facing = direction
val relative = target.subtract(this).toVector().normalize()
return facing.dot(relative) >= .0
}
fun Location.isInFront(target: Location, angle: Double): Boolean {
if (angle <= .0) return false
if (angle >= 360.0) return true
val dotTarget = Math.cos(angle)
val facing = direction
val relative = target.subtract(this).toVector().normalize()
return facing.dot(relative) >= dotTarget
}
@JvmOverloads
fun <T: LivingEntity> Location.getLivingTargets(clazz: Class<T>, range: Double, tolerance: Double = 4.0): List<T> {
val entityList = world.getNearbyEntities(this, range, range, range)
val facing = direction
val fLengthSq = facing.lengthSquared()
return entityList.filter { clazz.isInstance(it) && [email protected](it.location) }.map { clazz.cast(it) }.filter {
val relative = it.location.subtract(this).toVector()
val dot = relative.dot(facing)
val rLengthSq = relative.lengthSquared()
val cosSquared = dot * dot / (rLengthSq * fLengthSq)
val sinSquared = 1.0 - cosSquared
val dSquared = rLengthSq * sinSquared
dSquared < tolerance
}.toList()
}
@JvmOverloads
fun Location.getLivingTargets(range: Double, tolerance: Double = 4.0): List<LivingEntity>
= getLivingTargets(LivingEntity::class.java, range, tolerance)
@JvmOverloads
fun <T: LivingEntity> Location.getLivingTarget(clazz: Class<T>, range: Double, tolerance: Double = 4.0): T? {
val targets = getLivingTargets(clazz, range, tolerance)
if(targets.isEmpty()) return null
var target = targets.first()
var minDistance = target.location.distanceSquared(this)
targets.forEach {
val distance = it.location.distanceSquared(this)
if(distance < minDistance) {
minDistance = distance
target = it
}
}
return target
}
/** target function */
fun Entity.isInFront(target: Entity): Boolean
= location.isInFront(target.location)
fun Entity.isInFront(target: Entity, angle: Double): Boolean
= location.isInFront(target.location, angle)
fun Entity.isBehind(target: Entity, angle: Double): Boolean
= !isInFront(target, angle)
@JvmOverloads
fun <T: LivingEntity> LivingEntity.getLivingTargets(clazz: Class<T>, range: Double, tolerance: Double = 4.0): List<T>
= location.getLivingTargets(clazz, range, tolerance)
@JvmOverloads
fun LivingEntity.getLivingTargets(range: Double, tolerance: Double = 4.0): List<LivingEntity>
= getLivingTargets(LivingEntity::class.java, range, tolerance)
@JvmOverloads
fun <T: LivingEntity> LivingEntity.getLivingTarget(clazz: Class<T>, range: Double, tolerance: Double = 4.0): T?
= location.getLivingTarget(clazz, range, tolerance)
@JvmOverloads
fun LivingEntity.getLivingTarget(range: Double, tolerance: Double = 4.0): LivingEntity?
= getLivingTarget(LivingEntity::class.java, range, tolerance)
@JvmOverloads
fun <T: LivingEntity> MoonLakePlayer.getLivingTargets(clazz: Class<T>, range: Double, tolerance: Double = 4.0): List<T>
= bukkitPlayer.getLivingTargets(clazz, range, tolerance)
@JvmOverloads
fun MoonLakePlayer.getLivingTargets(range: Double, tolerance: Double = 4.0): List<LivingEntity>
= bukkitPlayer.getLivingTargets(range, tolerance)
@JvmOverloads
fun <T: LivingEntity> MoonLakePlayer.getLivingTarget(clazz: Class<T>, range: Double, tolerance: Double = 4.0): T?
= bukkitPlayer.getLivingTarget(clazz, range, tolerance)
@JvmOverloads
fun MoonLakePlayer.getLivingTarget(range: Double, tolerance: Double = 4.0): LivingEntity?
= bukkitPlayer.getLivingTarget(range, tolerance)
/** region function */
fun World.createCuboidRegion(pos1: Location, pos2: Location): RegionCuboid
= RegionCuboid(this, pos1.toRegionVector(), pos2.toRegionVector())
fun World.createCuboidRegion(pos1: RegionVector, pos2: RegionVector): RegionCuboid
= RegionCuboid(this, pos1, pos2)
fun Region.createWorldBorder(): WorldBorder {
val worldBorder = world.worldBorder
worldBorder.setSize(length.toDouble(), 0L)
worldBorder.center = center.toLocation(world)
return worldBorder
}
/** anvil window function */
fun Plugin.newAnvilWindow(): AnvilWindow
= AnvilWindows.create(this)
/** item builder function */
fun ItemStack.newItemBuilder(): ItemBuilder
= ItemBuilder.of(this)
@JvmOverloads
fun Material.newItemBuilder(amount: Int = 1, durability: Int = 0): ItemBuilder
= ItemBuilder.of(this, amount, durability)
@JvmOverloads
fun Material.newItemStack(amount: Int = 1, durability: Int = 0): ItemStack
= ItemStack(this, amount, durability.toShort())
fun ItemStack?.isAir(): Boolean
= this == null || this.type == Material.AIR
fun ItemStack?.isEmpty(): Boolean
= this == null || this.type == Material.AIR || !hasItemMeta()
fun ItemStack.givePlayer(player: Player): Boolean
= player.inventory.addItem(this).isEmpty() // the result is empty, indicating the success
fun ItemStack.givePlayer(player: MoonLakePlayer): Boolean
= givePlayer(player.bukkitPlayer)
fun ItemStack.dropLocation(location: Location): Item
= location.world.dropItemNaturally(location, this)
/** nbt function */
@JvmOverloads
fun ofNBTCompound(name: String = ""): NBTCompound
= NBTFactory.ofCompound(name)
@JvmOverloads
fun <T> ofNBTList(name: String = ""): NBTList<T>
= NBTFactory.ofList(name)
@JvmOverloads
fun Material.createItemStack(amount: Int = 1, durability: Int = 0, tag: NBTCompound? = null): ItemStack
= NBTFactory.createStack(this, amount, durability, tag)
inline fun ItemStack.readTag(block: (tag: NBTCompound?) -> Unit): ItemStack
{ block(NBTFactory.readStackTag(this)); return this; }
inline fun <R> ItemStack.readTagLet(block: (tag: NBTCompound?) -> R): R
= block(NBTFactory.readStackTag(this))
inline fun ItemStack.readTagSafe(block: (tag: NBTCompound) -> Unit): ItemStack
{ block(NBTFactory.readStackTagSafe(this)); return this; }
inline fun <R> ItemStack.readTagSafeLet(block: (tag: NBTCompound) -> R): R
= block(NBTFactory.readStackTagSafe(this))
fun ItemStack.writeTag(tag: NBTCompound?): ItemStack
= NBTFactory.writeStackTag(this, tag)
inline fun <T: Entity> T.readTag(block: (tag: NBTCompound) -> Unit): T
{ block(NBTFactory.readEntityTag(this)); return this; }
inline fun <T: Entity, R> T.readTagLet(block: (tag: NBTCompound) -> R): R
= block(NBTFactory.readEntityTag(this))
fun <T: Entity> T.writeTag(tag: NBTCompound): T
= NBTFactory.writeEntityTag(this, tag)
/** depend plugin function */
@Throws(DependPluginException::class)
inline fun <T: DependPlugin> Class<T>.useDepend(block: (depend: T) -> Unit): T
= DependPlugins.of(this).also(block)
@Throws(DependPluginException::class)
inline fun <T: DependPlugin, R> Class<T>.useDependLet(block: (depend: T) -> R): R
= block(DependPlugins.of(this))
inline fun <T: DependPlugin> Class<T>.useDependSafe(block: (depend: T?) -> Unit): T?
= DependPlugins.ofSafe(this).also(block)
inline fun <T: DependPlugin, R> Class<T>.useDependSafeLet(block: (depend: T?) -> R): R
= block(DependPlugins.ofSafe(this))
/** entity function */
fun <T: Entity> Class<T>.spawn(location: Location): T
= location.world.spawn(location, this)
inline fun <T: Entity> Class<T>.spawn(location: Location, block: T.() -> Unit): T
= spawn(location).also(block)
inline fun <T: Entity, R> Class<T>.spawnLet(location: Location, block: (T) -> R): R
= spawn(location).let(block)
/** packet function */
/**
* @see [PacketListeners.registerListener]
*/
@Throws(UnsupportedOperationException::class)
fun PacketListener.register(): Boolean
= PacketListeners.registerListener(this)
/**
* @see [PacketListeners.unregisterListener]
*/
@Throws(UnsupportedOperationException::class)
fun PacketListener.unregister(): Boolean
= PacketListeners.unregisterListener(this)
@JvmOverloads
fun Player.sendPacketChat(raw: String, action: ChatAction = ChatAction.CHAT)
= sendPacketChat(ChatSerializer.fromRaw(raw), action)
@JvmOverloads
fun Player.sendPacketChat(component: ChatComponent, action: ChatAction = ChatAction.CHAT)
= PacketOutChat(component, action).send(this)
@JvmOverloads
fun Player.sendPacketTitle(title: String, subTitle: String? = null, fadeIn: Int = 10, stay: Int = 70, fadeOut: Int = 20)
= sendPacketTitle(ChatSerializer.fromRaw(title), if(subTitle == null) null else ChatSerializer.fromRaw(subTitle), fadeIn, stay, fadeOut)
@JvmOverloads
fun Player.sendPacketTitle(title: ChatComponent, subTitle: ChatComponent? = null, fadeIn: Int = 10, stay: Int = 70, fadeOut: Int = 20) {
var packet = PacketOutTitle(fadeIn, stay, fadeOut)
packet.send(this)
if(subTitle != null) {
packet = PacketOutTitle(PacketOutTitle.Action.SUBTITLE, subTitle)
packet.send(this)
}
packet = PacketOutTitle(PacketOutTitle.Action.TITLE, title)
packet.send(this)
}
fun Player.sendPacketTitleReset()
= PacketOutTitle(PacketOutTitle.Action.RESET, null).send(this)
| gpl-3.0 | eb535f0ca0f4d3ed25a9717406dcae32 | 33.210345 | 177 | 0.707153 | 3.889063 | false | false | false | false |
AshishKayastha/Movie-Guide | app/src/main/kotlin/com/ashish/movieguide/ui/people/detail/PersonDetailPresenter.kt | 1 | 2029 | package com.ashish.movieguide.ui.people.detail
import com.ashish.movieguide.R
import com.ashish.movieguide.data.interactors.PeopleInteractor
import com.ashish.movieguide.data.models.FullDetailContent
import com.ashish.movieguide.data.models.PersonDetail
import com.ashish.movieguide.di.scopes.ActivityScope
import com.ashish.movieguide.ui.base.detail.BaseDetailPresenter
import com.ashish.movieguide.ui.base.detail.BaseDetailView
import com.ashish.movieguide.utils.extensions.convertListToCommaSeparatedText
import com.ashish.movieguide.utils.extensions.getFormattedMediumDate
import com.ashish.movieguide.utils.schedulers.BaseSchedulerProvider
import java.util.ArrayList
import javax.inject.Inject
/**
* Created by Ashish on Jan 04.
*/
@ActivityScope
class PersonDetailPresenter @Inject constructor(
private val peopleInteractor: PeopleInteractor,
schedulerProvider: BaseSchedulerProvider
) : BaseDetailPresenter<PersonDetail, BaseDetailView<PersonDetail>>(schedulerProvider) {
override fun getDetailContent(id: Long) = peopleInteractor.getFullPersonDetail(id)
override fun getContentList(fullDetailContent: FullDetailContent<PersonDetail>): List<String> {
val contentList = ArrayList<String>()
fullDetailContent.detailContent?.apply {
contentList.apply {
add(biography ?: "")
add(birthday.getFormattedMediumDate())
add(placeOfBirth ?: "")
add(deathday.getFormattedMediumDate())
add(fullDetailContent.omdbDetail?.Awards ?: "")
add(alsoKnownAs.convertListToCommaSeparatedText { it })
}
}
return contentList
}
override fun getBackdropImages(detailContent: PersonDetail) = detailContent.images?.profiles
override fun getPosterImages(detailContent: PersonDetail) = null
override fun getCredits(detailContent: PersonDetail) = detailContent.combinedCredits
override fun getErrorMessageId() = R.string.error_load_person_detail
} | apache-2.0 | 51d183dd7a6ace865d3cfea8567e35a8 | 39.6 | 99 | 0.75653 | 4.819477 | false | false | false | false |
AdamLuisSean/template-android | AndroidBottomView/app/src/main/kotlin/io/shtanko/androidbottomview/BottomView+Extentions.kt | 1 | 1050 | package io.shtanko.androidbottomview
import android.support.design.internal.BottomNavigationItemView
import android.support.design.internal.BottomNavigationMenuView
import android.support.design.widget.BottomNavigationView
import android.util.Log
fun removeShiftMode(view: BottomNavigationView) {
val menuView = view.getChildAt(0) as BottomNavigationMenuView
try {
val shiftingMode = menuView.javaClass.getDeclaredField("mShiftingMode")
shiftingMode.isAccessible = true
shiftingMode.setBoolean(menuView, false)
shiftingMode.isAccessible = false
for (i in 0..menuView.childCount - 1) {
val item = menuView.getChildAt(i) as BottomNavigationItemView
item.setShiftingMode(false)
// set once again checked value, so view will be updated
item.setChecked(item.itemData.isChecked)
}
} catch (e: NoSuchFieldException) {
Log.e("ERROR NO SUCH FIELD", "Unable to get shift mode field")
} catch (e: IllegalAccessException) {
Log.e("ERROR ILLEGAL ALG", "Unable to change value of shift mode")
}
} | apache-2.0 | d20385df92a7bffcdf3b89d599649047 | 39.423077 | 75 | 0.760952 | 4.320988 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/columnviewholder/ColumnViewHolderReactions.kt | 1 | 4354 | package jp.juggler.subwaytooter.columnviewholder
import androidx.appcompat.widget.AppCompatButton
import androidx.core.content.ContextCompat
import com.google.android.flexbox.FlexboxLayout
import jp.juggler.subwaytooter.ActMain
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.api.entity.TootReaction
import jp.juggler.subwaytooter.column.getContentColor
import jp.juggler.subwaytooter.dialog.launchEmojiPicker
import jp.juggler.subwaytooter.emoji.CustomEmoji
import jp.juggler.subwaytooter.emoji.UnicodeEmoji
import jp.juggler.subwaytooter.util.DecodeOptions
import jp.juggler.subwaytooter.util.NetworkEmojiInvalidator
import jp.juggler.subwaytooter.util.minWidthCompat
import jp.juggler.subwaytooter.util.startMargin
import jp.juggler.util.launchAndShowError
import org.jetbrains.anko.allCaps
fun ColumnViewHolder.addEmojiQuery(reaction: TootReaction? = null) {
val column = this.column ?: return
if (reaction == null) {
launchEmojiPicker(activity, column.accessInfo, closeOnSelected = true) { emoji, _ ->
val newReaction = when (emoji) {
is UnicodeEmoji -> TootReaction(name = emoji.unifiedCode)
is CustomEmoji -> TootReaction(
name = emoji.shortcode,
url = emoji.url,
staticUrl = emoji.staticUrl
)
}
addEmojiQuery(newReaction)
}
return
}
val list = TootReaction.decodeEmojiQuery(column.searchQuery).toMutableList()
list.add(reaction)
column.searchQuery = TootReaction.encodeEmojiQuery(list)
updateReactionQueryView()
activity.appState.saveColumnList()
}
private fun ColumnViewHolder.removeEmojiQuery(target: TootReaction?) {
target ?: return
val list = TootReaction.decodeEmojiQuery(column?.searchQuery).filter { it.name != target.name }
column?.searchQuery = TootReaction.encodeEmojiQuery(list)
updateReactionQueryView()
activity.appState.saveColumnList()
}
fun ColumnViewHolder.updateReactionQueryView() {
val column = this.column ?: return
val act = this.activity // not Button(View).getActivity()
act.launchAndShowError {
flEmoji.removeAllViews()
for (invalidator in emojiQueryInvalidatorList) {
invalidator.register(null)
}
emojiQueryInvalidatorList.clear()
val options = DecodeOptions(
act,
column.accessInfo,
decodeEmoji = true,
enlargeEmoji = 1.5f,
enlargeCustomEmoji = 1.5f
)
val buttonHeight = ActMain.boostButtonSize
val marginBetween = (buttonHeight.toFloat() * 0.05f + 0.5f).toInt()
val paddingH = (buttonHeight.toFloat() * 0.1f + 0.5f).toInt()
val paddingV = (buttonHeight.toFloat() * 0.1f + 0.5f).toInt()
val contentColor = column.getContentColor()
TootReaction.decodeEmojiQuery(column.searchQuery).forEachIndexed { index, reaction ->
val ssb = reaction.toSpannableStringBuilder(options, status = null)
val b = AppCompatButton(activity).apply {
layoutParams = FlexboxLayout.LayoutParams(
FlexboxLayout.LayoutParams.WRAP_CONTENT,
buttonHeight
).apply {
if (index > 0) startMargin = marginBetween
}
minWidthCompat = buttonHeight
background = ContextCompat.getDrawable(act, R.drawable.btn_bg_transparent_round6dp)
setTextColor(contentColor)
setPadding(paddingH, paddingV, paddingH, paddingV)
text = ssb
allCaps = false
tag = reaction
setOnLongClickListener {
removeEmojiQuery(it.tag as? TootReaction)
true
}
// カスタム絵文字の場合、アニメーション等のコールバックを処理する必要がある
val invalidator = NetworkEmojiInvalidator(act.handler, this)
invalidator.register(ssb)
emojiQueryInvalidatorList.add(invalidator)
}
flEmoji.addView(b)
}
}
}
| apache-2.0 | d42d0239a09966c5ec7faf0f6c8a7148 | 35.893805 | 99 | 0.634283 | 4.695175 | false | false | false | false |
flesire/ontrack | ontrack-extension-general/src/main/java/net/nemerosa/ontrack/extension/general/MetaInfoPropertyType.kt | 1 | 5774 | package net.nemerosa.ontrack.extension.general
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.extension.support.AbstractPropertyType
import net.nemerosa.ontrack.model.form.Form
import net.nemerosa.ontrack.model.form.MultiForm
import net.nemerosa.ontrack.model.form.Text
import net.nemerosa.ontrack.model.security.ProjectConfig
import net.nemerosa.ontrack.model.security.SecurityService
import net.nemerosa.ontrack.model.structure.ProjectEntity
import net.nemerosa.ontrack.model.structure.ProjectEntityType
import net.nemerosa.ontrack.model.structure.PropertySearchArguments
import org.apache.commons.lang3.StringUtils
import org.springframework.stereotype.Component
import java.util.*
import java.util.function.Function
@Component
class MetaInfoPropertyType(
extensionFeature: GeneralExtensionFeature
) : AbstractPropertyType<MetaInfoProperty>(extensionFeature) {
override fun getName(): String = "Meta information"
override fun getDescription(): String = "List of meta information properties"
override fun getSupportedEntityTypes(): Set<ProjectEntityType> = EnumSet.allOf(ProjectEntityType::class.java)
override fun canEdit(entity: ProjectEntity, securityService: SecurityService): Boolean {
return securityService.isProjectFunctionGranted(entity, ProjectConfig::class.java)
}
override fun canView(entity: ProjectEntity, securityService: SecurityService): Boolean = true
override fun getEditionForm(entity: ProjectEntity, value: MetaInfoProperty?): Form = Form.create()
.with(
MultiForm.of(
"items",
Form.create()
.name()
.with(
Text.of("value").label("Value")
)
.with(
Text.of("link").label("Link").optional()
)
.with(
Text.of("category").label("Category").optional()
)
)
.label("Items")
.value(if (value != null) value.items else emptyList<Any>())
)
override fun fromClient(node: JsonNode): MetaInfoProperty {
return fromStorage(node)
}
override fun fromStorage(node: JsonNode): MetaInfoProperty {
return AbstractPropertyType.parse(node, MetaInfoProperty::class.java)
}
override fun getSearchKey(value: MetaInfoProperty): String {
return value.items
.joinToString(separator = ";") {
"${it.name}:${it.value}"
}
}
override fun containsValue(property: MetaInfoProperty, propertyValue: String): Boolean {
val pos = StringUtils.indexOf(propertyValue, ":")
return if (pos > 0) {
val value = StringUtils.substringAfter(propertyValue, ":")
val name = StringUtils.substringBefore(propertyValue, ":")
property.matchNameValue(name, value)
} else {
false
}
}
override fun replaceValue(value: MetaInfoProperty, replacementFunction: Function<String, String>): MetaInfoProperty {
return MetaInfoProperty(
value.items
.map { item ->
MetaInfoPropertyItem(
item.name,
replacementFunction.apply(item.value),
item.link?.apply { replacementFunction.apply(this) },
item.category?.apply { replacementFunction.apply(this) }
)
}
)
}
override fun getSearchArguments(token: String): PropertySearchArguments? {
val name: String?
val value: String?
if (token.indexOf(":") >= 1) {
name = token.substringBefore(":").trim()
value = token.substringAfter(":").trimStart()
} else {
name = null
value = token
}
return if (name.isNullOrBlank()) {
if (value.isNullOrBlank()) {
// Empty
null
} else {
// Value only
PropertySearchArguments(
jsonContext = "jsonb_array_elements(pp.json->'items') as item",
jsonCriteria = "item->>'value' ilike :value",
criteriaParams = mapOf(
"value" to value.toValuePattern()
)
)
}
} else if (value.isNullOrBlank()) {
// Name only
PropertySearchArguments(
jsonContext = "jsonb_array_elements(pp.json->'items') as item",
jsonCriteria = "item->>'name' = :name",
criteriaParams = mapOf(
"name" to name
)
)
} else {
// Name & value
PropertySearchArguments(
jsonContext = "jsonb_array_elements(pp.json->'items') as item",
jsonCriteria = "item->>'name' = :name and item->>'value' ilike :value",
criteriaParams = mapOf(
"name" to name,
"value" to value.toValuePattern()
)
)
}
}
private fun String.toValuePattern(): String {
return this.replace("*", "%")
}
}
| mit | b05799ad6c8ac01668320942057f077f | 39.097222 | 121 | 0.530828 | 5.478178 | false | false | false | false |
madisp/lite-android | lite-android/src/main/kotlin/pink/madis/gradle/liteandroid/sdk.kt | 1 | 2617 | package pink.madis.gradle.liteandroid
import org.apache.tools.ant.taskdefs.condition.Os
import org.gradle.api.Project
import java.io.File
import java.io.FileNotFoundException
import java.nio.charset.StandardCharsets
import java.util.Properties
fun ensureSdk(project: Project): Sdk {
val location = findSdk(project)
// we're looking for the readme and platforms, if those exist then we're already good to go
if (!location.resolve("tools").exists() || !location.resolve("platforms").exists()) {
throw FileNotFoundException(
"lite-android: No valid SDK location found at '$location'.\nPlease ensure a correct " +
"SDK location is defined through the sdk.dir property in local.properties file or the ANDROID_HOME environment " +
"variable")
}
return Sdk(location)
}
fun findSdk(project: Project): File {
var sdkDir: String? = null
// use local.properties first
val localProps = project.rootProject.file("local.properties")
if (localProps.exists()) {
val props = Properties()
localProps.reader(StandardCharsets.UTF_8).use {
props.load(it)
}
sdkDir = props.getProperty("sdk.dir")
}
// if that fails, try to look at ANDROID_HOME
sdkDir = sdkDir ?: System.getenv("ANDROID_HOME")
if (sdkDir != null) {
return File(sdkDir)
}
throw IllegalStateException(
"lite-android: SDK location not defined.\nPlease create a local.properties file with sdk.dir set or set " +
"the ANDROID_HOME environment variable.")
}
class Sdk(baseDir: File) {
private val platforms = baseDir.resolve("platforms")
private val extras = baseDir.resolve("extras")
private val buildtools = baseDir.resolve("build-tools")
private val repos = listOf(
extras.resolve("m2repository"),
extras.resolve("android").resolve("m2repository"),
extras.resolve("google").resolve("m2repository")
)
fun androidJar(version: String): File {
return platforms
.resolve(version)
.resolve("android.jar")
.ensure("The android.jar file for platform '$version' was not found. Either it's a typo or the SDK is missing it.")
}
fun dxJar(buildToolsVersion: String): File {
return buildtools
.resolve(buildToolsVersion)
.resolve("lib")
.resolve("dx.jar")
.ensure("The dx jar for build tools '$buildToolsVersion' could not be found. Please make sure that the SDK is complete.")
}
fun extraRepos(): List<File> = repos.filter { it.exists() && it.isDirectory }
}
fun File.ensure(message: String): File {
if (exists()) {
return this
}
throw FileNotFoundException(message)
} | mit | 5fb2c5a6a1bfa1e36b62a97e8d7f37c2 | 31.725 | 129 | 0.695453 | 4.019969 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/nbt/tags/TagEnd.kt | 1 | 569 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.tags
import java.io.DataOutputStream
object TagEnd : NbtTag {
override val payloadSize = 0
override val typeId = NbtTypeId.END
override fun write(stream: DataOutputStream) {}
override fun toString() = toString(StringBuilder(), 0, WriterState.COMPOUND).toString()
override fun toString(sb: StringBuilder, indentLevel: Int, writerState: WriterState) = sb
override fun copy() = this
}
| mit | c209b00d022260d6233fcb42c564cd55 | 20.884615 | 93 | 0.710018 | 4.035461 | false | false | false | false |
google/intellij-community | python/src/com/jetbrains/python/run/PythonScripts.kt | 2 | 12282 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("PythonScripts")
package com.jetbrains.python.run
import com.intellij.execution.ExecutionException
import com.intellij.execution.Platform
import com.intellij.execution.configurations.ParametersList
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.process.LocalPtyOptions
import com.intellij.execution.process.ProcessOutput
import com.intellij.execution.target.*
import com.intellij.execution.target.TargetEnvironment.TargetPath
import com.intellij.execution.target.TargetEnvironment.UploadRoot
import com.intellij.execution.target.local.LocalTargetPtyOptions
import com.intellij.execution.target.value.*
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.remote.RemoteSdkPropertiesPaths
import com.intellij.util.io.isAncestor
import com.jetbrains.python.HelperPackage
import com.jetbrains.python.PythonHelpersLocator
import com.jetbrains.python.debugger.PyDebugRunner
import com.jetbrains.python.packaging.PyExecutionException
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.run.target.HelpersAwareTargetEnvironmentRequest
import com.jetbrains.python.sdk.PythonSdkType
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor
import com.jetbrains.python.sdk.targetAdditionalData
import com.jetbrains.python.target.PyTargetAwareAdditionalData.Companion.pathsAddedByUser
import java.nio.file.Path
private val LOG = Logger.getInstance("#com.jetbrains.python.run.PythonScripts")
fun PythonExecution.buildTargetedCommandLine(targetEnvironment: TargetEnvironment,
sdk: Sdk?,
interpreterParameters: List<String>,
isUsePty: Boolean = false): TargetedCommandLine {
val commandLineBuilder = TargetedCommandLineBuilder(targetEnvironment.request)
workingDir?.apply(targetEnvironment)?.let { commandLineBuilder.setWorkingDirectory(it) }
charset?.let { commandLineBuilder.setCharset(it) }
val interpreterPath = getInterpreterPath(sdk)
val platform = targetEnvironment.targetPlatform.platform
if (!interpreterPath.isNullOrEmpty()) {
commandLineBuilder.setExePath(platform.toSystemDependentName(interpreterPath))
}
commandLineBuilder.addParameters(interpreterParameters)
when (this) {
is PythonScriptExecution -> pythonScriptPath?.let { commandLineBuilder.addParameter(it.apply(targetEnvironment)) }
?: throw IllegalArgumentException("Python script path must be set")
is PythonModuleExecution -> moduleName?.let { commandLineBuilder.addParameters(listOf("-m", moduleName)) }
?: throw IllegalArgumentException("Python module name must be set")
}
for (parameter in parameters) {
commandLineBuilder.addParameter(parameter.apply(targetEnvironment))
}
sdk?.targetAdditionalData?.pathsAddedByUser?.map { it.value }?.forEach { path ->
appendToPythonPath(constant(path), targetEnvironment.targetPlatform)
}
for ((name, value) in envs) {
commandLineBuilder.addEnvironmentVariable(name, value.apply(targetEnvironment))
}
val environmentVariablesForVirtualenv = mutableMapOf<String, String>()
// TODO [Targets API] It would be cool to activate environment variables for any type of target
sdk?.let { PythonSdkType.patchEnvironmentVariablesForVirtualenv(environmentVariablesForVirtualenv, it) }
// TODO [Targets API] [major] PATH env for virtualenv should extend existing PATH env
environmentVariablesForVirtualenv.forEach { (name, value) -> commandLineBuilder.addEnvironmentVariable(name, value) }
// TODO [Targets API] [major] `PythonSdkFlavor` should be taken into account to pass (at least) "IRONPYTHONPATH" or "JYTHONPATH"
// environment variables for corresponding interpreters
if (isUsePty) {
commandLineBuilder.ptyOptions = LocalTargetPtyOptions(LocalPtyOptions.DEFAULT)
}
return commandLineBuilder.build()
}
/**
* Returns the path to Python interpreter executable. The path is the path on
* the target environment.
*/
fun getInterpreterPath(sdk: Sdk?): String? {
if (sdk == null) return null
// `RemoteSdkPropertiesPaths` suits both `PyRemoteSdkAdditionalDataBase` and `PyTargetAwareAdditionalData`
return sdk.sdkAdditionalData?.let { (it as? RemoteSdkPropertiesPaths)?.interpreterPath } ?: sdk.homePath
}
data class Upload(val localPath: String, val targetPath: TargetEnvironmentFunction<String>)
private fun resolveUploadPath(localPath: String, uploads: Iterable<Upload>): TargetEnvironmentFunction<String> {
val localFileSeparator = Platform.current().fileSeparator
val matchUploads = uploads.mapNotNull { upload ->
if (FileUtil.isAncestor(upload.localPath, localPath, false)) {
FileUtil.getRelativePath(upload.localPath, localPath, localFileSeparator)?.let { upload to it }
}
else {
null
}
}
if (matchUploads.size > 1) {
LOG.warn("Several uploads matches the local path '$localPath': $matchUploads")
}
val (upload, localRelativePath) = matchUploads.firstOrNull()
?: throw IllegalStateException("Failed to find uploads for the local path '$localPath'")
return upload.targetPath.getRelativeTargetPath(localRelativePath)
}
fun prepareHelperScriptExecution(helperPackage: HelperPackage,
helpersAwareTargetRequest: HelpersAwareTargetEnvironmentRequest): PythonScriptExecution =
PythonScriptExecution().apply {
val uploads = applyHelperPackageToPythonPath(helperPackage, helpersAwareTargetRequest)
pythonScriptPath = resolveUploadPath(helperPackage.asParamString(), uploads)
}
private const val PYTHONPATH_ENV = "PYTHONPATH"
/**
* Requests the upload of PyCharm helpers root directory to the target.
*/
fun PythonExecution.applyHelperPackageToPythonPath(helperPackage: HelperPackage,
helpersAwareTargetRequest: HelpersAwareTargetEnvironmentRequest): Iterable<Upload> {
return applyHelperPackageToPythonPath(helperPackage.pythonPathEntries, helpersAwareTargetRequest)
}
fun PythonExecution.applyHelperPackageToPythonPath(pythonPathEntries: List<String>,
helpersAwareTargetRequest: HelpersAwareTargetEnvironmentRequest): Iterable<Upload> {
val localHelpersRootPath = PythonHelpersLocator.getHelpersRoot().absolutePath
val targetPlatform = helpersAwareTargetRequest.targetEnvironmentRequest.targetPlatform
val targetUploadPath = helpersAwareTargetRequest.preparePyCharmHelpers()
val targetPathSeparator = targetPlatform.platform.pathSeparator
val uploads = pythonPathEntries.map {
// TODO [Targets API] Simplify the paths resolution
val relativePath = FileUtil.getRelativePath(localHelpersRootPath, it, Platform.current().fileSeparator)
?: throw IllegalStateException("Helpers PYTHONPATH entry '$it' cannot be resolved" +
" against the root path of PyCharm helpers '$localHelpersRootPath'")
Upload(it, targetUploadPath.getRelativeTargetPath(relativePath))
}
val pythonPathEntriesOnTarget = uploads.map { it.targetPath }
val pythonPathValue = pythonPathEntriesOnTarget.joinToStringFunction(separator = targetPathSeparator.toString())
appendToPythonPath(pythonPathValue, targetPlatform)
return uploads
}
/**
* Suits for coverage and profiler scripts.
*/
fun PythonExecution.addPythonScriptAsParameter(targetScript: PythonExecution) {
when (targetScript) {
is PythonScriptExecution -> targetScript.pythonScriptPath?.let { pythonScriptPath -> addParameter(pythonScriptPath) }
?: throw IllegalArgumentException("Python script path must be set")
is PythonModuleExecution -> targetScript.moduleName?.let { moduleName -> addParameters("-m", moduleName) }
?: throw IllegalArgumentException("Python module name must be set")
}
}
fun PythonExecution.addParametersString(parametersString: String) {
ParametersList.parse(parametersString).forEach { parameter -> addParameter(parameter) }
}
private fun PythonExecution.appendToPythonPath(value: TargetEnvironmentFunction<String>, targetPlatform: TargetPlatform) {
appendToPythonPath(envs, value, targetPlatform)
}
fun appendToPythonPath(envs: MutableMap<String, TargetEnvironmentFunction<String>>,
value: TargetEnvironmentFunction<String>,
targetPlatform: TargetPlatform) {
envs.merge(PYTHONPATH_ENV, value) { whole, suffix ->
listOf(whole, suffix).joinToPathValue(targetPlatform)
}
}
fun appendToPythonPath(envs: MutableMap<String, TargetEnvironmentFunction<String>>,
paths: Collection<TargetEnvironmentFunction<String>>,
targetPlatform: TargetPlatform) {
val value = paths.joinToPathValue(targetPlatform)
envs.merge(PYTHONPATH_ENV, value) { whole, suffix ->
listOf(whole, suffix).joinToPathValue(targetPlatform)
}
}
/**
* Joins the provided paths collection to single [TargetValue] using target
* platform's path separator.
*
* The result is applicable for `PYTHONPATH` and `PATH` environment variables.
*/
fun Collection<TargetEnvironmentFunction<String>>.joinToPathValue(targetPlatform: TargetPlatform): TargetEnvironmentFunction<String> =
this.joinToStringFunction(separator = targetPlatform.platform.pathSeparator.toString())
// TODO: Make this code python-agnostic, get red of path hardcode
fun PythonExecution.extendEnvs(additionalEnvs: Map<String, TargetEnvironmentFunction<String>>, targetPlatform: TargetPlatform) {
for ((key, value) in additionalEnvs) {
if (key == PYTHONPATH_ENV) {
appendToPythonPath(value, targetPlatform)
}
else {
addEnvironmentVariable(key, value)
}
}
}
/**
* Execute this command in a given environment, throwing an `ExecutionException` in case of a timeout or a non-zero exit code.
*/
@Throws(ExecutionException::class)
fun TargetedCommandLine.execute(env: TargetEnvironment, indicator: ProgressIndicator): ProcessOutput {
val process = env.createProcess(this, indicator)
val capturingHandler = CapturingProcessHandler(process, charset, getCommandPresentation(env))
val output = capturingHandler.runProcess()
if (output.isTimeout || output.exitCode != 0) {
val fullCommand = collectCommandsSynchronously()
throw PyExecutionException("", fullCommand[0], fullCommand.drop(1), output)
}
return output
}
/**
* Checks whether the base directory of [project] is registered in [this] request. Adds it if it is not.
* You can also provide [modules] to add its content roots and [Sdk] for which user added custom paths
*/
fun TargetEnvironmentRequest.ensureProjectSdkAndModuleDirsAreOnTarget(project: Project, vararg modules: Module) {
fun TargetEnvironmentRequest.addPathToVolume(basePath: Path) {
if (uploadVolumes.none { it.localRootPath.isAncestor(basePath) }) {
uploadVolumes += UploadRoot(localRootPath = basePath, targetRootPath = TargetPath.Temporary())
}
}
for (module in modules) {
ModuleRootManager.getInstance(module).contentRoots.forEach {
try {
addPathToVolume(it.toNioPath())
}
catch (_: UnsupportedOperationException) {
// VirtualFile.toNioPath throws UOE if VirtualFile has no associated path which is common case for JupyterRemoteVirtualFile
}
}
}
project.basePath?.let { addPathToVolume(Path.of(it)) }
}
/**
* Mimics [PyDebugRunner.disableBuiltinBreakpoint] for [PythonExecution].
*/
fun PythonExecution.disableBuiltinBreakpoint(sdk: Sdk?) {
if (sdk != null && PythonSdkFlavor.getFlavor(sdk)?.getLanguageLevel(sdk)?.isAtLeast(LanguageLevel.PYTHON37) == true) {
addEnvironmentVariable("PYTHONBREAKPOINT", "0")
}
} | apache-2.0 | aa98cfe8d53e298c3a2d3bf1f3821060 | 47.742063 | 140 | 0.756799 | 4.906912 | false | false | false | false |
JetBrains/intellij-community | java/java-tests/testSrc/com/intellij/util/indexing/StubIndexPerFileElementTypeModificationTrackerTestHelper.kt | 1 | 1609 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.util.indexing
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.StubIndex
import com.intellij.psi.stubs.StubIndexEx
import com.intellij.psi.stubs.StubUpdatingIndex
import com.intellij.psi.tree.StubFileElementType
import kotlin.test.assertEquals
class StubIndexPerFileElementTypeModificationTrackerTestHelper() {
private val lastSeenModCounts = mutableMapOf<StubFileElementType<*>, Long>()
fun setUp() {
lastSeenModCounts.clear()
}
fun ensureStubIndexUpToDate(project: Project) {
FileBasedIndex.getInstance().ensureUpToDate(StubUpdatingIndex.INDEX_ID, project, GlobalSearchScope.allScope(project))
}
fun getModCount(type: StubFileElementType<*>) = (StubIndex.getInstance() as StubIndexEx)
.getPerFileElementTypeModificationTracker(type).modificationCount
fun initModCounts(vararg types: StubFileElementType<*>) {
types.map {
lastSeenModCounts[it] = getModCount(it)
}
}
fun checkModCountIncreasedAtLeast(type: StubFileElementType<*>, minInc: Int) {
val modCount = getModCount(type)
assert(modCount >= lastSeenModCounts[type]!! + minInc)
lastSeenModCounts[type] = modCount
}
fun checkModCountHasChanged(type: StubFileElementType<*>) = checkModCountIncreasedAtLeast(type, 1)
fun checkModCountIsSame(type: StubFileElementType<*>) {
val modCount = getModCount(type)
assertEquals(lastSeenModCounts[type]!!, modCount)
}
} | apache-2.0 | 9a9b8059d64f1f5d82bb084860ce1522 | 35.590909 | 121 | 0.779366 | 4.507003 | false | false | false | false |
aguba/HighNoon | app/src/main/java/com/rafaelmallare/highnoon/MainActivity.kt | 1 | 3101 | package com.rafaelmallare.highnoon
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.view.View
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
val toggle = ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer.setDrawerListener(toggle)
toggle.syncState()
val navigationView = findViewById(R.id.nav_view) as NavigationView
navigationView.setNavigationItemSelectedListener(this)
}
override fun onBackPressed() {
val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
if (id == R.id.action_settings) {
return true
}
return super.onOptionsItemSelected(item)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
val id = item.itemId
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
drawer.closeDrawer(GravityCompat.START)
return true
}
}
| agpl-3.0 | f05e23bde3cc5f4af85cf75583984135 | 33.076923 | 105 | 0.672686 | 4.553598 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/code-insight/inspections-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/inspections/expressions/ReplaceCallWithBinaryOperatorInspection.kt | 1 | 10891 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.k2.codeinsight.inspections.expressions
import com.intellij.codeInsight.intention.FileModifier
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.calls.KtSimpleFunctionCall
import org.jetbrains.kotlin.analysis.api.calls.successfulCallOrNull
import org.jetbrains.kotlin.analysis.api.calls.successfulFunctionCallOrNull
import org.jetbrains.kotlin.analysis.api.calls.symbol
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol
import org.jetbrains.kotlin.analysis.api.types.KtTypeNullability
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicable.inspections.AbstractKotlinApplicableInspectionWithContext
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.applicabilityTarget
import org.jetbrains.kotlin.idea.codeinsight.utils.*
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.StandardClassIds
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.util.OperatorNameConventions
class ReplaceCallWithBinaryOperatorInspection :
AbstractKotlinApplicableInspectionWithContext<KtDotQualifiedExpression, ReplaceCallWithBinaryOperatorInspection.Context>(
KtDotQualifiedExpression::class
) {
@FileModifier.SafeTypeForPreview
data class Context(val operation: KtSingleValueToken, val isFloatingPointEquals: Boolean)
override fun getActionFamilyName(): String = KotlinBundle.message("replace.with.binary.operator")
override fun getProblemDescription(element: KtDotQualifiedExpression, context: Context) =
KotlinBundle.message("call.replaceable.with.binary.operator")
override fun getActionName(element: KtDotQualifiedExpression, context: Context): String {
// The `a == b` for Double/Float is IEEE 754 equality, so it might change the behavior.
// In this case, we show a different quick fix message with 'INFORMATION' highlight type.
if (context.isFloatingPointEquals) {
return KotlinBundle.message("replace.total.order.equality.with.ieee.754.equality")
}
return KotlinBundle.message("replace.with.0", context.operation.value)
}
override fun getApplicabilityRange() = applicabilityTarget<KtDotQualifiedExpression> { element ->
element.callExpression?.calleeExpression
}
override fun isApplicableByPsi(element: KtDotQualifiedExpression): Boolean {
if (element.receiverExpression is KtSuperExpression) return false
val callExpression = element.selectorExpression as? KtCallExpression ?: return false
if (callExpression.valueArguments.size != 1) return false
val calleeExpression = callExpression.calleeExpression as? KtSimpleNameExpression ?: return false
val identifier = calleeExpression.getReferencedNameAsName()
return (identifier == OperatorNameConventions.EQUALS
|| identifier == OperatorNameConventions.COMPARE_TO
|| identifier in OperatorNameConventions.BINARY_OPERATION_NAMES)
}
context(KtAnalysisSession)
override fun prepareContext(element: KtDotQualifiedExpression): Context? {
val callExpression = element.selectorExpression as? KtCallExpression ?: return null
val calleeExpression = callExpression.calleeExpression as? KtSimpleNameExpression ?: return null
val receiver = element.receiverExpression
val argument = callExpression.singleArgumentExpression() ?: return null
analyze(element) {
val resolvedCall = callExpression.resolveCall().successfulFunctionCallOrNull() ?: return null
if (resolvedCall.symbol.valueParameters.size != 1) return null
if (resolvedCall.typeArgumentsMapping.isNotEmpty()) return null
if (!element.isReceiverExpressionWithValue()) return null
val operationToken = getOperationToken(calleeExpression) ?: return null
val isFloatingPointEquals =
operationToken == KtTokens.EQEQ && receiver.hasDoubleOrFloatType() && argument.hasDoubleOrFloatType()
return Context(operationToken, isFloatingPointEquals)
}
}
override fun apply(element: KtDotQualifiedExpression, context: Context, project: Project, editor: Editor?) {
val receiver = element.receiverExpression
val argument = element.callExpression?.singleArgumentExpression() ?: return
val expressionToReplace = element.getReplacementTarget(context.operation) ?: return
val factory = KtPsiFactory(project)
val newExpression = factory.createExpressionByPattern("$0 ${context.operation.value} $1", receiver, argument, reformat = false)
expressionToReplace.replace(newExpression)
}
private fun KtDotQualifiedExpression.getReplacementTarget(operation: KtSingleValueToken): KtExpression? {
return when (operation) {
KtTokens.EXCLEQ -> this.getWrappingPrefixExpressionOrNull()
in OperatorConventions.COMPARISON_OPERATIONS -> this.parent as? KtBinaryExpression
else -> this
}
}
override fun getProblemHighlightType(element: KtDotQualifiedExpression, context: Context): ProblemHighlightType {
if (context.isFloatingPointEquals) {
return ProblemHighlightType.INFORMATION
}
return when (context.operation) {
KtTokens.EQEQ, KtTokens.EXCLEQ ->
analyze(element) {
// When the receiver has flexible nullability, `a.equals(b)` is not strictly equivalent to `a == b`
// If `a` is null, then `a.equals(b)` throws an NPE, but `a == b` is safe
if (element.receiverExpression.hasUnknownNullabilityType()) {
ProblemHighlightType.INFORMATION
} else {
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
}
}
in OperatorConventions.COMPARISON_OPERATIONS -> ProblemHighlightType.GENERIC_ERROR_OR_WARNING
else -> ProblemHighlightType.INFORMATION
}
}
context(KtAnalysisSession)
private fun KtQualifiedExpression.isReceiverExpressionWithValue(): Boolean {
val receiver = receiverExpression
if (receiver is KtSuperExpression) return false
return receiver.getKtType() != null
}
context(KtAnalysisSession)
private fun getOperationToken(calleeExpression: KtSimpleNameExpression): KtSingleValueToken? {
val identifier = calleeExpression.getReferencedNameAsName()
val dotQualified = calleeExpression.parent.parent as? KtDotQualifiedExpression ?: return null
fun isOperatorOrCompatible(): Boolean {
val functionCall = calleeExpression.resolveCall()?.successfulFunctionCallOrNull()
return (functionCall?.symbol as? KtFunctionSymbol)?.isOperator == true
}
return when (identifier) {
OperatorNameConventions.EQUALS -> {
val receiver = dotQualified.receiverExpression
val argument = dotQualified.callExpression?.singleArgumentExpression() ?: return null
if (!dotQualified.isAnyEquals() || !areRelatedBySubtyping(receiver, argument)) return null
val prefixExpression = dotQualified.getWrappingPrefixExpressionOrNull()
if (prefixExpression?.operationToken == KtTokens.EXCL) KtTokens.EXCLEQ
else KtTokens.EQEQ
}
OperatorNameConventions.COMPARE_TO -> {
if (!isOperatorOrCompatible()) return null
val binaryParent = dotQualified.parent as? KtBinaryExpression ?: return null
val comparedToZero = when {
binaryParent.right?.isZeroIntegerConstant() == true -> binaryParent.left
binaryParent.left?.isZeroIntegerConstant() == true -> binaryParent.right
else -> return null
}
if (comparedToZero != dotQualified) return null
val token = binaryParent.operationToken as? KtSingleValueToken ?: return null
if (token in OperatorConventions.COMPARISON_OPERATIONS) {
if (comparedToZero == binaryParent.left) token else token.invertedComparison()
} else {
null
}
}
else -> {
if (!isOperatorOrCompatible()) return null
OperatorConventions.BINARY_OPERATION_NAMES.inverse()[identifier]
}
}
}
}
private val KOTLIN_ANY_EQUALS_CALLABLE_ID = CallableId(StandardClassIds.Any, Name.identifier("equals"))
context(KtAnalysisSession)
private fun KtCallableSymbol.isAnyEquals(): Boolean {
val overriddenSymbols = sequence {
yield(this@isAnyEquals)
yieldAll([email protected]())
}
return overriddenSymbols.any { it.callableIdIfNonLocal == KOTLIN_ANY_EQUALS_CALLABLE_ID }
}
context(KtAnalysisSession)
private fun KtExpression.isAnyEquals(): Boolean {
val resolvedCall = resolveCall()?.successfulCallOrNull<KtSimpleFunctionCall>() ?: return false
return resolvedCall.symbol.isAnyEquals()
}
/**
* This function tries to determine when `first == second` expression is considered valid.
* According to Kotlin language specification, “no two objects unrelated by subtyping can ever be considered equal by ==”.
* [8.9.2 Value equality expressions](https://kotlinlang.org/spec/expressions.html#value-equality-expressions)
*/
context(KtAnalysisSession)
private fun areRelatedBySubtyping(first: KtExpression, second: KtExpression): Boolean {
val firstType = first.getKtType() ?: return false
val secondType = second.getKtType() ?: return false
return firstType isSubTypeOf secondType || secondType isSubTypeOf firstType
}
context(KtAnalysisSession)
private fun KtExpression.hasDoubleOrFloatType(): Boolean {
val type = getKtType() ?: return false
return type isSubTypeOf builtinTypes.DOUBLE || type isSubTypeOf builtinTypes.FLOAT
}
context(KtAnalysisSession)
private fun KtExpression.hasUnknownNullabilityType(): Boolean {
return this.getKtType()?.nullability == KtTypeNullability.UNKNOWN
}
| apache-2.0 | 8aff675575fd057204f793dca832dceb | 48.940367 | 135 | 0.720125 | 5.568798 | false | false | false | false |
NeatoRobotics/neato-sdk-android | Neato-SDK/app/src/main/java/com/neatorobotics/sdk/android/example/robots/RobotCommandsActivity.kt | 1 | 1778 | /*
* Copyright (c) 2019.
* Neato Robotics Inc.
*/
package com.neatorobotics.sdk.android.example.robots
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import android.view.MenuItem
import com.neatorobotics.sdk.android.example.R
import com.neatorobotics.sdk.android.models.Robot
import kotlinx.android.synthetic.main.activity_robot_commands.*
class RobotCommandsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_robot_commands)
setSupportActionBar(toolbar)
if (supportActionBar != null) {
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
}
fab.setOnClickListener { view ->
Snackbar.make(view, "Reloading robot state...", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
val fragment =
supportFragmentManager.findFragmentById(R.id.robotCommandFragment) as RobotCommandsActivityFragment?
fragment?.reloadRobotState()
}
val extras = intent.extras
if (extras != null && savedInstanceState == null) {
val robot = extras.getParcelable<Robot>("ROBOT")!!
//Inject robot class into fragment
val fragment =
supportFragmentManager.findFragmentById(R.id.robotCommandFragment) as RobotCommandsActivityFragment?
fragment?.injectRobot(robot)
}
}
override fun onOptionsItemSelected(menuItem: MenuItem): Boolean {
if (menuItem.itemId == android.R.id.home) {
finish()
}
return super.onOptionsItemSelected(menuItem)
}
}
| mit | 31860c06ddbded7938dd3b96db1385a4 | 33.192308 | 116 | 0.67829 | 4.96648 | false | false | false | false |
mikepenz/Android-Iconics | iconics-core/src/main/java/com/mikepenz/iconics/animation/IconicsAnimationProcessor.kt | 1 | 14763 | /*
* Copyright 2020 Mike Penz
*
* 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.mikepenz.iconics.animation
import android.animation.Animator
import android.animation.TimeInterpolator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.os.Build
import android.text.TextPaint
import android.view.animation.LinearInterpolator
import androidx.annotation.FloatRange
import androidx.annotation.RequiresApi
import androidx.startup.Initializer
import com.mikepenz.iconics.Iconics
import com.mikepenz.iconics.IconicsBrush
import com.mikepenz.iconics.animation.IconicsAnimationProcessor.Companion.INFINITE
import com.mikepenz.iconics.animation.IconicsAnimationProcessor.RepeatMode
import com.mikepenz.iconics.animation.IconicsAnimationProcessor.RepeatMode.RESTART
import com.mikepenz.iconics.typeface.IconicsInitializer
/**
* @author pa.gulko zTrap (28.11.2018)
*/
abstract class IconicsAnimationProcessor(
/**
* The time interpolator used in calculating the elapsed fraction of this animation. The
* interpolator determines whether the animation runs with linear or non-linear motion, such
* as acceleration and deceleration. The default value is
* [android.view.animation.LinearInterpolator]
*/
open var interpolator: TimeInterpolator = DEFAULT_INTERPOLATOR,
/**
* The length of the animation. The default duration is 300 milliseconds. This value
* cannot be negative.
*/
open var duration: Long = 300,
/**
* Sets how many times the animation should be repeated. If the repeat
* count is `0`, the animation is never repeated. If the repeat count is
* greater than `0` or [INFINITE], the repeat mode will be taken
* into account. The repeat count is [INFINITE] by default.
*/
open var repeatCount: Int = INFINITE,
/**
* Defines what this animation should do when it reaches the end. This
* setting is applied only when the repeat count is either greater than
* `0` or [INFINITE]. Defaults to [RepeatMode.RESTART].
*
* @see RepeatMode
*/
open var repeatMode: RepeatMode = RESTART,
/**
* Set the flag for starting animation immediately after attach to drawable and after drawable
* with the view is attached to window. Default value is `true`.
*/
open var isStartImmediately: Boolean = true
) : Initializer<Unit> {
companion object {
@JvmField val DEFAULT_INTERPOLATOR = LinearInterpolator()
/**
* This value used used with the [repeatCount] property to repeat the animation
* indefinitely.
*/
const val INFINITE = ValueAnimator.INFINITE
}
private val animator: ValueAnimator = ValueAnimator.ofFloat(0f, 100f)
private var drawable: IconicsAnimatedDrawable? = null
private var isStartRequested: Boolean = false
/** The set of listeners to be sent events through the life of an animation. */
private var listeners: MutableList<IconicsAnimationListener>? = null
/** The set of listeners to be sent pause/resume events through the life of an animation. */
private var pauseListeners: MutableList<IconicsAnimationPauseListener>? = null
private val proxyListener = object : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator, isReverse: Boolean) {
listeners?.forEach { it.onAnimationStart(this@IconicsAnimationProcessor, isReverse) }
}
override fun onAnimationEnd(animation: Animator, isReverse: Boolean) {
listeners?.forEach { it.onAnimationEnd(this@IconicsAnimationProcessor, isReverse) }
}
override fun onAnimationStart(animation: Animator) {
listeners?.forEach { it.onAnimationStart(this@IconicsAnimationProcessor) }
}
override fun onAnimationEnd(animation: Animator) {
listeners?.forEach { it.onAnimationEnd(this@IconicsAnimationProcessor) }
}
override fun onAnimationCancel(animation: Animator) {
listeners?.forEach { it.onAnimationCancel(this@IconicsAnimationProcessor) }
}
override fun onAnimationRepeat(animation: Animator) {
listeners?.forEach { it.onAnimationRepeat(this@IconicsAnimationProcessor) }
}
}
private val proxyPauseListener by lazy {
@RequiresApi(Build.VERSION_CODES.KITKAT)
object : Animator.AnimatorPauseListener {
override fun onAnimationPause(animation: Animator) {
pauseListeners?.forEach { it.onAnimationPause(this@IconicsAnimationProcessor) }
}
override fun onAnimationResume(animation: Animator) {
pauseListeners?.forEach { it.onAnimationResume(this@IconicsAnimationProcessor) }
}
}
}
/** Whether the processor has been started and not yet ended. */
val isStarted: Boolean
get() = animator.isStarted
/** Whether the processor is running. */
val isRunning: Boolean
get() = animator.isRunning
/**
* Returns whether this processor is currently in a paused state.
*
* @return True if the processor is currently paused, false otherwise.
* @see pause
* @see resume
*/
val isPaused: Boolean
@RequiresApi(Build.VERSION_CODES.KITKAT)
get() = animator.isPaused
/**
* Return the drawable's current state
*
* Nullability contract: calling this into [processPreDraw] or [processPostDraw] is
* guaranteed return `@NonNull` value, otherwise it can be `@Nullable`.
*
* @return The current state of the drawable
*/
protected val drawableState: IntArray?
get() = drawable?.state
/**
* Return the drawable's bounds Rect. Note: for efficiency, the returned object may be the same
* object stored in the drawable (though this is not guaranteed).
*
* Nullability contract: calling this into [processPreDraw] or [processPostDraw] is
* guaranteed return `@NonNull` value, otherwise it can be `@Nullable`.
*
* @return The bounds of the drawable (which may change later, so caller beware). DO NOT ALTER
* the returned object as it may change the stored bounds of this drawable.
*/
protected val drawableBounds: Rect?
get() = drawable?.bounds
/** Completed percent of animation */
@get:FloatRange(from = 0.0, to = 100.0)
protected val animatedPercent: Float
get() = animator.animatedValue as Float
/** Tag which will be used to apply this processor via xml */
abstract val animationTag: String
/**
* Starts the animation, if processor is attached to drawable, otherwise sets flag to start
* animation immediately after attaching
*/
fun start(): IconicsAnimationProcessor {
animator.interpolator = interpolator
animator.duration = duration
animator.repeatCount = repeatCount
animator.repeatMode = repeatMode.valueAnimatorConst
if (drawable != null) {
isStartRequested = false
animator.start()
} else {
isStartRequested = true
}
return this
}
/**
* Adds a listener to the set of listeners that are sent events through the life of an
* processor, such as start, repeat, and end.
*
* @param listener the listener to be added to the current set of listeners for this processor.
*/
fun addListener(listener: IconicsAnimationListener): IconicsAnimationProcessor {
if (listeners == null) {
listeners = ArrayList()
animator.addListener(proxyListener)
}
listeners?.add(listener)
return this
}
/**
* Removes a listener from the set listening to this processor.
*
* @param listener the listener to be removed from the current set of listeners for this
* processor.
*/
fun removeListener(listener: IconicsAnimationListener) {
listeners?.remove(listener)
if (listeners?.size == 0) {
listeners = null
animator.removeListener(proxyListener)
}
}
/**
* Adds a pause listener to this processor.
*
* @param listener the listener to be added to the current set of pause listeners for this
* processor.
*/
@RequiresApi(Build.VERSION_CODES.KITKAT)
fun addPauseListener(listener: IconicsAnimationPauseListener): IconicsAnimationProcessor {
if (pauseListeners == null) {
pauseListeners = ArrayList()
animator.addPauseListener(proxyPauseListener)
}
pauseListeners?.add(listener)
return this
}
/**
* Removes a pause listener from the set listening to this processor.
*
* @param listener the listener to be removed from the current set of pause listeners for
* this processor.
*/
@RequiresApi(Build.VERSION_CODES.KITKAT)
fun removePauseListener(listener: IconicsAnimationPauseListener) {
pauseListeners?.remove(listener)
if (pauseListeners?.size == 0) {
pauseListeners = null
animator.removePauseListener(proxyPauseListener)
}
}
/**
* Removes all [listeners][addListener] and [pauseListeners][addPauseListener] from this
* processor.
*/
fun removeAllListeners() {
if (listeners != null) {
listeners?.clear()
listeners = null
animator.removeListener(proxyListener)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (pauseListeners != null) {
pauseListeners?.clear()
pauseListeners = null
animator.removePauseListener(proxyPauseListener)
}
}
}
/**
* Cancels the animation. Unlike [end], [cancel] causes the animation to stop in its tracks,
* sending an [IconicsAnimationListener.onAnimationCancel] to its listeners, followed by an
* [IconicsAnimationListener.onAnimationEnd] message.
*
* This method must be called on the thread that is running the processor.
*/
fun cancel() = animator.cancel()
/**
* Ends the animation. This causes the processor to assign the end value of the property being
* animated, then calling the [IconicsAnimationListener.onAnimationEnd] method on its listeners.
*
* This method must be called on the thread that is running the processor.
*/
fun end() = animator.end()
/**
* Plays the processor in reverse. If the processor is already running, it will stop itself
* and play backwards from the point reached when reverse was called. If the processor is not
* currently running, then it will start from the end and play backwards.
*/
fun reverse() = animator.reverse()
/**
* Pauses a running processor. This method should only be called on the same thread on which
* the animation was started. If the animation has not yet been [started][isStarted] or has
* since ended, then the call is ignored. Paused processors can be resumed by calling [resume].
*
* @see resume
* @see isPaused
*/
@RequiresApi(Build.VERSION_CODES.KITKAT)
fun pause() = animator.pause()
/**
* Resumes a paused processor, causing the processor to pick up where it left off when it was
* paused. This method should only be called on the same thread on which the processor was
* started. Calls to [resume] on an processor that is not currently paused will be ignored.
*
* @see pause
* @see isPaused
*/
@RequiresApi(Build.VERSION_CODES.KITKAT)
fun resume() = animator.resume()
/**
* Will be called before [draw(Canvas)][android.graphics.drawable.Drawable.draw].
* Useful for some changes, based on [Paint][android.graphics.Paint]
*/
open fun processPreDraw(
canvas: Canvas,
iconBrush: IconicsBrush<TextPaint>,
iconContourBrush: IconicsBrush<Paint>,
backgroundBrush: IconicsBrush<Paint>,
backgroundContourBrush: IconicsBrush<Paint>
) {
}
/**
* Will be called after [draw(Canvas)][android.graphics.drawable.Drawable.draw].
* Useful for some changes, based on canvas and need to restore canvas after drawing the icon
* (scale, rotate etc.).
*/
open fun processPostDraw(canvas: Canvas) {}
/**
* Called when a drawable was attached and now [drawableBounds] and [drawableState] will
* return valid values. Good place to set some drawable-dependent fields
*/
protected fun onDrawableAttached() {}
/**
* Called when a drawable was detached and now [drawableBounds] and [drawableState] will
* return `null`. Good place to clear some drawable-dependent fields
*/
protected open fun onDrawableDetached() {}
/** Internal set an drawable to this processor */
internal fun setDrawable(drawable: IconicsAnimatedDrawable?) {
if (this.drawable != null) {
this.drawable = null
onDrawableDetached()
}
this.drawable = drawable
if (drawable != null) {
onDrawableAttached()
if (isStartImmediately || isStartRequested) {
start()
}
} else {
animator.cancel()
}
}
override fun create(context: Context) {
Iconics.registerProcessor(this)
}
override fun dependencies(): List<Class<out Initializer<*>>> {
return listOf(IconicsInitializer::class.java)
}
enum class RepeatMode(internal val valueAnimatorConst: Int) {
/**
* When the animation reaches the end and [repeatCount] is [INFINITE]
* or a positive value, the animation restarts from the beginning.
*/
RESTART(ValueAnimator.RESTART),
/**
* When the animation reaches the end and [repeatCount] is [INFINITE]
* or a positive value, the animation reverses direction on every iteration.
*/
REVERSE(ValueAnimator.REVERSE)
}
}
| apache-2.0 | e6c62812b50429f569361ac2a2ec2a8e | 34.919708 | 100 | 0.668631 | 4.883559 | false | false | false | false |
allotria/intellij-community | plugins/ide-features-trainer/src/training/statistic/FeatureUsageStatisticConsts.kt | 3 | 1115 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.statistic
object FeatureUsageStatisticConsts {
const val LESSON_ID = "lesson_id"
const val LANGUAGE = "language"
const val DURATION = "duration"
const val START = "start"
const val PASSED = "passed"
const val STOPPED = "stopped"
const val START_MODULE_ACTION = "start_module_action"
const val MODULE_NAME = "module_name"
const val PROGRESS = "progress"
const val COMPLETED_COUNT = "completed_count"
const val COURSE_SIZE = "course_size"
const val EXPAND_WELCOME_PANEL = "expand_welcome_screen"
const val SHORTCUT_CLICKED = "shortcut_clicked"
const val RESTORE = "restore"
const val LEARN_PROJECT_OPENED_FIRST_TIME = "learn_project_opened_first_time"
const val NON_LEARNING_PROJECT_OPENED = "non_learning_project_opened"
const val LEARN_PROJECT_OPENING_WAY = "learn_opening_way"
const val ACTION_ID = "action_id"
const val TASK_ID = "task_id"
const val KEYMAP_SCHEME = "keymap_scheme"
const val REASON = "reason"
}
| apache-2.0 | 65a527248b183995caaf133f322cdb92 | 41.884615 | 140 | 0.734529 | 3.573718 | false | false | false | false |
allotria/intellij-community | python/src/com/jetbrains/python/namespacePackages/PyNamespacePackageRootProvider.kt | 2 | 4060 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.namespacePackages
import com.intellij.openapi.Disposable
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ContentEntry
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.roots.ui.configuration.actions.ContentEntryEditingAction
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.pointers.VirtualFilePointer
import com.intellij.openapi.vfs.pointers.VirtualFilePointerManager
import com.intellij.ui.JBColor
import com.intellij.util.PlatformIcons
import com.intellij.util.containers.MultiMap
import com.jetbrains.python.PyBundle
import com.jetbrains.python.module.PyContentEntriesEditor
import com.jetbrains.python.module.PyRootTypeProvider
import java.awt.Color
import javax.swing.Icon
import javax.swing.JTree
class PyNamespacePackageRootProvider: PyRootTypeProvider() {
private val myNamespacePackages = MultiMap<ContentEntry, VirtualFilePointer>()
init {
if (!Registry.`is`("python.explicit.namespace.packages")) {
throw ExtensionNotApplicableException.INSTANCE
}
}
override fun reset(disposable: Disposable, editor: PyContentEntriesEditor, module: Module) {
myNamespacePackages.clear()
val namespacePackages = PyNamespacePackagesService.getInstance(module).namespacePackageFoldersVirtualFiles
for (namespacePackage in namespacePackages) {
val contentEntry = findContentEntryForFile(namespacePackage, editor) ?: continue
val pointer = VirtualFilePointerManager.getInstance().create(namespacePackage, disposable, DUMMY_LISTENER)
myNamespacePackages.putValue(contentEntry, pointer)
}
}
override fun apply(module: Module) {
val instance = PyNamespacePackagesService.getInstance(module)
val currentNamespacePackages = getCurrentNamespacePackages()
if (!Comparing.haveEqualElements(instance.namespacePackageFoldersVirtualFiles, currentNamespacePackages)) {
instance.namespacePackageFoldersVirtualFiles = currentNamespacePackages
PyNamespacePackagesStatisticsCollector.logApplyInNamespacePackageRootProvider()
}
}
override fun isModified(module: Module): Boolean =
!Comparing.haveEqualElements(PyNamespacePackagesService.getInstance(module).namespacePackageFoldersVirtualFiles,
getCurrentNamespacePackages())
override fun getRoots(): MultiMap<ContentEntry, VirtualFilePointer> = myNamespacePackages
override fun getIcon(): Icon {
return PlatformIcons.PACKAGE_ICON
}
override fun getName(): String {
return PyBundle.message("python.namespace.packages.name")
}
override fun getDescription(): String {
return PyBundle.message("python.namespace.packages.description")
}
override fun getColor(): Color {
return EASTERN_BLUE
}
override fun createRootEntryEditingAction(tree: JTree?,
disposable: Disposable?,
editor: PyContentEntriesEditor?,
model: ModifiableRootModel?): ContentEntryEditingAction {
return RootEntryEditingAction(tree, disposable, editor, model)
}
private fun getCurrentNamespacePackages(): List<VirtualFile> = myNamespacePackages.values().mapNotNull { it.file }
companion object {
private fun findContentEntryForFile(virtualFile: VirtualFile, editor: PyContentEntriesEditor): ContentEntry? {
return editor.contentEntries.find {
val possibleContentEntry = it.file
possibleContentEntry != null && VfsUtilCore.isAncestor(possibleContentEntry, virtualFile, false)
}
}
private val EASTERN_BLUE: Color = JBColor(0x29A5AD, 0x29A5AD)
}
} | apache-2.0 | 93ad526bc0d79ef9f1072fad6da05812 | 41.747368 | 140 | 0.769458 | 5.225225 | false | false | false | false |
goodwinnk/workshop-jb | src/i_introduction/_9_Extension_Functions/ExtensionFunctions.kt | 1 | 904 | package i_introduction._9_Extension_Functions
import util.*
fun String.lastChar() = this.get(this.length - 1)
// 'this' can be omitted
fun String.lastChar1() = get(length - 1)
fun use() {
// try Ctrl+Space "default completion" after the dot: lastChar() is visible
"abc".lastChar()
}
// 'lastChar' is compiled to a static function in the class ExtensionFunctionsKt (see JavaCode8.useExtension)
fun todoTask8(): Nothing = TODO(
"""
Task 8.
Implement the extension functions Int.r(), Pair<Int, Int>.r()
to support the following manner of creating rational numbers:
1.r(), Pair(1, 2).r()
""",
documentation = doc8(),
references = { 1.r(); Pair(1, 2).r(); RationalNumber(1, 9) })
data class RationalNumber(val numerator: Int, val denominator: Int)
fun Int.r(): RationalNumber = todoTask8()
fun Pair<Int, Int>.r(): RationalNumber = todoTask8()
| mit | 08f2a6a7ec77b846eed54d8958a7d8b5 | 27.25 | 109 | 0.662611 | 3.659919 | false | false | false | false |
kpi-ua/ecampus-client-android | app/src/main/java/com/goldenpiedevs/schedule/app/ui/base/BaseActivity.kt | 1 | 3198 | package com.goldenpiedevs.schedule.app.ui.base
import android.app.AlertDialog
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import com.goldenpiedevs.schedule.app.R
import com.goldenpiedevs.schedule.app.core.ext.getStatusBarHeight
import com.goldenpiedevs.schedule.app.ui.main.MainActivity
import com.goldenpiedevs.schedule.app.ui.view.hideSoftKeyboard
import io.github.inflationx.viewpump.ViewPumpContextWrapper
import kotlinx.android.synthetic.main.toolbar.*
import org.jetbrains.anko.indeterminateProgressDialog
import java.util.concurrent.atomic.AtomicLong
/**
* Created by Anton. A on 13.03.2018.
* Version 1.0
*/
abstract class BaseActivity<T : BasePresenter<V>, V : BaseView> : AppCompatActivity(), BaseView {
companion object {
const val KEY_ACTIVITY_ID = "KEY_ACTIVITY_ID"
}
private var dialog: AlertDialog? = null
private var nextId = AtomicLong(0)
private var activityId: Long = 0
protected abstract fun getPresenterChild(): T
override fun getContext(): Context {
return this
}
override fun getIt() = this
abstract fun getActivityLayout(): Int
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// try {
// requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
// requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_NOSENSOR
// } catch (e: IllegalStateException) {
// }
if (getActivityLayout() == -1)
return
setContentView(getActivityLayout())
activityId = savedInstanceState?.getLong(KEY_ACTIVITY_ID) ?: nextId.getAndIncrement()
toolbar?.let {
setSupportActionBar(it)
if (this@BaseActivity !is MainActivity)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
it.setPadding(0, getStatusBarHeight(), 0, 0)
}
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
setHomeButtonEnabled(true)
setDisplayShowTitleEnabled(false)
}
}
override fun onResume() {
getPresenterChild().onResume()
super.onResume()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putLong(KEY_ACTIVITY_ID, activityId)
}
override fun showProgressDialog() {
hideSoftKeyboard()
dialog = indeterminateProgressDialog(R.string.loading)
}
override fun dismissProgressDialog() {
dialog?.dismiss()
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
return when (item!!.itemId) {
android.R.id.home -> {
onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onDestroy() {
super.onDestroy()
getPresenterChild().detachView()
}
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase))
}
} | apache-2.0 | df27be594a7391273bb6b41bbe6576f4 | 27.81982 | 97 | 0.669481 | 4.904908 | false | false | false | false |
edvin/kdbc | src/main/kotlin/kdbc/transaction.kt | 1 | 3577 | package kdbc
import java.sql.Connection
import java.util.*
enum class TransactionType { REQUIRED, REQUIRES_NEW }
internal class TransactionContext(val type: TransactionType) {
val id: UUID = UUID.randomUUID()
private val childContexts = mutableListOf<TransactionContext>()
internal var connection: Connection? = null
fun trackConnection(connection: Connection): TransactionContext {
if (connection.autoCommit) connection.autoCommit = false
this.connection = connection
return this
}
fun trackChildContext(context: TransactionContext) {
childContexts.add(context)
}
fun rollback() {
connection?.silentlyRollback()
childContexts.forEach { it.rollback() }
cleanup()
}
fun commit() {
connection?.silentlyCommit()
childContexts.forEach { it.commit() }
cleanup()
}
private fun cleanup() {
connection = null
childContexts.clear()
}
private fun Connection.silentlyCommit() {
logErrors("Committing connection $this") {
commit()
close()
}
}
private fun Connection.silentlyRollback() {
logErrors("Rolling back connection $this") {
rollback()
close()
}
}
fun execute(op: () -> Unit) {
val activeContext = ConnectionFactory.transactionContext.get()
if (type == TransactionType.REQUIRED) {
if (activeContext != null) activeContext.trackChildContext(this)
else ConnectionFactory.transactionContext.set(this)
} else if (type == TransactionType.REQUIRES_NEW) {
ConnectionFactory.transactionContext.set(this)
}
var failed = false
try {
op()
} catch (e: Exception) {
failed = true
throw e
} finally {
if (failed) {
if (type == TransactionType.REQUIRED) {
if (activeContext != null) {
activeContext.rollback()
} else {
rollback()
}
} else if (type == TransactionType.REQUIRES_NEW) {
rollback()
}
} else {
if (type == TransactionType.REQUIRED) {
if (activeContext == null)
commit()
} else if (type == TransactionType.REQUIRES_NEW) {
commit()
}
}
ConnectionFactory.transactionContext.set(activeContext)
}
}
}
/**
* Make sure the surrounded code is executed within a transaction.
*
* All queries will use the same connection by default. To create a new connection that will
* participate in the transaction, nest another `transaction` block inside this.
*
* By default, the TransactionType.REQUIRED attribute indicates that this transaction
* can participate in an already active transaction or create it's own.
*
* Changing to TransactionType.REQUIRES_NEW will temporarily suspend any active transactions,
* and resume them after this block completes.
*
* If no connection is specified, the connection retrieved for the first query executed inside the transaction block will be used.
*
*/
fun transaction(connection: Connection? = null, type: TransactionType = TransactionType.REQUIRED, op: () -> Unit) {
val context = TransactionContext(type)
if (connection != null) context.trackConnection(connection)
context.execute(op)
} | apache-2.0 | 2491946f5160c6454e6d1104f53f7717 | 30.113043 | 130 | 0.601342 | 5.023876 | false | false | false | false |
LouisCAD/Splitties | modules/views-dsl-material/src/androidMain/kotlin/splitties/views/dsl/material/styles/TabLayoutStyles.kt | 1 | 1621 | /*
* Copyright 2019-2020 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.views.dsl.material.styles
import android.content.Context
import android.view.View
import androidx.annotation.IdRes
import androidx.annotation.StyleRes
import com.google.android.material.tabs.TabLayout
import splitties.views.dsl.core.NO_THEME
import splitties.views.dsl.core.styles.styledView
import splitties.views.dsl.material.R
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@JvmInline
value class TabLayoutStyles @PublishedApi internal constructor(
@PublishedApi internal val ctx: Context
) {
inline fun default(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: TabLayout.() -> Unit = {}
): TabLayout {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::TabLayout,
styleAttr = R.attr.Widget_MaterialComponents_TabLayout,
id = id,
theme = theme,
initView = initView
)
}
inline fun colored(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: TabLayout.() -> Unit = {}
): TabLayout {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::TabLayout,
styleAttr = R.attr.Widget_MaterialComponents_TabLayout_Colored,
id = id,
theme = theme,
initView = initView
)
}
}
| apache-2.0 | 30270f4ca43f784d9f4683e2b4b25562 | 30.784314 | 114 | 0.658853 | 4.477901 | false | false | false | false |
Groostav/CMPT886-Proj-3 | src/com/softwareleyline/GraphSurrogate.kt | 1 | 1400 | package com.softwareleyline
/**
* Created by Geoff on 5/2/2016.
*/
data class GraphSurrogate(
val nodes : List<NodeSurrogate>
){
fun asGraph() : Node {
val partials = nodes.map(NodeSurrogate::toPartial);
val nodes = partials.map{ it.first }
for((node, preds, sucs) in partials){
for(successorName in sucs){
node.successors.add(nodes.single{ it.name == successorName })
}
for(predecessorName in preds){
node.predeccessors.add(nodes.single{ it.name == predecessorName })
}
}
var root = nodes.first();
while(root.predeccessors.any()){ root = root.predeccessors.first() }
return root;
}
}
fun Node.toSurrogate() : GraphSurrogate{
val surrogates = flattened().map { it.run { NodeSurrogate(
"",
name,
signature,
predeccessors.map{ it.name },
successors.map{ it.name })
}}
return GraphSurrogate(surrogates)
}
data class NodeSurrogate (
val className : String,
val methodName : String,
val signature : String,
val predecessors : List<String>,
val successors : List<String>
){
fun toPartial() : Triple<Node, List<String>, List<String>>{
val node = Node(methodName, signature)
return Triple(node, predecessors, successors)
}
}
| apache-2.0 | 424e5a6df6ab9c84675929761930fdcb | 23.137931 | 82 | 0.585714 | 3.954802 | false | false | false | false |
siosio/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/XmlReader.kt | 1 | 35737 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("XmlReader")
@file:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty")
package com.intellij.ide.plugins
import com.intellij.openapi.components.ComponentConfig
import com.intellij.openapi.components.ServiceDescriptor
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionDescriptor
import com.intellij.openapi.extensions.ExtensionPointDescriptor
import com.intellij.openapi.extensions.LoadingOrder
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.createNonCoalescingXmlStreamReader
import com.intellij.platform.util.plugins.DataLoader
import com.intellij.util.NoOpXmlInterner
import com.intellij.util.XmlInterner
import com.intellij.util.lang.Java11Shim
import com.intellij.util.lang.ZipFilePool
import com.intellij.util.messages.ListenerDescriptor
import com.intellij.util.readXmlAsModel
import org.codehaus.stax2.XMLStreamReader2
import org.codehaus.stax2.typed.TypedXMLStreamException
import org.jetbrains.annotations.TestOnly
import java.io.IOException
import java.io.InputStream
import java.text.ParseException
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.*
import javax.xml.stream.XMLStreamConstants
import javax.xml.stream.XMLStreamException
import javax.xml.stream.XMLStreamReader
import javax.xml.stream.events.XMLEvent
private const val defaultXPointerValue = "xpointer(/idea-plugin/*)"
fun readModuleDescriptor(inputStream: InputStream,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?,
readInto: RawPluginDescriptor?,
locationSource: String?): RawPluginDescriptor {
return readModuleDescriptor(reader = createNonCoalescingXmlStreamReader(inputStream, locationSource),
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
readInto = readInto)
}
fun readModuleDescriptor(input: ByteArray,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?,
readInto: RawPluginDescriptor?,
locationSource: String?): RawPluginDescriptor {
return readModuleDescriptor(reader = createNonCoalescingXmlStreamReader(input, locationSource),
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
readInto = readInto)
}
private fun readModuleDescriptor(reader: XMLStreamReader2,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?,
readInto: RawPluginDescriptor?): RawPluginDescriptor {
try {
if (reader.eventType != XMLStreamConstants.START_DOCUMENT) {
throw XMLStreamException("State ${XMLStreamConstants.START_DOCUMENT} is expected, " +
"but current state is ${getEventTypeString(reader.eventType)}", reader.location)
}
val descriptor = readInto ?: RawPluginDescriptor()
@Suppress("ControlFlowWithEmptyBody")
while (reader.next() != XMLStreamConstants.START_ELEMENT) {
}
if (!reader.isStartElement) {
return descriptor
}
readRootAttributes(reader, descriptor)
reader.consumeChildElements { localName ->
readRootElementChild(reader = reader,
descriptor = descriptor,
readContext = readContext,
localName = localName,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase)
assert(reader.isEndElement)
}
return descriptor
}
finally {
reader.closeCompletely()
}
}
@TestOnly
fun readModuleDescriptorForTest(input: ByteArray): RawPluginDescriptor {
return readModuleDescriptor(
input = input,
readContext = object : ReadModuleContext {
override val interner = NoOpXmlInterner
override val isMissingIncludeIgnored
get() = false
},
pathResolver = PluginXmlPathResolver.DEFAULT_PATH_RESOLVER,
dataLoader = object : DataLoader {
override val pool: ZipFilePool? = null
override fun load(path: String) = throw UnsupportedOperationException()
override fun toString() = ""
},
includeBase = null,
readInto = null,
locationSource = null,
)
}
private fun readRootAttributes(reader: XMLStreamReader2, descriptor: RawPluginDescriptor) {
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"package" -> descriptor.`package` = getNullifiedAttributeValue(reader, i)
"url" -> descriptor.url = getNullifiedAttributeValue(reader, i)
"use-idea-classloader" -> descriptor.isUseIdeaClassLoader = reader.getAttributeAsBoolean(i)
"allow-bundled-update" -> descriptor.isBundledUpdateAllowed = reader.getAttributeAsBoolean(i)
"implementation-detail" -> descriptor.implementationDetail = reader.getAttributeAsBoolean(i)
"require-restart" -> descriptor.isRestartRequired = reader.getAttributeAsBoolean(i)
"version" -> {
// internalVersionString - why it is not used, but just checked?
getNullifiedAttributeValue(reader, i)?.let {
try {
it.toInt()
}
catch (e: NumberFormatException) {
LOG.error("Cannot parse version: $it'", e)
}
}
}
}
}
}
/**
* Keep in sync with KotlinPluginUtil.KNOWN_KOTLIN_PLUGIN_IDS
*/
@Suppress("ReplaceJavaStaticMethodWithKotlinAnalog", "SSBasedInspection")
private val KNOWN_KOTLIN_PLUGIN_IDS = HashSet(Arrays.asList(
"org.jetbrains.kotlin",
"com.intellij.appcode.kmm",
"org.jetbrains.kotlin.native.appcode"
))
private fun readRootElementChild(reader: XMLStreamReader2,
descriptor: RawPluginDescriptor,
localName: String,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?) {
when (localName) {
"id" -> {
if (descriptor.id == null) {
descriptor.id = getNullifiedContent(reader)
}
else if (!KNOWN_KOTLIN_PLUGIN_IDS.contains(descriptor.id)) {
// no warn and no redefinition for kotlin - compiler.xml is a known issue
LOG.warn("id redefinition (${reader.locationInfo.location})")
descriptor.id = getNullifiedContent(reader)
}
else {
reader.skipElement()
}
}
"name" -> descriptor.name = getNullifiedContent(reader)
"category" -> descriptor.category = getNullifiedContent(reader)
"version" -> {
// kotlin includes compiler.xml that due to some reasons duplicates version
if (descriptor.version == null || !KNOWN_KOTLIN_PLUGIN_IDS.contains(descriptor.id)) {
descriptor.version = getNullifiedContent(reader)
}
else {
reader.skipElement()
}
}
"description" -> descriptor.description = getNullifiedContent(reader)
"change-notes" -> descriptor.changeNotes = getNullifiedContent(reader)
"resource-bundle" -> descriptor.resourceBundleBaseName = getNullifiedContent(reader)
"product-descriptor" -> readProduct(reader, descriptor)
"module" -> {
findAttributeValue(reader, "value")?.let { moduleName ->
var modules = descriptor.modules
if (modules == null) {
descriptor.modules = Collections.singletonList(PluginId.getId(moduleName))
}
else {
if (modules.size == 1) {
val singleton = modules
modules = ArrayList(4)
modules.addAll(singleton)
descriptor.modules = modules
}
modules.add(PluginId.getId(moduleName))
}
}
reader.skipElement()
}
"idea-version" -> {
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"since-build" -> descriptor.sinceBuild = getNullifiedAttributeValue(reader, i)
"until-build" -> descriptor.untilBuild = getNullifiedAttributeValue(reader, i)
}
}
reader.skipElement()
}
"vendor" -> {
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"email" -> descriptor.vendorEmail = getNullifiedAttributeValue(reader, i)
"url" -> descriptor.vendorUrl = getNullifiedAttributeValue(reader, i)
}
}
descriptor.vendor = getNullifiedContent(reader)
}
"incompatible-with" -> {
getNullifiedContent(reader)?.let {
var list = descriptor.incompatibilities
if (list == null) {
list = ArrayList()
descriptor.incompatibilities = list
}
list.add(PluginId.getId(it))
}
}
"application-components" -> readComponents(reader, descriptor.appContainerDescriptor)
"project-components" -> readComponents(reader, descriptor.projectContainerDescriptor)
"module-components" -> readComponents(reader, descriptor.moduleContainerDescriptor)
"applicationListeners" -> readListeners(reader, descriptor.appContainerDescriptor)
"projectListeners" -> readListeners(reader, descriptor.projectContainerDescriptor)
"extensions" -> readExtensions(reader, descriptor, readContext.interner)
"extensionPoints" -> readExtensionPoints(reader = reader,
descriptor = descriptor,
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase)
"content" -> readContent(reader = reader,
descriptor = descriptor,
readContext = readContext)
"dependencies" -> readDependencies(reader = reader, descriptor = descriptor, readContext = readContext)
"depends" -> readOldDepends(reader, descriptor)
"actions" -> readActions(descriptor, reader, readContext)
"include" -> readInclude(reader = reader,
readInto = descriptor,
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
allowedPointer = defaultXPointerValue)
"helpset" -> {
// deprecated and not used element
reader.skipElement()
}
"locale" -> {
// not used in descriptor
reader.skipElement()
}
else -> {
LOG.error("Unknown element: $localName")
reader.skipElement()
}
}
if (!reader.isEndElement) {
throw XMLStreamException("Unexpected state (" +
"expected=END_ELEMENT, " +
"actual=${getEventTypeString(reader.eventType)}, " +
"lastProcessedElement=$localName" +
")", reader.location)
}
}
private fun readActions(descriptor: RawPluginDescriptor, reader: XMLStreamReader2, readContext: ReadModuleContext) {
var actionElements = descriptor.actions
if (actionElements == null) {
actionElements = ArrayList()
descriptor.actions = actionElements
}
val resourceBundle = findAttributeValue(reader, "resource-bundle")
reader.consumeChildElements { elementName ->
if (checkXInclude(elementName, reader)) {
return@consumeChildElements
}
actionElements.add(RawPluginDescriptor.ActionDescriptor(
name = elementName,
element = readXmlAsModel(reader = reader, rootName = elementName, interner = readContext.interner),
resourceBundle = resourceBundle,
))
}
}
private fun readOldDepends(reader: XMLStreamReader2, descriptor: RawPluginDescriptor) {
var isOptional = false
var configFile: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"optional" -> isOptional = reader.getAttributeAsBoolean(i)
"config-file" -> configFile = reader.getAttributeValue(i)
}
}
val dependencyIdString = getNullifiedContent(reader) ?: return
var depends = descriptor.depends
if (depends == null) {
depends = ArrayList()
descriptor.depends = depends
}
depends.add(PluginDependency(pluginId = PluginId.getId(dependencyIdString), configFile = configFile, isOptional = isOptional))
}
private fun readExtensions(reader: XMLStreamReader2, descriptor: RawPluginDescriptor, interner: XmlInterner) {
val ns = findAttributeValue(reader, "defaultExtensionNs")
reader.consumeChildElements { elementName ->
if (checkXInclude(elementName, reader)) {
return@consumeChildElements
}
var implementation: String? = null
var os: ExtensionDescriptor.Os? = null
var qualifiedExtensionPointName: String? = null
var order = LoadingOrder.ANY
var orderId: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"implementation" -> implementation = reader.getAttributeValue(i)
"implementationClass" -> {
// deprecated attribute
implementation = reader.getAttributeValue(i)
}
"os" -> os = readOs(reader.getAttributeValue(i))
"id" -> orderId = getNullifiedAttributeValue(reader, i)
"order" -> order = readOrder(reader.getAttributeValue(i))
"point" -> qualifiedExtensionPointName = getNullifiedAttributeValue(reader, i)
}
}
if (qualifiedExtensionPointName == null) {
qualifiedExtensionPointName = interner.name("${ns ?: reader.namespaceURI}.${elementName}")
}
val containerDescriptor: ContainerDescriptor
when (qualifiedExtensionPointName) {
"com.intellij.applicationService" -> containerDescriptor = descriptor.appContainerDescriptor
"com.intellij.projectService" -> containerDescriptor = descriptor.projectContainerDescriptor
"com.intellij.moduleService" -> containerDescriptor = descriptor.moduleContainerDescriptor
else -> {
// bean EP can use id / implementation attributes for own bean class
// - that's why we have to create XmlElement even if all attributes are common
val element = if (qualifiedExtensionPointName == "com.intellij.postStartupActivity") {
reader.skipElement()
null
}
else {
readXmlAsModel(reader = reader, rootName = null, interner = interner).takeIf {
!it.children.isEmpty() || !it.attributes.keys.isEmpty()
}
}
var map = descriptor.epNameToExtensions
if (map == null) {
map = HashMap()
descriptor.epNameToExtensions = map
}
val extensionDescriptor = ExtensionDescriptor(implementation, os, orderId, order, element)
val list = map.get(qualifiedExtensionPointName)
if (list == null) {
map.put(qualifiedExtensionPointName, Collections.singletonList(extensionDescriptor))
}
else if (list.size == 1) {
val l = ArrayList<ExtensionDescriptor>(4)
l.add(list.get(0))
l.add(extensionDescriptor)
map.put(qualifiedExtensionPointName, l)
}
else {
list.add(extensionDescriptor)
}
assert(reader.isEndElement)
return@consumeChildElements
}
}
containerDescriptor.addService(readServiceDescriptor(reader, os))
reader.skipElement()
}
}
private fun readOrder(orderAttr: String?): LoadingOrder {
return when (orderAttr) {
null -> LoadingOrder.ANY
LoadingOrder.FIRST_STR -> LoadingOrder.FIRST
LoadingOrder.LAST_STR -> LoadingOrder.LAST
else -> LoadingOrder(orderAttr)
}
}
private fun checkXInclude(elementName: String, reader: XMLStreamReader2): Boolean {
if (elementName == "include" && reader.namespaceURI == "http://www.w3.org/2001/XInclude") {
LOG.error("`include` is supported only on a root level (${reader.location})")
reader.skipElement()
return true
}
return false
}
private fun readExtensionPoints(reader: XMLStreamReader2,
descriptor: RawPluginDescriptor,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?) {
reader.consumeChildElements { elementName ->
if (elementName != "extensionPoint") {
if (elementName == "include" && reader.namespaceURI == "http://www.w3.org/2001/XInclude") {
val partial = RawPluginDescriptor()
readInclude(reader = reader,
readInto = partial,
readContext = readContext,
pathResolver = pathResolver,
dataLoader = dataLoader,
includeBase = includeBase,
allowedPointer = "xpointer(/idea-plugin/extensionPoints/*)")
LOG.warn("`include` is supported only on a root level (${reader.location})")
applyPartialContainer(partial, descriptor) { it.appContainerDescriptor }
applyPartialContainer(partial, descriptor) { it.projectContainerDescriptor }
applyPartialContainer(partial, descriptor) { it.moduleContainerDescriptor }
}
else {
LOG.error("Unknown element: $elementName (${reader.location})")
reader.skipElement()
}
return@consumeChildElements
}
var area: String? = null
var qualifiedName: String? = null
var name: String? = null
var beanClass: String? = null
var `interface`: String? = null
var isDynamic = false
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"area" -> area = getNullifiedAttributeValue(reader, i)
"qualifiedName" -> qualifiedName = reader.getAttributeValue(i)
"name" -> name = getNullifiedAttributeValue(reader, i)
"beanClass" -> beanClass = getNullifiedAttributeValue(reader, i)
"interface" -> `interface` = getNullifiedAttributeValue(reader, i)
"dynamic" -> isDynamic = reader.getAttributeAsBoolean(i)
}
}
if (beanClass == null && `interface` == null) {
throw RuntimeException("Neither beanClass nor interface attribute is specified for extension point at ${reader.location}")
}
if (beanClass != null && `interface` != null) {
throw RuntimeException("Both beanClass and interface attributes are specified for extension point at ${reader.location}")
}
reader.skipElement()
val containerDescriptor = when (area) {
null -> descriptor.appContainerDescriptor
"IDEA_PROJECT" -> descriptor.projectContainerDescriptor
"IDEA_MODULE" -> descriptor.moduleContainerDescriptor
else -> {
LOG.error("Unknown area: $area")
return@consumeChildElements
}
}
var result = containerDescriptor.extensionPoints
if (result == null) {
result = ArrayList()
containerDescriptor.extensionPoints = result
}
result.add(ExtensionPointDescriptor(
name = qualifiedName ?: name ?: throw RuntimeException("`name` attribute not specified for extension point at ${reader.location}"),
isNameQualified = qualifiedName != null,
className = `interface` ?: beanClass!!,
isBean = `interface` == null,
isDynamic = isDynamic
))
}
}
private inline fun applyPartialContainer(from: RawPluginDescriptor,
to: RawPluginDescriptor,
crossinline extractor: (RawPluginDescriptor) -> ContainerDescriptor) {
extractor(from).extensionPoints?.let {
val toContainer = extractor(to)
if (toContainer.extensionPoints == null) {
toContainer.extensionPoints = it
}
else {
toContainer.extensionPoints!!.addAll(it)
}
}
}
private fun readServiceDescriptor(reader: XMLStreamReader2, os: ExtensionDescriptor.Os?): ServiceDescriptor {
var serviceInterface: String? = null
var serviceImplementation: String? = null
var testServiceImplementation: String? = null
var headlessImplementation: String? = null
var configurationSchemaKey: String? = null
var overrides = false
var preload = ServiceDescriptor.PreloadMode.FALSE
var client: ServiceDescriptor.ClientKind? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"serviceInterface" -> serviceInterface = getNullifiedAttributeValue(reader, i)
"serviceImplementation" -> serviceImplementation = getNullifiedAttributeValue(reader, i)
"testServiceImplementation" -> testServiceImplementation = getNullifiedAttributeValue(reader, i)
"headlessImplementation" -> headlessImplementation = getNullifiedAttributeValue(reader, i)
"configurationSchemaKey" -> configurationSchemaKey = reader.getAttributeValue(i)
"overrides" -> overrides = reader.getAttributeAsBoolean(i)
"preload" -> {
when (reader.getAttributeValue(i)) {
"true" -> preload = ServiceDescriptor.PreloadMode.TRUE
"await" -> preload = ServiceDescriptor.PreloadMode.AWAIT
"notHeadless" -> preload = ServiceDescriptor.PreloadMode.NOT_HEADLESS
"notLightEdit" -> preload = ServiceDescriptor.PreloadMode.NOT_LIGHT_EDIT
else -> LOG.error("Unknown preload mode value ${reader.getAttributeValue(i)} at ${reader.location}")
}
}
"client" -> {
when (reader.getAttributeValue(i)) {
"all" -> client = ServiceDescriptor.ClientKind.ALL
"local" -> client = ServiceDescriptor.ClientKind.LOCAL
"guest" -> client = ServiceDescriptor.ClientKind.GUEST
else -> LOG.error("Unknown client value: ${reader.getAttributeValue(i)} at ${reader.location}")
}
}
}
}
return ServiceDescriptor(serviceInterface, serviceImplementation, testServiceImplementation, headlessImplementation,
overrides, configurationSchemaKey, preload, client, os)
}
private fun readProduct(reader: XMLStreamReader2, descriptor: RawPluginDescriptor) {
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"code" -> descriptor.productCode = getNullifiedAttributeValue(reader, i)
"release-date" -> descriptor.releaseDate = parseReleaseDate(reader.getAttributeValue(i))
"release-version" -> {
try {
descriptor.releaseVersion = reader.getAttributeAsInt(i)
}
catch (e: TypedXMLStreamException) {
descriptor.releaseVersion = 0
}
}
"optional" -> descriptor.isLicenseOptional = reader.getAttributeAsBoolean(i)
}
}
reader.skipElement()
}
private fun readComponents(reader: XMLStreamReader2, containerDescriptor: ContainerDescriptor) {
val result = containerDescriptor.getComponentListToAdd()
reader.consumeChildElements("component") {
var isApplicableForDefaultProject = false
var interfaceClass: String? = null
var implementationClass: String? = null
var headlessImplementationClass: String? = null
var os: ExtensionDescriptor.Os? = null
var overrides = false
var options: MutableMap<String, String?>? = null
reader.consumeChildElements { elementName ->
when (elementName) {
"skipForDefaultProject" -> {
val value = reader.elementText
if (!value.isEmpty() && value.equals("false", ignoreCase = true)) {
isApplicableForDefaultProject = true
}
}
"loadForDefaultProject" -> {
val value = reader.elementText
isApplicableForDefaultProject = value.isEmpty() || value.equals("true", ignoreCase = true)
}
"interface-class" -> interfaceClass = getNullifiedContent(reader)
// empty value must be supported
"implementation-class" -> implementationClass = getNullifiedContent(reader)
// empty value must be supported
"headless-implementation-class" -> headlessImplementationClass = reader.elementText
"option" -> {
var name: String? = null
var value: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"name" -> name = getNullifiedAttributeValue(reader, i)
"value" -> value = getNullifiedAttributeValue(reader, i)
}
}
reader.skipElement()
if (name != null && value != null) {
when {
name == "os" -> os = readOs(value)
name == "overrides" -> overrides = value.toBoolean()
options == null -> {
options = Collections.singletonMap(name, value)
}
else -> {
if (options!!.size == 1) {
options = HashMap(options)
}
options!!.put(name, value)
}
}
}
}
else -> reader.skipElement()
}
assert(reader.isEndElement)
}
assert(reader.isEndElement)
result.add(ComponentConfig(interfaceClass, implementationClass, headlessImplementationClass, isApplicableForDefaultProject,
os, overrides, options))
}
}
private fun readContent(reader: XMLStreamReader2,
descriptor: RawPluginDescriptor,
readContext: ReadModuleContext) {
val items = ArrayList<PluginContentDescriptor.ModuleItem>()
reader.consumeChildElements { elementName ->
when (elementName) {
"module" -> {
var name: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"name" -> name = readContext.interner.name(reader.getAttributeValue(i))
}
}
if (name.isNullOrEmpty()) {
throw RuntimeException("Name is not specified at ${reader.location}")
}
var configFile: String? = null
val index = name.lastIndexOf('/')
if (index != -1) {
configFile = "${name.substring(0, index)}.${name.substring(index + 1)}.xml"
}
items.add(PluginContentDescriptor.ModuleItem(name = name, configFile = configFile))
}
else -> throw RuntimeException("Unknown content item type: $elementName")
}
reader.skipElement()
}
descriptor.content = PluginContentDescriptor(Java11Shim.INSTANCE.copyOf(items))
assert(reader.isEndElement)
}
private fun readDependencies(reader: XMLStreamReader2, descriptor: RawPluginDescriptor, readContext: ReadModuleContext) {
var modules: MutableList<ModuleDependenciesDescriptor.ModuleReference>? = null
var plugins: MutableList<ModuleDependenciesDescriptor.PluginReference>? = null
reader.consumeChildElements { elementName ->
when (elementName) {
"module" -> {
var name: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"name" -> name = readContext.interner.name(reader.getAttributeValue(i))
}
}
if (modules == null) {
modules = ArrayList()
}
modules!!.add(ModuleDependenciesDescriptor.ModuleReference(name!!))
}
"plugin" -> {
var id: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"id" -> id = readContext.interner.name(reader.getAttributeValue(i))
}
}
if (plugins == null) {
plugins = ArrayList()
}
plugins!!.add(ModuleDependenciesDescriptor.PluginReference(PluginId.getId(id!!)))
}
else -> throw RuntimeException("Unknown content item type: ${elementName}")
}
reader.skipElement()
}
descriptor.dependencies = ModuleDependenciesDescriptor(modules ?: Collections.emptyList(), plugins ?: Collections.emptyList())
assert(reader.isEndElement)
}
private fun findAttributeValue(reader: XMLStreamReader2, name: String): String? {
for (i in 0 until reader.attributeCount) {
if (reader.getAttributeLocalName(i) == name) {
return getNullifiedAttributeValue(reader, i)
}
}
return null
}
private fun getNullifiedContent(reader: XMLStreamReader2): String? = reader.elementText.takeIf { !it.isEmpty() }
private fun getNullifiedAttributeValue(reader: XMLStreamReader2, i: Int) = reader.getAttributeValue(i).takeIf { !it.isEmpty() }
interface ReadModuleContext {
val interner: XmlInterner
val isMissingIncludeIgnored: Boolean
}
private fun readInclude(reader: XMLStreamReader2,
readInto: RawPluginDescriptor,
readContext: ReadModuleContext,
pathResolver: PathResolver,
dataLoader: DataLoader,
includeBase: String?,
allowedPointer: String) {
var path: String? = null
var pointer: String? = null
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"href" -> path = getNullifiedAttributeValue(reader, i)
"xpointer" -> pointer = reader.getAttributeValue(i)?.takeIf { !it.isEmpty() && it != allowedPointer }
else -> throw RuntimeException("Unknown attribute ${reader.getAttributeLocalName(i)} (${reader.location})")
}
}
if (pointer != null) {
throw RuntimeException("Attribute `xpointer` is not supported anymore (xpointer=$pointer, location=${reader.location})")
}
if (path == null) {
throw RuntimeException("Missing `href` attribute (${reader.location})")
}
var isOptional = false
reader.consumeChildElements("fallback") {
isOptional = true
reader.skipElement()
}
var readError: IOException? = null
val read = try {
pathResolver.loadXIncludeReference(dataLoader = dataLoader,
base = includeBase,
relativePath = path,
readContext = readContext,
readInto = readInto)
}
catch (e: IOException) {
readError = e
false
}
if (read || isOptional) {
return
}
if (readContext.isMissingIncludeIgnored) {
LOG.info("$path include ignored (dataLoader=$dataLoader)", readError)
return
}
else {
throw RuntimeException("Cannot resolve $path (dataLoader=$dataLoader)", readError)
}
}
private var dateTimeFormatter: DateTimeFormatter? = null
private val LOG: Logger
get() = PluginManagerCore.getLogger()
private fun parseReleaseDate(dateString: String): LocalDate? {
if (dateString.isEmpty() || dateString == "__DATE__") {
return null
}
var formatter = dateTimeFormatter
if (formatter == null) {
formatter = DateTimeFormatter.ofPattern("yyyyMMdd", Locale.US)
dateTimeFormatter = formatter
}
try {
return LocalDate.parse(dateString, formatter)
}
catch (e: ParseException) {
LOG.error("Cannot parse release date", e)
}
return null
}
private fun readListeners(reader: XMLStreamReader2, containerDescriptor: ContainerDescriptor) {
var result = containerDescriptor.listeners
if (result == null) {
result = ArrayList()
containerDescriptor.listeners = result
}
reader.consumeChildElements("listener") {
var os: ExtensionDescriptor.Os? = null
var listenerClassName: String? = null
var topicClassName: String? = null
var activeInTestMode = true
var activeInHeadlessMode = true
for (i in 0 until reader.attributeCount) {
when (reader.getAttributeLocalName(i)) {
"os" -> os = readOs(reader.getAttributeValue(i))
"class" -> listenerClassName = getNullifiedAttributeValue(reader, i)
"topic" -> topicClassName = getNullifiedAttributeValue(reader, i)
"activeInTestMode" -> activeInTestMode = reader.getAttributeAsBoolean(i)
"activeInHeadlessMode" -> activeInHeadlessMode = reader.getAttributeAsBoolean(i)
}
}
if (listenerClassName == null || topicClassName == null) {
LOG.error("Listener descriptor is not correct as ${reader.location}")
}
else {
result.add(ListenerDescriptor(os, listenerClassName, topicClassName, activeInTestMode, activeInHeadlessMode))
}
reader.skipElement()
}
assert(reader.isEndElement)
}
private fun readOs(value: String): ExtensionDescriptor.Os {
return when (value) {
"mac" -> ExtensionDescriptor.Os.mac
"linux" -> ExtensionDescriptor.Os.linux
"windows" -> ExtensionDescriptor.Os.windows
"unix" -> ExtensionDescriptor.Os.unix
"freebsd" -> ExtensionDescriptor.Os.freebsd
else -> throw IllegalArgumentException("Unknown OS: $value")
}
}
private inline fun XMLStreamReader.consumeChildElements(crossinline consumer: (name: String) -> Unit) {
// cursor must be at the start of parent element
assert(isStartElement)
var depth = 1
while (true) {
@Suppress("DuplicatedCode")
when (next()) {
XMLStreamConstants.START_ELEMENT -> {
depth++
consumer(localName)
assert(isEndElement)
depth--
}
XMLStreamConstants.END_ELEMENT -> {
if (depth != 1) {
throw IllegalStateException("Expected depth: 1")
}
return
}
XMLStreamConstants.CDATA,
XMLStreamConstants.SPACE,
XMLStreamConstants.CHARACTERS,
XMLStreamConstants.ENTITY_REFERENCE,
XMLStreamConstants.COMMENT,
XMLStreamConstants.PROCESSING_INSTRUCTION -> {
// ignore
}
else -> throw XMLStreamException("Unexpected state: ${getEventTypeString(eventType)}", location)
}
}
}
private inline fun XMLStreamReader2.consumeChildElements(name: String, crossinline consumer: () -> Unit) {
consumeChildElements {
if (name == it) {
consumer()
assert(isEndElement)
}
else {
skipElement()
}
}
}
private fun getEventTypeString(eventType: Int): String {
return when (eventType) {
XMLEvent.START_ELEMENT -> "START_ELEMENT"
XMLEvent.END_ELEMENT -> "END_ELEMENT"
XMLEvent.PROCESSING_INSTRUCTION -> "PROCESSING_INSTRUCTION"
XMLEvent.CHARACTERS -> "CHARACTERS"
XMLEvent.COMMENT -> "COMMENT"
XMLEvent.START_DOCUMENT -> "START_DOCUMENT"
XMLEvent.END_DOCUMENT -> "END_DOCUMENT"
XMLEvent.ENTITY_REFERENCE -> "ENTITY_REFERENCE"
XMLEvent.ATTRIBUTE -> "ATTRIBUTE"
XMLEvent.DTD -> "DTD"
XMLEvent.CDATA -> "CDATA"
XMLEvent.SPACE -> "SPACE"
else -> "UNKNOWN_EVENT_TYPE, $eventType"
}
} | apache-2.0 | a73089c0086cabed05969bc3bea43392 | 36.778013 | 158 | 0.643059 | 4.944929 | false | false | false | false |
siosio/intellij-community | plugins/ide-features-trainer/src/training/learn/OpenLessonActivities.kt | 1 | 19724 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.learn
import com.intellij.ide.scratch.ScratchFileService
import com.intellij.ide.scratch.ScratchRootType
import com.intellij.ide.startup.StartupManagerEx
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.fileEditor.TextEditorWithPreview
import com.intellij.openapi.progress.runBackgroundableTask
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Computable
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ToolWindowType
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.util.Alarm
import com.intellij.util.concurrency.annotations.RequiresEdt
import training.dsl.LessonUtil
import training.dsl.impl.LessonContextImpl
import training.dsl.impl.LessonExecutor
import training.lang.LangManager
import training.lang.LangSupport
import training.learn.course.KLesson
import training.learn.course.Lesson
import training.learn.course.LessonType
import training.learn.lesson.LessonManager
import training.project.ProjectUtils
import training.statistic.StatisticBase
import training.statistic.StatisticLessonListener
import training.ui.LearnToolWindowFactory
import training.ui.LearningUiManager
import training.util.findLanguageByID
import training.util.isLearningProject
import training.util.learningToolWindow
import java.io.IOException
internal object OpenLessonActivities {
private val LOG = logger<OpenLessonActivities>()
@RequiresEdt
fun openLesson(projectWhereToStartLesson: Project, lesson: Lesson, forceStartLesson: Boolean) {
LOG.debug("${projectWhereToStartLesson.name}: start openLesson method")
// Stop the current lesson (if any)
LessonManager.instance.stopLesson()
val activeToolWindow = LearningUiManager.activeToolWindow
?: LearnToolWindowFactory.learnWindowPerProject[projectWhereToStartLesson].also {
LearningUiManager.activeToolWindow = it
}
if (activeToolWindow != null && activeToolWindow.project != projectWhereToStartLesson) {
// maybe we need to add some confirmation dialog?
activeToolWindow.setModulesPanel()
}
if (!forceStartLesson && LessonManager.instance.lessonShouldBeOpenedCompleted(lesson)) {
// TODO: Do not stop lesson in another toolwindow IFT-110
LearningUiManager.activeToolWindow?.setLearnPanel() ?: error("No active toolwindow in $projectWhereToStartLesson")
LessonManager.instance.openLessonPassed(lesson as KLesson, projectWhereToStartLesson)
return
}
try {
val langSupport = LangManager.getInstance().getLangSupport() ?: throw Exception("Language for learning plugin is not defined")
var learnProject = LearningUiManager.learnProject
if (learnProject != null && !isLearningProject(learnProject, langSupport)) {
learnProject = null // We are in the project from another course
}
LOG.debug("${projectWhereToStartLesson.name}: trying to get cached LearnProject ${learnProject != null}")
if (learnProject == null) learnProject = findLearnProjectInOpenedProjects(langSupport)
LOG.debug("${projectWhereToStartLesson.name}: trying to find LearnProject in opened projects ${learnProject != null}")
if (learnProject != null) LearningUiManager.learnProject = learnProject
when {
lesson.lessonType == LessonType.SCRATCH -> {
LOG.debug("${projectWhereToStartLesson.name}: scratch based lesson")
}
learnProject == null || learnProject.isDisposed -> {
if (!isLearningProject(projectWhereToStartLesson, langSupport)) {
//1. learnProject == null and current project has different name then initLearnProject and register post startup open lesson
LOG.debug("${projectWhereToStartLesson.name}: 1. learnProject is null or disposed")
initLearnProject(projectWhereToStartLesson) {
LOG.debug("${projectWhereToStartLesson.name}: 1. ... LearnProject has been started")
openLessonWhenLearnProjectStart(lesson, it)
LOG.debug("${projectWhereToStartLesson.name}: 1. ... open lesson when learn project has been started")
}
return
}
else {
LOG.debug(
"${projectWhereToStartLesson.name}: 0. learnProject is null but the current project (${projectWhereToStartLesson.name})" +
"is LearnProject then just getFileInLearnProject")
LearningUiManager.learnProject = projectWhereToStartLesson
learnProject = projectWhereToStartLesson
}
}
learnProject.isOpen && projectWhereToStartLesson != learnProject -> {
LOG.debug("${projectWhereToStartLesson.name}: 3. LearnProject is opened but not focused. Ask user to focus to LearnProject")
askSwitchToLearnProjectBack(learnProject, projectWhereToStartLesson)
return
}
learnProject.isOpen && projectWhereToStartLesson == learnProject -> {
LOG.debug("${projectWhereToStartLesson.name}: 4. LearnProject is the current project")
}
else -> {
throw Exception("Unable to start Learn project")
}
}
if (lesson.lessonType.isProject) {
if (projectWhereToStartLesson != learnProject) {
LOG.error(Exception("Invalid learning project initialization: " +
"projectWhereToStartLesson = $projectWhereToStartLesson, learnProject = $learnProject"))
return
}
prepareAndOpenLesson(projectWhereToStartLesson, lesson)
}
else {
openLessonForPreparedProject(projectWhereToStartLesson, lesson)
}
}
catch (e: Exception) {
LOG.error(e)
}
}
private fun prepareAndOpenLesson(project: Project, lessonToOpen: Lesson, withCleanup: Boolean = true) {
runBackgroundableTask(LearnBundle.message("learn.project.initializing.process"), project = project) {
if (withCleanup) {
LangManager.getInstance().getLangSupport()?.cleanupBeforeLessons(project)
}
lessonToOpen.prepare(project)
invokeLater {
openLessonForPreparedProject(project, lessonToOpen)
}
}
}
private fun openLessonForPreparedProject(project: Project, lesson: Lesson) {
val langSupport = LangManager.getInstance().getLangSupport() ?: throw Exception("Language should be defined by now")
val vf: VirtualFile? = if (lesson.lessonType == LessonType.SCRATCH) {
LOG.debug("${project.name}: scratch based lesson")
getScratchFile(project, lesson, langSupport.filename)
}
else {
LOG.debug("${project.name}: 4. LearnProject is the current project")
getFileInLearnProject(lesson)
}
if (lesson.lessonType != LessonType.SCRATCH) {
ProjectUtils.closeAllEditorsInProject(project)
}
if (lesson.lessonType != LessonType.SCRATCH || LearningUiManager.learnProject == project) {
// do not change view environment for scratch lessons in user project
hideOtherViews(project)
}
// We need to ensure that the learning panel is initialized
if (showLearnPanel(project, lesson.preferredLearnWindowAnchor(project))) {
openLessonWhenLearnPanelIsReady(project, lesson, vf)
}
else waitLearningToolwindow(project, lesson, vf)
}
private fun openLessonWhenLearnPanelIsReady(project: Project, lesson: Lesson, vf: VirtualFile?) {
LOG.debug("${project.name}: Add listeners to lesson")
addStatisticLessonListenerIfNeeded(project, lesson)
//open next lesson if current is passed
LOG.debug("${project.name}: Set lesson view")
LearningUiManager.activeToolWindow = LearnToolWindowFactory.learnWindowPerProject[project]?.also {
it.setLearnPanel()
}
LOG.debug("${project.name}: XmlLesson onStart()")
lesson.onStart()
//to start any lesson we need to do 4 steps:
//1. open editor or find editor
LOG.debug("${project.name}: PREPARING TO START LESSON:")
LOG.debug("${project.name}: 1. Open or find editor")
var textEditor: TextEditor? = null
if (vf != null && FileEditorManager.getInstance(project).isFileOpen(vf)) {
val editors = FileEditorManager.getInstance(project).getEditors(vf)
for (fileEditor in editors) {
if (fileEditor is TextEditor) {
textEditor = fileEditor
}
}
}
if (vf != null && textEditor == null) {
val editors = FileEditorManager.getInstance(project).openFile(vf, true, true)
for (fileEditor in editors) {
if (fileEditor is TextEditor) {
textEditor = fileEditor
}
}
if (textEditor == null) {
LOG.error("Cannot open editor for $vf")
if (lesson.lessonType == LessonType.SCRATCH) {
invokeLater {
runWriteAction {
vf.delete(this)
}
}
}
}
}
//2. set the focus on this editor
//FileEditorManager.getInstance(project).setSelectedEditor(vf, TextEditorProvider.getInstance().getEditorTypeId());
LOG.debug("${project.name}: 2. Set the focus on this editor")
if (vf != null)
FileEditorManager.getInstance(project).openEditor(OpenFileDescriptor(project, vf), true)
//4. Process lesson
LOG.debug("${project.name}: 4. Process lesson")
if (lesson is KLesson) processDslLesson(lesson, textEditor, project, vf)
else error("Unknown lesson format")
}
private fun waitLearningToolwindow(project: Project, lesson: Lesson, vf: VirtualFile?) {
val connect = project.messageBus.connect()
connect.subscribe(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener {
override fun toolWindowsRegistered(ids: MutableList<String>, toolWindowManager: ToolWindowManager) {
if (ids.contains(LearnToolWindowFactory.LEARN_TOOL_WINDOW)) {
val toolWindow = toolWindowManager.getToolWindow(LearnToolWindowFactory.LEARN_TOOL_WINDOW)
if (toolWindow != null) {
connect.disconnect()
invokeLater {
showLearnPanel(project, lesson.preferredLearnWindowAnchor(project))
openLessonWhenLearnPanelIsReady(project, lesson, vf)
}
}
}
}
})
}
private fun processDslLesson(lesson: KLesson, textEditor: TextEditor?, projectWhereToStartLesson: Project, vf: VirtualFile?) {
val executor = LessonExecutor(lesson, projectWhereToStartLesson, textEditor?.editor, vf)
val lessonContext = LessonContextImpl(executor)
LessonManager.instance.initDslLesson(textEditor?.editor, lesson, executor)
lesson.lessonContent(lessonContext)
executor.startLesson()
}
private fun hideOtherViews(project: Project) {
ApplicationManager.getApplication().invokeLater {
LessonUtil.hideStandardToolwindows(project)
}
}
private fun addStatisticLessonListenerIfNeeded(currentProject: Project, lesson: Lesson) {
val statLessonListener = StatisticLessonListener(currentProject)
if (!lesson.lessonListeners.any { it is StatisticLessonListener })
lesson.addLessonListener(statLessonListener)
}
private fun openReadme(project: Project) {
val root = ProjectUtils.getProjectRoot(project)
val readme = root.findFileByRelativePath("README.md") ?: return
TextEditorWithPreview.openPreviewForFile(project, readme)
}
fun openOnboardingFromWelcomeScreen(onboarding: Lesson) {
StatisticBase.logLearnProjectOpenedForTheFirstTime(StatisticBase.LearnProjectOpeningWay.ONBOARDING_PROMOTER)
initLearnProject(null) { project ->
StartupManager.getInstance(project).runAfterOpened {
invokeLater {
if (onboarding.properties.canStartInDumbMode) {
CourseManager.instance.openLesson(project, onboarding, true)
}
else {
DumbService.getInstance(project).runWhenSmart {
CourseManager.instance.openLesson(project, onboarding, true)
}
}
}
}
}
}
fun openLearnProjectFromWelcomeScreen() {
StatisticBase.logLearnProjectOpenedForTheFirstTime(StatisticBase.LearnProjectOpeningWay.LEARN_IDE)
initLearnProject(null) { project ->
StartupManager.getInstance(project).runAfterOpened {
invokeLater {
openReadme(project)
hideOtherViews(project)
showLearnPanel(project)
CourseManager.instance.unfoldModuleOnInit = null
// Try to fix PyCharm double startup indexing :(
val openWhenSmart = {
showLearnPanel(project)
DumbService.getInstance(project).runWhenSmart {
showLearnPanel(project)
}
}
Alarm().addRequest(openWhenSmart, 500)
}
}
}
}
private fun showLearnPanel(project: Project, preferredAnchor: ToolWindowAnchor = ToolWindowAnchor.LEFT): Boolean {
val learn = learningToolWindow(project) ?: return false
if (learn.anchor != preferredAnchor && learn.type == ToolWindowType.DOCKED) {
learn.setAnchor(preferredAnchor, null)
}
learn.show()
return true
}
@RequiresEdt
private fun openLessonWhenLearnProjectStart(lesson: Lesson, myLearnProject: Project) {
if (lesson.properties.canStartInDumbMode) {
prepareAndOpenLesson(myLearnProject, lesson, withCleanup = false)
return
}
fun openLesson() {
val toolWindowManager = ToolWindowManager.getInstance(myLearnProject)
val learnToolWindow = toolWindowManager.getToolWindow(LearnToolWindowFactory.LEARN_TOOL_WINDOW)
if (learnToolWindow != null) {
DumbService.getInstance(myLearnProject).runWhenSmart {
// Try to fix PyCharm double startup indexing :(
val openWhenSmart = {
DumbService.getInstance(myLearnProject).runWhenSmart {
prepareAndOpenLesson(myLearnProject, lesson, withCleanup = false)
}
}
Alarm().addRequest(openWhenSmart, 500)
}
}
}
val startupManager = StartupManager.getInstance(myLearnProject)
if (startupManager is StartupManagerEx && startupManager.postStartupActivityPassed()) {
openLesson()
}
else {
startupManager.registerPostStartupActivity {
openLesson()
}
}
}
@Throws(IOException::class)
private fun getScratchFile(project: Project, lesson: Lesson, filename: String): VirtualFile {
val languageId = lesson.languageId ?: error("Scratch lesson ${lesson.id} should define language")
var vf: VirtualFile? = null
val languageByID = findLanguageByID(languageId)
if (CourseManager.instance.mapModuleVirtualFile.containsKey(lesson.module)) {
vf = CourseManager.instance.mapModuleVirtualFile[lesson.module]
ScratchFileService.getInstance().scratchesMapping.setMapping(vf, languageByID)
}
if (vf == null || !vf.isValid) {
//while module info is not stored
//find file if it is existed
vf = ScratchFileService.getInstance().findFile(ScratchRootType.getInstance(), filename, ScratchFileService.Option.existing_only)
if (vf != null) {
FileEditorManager.getInstance(project).closeFile(vf)
ScratchFileService.getInstance().scratchesMapping.setMapping(vf, languageByID)
}
if (vf == null || !vf.isValid) {
vf = ScratchRootType.getInstance().createScratchFile(project, filename, languageByID, "")
assert(vf != null)
}
CourseManager.instance.registerVirtualFile(lesson.module, vf!!)
}
return vf
}
private fun askSwitchToLearnProjectBack(learnProject: Project, currentProject: Project) {
Messages.showInfoMessage(currentProject,
LearnBundle.message("dialog.askToSwitchToLearnProject.message", learnProject.name),
LearnBundle.message("dialog.askToSwitchToLearnProject.title"))
}
@Throws(IOException::class)
private fun getFileInLearnProject(lesson: Lesson): VirtualFile? {
if (!lesson.properties.openFileAtStart) {
LOG.debug("${lesson.name} does not open any file at the start")
return null
}
val function = object : Computable<VirtualFile> {
override fun compute(): VirtualFile {
val learnProject = LearningUiManager.learnProject!!
val existedFile = lesson.existedFile ?: lesson.module.primaryLanguage?.projectSandboxRelativePath
val manager = ProjectRootManager.getInstance(learnProject)
if (existedFile != null) {
val root = ProjectUtils.getProjectRoot(learnProject)
val findFileByRelativePath = root.findFileByRelativePath(existedFile)
if (findFileByRelativePath != null) return findFileByRelativePath
}
val fileName = existedFile ?: lesson.fileName
var lessonVirtualFile: VirtualFile? = null
var roots = manager.contentSourceRoots
if (roots.isEmpty()) {
roots = manager.contentRoots
}
for (file in roots) {
if (file.name == fileName) {
lessonVirtualFile = file
break
}
else {
lessonVirtualFile = file.findChild(fileName)
if (lessonVirtualFile != null) {
break
}
}
}
if (lessonVirtualFile == null) {
lessonVirtualFile = roots[0].createChildData(this, fileName)
}
CourseManager.instance.registerVirtualFile(lesson.module, lessonVirtualFile)
return lessonVirtualFile
}
}
val vf = ApplicationManager.getApplication().runWriteAction(function)
assert(vf is VirtualFile)
return vf
}
private fun initLearnProject(projectToClose: Project?, postInitCallback: (learnProject: Project) -> Unit) {
val langSupport = LangManager.getInstance().getLangSupport() ?: throw Exception("Language for learning plugin is not defined")
//if projectToClose is open
findLearnProjectInOpenedProjects(langSupport)?.let {
postInitCallback(it)
return
}
if (!ApplicationManager.getApplication().isUnitTestMode && projectToClose != null)
if (!NewLearnProjectUtil.showDialogOpenLearnProject(projectToClose))
return //if user abort to open lesson in a new Project
try {
NewLearnProjectUtil.createLearnProject(projectToClose, langSupport) { learnProject ->
langSupport.applyToProjectAfterConfigure().invoke(learnProject)
LearningUiManager.learnProject = learnProject
runInEdt {
postInitCallback(learnProject)
}
}
}
catch (e: IOException) {
LOG.error(e)
}
}
private fun findLearnProjectInOpenedProjects(langSupport: LangSupport): Project? {
val openProjects = ProjectManager.getInstance().openProjects
return openProjects.firstOrNull { isLearningProject(it, langSupport) }
}
} | apache-2.0 | 95dde313624482731b65910687957659 | 40.179541 | 140 | 0.703204 | 4.88097 | false | false | false | false |
bydzodo1/batch-lemmatize-processor | src/main/kt/cz/bydzodo1/batchLemmatizationProcessor/model/CommandProvider.kt | 1 | 1448 | package cz.bydzodo1.batchLemmatizationProcessor.model
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
class CommandProvider(val settings: Settings) {
fun getCommands(files: Array<File>, pairs: MutableList<Pair<String, Path>>, tempFile: Path): ArrayList<String> {
val commands = arrayListOf<String>()
var commandBuilder = getStringBuilder()
var builderBuilded = false
files.forEach {
builderBuilded = false
val newTempFileName = tempFile.toAbsolutePath().toString() + File.separator + "tmp"+ it.name.hashCode() + ".txt"
val pathNewTempFile = Paths.get(newTempFileName)
// Files.createFile(pathNewTempFile)
val command = "\"${it.absoluteFile}\":\"$newTempFileName\""
commandBuilder.append(" ").append(command)
pairs.add(Pair(it.name, pathNewTempFile))
if (commandBuilder.length > 7000){
commands.add(commandBuilder.toString())
commandBuilder = getStringBuilder()
builderBuilded = true
}
}
if (!builderBuilded){
commands.add(commandBuilder.toString())
}
return commands
}
private fun getStringBuilder(): StringBuilder{
return StringBuilder("${settings.morphoDiTaRunTaggerPath} ${settings.MORPHODITA_OPTIONS} ${settings.taggerDataFile}")
}
} | mpl-2.0 | 4f0e73bb5918d24352e9dbb9df6e4a18 | 38.162162 | 125 | 0.642956 | 4.401216 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceSizeCheckWithIsNotEmptyIntention.kt | 2 | 2803 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
@Suppress("DEPRECATION")
class ReplaceSizeCheckWithIsNotEmptyInspection : IntentionBasedInspection<KtBinaryExpression>(
ReplaceSizeCheckWithIsNotEmptyIntention::class
) {
override fun inspectionProblemText(element: KtBinaryExpression): String {
return KotlinBundle.message("inspection.replace.size.check.with.is.not.empty.display.name")
}
}
class ReplaceSizeCheckWithIsNotEmptyIntention : ReplaceSizeCheckIntention(KotlinBundle.lazyMessage("replace.size.check.with.isnotempty")) {
override fun getTargetExpression(element: KtBinaryExpression): KtExpression? = when (element.operationToken) {
KtTokens.EXCLEQ -> when {
element.right.isZero() -> element.left
element.left.isZero() -> element.right
else -> null
}
KtTokens.GT -> if (element.right.isZero()) element.left else null
KtTokens.LT -> if (element.left.isZero()) element.right else null
KtTokens.GTEQ -> if (element.right.isOne()) element.left else null
KtTokens.LTEQ -> if (element.left.isOne()) element.right else null
else -> null
}
override fun getReplacement(expression: KtExpression, isCountCall: Boolean): Replacement {
return if (isCountCall && expression.isRange() /* Ranges don't have isNotEmpty function: KT-51560 */) {
Replacement(
targetExpression = expression,
newFunctionCall = "isEmpty()",
negate = true,
intentionTextGetter = KotlinBundle.lazyMessage("replace.size.check.with.0", "!isEmpty")
)
} else {
Replacement(
targetExpression = expression,
newFunctionCall = "isNotEmpty()",
negate = false,
intentionTextGetter = KotlinBundle.lazyMessage("replace.size.check.with.0", "isNotEmpty")
)
}
}
private fun KtExpression.isRange(): Boolean {
val receiver = resolveToCall()?.let { it.extensionReceiver ?: it.dispatchReceiver } ?: return false
return receiver.type.constructor.declarationDescriptor.safeAs<ClassDescriptor>()?.isRange() == true
}
} | apache-2.0 | c391befa61f5f04e13e08531f832eafc | 46.525424 | 158 | 0.699964 | 4.874783 | false | false | false | false |
vovagrechka/fucking-everything | phizdets/phizdetsc/src/org/jetbrains/kotlin/js/coroutine/CoroutineTransformer.kt | 3 | 3036 | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.coroutine
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.js.backend.ast.metadata.coroutineMetadata
import org.jetbrains.kotlin.js.translate.expression.InlineMetadata
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils
class CoroutineTransformer(private val program: JsProgram) : JsVisitorWithContextImpl() {
private val additionalStatementsByNode = mutableMapOf<JsNode, List<JsStatement>>()
override fun endVisit(x: JsExpressionStatement, ctx: JsContext<in JsStatement>) {
additionalStatementsByNode.remove(x)?.forEach { ctx.addNext(it) }
super.endVisit(x, ctx)
}
override fun endVisit(x: JsVars, ctx: JsContext<in JsStatement>) {
for (v in x.vars) {
additionalStatementsByNode.remove(v)?.forEach { ctx.addNext(it) }
}
super.endVisit(x, ctx)
}
override fun visit(x: JsExpressionStatement, ctx: JsContext<*>): Boolean {
val expression = x.expression
val assignment = JsAstUtils.decomposeAssignment(expression)
if (assignment != null) {
val (lhs, rhs) = assignment
val function = rhs as? JsFunction ?: InlineMetadata.decompose(rhs)?.function
if (function?.coroutineMetadata != null) {
val name = ((lhs as? JsNameRef)?.name ?: function.name)?.ident
additionalStatementsByNode[x] = CoroutineFunctionTransformer(program, function, name).transform()
return false
}
}
else if (expression is JsFunction) {
if (expression.coroutineMetadata != null) {
additionalStatementsByNode[x] = CoroutineFunctionTransformer(program, expression, expression.name?.ident).transform()
return false
}
}
return super.visit(x, ctx)
}
override fun visit(x: JsVars.JsVar, ctx: JsContext<*>): Boolean {
val initExpression = x.initExpression
if (initExpression != null) {
val function = initExpression as? JsFunction ?: InlineMetadata.decompose(initExpression)?.function
if (function?.coroutineMetadata != null) {
val name = x.name.ident
additionalStatementsByNode[x] = CoroutineFunctionTransformer(program, function, name).transform()
return false
}
}
return super.visit(x, ctx)
}
}
| apache-2.0 | 13d1824ebcf52ef147f0c341018a676b | 41.166667 | 133 | 0.667655 | 4.477876 | false | false | false | false |
PaleoCrafter/VanillaImmersion | src/main/kotlin/de/mineformers/vanillaimmersion/immersion/EnchantingHandler.kt | 1 | 7895 | package de.mineformers.vanillaimmersion.immersion
import de.mineformers.vanillaimmersion.tileentity.EnchantingTableLogic
import de.mineformers.vanillaimmersion.util.Rays
import de.mineformers.vanillaimmersion.util.Rendering
import de.mineformers.vanillaimmersion.util.div
import de.mineformers.vanillaimmersion.util.minus
import de.mineformers.vanillaimmersion.util.plus
import net.minecraft.client.Minecraft
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.util.EnumHand
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.MathHelper
import net.minecraft.util.math.Vec3d
import net.minecraftforge.event.entity.player.PlayerInteractEvent
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
import net.minecraftforge.fml.relauncher.Side
import net.minecraftforge.fml.relauncher.SideOnly
import javax.vecmath.Matrix4f
import javax.vecmath.Vector3f
import javax.vecmath.Vector4f
/**
* Handles interaction with the enchantment table's book "GUI".
*/
object EnchantingHandler {
/**
* Handles interaction with enchantment tables when a right click with an empty hand happens.
*/
@SubscribeEvent
@SideOnly(Side.CLIENT)
fun onRightClickEmpty(event: PlayerInteractEvent.RightClickEmpty) {
if (event.hand == EnumHand.OFF_HAND)
return
onInteract(event, Minecraft.getMinecraft().objectMouseOver?.hitVec ?: Vec3d.ZERO)
}
/**
* Handles interaction with enchantment tables when a right click on a block happens.
*/
@SubscribeEvent
fun onRightClickBlock(event: PlayerInteractEvent.RightClickBlock) {
if (event.hand == EnumHand.OFF_HAND || event.hitVec == null)
return
onInteract(event, event.hitVec)
}
/**
* Handles interaction with any enchantment tables near a player.
* Will scan a 7x7x7 cube around the player to check against since we can't rely
* on the currently hovered block being the enchantment table.
*/
private fun onInteract(event: PlayerInteractEvent, hovered: Vec3d) {
val player = event.entityPlayer
val surroundingBlocks = BlockPos.getAllInBox(player.position - BlockPos(3, 3, 3), player.position + BlockPos(3, 3, 3))
// Filter all enchantment tables out of the surrounding blocks and sort them by distance to the player
// The sorting is required because otherwise an enchantment table further away might be prioritized.
val enchantingTables =
surroundingBlocks
.filter { player.world.getTileEntity(it) is EnchantingTableLogic }
.sortedBy { player.getDistanceSq(it) }
.map { player.world.getTileEntity(it) as EnchantingTableLogic }
if (enchantingTables.isEmpty())
return
val partialTicks = Rendering.partialTicks
val origin = Rendering.getEyePosition(player, partialTicks)
val direction = player.getLook(partialTicks)
val hoverDistance = origin.squareDistanceTo(hovered)
for (te in enchantingTables) {
// If the active page is smaller than 0 (normally -1), the book is closed.
if (te.page < 0)
continue
// Try to hit the left page first, then the right one
if (tryHit(te, player, origin, direction, hoverDistance, partialTicks, false)) {
if (event.isCancelable)
event.isCanceled = true
return
}
if (tryHit(te, player, origin, direction, hoverDistance, partialTicks, true)) {
if (event.isCancelable)
event.isCanceled = true
return
}
}
}
/**
* Sends a ray through the specified enchantment table's left or right page.
* Will invoke the desired action for the appropriate page if the ray intersected it.
*/
private fun tryHit(te: EnchantingTableLogic,
player: EntityPlayer, origin: Vec3d, direction: Vec3d, hoverDistance: Double,
partialTicks: Float, right: Boolean): Boolean {
val quad = listOf(
Vec3d(.0, .0, .0), Vec3d(6 * 0.0625, .0, .0),
Vec3d(6 * 0.0625, 8 * 0.0625, .0), Vec3d(.0, 8 * 0.0625, .0)
)
val matrix = calculateMatrix(te, partialTicks, right)
val hit = Rays.rayTraceQuad(origin, direction, quad, matrix)
val distanceCheck =
if (hit == null)
false
else {
val v = Vector4f(hit.x.toFloat(), hit.y.toFloat(), hit.z.toFloat(), 1f)
matrix.transform(v)
origin.squareDistanceTo(v.x.toDouble(), v.y.toDouble(), v.z.toDouble()) < hoverDistance
}
if (hit != null && distanceCheck) {
// The "GUI" pixel position of the hit depends on the clicked page since we have two different
// reference corners
val pixelHit =
if (right)
Vec3d(0.0, 125.0, 0.0) - Vec3d(-hit.x, hit.y, 0.0) / 0.004
else
Vec3d(94.0, 125.0, 0.0) - Vec3d(hit.x, hit.y, 0.0) / 0.004
if (!player.world.isRemote) {
handleUIHit(te, right, player, pixelHit.x, pixelHit.y)
} else {
player.swingArm(EnumHand.MAIN_HAND)
}
return true
}
return false
}
/**
* Handles a click on the enchantment table's "GUI", performing the appropriate action.
*/
private fun handleUIHit(table: EnchantingTableLogic, right: Boolean, player: EntityPlayer, x: Double, y: Double) {
table.performPageAction(player, table.page + if (right) 1 else 0, x, y)
}
/**
* Calculates the transformation matrix for the left or right page of an enchantment table.
* The inverse can be multiplied with any point in the table's local coordinate space to get its position relative
* to the respective page.
*/
private fun calculateMatrix(te: EnchantingTableLogic, partialTicks: Float, right: Boolean): Matrix4f {
// See the enchantment table's renderer, we need to reproduce the transformations exactly
val hover = te.tickCount + partialTicks
var dYaw: Float = te.bookRotation - te.bookRotationPrev
while (dYaw >= Math.PI) {
dYaw -= Math.PI.toFloat() * 2f
}
while (dYaw < -Math.PI) {
dYaw += Math.PI.toFloat() * 2f
}
val yaw = te.bookRotationPrev + dYaw * partialTicks
var flipLeft = te.pageFlipPrev + (te.pageFlip - te.pageFlipPrev) * partialTicks + 0.25f
flipLeft = (flipLeft - flipLeft.toInt()) * 1.6f - 0.3f
if (flipLeft < 0.0f) {
flipLeft = 0.0f
}
if (flipLeft > 1.0f) {
flipLeft = 1.0f
}
val spread = te.bookSpreadPrev + (te.bookSpread - te.bookSpreadPrev) * partialTicks
val breath = (MathHelper.sin(hover * 0.02f) * 0.1f + 1.25f) * spread
val rotation = breath - breath * 2.0f * flipLeft
// Again, see the renderer, the transformations are applied in the same order
val result = Matrix4f()
result.setIdentity()
val tmp = Matrix4f()
tmp.set(Vector3f(te.pos.x.toFloat(), te.pos.y.toFloat(), te.pos.z.toFloat()))
result.mul(tmp)
tmp.set(Vector3f(0.5f, 0.75f + 1.6f * 0.0625f + 0.0001f + MathHelper.sin(hover * 0.1f) * 0.01f, 0.5f))
result.mul(tmp)
tmp.rotY(-yaw)
result.mul(tmp)
tmp.rotZ(80 * Math.PI.toFloat() / 180)
result.mul(tmp)
tmp.set(Vector3f(MathHelper.sin(breath) / 16, 0f, 0f))
result.mul(tmp)
tmp.rotY(if (right) rotation else -rotation)
result.mul(tmp)
tmp.set(Vector3f(0f, -0.25f, 0f))
result.mul(tmp)
return result
}
} | mit | e37aa2b55d095f72d8471fdb1ae510e4 | 41.224599 | 126 | 0.627486 | 4.042499 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/gradle/gradle-native/src/org/jetbrains/kotlin/idea/gradle/native/KotlinNativeABICompatibilityChecker.kt | 1 | 11515 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.gradle.native
import com.intellij.ProjectTopics
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ReadAction.nonBlocking
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.guessProjectDir
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.util.PathUtilRt
import com.intellij.util.concurrency.AppExecutorUtil
import org.jetbrains.concurrency.CancellablePromise
import org.jetbrains.kotlin.ide.konan.NativeKlibLibraryInfo
import org.jetbrains.kotlin.idea.caches.project.getModuleInfosFromIdeaModel
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.gradle.configuration.klib.KotlinNativeLibraryNameUtil.isGradleLibraryName
import org.jetbrains.kotlin.idea.gradle.configuration.klib.KotlinNativeLibraryNameUtil.parseIDELibraryName
import org.jetbrains.kotlin.idea.klib.KlibCompatibilityInfo.IncompatibleMetadata
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.versions.UnsupportedAbiVersionNotificationPanelProvider
import org.jetbrains.kotlin.konan.library.KONAN_STDLIB_NAME
/** TODO: merge [KotlinNativeABICompatibilityChecker] in the future with [UnsupportedAbiVersionNotificationPanelProvider], KT-34525 */
class KotlinNativeABICompatibilityChecker : StartupActivity {
override fun runActivity(project: Project) {
KotlinNativeABICompatibilityCheckerService.getInstance(project).runActivity()
}
}
class KotlinNativeABICompatibilityCheckerService(private val project: Project): Disposable {
fun runActivity() {
project.messageBus.connect(this).subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
// run when project roots are changes, e.g. on project import
validateKotlinNativeLibraries()
}
})
validateKotlinNativeLibraries()
}
private sealed class LibraryGroup(private val ordinal: Int) : Comparable<LibraryGroup> {
override fun compareTo(other: LibraryGroup) = when {
this == other -> 0
this is FromDistribution && other is FromDistribution -> kotlinVersion.compareTo(other.kotlinVersion)
else -> ordinal.compareTo(other.ordinal)
}
data class FromDistribution(val kotlinVersion: String) : LibraryGroup(0)
object ThirdParty : LibraryGroup(1)
object User : LibraryGroup(2)
}
private val cachedIncompatibleLibraries = mutableSetOf<String>()
internal fun validateKotlinNativeLibraries() {
if (isUnitTestMode() || project.isDisposed) return
val backgroundJob: Ref<CancellablePromise<*>> = Ref()
val disposable = Disposable {
backgroundJob.get()?.let(CancellablePromise<*>::cancel)
}
Disposer.register(this, disposable)
backgroundJob.set(
nonBlocking<List<Notification>> {
val librariesToNotify = getLibrariesToNotifyAbout()
prepareNotifications(librariesToNotify)
}
.finishOnUiThread(ModalityState.defaultModalityState()) { notifications ->
notifications.forEach {
it.notify(project)
}
}
.expireWith(this) // cancel job when project is disposed
.coalesceBy(this@KotlinNativeABICompatibilityCheckerService) // cancel previous job when new one is submitted
.withDocumentsCommitted(project)
.submit(AppExecutorUtil.getAppExecutorService())
.onProcessed {
backgroundJob.set(null)
Disposer.dispose(disposable)
})
}
private fun getLibrariesToNotifyAbout(): Map<String, NativeKlibLibraryInfo> {
val incompatibleLibraries = getModuleInfosFromIdeaModel(project)
.filterIsInstance<NativeKlibLibraryInfo>()
.filter { !it.compatibilityInfo.isCompatible }
.associateBy { it.libraryRoot }
val newEntries = if (cachedIncompatibleLibraries.isNotEmpty())
incompatibleLibraries.filterKeys { it !in cachedIncompatibleLibraries }
else
incompatibleLibraries
cachedIncompatibleLibraries.clear()
cachedIncompatibleLibraries.addAll(incompatibleLibraries.keys)
return newEntries
}
private fun prepareNotifications(librariesToNotify: Map<String, NativeKlibLibraryInfo>): List<Notification> {
if (librariesToNotify.isEmpty())
return emptyList()
val librariesByGroups = HashMap<Pair<LibraryGroup, Boolean>, MutableList<Pair<String, String>>>()
librariesToNotify.forEach { (libraryRoot, libraryInfo) ->
val isOldMetadata = (libraryInfo.compatibilityInfo as? IncompatibleMetadata)?.isOlder ?: true
val (libraryName, libraryGroup) = parseIDELibraryName(libraryInfo)
librariesByGroups.computeIfAbsent(libraryGroup to isOldMetadata) { mutableListOf() } += libraryName to libraryRoot
}
return librariesByGroups.keys.sortedWith(
compareBy(
{ (libraryGroup, _) -> libraryGroup },
{ (_, isOldMetadata) -> isOldMetadata }
)
).map { key ->
val (libraryGroup, isOldMetadata) = key
val libraries =
librariesByGroups.getValue(key).sortedWith(compareBy(LIBRARY_NAME_COMPARATOR) { (libraryName, _) -> libraryName })
val message = when (libraryGroup) {
is LibraryGroup.FromDistribution -> {
val libraryNamesInOneLine = libraries
.joinToString(limit = MAX_LIBRARY_NAMES_IN_ONE_LINE) { (libraryName, _) -> libraryName }
val text = KotlinGradleNativeBundle.message(
"error.incompatible.libraries",
libraries.size, libraryGroup.kotlinVersion, libraryNamesInOneLine
)
val explanation = when (isOldMetadata) {
true -> KotlinGradleNativeBundle.message("error.incompatible.libraries.older")
false -> KotlinGradleNativeBundle.message("error.incompatible.libraries.newer")
}
val recipe = KotlinGradleNativeBundle.message(
"error.incompatible.libraries.recipe",
KotlinPluginLayout.instance.standaloneCompilerVersion.rawVersion
)
"$text\n\n$explanation\n$recipe"
}
is LibraryGroup.ThirdParty -> {
val text = when (isOldMetadata) {
true -> KotlinGradleNativeBundle.message("error.incompatible.3p.libraries.older", libraries.size)
false -> KotlinGradleNativeBundle.message("error.incompatible.3p.libraries.newer", libraries.size)
}
val librariesLineByLine = libraries.joinToString(separator = "\n") { (libraryName, _) -> libraryName }
val recipe = KotlinGradleNativeBundle.message(
"error.incompatible.3p.libraries.recipe",
KotlinPluginLayout.instance.standaloneCompilerVersion.rawVersion
)
"$text\n$librariesLineByLine\n\n$recipe"
}
is LibraryGroup.User -> {
val projectRoot = project.guessProjectDir()?.canonicalPath
fun getLibraryTextToPrint(libraryNameAndRoot: Pair<String, String>): String {
val (libraryName, libraryRoot) = libraryNameAndRoot
val relativeRoot = projectRoot?.let {
libraryRoot.substringAfter(projectRoot)
.takeIf { it != libraryRoot }
?.trimStart('/', '\\')
?.let { "${'$'}project/$it" }
} ?: libraryRoot
return KotlinGradleNativeBundle.message("library.name.0.at.1.relative.root", libraryName, relativeRoot)
}
val text = when (isOldMetadata) {
true -> KotlinGradleNativeBundle.message("error.incompatible.user.libraries.older", libraries.size)
false -> KotlinGradleNativeBundle.message("error.incompatible.user.libraries.newer", libraries.size)
}
val librariesLineByLine = libraries.joinToString(separator = "\n", transform = ::getLibraryTextToPrint)
val recipe = KotlinGradleNativeBundle.message(
"error.incompatible.user.libraries.recipe",
KotlinPluginLayout.instance.standaloneCompilerVersion.rawVersion
)
"$text\n$librariesLineByLine\n\n$recipe"
}
}
Notification(
NOTIFICATION_GROUP_ID,
NOTIFICATION_TITLE,
StringUtilRt.convertLineSeparators(message, "<br/>"),
NotificationType.ERROR
)
}
}
// returns pair of library name and library group
private fun parseIDELibraryName(libraryInfo: NativeKlibLibraryInfo): Pair<String, LibraryGroup> {
val ideLibraryName = libraryInfo.library.name?.takeIf(String::isNotEmpty)
if (ideLibraryName != null) {
parseIDELibraryName(ideLibraryName)?.let { (kotlinVersion, libraryName) ->
return libraryName to LibraryGroup.FromDistribution(kotlinVersion)
}
if (isGradleLibraryName(ideLibraryName))
return ideLibraryName to LibraryGroup.ThirdParty
}
return (ideLibraryName ?: PathUtilRt.getFileName(libraryInfo.libraryRoot)) to LibraryGroup.User
}
override fun dispose() {
}
companion object {
private val LIBRARY_NAME_COMPARATOR = Comparator<String> { libraryName1, libraryName2 ->
when {
libraryName1 == libraryName2 -> 0
libraryName1 == KONAN_STDLIB_NAME -> -1 // stdlib must go the first
libraryName2 == KONAN_STDLIB_NAME -> 1
else -> libraryName1.compareTo(libraryName2)
}
}
private const val MAX_LIBRARY_NAMES_IN_ONE_LINE = 5
private val NOTIFICATION_TITLE get() = KotlinGradleNativeBundle.message("error.incompatible.libraries.title")
private const val NOTIFICATION_GROUP_ID = "Incompatible Kotlin/Native libraries"
fun getInstance(project: Project): KotlinNativeABICompatibilityCheckerService = project.service()
}
}
| apache-2.0 | 3797558ff55e645550919bb21bbcfce0 | 47.179916 | 158 | 0.647069 | 5.536058 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/order-creation.kt | 1 | 6840 | package alraune
import alraune.entity.*
import aplight.GelPropValueVisitor
import pieces100.*
import vgrechka.*
import java.sql.Timestamp
fun dateTimeField1(title: String, initial: Timestamp? = null, min: Long, minToShowInCalendar: Long): DateTimeField__killme {
val minError = t("TOTE", "Это слишком мало времени")
val max = System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000
val maxError = t("TOTE", "Слишком долго это")
return DateTimeField__killme(title, initial = initial, mandatory = true,
min = min, minToShowInCalendar = minToShowInCalendar, minError = minError, max = max, maxError = maxError)
.prop(Order::deadline)
}
@GelPropValueVisitor
class OrderFields3__killme : BunchOfFields {
val contactName: TextField__killme = TextField__killme(t("TOTE", "Контактное имя"), {AlValidators.string(it, 3, 50)}).prop(listOf(Order::data, Order.Data::contactName))
val email: TextField__killme = Fields.email().prop(listOf(Order::data, Order.Data::email))
val phone: TextField__killme = Fields.phone().prop(listOf(Order::data, Order.Data::phone))
val documentTitle: TextField__killme = Fields.title(t("TOTE", "Тема работы (задание)")).prop(listOf(Order::data, Order.Data::documentTitle))
val documentDetails: TextField__killme = Fields.details().prop(listOf(Order::data, Order.Data::documentDetails))
val numPages: TextField__killme = TextField__killme(t("TOTE", "Страниц"), {AlValidators.integer(it, 3, 500, true)}).prop(listOf(Order::data, Order.Data::numPages))
val numSources: TextField__killme = TextField__killme(t("TOTE", "Источников"), {AlValidators.integer(it, 0, 50, true)}).prop(listOf(Order::data, Order.Data::numSources))
val documentType: EnumField2<Order.DocumentType> = EnumField2(t("TOTE", "Тип документа"), Order.DocumentType.values(), Order.DocumentType.Abstract).prop(Order::data, Order.Data::documentType)
val documentCategory: DocumentCategoryField = DocumentCategoryField()
val deadline: DateTimeField__killme = dateTimeField1(t("TOTE", "Срок"),
min = TimePile.hoursFromRealNow_ms(4L), minToShowInCalendar = TimePile.plusHours_ms(TimePile.hoursFromRealNow_ms(4L), 1L))
}
//class SpitOrderCreationFormPage_A1 : SpitPage {
// override fun isPrivate() = false
//
// override fun spit() {
// redirectToLandingIfSiteIsNot(AlSite.Customer)
//
// val fs = useFields(OrderFields2(), FieldSource.Initial())
// SpitOrderCreationFormPage_Tampering(fs)
// btfReplaceElement_withOrderCreationFormPage(fs)
// spitUsualPage(div().id(OrderCreation.contentDomid))
// }
//}
//fun btfReplaceElement_withOrderCreationFormPage(fields: OrderFields2) {
// btfReplaceElement_withShitComposedInNewContext1(OrderCreation.contentDomid) {
// div().id(OrderCreation.contentDomid).with {
// oo(div().className("container").with {
// oo(pageHeader(t("TOTE", "Йобаный Заказ")))
// oo(composeErrorBanner())
// oo(composeOrderParamsFormBody(fields))
// oo(dance(ButtonBarWithTicker()
// .addSubmitFormButton(
// MinimalButtonShit(AlText.proceed, AlButtonStyle.Primary,
// ServantHandle.JsonizedInstance.of(ServeCreateOrder())))
// .tickerLocation(Rightness.Right)))
// })
// }
// }
//}
//class ServeCreateOrder_A1 : Servant {
// override fun ignite() {
// val fs = useFields(OrderFields2(), FieldSource.Post())
//
// if (anyFieldErrors(fs))
// return btfReplaceElement_withOrderCreationFormPage(fs)
//
// val orderUuid = largeUuid()
//
// val order = AlUAOrder().fill(
// uuid = orderUuid,
// state = AlUAOrderState.CustomerDraft,
// email = fs.email.sanitized(),
// contactName = fs.contactName.sanitized(),
// phone = fs.phone.sanitized(),
// documentType = fs.documentType.value(),
// documentTitle = fs.documentTitle.sanitized(),
// documentDetails = fs.documentDetails.sanitized(),
// documentCategory = fs.documentCategory.value(),
// numPages = Integer.parseInt(fs.numPages.sanitized()),
// numSources = Integer.parseInt(fs.numSources.sanitized()),
// adminNotes = "",
// rejectionReason = "",
// wasRejectionReason = "",
// dataPile = OrderDataPile().fill(
// deadline = fs.deadline.value()!!))
// rctx2.db.insertEntity(order)
//
// rctx2.db.insertEntity(AlOperation().fill(
// orderId = order.id,
// dataPile = AlOperation_Order_V1().fill(
// time = order.createdAt,
// site = rctx2.site(),
// user = rctx2.maybeUser(),
// operationCode = AlOperation_Order_V1.Code.CreateOrder,
// shortOperationDescription = "Create order",
// orderBeforeOperation = null,
// orderAfterOperation = order)))
//
// btfSetLocationHref(SpitOrderPage::class) {
// it.uuid.set(orderUuid)}
// }
//}
//fun composeOrderParamsFormBody(fields: OrderFields2) = div().with {
// oo(div().className("row").with {
// oo(div().className("col-md-4").with {
// oo(fields.contactName.compose())
// })
// oo(div().className("col-md-4").with {
// oo(fields.email.compose())
// })
// oo(div().className("col-md-4").with {
// oo(fields.phone.compose())
// })
// })
//
// oo(div().className("row").with {
// oo(div().className("col-md-4").with {
// val values = AlUADocumentType.values()
// oo(TextControlBuilder().begin(AlText.documentType, FTBProps.documentType,
// ValidationResult(fields.documentType.value().name, null))
// .select(values.map {TitledValue(it.name, it.title)})
// .compose())
// })
// oo(div().className("col-md-8").with {
// oo(fields.documentCategory.compose().render())
// })
// })
//
// oo(div().with {
// oo(fields.documentTitle.compose())
// })
//
// oo(div().className("row").with {
// oo(div().className("col-md-4").with {
// oo(fields.numPages.compose())
// })
// oo(div().className("col-md-4").with {
// oo(fields.numSources.compose())
// })
// oo(div().className("col-md-4").with {
// oo(fields.deadline.compose().render())
// })
// })
//
// oo(div().with {
// oo(fields.documentDetails.compose())
// })
//}
| apache-2.0 | 9ede189774d01b7a7080c7b782480e4b | 37.232955 | 195 | 0.603656 | 3.627493 | false | false | false | false |
androidx/androidx | fragment/fragment/src/androidTest/java/androidx/fragment/app/MenuVisibilityFragmentTest.kt | 3 | 5166 | /*
* 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.fragment.app
import android.os.Bundle
import androidx.fragment.test.R
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.testutils.withActivity
import androidx.testutils.withUse
import com.google.common.truth.Truth.assertWithMessage
import leakcanary.DetectLeaksAfterTestSuccess
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@MediumTest
@RunWith(AndroidJUnit4::class)
class MenuVisibilityFragmentTest {
@get:Rule
val rule = DetectLeaksAfterTestSuccess()
@Test
fun setMenuVisibility() {
withUse(ActivityScenario.launch(SimpleContainerActivity::class.java)) {
val fm = withActivity { supportFragmentManager }
val fragment = MenuVisibilityFragment()
assertWithMessage("Menu visibility should start out true")
.that(fragment.isMenuVisible)
.isTrue()
withActivity {
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commitNow()
}
assertWithMessage("Menu visibility should be true")
.that(fragment.isMenuVisible)
.isTrue()
withActivity {
fm.beginTransaction()
.remove(fragment)
.commitNow()
}
assertWithMessage("Menu visibility should be false")
.that(fragment.isMenuVisible)
.isFalse()
}
}
@Test
fun setChildMenuVisibilityTrue() {
withUse(ActivityScenario.launch(SimpleContainerActivity::class.java)) {
val fm = withActivity { supportFragmentManager }
val parentFragment = ParentMenuVisibilityFragment()
val childFragment = parentFragment.childFragment
withActivity {
fm.beginTransaction()
.add(R.id.fragmentContainer, parentFragment)
.commitNow()
}
assertWithMessage("ChildFragment Menu Visibility should be true")
.that(childFragment.isMenuVisible)
.isTrue()
withActivity {
fm.beginTransaction()
.remove(parentFragment)
.commitNow()
}
assertWithMessage("ChildFragment Menu Visibility should be false")
.that(childFragment.isMenuVisible)
.isFalse()
}
}
@Test
fun setChildMenuVisibilityFalse() {
withUse(ActivityScenario.launch(SimpleContainerActivity::class.java)) {
val fm = withActivity { supportFragmentManager }
val parentFragment = MenuVisibilityFragment()
val childFragment = StrictFragment()
childFragment.setMenuVisibility(false)
withActivity {
fm.beginTransaction()
.add(R.id.fragmentContainer, parentFragment)
.commitNow()
parentFragment.childFragmentManager.beginTransaction()
.add(childFragment, "childFragment")
.commitNow()
}
assertWithMessage("ParentFragment Men Visibility should be true")
.that(parentFragment.isMenuVisible)
.isTrue()
assertWithMessage("ChildFragment Menu Visibility should be false")
.that(childFragment.isMenuVisible)
.isFalse()
withActivity {
fm.beginTransaction()
.remove(parentFragment)
.commitNow()
}
assertWithMessage("ChildFragment Menu Visibility should be false")
.that(childFragment.isMenuVisible)
.isFalse()
}
}
}
class MenuVisibilityFragment : StrictFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setMenuVisibility(true)
}
override fun onStop() {
super.onStop()
setMenuVisibility(false)
}
}
class ParentMenuVisibilityFragment : StrictFragment() {
val childFragment = MenuVisibilityFragment()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
childFragmentManager.beginTransaction()
.add(childFragment, "childFragment")
.commitNow()
}
}
| apache-2.0 | 42293f277b39bd93132ac17ec2d4b417 | 30.5 | 78 | 0.617693 | 5.596966 | false | true | false | false |
androidx/androidx | paging/paging-common/src/test/kotlin/androidx/paging/ContiguousPagedListTest.kt | 3 | 37450 | /*
* 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.
*/
@file:Suppress("DEPRECATION")
package androidx.paging
import androidx.paging.ItemKeyedDataSourceTest.ItemDataSource
import androidx.paging.LoadState.Error
import androidx.paging.LoadState.Loading
import androidx.paging.LoadState.NotLoading
import androidx.paging.LoadType.APPEND
import androidx.paging.LoadType.PREPEND
import androidx.paging.PagedList.BoundaryCallback
import androidx.paging.PagedList.Callback
import androidx.paging.PagedList.Config
import androidx.paging.PagingSource.LoadResult.Page
import androidx.testutils.TestDispatcher
import org.mockito.kotlin.mock
import org.mockito.kotlin.reset
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoMoreInteractions
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
@RunWith(Parameterized::class)
class ContiguousPagedListTest(private val placeholdersEnabled: Boolean) {
private val mainThread = TestDispatcher()
private val backgroundThread = TestDispatcher()
private class Item(position: Int) {
val pos: Int = position
val name: String = "Item $position"
override fun toString(): String = name
}
/**
* Note: we use a non-positional dataSource here because we want to avoid the initial load size
* and alignment restrictions. These tests were written before positional+contiguous enforced
* these behaviors.
*/
private inner class TestPagingSource(
val listData: List<Item> = ITEMS
) : PagingSource<Int, Item>() {
var invalidData = false
override fun getRefreshKey(state: PagingState<Int, Item>): Int? {
return state.anchorPosition
?.let { anchorPosition -> state.closestItemToPosition(anchorPosition)?.pos }
?: 0
}
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Item> {
return when (params) {
is LoadParams.Refresh -> loadInitial(params)
is LoadParams.Prepend -> loadBefore(params)
is LoadParams.Append -> loadAfter(params)
}
}
fun enqueueErrorForIndex(index: Int) {
errorIndices.add(index)
}
val errorIndices = mutableListOf<Int>()
private fun loadInitial(params: LoadParams<Int>): LoadResult<Int, Item> {
val initPos = params.key ?: 0
val start = maxOf(initPos - params.loadSize / 2, 0)
val result = getClampedRange(start, start + params.loadSize)
if (invalidData) {
invalidData = false
return LoadResult.Invalid()
}
return when {
result == null -> LoadResult.Error(EXCEPTION)
placeholdersEnabled -> Page(
data = result,
prevKey = result.firstOrNull()?.pos,
nextKey = result.lastOrNull()?.pos,
itemsBefore = start,
itemsAfter = listData.size - result.size - start
)
else -> Page(
data = result,
prevKey = result.firstOrNull()?.pos,
nextKey = result.lastOrNull()?.pos
)
}
}
private fun loadAfter(params: LoadParams<Int>): LoadResult<Int, Item> {
val result = getClampedRange(params.key!! + 1, params.key!! + 1 + params.loadSize)
?: return LoadResult.Error(EXCEPTION)
if (invalidData) {
invalidData = false
return LoadResult.Invalid()
}
return Page(
data = result,
prevKey = if (result.isNotEmpty()) result.first().pos else null,
nextKey = if (result.isNotEmpty()) result.last().pos else null
)
}
private fun loadBefore(params: LoadParams<Int>): LoadResult<Int, Item> {
val result = getClampedRange(params.key!! - params.loadSize, params.key!!)
?: return LoadResult.Error(EXCEPTION)
if (invalidData) {
invalidData = false
return LoadResult.Invalid()
}
return Page(
data = result,
prevKey = result.firstOrNull()?.pos,
nextKey = result.lastOrNull()?.pos
)
}
private fun getClampedRange(startInc: Int, endExc: Int): List<Item>? {
val matching = errorIndices.filter { it in startInc until endExc }
if (matching.isNotEmpty()) {
// found indices with errors enqueued - fail to load them
errorIndices.removeAll(matching)
return null
}
return listData.subList(maxOf(0, startInc), minOf(listData.size, endExc))
}
}
private fun PagingSource<*, Item>.enqueueErrorForIndex(index: Int) {
(this as TestPagingSource).enqueueErrorForIndex(index)
}
private fun <E : Any> PagedList<E>.withLoadStateCapture(
desiredType: LoadType,
callback: (list: MutableList<StateChange>) -> Unit,
) {
val list = mutableListOf<StateChange>()
val listener = { type: LoadType, state: LoadState ->
if (type == desiredType) {
list.add(StateChange(type, state))
}
}
addWeakLoadStateListener(listener)
callback(list)
// Note: Referencing listener here prevents it from getting gc'd before the test finishes.
removeWeakLoadStateListener(listener)
}
private fun verifyRange(start: Int, count: Int, actual: PagedStorage<Item>) {
if (placeholdersEnabled) {
// assert nulls + content
val expected = arrayOfNulls<Item>(ITEMS.size)
System.arraycopy(ITEMS.toTypedArray(), start, expected, start, count)
assertEquals(expected.toList(), actual)
val expectedTrailing = ITEMS.size - start - count
assertEquals(ITEMS.size, actual.size)
assertEquals(start, actual.placeholdersBefore)
assertEquals(expectedTrailing, actual.placeholdersAfter)
} else {
assertEquals(ITEMS.subList(start, start + count), actual)
assertEquals(count, actual.size)
assertEquals(0, actual.placeholdersBefore)
assertEquals(0, actual.placeholdersAfter)
}
assertEquals(count, actual.storageCount)
}
private fun verifyRange(start: Int, count: Int, actual: PagedList<Item>) {
verifyRange(start, count, actual.storage)
assertEquals(count, actual.loadedCount)
}
private fun PagingSource<Int, Item>.getInitialPage(
initialKey: Int,
loadSize: Int
): Page<Int, Item> = runBlocking {
val result = load(
PagingSource.LoadParams.Refresh(
initialKey,
loadSize,
placeholdersEnabled,
)
)
result as? Page ?: throw RuntimeException("Unexpected load failure")
}
private fun createCountedPagedList(
initialPosition: Int?,
pageSize: Int = 20,
initLoadSize: Int = 40,
prefetchDistance: Int = 20,
listData: List<Item> = ITEMS,
boundaryCallback: BoundaryCallback<Item>? = null,
maxSize: Int = Config.MAX_SIZE_UNBOUNDED,
pagingSource: PagingSource<Int, Item> = TestPagingSource(listData)
): PagedList<Item> {
val initialPage = pagingSource.getInitialPage(
initialPosition ?: 0,
initLoadSize
)
val config = Config.Builder()
.setPageSize(pageSize)
.setInitialLoadSizeHint(initLoadSize)
.setPrefetchDistance(prefetchDistance)
.setMaxSize(maxSize)
.setEnablePlaceholders(placeholdersEnabled)
.build()
return PagedList.Builder(pagingSource, initialPage, config)
.setBoundaryCallback(boundaryCallback)
.setFetchDispatcher(backgroundThread)
.setNotifyDispatcher(mainThread)
.setInitialKey(initialPosition)
.build()
}
@Test
fun construct() {
val pagedList = createCountedPagedList(0)
verifyRange(0, 40, pagedList)
}
@Test
fun getDataSource() {
// Create a pagedList with a pagingSource directly.
val pagedListWithPagingSource = createCountedPagedList(0)
@Suppress("DEPRECATION")
assertFailsWith<IllegalStateException> { pagedListWithPagingSource.dataSource }
@Suppress("DEPRECATION")
val pagedListWithDataSource = PagedList.Builder(ItemDataSource(), 10).build()
@Suppress("DEPRECATION")
assertTrue(pagedListWithDataSource.dataSource is ItemDataSource)
// snapshot keeps same DataSource
@Suppress("DEPRECATION")
assertSame(
pagedListWithDataSource.dataSource,
(pagedListWithDataSource.snapshot() as SnapshotPagedList<*>).dataSource
)
}
@Test
fun getPagingSource() {
val pagedList = createCountedPagedList(0)
assertTrue(pagedList.pagingSource is TestPagingSource)
// snapshot keeps same DataSource
@Suppress("DEPRECATION")
assertSame(
pagedList.pagingSource,
(pagedList.snapshot() as SnapshotPagedList<Item>).pagingSource
)
}
@Test(expected = IndexOutOfBoundsException::class)
fun loadAroundNegative() {
val pagedList = createCountedPagedList(0)
pagedList.loadAround(-1)
}
@Test(expected = IndexOutOfBoundsException::class)
fun loadAroundTooLarge() {
val pagedList = createCountedPagedList(0)
pagedList.loadAround(pagedList.size)
}
private fun verifyCallback(
callback: Callback,
countedPosition: Int,
uncountedPosition: Int
) {
if (placeholdersEnabled) {
verify(callback).onChanged(countedPosition, 20)
} else {
verify(callback).onInserted(uncountedPosition, 20)
}
}
private fun verifyCallback(callback: Callback, position: Int) {
verifyCallback(callback, position, position)
}
private fun verifyDropCallback(
callback: Callback,
countedPosition: Int,
uncountedPosition: Int
) {
if (placeholdersEnabled) {
verify(callback).onChanged(countedPosition, 20)
} else {
verify(callback).onRemoved(uncountedPosition, 20)
}
}
@Test
fun append() {
val pagedList = createCountedPagedList(0)
val callback = mock<Callback>()
pagedList.addWeakCallback(callback)
verifyRange(0, 40, pagedList)
verifyNoMoreInteractions(callback)
pagedList.loadAround(35)
drain()
verifyRange(0, 60, pagedList)
verifyCallback(callback, 40)
verifyNoMoreInteractions(callback)
}
@Test
fun append_invalidData_detach() {
val pagedList = createCountedPagedList(0)
val callback = mock<Callback>()
pagedList.addWeakCallback(callback)
verifyRange(0, 40, pagedList)
verifyNoMoreInteractions(callback)
pagedList.loadAround(35)
// return a LoadResult.Invalid
val pagingSource = pagedList.pagingSource as TestPagingSource
pagingSource.invalidData = true
drain()
// nothing new should be loaded
verifyRange(0, 40, pagedList)
verifyNoMoreInteractions(callback)
assertTrue(pagingSource.invalid)
assertTrue(pagedList.isDetached)
// detached status should turn pagedList into immutable, and snapshot should return the
// pagedList itself
assertSame(pagedList.snapshot(), pagedList)
}
@Test
fun prepend() {
val pagedList = createCountedPagedList(80)
val callback = mock<Callback>()
pagedList.addWeakCallback(callback)
verifyRange(60, 40, pagedList)
verifyNoMoreInteractions(callback)
pagedList.loadAround(if (placeholdersEnabled) 65 else 5)
drain()
verifyRange(40, 60, pagedList)
verifyCallback(callback, 40, 0)
verifyNoMoreInteractions(callback)
}
@Test
fun prepend_invalidData_detach() {
val pagedList = createCountedPagedList(80)
val callback = mock<Callback>()
pagedList.addWeakCallback(callback)
verifyRange(60, 40, pagedList)
verifyNoMoreInteractions(callback)
pagedList.loadAround(if (placeholdersEnabled) 65 else 5)
// return a LoadResult.Invalid
val pagingSource = pagedList.pagingSource as TestPagingSource
pagingSource.invalidData = true
drain()
// nothing new should be loaded
verifyRange(60, 40, pagedList)
verifyNoMoreInteractions(callback)
assertTrue(pagingSource.invalid)
assertTrue(pagedList.isDetached)
// detached status should turn pagedList into immutable, and snapshot should return the
// pagedList itself
assertSame(pagedList.snapshot(), pagedList)
}
@Test
fun outwards() {
val pagedList = createCountedPagedList(40)
val callback = mock<Callback>()
pagedList.addWeakCallback(callback)
verifyRange(20, 40, pagedList)
verifyNoMoreInteractions(callback)
pagedList.loadAround(if (placeholdersEnabled) 55 else 35)
drain()
verifyRange(20, 60, pagedList)
verifyCallback(callback, 60, 40)
verifyNoMoreInteractions(callback)
pagedList.loadAround(if (placeholdersEnabled) 25 else 5)
drain()
verifyRange(0, 80, pagedList)
verifyCallback(callback, 0, 0)
verifyNoMoreInteractions(callback)
}
@Test
fun prefetchRequestedPrepend() {
assertEquals(10, ContiguousPagedList.getPrependItemsRequested(10, 0, 0))
assertEquals(15, ContiguousPagedList.getPrependItemsRequested(10, 0, 5))
assertEquals(0, ContiguousPagedList.getPrependItemsRequested(1, 41, 40))
assertEquals(1, ContiguousPagedList.getPrependItemsRequested(1, 40, 40))
}
@Test
fun prefetchRequestedAppend() {
assertEquals(10, ContiguousPagedList.getAppendItemsRequested(10, 9, 10))
assertEquals(15, ContiguousPagedList.getAppendItemsRequested(10, 9, 5))
assertEquals(0, ContiguousPagedList.getAppendItemsRequested(1, 8, 10))
assertEquals(1, ContiguousPagedList.getAppendItemsRequested(1, 9, 10))
}
@Test
fun prefetchFront() {
val pagedList = createCountedPagedList(
initialPosition = 50,
pageSize = 20,
initLoadSize = 20,
prefetchDistance = 1
)
verifyRange(40, 20, pagedList)
// access adjacent to front, shouldn't trigger prefetch
pagedList.loadAround(if (placeholdersEnabled) 41 else 1)
drain()
verifyRange(40, 20, pagedList)
// access front item, should trigger prefetch
pagedList.loadAround(if (placeholdersEnabled) 40 else 0)
drain()
verifyRange(20, 40, pagedList)
}
@Test
fun prefetchEnd() {
val pagedList = createCountedPagedList(
initialPosition = 50,
pageSize = 20,
initLoadSize = 20,
prefetchDistance = 1
)
verifyRange(40, 20, pagedList)
// access adjacent from end, shouldn't trigger prefetch
pagedList.loadAround(if (placeholdersEnabled) 58 else 18)
drain()
verifyRange(40, 20, pagedList)
// access end item, should trigger prefetch
pagedList.loadAround(if (placeholdersEnabled) 59 else 19)
drain()
verifyRange(40, 40, pagedList)
}
@Test
fun pageDropEnd() {
val pagedList = createCountedPagedList(
initialPosition = 0,
pageSize = 20,
initLoadSize = 20,
prefetchDistance = 1,
maxSize = 70
)
val callback = mock<Callback>()
pagedList.addWeakCallback(callback)
verifyRange(0, 20, pagedList)
verifyNoMoreInteractions(callback)
// load 2nd page
pagedList.loadAround(19)
drain()
verifyRange(0, 40, pagedList)
verifyCallback(callback, 20)
verifyNoMoreInteractions(callback)
// load 3rd page
pagedList.loadAround(39)
drain()
verifyRange(0, 60, pagedList)
verifyCallback(callback, 40)
verifyNoMoreInteractions(callback)
// load 4th page, drop 1st
pagedList.loadAround(59)
drain()
verifyRange(20, 60, pagedList)
verifyCallback(callback, 60)
verifyDropCallback(callback, 0, 0)
verifyNoMoreInteractions(callback)
}
@Test
fun pageDropFront() {
val pagedList = createCountedPagedList(
initialPosition = 90,
pageSize = 20,
initLoadSize = 20,
prefetchDistance = 1,
maxSize = 70
)
val callback = mock<Callback>()
pagedList.addWeakCallback(callback)
verifyRange(80, 20, pagedList)
verifyNoMoreInteractions(callback)
// load 4th page
pagedList.loadAround(if (placeholdersEnabled) 80 else 0)
drain()
verifyRange(60, 40, pagedList)
verifyCallback(callback, 60, 0)
verifyNoMoreInteractions(callback)
reset(callback)
// load 3rd page
pagedList.loadAround(if (placeholdersEnabled) 60 else 0)
drain()
verifyRange(40, 60, pagedList)
verifyCallback(callback, 40, 0)
verifyNoMoreInteractions(callback)
reset(callback)
// load 2nd page, drop 5th
pagedList.loadAround(if (placeholdersEnabled) 40 else 0)
drain()
verifyRange(20, 60, pagedList)
verifyCallback(callback, 20, 0)
verifyDropCallback(callback, 80, 60)
verifyNoMoreInteractions(callback)
}
@Test
fun pageDropCancelPrepend() {
// verify that, based on most recent load position, a prepend can be dropped as it arrives
val pagedList = createCountedPagedList(
initialPosition = 2,
pageSize = 1,
initLoadSize = 1,
prefetchDistance = 1,
maxSize = 3
)
// load 3 pages - 2nd, 3rd, 4th
pagedList.loadAround(if (placeholdersEnabled) 2 else 0)
drain()
verifyRange(1, 3, pagedList)
val callback = mock<Callback>()
pagedList.addWeakCallback(callback)
// start a load at the beginning...
pagedList.loadAround(if (placeholdersEnabled) 1 else 0)
backgroundThread.executeAll()
// but before page received, access near end of list
pagedList.loadAround(if (placeholdersEnabled) 3 else 2)
verifyNoMoreInteractions(callback)
mainThread.executeAll()
// and the load at the beginning is dropped without signaling callback
verifyNoMoreInteractions(callback)
verifyRange(1, 3, pagedList)
drain()
if (placeholdersEnabled) {
verify(callback).onChanged(4, 1)
verify(callback).onChanged(1, 1)
} else {
verify(callback).onInserted(3, 1)
verify(callback).onRemoved(0, 1)
}
verifyRange(2, 3, pagedList)
}
@Test
fun pageDropCancelAppend() {
// verify that, based on most recent load position, an append can be dropped as it arrives
val pagedList = createCountedPagedList(
initialPosition = 2,
pageSize = 1,
initLoadSize = 1,
prefetchDistance = 1,
maxSize = 3
)
// load 3 pages - 2nd, 3rd, 4th
pagedList.loadAround(if (placeholdersEnabled) 2 else 0)
drain()
val callback = mock<Callback>()
pagedList.addWeakCallback(callback)
// start a load at the end...
pagedList.loadAround(if (placeholdersEnabled) 3 else 2)
backgroundThread.executeAll()
// but before page received, access near front of list
pagedList.loadAround(if (placeholdersEnabled) 1 else 0)
verifyNoMoreInteractions(callback)
mainThread.executeAll()
// and the load at the end is dropped without signaling callback
verifyNoMoreInteractions(callback)
verifyRange(1, 3, pagedList)
drain()
if (placeholdersEnabled) {
verify(callback).onChanged(0, 1)
verify(callback).onChanged(3, 1)
} else {
verify(callback).onInserted(0, 1)
verify(callback).onRemoved(3, 1)
}
verifyRange(0, 3, pagedList)
}
@Test
fun loadingListenerAppend() {
val pagedList = createCountedPagedList(0)
pagedList.withLoadStateCapture(APPEND) { states ->
// No loading going on currently
assertEquals(
listOf(
StateChange(
APPEND,
NotLoading(endOfPaginationReached = false)
)
),
states.getAllAndClear()
)
verifyRange(0, 40, pagedList)
// trigger load
pagedList.loadAround(35)
mainThread.executeAll()
assertEquals(
listOf(StateChange(APPEND, Loading)),
states.getAllAndClear()
)
verifyRange(0, 40, pagedList)
// load finishes
drain()
assertEquals(
listOf(
StateChange(
APPEND,
NotLoading(endOfPaginationReached = false)
)
),
states.getAllAndClear()
)
verifyRange(0, 60, pagedList)
pagedList.pagingSource.enqueueErrorForIndex(65)
// trigger load which will error
pagedList.loadAround(55)
mainThread.executeAll()
assertEquals(
listOf(StateChange(APPEND, Loading)),
states.getAllAndClear()
)
verifyRange(0, 60, pagedList)
// load now in error state
drain()
assertEquals(
listOf(StateChange(APPEND, Error(EXCEPTION))),
states.getAllAndClear()
)
verifyRange(0, 60, pagedList)
// retry
pagedList.retry()
mainThread.executeAll()
assertEquals(
listOf(StateChange(APPEND, Loading)),
states.getAllAndClear()
)
// load finishes
drain()
assertEquals(
listOf(
StateChange(
APPEND,
NotLoading(endOfPaginationReached = false)
)
),
states.getAllAndClear()
)
verifyRange(0, 80, pagedList)
}
}
@Test
fun pageDropCancelPrependError() {
// verify a prepend in error state can be dropped
val pagedList = createCountedPagedList(
initialPosition = 2,
pageSize = 1,
initLoadSize = 1,
prefetchDistance = 1,
maxSize = 3
)
pagedList.withLoadStateCapture(PREPEND) { states ->
// load 3 pages - 2nd, 3rd, 4th
pagedList.loadAround(if (placeholdersEnabled) 2 else 0)
drain()
verifyRange(1, 3, pagedList)
assertEquals(
listOf(
StateChange(
PREPEND,
NotLoading(endOfPaginationReached = false)
),
StateChange(PREPEND, Loading),
StateChange(
PREPEND,
NotLoading(endOfPaginationReached = false)
)
),
states.getAllAndClear()
)
// start a load at the beginning, which will fail
pagedList.pagingSource.enqueueErrorForIndex(0)
pagedList.loadAround(if (placeholdersEnabled) 1 else 0)
drain()
verifyRange(1, 3, pagedList)
assertEquals(
listOf(
StateChange(PREPEND, Loading),
StateChange(PREPEND, Error(EXCEPTION))
),
states.getAllAndClear()
)
// but without that failure being retried, access near end of list, which drops the error
pagedList.loadAround(if (placeholdersEnabled) 3 else 2)
drain()
assertEquals(
listOf(
StateChange(
PREPEND,
NotLoading(endOfPaginationReached = false)
)
),
states.getAllAndClear()
)
verifyRange(2, 3, pagedList)
}
}
@Test
fun pageDropCancelAppendError() {
// verify an append in error state can be dropped
val pagedList = createCountedPagedList(
initialPosition = 2,
pageSize = 1,
initLoadSize = 1,
prefetchDistance = 1,
maxSize = 3
)
pagedList.withLoadStateCapture(APPEND) { states ->
// load 3 pages - 2nd, 3rd, 4th
pagedList.loadAround(if (placeholdersEnabled) 2 else 0)
drain()
verifyRange(1, 3, pagedList)
assertEquals(
listOf(
StateChange(
APPEND,
NotLoading(endOfPaginationReached = false)
),
StateChange(APPEND, Loading),
StateChange(
APPEND,
NotLoading(endOfPaginationReached = false)
)
),
states.getAllAndClear()
)
// start a load at the end, which will fail
pagedList.pagingSource.enqueueErrorForIndex(4)
pagedList.loadAround(if (placeholdersEnabled) 3 else 2)
drain()
verifyRange(1, 3, pagedList)
assertEquals(
listOf(
StateChange(APPEND, Loading),
StateChange(APPEND, Error(EXCEPTION))
),
states.getAllAndClear()
)
// but without that failure being retried, access near start of list, which drops the error
pagedList.loadAround(if (placeholdersEnabled) 1 else 0)
drain()
assertEquals(
listOf(
StateChange(
APPEND,
NotLoading(endOfPaginationReached = false)
)
),
states.getAllAndClear()
)
verifyRange(0, 3, pagedList)
}
}
@Test
fun errorIntoDrop() {
// have an error, move loading range, error goes away
val pagedList = createCountedPagedList(0)
pagedList.withLoadStateCapture(APPEND) { states ->
pagedList.pagingSource.enqueueErrorForIndex(45)
pagedList.loadAround(35)
drain()
assertEquals(
listOf(
StateChange(
APPEND,
NotLoading(endOfPaginationReached = false)
),
StateChange(APPEND, Loading),
StateChange(APPEND, Error(EXCEPTION))
),
states.getAllAndClear()
)
verifyRange(0, 40, pagedList)
}
}
@Test
fun distantPrefetch() {
val pagedList = createCountedPagedList(
0,
initLoadSize = 10,
pageSize = 10,
prefetchDistance = 30
)
val callback = mock<Callback>()
pagedList.addWeakCallback(callback)
verifyRange(0, 10, pagedList)
verifyNoMoreInteractions(callback)
pagedList.loadAround(5)
drain()
verifyRange(0, 40, pagedList)
pagedList.loadAround(6)
drain()
// although our prefetch window moves forward, no new load triggered
verifyRange(0, 40, pagedList)
}
@Test
fun appendCallbackAddedLate() {
val pagedList = createCountedPagedList(0)
verifyRange(0, 40, pagedList)
pagedList.loadAround(35)
drain()
verifyRange(0, 60, pagedList)
// snapshot at 60 items
val snapshot = pagedList.snapshot() as PagedList<Item>
val snapshotCopy = snapshot.toList()
verifyRange(0, 60, snapshot)
// load more items...
pagedList.loadAround(55)
drain()
verifyRange(0, 80, pagedList)
verifyRange(0, 60, snapshot)
// and verify the snapshot hasn't received them
assertEquals(snapshotCopy, snapshot)
val callback = mock<Callback>()
@Suppress("DEPRECATION")
pagedList.addWeakCallback(snapshot, callback)
verify(callback).onChanged(0, snapshot.size)
if (!placeholdersEnabled) {
verify(callback).onInserted(60, 20)
}
verifyNoMoreInteractions(callback)
}
@Test
fun prependCallbackAddedLate() {
val pagedList = createCountedPagedList(80)
verifyRange(60, 40, pagedList)
pagedList.loadAround(if (placeholdersEnabled) 65 else 5)
drain()
verifyRange(40, 60, pagedList)
// snapshot at 60 items
val snapshot = pagedList.snapshot() as PagedList<Item>
val snapshotCopy = snapshot.toList()
verifyRange(40, 60, snapshot)
pagedList.loadAround(if (placeholdersEnabled) 45 else 5)
drain()
verifyRange(20, 80, pagedList)
verifyRange(40, 60, snapshot)
assertEquals(snapshotCopy, snapshot)
val callback = mock<Callback>()
@Suppress("DEPRECATION")
pagedList.addWeakCallback(snapshot, callback)
verify(callback).onChanged(0, snapshot.size)
if (!placeholdersEnabled) {
// deprecated snapshot compare dispatches as if inserts occur at the end
verify(callback).onInserted(60, 20)
}
verifyNoMoreInteractions(callback)
}
@Test
fun initialLoad_lastKey() {
val pagedList = createCountedPagedList(
initialPosition = 4,
initLoadSize = 20,
pageSize = 10
)
verifyRange(0, 20, pagedList)
// lastKey should return result of PagingSource.getRefreshKey after loading 20 items.
assertEquals(10, pagedList.lastKey)
// but in practice will be immediately overridden by quick loadAround call
// (e.g. in latching list after diffing, we loadAround immediately, since previous pos of
// viewport should win overall)
pagedList.loadAround(4)
assertEquals(4, pagedList.lastKey)
}
@Test
fun addWeakCallbackLegacyEmpty() {
val pagedList = createCountedPagedList(0)
verifyRange(0, 40, pagedList)
// capture empty snapshot
val initSnapshot = pagedList.snapshot()
assertEquals(pagedList, initSnapshot)
// verify that adding callback notifies naive "everything changed" when snapshot passed
var callback = mock<Callback>()
@Suppress("DEPRECATION")
pagedList.addWeakCallback(initSnapshot, callback)
verify(callback).onChanged(0, pagedList.size)
verifyNoMoreInteractions(callback)
pagedList.removeWeakCallback(callback)
pagedList.loadAround(35)
drain()
verifyRange(0, 60, pagedList)
// verify that adding callback notifies insert going from empty -> content
callback = mock()
@Suppress("DEPRECATION")
pagedList.addWeakCallback(initSnapshot, callback)
verify(callback).onChanged(0, initSnapshot.size)
if (!placeholdersEnabled) {
verify(callback).onInserted(40, 20)
}
verifyNoMoreInteractions(callback)
}
@Test
fun boundaryCallback_empty() {
@Suppress("UNCHECKED_CAST")
val boundaryCallback = mock<BoundaryCallback<Item>>()
val pagedList = createCountedPagedList(
0,
listData = ArrayList(), boundaryCallback = boundaryCallback
)
assertEquals(0, pagedList.size)
// nothing yet
verifyNoMoreInteractions(boundaryCallback)
// onZeroItemsLoaded posted, since creation often happens on BG thread
drain()
verify(boundaryCallback).onZeroItemsLoaded()
verifyNoMoreInteractions(boundaryCallback)
}
@Test
fun boundaryCallback_singleInitialLoad() {
val shortList = ITEMS.subList(0, 4)
@Suppress("UNCHECKED_CAST")
val boundaryCallback = mock<BoundaryCallback<Item>>()
val pagedList = createCountedPagedList(
0, listData = shortList,
initLoadSize = shortList.size, boundaryCallback = boundaryCallback
)
assertEquals(shortList.size, pagedList.size)
// nothing yet
verifyNoMoreInteractions(boundaryCallback)
// onItemAtFrontLoaded / onItemAtEndLoaded posted, since creation often happens on BG thread
drain()
pagedList.loadAround(0)
drain()
verify(boundaryCallback).onItemAtFrontLoaded(shortList.first())
verify(boundaryCallback).onItemAtEndLoaded(shortList.last())
verifyNoMoreInteractions(boundaryCallback)
}
@Test
fun boundaryCallback_delayed() {
@Suppress("UNCHECKED_CAST")
val boundaryCallback = mock<BoundaryCallback<Item>>()
val pagedList = createCountedPagedList(
90,
initLoadSize = 20, prefetchDistance = 5, boundaryCallback = boundaryCallback
)
verifyRange(80, 20, pagedList)
// nothing yet
verifyNoMoreInteractions(boundaryCallback)
drain()
verifyNoMoreInteractions(boundaryCallback)
// loading around last item causes onItemAtEndLoaded
pagedList.loadAround(if (placeholdersEnabled) 99 else 19)
drain()
verifyRange(80, 20, pagedList)
verify(boundaryCallback).onItemAtEndLoaded(ITEMS.last())
verifyNoMoreInteractions(boundaryCallback)
// prepending doesn't trigger callback...
pagedList.loadAround(if (placeholdersEnabled) 80 else 0)
drain()
verifyRange(60, 40, pagedList)
verifyNoMoreInteractions(boundaryCallback)
// ...load rest of data, still no dispatch...
pagedList.loadAround(if (placeholdersEnabled) 60 else 0)
drain()
pagedList.loadAround(if (placeholdersEnabled) 40 else 0)
drain()
pagedList.loadAround(if (placeholdersEnabled) 20 else 0)
drain()
verifyRange(0, 100, pagedList)
verifyNoMoreInteractions(boundaryCallback)
// ... finally try prepend, see 0 items, which will dispatch front callback
pagedList.loadAround(0)
drain()
verify(boundaryCallback).onItemAtFrontLoaded(ITEMS.first())
verifyNoMoreInteractions(boundaryCallback)
}
@Test
fun dispatchStateChange_dispatchesOnNotifyDispatcher() {
val pagedList = createCountedPagedList(0)
assertTrue { mainThread.queue.isEmpty() }
pagedList.dispatchStateChangeAsync(LoadType.REFRESH, Loading)
assertEquals(1, mainThread.queue.size)
pagedList.dispatchStateChangeAsync(LoadType.REFRESH, NotLoading.Incomplete)
assertEquals(2, mainThread.queue.size)
}
private fun drain() {
while (backgroundThread.queue.isNotEmpty() || mainThread.queue.isNotEmpty()) {
backgroundThread.executeAll()
mainThread.executeAll()
}
}
companion object {
@JvmStatic
@Parameterized.Parameters(name = "counted:{0}")
fun parameters(): Array<Array<Boolean>> {
return arrayOf(arrayOf(true), arrayOf(false))
}
val EXCEPTION = Exception()
private val ITEMS = List(100) { Item(it) }
}
}
| apache-2.0 | 7d9384fb36c937fbdc67267e1372ca22 | 32.229814 | 103 | 0.596155 | 5.201389 | false | false | false | false |
androidx/androidx | compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/layoutanimation/AnimatedVisiblilityLazyColumnDemo.kt | 3 | 4622 | /*
* 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.layoutanimation
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.ExperimentalTransitionApi
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.expandVertically
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment.Companion.CenterEnd
import androidx.compose.ui.Alignment.Companion.End
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@Preview
@Composable
fun AnimatedVisibilityLazyColumnDemo() {
Column {
val model = remember { MyModel() }
Row(Modifier.fillMaxWidth()) {
Button(
{ model.addNewItem() },
modifier = Modifier.padding(15.dp).weight(1f)
) {
Text("Add")
}
}
LaunchedEffect(model) {
snapshotFlow {
model.items.firstOrNull { it.visible.isIdle && !it.visible.targetState }
}.collect {
if (it != null) {
model.pruneItems()
}
}
}
LazyColumn {
items(model.items, key = { it.itemId }) { item ->
AnimatedVisibility(
item.visible,
enter = expandVertically(),
exit = shrinkVertically()
) {
Box(Modifier.fillMaxWidth().requiredHeight(90.dp).background(item.color)) {
Button(
{ model.removeItem(item) },
modifier = Modifier.align(CenterEnd).padding(15.dp)
) {
Text("Remove")
}
}
}
}
}
Button(
{ model.removeAll() },
modifier = Modifier.align(End).padding(15.dp)
) {
Text("Clear All")
}
}
}
private class MyModel {
private val _items: MutableList<ColoredItem> = mutableStateListOf()
private var lastItemId = 0
val items: List<ColoredItem> = _items
class ColoredItem(val visible: MutableTransitionState<Boolean>, val itemId: Int) {
val color: Color
get() = turquoiseColors.let {
it[itemId % it.size]
}
}
fun addNewItem() {
lastItemId++
_items.add(
ColoredItem(
MutableTransitionState(false).apply { targetState = true },
lastItemId
)
)
}
fun removeItem(item: ColoredItem) {
item.visible.targetState = false
}
@OptIn(ExperimentalTransitionApi::class)
fun pruneItems() {
_items.removeAll(items.filter { it.visible.isIdle && !it.visible.targetState })
}
fun removeAll() {
_items.forEach {
it.visible.targetState = false
}
}
}
internal val turquoiseColors = listOf(
Color(0xff07688C),
Color(0xff1986AF),
Color(0xff50B6CD),
Color(0xffBCF8FF),
Color(0xff8AEAE9),
Color(0xff46CECA)
)
| apache-2.0 | 6dfd46812f23b0e11910febe292b7e87 | 31.321678 | 95 | 0.633276 | 4.594433 | false | false | false | false |
hellenxu/TipsProject | DroidDailyProject/app/src/main/java/six/ca/droiddailyproject/fragment/NestedSampleActivity.kt | 1 | 3363 | package six.ca.droiddailyproject.fragment
import android.os.Bundle
import android.os.PersistableBundle
import androidx.appcompat.app.AppCompatActivity
import six.ca.droiddailyproject.R
/**
* @author hellenxu
* @date 2020-02-13
* Copyright 2020 Six. All rights reserved.
*/
class NestedSampleActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.act_nested_frag)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, LevelOneFragment().apply {
val bundle = Bundle()
bundle.putInt("fromActInt", 3)
bundle.putParcelable("fromActObj", InfoManager.Info("qazxsw"))
arguments = bundle
})
.commit()
}
}
// override fun onSaveInstanceState(outState: Bundle?) {
// outState?.putParcelable("info", InfoManager.instance.sharedInfo)
// super.onSaveInstanceState(outState)
// println("xxl-act-onSaveInstanceState: $outState")
// }
// without setting android:persistableMode, this onSaveInstanceState will not be called
override fun onSaveInstanceState(outState: Bundle?, outPersistentState: PersistableBundle?) {
super.onSaveInstanceState(outState, outPersistentState)
println("xxl-act-the-other-onSaveInstanceState")
}
override fun onResumeFragments() {
super.onResumeFragments()
println("xxl-act-onResumeFragments")
}
override fun onResume() {
super.onResume()
val bundle = intent.extras
println("xxl-act-intent-Int: ${bundle?.getInt("intent-Int", 0)}")
println("xxl-act-intent-Obj: ${(bundle?.getParcelable("intent-Obj") as? InfoManager.Info)?.userId}")
println("xxl-act-onResume")
}
// override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
// super.onRestoreInstanceState(savedInstanceState)
// InfoManager.instance.sharedInfo = savedInstanceState?.getParcelable("info") ?: InfoManager.Info("000")
// println("xxl-act-onRestoreInstanceState")
// }
}
/**
* launch -> press home:
* 2020-02-19 22:31:09.997 32316-32316/six.ca.droiddailyproject I/System.out: xxl-frag-onViewStateRestored: null
* 2020-02-19 22:31:10.000 32316-32316/six.ca.droiddailyproject I/System.out: xxl-onResume
* 2020-02-19 22:31:10.001 32316-32316/six.ca.droiddailyproject I/System.out: xxl-act-onResumeFragments
* 2020-02-19 22:33:30.826 32316-32316/six.ca.droiddailyproject I/System.out: xxl-frag-onSaveInstanceState: Bundle[{}]
* 2020-02-19 22:33:30.838 32316-32316/six.ca.droiddailyproject I/System.out: xxl-act-onSaveInstanceState: Bundle[{android:viewHierarchyState=Bundle[{android:views={16908290=android.view.AbsSavedState$1@1352a56, 2131230726=android.support.v7.widget.Toolbar$SavedState@b0d6ad7, 2131230728=android.view.AbsSavedState$1@1352a56, 2131230734=android.view.AbsSavedState$1@1352a56, 2131230791=android.view.AbsSavedState$1@1352a56, 2131230827=android.view.AbsSavedState$1@1352a56}}], android:support:fragments=android.support.v4.app.FragmentManagerState@48e2fc4, android:lastAutofillId=1073741823, android:fragments=android.app.FragmentManagerState@8b03ead}]
*
*/ | apache-2.0 | 16390ef93fb24c626774c732fb52086a | 44.459459 | 650 | 0.710675 | 3.874424 | false | false | false | false |
GunoH/intellij-community | platform/lang-api/src/com/intellij/refactoring/suggested/SuggestedRefactoringSupport.kt | 2 | 8382 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.refactoring.suggested
import com.intellij.lang.Language
import com.intellij.lang.LanguageExtension
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.hasErrorElementInRange
import com.intellij.psi.util.parents
/**
* Language extension to implement to support suggested Rename and/or Change Signature refactorings.
*/
interface SuggestedRefactoringSupport {
companion object : LanguageExtension<SuggestedRefactoringSupport>("com.intellij.suggestedRefactoringSupport") {
@Suppress("RedundantOverride")
override fun forLanguage(l: Language): SuggestedRefactoringSupport? {
return super.forLanguage(l)
}
}
/**
* Returns true, if given PsiElement is a declaration which may be subject of suggested refactoring.
*
* Note, that if Change Signature is supported then individual parameters must not be considered as declarations
* for they are part of a bigger declaration.
*/
@Deprecated(message = "Use isAnchor instead", replaceWith = ReplaceWith("isAnchor(psiElement)"))
fun isDeclaration(psiElement: PsiElement): Boolean = throw NotImplementedError("Will be removed")
/**
* Returns true, if given PsiElement is an anchor element where suggested refactoring can start.
*
* It could be either a declaration or a call-site if suggested refactoring from the call-site is supported.
*
* Note, that if Change Signature is supported then individual parameters must not be considered as anchors
* for they are part of a bigger anchor (method or function).
*/
@Suppress("DEPRECATION")
fun isAnchor(psiElement: PsiElement): Boolean = isDeclaration(psiElement)
/**
* Returns "signature range" for a given anchor.
*
* Signature range is a range that contains all properties taken into account by Change Signature refactoring.
* If only Rename refactoring is supported for the given declaration, the name identifier range must be returned.
*
* Only PsiElement's that are classified as anchor by [isAnchor] method must be passed to this method.
* @return signature range for the anchor, or *null* if anchor is considered unsuitable for refactoring
* (usually when it has syntax error).
*/
fun signatureRange(anchor: PsiElement): TextRange?
/**
* Returns range in the given file taken by imports (if supported by the language).
*
* If no imports exist yet in the given file, it must return an empty range within whitespace where the imports are to be inserted.
* @return range taken by imports, or *null* if imports are not supported by the language.
*/
fun importsRange(psiFile: PsiFile): TextRange?
/**
* Returns name range for a given anchor.
*
* Only PsiElement's that are classified as anchors by [isAnchor] method must be passed to this method.
* @return name range for the anchor, or *null* if anchor does not have a name.
*/
fun nameRange(anchor: PsiElement): TextRange?
/**
* Returns true if there's a syntax error within given anchor that prevents
* suggested refactoring from successful completion
*/
fun hasSyntaxError(anchor: PsiElement): Boolean {
val signatureRange = signatureRange(anchor) ?: return true
return anchor.containingFile.hasErrorElementInRange(signatureRange)
}
/**
* Determines if the character can start an identifier in the language.
*
* This method is used for suppression of refactoring for a declaration which has been just typed by the user.
*/
fun isIdentifierStart(c: Char): Boolean
/**
* Determines if an identifier can contain the character.
*
* This method is used for suppression of refactoring for a declaration which has been just typed by the user.
*/
fun isIdentifierPart(c: Char): Boolean
/**
* A service transforming a sequence of declaration states into [SuggestedRefactoringState].
*
* Use [SuggestedRefactoringStateChanges.RenameOnly] if only Rename refactoring is supported.
*/
val stateChanges: SuggestedRefactoringStateChanges
/**
* A service determining available refactoring for a given [SuggestedRefactoringState].
*
* Use [SuggestedRefactoringAvailability.RenameOnly] if only Rename refactoring is supported.
*/
val availability: SuggestedRefactoringAvailability
/**
* A service providing information required for building user-interface of Change Signature refactoring.
*
* Use [SuggestedRefactoringUI.RenameOnly] if only Rename refactoring is supported.
*/
val ui: SuggestedRefactoringUI
/**
* A service performing actual changes in the code when user executes suggested refactoring.
*
* Use [SuggestedRefactoringExecution.RenameOnly] if only Rename refactoring is supported.
*/
val execution: SuggestedRefactoringExecution
/**
* A class with data representing declaration signature.
*
* This data is used mainly for signature change presentation and for detection of refactoring availability.
* No PSI-related objects must be referenced by instances of this class and all PSI-related information
* that is required to perform the refactoring must be extracted from the declaration itself prior to perform the refactoring.
*/
class Signature private constructor(
val name: String,
val type: String?,
val parameters: List<Parameter>,
val additionalData: SignatureAdditionalData?,
private val nameToParameter: Map<String, Parameter>
) {
private val idToParameter: Map<Any, Parameter> = mutableMapOf<Any, Parameter>().apply {
for (parameter in parameters) {
val prev = this.put(parameter.id, parameter)
require(prev == null) { "Duplicate parameter id: ${parameter.id}" }
}
}
private val parameterToIndex = parameters.withIndex().associate { (index, parameter) -> parameter to index }
fun parameterById(id: Any): Parameter? = idToParameter[id]
fun parameterByName(name: String): Parameter? = nameToParameter[name]
fun parameterIndex(parameter: Parameter): Int = parameterToIndex[parameter]!!
override fun equals(other: Any?): Boolean {
return other is Signature &&
name == other.name &&
type == other.type &&
additionalData == other.additionalData &&
parameters == other.parameters
}
override fun hashCode(): Int {
return 0
}
companion object {
/**
* Factory method, used to create instances of [Signature] class.
*
* @return create instance of [Signature], or *null* if it cannot be created due to duplicated parameter names
*/
@JvmStatic
fun create(
name: String,
type: String?,
parameters: List<Parameter>,
additionalData: SignatureAdditionalData?
): Signature? {
val nameToParameter = mutableMapOf<String, Parameter>()
for (parameter in parameters) {
val key = parameter.name
if (nameToParameter.containsKey(key)) return null
nameToParameter[key] = parameter
}
return Signature(name, type, parameters, additionalData, nameToParameter)
}
}
}
/**
* A class representing a parameter in [Signature].
*
* Parameters with the same [id] represent the same parameter in the old and new signatures.
* All parameters in the same [Signature] must have unique [id].
*/
data class Parameter(
val id: Any,
@NlsSafe val name: String,
val type: String,
val additionalData: ParameterAdditionalData? = null
)
/**
* Language-specific information to be stored in [Signature].
*
* Don't put any PSI-related objects here.
*/
interface SignatureAdditionalData {
override fun equals(other: Any?): Boolean
}
/**
* Language-specific information to be stored in [Parameter].
*
* Don't put any PSI-related objects here.
*/
interface ParameterAdditionalData {
override fun equals(other: Any?): Boolean
}
}
fun SuggestedRefactoringSupport.anchorByOffset(psiFile: PsiFile, offset: Int): PsiElement? {
return psiFile.findElementAt(offset)
?.parents(true)
?.firstOrNull { isAnchor(it) }
}
| apache-2.0 | 13886ce946c3424c2cfb62480aee7853 | 36.419643 | 133 | 0.717013 | 4.836699 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.