repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
UCSoftworks/LeafDb | leafdb-jdbc/src/main/java/com/ucsoftworks/leafdb/jdbc/LeafDbJdbcCursor.kt | 1 | 744 | package com.ucsoftworks.leafdb.jdbc
import com.ucsoftworks.leafdb.wrapper.ILeafDbCursor
import java.sql.ResultSet
/**
* Created by Pasenchuk Victor on 28/08/2017
*/
class LeafDbJdbcCursor(private val cursor: ResultSet) : ILeafDbCursor {
override val empty: Boolean
get() = !cursor.next()
override val isClosed: Boolean
get() = cursor.isClosed
override fun close() {
cursor.close()
}
override fun moveToNext() =
cursor.next()
override fun getString(index: Int): String
= cursor.getString(index)
override fun getLong(index: Int): Long
= cursor.getLong(index)
override fun getDouble(index: Int): Double
= cursor.getDouble(index)
}
| lgpl-3.0 | 0d5db01d2ae192ee332e1783a2d916df | 21.545455 | 71 | 0.651882 | 4.227273 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/browse/ExtensionDetailsScreen.kt | 1 | 15231 | package eu.kanade.presentation.browse
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import android.util.DisplayMetrics
import androidx.annotation.StringRes
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.HelpOutline
import androidx.compose.material.icons.outlined.History
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import eu.kanade.presentation.browse.components.ExtensionIcon
import eu.kanade.presentation.components.AppBar
import eu.kanade.presentation.components.AppBarActions
import eu.kanade.presentation.components.DIVIDER_ALPHA
import eu.kanade.presentation.components.Divider
import eu.kanade.presentation.components.EmptyScreen
import eu.kanade.presentation.components.LoadingScreen
import eu.kanade.presentation.components.PreferenceRow
import eu.kanade.presentation.components.Scaffold
import eu.kanade.presentation.components.ScrollbarLazyColumn
import eu.kanade.presentation.util.horizontalPadding
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.extension.model.Extension
import eu.kanade.tachiyomi.source.ConfigurableSource
import eu.kanade.tachiyomi.ui.browse.extension.details.ExtensionDetailsPresenter
import eu.kanade.tachiyomi.ui.browse.extension.details.ExtensionSourceItem
import eu.kanade.tachiyomi.util.system.LocaleHelper
@Composable
fun ExtensionDetailsScreen(
navigateUp: () -> Unit,
presenter: ExtensionDetailsPresenter,
onClickSourcePreferences: (sourceId: Long) -> Unit,
) {
val uriHandler = LocalUriHandler.current
Scaffold(
topBar = { scrollBehavior ->
AppBar(
title = stringResource(R.string.label_extension_info),
navigateUp = navigateUp,
actions = {
AppBarActions(
actions = buildList {
if (presenter.extension?.isUnofficial == false) {
add(
AppBar.Action(
title = stringResource(R.string.whats_new),
icon = Icons.Outlined.History,
onClick = { uriHandler.openUri(presenter.getChangelogUrl()) },
),
)
add(
AppBar.Action(
title = stringResource(R.string.action_faq_and_guides),
icon = Icons.Outlined.HelpOutline,
onClick = { uriHandler.openUri(presenter.getReadmeUrl()) },
),
)
}
addAll(
listOf(
AppBar.OverflowAction(
title = stringResource(R.string.action_enable_all),
onClick = { presenter.toggleSources(true) },
),
AppBar.OverflowAction(
title = stringResource(R.string.action_disable_all),
onClick = { presenter.toggleSources(false) },
),
AppBar.OverflowAction(
title = stringResource(R.string.pref_clear_cookies),
onClick = { presenter.clearCookies() },
),
),
)
},
)
},
scrollBehavior = scrollBehavior,
)
},
) { paddingValues ->
ExtensionDetails(paddingValues, presenter, onClickSourcePreferences)
}
}
@Composable
private fun ExtensionDetails(
contentPadding: PaddingValues,
presenter: ExtensionDetailsPresenter,
onClickSourcePreferences: (sourceId: Long) -> Unit,
) {
when {
presenter.isLoading -> LoadingScreen()
presenter.extension == null -> EmptyScreen(
textResource = R.string.empty_screen,
modifier = Modifier.padding(contentPadding),
)
else -> {
val context = LocalContext.current
val extension = presenter.extension
var showNsfwWarning by remember { mutableStateOf(false) }
ScrollbarLazyColumn(
contentPadding = contentPadding,
) {
when {
extension.isUnofficial ->
item {
WarningBanner(R.string.unofficial_extension_message)
}
extension.isObsolete ->
item {
WarningBanner(R.string.obsolete_extension_message)
}
}
item {
DetailsHeader(
extension = extension,
onClickUninstall = { presenter.uninstallExtension() },
onClickAppInfo = {
Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
data = Uri.fromParts("package", extension.pkgName, null)
context.startActivity(this)
}
},
onClickAgeRating = {
showNsfwWarning = true
},
)
}
items(
items = presenter.sources,
key = { it.source.id },
) { source ->
SourceSwitchPreference(
modifier = Modifier.animateItemPlacement(),
source = source,
onClickSourcePreferences = onClickSourcePreferences,
onClickSource = { presenter.toggleSource(it) },
)
}
}
if (showNsfwWarning) {
NsfwWarningDialog(
onClickConfirm = {
showNsfwWarning = false
},
)
}
}
}
}
@Composable
private fun WarningBanner(@StringRes textRes: Int) {
Box(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.error)
.padding(16.dp),
contentAlignment = Alignment.Center,
) {
Text(
text = stringResource(textRes),
color = MaterialTheme.colorScheme.onError,
style = MaterialTheme.typography.bodyMedium,
)
}
}
@Composable
private fun DetailsHeader(
extension: Extension,
onClickAgeRating: () -> Unit,
onClickUninstall: () -> Unit,
onClickAppInfo: () -> Unit,
) {
val context = LocalContext.current
Column {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(
start = horizontalPadding,
end = horizontalPadding,
top = 16.dp,
bottom = 8.dp,
),
horizontalAlignment = Alignment.CenterHorizontally,
) {
ExtensionIcon(
modifier = Modifier
.size(112.dp),
extension = extension,
density = DisplayMetrics.DENSITY_XXXHIGH,
)
Text(
text = extension.name,
style = MaterialTheme.typography.headlineSmall,
)
val strippedPkgName = extension.pkgName.substringAfter("eu.kanade.tachiyomi.extension.")
Text(
text = strippedPkgName,
style = MaterialTheme.typography.bodySmall,
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(
horizontal = horizontalPadding * 2,
vertical = 8.dp,
),
horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.CenterVertically,
) {
InfoText(
modifier = Modifier.weight(1f),
primaryText = extension.versionName,
secondaryText = stringResource(R.string.ext_info_version),
)
InfoDivider()
InfoText(
modifier = Modifier.weight(if (extension.isNsfw) 1.5f else 1f),
primaryText = LocaleHelper.getSourceDisplayName(extension.lang, context),
secondaryText = stringResource(R.string.ext_info_language),
)
if (extension.isNsfw) {
InfoDivider()
InfoText(
modifier = Modifier.weight(1f),
primaryText = stringResource(R.string.ext_nsfw_short),
primaryTextStyle = MaterialTheme.typography.bodyLarge.copy(
color = MaterialTheme.colorScheme.error,
fontWeight = FontWeight.Medium,
),
secondaryText = stringResource(R.string.ext_info_age_rating),
onClick = onClickAgeRating,
)
}
}
Row(
modifier = Modifier.padding(
start = horizontalPadding,
end = horizontalPadding,
top = 8.dp,
bottom = 16.dp,
),
) {
OutlinedButton(
modifier = Modifier.weight(1f),
onClick = onClickUninstall,
) {
Text(stringResource(R.string.ext_uninstall))
}
Spacer(Modifier.width(16.dp))
Button(
modifier = Modifier.weight(1f),
onClick = onClickAppInfo,
) {
Text(
text = stringResource(R.string.ext_app_info),
color = MaterialTheme.colorScheme.onPrimary,
)
}
}
Divider()
}
}
@Composable
private fun InfoText(
modifier: Modifier,
primaryText: String,
primaryTextStyle: TextStyle = MaterialTheme.typography.bodyLarge,
secondaryText: String,
onClick: (() -> Unit)? = null,
) {
val interactionSource = remember { MutableInteractionSource() }
val clickableModifier = if (onClick != null) {
Modifier.clickable(interactionSource, indication = null) { onClick() }
} else {
Modifier
}
Column(
modifier = modifier.then(clickableModifier),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
) {
Text(
text = primaryText,
textAlign = TextAlign.Center,
style = primaryTextStyle,
)
Text(
text = secondaryText + if (onClick != null) " ⓘ" else "",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f),
)
}
}
@Composable
private fun InfoDivider() {
Divider(
modifier = Modifier
.height(20.dp)
.width(1.dp),
color = MaterialTheme.colorScheme.onSurface.copy(alpha = DIVIDER_ALPHA),
)
}
@Composable
private fun SourceSwitchPreference(
modifier: Modifier = Modifier,
source: ExtensionSourceItem,
onClickSourcePreferences: (sourceId: Long) -> Unit,
onClickSource: (sourceId: Long) -> Unit,
) {
val context = LocalContext.current
PreferenceRow(
modifier = modifier,
title = if (source.labelAsName) {
source.source.toString()
} else {
LocaleHelper.getSourceDisplayName(source.source.lang, context)
},
onClick = { onClickSource(source.source.id) },
action = {
Row(
verticalAlignment = Alignment.CenterVertically,
) {
if (source.source is ConfigurableSource) {
IconButton(onClick = { onClickSourcePreferences(source.source.id) }) {
Icon(
imageVector = Icons.Outlined.Settings,
contentDescription = stringResource(R.string.label_settings),
tint = MaterialTheme.colorScheme.onSurface,
)
}
}
Switch(checked = source.enabled, onCheckedChange = null)
}
},
)
}
@Composable
private fun NsfwWarningDialog(
onClickConfirm: () -> Unit,
) {
AlertDialog(
text = {
Text(text = stringResource(R.string.ext_nsfw_warning))
},
confirmButton = {
TextButton(onClick = onClickConfirm) {
Text(text = stringResource(android.R.string.ok))
}
},
onDismissRequest = onClickConfirm,
)
}
| apache-2.0 | 92c1a5fb367674b7152f8f6612878cd8 | 34.748826 | 102 | 0.552893 | 5.607143 | false | false | false | false |
Heiner1/AndroidAPS | diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SerialNumInquireResponsePacket.kt | 1 | 2982 | package info.nightscout.androidaps.diaconn.packet
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.diaconn.DiaconnG8Pump
import info.nightscout.androidaps.diaconn.R
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.logging.LTag
import info.nightscout.shared.sharedPreferences.SP
import javax.inject.Inject
/**
* SerialNumInquireResponsePacket
*/
class SerialNumInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) {
@Inject lateinit var diaconnG8Pump: DiaconnG8Pump
@Inject lateinit var sp: SP
@Inject lateinit var rh: ResourceHelper
init {
msgType = 0xAE.toByte()
aapsLogger.debug(LTag.PUMPCOMM, "SerialNumInquireResponsePacket init")
}
override fun handleMessage(data: ByteArray?) {
val result = defect(data)
if (result != 0) {
aapsLogger.debug(LTag.PUMPCOMM, "SerialNumInquireResponsePacket Got some Error")
failed = true
return
} else failed = false
val bufferData = prefixDecode(data)
val result2 = getByteToInt(bufferData)
if(!isSuccInquireResponseResult(result2)) {
failed = true
return
}
diaconnG8Pump.country = getByteToInt(bufferData).toChar().toString().toInt() // ASCII
diaconnG8Pump.productType = getByteToInt(bufferData).toChar().toString().toInt() // ASCII
diaconnG8Pump.makeYear = getByteToInt(bufferData)
diaconnG8Pump.makeMonth = getByteToInt(bufferData)
diaconnG8Pump.makeDay = getByteToInt(bufferData)
diaconnG8Pump.lotNo = getByteToInt(bufferData)// LOT NO
diaconnG8Pump.serialNo = getShortToInt(bufferData)
diaconnG8Pump.majorVersion = getByteToInt(bufferData)
diaconnG8Pump.minorVersion = getByteToInt(bufferData)
aapsLogger.debug(LTag.PUMPCOMM, "Result --> ${diaconnG8Pump.result}")
aapsLogger.debug(LTag.PUMPCOMM, "country --> ${diaconnG8Pump.country}")
aapsLogger.debug(LTag.PUMPCOMM, "productType --> ${diaconnG8Pump.productType}")
aapsLogger.debug(LTag.PUMPCOMM, "makeYear --> ${diaconnG8Pump.makeYear}")
aapsLogger.debug(LTag.PUMPCOMM, "makeMonth --> ${diaconnG8Pump.makeMonth}")
aapsLogger.debug(LTag.PUMPCOMM, "makeDay --> ${diaconnG8Pump.makeDay}")
aapsLogger.debug(LTag.PUMPCOMM, "lotNo --> ${diaconnG8Pump.lotNo}")
aapsLogger.debug(LTag.PUMPCOMM, "serialNo --> ${diaconnG8Pump.serialNo}")
aapsLogger.debug(LTag.PUMPCOMM, "majorVersion --> ${diaconnG8Pump.majorVersion}")
aapsLogger.debug(LTag.PUMPCOMM, "minorVersion --> ${diaconnG8Pump.minorVersion}")
sp.putString(rh.gs(R.string.pumpversion), diaconnG8Pump.majorVersion.toString() + "." + diaconnG8Pump.minorVersion.toString())
}
override fun getFriendlyName(): String {
return "PUMP_SERIAL_NUM_INQUIRE_RESPONSE"
}
} | agpl-3.0 | 9332ae295e1a298bcf3205f61aed2311 | 42.231884 | 134 | 0.698189 | 4.290647 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt | 1 | 70620 | package info.nightscout.androidaps.plugins.general.smsCommunicator
import android.content.Context
import android.telephony.SmsManager
import android.telephony.SmsMessage
import android.text.TextUtils
import androidx.preference.EditTextPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.work.Worker
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.annotations.OpenForTesting
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.OfflineEvent
import info.nightscout.androidaps.database.entities.TemporaryTarget
import info.nightscout.androidaps.database.entities.UserEntry.Action
import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.database.entities.ValueWithUnit
import info.nightscout.androidaps.database.transactions.CancelCurrentOfflineEventIfAnyTransaction
import info.nightscout.androidaps.database.transactions.CancelCurrentTemporaryTargetIfAnyTransaction
import info.nightscout.androidaps.database.transactions.InsertAndCancelCurrentOfflineEventTransaction
import info.nightscout.androidaps.database.transactions.InsertAndCancelCurrentTemporaryTargetTransaction
import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.extensions.valueToUnitsString
import info.nightscout.androidaps.interfaces.*
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.plugins.general.smsCommunicator.events.EventSmsCommunicatorUpdateGui
import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePassword
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.receivers.DataWorker
import info.nightscout.androidaps.utils.*
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.shared.sharedPreferences.SP
import info.nightscout.androidaps.utils.textValidator.ValidatingEditTextPreference
import info.nightscout.shared.SafeParse
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.plusAssign
import org.apache.commons.lang3.StringUtils
import org.joda.time.DateTime
import java.text.Normalizer
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.regex.Pattern
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.math.max
import kotlin.math.min
@OpenForTesting
@Singleton
class SmsCommunicatorPlugin @Inject constructor(
injector: HasAndroidInjector,
aapsLogger: AAPSLogger,
rh: ResourceHelper,
private val smsManager: SmsManager?,
private val aapsSchedulers: AapsSchedulers,
private val sp: SP,
private val constraintChecker: ConstraintChecker,
private val rxBus: RxBus,
private val profileFunction: ProfileFunction,
private val fabricPrivacy: FabricPrivacy,
private val activePlugin: ActivePlugin,
private val commandQueue: CommandQueue,
private val loop: Loop,
private val iobCobCalculator: IobCobCalculator,
private val xDripBroadcast: XDripBroadcast,
private var otp: OneTimePassword,
private val config: Config,
private val dateUtil: DateUtil,
private val uel: UserEntryLogger,
private val glucoseStatusProvider: GlucoseStatusProvider,
private val repository: AppRepository
) : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(SmsCommunicatorFragment::class.java.name)
.pluginIcon(R.drawable.ic_sms)
.pluginName(R.string.smscommunicator)
.shortName(R.string.smscommunicator_shortname)
.preferencesId(R.xml.pref_smscommunicator)
.description(R.string.description_sms_communicator),
aapsLogger, rh, injector
), SmsCommunicator {
private val disposable = CompositeDisposable()
var allowedNumbers: MutableList<String> = ArrayList()
@Volatile var messageToConfirm: AuthRequest? = null
@Volatile var lastRemoteBolusTime: Long = 0
var messages = ArrayList<Sms>()
val commands = mapOf(
"BG" to "BG",
"LOOP" to "LOOP STOP/DISABLE/START/ENABLE/RESUME/STATUS\nLOOP SUSPEND 20",
"NSCLIENT" to "NSCLIENT RESTART",
"PUMP" to "PUMP\nPUMP CONNECT\nPUMP DISCONNECT 30\n",
"BASAL" to "BASAL STOP/CANCEL\nBASAL 0.3\nBASAL 0.3 20\nBASAL 30%\nBASAL 30% 20\n",
"BOLUS" to "BOLUS 1.2\nBOLUS 1.2 MEAL",
"EXTENDED" to "EXTENDED STOP/CANCEL\nEXTENDED 2 120",
"CAL" to "CAL 5.6",
"PROFILE" to "PROFILE STATUS/LIST\nPROFILE 1\nPROFILE 2 30",
"TARGET" to "TARGET MEAL/ACTIVITY/HYPO/STOP",
"SMS" to "SMS DISABLE/STOP",
"CARBS" to "CARBS 12\nCARBS 12 23:05\nCARBS 12 11:05PM",
"HELP" to "HELP\nHELP command"
)
override fun onStart() {
processSettings(null)
super.onStart()
disposable += rxBus
.toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ event: EventPreferenceChange? -> processSettings(event) }, fabricPrivacy::logException)
}
override fun onStop() {
disposable.clear()
super.onStop()
}
override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) {
super.preprocessPreferences(preferenceFragment)
val distance = preferenceFragment.findPreference(rh.gs(R.string.key_smscommunicator_remotebolusmindistance)) as ValidatingEditTextPreference?
?: return
val allowedNumbers = preferenceFragment.findPreference(rh.gs(R.string.key_smscommunicator_allowednumbers)) as EditTextPreference?
?: return
if (!areMoreNumbers(allowedNumbers.text)) {
distance.title = (rh.gs(R.string.smscommunicator_remotebolusmindistance)
+ ".\n"
+ rh.gs(R.string.smscommunicator_remotebolusmindistance_caveat))
distance.isEnabled = false
} else {
distance.title = rh.gs(R.string.smscommunicator_remotebolusmindistance)
distance.isEnabled = true
}
allowedNumbers.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _: Preference?, newValue: Any ->
if (!areMoreNumbers(newValue as String)) {
distance.text = (Constants.remoteBolusMinDistance / (60 * 1000L)).toString()
distance.title = (rh.gs(R.string.smscommunicator_remotebolusmindistance)
+ ".\n"
+ rh.gs(R.string.smscommunicator_remotebolusmindistance_caveat))
distance.isEnabled = false
} else {
distance.title = rh.gs(R.string.smscommunicator_remotebolusmindistance)
distance.isEnabled = true
}
true
}
}
override fun updatePreferenceSummary(pref: Preference) {
super.updatePreferenceSummary(pref)
if (pref is EditTextPreference) {
if (pref.getKey().contains("smscommunicator_allowednumbers") && (TextUtils.isEmpty(pref.text?.trim { it <= ' ' }))) {
pref.setSummary(rh.gs(R.string.smscommunicator_allowednumbers_summary))
}
}
}
// cannot be inner class because of needed injection
class SmsCommunicatorWorker(
context: Context,
params: WorkerParameters
) : Worker(context, params) {
@Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin
@Inject lateinit var dataWorker: DataWorker
init {
(context.applicationContext as HasAndroidInjector).androidInjector().inject(this)
}
@Suppress("SpellCheckingInspection")
override fun doWork(): Result {
val bundle = dataWorker.pickupBundle(inputData.getLong(DataWorker.STORE_KEY, -1))
?: return Result.failure(workDataOf("Error" to "missing input data"))
val format = bundle.getString("format")
?: return Result.failure(workDataOf("Error" to "missing format in input data"))
val pdus = bundle["pdus"] as Array<*>
for (pdu in pdus) {
val message = SmsMessage.createFromPdu(pdu as ByteArray, format)
smsCommunicatorPlugin.processSms(Sms(message))
}
return Result.success()
}
}
private fun processSettings(ev: EventPreferenceChange?) {
if (ev == null || ev.isChanged(rh, R.string.key_smscommunicator_allowednumbers)) {
val settings = sp.getString(R.string.key_smscommunicator_allowednumbers, "")
allowedNumbers.clear()
val substrings = settings.split(";").toTypedArray()
for (number in substrings) {
val cleaned = number.replace("\\s+".toRegex(), "")
allowedNumbers.add(cleaned)
aapsLogger.debug(LTag.SMS, "Found allowed number: $cleaned")
}
}
}
fun isCommand(command: String, number: String): Boolean {
var found = false
commands.forEach { (k, _) ->
if (k == command) found = true
}
return found || messageToConfirm?.requester?.phoneNumber == number
}
fun isAllowedNumber(number: String): Boolean {
for (num in allowedNumbers) {
if (num == number) return true
}
return false
}
fun processSms(receivedSms: Sms) {
if (!isEnabled(PluginType.GENERAL)) {
aapsLogger.debug(LTag.SMS, "Ignoring SMS. Plugin disabled.")
return
}
if (!isAllowedNumber(receivedSms.phoneNumber)) {
aapsLogger.debug(LTag.SMS, "Ignoring SMS from: " + receivedSms.phoneNumber + ". Sender not allowed")
receivedSms.ignored = true
messages.add(receivedSms)
rxBus.send(EventSmsCommunicatorUpdateGui())
return
}
val pump = activePlugin.activePump
messages.add(receivedSms)
aapsLogger.debug(LTag.SMS, receivedSms.toString())
val divided = receivedSms.text.split(Regex("\\s+")).toTypedArray()
val remoteCommandsAllowed = sp.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)
val minDistance =
if (areMoreNumbers(sp.getString(R.string.key_smscommunicator_allowednumbers, "")))
T.mins(sp.getLong(R.string.key_smscommunicator_remotebolusmindistance, T.msecs(Constants.remoteBolusMinDistance).mins())).msecs()
else Constants.remoteBolusMinDistance
if (divided.isNotEmpty() && isCommand(divided[0].uppercase(Locale.getDefault()), receivedSms.phoneNumber)) {
when (divided[0].uppercase(Locale.getDefault())) {
"BG" ->
if (divided.size == 1) processBG(receivedSms)
else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
"LOOP" ->
if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed)))
else if (divided.size == 2 || divided.size == 3) processLOOP(divided, receivedSms)
else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
"NSCLIENT" ->
if (divided.size == 2) processNSCLIENT(divided, receivedSms)
else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
"PUMP" ->
if (!remoteCommandsAllowed && divided.size > 1) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed)))
else if (divided.size <= 3) processPUMP(divided, receivedSms)
else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
"PROFILE" ->
if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed)))
else if (divided.size == 2 || divided.size == 3) processPROFILE(divided, receivedSms)
else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
"BASAL" ->
if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed)))
else if (divided.size == 2 || divided.size == 3) processBASAL(divided, receivedSms)
else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
"EXTENDED" ->
if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed)))
else if (divided.size == 2 || divided.size == 3) processEXTENDED(divided, receivedSms)
else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
"BOLUS" ->
if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed)))
else if (commandQueue.bolusInQueue()) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_another_bolus_in_queue)))
else if (divided.size == 2 && dateUtil.now() - lastRemoteBolusTime < minDistance) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotebolusnotallowed)))
else if (divided.size == 2 && pump.isSuspended()) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.pumpsuspended)))
else if (divided.size == 2 || divided.size == 3) processBOLUS(divided, receivedSms)
else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
"CARBS" ->
if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed)))
else if (divided.size == 2 || divided.size == 3) processCARBS(divided, receivedSms)
else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
"CAL" ->
if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed)))
else if (divided.size == 2) processCAL(divided, receivedSms)
else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
"TARGET" ->
if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed)))
else if (divided.size == 2) processTARGET(divided, receivedSms)
else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
"SMS" ->
if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed)))
else if (divided.size == 2) processSMS(divided, receivedSms)
else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
"HELP" ->
if (divided.size == 1 || divided.size == 2) processHELP(divided, receivedSms)
else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
else ->
if (messageToConfirm?.requester?.phoneNumber == receivedSms.phoneNumber) {
val execute = messageToConfirm
messageToConfirm = null
execute?.action(divided[0])
} else {
messageToConfirm = null
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_unknowncommand)))
}
}
}
rxBus.send(EventSmsCommunicatorUpdateGui())
}
private fun processBG(receivedSms: Sms) {
val actualBG = iobCobCalculator.ads.actualBg()
val lastBG = iobCobCalculator.ads.lastBg()
var reply = ""
val units = profileFunction.getUnits()
if (actualBG != null) {
reply = rh.gs(R.string.sms_actualbg) + " " + actualBG.valueToUnitsString(units) + ", "
} else if (lastBG != null) {
val agoMilliseconds = dateUtil.now() - lastBG.timestamp
val agoMin = (agoMilliseconds / 60.0 / 1000.0).toInt()
reply = rh.gs(R.string.sms_lastbg) + " " + lastBG.valueToUnitsString(units) + " " + rh.gs(R.string.sms_minago, agoMin) + ", "
}
val glucoseStatus = glucoseStatusProvider.glucoseStatusData
if (glucoseStatus != null) reply += rh.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", "
val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
val cobInfo = iobCobCalculator.getCobInfo(false, "SMS COB")
reply += (rh.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
+ rh.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U "
+ rh.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U), "
+ rh.gs(R.string.cob) + ": " + cobInfo.generateCOBString())
sendSMS(Sms(receivedSms.phoneNumber, reply))
receivedSms.processed = true
}
private fun processLOOP(divided: Array<String>, receivedSms: Sms) {
when (divided[1].uppercase(Locale.getDefault())) {
"DISABLE", "STOP" -> {
if (loop.enabled) {
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_loopdisablereplywithcode, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() {
uel.log(Action.LOOP_DISABLED, Sources.SMS)
loop.enabled = false
commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() {
rxBus.send(EventRefreshOverview("SMS_LOOP_STOP"))
val replyText = rh.gs(R.string.smscommunicator_loophasbeendisabled) + " " +
rh.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed)
sendSMS(Sms(receivedSms.phoneNumber, replyText))
}
})
}
})
} else
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.loopisdisabled)))
receivedSms.processed = true
}
"ENABLE", "START" -> {
if (!loop.enabled) {
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_loopenablereplywithcode, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() {
uel.log(Action.LOOP_ENABLED, Sources.SMS)
loop.enabled = true
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_loophasbeenenabled)))
rxBus.send(EventRefreshOverview("SMS_LOOP_START"))
}
})
} else
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_loopisenabled)))
receivedSms.processed = true
}
"STATUS" -> {
val reply = if (loop.enabled) {
if (loop.isSuspended) rh.gs(R.string.loopsuspendedfor, loop.minutesToEndOfSuspend())
else rh.gs(R.string.smscommunicator_loopisenabled)
} else
rh.gs(R.string.loopisdisabled)
sendSMS(Sms(receivedSms.phoneNumber, reply))
receivedSms.processed = true
}
"RESUME" -> {
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_loopresumereplywithcode, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() {
uel.log(Action.RESUME, Sources.SMS)
disposable += repository.runTransactionForResult(CancelCurrentOfflineEventIfAnyTransaction(dateUtil.now()))
.subscribe({ result ->
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it)
})
rxBus.send(EventRefreshOverview("SMS_LOOP_RESUME"))
commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() {
if (!result.success) {
var replyText = rh.gs(R.string.smscommunicator_tempbasalfailed)
replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText))
}
}
})
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_loopresumed)))
}
})
}
"SUSPEND" -> {
var duration = 0
if (divided.size == 3) duration = SafeParse.stringToInt(divided[2])
duration = max(0, duration)
duration = min(180, duration)
if (duration == 0) {
receivedSms.processed = true
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_wrongduration)))
return
} else {
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_suspendreplywithcode, duration, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, duration) {
override fun run() {
uel.log(Action.SUSPEND, Sources.SMS)
commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() {
if (result.success) {
disposable += repository.runTransactionForResult(InsertAndCancelCurrentOfflineEventTransaction(dateUtil.now(), T.mins(anInteger().toLong()).msecs(), OfflineEvent.Reason.SUSPEND))
.subscribe({ result ->
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") }
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted OfflineEvent $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it)
})
rxBus.send(EventRefreshOverview("SMS_LOOP_SUSPENDED"))
val replyText = rh.gs(R.string.smscommunicator_loopsuspended) + " " +
rh.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
} else {
var replyText = rh.gs(R.string.smscommunicator_tempbasalcancelfailed)
replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText))
}
}
})
}
})
}
}
else -> sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
}
}
private fun processNSCLIENT(divided: Array<String>, receivedSms: Sms) {
if (divided[1].uppercase(Locale.getDefault()) == "RESTART") {
rxBus.send(EventNSClientRestart())
sendSMS(Sms(receivedSms.phoneNumber, "NSCLIENT RESTART SENT"))
receivedSms.processed = true
} else
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
}
private fun processHELP(divided: Array<String>, receivedSms: Sms) {
when {
divided.size == 1 -> {
sendSMS(Sms(receivedSms.phoneNumber, commands.keys.toString().replace("[", "").replace("]", "")))
receivedSms.processed = true
}
isCommand(divided[1].uppercase(Locale.getDefault()), receivedSms.phoneNumber) -> {
commands[divided[1].uppercase(Locale.getDefault())]?.let {
sendSMS(Sms(receivedSms.phoneNumber, it))
receivedSms.processed = true
}
}
else -> sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
}
}
private fun processPUMP(divided: Array<String>, receivedSms: Sms) {
if (divided.size == 1) {
commandQueue.readStatus(rh.gs(R.string.sms), object : Callback() {
override fun run() {
val pump = activePlugin.activePump
if (result.success) {
val reply = pump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, reply))
} else {
val reply = rh.gs(R.string.readstatusfailed)
sendSMS(Sms(receivedSms.phoneNumber, reply))
}
}
})
receivedSms.processed = true
} else if ((divided.size == 2) && (divided[1].equals("CONNECT", ignoreCase = true))) {
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_pumpconnectwithcode, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() {
uel.log(Action.RECONNECT, Sources.SMS)
commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() {
if (!result.success) {
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_pumpconnectfail)))
} else {
disposable += repository.runTransactionForResult(CancelCurrentOfflineEventIfAnyTransaction(dateUtil.now()))
.subscribe({ result ->
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it)
})
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_reconnect)))
rxBus.send(EventRefreshOverview("SMS_PUMP_START"))
}
}
})
}
})
} else if ((divided.size == 3) && (divided[1].equals("DISCONNECT", ignoreCase = true))) {
var duration = SafeParse.stringToInt(divided[2])
duration = max(0, duration)
duration = min(120, duration)
if (duration == 0) {
receivedSms.processed = true
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_wrongduration)))
return
} else {
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_pumpdisconnectwithcode, duration, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() {
uel.log(Action.DISCONNECT, Sources.SMS)
val profile = profileFunction.getProfile() ?: return
loop.goToZeroTemp(duration, profile, OfflineEvent.Reason.DISCONNECT_PUMP)
rxBus.send(EventRefreshOverview("SMS_PUMP_DISCONNECT"))
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_pumpdisconnected)))
}
})
}
} else {
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
return
}
}
private fun processPROFILE(divided: Array<String>, receivedSms: Sms) { // load profiles
val anInterface = activePlugin.activeProfileSource
val store = anInterface.profile
if (store == null) {
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.notconfigured)))
receivedSms.processed = true
return
}
val profileName = profileFunction.getProfileName()
val list = store.getProfileList()
if (divided[1].uppercase(Locale.getDefault()) == "STATUS") {
sendSMS(Sms(receivedSms.phoneNumber, profileName))
} else if (divided[1].uppercase(Locale.getDefault()) == "LIST") {
if (list.isEmpty()) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.invalidprofile)))
else {
var reply = ""
for (i in list.indices) {
if (i > 0) reply += "\n"
reply += (i + 1).toString() + ". "
reply += list[i]
}
sendSMS(Sms(receivedSms.phoneNumber, reply))
}
} else {
val pIndex = SafeParse.stringToInt(divided[1])
var percentage = 100
if (divided.size > 2) percentage = SafeParse.stringToInt(divided[2])
if (pIndex > list.size) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
else if (percentage == 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
else if (pIndex == 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
else {
val profile = store.getSpecificProfile(list[pIndex - 1] as String)
if (profile == null) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.noprofile)))
else {
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_profilereplywithcode, list[pIndex - 1], percentage, passCode)
receivedSms.processed = true
val finalPercentage = percentage
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, list[pIndex - 1] as String, finalPercentage) {
override fun run() {
if (profileFunction.createProfileSwitch(store, list[pIndex - 1] as String, 0, finalPercentage, 0, dateUtil.now())) {
val replyText = rh.gs(R.string.profileswitchcreated)
sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log(
Action.PROFILE_SWITCH, Sources.SMS, rh.gs(R.string.profileswitchcreated),
ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.profileswitchcreated))
)
} else {
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.invalidprofile)))
}
}
})
}
}
}
receivedSms.processed = true
}
private fun processBASAL(divided: Array<String>, receivedSms: Sms) {
if (divided[1].uppercase(Locale.getDefault()) == "CANCEL" || divided[1].uppercase(Locale.getDefault()) == "STOP") {
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_basalstopreplywithcode, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() {
commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() {
if (result.success) {
var replyText = rh.gs(R.string.smscommunicator_tempbasalcanceled)
replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalcanceled),
ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_tempbasalcanceled)))
} else {
var replyText = rh.gs(R.string.smscommunicator_tempbasalcancelfailed)
replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalcancelfailed),
ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_tempbasalcancelfailed)))
}
}
})
}
})
} else if (divided[1].endsWith("%")) {
var tempBasalPct = SafeParse.stringToInt(StringUtils.removeEnd(divided[1], "%"))
val durationStep = activePlugin.activePump.model().tbrSettings?.durationStep ?: 60
var duration = 30
if (divided.size > 2) duration = SafeParse.stringToInt(divided[2])
val profile = profileFunction.getProfile()
if (profile == null) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.noprofile)))
else if (tempBasalPct == 0 && divided[1] != "0%") sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
else if (duration <= 0 || duration % durationStep != 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongTbrDuration, durationStep)))
else {
tempBasalPct = constraintChecker.applyBasalPercentConstraints(Constraint(tempBasalPct), profile).value()
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_basalpctreplywithcode, tempBasalPct, duration, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, tempBasalPct, duration) {
override fun run() {
commandQueue.tempBasalPercent(anInteger(), secondInteger(), true, profile, PumpSync.TemporaryBasalType.NORMAL, object : Callback() {
override fun run() {
if (result.success) {
var replyText = if (result.isPercent) rh.gs(R.string.smscommunicator_tempbasalset_percent, result.percent, result.duration) else rh.gs(R.string.smscommunicator_tempbasalset, result.absolute, result.duration)
replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
if (result.isPercent)
uel.log(Action.TEMP_BASAL, Sources.SMS,
activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalset_percent, result.percent, result.duration),
ValueWithUnit.Percent(result.percent),
ValueWithUnit.Minute(result.duration))
else
uel.log(Action.TEMP_BASAL, Sources.SMS,
activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalset, result.absolute, result.duration),
ValueWithUnit.UnitPerHour(result.absolute),
ValueWithUnit.Minute(result.duration))
} else {
var replyText = rh.gs(R.string.smscommunicator_tempbasalfailed)
replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalfailed),
ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_tempbasalfailed)))
}
}
})
}
})
}
} else {
var tempBasal = SafeParse.stringToDouble(divided[1])
val durationStep = activePlugin.activePump.model().tbrSettings?.durationStep ?: 60
var duration = 30
if (divided.size > 2) duration = SafeParse.stringToInt(divided[2])
val profile = profileFunction.getProfile()
if (profile == null) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.noprofile)))
else if (tempBasal == 0.0 && divided[1] != "0") sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
else if (duration <= 0 || duration % durationStep != 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongTbrDuration, durationStep)))
else {
tempBasal = constraintChecker.applyBasalConstraints(Constraint(tempBasal), profile).value()
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_basalreplywithcode, tempBasal, duration, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, tempBasal, duration) {
override fun run() {
commandQueue.tempBasalAbsolute(aDouble(), secondInteger(), true, profile, PumpSync.TemporaryBasalType.NORMAL, object : Callback() {
override fun run() {
if (result.success) {
var replyText = if (result.isPercent) rh.gs(R.string.smscommunicator_tempbasalset_percent, result.percent, result.duration)
else rh.gs(R.string.smscommunicator_tempbasalset, result.absolute, result.duration)
replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
if (result.isPercent)
uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalset_percent, result.percent, result.duration),
ValueWithUnit.Percent(result.percent),
ValueWithUnit.Minute(result.duration))
else
uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalset, result.absolute, result.duration),
ValueWithUnit.UnitPerHour(result.absolute),
ValueWithUnit.Minute(result.duration))
} else {
var replyText = rh.gs(R.string.smscommunicator_tempbasalfailed)
replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalfailed),
ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_tempbasalfailed)))
}
}
})
}
})
}
}
}
private fun processEXTENDED(divided: Array<String>, receivedSms: Sms) {
if (divided[1].uppercase(Locale.getDefault()) == "CANCEL" || divided[1].uppercase(Locale.getDefault()) == "STOP") {
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_extendedstopreplywithcode, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() {
commandQueue.cancelExtended(object : Callback() {
override fun run() {
if (result.success) {
var replyText = rh.gs(R.string.smscommunicator_extendedcanceled)
replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
} else {
var replyText = rh.gs(R.string.smscommunicator_extendedcancelfailed)
replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_extendedcanceled),
ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_extendedcanceled)))
}
}
})
}
})
} else if (divided.size != 3) {
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
} else {
var extended = SafeParse.stringToDouble(divided[1])
val duration = SafeParse.stringToInt(divided[2])
extended = constraintChecker.applyExtendedBolusConstraints(Constraint(extended)).value()
if (extended == 0.0 || duration == 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
else {
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_extendedreplywithcode, extended, duration, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, extended, duration) {
override fun run() {
commandQueue.extendedBolus(aDouble(), secondInteger(), object : Callback() {
override fun run() {
if (result.success) {
var replyText = rh.gs(R.string.smscommunicator_extendedset, aDouble, duration)
if (config.APS) replyText += "\n" + rh.gs(R.string.loopsuspended)
replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
if (config.APS)
uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_extendedset, aDouble, duration) + " / " + rh.gs(R.string.loopsuspended),
ValueWithUnit.Insulin(aDouble ?: 0.0),
ValueWithUnit.Minute(duration),
ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.loopsuspended)))
else
uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_extendedset, aDouble, duration),
ValueWithUnit.Insulin(aDouble ?: 0.0),
ValueWithUnit.Minute(duration))
} else {
var replyText = rh.gs(R.string.smscommunicator_extendedfailed)
replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_extendedfailed),
ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_extendedfailed)))
}
}
})
}
})
}
}
}
private fun processBOLUS(divided: Array<String>, receivedSms: Sms) {
var bolus = SafeParse.stringToDouble(divided[1])
val isMeal = divided.size > 2 && divided[2].equals("MEAL", ignoreCase = true)
bolus = constraintChecker.applyBolusConstraints(Constraint(bolus)).value()
if (divided.size == 3 && !isMeal) {
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
} else if (bolus > 0.0) {
val passCode = generatePassCode()
val reply = if (isMeal)
rh.gs(R.string.smscommunicator_mealbolusreplywithcode, bolus, passCode)
else
rh.gs(R.string.smscommunicator_bolusreplywithcode, bolus, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, bolus) {
override fun run() {
val detailedBolusInfo = DetailedBolusInfo()
detailedBolusInfo.insulin = aDouble()
commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() {
val resultSuccess = result.success
val resultBolusDelivered = result.bolusDelivered
commandQueue.readStatus(rh.gs(R.string.sms), object : Callback() {
override fun run() {
if (resultSuccess) {
var replyText = if (isMeal)
rh.gs(R.string.smscommunicator_mealbolusdelivered, resultBolusDelivered)
else
rh.gs(R.string.smscommunicator_bolusdelivered, resultBolusDelivered)
replyText += "\n" + activePlugin.activePump.shortStatus(true)
lastRemoteBolusTime = dateUtil.now()
if (isMeal) {
profileFunction.getProfile()?.let { currentProfile ->
var eatingSoonTTDuration = sp.getInt(R.string.key_eatingsoon_duration, Constants.defaultEatingSoonTTDuration)
eatingSoonTTDuration =
if (eatingSoonTTDuration > 0) eatingSoonTTDuration
else Constants.defaultEatingSoonTTDuration
var eatingSoonTT = sp.getDouble(R.string.key_eatingsoon_target, if (currentProfile.units == GlucoseUnit.MMOL) Constants.defaultEatingSoonTTmmol else Constants.defaultEatingSoonTTmgdl)
eatingSoonTT =
when {
eatingSoonTT > 0 -> eatingSoonTT
currentProfile.units == GlucoseUnit.MMOL -> Constants.defaultEatingSoonTTmmol
else -> Constants.defaultEatingSoonTTmgdl
}
disposable += repository.runTransactionForResult(InsertAndCancelCurrentTemporaryTargetTransaction(
timestamp = dateUtil.now(),
duration = TimeUnit.MINUTES.toMillis(eatingSoonTTDuration.toLong()),
reason = TemporaryTarget.Reason.EATING_SOON,
lowTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()),
highTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits())
)).subscribe({ result ->
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") }
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
})
val tt = if (currentProfile.units == GlucoseUnit.MMOL) {
DecimalFormatter.to1Decimal(eatingSoonTT)
} else DecimalFormatter.to0Decimal(eatingSoonTT)
replyText += "\n" + rh.gs(R.string.smscommunicator_mealbolusdelivered_tt, tt, eatingSoonTTDuration)
}
}
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.BOLUS, Sources.SMS, replyText)
} else {
var replyText = rh.gs(R.string.smscommunicator_bolusfailed)
replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_bolusfailed),
ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_bolusfailed)))
}
}
})
}
})
}
})
} else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
}
private fun toTodayTime(hh_colon_mm: String): Long {
val p = Pattern.compile("(\\d+):(\\d+)( a.m.| p.m.| AM| PM|AM|PM|)")
val m = p.matcher(hh_colon_mm)
var retVal: Long = 0
if (m.find()) {
var hours = SafeParse.stringToInt(m.group(1))
val minutes = SafeParse.stringToInt(m.group(2))
if ((m.group(3) == " a.m." || m.group(3) == " AM" || m.group(3) == "AM") && m.group(1) == "12") hours -= 12
if ((m.group(3) == " p.m." || m.group(3) == " PM" || m.group(3) == "PM") && m.group(1) != "12") hours += 12
val t = DateTime()
.withHourOfDay(hours)
.withMinuteOfHour(minutes)
.withSecondOfMinute(0)
.withMillisOfSecond(0)
retVal = t.millis
}
return retVal
}
private fun processCARBS(divided: Array<String>, receivedSms: Sms) {
var grams = SafeParse.stringToInt(divided[1])
var time = dateUtil.now()
if (divided.size > 2) {
time = toTodayTime(divided[2].uppercase(Locale.getDefault()))
if (time == 0L) {
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
return
}
}
grams = constraintChecker.applyCarbsConstraints(Constraint(grams)).value()
if (grams == 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
else {
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_carbsreplywithcode, grams, dateUtil.timeString(time), passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, grams, time) {
override fun run() {
val detailedBolusInfo = DetailedBolusInfo()
detailedBolusInfo.carbs = anInteger().toDouble()
detailedBolusInfo.timestamp = secondLong()
commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() {
if (result.success) {
var replyText = rh.gs(R.string.smscommunicator_carbsset, anInteger)
replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.CARBS, Sources.SMS, activePlugin.activePump.shortStatus(true) + ": " + rh.gs(R.string.smscommunicator_carbsset, anInteger),
ValueWithUnit.Gram(anInteger ?: 0))
} else {
var replyText = rh.gs(R.string.smscommunicator_carbsfailed, anInteger)
replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.CARBS, Sources.SMS, activePlugin.activePump.shortStatus(true) + ": " + rh.gs(R.string.smscommunicator_carbsfailed, anInteger),
ValueWithUnit.Gram(anInteger ?: 0))
}
}
})
}
})
}
}
private fun processTARGET(divided: Array<String>, receivedSms: Sms) {
val isMeal = divided[1].equals("MEAL", ignoreCase = true)
val isActivity = divided[1].equals("ACTIVITY", ignoreCase = true)
val isHypo = divided[1].equals("HYPO", ignoreCase = true)
val isStop = divided[1].equals("STOP", ignoreCase = true) || divided[1].equals("CANCEL", ignoreCase = true)
if (isMeal || isActivity || isHypo) {
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_temptargetwithcode, divided[1].uppercase(Locale.getDefault()), passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() {
val units = profileFunction.getUnits()
var keyDuration = 0
var defaultTargetDuration = 0
var keyTarget = 0
var defaultTargetMMOL = 0.0
var defaultTargetMGDL = 0.0
var reason = TemporaryTarget.Reason.EATING_SOON
when {
isMeal -> {
keyDuration = R.string.key_eatingsoon_duration
defaultTargetDuration = Constants.defaultEatingSoonTTDuration
keyTarget = R.string.key_eatingsoon_target
defaultTargetMMOL = Constants.defaultEatingSoonTTmmol
defaultTargetMGDL = Constants.defaultEatingSoonTTmgdl
reason = TemporaryTarget.Reason.EATING_SOON
}
isActivity -> {
keyDuration = R.string.key_activity_duration
defaultTargetDuration = Constants.defaultActivityTTDuration
keyTarget = R.string.key_activity_target
defaultTargetMMOL = Constants.defaultActivityTTmmol
defaultTargetMGDL = Constants.defaultActivityTTmgdl
reason = TemporaryTarget.Reason.ACTIVITY
}
isHypo -> {
keyDuration = R.string.key_hypo_duration
defaultTargetDuration = Constants.defaultHypoTTDuration
keyTarget = R.string.key_hypo_target
defaultTargetMMOL = Constants.defaultHypoTTmmol
defaultTargetMGDL = Constants.defaultHypoTTmgdl
reason = TemporaryTarget.Reason.HYPOGLYCEMIA
}
}
var ttDuration = sp.getInt(keyDuration, defaultTargetDuration)
ttDuration = if (ttDuration > 0) ttDuration else defaultTargetDuration
var tt = sp.getDouble(keyTarget, if (units == GlucoseUnit.MMOL) defaultTargetMMOL else defaultTargetMGDL)
tt = Profile.toCurrentUnits(profileFunction, tt)
tt = if (tt > 0) tt else if (units == GlucoseUnit.MMOL) defaultTargetMMOL else defaultTargetMGDL
disposable += repository.runTransactionForResult(InsertAndCancelCurrentTemporaryTargetTransaction(
timestamp = dateUtil.now(),
duration = TimeUnit.MINUTES.toMillis(ttDuration.toLong()),
reason = reason,
lowTarget = Profile.toMgdl(tt, profileFunction.getUnits()),
highTarget = Profile.toMgdl(tt, profileFunction.getUnits())
)).subscribe({ result ->
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") }
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
})
val ttString = if (units == GlucoseUnit.MMOL) DecimalFormatter.to1Decimal(tt) else DecimalFormatter.to0Decimal(tt)
val replyText = rh.gs(R.string.smscommunicator_tt_set, ttString, ttDuration)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.TT, Sources.SMS,
ValueWithUnit.fromGlucoseUnit(tt, units.asText),
ValueWithUnit.Minute(ttDuration))
}
})
} else if (isStop) {
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_temptargetcancel, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() {
disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(dateUtil.now()))
.subscribe({ result ->
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
})
val replyText = rh.gs(R.string.smscommunicator_tt_canceled)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.CANCEL_TT, Sources.SMS, rh.gs(R.string.smscommunicator_tt_canceled),
ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_tt_canceled)))
}
})
} else
sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
}
private fun processSMS(divided: Array<String>, receivedSms: Sms) {
val isStop = (divided[1].equals("STOP", ignoreCase = true)
|| divided[1].equals("DISABLE", ignoreCase = true))
if (isStop) {
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_stopsmswithcode, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() {
sp.putBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)
val replyText = rh.gs(R.string.smscommunicator_stoppedsms)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.STOP_SMS, Sources.SMS, rh.gs(R.string.smscommunicator_stoppedsms),
ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_stoppedsms)))
}
})
} else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
}
private fun processCAL(divided: Array<String>, receivedSms: Sms) {
val cal = SafeParse.stringToDouble(divided[1])
if (cal > 0.0) {
val passCode = generatePassCode()
val reply = rh.gs(R.string.smscommunicator_calibrationreplywithcode, cal, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false, cal) {
override fun run() {
val result = xDripBroadcast.sendCalibration(aDouble!!)
val replyText =
if (result) rh.gs(R.string.smscommunicator_calibrationsent) else rh.gs(R.string.smscommunicator_calibrationfailed)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
if (result)
uel.log(Action.CALIBRATION, Sources.SMS, rh.gs(R.string.smscommunicator_calibrationsent),
ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_calibrationsent)))
else
uel.log(Action.CALIBRATION, Sources.SMS, rh.gs(R.string.smscommunicator_calibrationfailed),
ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_calibrationfailed)))
}
})
} else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
}
override fun sendNotificationToAllNumbers(text: String): Boolean {
var result = true
for (i in allowedNumbers.indices) {
val sms = Sms(allowedNumbers[i], text)
result = result && sendSMS(sms)
}
return result
}
private fun sendSMSToAllNumbers(sms: Sms) {
for (number in allowedNumbers) {
sms.phoneNumber = number
sendSMS(sms)
}
}
fun sendSMS(sms: Sms): Boolean {
sms.text = stripAccents(sms.text)
try {
aapsLogger.debug(LTag.SMS, "Sending SMS to " + sms.phoneNumber + ": " + sms.text)
if (sms.text.toByteArray().size <= 140) smsManager?.sendTextMessage(sms.phoneNumber, null, sms.text, null, null)
else {
val parts = smsManager?.divideMessage(sms.text)
smsManager?.sendMultipartTextMessage(sms.phoneNumber, null, parts,
null, null)
}
messages.add(sms)
} catch (e: IllegalArgumentException) {
return if (e.message == "Invalid message body") {
val notification = Notification(Notification.INVALID_MESSAGE_BODY, rh.gs(R.string.smscommunicator_messagebody), Notification.NORMAL)
rxBus.send(EventNewNotification(notification))
false
} else {
val notification = Notification(Notification.INVALID_PHONE_NUMBER, rh.gs(R.string.smscommunicator_invalidphonennumber), Notification.NORMAL)
rxBus.send(EventNewNotification(notification))
false
}
} catch (e: SecurityException) {
val notification = Notification(Notification.MISSING_SMS_PERMISSION, rh.gs(R.string.smscommunicator_missingsmspermission), Notification.NORMAL)
rxBus.send(EventNewNotification(notification))
return false
}
rxBus.send(EventSmsCommunicatorUpdateGui())
return true
}
private fun generatePassCode(): String =
rh.gs(R.string.smscommunicator_code_from_authenticator_for, otp.name())
private fun stripAccents(str: String): String {
var s = str
s = Normalizer.normalize(s, Normalizer.Form.NFD)
s = s.replace("[\\p{InCombiningDiacriticalMarks}]".toRegex(), "")
s = s.replace("ł", "l") // hack for Polish language (bug in libs)
return s
}
private fun areMoreNumbers(allowedNumbers: String?): Boolean {
return allowedNumbers?.let {
val knownNumbers = HashSet<String>()
val substrings = it.split(";").toTypedArray()
for (number in substrings) {
var cleaned = number.replace(Regex("\\s+"), "")
if (cleaned.length < 4) continue
cleaned = cleaned.replace("+", "")
cleaned = cleaned.replace("-", "")
if (!cleaned.matches(Regex("[0-9]+"))) continue
knownNumbers.add(cleaned)
}
knownNumbers.size > 1
} ?: false
}
} | agpl-3.0 | 146362eb64eced633dc0818dba9ffd07 | 59.931838 | 243 | 0.561095 | 4.920842 | false | false | false | false |
notsyncing/lightfur | lightfur-entity/src/main/kotlin/io/github/notsyncing/lightfur/entity/dsl/EntityBaseDSL.kt | 1 | 5563 | package io.github.notsyncing.lightfur.entity.dsl
import com.alibaba.fastjson.JSONObject
import io.github.notsyncing.lightfur.DataSession
import io.github.notsyncing.lightfur.entity.EntityField
import io.github.notsyncing.lightfur.entity.EntityGlobal
import io.github.notsyncing.lightfur.entity.EntityModel
import io.github.notsyncing.lightfur.entity.EntityQueryExecutor
import io.github.notsyncing.lightfur.sql.base.SQLPart
import io.github.notsyncing.lightfur.sql.builders.SelectQueryBuilder
import io.github.notsyncing.lightfur.sql.builders.UpdateQueryBuilder
import io.github.notsyncing.lightfur.sql.models.ColumnModel
import io.github.notsyncing.lightfur.sql.models.TableModel
import io.github.notsyncing.lightfur.utils.FutureUtils
import kotlinx.coroutines.experimental.future.await
import kotlinx.coroutines.experimental.future.future
import java.util.concurrent.CompletableFuture
abstract class EntityBaseDSL<F: EntityModel>(val finalModel: F?,
val isQuery: Boolean = false,
val isInsert: Boolean = false,
private val cacheTag: String? = null) {
abstract protected val builder: SQLPart
private var cachedSQL: String? = null
protected var cached: Boolean = false
get() = cachedSQL != null
var requireTableAlias = false
companion object {
private var executor: EntityQueryExecutor<Any, Any, Any>? = null
fun setQueryExecutor(e: EntityQueryExecutor<*, *, *>) {
executor = e as EntityQueryExecutor<Any, Any, Any>
}
@JvmStatic
protected fun getTableModelFromEntityModel(m: EntityModel): TableModel {
val table = TableModel()
table.name = m.table
table.database = m.database
table.schema = m.schema
table.alias = "${m::class.java.simpleName}_${m.hashCode()}"
return table
}
@JvmStatic
protected fun getTableModelFromSubQuery(s: EntitySelectDSL<*>): TableModel {
val table = TableModel()
table.subQuery = s.toSQLPart() as SelectQueryBuilder
table.alias = "${s::class.java.simpleName}_${s.hashCode()}"
return table
}
@JvmStatic
fun getColumnModelFromEntityField(info: EntityField<*>): ColumnModel {
val c = ColumnModel()
c.table = EntityGlobal.tableModels[info.entity::class.java]!!.clone()
if (info.entity.skipTableName) {
c.table.name = null
}
if (!info.entity.skipTableAlias) {
c.table.alias = "${info.entity::class.java.simpleName}_${info.entity.hashCode()}"
}
c.modelType = info.entity::class.java.canonicalName
c.column = info.dbColumn
c.fieldName = info.name
c.fieldType = info.dbType
c.isAutoGenerated = info.dbAutoGenerated
c.isPrimaryKey = info.dbPrimaryKey
if (info.entity.modelAliasBeforeColumnName) {
c.alias = "${info.entity::class.java.simpleName}_${info.entity.hashCode()}_${c.fieldName}"
}
return c
}
}
init {
if (cacheTag != null) {
cachedSQL = EntityGlobal.sqlCache[cacheTag]
}
}
fun execute(session: DataSession<*, *, *>? = null): CompletableFuture<Pair<List<F>, Int>> {
if (executor == null) {
return FutureUtils.failed(RuntimeException("You must specify an EntityQueryExecutor!"))
}
return executor!!.execute(this, session as DataSession<Any, Any, Any>?) as CompletableFuture<Pair<List<F>, Int>>
}
fun executeFirst(session: DataSession<*, *, *>? = null): CompletableFuture<F?> {
return execute(session)
.thenApply { (l, c) ->
if (c > 0) {
l[0]
} else {
null
}
}
}
fun queryRaw(session: DataSession<*, *, *>? = null): CompletableFuture<Any?> {
if (executor == null) {
return FutureUtils.failed(RuntimeException("You must specify an EntityQueryExecutor!"))
}
return executor!!.queryRaw(this, session as DataSession<Any, Any, Any>?) as CompletableFuture<Any?>
}
fun queryJson(session: DataSession<*, *, *>? = null): CompletableFuture<List<JSONObject>> {
if (executor == null) {
return FutureUtils.failed(RuntimeException("You must specify an EntityQueryExecutor!"))
}
return executor!!.queryJson(this, session as DataSession<Any, Any, Any>?)
}
fun executeRaw(session: DataSession<*, *, *>? = null) = future {
val sql = toSQL()
if (sql == UpdateQueryBuilder.NOTHING_TO_UPDATE) {
return@future
}
val params = toSQLParameters().toTypedArray()
val db = session ?: DataSession.start()
try {
db.update(sql, *params).await()
} finally {
if (session == null) {
db.end().await()
}
}
}
open fun toSQLPart() = builder
open fun toSQL(): String {
// FIXME: Implement parameter-only generation
if (cachedSQL != null) {
// This call is for parameter generation
builder.toString()
}
return cachedSQL ?: builder.toString()
}
open fun toSQLParameters() = builder.parameters
} | gpl-3.0 | 42971c6a3d6b812e739dcdba0e470955 | 33.775 | 120 | 0.598778 | 4.694515 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/interpret/module/ModuleClass.kt | 1 | 1280 | package com.bajdcc.LALR1.interpret.module
import com.bajdcc.LALR1.grammar.Grammar
import com.bajdcc.LALR1.grammar.runtime.RuntimeCodePage
import com.bajdcc.LALR1.grammar.runtime.RuntimeDebugValue
import com.bajdcc.LALR1.grammar.runtime.RuntimeObject
import com.bajdcc.LALR1.grammar.runtime.data.RuntimeMap
import com.bajdcc.util.ResourceLoader
/**
* 【模块】类
*
* @author bajdcc
*/
class ModuleClass : IInterpreterModule {
private var runtimeCodePage: RuntimeCodePage? = null
override val moduleName: String
get() = "sys.class"
override val moduleCode: String
get() = ResourceLoader.load(javaClass)
override val codePage: RuntimeCodePage
@Throws(Exception::class)
get() {
if (runtimeCodePage != null)
return runtimeCodePage!!
val base = ResourceLoader.load(javaClass)
val grammar = Grammar(base)
val page = grammar.codePage
val info = page.info
info.addExternalValue("g_class_context", RuntimeDebugValue { globalContext })
runtimeCodePage = page
return page
}
companion object {
val instance = ModuleClass()
private val globalContext = RuntimeObject(RuntimeMap())
}
} | mit | d862d866a04d32e2cbbcb53d51795a4c | 26.042553 | 89 | 0.670866 | 4.568345 | false | false | false | false |
KotlinNLP/SimpleDNN | src/main/kotlin/com/kotlinnlp/simplednn/core/neuralnetwork/preset/HighwayNeuralNetwork.kt | 1 | 2722 | package com.kotlinnlp.simplednn.core.neuralnetwork.preset
import com.kotlinnlp.simplednn.core.functionalities.activations.ActivationFunction
import com.kotlinnlp.simplednn.core.functionalities.initializers.GlorotInitializer
import com.kotlinnlp.simplednn.core.functionalities.initializers.Initializer
import com.kotlinnlp.simplednn.core.layers.LayerInterface
import com.kotlinnlp.simplednn.core.layers.LayerType
import com.kotlinnlp.simplednn.core.layers.StackedLayersParameters
/**
* The Highway neural network factory.
*/
object HighwayNeuralNetwork {
/**
* @param inputSize the size of the input layer
* @param inputType the type of the input layer (Dense -default-, Sparse, SparseBinary)
* @param hiddenSize the size of the hidden layers
* @param hiddenActivation the activation function of the hidden layers
* @param numOfHighway the number of hidden highway layers (at least 1, the default)
* @param outputSize the size of the output layer
* @param outputActivation the activation function of the output layer
* @param weightsInitializer the initializer of the weights (zeros if null, default: Glorot)
* @param biasesInitializer the initializer of the biases (zeros if null, default: Glorot)
*/
operator fun invoke(inputSize: Int,
inputType: LayerType.Input = LayerType.Input.Dense,
hiddenSize: Int,
hiddenActivation: ActivationFunction?,
numOfHighway: Int = 1,
outputSize: Int,
outputActivation: ActivationFunction?,
weightsInitializer: Initializer? = GlorotInitializer(),
biasesInitializer: Initializer? = GlorotInitializer()): StackedLayersParameters {
require(numOfHighway >= 1) { "The number of highway layers must be >= 1." }
val layersConfiguration = mutableListOf<LayerInterface>().apply {
add(LayerInterface(size = inputSize, type = inputType))
add(LayerInterface(
size = hiddenSize,
activationFunction = hiddenActivation,
connectionType = LayerType.Connection.Feedforward))
repeat(numOfHighway) {
add(LayerInterface(
size = hiddenSize,
activationFunction = hiddenActivation,
connectionType = LayerType.Connection.Highway))
}
add(LayerInterface(
size = outputSize,
activationFunction = outputActivation,
connectionType = LayerType.Connection.Feedforward))
}
return StackedLayersParameters(
layersConfiguration = *layersConfiguration.toTypedArray(),
weightsInitializer = weightsInitializer,
biasesInitializer = biasesInitializer)
}
}
| mpl-2.0 | a21e6d66594c00d621b48087576a88ff | 40.876923 | 103 | 0.705731 | 5.285437 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/posts/PrepublishingViewModel.kt | 1 | 6556 | package org.wordpress.android.ui.posts
import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Parcelable
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.parcelize.Parcelize
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.generated.TaxonomyActionBuilder
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.TaxonomyStore.OnTaxonomyChanged
import org.wordpress.android.ui.posts.PrepublishingHomeItemUiState.ActionType
import org.wordpress.android.ui.posts.PrepublishingScreen.ADD_CATEGORY
import org.wordpress.android.ui.posts.PrepublishingScreen.CATEGORIES
import org.wordpress.android.ui.posts.PrepublishingScreen.HOME
import org.wordpress.android.ui.posts.PrepublishingScreen.PUBLISH
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T
import org.wordpress.android.viewmodel.Event
import java.io.Serializable
import javax.inject.Inject
const val KEY_SCREEN_STATE = "key_screen_state"
class PrepublishingViewModel @Inject constructor(private val dispatcher: Dispatcher) : ViewModel() {
private var isStarted = false
private lateinit var site: SiteModel
private val _navigationTarget = MutableLiveData<Event<PrepublishingNavigationTarget>>()
val navigationTarget: LiveData<Event<PrepublishingNavigationTarget>> = _navigationTarget
private var currentScreen: PrepublishingScreen? = null
private val _dismissBottomSheet = MutableLiveData<Event<Unit>>()
val dismissBottomSheet: LiveData<Event<Unit>> = _dismissBottomSheet
private val _dismissKeyboard = MutableLiveData<Event<Unit>>()
val dismissKeyboard: LiveData<Event<Unit>> = _dismissKeyboard
private val _triggerOnSubmitButtonClickedListener = MutableLiveData<Event<PublishPost>>()
val triggerOnSubmitButtonClickedListener: LiveData<Event<PublishPost>> = _triggerOnSubmitButtonClickedListener
private val _triggerOnDeviceBackPressed = MutableLiveData<Event<PrepublishingScreen>>()
val triggerOnDeviceBackPressed: LiveData<Event<PrepublishingScreen>> = _triggerOnDeviceBackPressed
init {
dispatcher.register(this)
}
override fun onCleared() {
super.onCleared()
dispatcher.unregister(this)
}
fun start(
site: SiteModel,
currentScreenFromSavedState: PrepublishingScreen?
) {
if (isStarted) return
isStarted = true
this.site = site
this.currentScreen = currentScreenFromSavedState ?: HOME
currentScreen?.let { screen ->
navigateToScreen(screen)
}
fetchTags()
}
private fun navigateToScreen(prepublishingScreen: PrepublishingScreen, bundle: Bundle? = null) {
// Note: given we know both the HOME, TAGS and ADD_CATEGORY screens have an EditText, we can ask to send the
// dismissKeyboard signal only when we're not either in one of these nor navigating towards one of these.
// At this point in code we only know where we want to navigate to, but it's ok since landing on any of these
// two we'll want the keyboard to stay up if it was already up ;) (i.e. don't dismiss it).
// For the case where this is not a story and hence there's no EditText in the HOME screen, we're ok too,
// because there wouldn't have been a keyboard up anyway.
if (prepublishingScreen == PUBLISH ||
prepublishingScreen == CATEGORIES) {
_dismissKeyboard.postValue(Event(Unit))
}
updateNavigationTarget(PrepublishingNavigationTarget(site, prepublishingScreen, bundle))
}
// Send this back out to the current screen and so it can determine if it needs to save
// any data before accepting a backPress - in our case, the only view that needs this today
// is the Categories selection & AddCategory
fun onDeviceBackPressed() {
if (currentScreen == CATEGORIES || currentScreen == ADD_CATEGORY) {
_triggerOnDeviceBackPressed.value = Event(currentScreen as PrepublishingScreen)
} else {
onBackClicked()
}
}
fun onBackClicked(bundle: Bundle? = null) {
when {
currentScreen == ADD_CATEGORY -> {
currentScreen = CATEGORIES
navigateToScreen(currentScreen as PrepublishingScreen, bundle)
}
currentScreen != HOME -> {
currentScreen = HOME
navigateToScreen(currentScreen as PrepublishingScreen)
}
else -> {
_dismissBottomSheet.postValue(Event(Unit))
}
}
}
fun onCloseClicked() {
_dismissBottomSheet.postValue(Event(Unit))
}
private fun updateNavigationTarget(target: PrepublishingNavigationTarget) {
_navigationTarget.postValue(Event(target))
}
fun writeToBundle(outState: Bundle) {
outState.putParcelable(KEY_SCREEN_STATE, currentScreen)
}
fun onActionClicked(actionType: ActionType, bundle: Bundle? = null) {
val screen = PrepublishingScreen.valueOf(actionType.name)
currentScreen = screen
navigateToScreen(screen, bundle)
}
fun onSubmitButtonClicked(publishPost: PublishPost) {
onCloseClicked()
_triggerOnSubmitButtonClickedListener.postValue(Event(publishPost))
}
/**
* Fetches the tags so that they will be available when the Tags action is clicked
*/
private fun fetchTags() {
dispatcher.dispatch(TaxonomyActionBuilder.newFetchTagsAction(site))
}
@Suppress("unused")
@Subscribe(threadMode = ThreadMode.MAIN)
fun onTaxonomyChanged(event: OnTaxonomyChanged) {
if (event.isError) {
AppLog.e(
T.POSTS,
"An error occurred while updating taxonomy with type: " + event.error.type
)
}
}
}
@Parcelize
@SuppressLint("ParcelCreator")
enum class PrepublishingScreen : Parcelable {
HOME,
PUBLISH,
TAGS,
CATEGORIES,
ADD_CATEGORY
}
data class PrepublishingNavigationTarget(
val site: SiteModel,
val targetScreen: PrepublishingScreen,
val bundle: Bundle? = null
)
@Suppress("SerialVersionUIDInSerializableClass")
data class PrepublishingAddCategoryRequest(
val categoryText: String,
val categoryParentId: Long
) : Serializable
| gpl-2.0 | 6c1d95ef3639558162d12e807c4c87e7 | 35.831461 | 117 | 0.709884 | 4.91823 | false | false | false | false |
google/identity-credential | appholder/src/main/java/com/android/mdl/app/authprompt/UserAuthPromptBuilder.kt | 1 | 4393 | package com.android.mdl.app.authprompt
import android.util.Log
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG
import androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL
import androidx.biometric.BiometricManager.BIOMETRIC_SUCCESS
import androidx.biometric.BiometricPrompt
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
class UserAuthPromptBuilder private constructor(private val fragment: Fragment) {
private var title: String = ""
private var subtitle: String = ""
private var description: String = ""
private var negativeButton: String = ""
private var forceLskf: Boolean = false
private var onSuccess: () -> Unit = {}
private var onFailure: () -> Unit = {}
private var onCancelled: () -> Unit = {}
private val biometricAuthCallback = object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
// reached max attempts to authenticate the user, or authentication dialog was cancelled
if (errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON) {
onCancelled.invoke()
} else {
Log.d(LOG_TAG, "User authentication failed $errorCode - $errString")
onFailure.invoke()
}
}
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
Log.d(LOG_TAG, "User authentication succeeded")
onSuccess.invoke()
}
override fun onAuthenticationFailed() {
super.onAuthenticationFailed()
Log.d(LOG_TAG, "User authentication failed")
onFailure.invoke()
}
}
fun withTitle(title: String) = apply {
this.title = title
}
fun withSubtitle(subtitle: String) = apply {
this.subtitle = subtitle
}
fun withDescription(description: String) = apply {
this.description = description
}
fun withNegativeButton(negativeButton: String) = apply {
this.negativeButton = negativeButton
}
fun setForceLskf(forceLskf: Boolean) = apply {
this.forceLskf = forceLskf
}
fun withSuccessCallback(onSuccess: () -> Unit) = apply {
this.onSuccess = onSuccess
}
fun withFailureCallback(onFailure: () -> Unit) = apply {
this.onFailure = onFailure
}
fun withCancelledCallback(onCancelled: () -> Unit) = apply {
this.onCancelled = onCancelled
}
fun build(): BiometricUserAuthPrompt {
val promptInfoBuilder = BiometricPrompt.PromptInfo.Builder()
.setTitle(title)
.setSubtitle(subtitle)
.setDescription(description)
.setConfirmationRequired(false)
if (forceLskf) {
// TODO: this works only on Android 11 or later but for now this is fine
// as this is just a reference/test app and this path is only hit if
// the user actually presses the "Use PIN" button. Longer term, we should
// fall back to using KeyGuard which will work on all Android versions.
promptInfoBuilder.setAllowedAuthenticators(DEVICE_CREDENTIAL)
} else {
val canUseBiometricAuth = BiometricManager
.from(fragment.requireContext())
.canAuthenticate(BIOMETRIC_STRONG) == BIOMETRIC_SUCCESS
if (canUseBiometricAuth) {
promptInfoBuilder.setNegativeButtonText(negativeButton)
} else {
// No biometrics enrolled, force use of LSKF
promptInfoBuilder.setDeviceCredentialAllowed(true)
}
}
val promptInfo = promptInfoBuilder.build()
val executor = ContextCompat.getMainExecutor(fragment.requireContext())
val prompt = BiometricPrompt(fragment, executor, biometricAuthCallback)
return BiometricUserAuthPrompt(prompt, promptInfo)
}
companion object {
private const val LOG_TAG = "Holder-UserAuthPrompt"
fun requestUserAuth(fragment: Fragment): UserAuthPromptBuilder {
return UserAuthPromptBuilder(fragment)
}
}
} | apache-2.0 | 7fd0ecb45f8561c623d3eb7951406ab5 | 35.92437 | 100 | 0.658775 | 5.037844 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KotlinEqualityInstruction.kt | 4 | 3608 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.dfa
import com.intellij.codeInspection.dataFlow.interpreter.DataFlowInterpreter
import com.intellij.codeInspection.dataFlow.lang.ir.DfaInstructionState
import com.intellij.codeInspection.dataFlow.lang.ir.ExpressionPushingInstruction
import com.intellij.codeInspection.dataFlow.lang.ir.Instruction
import com.intellij.codeInspection.dataFlow.memory.DfaMemoryState
import com.intellij.codeInspection.dataFlow.types.DfTypes
import com.intellij.codeInspection.dataFlow.value.DfaControlTransferValue
import com.intellij.codeInspection.dataFlow.value.DfaValueFactory
import org.jetbrains.kotlin.idea.inspections.dfa.KotlinAnchor.KotlinExpressionAnchor
import org.jetbrains.kotlin.psi.KtExpression
/**
* Instruction that processes kotlin == or != operators between unknown reference values, assuming the following contract:
* if x == y => true
* else if x == null => false
* else if y == null => false
* else unknown
*/
class KotlinEqualityInstruction(
equality: KtExpression,
private val negated: Boolean,
private val exceptionTransfer: DfaControlTransferValue?
) : ExpressionPushingInstruction(KotlinExpressionAnchor(equality)) {
override fun bindToFactory(factory: DfaValueFactory): Instruction =
if (exceptionTransfer == null) this
else KotlinEqualityInstruction((dfaAnchor as KotlinExpressionAnchor).expression, negated, exceptionTransfer.bindToFactory(factory))
override fun accept(interpreter: DataFlowInterpreter, stateBefore: DfaMemoryState): Array<DfaInstructionState> {
val right = stateBefore.pop()
val left = stateBefore.pop()
val result = mutableListOf<DfaInstructionState>()
if (exceptionTransfer != null) {
val exceptional = stateBefore.createCopy()
result += exceptionTransfer.dispatch(exceptional, interpreter)
}
val eqState = stateBefore.createCopy()
val leftEqRight = left.eq(right)
if (eqState.applyCondition(leftEqRight)) {
pushResult(interpreter, eqState, DfTypes.booleanValue(!negated))
result += nextState(interpreter, eqState)
}
if (stateBefore.applyCondition(leftEqRight.negate())) {
val leftNullState = stateBefore.createCopy()
val nullValue = interpreter.factory.fromDfType(DfTypes.NULL)
val leftEqNull = left.eq(nullValue)
if (leftNullState.applyCondition(leftEqNull)) {
pushResult(interpreter, leftNullState, DfTypes.booleanValue(negated))
result += nextState(interpreter, leftNullState)
}
if (stateBefore.applyCondition(leftEqNull.negate())) {
val rightNullState = stateBefore.createCopy()
val rightEqNull = right.eq(nullValue)
if (rightNullState.applyCondition(rightEqNull)) {
pushResult(interpreter, rightNullState, DfTypes.booleanValue(negated))
result += nextState(interpreter, rightNullState)
}
if (stateBefore.applyCondition(rightEqNull.negate())) {
pushResult(interpreter, stateBefore, DfTypes.BOOLEAN)
result += nextState(interpreter, stateBefore)
}
}
}
return result.toTypedArray()
}
override fun toString(): String {
return if (negated) "NOT_EQUAL" else "EQUAL"
}
} | apache-2.0 | 70dad6b4291fccc2de8c7a9b1a1f9fbc | 48.438356 | 158 | 0.70316 | 5.018081 | false | false | false | false |
mdaniel/intellij-community | platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/impl/EditorHistoryManagerTest.kt | 1 | 4094 | // 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.openapi.fileEditor.impl
import com.intellij.diagnostic.ThreadDumper
import com.intellij.openapi.application.EDT
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.project.impl.ProjectServiceContainerCustomizer
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.project.stateStore
import com.intellij.testFramework.*
import com.intellij.testFramework.TestApplicationManager.Companion.publishHeapDump
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.io.write
import com.intellij.util.ref.GCWatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Fail.fail
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.nio.file.Path
class EditorHistoryManagerTest {
companion object {
@ClassRule
@JvmField
val appRule = ApplicationRule()
}
@Rule
@JvmField
val tempDir = TemporaryDirectory()
@Rule
@JvmField
val disposable = DisposableRule()
@Test
fun testSavingStateForNotOpenedEditors() {
val dir = tempDir.newPath("foo")
val file = dir.resolve("some.txt")
file.write("first line\nsecond line")
val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(file.systemIndependentPath)!!
useRealFileEditorManager()
runBlocking {
openProjectPerformTaskCloseProject(dir) { project ->
val editor = FileEditorManager.getInstance(project).openTextEditor(OpenFileDescriptor(project, virtualFile), false)!!
try {
EditorTestUtil.waitForLoading(editor)
EditorTestUtil.addFoldRegion(editor, 15, 16, ".", true)
}
finally {
FileEditorManager.getInstance(project).closeFile(virtualFile)
}
}
val threadDumpBefore = ThreadDumper.dumpThreadsToString()
fun createWatcher() = GCWatcher.tracking(FileDocumentManager.getInstance().getCachedDocument(virtualFile))
createWatcher().ensureCollected()
val document = FileDocumentManager.getInstance().getCachedDocument(virtualFile)
if (document != null) {
fail<Any>("Document wasn't collected, see heap dump at ${publishHeapDump(EditorHistoryManagerTest::class.java.name)}")
System.err.println("Keeping a reference to the document: $document")
System.err.println(threadDumpBefore)
}
openProjectPerformTaskCloseProject(dir) { }
openProjectPerformTaskCloseProject(dir) { project ->
val newEditor = FileEditorManager.getInstance(project).openTextEditor(OpenFileDescriptor(project, virtualFile), false)!!
EditorTestUtil.waitForLoading(newEditor)
assertThat(newEditor.foldingModel.allFoldRegions.contentToString()).isEqualTo("[FoldRegion +(15:16), placeholder='.']")
}
}
}
private fun useRealFileEditorManager() {
ProjectServiceContainerCustomizer.getEp().maskAll(listOf(object : ProjectServiceContainerCustomizer {
override fun serviceRegistered(project: Project) {
project.registerComponentImplementation(FileEditorManager::class.java, PsiAwareFileEditorManagerImpl::class.java, false)
}
}), disposable.disposable, false)
}
}
private suspend fun openProjectPerformTaskCloseProject(projectDir: Path, task: (Project) -> Unit) {
val project = ProjectManagerEx.getInstanceEx().openProject(projectDir, createTestOpenProjectOptions())!!
try {
withContext(Dispatchers.EDT) {
task(project)
project.stateStore.saveComponent(EditorHistoryManager.getInstance(project))
}
}
finally {
ProjectManagerEx.getInstanceEx().forceCloseProjectAsync(project)
}
}
| apache-2.0 | 367643a8c03ce24e9a61a38b2e6ad451 | 38.747573 | 128 | 0.765999 | 4.868014 | false | true | false | false |
AberrantFox/hotbot | src/main/kotlin/me/aberrantfox/hotbot/extensions/stdlib/StringExtensions.kt | 1 | 2638 | package me.aberrantfox.hotbot.extensions.stdlib
import me.aberrantfox.hotbot.permissions.PermissionLevel
import net.dv8tion.jda.core.JDA
import net.dv8tion.jda.core.entities.Guild
import net.dv8tion.jda.core.entities.Role
import net.dv8tion.jda.core.entities.User
private val urlRegexes = listOf(
"[-a-zA-Z0-9@:%._+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_+.~#?&//=]*)",
"https?://(www\\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_+.~#?&//=]*)"
).map { it.toRegex() }
private val inviteRegex = "(\n|.)*((discord|discordapp).(gg|me|io|com/invite)/)(\n|.)*".toRegex()
fun String.containsURl() = urlRegexes.any { this.replace("\n", "").contains(it) }
fun String.containsInvite() = inviteRegex.matches(this)
fun String.formatJdaDate() = this.substring(0, this.indexOf("T"))
fun String.limit(length: Int) = if (this.length > length) substring(length) else this
fun String.isInteger(): Boolean =
try {
this.toInt()
true
} catch (e: NumberFormatException) {
false
}
fun String.isLong(): Boolean =
try {
this.toLong()
true
} catch (e: NumberFormatException) {
false
}
fun String.isDouble(): Boolean =
try {
this.toDouble()
true
} catch (e: NumberFormatException) {
false
}
fun String.isBooleanValue(): Boolean =
when(this.toLowerCase()) {
"true" -> true
"false" -> true
"t" -> true
"f" -> true
else -> false
}
fun String.toBooleanValue(): Boolean =
when(this.toLowerCase()) {
"true" -> true
"t" -> true
else -> false
}
fun String.idToName(jda: JDA): String = jda.getUserById(this).name
fun String.idToUser(jda: JDA): User? = jda.getUserById(this.trimToID())
fun String.retrieveIdToUser(jda: JDA): User = jda.retrieveUserById(this.trimToID()).complete()
fun String.retrieveIdToName(jda: JDA): String = jda.retrieveUserById(this.trimToID()).complete().name
fun String.toRole(guild: Guild): Role? = guild.getRoleById(this)
fun String.sanitiseMentions() = this.replace("@", "")
fun String.trimToID(): String =
if (this.startsWith("<@") && this.endsWith(">")) {
replace("<", "")
.replace(">", "")
.replace("@", "")
.replace("!", "") // Mentions with nicknames
.replace("&", "") // Role mentions
} else {
this
}
fun String.isPermission() = PermissionLevel.isLevel(this) | mit | ba9396bfa356ed71ed442d3a9e46997e | 30.047059 | 101 | 0.560652 | 3.545699 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveAtFromAnnotationArgument.kt | 4 | 1547 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.KtAnnotatedExpression
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtFile
class RemoveAtFromAnnotationArgument(constructor: KtAnnotationEntry) : KotlinQuickFixAction<KtAnnotationEntry>(constructor) {
override fun getText() = KotlinBundle.message("remove.from.annotation.argument")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val elementToReplace = (element?.parent as? KtAnnotatedExpression) ?: return
val document = file.viewProvider.document
val pos = elementToReplace.textRange.startOffset
if (document.charsSequence[pos] == '@') {
document.deleteString(pos, pos + 1)
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtAnnotationEntry>? =
(diagnostic.psiElement as? KtAnnotationEntry)?.let { RemoveAtFromAnnotationArgument(it) }
}
}
| apache-2.0 | 52c622054f33c52ec4e68e8cb326b26f | 43.2 | 158 | 0.767292 | 4.789474 | false | false | false | false |
GunoH/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesTableItem.kt | 3 | 5730 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages
import com.intellij.ide.CopyProvider
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DataKey
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.ide.CopyPasteManager
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel
import com.jetbrains.packagesearch.intellij.plugin.util.VersionNameComparator
import java.awt.datatransfer.StringSelection
internal sealed class PackagesTableItem<T : PackageModel> : DataProvider, CopyProvider {
val packageModel: T
get() = uiPackageModel.packageModel
abstract val uiPackageModel: UiPackageModel<T>
abstract val allScopes: List<PackageScope>
protected open val handledDataKeys: List<DataKey<*>> = listOf(PlatformDataKeys.COPY_PROVIDER)
fun canProvideDataFor(key: String) = handledDataKeys.any { it.`is`(key) }
override fun getData(dataId: String): Any? = when {
PlatformDataKeys.COPY_PROVIDER.`is`(dataId) -> this
else -> null
}
override fun performCopy(dataContext: DataContext) =
CopyPasteManager.getInstance().setContents(StringSelection(getTextForCopy(packageModel)))
private fun getTextForCopy(packageModel: PackageModel) = buildString {
appendLine("${packageModel.groupId}:${packageModel.artifactId}")
append(additionalCopyText())
packageModel.remoteInfo?.versions?.let { versions ->
if (versions.any()) {
appendLine()
append("${PackageSearchBundle.message("packagesearch.package.copyableInfo.availableVersions")} ")
append(
versions.map { it.version }
.distinct()
.sortedWith(VersionNameComparator)
.joinToString(", ")
.removeSuffix(", ")
)
}
}
packageModel.remoteInfo?.gitHub?.let { gitHub ->
appendLine()
append(PackageSearchBundle.message("packagesearch.package.copyableInfo.githubStats"))
gitHub.stars?.let { ghStars ->
append(" ")
append(PackageSearchBundle.message("packagesearch.package.copyableInfo.githubStats.stars", ghStars))
}
gitHub.forks?.let { ghForks ->
if (gitHub.stars != null) append(',')
append(" ")
append(PackageSearchBundle.message("packagesearch.package.copyableInfo.githubStats.forks", ghForks))
}
}
packageModel.remoteInfo?.stackOverflow?.tags?.let { tags ->
if (tags.any()) {
appendLine()
append("${PackageSearchBundle.message("packagesearch.package.copyableInfo.stackOverflowTags")} ")
append(
tags.joinToString(", ") { "${it.tag} (${it.count})" }
.removeSuffix(", ")
)
}
}
}
protected abstract fun additionalCopyText(): String
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
override fun isCopyVisible(dataContext: DataContext) = true
override fun isCopyEnabled(dataContext: DataContext) = true
data class InstalledPackage(
override val uiPackageModel: UiPackageModel.Installed,
override val allScopes: List<PackageScope>
) : PackagesTableItem<PackageModel.Installed>() {
init {
require(allScopes.isNotEmpty()) { "An installed package must have at least one installed scope" }
}
override fun additionalCopyText() = buildString {
if (packageModel.usageInfo.isEmpty()) return@buildString
appendLine()
append("${PackageSearchBundle.message("packagesearch.package.copyableInfo.installedVersions")} ")
append(
packageModel.usageInfo.map { it.declaredVersion }
.distinct()
.joinToString(", ")
.removeSuffix(", ")
)
}
}
data class InstallablePackage(
override val uiPackageModel: UiPackageModel.SearchResult,
override val allScopes: List<PackageScope>
) : PackagesTableItem<PackageModel.SearchResult>() {
init {
require(allScopes.isNotEmpty()) { "An installable package must have at least one available scope" }
}
override fun additionalCopyText() = ""
}
}
| apache-2.0 | 1e7715a6e68d4e4936b8ff6ee00e82a7 | 39.638298 | 116 | 0.644503 | 5.421003 | false | false | false | false |
yongce/AndroidLib | baseLib/src/main/java/me/ycdev/android/lib/common/internalapi/android/os/PowerManagerIA.kt | 1 | 11204 | package me.ycdev.android.lib.common.internalapi.android.os
import android.annotation.SuppressLint
import android.content.Context
import android.os.IBinder
import androidx.annotation.RestrictTo
import timber.log.Timber
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
@Suppress("unused")
@SuppressLint("PrivateApi")
object PowerManagerIA {
private const val TAG = "PowerManagerIA"
private const val API_VERSION_1 = 1
private const val API_VERSION_2 = 2
/**
* Go to sleep reason code: Going to sleep due by user request.
*/
private const val GO_TO_SLEEP_REASON_USER = 0
private var sMtd_asInterface: Method? = null
private var sClass_IPowerManager: Class<*>? = null
private var sMtd_reboot: Method? = null
private var sVersion_reboot: Int = 0
private var sMtd_shutdown: Method? = null
private var sVersion_shutdown: Int = 0
private var sMtd_crash: Method? = null
private var sMtd_goToSleep: Method? = null
private var sVersion_goToSleep: Int = 0
/**
* Get "android.os.IPowerManager" object from the service manager.
* @return null will be returned if failed
*/
val iPowerManager: Any?
get() {
val binder = ServiceManagerIA.getService(Context.POWER_SERVICE)
return if (binder != null) {
asInterface(binder)
} else null
}
init {
try {
val stubClass = Class.forName(
"android.os.IPowerManager\$Stub", false,
Thread.currentThread().contextClassLoader
)
sMtd_asInterface = stubClass.getMethod("asInterface", IBinder::class.java)
sClass_IPowerManager = Class.forName(
"android.os.IPowerManager", false,
Thread.currentThread().contextClassLoader
)
} catch (e: ClassNotFoundException) {
Timber.tag(TAG).w(e, "class not found")
} catch (e: NoSuchMethodException) {
Timber.tag(TAG).w(e, "method not found")
}
}
/**
* Get "android.os.IPowerManager" object from the service binder.
* @return null will be returned if failed
*/
fun asInterface(binder: IBinder): Any? {
if (sMtd_asInterface != null) {
try {
return sMtd_asInterface!!.invoke(null, binder)
} catch (e: IllegalAccessException) {
Timber.tag(TAG).w(e, "Failed to invoke #asInterface()")
} catch (e: InvocationTargetException) {
Timber.tag(TAG).w(e, "Failed to invoke #asInterface() more")
}
} else {
Timber.tag(TAG).w("#asInterface() not available")
}
return null
}
private fun reflectReboot() {
if (sMtd_reboot != null || sClass_IPowerManager == null) {
return
}
try {
try {
// Android 2.2 ~ Android 4.1: void reboot(String reason);
sMtd_reboot = sClass_IPowerManager!!.getMethod("reboot", String::class.java)
sVersion_reboot = API_VERSION_1
} catch (e: NoSuchMethodException) {
// Android 4.2: void reboot(boolean confirm, String reason, boolean wait);
sMtd_reboot = sClass_IPowerManager!!.getMethod(
"reboot",
Boolean::class.javaPrimitiveType,
String::class.java,
Boolean::class.javaPrimitiveType
)
sVersion_reboot = API_VERSION_2
}
} catch (e: NoSuchMethodException) {
Timber.tag(TAG).w(e, "method not found")
}
}
/**
* Reboot the device.
* @param service The "android.os.IPowerManager" object.
* @param reason Just for logging
* @see .asInterface
*/
fun reboot(service: Any, reason: String) {
reflectReboot()
if (sMtd_reboot != null) {
try {
when (sVersion_reboot) {
API_VERSION_1 -> sMtd_reboot!!.invoke(service, reason)
API_VERSION_2 -> sMtd_reboot!!.invoke(service, false, reason, false)
else -> Timber.tag(TAG).e("reboot, unknown api version: $sVersion_reboot")
}
} catch (e: IllegalAccessException) {
Timber.tag(TAG).w(e, "Failed to invoke #reboot()")
} catch (e: InvocationTargetException) {
Timber.tag(TAG).w(e, "Failed to invoke #reboot() more")
}
} else {
Timber.tag(TAG).w("#reboot() not available")
}
}
/**
* Just for unit test.
*/
@RestrictTo(RestrictTo.Scope.TESTS)
internal fun checkReflectReboot(): Boolean {
reflectReboot()
return sMtd_reboot != null
}
private fun reflectShutdown() {
if (sMtd_shutdown != null || sClass_IPowerManager == null) return
try {
try {
// Android 4.2: void shutdown(boolean confirm, boolean wait);
sMtd_shutdown = sClass_IPowerManager!!.getMethod(
"shutdown",
Boolean::class.javaPrimitiveType, Boolean::class.javaPrimitiveType
)
sVersion_shutdown = API_VERSION_1
} catch (e: NoSuchMethodException) {
// Android 7.0: void shutdown(boolean confirm, String reason, boolean wait);
sMtd_shutdown = sClass_IPowerManager!!.getMethod(
"shutdown",
Boolean::class.javaPrimitiveType,
String::class.java,
Boolean::class.javaPrimitiveType
)
sVersion_shutdown = API_VERSION_2
}
} catch (e: NoSuchMethodException) {
Timber.tag(TAG).w(e, "method not found")
}
}
fun shutdown(service: Any, reason: String) {
reflectShutdown()
if (sMtd_shutdown != null) {
try {
when (sVersion_shutdown) {
API_VERSION_1 -> sMtd_shutdown!!.invoke(service, false, false)
API_VERSION_2 -> sMtd_shutdown!!.invoke(service, false, reason, false)
else -> Timber.tag(TAG).e("shutdown, unknown api version: $sVersion_shutdown")
}
} catch (e: IllegalAccessException) {
Timber.tag(TAG).w(e, "Failed to invoke #shutdown()")
} catch (e: InvocationTargetException) {
Timber.tag(TAG).w(e, "Failed to invoke #shutdown() more")
}
} else {
Timber.tag(TAG).w("#shutdown() not available")
}
}
/**
* Just for unit test.
*/
@RestrictTo(RestrictTo.Scope.TESTS)
internal fun checkReflectShutdown(): Boolean {
reflectShutdown()
return sMtd_shutdown != null
}
private fun reflectCrash() {
if (sMtd_crash != null || sClass_IPowerManager == null) {
return
}
try {
// Android 2.2 and next versions: void crash(String message);
sMtd_crash = sClass_IPowerManager!!.getMethod("crash", String::class.java)
} catch (e: NoSuchMethodException) {
Timber.tag(TAG).w(e, "method not found")
}
}
fun crash(service: Any, msg: String) {
reflectCrash()
if (sMtd_crash != null) {
try {
sMtd_crash!!.invoke(service, msg)
} catch (e: IllegalAccessException) {
Timber.tag(TAG).w(e, "Failed to invoke #crash()")
} catch (e: InvocationTargetException) {
Timber.tag(TAG).w(e, "Failed to invoke #crash() more")
}
} else {
Timber.tag(TAG).w("#crash() not available")
}
}
/**
* Just for unit test.
*/
@RestrictTo(RestrictTo.Scope.TESTS)
internal fun checkReflectCrash(): Boolean {
reflectCrash()
return sMtd_crash != null
}
private fun reflectGoToSleep() {
if (sMtd_goToSleep != null || sClass_IPowerManager == null) {
return
}
try {
try {
// Android 2.2 ~ Android 4.1: void goToSleepWithReason(long time, int reason);
sMtd_goToSleep = sClass_IPowerManager!!.getMethod(
"goToSleepWithReason",
Long::class.javaPrimitiveType,
Int::class.javaPrimitiveType
)
sVersion_goToSleep = API_VERSION_1
} catch (e: NoSuchMethodException) {
try {
// Android 4.2: void goToSleep(long time, int reason);
sMtd_goToSleep = sClass_IPowerManager!!.getMethod(
"goToSleep",
Long::class.javaPrimitiveType,
Int::class.javaPrimitiveType
)
sVersion_goToSleep = API_VERSION_1
} catch (e1: NoSuchMethodException) {
// Android 5.0: void goToSleep(long time, int reason, int flags);
sMtd_goToSleep = sClass_IPowerManager!!.getMethod(
"goToSleep",
Long::class.javaPrimitiveType,
Int::class.javaPrimitiveType,
Int::class.javaPrimitiveType
)
sVersion_goToSleep = API_VERSION_2
}
}
} catch (e: NoSuchMethodException) {
Timber.tag(TAG).w(e, "method not found")
}
}
/**
* Forces the device to go to sleep. Please refer android.os.PowerManager#goToSleep(long).
* @param service The IPowerManager object
* @param time The time when the request to go to sleep was issued,
* in the [android.os.SystemClock.uptimeMillis] time base.
* This timestamp is used to correctly order the go to sleep request with
* other power management functions. It should be set to the timestamp
* of the input event that caused the request to go to sleep.
*/
fun goToSleep(service: Any, time: Long) {
reflectGoToSleep()
if (sMtd_goToSleep != null) {
try {
if (sVersion_goToSleep == API_VERSION_1) {
sMtd_goToSleep!!.invoke(service, time, GO_TO_SLEEP_REASON_USER)
} else if (sVersion_goToSleep == API_VERSION_2) {
sMtd_goToSleep!!.invoke(service, time, GO_TO_SLEEP_REASON_USER, 0)
}
} catch (e: IllegalAccessException) {
Timber.tag(TAG).w(e, "Failed to invoke #crash()")
} catch (e: InvocationTargetException) {
Timber.tag(TAG).w(e, "Failed to invoke #crash() more")
}
} else {
Timber.tag(TAG).w("#crash() not available")
}
}
/**
* Just for unit test.
*/
@RestrictTo(RestrictTo.Scope.TESTS)
internal fun checkReflectGoToSleep(): Boolean {
reflectGoToSleep()
return sMtd_goToSleep != null
}
}
| apache-2.0 | 4b171a95eed865ed2299c6c1d3031dea | 35.141935 | 98 | 0.54311 | 4.444268 | false | false | false | false |
Qase/KotlinLogger | kotlinlog/src/main/kotlin/quanti/com/kotlinlog/utils/FileUtils.kt | 1 | 3999 | package quanti.com.kotlinlog.utils
import android.content.Context
import android.media.MediaScannerConnection
import android.os.Environment
import androidx.core.content.FileProvider
import quanti.com.kotlinlog.Log.Companion.i
import quanti.com.kotlinlog.file.file.MetadataFile
import quanti.com.kotlinlog.forceWrite
import java.io.File
import java.io.FileNotFoundException
import java.util.concurrent.TimeUnit
/**
* File extensions written in kotlin
*
* @author Vladislav Trnka
*/
/**
* Scan file system to make file available
* according to this {@see http://developer.android.com/reference/android/os/Environment.html#getExternalStoragePublicDirectory(java.lang.String)}
* @param ctx app context
*/
fun File.scanFile(ctx: Context) {
scanFiles(ctx, this.toString())
}
/**
* Scan file system to make file available
* according to this {@see http://developer.android.com/reference/android/os/Environment.html#getExternalStoragePublicDirectory(java.lang.String)}
* @param ctx app context
* @param args File.tostrings(0)
*/
private fun scanFiles(ctx: Context, vararg args: String) {
MediaScannerConnection.scanFile(ctx, args, null) { path, _ -> i("Scanned $path:") }
}
/**
* Returns how old is this file
* -1 --> created tomorrow
* 0 --> created today
* 1 --> created yesterday
* and so on
*/
fun File.fileAge(): Int {
if (!exists()) {
//file does not exists
throw FileNotFoundException("File does not exists $absolutePath")
}
//i do not want the basic difference
//i want
val todayMillis = ActualTime.currentDate().time
val fileMillis = lastModified()
val todayDay = TimeUnit.DAYS.convert(todayMillis, TimeUnit.MILLISECONDS)
val fileDay = TimeUnit.DAYS.convert(fileMillis, TimeUnit.MILLISECONDS)
val ret = (todayDay - fileDay).toInt()
loga(name, ret)
return ret
}
/**
* Add children path to current filepath
*/
fun File.addPath(vararg childrenPath :String): File {
var file = this
childrenPath.forEach {
file = File(file, it)
}
return file
}
/**
* Get shareable uri fo current file
*/
fun File.getUriForFile(appCtx: Context) = FileProvider.getUriForFile(appCtx, appCtx.packageName, this)
/**
* Copy zip of logs to sd card
*/
fun File.copyLogsTOSDCard(context: Context, sdCardFolderName: String = "KotlinLogger"): File {
val outputFile = context.getExternalFilesDir(null)
?.addPath(sdCardFolderName, name) ?: throw Exception("External files directory was not found")
copyTo(outputFile, overwrite = true)
return outputFile
}
/**
* Create zip of all logs in current app directory
*
* @param appCtx application context
* @param fileAge how many days backward you want to go - default 4
* @param extraFiles extra files can be added to the zip file (for example screenshots from app)
*/
fun getZipOfLogs(appCtx: Context, fileAge: Int = 4, extraFiles: List<File> = arrayListOf()): File {
val listOfFiles = getLogFiles(appCtx, fileAge).toMutableList()
listOfFiles.addAll(extraFiles)
val zipFileName = "Logs_${getFormattedFileNameForDayTemp()}_${appCtx.getApplicationName()}.zip"
val zipFile = File(appCtx.logFilesDir, zipFileName)
zipFile.createNewFile() //create file if not exists
listOfFiles.zip(zipFile)
return zipFile
}
fun getLogFiles(appCtx: Context, fileAge: Int = 4): List<File> {
//first perform clean of mess
appCtx.logFilesDir.listFiles()?.deleteAllZips()
appCtx.logFilesDir.listFiles()?.deleteAllOldFiles(fileAge)
if (appCtx.logFilesDir.listFiles().isNullOrEmpty()) {
throw FileNotFoundException("No files were found")
}
//create metadata info file
MetadataFile(appCtx).apply {
write()
closeOutputStream()
}
loga("Force write")
forceWrite()
return appCtx.logFilesDir
.listFiles()
?.filter { it.isFile } //take only files
?.filter { it.name.contains(".log", ignoreCase = true) }
?: listOf()
}
| mit | 84ff53ead30dffef00ffa384f9a29597 | 27.978261 | 146 | 0.706927 | 4.076453 | false | false | false | false |
daviddenton/k2 | src/main/kotlin/io/github/daviddenton/k2/formats/ResponseBuilder.kt | 1 | 1343 | package io.github.daviddenton.k2.formats
import io.github.daviddenton.k2.contract.ContentType
import io.github.daviddenton.k2.http.Response
data class ResponseBuilder<T>(val toFormat: (T) -> String,
val errorFormat: (String) -> T,
val exceptionFormat: (Throwable) -> T,
val contentType: ContentType,
val response: Response) {
fun withError(e: Throwable): ResponseBuilder<T> = withContent(exceptionFormat(e))
fun withErrorMessage(e: String): ResponseBuilder<T> = withContent(errorFormat(e))
fun withContent(content: T): ResponseBuilder<T> = withContent(toFormat(content))
fun withContent(body: String): ResponseBuilder<T> = copy(response = response.copy(body = body))
fun withCode(status: Int): ResponseBuilder<T> = copy(response = response.copy(status = status))
fun withHeaders(vararg headers: Pair<String, String>): ResponseBuilder<T> =
copy(response = headers.fold(response, { (_, _, headerMap), r ->
response.copy(
headerMap = headerMap.plus(r.first to headerMap.getOrDefault(r.first, emptySet()).plus(r.second)))
}))
fun build(): Response = response.copy(headerMap = response.headerMap.plus("Content Type" to setOf(contentType.value)))
} | apache-2.0 | 6ce4c8e5e89f228009dda5eee5de1710 | 45.344828 | 122 | 0.650782 | 4.196875 | false | false | false | false |
McMoonLakeDev/MoonLake | API/src/main/kotlin/com/mcmoonlake/api/attribute/AttributeItemModifier.kt | 1 | 4392 | /*
* 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/>.
*/
package com.mcmoonlake.api.attribute
import com.mcmoonlake.api.item.ItemBuilder
import com.mcmoonlake.api.ofValuable
import com.mcmoonlake.api.ofValuableNotNull
import com.mcmoonlake.api.parseDouble
import com.mcmoonlake.api.parseInt
import com.mcmoonlake.api.util.ComparisonChain
import org.bukkit.configuration.serialization.ConfigurationSerializable
import java.util.*
/**
* ## AttributeItemModifier (属性物品修改器)
*
* * Add or remove modifiers to the specified item stack.
* * 从物品栈中添加或移除此修改器.
*
* @see [ItemBuilder]
* @see [ItemBuilder.getAttribute]
* @see [ConfigurationSerializable]
* @author lgou2w
* @since 2.0
* @constructor AttributeItemModifier
* @param type Attribute type.
* @param type 属性类型.
* @param operation Operation mode.
* @param operation 运算模式.
* @param slot This modifier takes effect in which slot of the player. If `null` then all slots.
* @param slot 此修改器在玩家哪个槽位生效. 如果 `null` 则所有槽位.
* @param amount Operation amount.
* @param amount 运算数量.
* @param uuid Unique id.
* @param uuid 唯一 Id.
*/
data class AttributeItemModifier(
/**
* * The type of this modifier.
* * 此修改器的类型.
*/
val type: AttributeType,
/**
* * The name of this modifier.
* * 此修改器的名称.
*/
val name: String = type.name,
/**
* * The operation mode of this modifier.
* * 此修改器的运算模式.
*/
val operation: Operation,
/**
* * The modifier is takes effect in which slot. If `null` then all slots.
* * 此修改器的生效槽位. 如果 `null` 则所有槽位.
*/
val slot: Slot?,
/**
* * The operation amount of this modifier.
* * 此修改器的运算数量.
*/
val amount: Double,
/**
* * The unique id of this modifier.
* * 此修改器的唯一 Id.
*/
val uuid: UUID
) : ConfigurationSerializable,
Comparable<AttributeItemModifier> {
override fun compareTo(other: AttributeItemModifier): Int {
return ComparisonChain.start()
.compare(type, other.type)
.compare(name, other.name)
.compare(operation, other.operation)
.compare(slot?.ordinal ?: -1, other.slot?.ordinal ?: -1)
.compare(amount, other.amount)
.compare(uuid, other.uuid)
.result
}
override fun serialize(): MutableMap<String, Any> {
val result = LinkedHashMap<String, Any>()
result["type"] = type.value()
result["name"] = name
result["operation"] = operation.value()
if(slot != null) result["slot"] = slot.value()
result["amount"] = amount
result["uuid"] = uuid.toString()
return result
}
/** static */
companion object {
@JvmStatic
@JvmName("deserialize")
fun deserialize(args: Map<String, Any>): AttributeItemModifier {
val type: AttributeType = ofValuableNotNull(args["type"]?.toString())
val operation: Operation = ofValuableNotNull(args["operation"]?.parseInt())
val slot: Slot? = ofValuable(args["slot"]?.toString())
val amount = args["amount"]?.parseDouble() ?: .0
val uuid = UUID.fromString(args["uuid"]?.toString())
val name = args["name"]?.toString() ?: type.name
return AttributeItemModifier(type, name, operation, slot, amount, uuid)
}
}
}
| gpl-3.0 | cc94e3920d19c71de8f6e7e3b4a1724d | 32.376 | 96 | 0.622963 | 4.023144 | false | false | false | false |
songful/PocketHub | app/src/main/java/com/github/pockethub/android/ui/issue/EditIssueActivity.kt | 1 | 17432 | /*
* Copyright (c) 2015 PocketHub
*
* 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.github.pockethub.android.ui.issue
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Parcelable
import android.support.design.widget.FloatingActionButton
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout.LayoutParams
import android.widget.TextView
import androidx.text.bold
import androidx.text.buildSpannedString
import butterknife.BindView
import butterknife.OnClick
import butterknife.OnTextChanged
import com.github.pockethub.android.Intents.*
import com.github.pockethub.android.R
import com.github.pockethub.android.RequestCodes.*
import com.github.pockethub.android.accounts.AccountUtils
import com.github.pockethub.android.core.issue.IssueUtils
import com.github.pockethub.android.rx.AutoDisposeUtils
import com.github.pockethub.android.rx.RxProgress
import com.github.pockethub.android.ui.BaseActivity
import com.github.pockethub.android.util.*
import com.meisolsson.githubsdk.core.ServiceGenerator
import com.meisolsson.githubsdk.model.Issue
import com.meisolsson.githubsdk.model.Repository
import com.meisolsson.githubsdk.model.User
import com.meisolsson.githubsdk.model.request.issue.IssueRequest
import com.meisolsson.githubsdk.service.issues.IssueService
import com.meisolsson.githubsdk.service.repositories.RepositoryCollaboratorService
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import retrofit2.Response
import java.util.*
import javax.inject.Inject
/**
* Activity to edit or create an issue
*/
class EditIssueActivity : BaseActivity() {
@BindView(R.id.et_issue_title)
lateinit var titleText: EditText
@BindView(R.id.et_issue_body)
lateinit var bodyText: EditText
@BindView(R.id.ll_milestone_graph)
lateinit var milestoneGraph: View
@BindView(R.id.tv_milestone)
lateinit var milestoneText: TextView
@BindView(R.id.v_closed)
lateinit var milestoneClosed: View
@BindView(R.id.iv_assignee_avatar)
lateinit var assigneeAvatar: ImageView
@BindView(R.id.tv_assignee_name)
lateinit var assigneeText: TextView
@BindView(R.id.tv_labels)
lateinit var labelsText: TextView
@BindView(R.id.fab_add_image)
lateinit var addImageFab: FloatingActionButton
@Inject
lateinit var avatars: AvatarLoader
private var issue: Issue? = null
private var repository: Repository? = null
private var saveItem: MenuItem? = null
private var milestoneDialog: MilestoneDialog? = null
private var assigneeDialog: AssigneeDialog? = null
private var labelsDialog: LabelsDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_issue_edit)
val intent = intent
if (savedInstanceState != null) {
issue = savedInstanceState.getParcelable(EXTRA_ISSUE)
}
if (issue == null) {
issue = intent.getParcelableExtra(EXTRA_ISSUE)
}
if (issue == null) {
issue = Issue.builder().build()
}
repository = InfoUtils.createRepoFromData(
intent.getStringExtra(EXTRA_REPOSITORY_OWNER),
intent.getStringExtra(EXTRA_REPOSITORY_NAME)
)
checkCollaboratorStatus()
val actionBar = supportActionBar
if (issue!!.number() != null && issue!!.number()!! > 0) {
if (IssueUtils.isPullRequest(issue)) {
actionBar!!.title = getString(R.string.pull_request_title) + issue!!.number()!!
} else {
actionBar!!.title = getString(R.string.issue_title) + issue!!.number()!!
}
} else {
actionBar!!.setTitle(R.string.new_issue)
}
actionBar.subtitle = InfoUtils.createRepoId(repository)
avatars.bind(actionBar, intent.getParcelableExtra<Parcelable>(EXTRA_USER) as User)
updateSaveMenu()
titleText.setText(issue!!.title())
bodyText.setText(issue!!.body())
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == READ_PERMISSION_REQUEST) {
var result = true
for (i in permissions.indices) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
result = false
}
}
if (result) {
startImagePicker()
}
}
}
private fun startImagePicker() {
val photoPickerIntent = Intent(Intent.ACTION_GET_CONTENT)
photoPickerIntent.type = "image/*"
startActivityForResult(photoPickerIntent, REQUEST_CODE_SELECT_PHOTO)
}
override fun onDialogResult(requestCode: Int, resultCode: Int, arguments: Bundle) {
if (Activity.RESULT_OK != resultCode) {
return
}
when (requestCode) {
ISSUE_MILESTONE_UPDATE -> {
issue = issue!!.toBuilder()
.milestone(MilestoneDialogFragment.getSelected(arguments))
.build()
updateMilestone()
}
ISSUE_ASSIGNEE_UPDATE -> {
var assignee: User? = AssigneeDialogFragment.getSelected(arguments)
if (assignee == null) {
assignee = User.builder().login("").build()
}
issue = issue!!.toBuilder().assignee(assignee).build()
updateAssignee()
}
ISSUE_LABELS_UPDATE -> {
issue = issue!!.toBuilder()
.labels(LabelsDialogFragment.getSelected(arguments))
.build()
updateLabels()
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_SELECT_PHOTO && resultCode == Activity.RESULT_OK) {
ImageBinPoster.post(this, data.data!!)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.compose(RxProgress.bindToLifecycle(this, R.string.loading))
.`as`(AutoDisposeUtils.bindToLifecycle(this))
.subscribe({ response ->
if (response.isSuccessful) {
insertImage(ImageBinPoster.getUrl(response.body()!!.string()))
} else {
showImageError()
}
}, { _ -> showImageError() })
}
}
@OnTextChanged(R.id.et_issue_title)
fun onIssueTitleChange(text: CharSequence) {
updateSaveMenu(text)
}
@OnClick(R.id.fab_add_image)
fun onAddImageClicked() {
val activity = this@EditIssueActivity
val permission = Manifest.permission.READ_EXTERNAL_STORAGE
if (ContextCompat.checkSelfPermission(activity, permission) !=
PackageManager.PERMISSION_GRANTED
) {
PermissionsUtils.askForPermission(
activity,
READ_PERMISSION_REQUEST,
permission,
R.string.read_permission_title,
R.string.read_permission_content
)
} else {
startImagePicker()
}
}
private fun showImageError() {
ToastUtils.show(this, R.string.error_image_upload)
}
private fun insertImage(url: String?) {
runOnUiThread { bodyText.append("") }
}
private fun showMainContent() {
findViewById<View>(R.id.sv_issue_content).visibility = View.VISIBLE
findViewById<View>(R.id.pb_loading).visibility = View.GONE
}
private fun showCollaboratorOptions() {
val milestone = findViewById<View>(R.id.ll_milestone)
val labels = findViewById<View>(R.id.ll_labels)
val assignee = findViewById<View>(R.id.ll_assignee)
findViewById<View>(R.id.tv_milestone_label).visibility = View.VISIBLE
milestone.visibility = View.VISIBLE
findViewById<View>(R.id.tv_labels_label).visibility = View.VISIBLE
labels.visibility = View.VISIBLE
findViewById<View>(R.id.tv_assignee_label).visibility = View.VISIBLE
assignee.visibility = View.VISIBLE
milestone.setOnClickListener { _ ->
if (milestoneDialog == null) {
milestoneDialog = MilestoneDialog(this, ISSUE_MILESTONE_UPDATE, repository)
}
milestoneDialog!!.show(issue!!.milestone())
}
assignee.setOnClickListener { _ ->
if (assigneeDialog == null) {
assigneeDialog = AssigneeDialog(this, ISSUE_ASSIGNEE_UPDATE, repository)
}
assigneeDialog!!.show(issue!!.assignee())
}
labels.setOnClickListener { _ ->
if (labelsDialog == null) {
labelsDialog = LabelsDialog(this, ISSUE_LABELS_UPDATE, repository)
}
labelsDialog!!.show(issue!!.labels())
}
updateAssignee()
updateLabels()
updateMilestone()
}
private fun updateMilestone() {
val milestone = issue!!.milestone()
if (milestone != null) {
milestoneText.text = milestone.title()
val closed = milestone.closedIssues()!!.toFloat()
val total = closed + milestone.openIssues()!!
if (total > 0) {
(milestoneClosed.layoutParams as LayoutParams).weight = closed / total
milestoneClosed.visibility = VISIBLE
} else {
milestoneClosed.visibility = GONE
}
milestoneGraph.visibility = VISIBLE
} else {
milestoneText.setText(R.string.none)
milestoneGraph.visibility = GONE
}
}
private fun updateAssignee() {
val assignee = issue!!.assignee()
val login = assignee?.login()
if (!TextUtils.isEmpty(login)) {
assigneeText.text = buildSpannedString {
bold {
append(login)
}
}
assigneeAvatar.visibility = VISIBLE
avatars.bind(assigneeAvatar, assignee)
} else {
assigneeAvatar.visibility = GONE
assigneeText.setText(R.string.unassigned)
}
}
private fun updateLabels() {
val labels = issue!!.labels()
if (labels != null && !labels.isEmpty()) {
LabelDrawableSpan.setText(labelsText, labels)
} else {
labelsText.setText(R.string.none)
}
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
outState!!.putParcelable(EXTRA_ISSUE, issue)
}
private fun updateSaveMenu(text: CharSequence = titleText.text) {
if (saveItem != null) {
saveItem!!.isEnabled = !TextUtils.isEmpty(text)
}
}
override fun onCreateOptionsMenu(options: Menu): Boolean {
menuInflater.inflate(R.menu.activity_issue_edit, options)
saveItem = options.findItem(R.id.m_apply)
updateSaveMenu()
return super.onCreateOptionsMenu(options)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.m_apply -> {
val request = IssueRequest.builder()
.body(bodyText.text.toString())
.title(titleText.text.toString())
.state(issue!!.state())
if (issue!!.assignee() != null) {
request.assignees(listOf(issue!!.assignee()!!.login()!!))
} else {
request.assignees(emptyList())
}
if (issue!!.milestone() != null) {
request.milestone(issue!!.milestone()!!.number()!!.toLong())
}
val labels = ArrayList<String>()
if (issue!!.labels() != null) {
for (label in issue!!.labels()!!) {
labels.add(label.name()!!)
}
}
request.labels(labels)
val service = ServiceGenerator.createService(this, IssueService::class.java)
val single: Single<Response<Issue>>
val message: Int
if (issue!!.number() != null && issue!!.number()!! > 0) {
single = service.editIssue(
repository!!.owner()!!.login(),
repository!!.name(),
issue!!.number()!!.toLong(),
request.build()
)
message = R.string.updating_issue
} else {
single = service.createIssue(
repository!!.owner()!!.login(),
repository!!.name(),
request.build()
)
message = R.string.creating_issue
}
single.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.compose(RxProgress.bindToLifecycle(this, message))
.`as`(AutoDisposeUtils.bindToLifecycle(this))
.subscribe({ response ->
val intent = Intent()
intent.putExtra(EXTRA_ISSUE, response.body())
setResult(Activity.RESULT_OK, intent)
finish()
}, { e ->
Log.e(TAG, "Exception creating issue", e)
ToastUtils.show(this, e.message)
})
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
private fun checkCollaboratorStatus() {
ServiceGenerator.createService(this, RepositoryCollaboratorService::class.java)
.isUserCollaborator(
repository!!.owner()!!.login(),
repository!!.name(),
AccountUtils.getLogin(this)
)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.`as`(AutoDisposeUtils.bindToLifecycle(this))
.subscribe({ response ->
showMainContent()
if (response.code() == 204) {
showCollaboratorOptions()
}
})
}
companion object {
private const val TAG = "EditIssueActivity"
private const val REQUEST_CODE_SELECT_PHOTO = 0
private const val READ_PERMISSION_REQUEST = 1
/**
* Create intent to create an issue
*
* @param repository
* @return intent
*/
fun createIntent(repository: Repository?): Intent {
return createIntent(
null,
repository!!.owner()!!.login(),
repository.name(),
repository.owner()
)
}
/**
* Create intent to edit an issue
*
* @param issue
* @param repositoryOwner
* @param repositoryName
* @param user
* @return intent
*/
fun createIntent(
issue: Issue?,
repositoryOwner: String?,
repositoryName: String?,
user: User?
): Intent {
val builder = Builder("repo.issues.edit.VIEW")
if (user != null) {
builder.add(EXTRA_USER, user)
}
builder.add(EXTRA_REPOSITORY_NAME, repositoryName)
builder.add(EXTRA_REPOSITORY_OWNER, repositoryOwner)
if (issue != null) {
builder.issue(issue)
}
return builder.toIntent()
}
}
}
| apache-2.0 | bebd0c78631ded21bad85982c2338088 | 33.794411 | 95 | 0.573887 | 5.064497 | false | false | false | false |
fwcd/kotlin-language-server | server/src/main/kotlin/org/javacs/kt/util/RangeUtils.kt | 1 | 409 | package org.javacs.kt.util
import org.eclipse.lsp4j.Range
// checks if the current range is within the other range (same lines, within the character bounds)
fun Range.isSubrangeOf(otherRange: Range): Boolean =
otherRange.start.line == this.start.line && otherRange.end.line == this.end.line &&
otherRange.start.character <= this.start.character && otherRange.end.character >= this.end.character
| mit | 7854da36637d3bbdf02e84ae2cf88019 | 50.125 | 108 | 0.750611 | 3.684685 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/changeReminder/src/com/jetbrains/changeReminder/predict/PredictionController.kt | 12 | 2447 | // 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.changeReminder.predict
import com.intellij.openapi.Disposable
import com.intellij.openapi.progress.*
import com.intellij.openapi.progress.impl.CoreProgressManager
import com.intellij.openapi.project.Project
import com.intellij.util.Consumer
import com.intellij.vcs.log.data.SingleTaskController
import com.jetbrains.changeReminder.ChangeReminderBundle
internal abstract class PredictionController(private val project: Project,
name: String,
parent: Disposable,
handler: (PredictionData) -> Unit
) : SingleTaskController<PredictionRequest, PredictionData>(name, Consumer { handler(it) }, parent) {
var inProgress = false
private set(value) {
field = value
inProgressChanged(value)
}
override fun cancelRunningTasks(requests: List<PredictionRequest>) = true
override fun startNewBackgroundTask(): SingleTask {
val task: Task.Backgroundable = object : Task.Backgroundable(
project,
ChangeReminderBundle.message("prediction.controller.task.background.title")
) {
override fun run(indicator: ProgressIndicator) {
inProgress = true
var predictionData: PredictionData? = null
val request = popRequest() ?: return
try {
predictionData = request.calculate()
}
catch (e: ProcessCanceledException) {
predictionData = PredictionData.EmptyPrediction(PredictionData.EmptyPredictionReason.CALCULATION_CANCELED)
throw e
}
catch (_: Exception) {
predictionData = PredictionData.EmptyPrediction(PredictionData.EmptyPredictionReason.EXCEPTION_THROWN)
}
finally {
complete(predictionData ?: PredictionData.EmptyPrediction(PredictionData.EmptyPredictionReason.UNEXPECTED_REASON))
}
}
}
val indicator = EmptyProgressIndicator()
val future = (ProgressManager.getInstance() as CoreProgressManager).runProcessWithProgressAsynchronously(task, indicator, null)
return SingleTaskImpl(future, indicator)
}
abstract fun inProgressChanged(value: Boolean)
private fun complete(result: PredictionData) {
inProgress = false
taskCompleted(result)
}
} | apache-2.0 | fd31b0eda4eeb1a7beaed8492e0b2fcf | 39.8 | 140 | 0.697998 | 5.024641 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/core/overrideImplement/KtImplementMembersHandler.kt | 2 | 8427 | // 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 com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
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.overrideImplement.KtImplementMembersHandler.Companion.getUnimplementedMembers
import org.jetbrains.kotlin.idea.core.util.KotlinIdeaCoreBundle
import org.jetbrains.kotlin.idea.fir.api.fixes.diagnosticFixFactoryFromIntentionActions
import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt
import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtEnumEntry
import org.jetbrains.kotlin.util.ImplementationStatus
internal open class KtImplementMembersHandler : KtGenerateMembersHandler(true) {
override fun getChooserTitle() = KotlinIdeaCoreBundle.message("implement.members.handler.title")
override fun getNoMembersFoundHint() = KotlinIdeaCoreBundle.message("implement.members.handler.no.members.hint")
@OptIn(KtAllowAnalysisOnEdt::class)
override fun collectMembersToGenerate(classOrObject: KtClassOrObject): Collection<KtClassMember> {
return allowAnalysisOnEdt {
analyze(classOrObject) {
getUnimplementedMembers(classOrObject).map { createKtClassMember(it, BodyType.FROM_TEMPLATE, false) }
}
}
}
companion object {
fun KtAnalysisSession.getUnimplementedMembers(classWithUnimplementedMembers: KtClassOrObject): List<KtClassMemberInfo> {
return getUnimplementedMemberSymbols(classWithUnimplementedMembers.getClassOrObjectSymbol()).map { unimplementedMemberSymbol ->
val containingSymbol = unimplementedMemberSymbol.originalContainingClassForOverride
KtClassMemberInfo(
symbol = unimplementedMemberSymbol,
memberText = unimplementedMemberSymbol.render(renderOption),
memberIcon = getIcon(unimplementedMemberSymbol),
containingSymbolText = containingSymbol?.classIdIfNonLocal?.asSingleFqName()?.toString()
?: containingSymbol?.name?.asString(),
containingSymbolIcon = containingSymbol?.let { symbol -> getIcon(symbol) }
)
}
}
@OptIn(ExperimentalStdlibApi::class)
private fun KtAnalysisSession.getUnimplementedMemberSymbols(classWithUnimplementedMembers: KtClassOrObjectSymbol): List<KtCallableSymbol> {
return buildList {
classWithUnimplementedMembers.getMemberScope().getCallableSymbols().forEach { symbol ->
if (!symbol.isVisibleInClass(classWithUnimplementedMembers)) return@forEach
when (symbol.getImplementationStatus(classWithUnimplementedMembers)) {
ImplementationStatus.NOT_IMPLEMENTED -> add(symbol)
ImplementationStatus.AMBIGUOUSLY_INHERITED,
ImplementationStatus.INHERITED_OR_SYNTHESIZED -> {
// This case is to show user abstract members that don't need to be implemented because another super class has provide
// an implementation. For example, given the following
//
// interface A { fun foo() }
// interface B { fun foo() {} }
// class Foo : A, B {}
//
// `Foo` does not need to implement `foo` since it inherits the implementation from `B`. But in the dialog, we should
// allow user to choose `foo` to implement.
symbol.getIntersectionOverriddenSymbols()
.filter { (it as? KtSymbolWithModality)?.modality == Modality.ABSTRACT }
.forEach { add(it) }
}
else -> {
}
}
}
}
}
}
}
internal class KtImplementMembersQuickfix(private val members: Collection<KtClassMemberInfo>) : KtImplementMembersHandler(),
IntentionAction {
override fun getText() = familyName
override fun getFamilyName() = KotlinIdeaCoreBundle.message("implement.members.handler.family")
override fun isAvailable(project: Project, editor: Editor, file: PsiFile) = true
override fun collectMembersToGenerate(classOrObject: KtClassOrObject): Collection<KtClassMember> {
return members.map { createKtClassMember(it, BodyType.FROM_TEMPLATE, false) }
}
}
internal class KtImplementAsConstructorParameterQuickfix(private val members: Collection<KtClassMemberInfo>) : KtImplementMembersHandler(),
IntentionAction {
override fun getText() = KotlinIdeaCoreBundle.message("action.text.implement.as.constructor.parameters")
override fun getFamilyName() = KotlinIdeaCoreBundle.message("implement.members.handler.family")
override fun isAvailable(project: Project, editor: Editor, file: PsiFile) = true
override fun collectMembersToGenerate(classOrObject: KtClassOrObject): Collection<KtClassMember> {
return members.filter { it.isProperty }.map { createKtClassMember(it, BodyType.FROM_TEMPLATE, true) }
}
}
object MemberNotImplementedQuickfixFactories {
val abstractMemberNotImplemented =
diagnosticFixFactoryFromIntentionActions(KtFirDiagnostic.AbstractMemberNotImplemented::class) { diagnostic ->
getUnimplementedMemberFixes(diagnostic.psi)
}
val abstractClassMemberNotImplemented =
diagnosticFixFactoryFromIntentionActions(KtFirDiagnostic.AbstractClassMemberNotImplemented::class) { diagnostic ->
getUnimplementedMemberFixes(diagnostic.psi)
}
val manyInterfacesMemberNotImplemented =
diagnosticFixFactoryFromIntentionActions(KtFirDiagnostic.ManyInterfacesMemberNotImplemented::class) { diagnostic ->
getUnimplementedMemberFixes(diagnostic.psi)
}
val manyImplMemberNotImplemented =
diagnosticFixFactoryFromIntentionActions(KtFirDiagnostic.ManyImplMemberNotImplemented::class) { diagnostic ->
getUnimplementedMemberFixes(diagnostic.psi, false)
}
@OptIn(ExperimentalStdlibApi::class)
private fun KtAnalysisSession.getUnimplementedMemberFixes(
classWithUnimplementedMembers: KtClassOrObject,
includeImplementAsConstructorParameterQuickfix: Boolean = true
): List<IntentionAction> {
val unimplementedMembers = getUnimplementedMembers(classWithUnimplementedMembers)
if (unimplementedMembers.isEmpty()) return emptyList()
return buildList {
add(KtImplementMembersQuickfix(unimplementedMembers))
if (includeImplementAsConstructorParameterQuickfix && classWithUnimplementedMembers is KtClass && classWithUnimplementedMembers !is KtEnumEntry && !classWithUnimplementedMembers.isInterface()) {
// TODO: when MPP support is ready, return false if this class is `actual` and any expect classes have primary constructor.
val unimplementedProperties = unimplementedMembers.filter { it.isProperty }
if (unimplementedProperties.isNotEmpty()) {
add(KtImplementAsConstructorParameterQuickfix(unimplementedProperties))
}
}
}
}
}
| apache-2.0 | 0cc7a8c2be1d9704b82a4346875e5ef5 | 54.078431 | 206 | 0.689451 | 6.164594 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/handlers/KotlinFindMemberUsagesHandler.kt | 1 | 18822 | // 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.findUsages.handlers
import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector
import com.intellij.find.FindManager
import com.intellij.find.findUsages.AbstractFindUsagesDialog
import com.intellij.find.findUsages.FindUsagesOptions
import com.intellij.find.impl.FindManagerImpl
import com.intellij.icons.AllIcons.Actions
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.MethodReferencesSearch
import com.intellij.psi.search.searches.OverridingMethodsSearch
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.usageView.UsageInfo
import com.intellij.util.*
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.idea.base.util.excludeKotlinSources
import org.jetbrains.kotlin.idea.findUsages.*
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesSupport.Companion.getTopMostOverriddenElementsToHighlight
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesSupport.Companion.isDataClassComponentFunction
import org.jetbrains.kotlin.idea.findUsages.dialogs.KotlinFindFunctionUsagesDialog
import org.jetbrains.kotlin.idea.findUsages.dialogs.KotlinFindPropertyUsagesDialog
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.filterDataClassComponentsIfDisabled
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.isOverridable
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchOverriders
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReadWriteAccessDetector
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters
import org.jetbrains.kotlin.idea.search.isImportUsage
import org.jetbrains.kotlin.idea.search.isOnlyKotlinSearch
import org.jetbrains.kotlin.idea.search.isPotentiallyOperator
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parameterIndex
import javax.swing.event.HyperlinkEvent
import javax.swing.event.HyperlinkListener
abstract class KotlinFindMemberUsagesHandler<T : KtNamedDeclaration> protected constructor(
declaration: T,
elementsToSearch: Collection<PsiElement>,
factory: KotlinFindUsagesHandlerFactory
) : KotlinFindUsagesHandler<T>(declaration, elementsToSearch, factory) {
private class Function(
declaration: KtFunction,
elementsToSearch: Collection<PsiElement>,
factory: KotlinFindUsagesHandlerFactory
) : KotlinFindMemberUsagesHandler<KtFunction>(declaration, elementsToSearch, factory) {
override fun getFindUsagesOptions(dataContext: DataContext?): FindUsagesOptions = factory.findFunctionOptions
override fun getPrimaryElements(): Array<PsiElement> =
if (factory.findFunctionOptions.isSearchForBaseMethod) {
val supers = KotlinFindUsagesSupport.getSuperMethods(psiElement as KtFunction, null)
if (supers.contains(psiElement)) supers.toTypedArray() else (supers + psiElement).toTypedArray()
} else super.getPrimaryElements()
override fun getFindUsagesDialog(
isSingleFile: Boolean,
toShowInNewTab: Boolean,
mustOpenInNewTab: Boolean
): AbstractFindUsagesDialog {
val options = factory.findFunctionOptions
val lightMethod = getElement().toLightMethods().firstOrNull()
if (lightMethod != null) {
return KotlinFindFunctionUsagesDialog(lightMethod, project, options, toShowInNewTab, mustOpenInNewTab, isSingleFile, this)
}
return super.getFindUsagesDialog(isSingleFile, toShowInNewTab, mustOpenInNewTab)
}
override fun createKotlinReferencesSearchOptions(options: FindUsagesOptions, forHighlight: Boolean): KotlinReferencesSearchOptions {
val kotlinOptions = options as KotlinFunctionFindUsagesOptions
return KotlinReferencesSearchOptions(
acceptCallableOverrides = true,
acceptOverloads = kotlinOptions.isIncludeOverloadUsages,
acceptExtensionsOfDeclarationClass = kotlinOptions.isIncludeOverloadUsages,
searchForExpectedUsages = kotlinOptions.searchExpected,
searchForComponentConventions = !forHighlight
)
}
override fun applyQueryFilters(element: PsiElement, options: FindUsagesOptions, query: Query<PsiReference>): Query<PsiReference> {
val kotlinOptions = options as KotlinFunctionFindUsagesOptions
return query
.applyFilter(kotlinOptions.isSkipImportStatements) { !it.isImportUsage() }
}
}
private class Property(
propertyDeclaration: KtNamedDeclaration,
elementsToSearch: Collection<PsiElement>,
factory: KotlinFindUsagesHandlerFactory
) : KotlinFindMemberUsagesHandler<KtNamedDeclaration>(propertyDeclaration, elementsToSearch, factory) {
override fun processElementUsages(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions
): Boolean {
if (isUnitTestMode() ||
!isPropertyOfDataClass ||
psiElement.getDisableComponentAndDestructionSearch(resetSingleFind = false)
) return super.processElementUsages(element, processor, options)
val indicator = ProgressManager.getInstance().progressIndicator
val notificationCanceller = scheduleNotificationForDataClassComponent(project, element, indicator)
try {
return super.processElementUsages(element, processor, options)
} finally {
Disposer.dispose(notificationCanceller)
}
}
private val isPropertyOfDataClass = runReadAction {
propertyDeclaration.parent is KtParameterList &&
propertyDeclaration.parent.parent is KtPrimaryConstructor &&
propertyDeclaration.parent.parent.parent.let { it is KtClass && it.isData() }
}
override fun getPrimaryElements(): Array<PsiElement> {
val element = psiElement as KtNamedDeclaration
if (element is KtParameter && !element.hasValOrVar() && factory.findPropertyOptions.isSearchInOverridingMethods) {
val function = element.ownerFunction
if (function != null && function.isOverridable()) {
function.toLightMethods().singleOrNull()?.let { method ->
if (OverridingMethodsSearch.search(method).any()) {
val parametersCount = method.parameterList.parametersCount
val parameterIndex = element.parameterIndex()
assert(parameterIndex < parametersCount)
return OverridingMethodsSearch.search(method, true)
.filter { method.parameterList.parametersCount == parametersCount }
.mapNotNull { method.parameterList.parameters[parameterIndex].unwrapped }
.toTypedArray()
}
}
}
} else if (factory.findPropertyOptions.isSearchForBaseAccessors) {
val supers = KotlinFindUsagesSupport.getSuperMethods(element, null)
return if (supers.contains(psiElement)) supers.toTypedArray() else (supers + psiElement).toTypedArray()
}
return super.getPrimaryElements()
}
override fun getFindUsagesOptions(dataContext: DataContext?): FindUsagesOptions = factory.findPropertyOptions
override fun getFindUsagesDialog(
isSingleFile: Boolean,
toShowInNewTab: Boolean,
mustOpenInNewTab: Boolean
): AbstractFindUsagesDialog {
return KotlinFindPropertyUsagesDialog(
getElement(),
project,
factory.findPropertyOptions,
toShowInNewTab,
mustOpenInNewTab,
isSingleFile,
this
)
}
override fun applyQueryFilters(element: PsiElement, options: FindUsagesOptions, query: Query<PsiReference>): Query<PsiReference> {
val kotlinOptions = options as KotlinPropertyFindUsagesOptions
if (!kotlinOptions.isReadAccess && !kotlinOptions.isWriteAccess) {
return EmptyQuery()
}
val result = query.applyFilter(kotlinOptions.isSkipImportStatements) { !it.isImportUsage() }
if (!kotlinOptions.isReadAccess || !kotlinOptions.isWriteAccess) {
val detector = KotlinReadWriteAccessDetector()
return FilteredQuery(result) {
when (detector.getReferenceAccess(element, it)) {
ReadWriteAccessDetector.Access.Read -> kotlinOptions.isReadAccess
ReadWriteAccessDetector.Access.Write -> kotlinOptions.isWriteAccess
ReadWriteAccessDetector.Access.ReadWrite -> kotlinOptions.isReadWriteAccess
}
}
}
return result
}
private fun PsiElement.getDisableComponentAndDestructionSearch(resetSingleFind: Boolean): Boolean {
if (!isPropertyOfDataClass) return false
if (forceDisableComponentAndDestructionSearch) return true
if (KotlinFindPropertyUsagesDialog.getDisableComponentAndDestructionSearch(project)) return true
return if (getUserData(FIND_USAGES_ONES_FOR_DATA_CLASS_KEY) == true) {
if (resetSingleFind) {
putUserData(FIND_USAGES_ONES_FOR_DATA_CLASS_KEY, null)
}
true
} else false
}
override fun createKotlinReferencesSearchOptions(options: FindUsagesOptions, forHighlight: Boolean): KotlinReferencesSearchOptions {
val kotlinOptions = options as KotlinPropertyFindUsagesOptions
val disabledComponentsAndOperatorsSearch =
!forHighlight && psiElement.getDisableComponentAndDestructionSearch(resetSingleFind = true)
return KotlinReferencesSearchOptions(
acceptCallableOverrides = true,
acceptOverloads = false,
acceptExtensionsOfDeclarationClass = false,
searchForExpectedUsages = kotlinOptions.searchExpected,
searchForOperatorConventions = !disabledComponentsAndOperatorsSearch,
searchForComponentConventions = !disabledComponentsAndOperatorsSearch
)
}
}
override fun createSearcher(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions
): Searcher {
return MySearcher(element, processor, options)
}
private inner class MySearcher(
element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions
) : Searcher(element, processor, options) {
private val kotlinOptions = options as KotlinCallableFindUsagesOptions
override fun buildTaskList(forHighlight: Boolean): Boolean {
val referenceProcessor = createReferenceProcessor(processor)
val uniqueProcessor = CommonProcessors.UniqueProcessor(processor)
if (options.isUsages) {
val baseKotlinSearchOptions = createKotlinReferencesSearchOptions(options, forHighlight)
val kotlinSearchOptions = if (element.isPotentiallyOperator()) {
baseKotlinSearchOptions
} else {
baseKotlinSearchOptions.copy(searchForOperatorConventions = false)
}
val searchParameters = KotlinReferencesSearchParameters(element, options.searchScope, kotlinOptions = kotlinSearchOptions)
addTask { applyQueryFilters(element, options, ReferencesSearch.search(searchParameters)).forEach(referenceProcessor) }
if (element is KtElement && !isOnlyKotlinSearch(options.searchScope)) {
// TODO: very bad code!! ReferencesSearch does not work correctly for constructors and annotation parameters
val psiMethodScopeSearch = when {
element is KtParameter && element.isDataClassComponentFunction ->
options.searchScope.excludeKotlinSources(project)
else -> options.searchScope
}
for (psiMethod in element.toLightMethods().filterDataClassComponentsIfDisabled(kotlinSearchOptions)) {
addTask {
val query = MethodReferencesSearch.search(psiMethod, psiMethodScopeSearch, true)
applyQueryFilters(
element,
options,
query
).forEach(referenceProcessor)
}
}
}
}
if (kotlinOptions.searchOverrides) {
addTask {
val overriders = HierarchySearchRequest(element, options.searchScope, true).searchOverriders()
overriders.all {
val element = runReadAction { it.takeIf { it.isValid }?.navigationElement } ?: return@all true
processUsage(uniqueProcessor, element)
}
}
}
return true
}
}
protected abstract fun createKotlinReferencesSearchOptions(
options: FindUsagesOptions,
forHighlight: Boolean
): KotlinReferencesSearchOptions
protected abstract fun applyQueryFilters(
element: PsiElement,
options: FindUsagesOptions,
query: Query<PsiReference>
): Query<PsiReference>
override fun isSearchForTextOccurrencesAvailable(psiElement: PsiElement, isSingleFile: Boolean): Boolean =
!isSingleFile && psiElement !is KtParameter
override fun findReferencesToHighlight(target: PsiElement, searchScope: SearchScope): Collection<PsiReference> {
val baseDeclarations = getTopMostOverriddenElementsToHighlight(target)
return if (baseDeclarations.isNotEmpty()) {
baseDeclarations.flatMap {
val handler = (FindManager.getInstance(project) as FindManagerImpl).findUsagesManager.getFindUsagesHandler(it!!, true)
handler?.findReferencesToHighlight(it, searchScope) ?: emptyList()
}
} else {
super.findReferencesToHighlight(target, searchScope)
}
}
companion object {
@Volatile
@get:TestOnly
var forceDisableComponentAndDestructionSearch = false
private const val DISABLE_ONCE = "DISABLE_ONCE"
private const val DISABLE = "DISABLE"
private val DISABLE_COMPONENT_AND_DESTRUCTION_SEARCH_TEXT
@Nls
get() = KotlinBundle.message(
"find.usages.text.find.usages.for.data.class.components.and.destruction.declarations",
DISABLE_ONCE,
DISABLE
)
private const val DISABLE_COMPONENT_AND_DESTRUCTION_SEARCH_TIMEOUT = 5000
private val FIND_USAGES_ONES_FOR_DATA_CLASS_KEY = Key<Boolean>("FIND_USAGES_ONES")
private fun scheduleNotificationForDataClassComponent(
project: Project,
element: PsiElement,
indicator: ProgressIndicator
): Disposable {
val notification = {
val listener = HyperlinkListener { event ->
if (event.eventType == HyperlinkEvent.EventType.ACTIVATED) {
indicator.cancel()
if (event.description == DISABLE) {
KotlinFindPropertyUsagesDialog.setDisableComponentAndDestructionSearch(project, /* value = */ true)
} else {
element.putUserData(FIND_USAGES_ONES_FOR_DATA_CLASS_KEY, true)
}
FindManager.getInstance(project).findUsages(element)
}
}
val windowManager = ToolWindowManager.getInstance(project)
windowManager.getToolWindow(ToolWindowId.FIND)?.let { toolWindow ->
windowManager.notifyByBalloon(
toolWindow.id,
MessageType.INFO,
DISABLE_COMPONENT_AND_DESTRUCTION_SEARCH_TEXT,
Actions.Find,
listener
)
}
Unit
}
return Alarm().also {
it.addRequest(notification, DISABLE_COMPONENT_AND_DESTRUCTION_SEARCH_TIMEOUT)
}
}
fun getInstance(
declaration: KtNamedDeclaration,
elementsToSearch: Collection<PsiElement> = emptyList(),
factory: KotlinFindUsagesHandlerFactory
): KotlinFindMemberUsagesHandler<out KtNamedDeclaration> {
return if (declaration is KtFunction)
Function(declaration, elementsToSearch, factory)
else
Property(declaration, elementsToSearch, factory)
}
}
}
fun Query<PsiReference>.applyFilter(flag: Boolean, condition: (PsiReference) -> Boolean): Query<PsiReference> {
return if (flag) FilteredQuery(this, condition) else this
}
| apache-2.0 | 5e5ed307a0676d2f0ac310c71322be31 | 45.01956 | 140 | 0.662948 | 6.017263 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/leetcode/longest_string_without_consequetive_chars/LongestString.kt | 1 | 2877 | package katas.kotlin.leetcode.longest_string_without_consequetive_chars
import datsok.shouldEqual
import org.junit.Test
import java.util.*
/**
* https://leetcode.com/discuss/interview-question/330356/Amazon-or-Online-Assessment-2019-or-Longest-string-without-3-consecutive-characters
*/
class LongestStringTests {
@Test fun examples() {
findMaxLengthString(a = 0, b = 0, c = 0) shouldEqual ""
findMaxLengthString(a = 1, b = 0, c = 0) shouldEqual "a"
findMaxLengthString(a = 0, b = 1, c = 0) shouldEqual "b"
findMaxLengthString(a = 0, b = 0, c = 1) shouldEqual "c"
findMaxLengthString(a = 3, b = 0, c = 0) shouldEqual "aa"
findMaxLengthString(a = 1, b = 1, c = 1) shouldEqual "acb"
findMaxLengthString(a = 2, b = 1, c = 1) shouldEqual "acab"
findMaxLengthString(a = 1, b = 1, c = 6) shouldEqual "ccaccbcc"
findMaxLengthString(a = 1, b = 2, c = 3) shouldEqual "cbcbca"
}
}
private fun findMaxLengthString(a: Int, b: Int, c: Int): String {
val heap = PriorityQueue<Pair<Int, Char>>(Comparator { o1, o2 -> -o1.first.compareTo(o2.first) })
if (a > 0) heap.add(Pair(a, 'a'))
if (b > 0) heap.add(Pair(b, 'b'))
if (c > 0) heap.add(Pair(c, 'c'))
var onHold: Pair<Int, Char>? = null
var result = ""
while (heap.isNotEmpty()) {
val (count, char) = heap.remove()
result += char
if (onHold != null) {
heap.add(onHold)
onHold = null
}
val updatedCount = count - 1
if (updatedCount > 0) {
if (result.length >= 2 && result[result.length - 2] == char) {
onHold = Pair(updatedCount, char)
} else {
heap.add(Pair(updatedCount, char))
}
}
}
return result
}
private fun findMaxLengthString_(a: Int, b: Int, c: Int): String {
fun findMaxLengthString(solution: Solution): List<Solution> {
if (solution.isComplete()) return listOf(solution)
return solution.nextSteps()
.filter { it.isValid() }
.flatMap { findMaxLengthString(it) }
}
return findMaxLengthString(Solution(List(a) { 'a' }, List(b) { 'b' }, List(c) { 'c' }))
.maxByOrNull { it.value.length }!!.value
}
private data class Solution(val a: List<Char>, val b: List<Char>, val c: List<Char>, val value: String = "") {
fun isComplete() = a.isEmpty() && b.isEmpty() && c.isEmpty()
fun isValid() = value.length < 3 || value.takeLast(3).toSet().size > 1
fun nextSteps(): List<Solution> {
return listOfNotNull(
if (a.isNotEmpty()) Solution(a.drop(1), b, c, value + a.first()) else null,
if (b.isNotEmpty()) Solution(a, b.drop(1), c, value + b.first()) else null,
if (c.isNotEmpty()) Solution(a, b, c.drop(1), value + c.first()) else null
)
}
} | unlicense | c4dc45036f85fab7b5bc0aaaf7205480 | 35.897436 | 141 | 0.583594 | 3.376761 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/dialog/DlgConfirm.kt | 1 | 4827 | package jp.juggler.subwaytooter.dialog
import android.annotation.SuppressLint
import android.view.View
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.databinding.DlgConfirmBinding
import jp.juggler.util.dismissSafe
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
object DlgConfirm {
// interface Callback {
// var isConfirmEnabled: Boolean
//
// fun onOK()
// }
// @SuppressLint("InflateParams")
// fun open(activity: Activity, message: String, callback: Callback): Dialog {
//
// if (!callback.isConfirmEnabled) {
// callback.onOK()
// return
// }
//
// val view = activity.layoutInflater.inflate(R.layout.dlg_confirm, null, false)
// val tvMessage = view.findViewById<TextView>(R.id.tvMessage)
// val cbSkipNext = view.findViewById<CheckBox>(R.id.cbSkipNext)
// tvMessage.text = message
//
// AlertDialog.Builder(activity)
// .setView(view)
// .setCancelable(true)
// .setNegativeButton(R.string.cancel, null)
// .setPositiveButton(R.string.ok) { _, _ ->
// if (cbSkipNext.isChecked) {
// callback.isConfirmEnabled = false
// }
// callback.onOK()
// }
// .show()
// }
// @SuppressLint("InflateParams")
// fun openSimple(activity: Activity, message: String, callback: () -> Unit) {
// val view = activity.layoutInflater.inflate(R.layout.dlg_confirm, null, false)
// val tvMessage = view.findViewById<TextView>(R.id.tvMessage)
// val cbSkipNext = view.findViewById<CheckBox>(R.id.cbSkipNext)
// tvMessage.text = message
// cbSkipNext.visibility = View.GONE
//
// AlertDialog.Builder(activity)
// .setView(view)
// .setCancelable(true)
// .setNegativeButton(R.string.cancel, null)
// .setPositiveButton(R.string.ok) { _, _ -> callback() }
// .show()
// }
@SuppressLint("InflateParams")
suspend fun AppCompatActivity.confirm(
message: String,
getConfirmEnabled: Boolean,
setConfirmEnabled: (newConfirmEnabled: Boolean) -> Unit,
) {
if (!getConfirmEnabled) return
suspendCancellableCoroutine<Unit> { cont ->
try {
val views = DlgConfirmBinding.inflate(layoutInflater)
views.tvMessage.text = message
val dialog = AlertDialog.Builder(this)
.setView(views.root)
.setCancelable(true)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ok) { _, _ ->
if (views.cbSkipNext.isChecked) {
setConfirmEnabled(false)
}
if (cont.isActive) cont.resume(Unit)
}
dialog.setOnDismissListener {
if (cont.isActive) cont.resumeWithException(CancellationException("dialog cancelled."))
}
dialog.show()
} catch (ex: Throwable) {
cont.resumeWithException(ex)
}
}
}
suspend fun AppCompatActivity.confirm(@StringRes messageId: Int, vararg args: Any?) =
confirm(getString(messageId, *args))
suspend fun AppCompatActivity.confirm(message: String) {
suspendCancellableCoroutine<Unit> { cont ->
try {
val views = DlgConfirmBinding.inflate(layoutInflater)
views.tvMessage.text = message
views.cbSkipNext.visibility = View.GONE
val dialog = AlertDialog.Builder(this)
.setView(views.root)
.setCancelable(true)
.setNegativeButton(R.string.cancel, null)
.setPositiveButton(R.string.ok) { _, _ ->
if (cont.isActive) cont.resume(Unit)
}
.create()
dialog.setOnDismissListener {
if (cont.isActive) cont.resumeWithException(CancellationException("dialog closed."))
}
dialog.show()
cont.invokeOnCancellation { dialog.dismissSafe() }
} catch (ex: Throwable) {
cont.resumeWithException(ex)
}
}
}
}
| apache-2.0 | 2a40f4f4c8703ac51e0bee786e245a0d | 36.616 | 107 | 0.559768 | 4.579696 | false | false | false | false |
tateisu/SubwayTooter | _Emoji/emojiConverter/src/main/kotlin/jp/juggler/subwaytooter/emoji/model/Emoji.kt | 1 | 3282 | package jp.juggler.subwaytooter.emoji.model
import jp.juggler.subwaytooter.emoji.cast
import java.io.File
class Emoji(
val key: CodepointList,
val unified: CodepointList
) : Comparable<Emoji> {
companion object {
val codeCameFroms = HashSet<String>()
val nameCameFroms = HashSet<String>()
}
override fun equals(other: Any?): Boolean =
key == other.cast<Emoji>()?.key
override fun hashCode(): Int =
key.hashCode()
override fun toString(): String =
"Emoji(${resName},${imageFiles.first().second})"
override fun compareTo(other: Emoji): Int =
key.compareTo(other.key)
////////////////
private val _shortNames = ArrayList<ShortName>()
val shortNames: List<ShortName> get() = _shortNames
fun addShortName(src: ShortName) {
nameCameFroms.add(src.cameFrom)
_shortNames.add(src)
}
fun removeShortName(name: String) {
_shortNames.removeIf { it.name == name }
}
fun removeShortNameByCameFrom(cameFrom: String) {
_shortNames.removeIf { it.cameFrom == cameFrom }
}
// 重複排除したコード一覧を返す
val nameList: List<Triple<Int,String,List<String>>>
get() {
val dst = ArrayList<Triple<Int, String, List<String>>>()
for (name in _shortNames.map { it.name }.toSet().sorted()) {
val froms = _shortNames.filter { it.name == name }.map { it.cameFrom }.sorted()
val priority = when {
froms.contains("fixName") -> 0
froms.contains("EmojiDataJson") -> 1
froms.contains("EmojiData(skinTone)") -> 2
froms.contains("EmojiOneJson") -> 3
froms.contains("emojiQualified") -> 4
else -> Int.MAX_VALUE
}
dst.add(Triple(priority, name, froms))
}
return dst.sortedBy { it.first }
}
////////////////
private val _codes = ArrayList<CodepointList>()
val codes: List<CodepointList> get() = _codes
fun addCode(item: CodepointList) {
if (item == unified) return
_codes.add(item)
}
fun removeCodeByCode(code: CodepointList) =
_codes.removeIf { it == code }
// 重複排除したコード一覧を返す
val codeSet: List<CodepointList>
get() = ArrayList<CodepointList>().also { dst ->
_codes.forEach { code ->
// twemoji svg のコードは末尾にfe0fを含む場合がある。そのまま使う
// emojiData(google)のコードは末尾にfe0fを含む場合がある。そのまま使う
// emojiData(twitter)のコードは末尾にfe0fを含む場合がある。そのまま使う
// mastodonSVG (emoji-dataの派生だ) のコードは末尾にfe0fを含む場合がある。そのまま使う
// 他のは工夫できるけど、とりあえずそのまま
if (!code.list.isAsciiEmoji() && !dst.any { it == code }) {
dst.add(code)
codeCameFroms.add(code.from)
}
}
}
/////////////////////////////
val imageFiles = ArrayList<Pair<File, String>>()
var resName: String = ""
// set of parent.unified
private val _toneParents = HashSet<Emoji>()
fun addToneParent(parent: Emoji) = _toneParents.add(parent)
val toneParents: Set<Emoji> get() = _toneParents
val toneChildren = HashMap<CodepointList,Emoji>()
var usedInCategory: Category? = null
var skip = false
init {
_codes.add(unified)
}
}
| apache-2.0 | 49a03c616f693fc890f4f50c6eb480a8 | 24.495575 | 83 | 0.643287 | 2.889961 | false | false | false | false |
google-developer-training/basic-android-kotlin-compose-training-reply-app | app/src/main/java/com/example/reply/ui/ReplyDetailsScreen.kt | 1 | 9388 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.reply.ui
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.example.reply.R
import com.example.reply.data.Email
import com.example.reply.data.MailboxType
/**
* Component that displays details screen
*/
@Composable
fun ReplyDetailsScreen(
replyUiState: ReplyUiState,
modifier: Modifier = Modifier,
onBackPressed: () -> Unit = {},
isFullScreen: Boolean = false
) {
BackHandler {
onBackPressed()
}
LazyColumn(
modifier = modifier
.testTag(stringResource(R.string.details_screen))
.fillMaxSize()
.background(color = MaterialTheme.colorScheme.inverseOnSurface)
.padding(top = 24.dp)
) {
item {
if (isFullScreen) {
ReplyDetailsScreenTopBar(onBackPressed, replyUiState)
}
ReplyEmailDetailsCard(
email = replyUiState.currentSelectedEmail,
mailboxType = replyUiState.currentMailbox,
isFullScreen = isFullScreen,
modifier = if (isFullScreen)
Modifier.padding(horizontal = 16.dp)
else
Modifier.padding(end = 16.dp)
)
}
}
}
@Composable
private fun ReplyDetailsScreenTopBar(
onBackButtonClicked: () -> Unit,
replyUiState: ReplyUiState,
modifier: Modifier = Modifier
) {
Row(
modifier = modifier
.fillMaxWidth()
.padding(bottom = 24.dp),
verticalAlignment = Alignment.CenterVertically,
) {
IconButton(
onClick = onBackButtonClicked,
modifier = Modifier
.padding(horizontal = 16.dp)
.background(MaterialTheme.colorScheme.surface, shape = CircleShape),
) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = stringResource(id = R.string.navigation_back)
)
}
Row(
horizontalArrangement = Arrangement.Center,
modifier = Modifier
.fillMaxWidth()
.padding(end = 40.dp)
) {
Text(
text = replyUiState.currentSelectedEmail.subject,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ReplyEmailDetailsCard(
email: Email,
mailboxType: MailboxType,
modifier: Modifier = Modifier,
isFullScreen: Boolean = false
) {
val context = LocalContext.current
val displayToast = { text: String ->
Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
}
Card(
modifier = modifier,
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(20.dp)
) {
DetailsScreenHeader(email)
if (!isFullScreen) {
Text(
text = email.subject,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.outline,
modifier = Modifier.padding(top = 12.dp, bottom = 8.dp),
)
} else {
Spacer(modifier = Modifier.height(12.dp))
}
Text(
text = email.body,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
DetailsScreenButtonBar(mailboxType, displayToast)
}
}
}
@Composable
private fun DetailsScreenButtonBar(
mailboxType: MailboxType,
displayToast: (String) -> Unit,
modifier: Modifier = Modifier
) {
when (mailboxType) {
MailboxType.Drafts ->
ActionButton(
text = stringResource(id = R.string.continue_composing),
onButtonClicked = displayToast,
modifier = modifier
)
MailboxType.Spam ->
Row(
modifier = modifier
.fillMaxWidth()
.padding(vertical = 20.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
ActionButton(
text = stringResource(id = R.string.move_to_inbox),
onButtonClicked = displayToast,
modifier = Modifier.weight(1f)
)
ActionButton(
text = stringResource(id = R.string.delete),
onButtonClicked = displayToast,
containIrreversibleAction = true,
modifier = Modifier.weight(1f)
)
}
MailboxType.Sent, MailboxType.Inbox ->
Row(
modifier = modifier
.fillMaxWidth()
.padding(vertical = 20.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
ActionButton(
text = stringResource(id = R.string.reply),
onButtonClicked = displayToast,
modifier = Modifier.weight(1f)
)
ActionButton(
text = stringResource(id = R.string.reply_all),
onButtonClicked = displayToast,
modifier = Modifier.weight(1f)
)
}
}
}
@Composable
private fun DetailsScreenHeader(email: Email, modifier: Modifier = Modifier) {
Row(modifier = modifier.fillMaxWidth()) {
ReplyProfileImage(
drawableResource = email.sender.avatar,
description = email.sender.fullName,
modifier = Modifier.size(40.dp)
)
Column(
modifier = Modifier
.weight(1f)
.padding(horizontal = 12.dp, vertical = 4.dp),
verticalArrangement = Arrangement.Center
) {
Text(
text = email.sender.firstName,
style = MaterialTheme.typography.labelMedium
)
Text(
text = email.createdAt,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.outline
)
}
}
}
@Composable
private fun ActionButton(
text: String,
onButtonClicked: (String) -> Unit,
modifier: Modifier = Modifier,
containIrreversibleAction: Boolean = false
) {
Button(
onClick = { onButtonClicked(text) },
modifier = modifier
.fillMaxWidth()
.padding(vertical = 20.dp),
colors = ButtonDefaults.buttonColors(
containerColor =
if (!containIrreversibleAction)
MaterialTheme.colorScheme.inverseOnSurface
else MaterialTheme.colorScheme.onErrorContainer
)
) {
Text(
text = text,
color =
if (!containIrreversibleAction)
MaterialTheme.colorScheme.onSurfaceVariant
else MaterialTheme.colorScheme.onError
)
}
}
| apache-2.0 | fe69fa8b6c731ad7c8889159c4ec14ab | 32.648746 | 92 | 0.605028 | 5.096634 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/translations/actions/SortTranslationsAction.kt | 1 | 1112 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.actions
import com.demonwav.mcdev.translations.TranslationFiles
import com.demonwav.mcdev.translations.sorting.TranslationSorter
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.actionSystem.PlatformDataKeys
class SortTranslationsAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val file = e.getData(LangDataKeys.PSI_FILE) ?: return
TranslationSorter.query(file.project, file)
}
override fun update(e: AnActionEvent) {
val file = e.getData(LangDataKeys.VIRTUAL_FILE)
val editor = e.getData(PlatformDataKeys.EDITOR)
if (file == null || editor == null) {
e.presentation.isEnabledAndVisible = false
return
}
e.presentation.isEnabledAndVisible = TranslationFiles.isTranslationFile(file)
}
}
| mit | 413b40435f5db5e9573b553abcd77bfa | 30.771429 | 85 | 0.732014 | 4.483871 | false | false | false | false |
paplorinc/intellij-community | uast/uast-tests/src/org/jetbrains/uast/test/env/AbstractTestWithCoreEnvironment.kt | 7 | 1636 | /*
* 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.test.env
import com.intellij.openapi.util.text.StringUtil
import com.intellij.rt.execution.junit.FileComparisonFailure
import junit.framework.TestCase
import java.io.File
private fun String.trimTrailingWhitespacesAndAddNewlineAtEOF(): String =
this.split('\n').map(String::trimEnd).joinToString(separator = "\n").let { result ->
if (result.endsWith("\n")) result else result + "\n"
}
fun assertEqualsToFile(description: String, expected: File, actual: String) {
if (!expected.exists()) {
expected.writeText(actual)
TestCase.fail("File didn't exist. New file was created (${expected.canonicalPath}).")
}
val expectedText =
StringUtil.convertLineSeparators(expected.readText().trim()).trimTrailingWhitespacesAndAddNewlineAtEOF()
val actualText =
StringUtil.convertLineSeparators(actual.trim()).trimTrailingWhitespacesAndAddNewlineAtEOF()
if (expectedText != actualText) {
throw FileComparisonFailure(description, expectedText, actualText, expected.absolutePath)
}
}
| apache-2.0 | e27aa837424436f95832ba702185854b | 38.902439 | 108 | 0.757335 | 4.316623 | false | true | false | false |
google/intellij-community | plugins/kotlin/base/code-insight/tests/test/org/jetbrains/kotlin/idea/base/codeInsight/test/KotlinExpressionNameSuggesterTest.kt | 1 | 2762 | // 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.base.codeInsight.test
import com.intellij.psi.util.findParentOfType
import com.intellij.testFramework.LightProjectDescriptor
import junit.framework.TestCase
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.executeOnPooledThreadInReadAction
import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggester
import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggester.Case
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.psi.KtCallExpression
class KotlinExpressionNameSuggesterTest : KotlinLightCodeInsightFixtureTestCase() {
fun testNumericLiteral() = test("5", "int", "i", "n")
fun testStringLiteral() = test("\"foo\"", "string", "str", "s", "text")
fun testClassLiteral() = test("String::class", "klass", "clazz", "declaration")
fun testIntArray() = test("intArrayOf(1, 2, 3)", "ints")
fun testGenericIntArray() = test("arrayOf(1, 2, 3)", "ints")
fun testGenericArray() = test("arrayOf(1, 'c')", "values")
fun testIntList() = test("listOf(1, 2, 3)", "ints")
fun testClassList() = test("listOf(String::class.java, Long::class.java)", "classes")
fun testStringList() = test("listOf(\"foo\", \"bar\")", "strings")
fun testGenericList() = test("listOf(1, 'c')", "values")
fun testLazy() = test("lazy { 5 }", "lazy")
fun testJavaFile() = test("java.io.File(\".\")", "file")
fun testAnonymousFunction() = test("fun(s: String): Boolean = s.isNotEmpty()", "function", "fn", "f")
fun testLambda() = test("{ s: String -> s.isNotEmpty() }", "function", "fn", "f")
private fun test(expressionText: String, vararg names: String) {
val fileText = "fun test() { print<caret>($expressionText) }"
val file = myFixture.configureByText("file.kt", fileText)
val callExpression = file.findElementAt(myFixture.caretOffset)!!.findParentOfType<KtCallExpression>()!!
val targetExpression = callExpression.valueArguments.single().getArgumentExpression()!!
executeOnPooledThreadInReadAction {
analyze(targetExpression) {
val actualNames = with(KotlinNameSuggester(Case.CAMEL)) {
suggestExpressionNames(targetExpression).toList().sorted()
}
TestCase.assertEquals(names.sorted(), actualNames)
}
}
}
override fun getProjectDescriptor(): LightProjectDescriptor {
return KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
}
} | apache-2.0 | 07a387d3e553c9dd894473103619eac1 | 52.134615 | 120 | 0.700579 | 4.550247 | false | true | false | false |
RuneSuite/client | api/src/main/java/org/runestar/client/api/game/Component.kt | 1 | 6129 | package org.runestar.client.api.game
import org.runestar.client.api.game.live.InterfaceParents
import org.runestar.client.api.game.live.Interfaces
import org.runestar.client.raw.CLIENT
import org.runestar.client.raw.access.XComponent
import java.awt.Dimension
import java.awt.Point
class Component(override val accessor: XComponent) : Wrapper(accessor) {
val type: Int get() = accessor.type
val cycle: Int get() = accessor.cycle
val isActive get() = cycle >= CLIENT.cycle
var isHidden: Boolean
get() = accessor.isHidden
set(value) { accessor.isHidden = value }
val id get() = ComponentId(accessor.id)
val group get() = checkNotNull(Interfaces[id.itf])
val hasStaticParent: Boolean get() = accessor.parentId != -1
val staticParent: Component? get() = staticParent(accessor)?.let { Component(it) }
val parent: Component? get() = parent(accessor)?.let { Component(it) }
val dynamicChildIndex: Int get() = accessor.childIndex
val isDynamicChild: Boolean get() = dynamicChildIndex != -1
var color: RgbColor
get() = RgbColor(accessor.color)
set(value) { accessor.color = value.packed }
var rawX: Int
get() = accessor.rawX
set(value) { accessor.rawX = value }
var rawY: Int
get() = accessor.rawY
set(value) { accessor.rawY = value }
val width: Int get() = when (type) {
ComponentType.INVENTORY -> accessor.width * (ITEM_SLOT_SIZE + accessor.paddingX) - accessor.paddingX
else -> accessor.width
}
val height: Int get() = when (type) {
ComponentType.INVENTORY -> accessor.height * (ITEM_SLOT_SIZE + accessor.paddingY) - accessor.paddingY
else -> accessor.height
}
val dimension: Dimension get() = Dimension(width, height)
val shape: java.awt.Rectangle? get() = location?.let { java.awt.Rectangle(it.x, it.y, width, height) }
val flat: Sequence<Component> get() = when(type) {
ComponentType.LAYER -> sequenceOf(this).plus(dynamicChildren.asSequence().filterNotNull())
else -> sequenceOf(this)
}
val dynamicChildren: List<Component?> get() = object : AbstractList<Component?>(), RandomAccess {
override val size: Int get() = accessor.children?.size ?: 0
override fun get(index: Int): Component? {
val array = accessor.children ?: return null
return array[index]?.let { Component(it) }
}
}
val staticChildren: Sequence<Component> get() = group.asSequence().filter { it.accessor.parentId == accessor.id }
val nestedGroup: Interface? get() = InterfaceParents[id]?.let { Interfaces[it] }
val nestedChildren: Sequence<Component> get() = nestedGroup?.roots ?: emptySequence()
val children: Sequence<Component> get() = sequenceOf(dynamicChildren.asSequence().filterNotNull(), staticChildren, nestedChildren).flatten()
val location: Point? get() {
var cur = accessor
var anc = parent(cur)
var x = 0
var y = 0
while(anc != null) {
x += cur.x - anc.scrollX
y += cur.y - anc.scrollY
cur = anc
anc = parent(anc)
}
if (ComponentId.getItf(cur.id) != Interfaces.rootId) return null
if (cur.rootIndex == -1) return null
x += CLIENT.rootComponentXs[cur.rootIndex]
y += CLIENT.rootComponentYs[cur.rootIndex]
return Point(x, y)
}
val scrollX: Int get() = accessor.scrollX
val scrollY: Int get() = accessor.scrollY
val scrollWidth: Int get() = accessor.scrollWidth
val scrollHeight: Int get() = accessor.scrollHeight
val fontId: Int get() = accessor.fontId
var text: String?
get() = accessor.text
set(value) { accessor.text = value }
val textXAlignment: Int get() = accessor.textXAlignment
val textYAlignment: Int get() = accessor.textYAlignment
val isTextShadowed: Boolean get() = accessor.textShadowed
val textLineHeight: Int get() = accessor.textLineHeight
val modelType: Int get() = accessor.modelType
val modelId: Int get() = accessor.modelId
fun idString(): String {
return if (isDynamicChild) {
"${id.itf}:${id.component}:$dynamicChildIndex"
} else {
"${id.itf}:${id.component}"
}
}
override fun toString(): String {
return "Component(${idString()})"
}
val items: List<ComponentItem> get() = object : AbstractList<ComponentItem>(), RandomAccess {
private val location = checkNotNull([email protected])
override val size: Int get() = accessor.width * accessor.height
override fun get(index: Int): ComponentItem {
val id = accessor.itemIds[index]
val quantity = accessor.itemQuantities[index]
val item = Item.of(id, quantity)
val row = index / accessor.width
val col = index % accessor.width
val x = location.x + ((ITEM_SLOT_SIZE + accessor.paddingX) * col)
val y = location.y + ((ITEM_SLOT_SIZE + accessor.paddingY) * row)
val rect = java.awt.Rectangle(x, y, ITEM_SLOT_SIZE, ITEM_SLOT_SIZE)
return ComponentItem(item, rect)
}
}
companion object {
const val ITEM_SLOT_SIZE = 32
private fun parent(component: XComponent): XComponent? {
val staticParent = staticParent(component)
if (staticParent != null) return staticParent
if (ComponentId.getItf(component.id) == Interfaces.rootId) return null
val nestedParentId = InterfaceParents.parentId(ComponentId.getItf(component.id))
if (nestedParentId == -1) return null
return CLIENT.interfaceComponents[ComponentId.getItf(nestedParentId)][ComponentId.getComponent(nestedParentId)]
}
private fun staticParent(component: XComponent): XComponent? {
val pid = component.parentId
if (pid == -1) return null
return CLIENT.interfaceComponents[ComponentId.getItf(pid)][ComponentId.getComponent(pid)]
}
}
} | mit | 6cdb9c5e8846e922a8dc00ae8098561b | 33.24581 | 144 | 0.637135 | 4.155254 | false | false | false | false |
square/okhttp | samples/tlssurvey/src/main/kotlin/okhttp3/survey/Iana.kt | 2 | 2170 | /*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.survey
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.executeAsync
import okhttp3.survey.types.SuiteId
import okio.ByteString
import okio.ByteString.Companion.decodeHex
import okio.IOException
/** Example: "0x00,0x08",TLS_RSA_EXPORT_WITH_DES40_CBC_SHA,Y,N,[RFC4346] */
val IANA_CSV_PATTERN = "\"0x(\\w\\w),0x(\\w\\w)\",(\\w+).*".toRegex()
fun parseIanaCsvRow(s: String): SuiteId? {
if (s.contains("Reserved") || s.contains("Unassigned")) return null
val matcher = IANA_CSV_PATTERN.matchEntire(s) ?: return null
val id: ByteString = (matcher.groupValues[1] + matcher.groupValues[2]).decodeHex()
return SuiteId(id, matcher.groupValues[3])
}
class IanaSuites(
val name: String, val suites: List<SuiteId>
) {
fun fromJavaName(javaName: String): SuiteId {
for (suiteId in suites) {
val alternateName = "TLS_" + javaName.substring(4)
if (suiteId.name == javaName || suiteId.name == alternateName) {
return suiteId
}
}
throw IllegalArgumentException("No such suite: $javaName")
}
}
suspend fun fetchIanaSuites(okHttpClient: OkHttpClient): IanaSuites {
val url = "https://www.iana.org/assignments/tls-parameters/tls-parameters-4.csv"
val call = okHttpClient.newCall(Request(url.toHttpUrl()))
val suites = call.executeAsync().use {
if (!it.isSuccessful) {
throw IOException("Failed ${it.code} ${it.message}")
}
it.body.string().lines()
}.mapNotNull { parseIanaCsvRow(it) }
return IanaSuites("current", suites)
}
| apache-2.0 | 8c164a1a813b80c0206aebfbb9e31225 | 32.90625 | 84 | 0.713364 | 3.598673 | false | false | false | false |
JetBrains/intellij-community | platform/lang-impl/src/com/intellij/ide/navbar/ide/NavBarService.kt | 1 | 4537 | // 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.ide.navbar.ide
import com.intellij.ide.navbar.NavBarItem
import com.intellij.ide.navbar.actions.NavBarActionHandler
import com.intellij.ide.navbar.impl.ProjectNavBarItem
import com.intellij.ide.navbar.impl.isModuleContentRoot
import com.intellij.ide.navbar.impl.pathToItem
import com.intellij.ide.navbar.ui.NewNavBarPanel
import com.intellij.ide.navbar.ui.StaticNavBarPanel
import com.intellij.ide.navbar.ui.showHint
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.*
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.Service.Level.PROJECT
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.util.ui.EDT
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import javax.swing.JComponent
@Service(PROJECT)
internal class NavBarService(private val project: Project) : Disposable {
companion object {
@JvmStatic
fun getInstance(project: Project): NavBarService = project.service()
}
@OptIn(ExperimentalCoroutinesApi::class)
private val cs: CoroutineScope = CoroutineScope(
SupervisorJob() +
Dispatchers.Default.limitedParallelism(1) // allows to reason about the ordering
)
override fun dispose() {
cs.cancel()
}
private val staticNavBarVm = StaticNavBarVmImpl(cs, project, UISettings.getInstance().isNavbarShown())
private var floatingBarJob: Job? = null
fun uiSettingsChanged(uiSettings: UISettings) {
if (uiSettings.isNavbarShown()) {
floatingBarJob?.cancel()
}
staticNavBarVm.isVisible = uiSettings.isNavbarShown()
}
val staticNavBarPanel: JComponent by lazy(LazyThreadSafetyMode.NONE) {
EDT.assertIsEdt()
StaticNavBarPanel(cs, staticNavBarVm, project)
}
fun jumpToNavbar(dataContext: DataContext) {
val navBarVm = staticNavBarVm.vm.value
if (navBarVm != null) {
navBarVm.selectTail()
navBarVm.showPopup()
}
else {
showFloatingNavbar(dataContext)
}
}
fun selectTail() {
staticNavBarVm.vm.value?.selectTail()
}
private fun showFloatingNavbar(dataContext: DataContext) {
val job = cs.launch(ModalityState.current().asContextElement()) {
val model = contextModel(dataContext, project).ifEmpty {
defaultModel(project)
}
val barScope = this@launch
val vm = NavBarVmImpl(cs = barScope, project, model, activityFlow = emptyFlow())
withContext(Dispatchers.EDT) {
val component = NewNavBarPanel(barScope, vm, project, true)
while (component.componentCount == 0) {
// wait while panel will fill itself with item components
yield()
}
showHint(dataContext, project, component)
vm.selectTail()
vm.showPopup()
}
}
floatingBarJob = job
job.invokeOnCompletion {
floatingBarJob = null
}
}
}
internal suspend fun focusModel(project: Project): List<NavBarVmItem> {
val ctx = focusDataContext()
if (ctx.getData(NavBarActionHandler.NAV_BAR_ACTION_HANDLER) != null) {
// ignore updates while nav bar has focus
return emptyList()
}
return contextModel(ctx, project)
}
private suspend fun contextModel(ctx: DataContext, project: Project): List<NavBarVmItem> {
if (CommonDataKeys.PROJECT.getData(ctx) != project) {
return emptyList()
}
try {
return readAction {
contextModelInner(ctx)
}
}
catch (ce: CancellationException) {
throw ce
}
catch (t: Throwable) {
LOG.error(t)
return emptyList()
}
}
private fun contextModelInner(ctx: DataContext): List<NavBarVmItem> {
val contextItem = NavBarItem.NAVBAR_ITEM_KEY.getData(ctx)
?: return emptyList()
return contextItem.pathToItem().toVmItems()
}
internal fun List<NavBarItem>.toVmItems(): List<NavBarVmItem> {
ApplicationManager.getApplication().assertReadAccessAllowed()
return map {
NavBarVmItem(it.createPointer(), it.presentation(), it.isModuleContentRoot(), it.javaClass)
}
}
internal suspend fun defaultModel(project: Project): List<NavBarVmItem> {
return readAction {
val item = ProjectNavBarItem(project)
listOf(NavBarVmItem(item.createPointer(), item.presentation(), true, item.javaClass))
}
}
| apache-2.0 | cd95fc643259c717bcfa8df7d8cab8a0 | 29.863946 | 120 | 0.729777 | 4.181567 | false | false | false | false |
Leifzhang/AndroidRouter | app/src/main/java/com/kronos/sample/viewbinding/ext/ReflectExt.kt | 2 | 573 | package com.kronos.sample.viewbinding.ext
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
/**
* <pre>
* author: dhl
* date : 2020/12/11
* desc :
* </pre>
*/
const val INFLATE_NAME = "inflate"
const val BIND_NAME = "bind"
fun <T> Class<T>.inflateMethod() = getMethod(INFLATE_NAME, LayoutInflater::class.java)
fun <T> Class<T>.inflateMethodWithViewGroup() =
getMethod(INFLATE_NAME, LayoutInflater::class.java, ViewGroup::class.java)
fun <T> Class<T>.bindMethod() = getMethod(BIND_NAME, View::class.java) | mit | 3054ade5f577e3b9cfec5cc69d2454e3 | 23.956522 | 86 | 0.705061 | 3.148352 | false | false | false | false |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/ui/feed/FeedAdapter.kt | 4 | 3350 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.ui.feed
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
typealias FeedItemClass = Class<out Any>
typealias FeedItemBinder = FeedItemViewBinder<Any, ViewHolder>
class FeedAdapter(
private val viewBinders: Map<FeedItemClass, FeedItemBinder>
) : ListAdapter<Any, ViewHolder>(FeedDiffCallback(viewBinders)) {
private val viewTypeToBinders = viewBinders.mapKeys { it.value.getFeedItemType() }
private fun getViewBinder(viewType: Int): FeedItemBinder = viewTypeToBinders.getValue(viewType)
override fun getItemViewType(position: Int): Int =
viewBinders.getValue(super.getItem(position).javaClass).getFeedItemType()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return getViewBinder(viewType).createViewHolder(parent)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
return getViewBinder(getItemViewType(position)).bindViewHolder(getItem(position), holder)
}
override fun onViewRecycled(holder: ViewHolder) {
getViewBinder(holder.itemViewType).onViewRecycled(holder)
super.onViewRecycled(holder)
}
override fun onViewDetachedFromWindow(holder: ViewHolder) {
getViewBinder(holder.itemViewType).onViewDetachedFromWindow(holder)
super.onViewDetachedFromWindow(holder)
}
}
/** Encapsulates logic to create and bind a ViewHolder for a type of item in the Feed. */
abstract class FeedItemViewBinder<M, in VH : ViewHolder>(
val modelClass: Class<out M>
) : DiffUtil.ItemCallback<M>() {
abstract fun createViewHolder(parent: ViewGroup): ViewHolder
abstract fun bindViewHolder(model: M, viewHolder: VH)
abstract fun getFeedItemType(): Int
// Having these as non abstract because not all the viewBinders are required to implement them.
open fun onViewRecycled(viewHolder: VH) = Unit
open fun onViewDetachedFromWindow(viewHolder: VH) = Unit
}
internal class FeedDiffCallback(
private val viewBinders: Map<FeedItemClass, FeedItemBinder>
) : DiffUtil.ItemCallback<Any>() {
override fun areItemsTheSame(oldItem: Any, newItem: Any): Boolean {
if (oldItem::class != newItem::class) {
return false
}
return viewBinders[oldItem::class.java]?.areItemsTheSame(oldItem, newItem) ?: false
}
override fun areContentsTheSame(oldItem: Any, newItem: Any): Boolean {
// We know the items are the same class because [areItemsTheSame] returned true
return viewBinders[oldItem::class.java]?.areContentsTheSame(oldItem, newItem) ?: false
}
}
| apache-2.0 | 7ecca591bc240ab09dee242e9bdc2a13 | 37.505747 | 99 | 0.745075 | 4.724965 | false | false | false | false |
allotria/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHPRDiffEditorGutterIconRendererFactoryImpl.kt | 2 | 6486 | // 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 org.jetbrains.plugins.github.pullrequest.comment.ui
import com.intellij.diff.util.Side
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.Disposer
import com.intellij.util.ui.codereview.diff.AddCommentGutterIconRenderer
import com.intellij.util.ui.codereview.diff.DiffEditorGutterIconRendererFactory
import com.intellij.util.ui.codereview.diff.EditorComponentInlaysManager
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.ui.SimpleEventListener
import org.jetbrains.plugins.github.ui.util.GHUIUtil
import javax.swing.JComponent
class GHPRDiffEditorGutterIconRendererFactoryImpl(private val reviewProcessModel: GHPRReviewProcessModel,
private val inlaysManager: EditorComponentInlaysManager,
private val componentFactory: GHPRDiffEditorReviewComponentsFactory,
private val cumulative: Boolean,
private val lineLocationCalculator: (Int) -> GHPRCommentLocation?)
: DiffEditorGutterIconRendererFactory {
override fun createCommentRenderer(line: Int): AddCommentGutterIconRenderer = CreateCommentIconRenderer(line)
private inner class CreateCommentIconRenderer(override val line: Int)
: AddCommentGutterIconRenderer() {
private var reviewState = ReviewState(false, null)
private val reviewProcessListener = object : SimpleEventListener {
override fun eventOccurred() {
reviewState = ReviewState(reviewProcessModel.isActual, reviewProcessModel.pendingReview?.id)
}
}
private var inlay: Pair<JComponent, Disposable>? = null
init {
reviewProcessModel.addAndInvokeChangesListener(reviewProcessListener)
}
override fun getClickAction(): DumbAwareAction? {
if (inlay != null) return FocusInlayAction()
val reviewId = reviewState.reviewId
if (!reviewState.isDataActual || reviewId == null) return null
return AddReviewCommentAction(line, reviewId, isMultiline(line))
}
private inner class FocusInlayAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
if (inlay?.let { GHUIUtil.focusPanel(it.first) } != null) return
}
}
override fun getPopupMenuActions(): ActionGroup? {
if (inlay != null) return null
if (!reviewState.isDataActual || reviewState.reviewId != null) return null
val multiline = isMultiline(line)
return DefaultActionGroup(StartReviewAction(line, multiline), AddSingleCommentAction(line, multiline))
}
private fun isMultiline(line: Int) = cumulative &&
(lineLocationCalculator(line)
?: GHPRCommentLocation(Side.RIGHT, line, line, line)).let { it.line != it.startLine }
private abstract inner class InlayAction(actionName: () -> String,
private val editorLine: Int)
: DumbAwareAction(actionName) {
override fun actionPerformed(e: AnActionEvent) {
if (inlay?.let { GHUIUtil.focusPanel(it.first) } != null) return
val (side, line, startLine, realEditorLine) = lineLocationCalculator(editorLine) ?: return
val hideCallback = {
inlay?.let { Disposer.dispose(it.second) }
inlay = null
}
val component = if (isMultiline(editorLine))
createComponent(side, line, startLine, hideCallback)
else
createComponent(side, line, line, hideCallback)
val disposable = inlaysManager.insertAfter(realEditorLine, component) ?: return
GHUIUtil.focusPanel(component)
inlay = component to disposable
}
protected abstract fun createComponent(side: Side, line: Int, startLine: Int = line, hideCallback: () -> Unit): JComponent
}
private inner class AddSingleCommentAction(editorLine: Int, isMultiline: Boolean = false)
: InlayAction({
if (isMultiline) GithubBundle.message("pull.request.diff.editor.add.multiline.comment")
else GithubBundle.message("pull.request.diff.editor.add.single.comment")
}, editorLine) {
override fun createComponent(side: Side, line: Int, startLine: Int, hideCallback: () -> Unit) =
componentFactory.createSingleCommentComponent(side, line, startLine, hideCallback)
}
private inner class StartReviewAction(editorLine: Int, isMultiline: Boolean = false)
: InlayAction({
if (isMultiline) GithubBundle.message("pull.request.diff.editor.start.review.with.multiline.comment")
else GithubBundle.message("pull.request.diff.editor.review.with.comment")
}, editorLine) {
override fun createComponent(side: Side, line: Int, startLine: Int, hideCallback: () -> Unit) =
componentFactory.createNewReviewCommentComponent(side, line, startLine, hideCallback)
}
private inner class AddReviewCommentAction(editorLine: Int, private val reviewId: String, isMultiline: Boolean = false)
: InlayAction({
if (isMultiline) GithubBundle.message("pull.request.diff.editor.add.multiline.review.comment")
else GithubBundle.message("pull.request.diff.editor.add.review.comment")
}, editorLine) {
override fun createComponent(side: Side, line: Int, startLine: Int, hideCallback: () -> Unit) =
componentFactory.createReviewCommentComponent(reviewId, side, line, startLine, hideCallback)
}
override fun dispose() {
super.dispose()
reviewProcessModel.removeChangesListener(reviewProcessListener)
}
override fun disposeInlay() {
inlay?.second?.let { Disposer.dispose(it) }
}
}
private data class ReviewState(val isDataActual: Boolean, val reviewId: String?)
}
data class GHPRCommentLocation(val side: Side, val line: Int, val startLine: Int = line, val editorLine: Int = line)
| apache-2.0 | af33a368e425fcace58c61884f9ca7ec | 45 | 140 | 0.688406 | 4.977744 | false | false | false | false |
allotria/intellij-community | platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/propertyBased/EntityManipulations.kt | 2 | 23913 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.propertyBased
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.entities.*
import com.intellij.workspaceModel.storage.impl.ClassConversion
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityStorageBuilderImpl
import com.intellij.workspaceModel.storage.impl.exceptions.PersistentIdAlreadyExistsException
import com.intellij.workspaceModel.storage.impl.toClassId
import org.jetbrains.jetCheck.Generator
import org.jetbrains.jetCheck.ImperativeCommand
import org.junit.Assert
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty1
internal fun getEntityManipulation(workspace: WorkspaceEntityStorageBuilderImpl): Generator<ImperativeCommand>? {
return Generator.anyOf(
RemoveSomeEntity.create(workspace),
EntityManipulation.addManipulations(workspace),
EntityManipulation.modifyManipulations(workspace),
ChangeEntitySource.create(workspace)
)
}
internal interface EntityManipulation {
fun addManipulation(storage: WorkspaceEntityStorageBuilderImpl): AddEntity
fun modifyManipulation(storage: WorkspaceEntityStorageBuilderImpl): ModifyEntity<out WorkspaceEntity, out ModifiableWorkspaceEntity<out WorkspaceEntity>>
companion object {
fun addManipulations(storage: WorkspaceEntityStorageBuilderImpl): Generator<AddEntity> {
return Generator.sampledFrom(manipulations.map { it.addManipulation(storage) })
}
fun modifyManipulations(storage: WorkspaceEntityStorageBuilderImpl): Generator<ModifyEntity<*, *>> {
return Generator.sampledFrom(manipulations.map { it.modifyManipulation(storage) })
}
private val manipulations = listOf(
SampleEntityManipulation,
ParentEntityManipulation,
ChildEntityManipulation,
ChildWithOptionalParentManipulation,
OoParentManipulation,
OoChildManipulation,
// Entities with abstractions
MiddleEntityManipulation,
AbstractEntities.Left,
AbstractEntities.Right,
// Do not enable at the moment. A lot of issues about entities with persistentId
//NamedEntityManipulation
)
}
}
// Common for all entities
private class RemoveSomeEntity(private val storage: WorkspaceEntityStorageBuilderImpl) : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val id = env.generateValue(EntityIdGenerator.create(storage), null) ?: run {
env.logMessage("Tried to remove random entity, but failed to select entity")
return
}
storage.removeEntity(storage.entityDataByIdOrDie(id).createEntity(storage))
Assert.assertNull(storage.entityDataById(id))
env.logMessage("Entity removed. Id: $id")
}
companion object {
fun create(workspace: WorkspaceEntityStorageBuilderImpl): Generator<RemoveSomeEntity> = Generator.constant(RemoveSomeEntity(workspace))
}
}
private class ChangeEntitySource(private val storage: WorkspaceEntityStorageBuilderImpl) : ImperativeCommand {
override fun performCommand(env: ImperativeCommand.Environment) {
val id = env.generateValue(EntityIdGenerator.create(storage), null) ?: run {
env.logMessage("Tried to change entity source, but entity to change isn't found")
return
}
val newSource = env.generateValue(sources, null)
val entity = storage.entityDataByIdOrDie(id).createEntity(storage)
val oldEntitySource = entity.entitySource
storage.changeSource(entity, newSource)
env.logMessage("Entity source changed. Entity: $entity, Old source: $oldEntitySource, New source: $newSource")
}
companion object {
fun create(workspace: WorkspaceEntityStorageBuilderImpl): Generator<ChangeEntitySource> {
return Generator.constant(ChangeEntitySource(workspace))
}
}
}
internal abstract class AddEntity(protected val storage: WorkspaceEntityStorageBuilderImpl,
private val entityDescription: String) : ImperativeCommand {
abstract fun makeEntity(source: EntitySource, someProperty: String, env: ImperativeCommand.Environment): Pair<WorkspaceEntity?, String>
final override fun performCommand(env: ImperativeCommand.Environment) {
val property = env.generateValue(randomNames, null)
val source = env.generateValue(sources, null)
val (createdEntity, description) = makeEntity(source, property, env)
if (createdEntity != null) {
createdEntity as WorkspaceEntityBase
Assert.assertNotNull(storage.entityDataById(createdEntity.id))
env.logMessage("New entity added: $createdEntity. Source: ${createdEntity.entitySource}. $description")
}
else {
env.logMessage("Tried to add $entityDescription but failed because: $description")
}
}
}
internal abstract class ModifyEntity<E : WorkspaceEntity, M : ModifiableWorkspaceEntity<E>>(private val entityClass: KClass<E>,
protected val storage: WorkspaceEntityStorageBuilderImpl) : ImperativeCommand {
abstract fun modifyEntity(env: ImperativeCommand.Environment): List<M.() -> Unit>
final override fun performCommand(env: ImperativeCommand.Environment) {
val modifiableClass = ClassConversion.entityDataToModifiableEntity(ClassConversion.entityToEntityData(entityClass)).java as Class<M>
val entityId = env.generateValue(EntityIdOfFamilyGenerator.create(storage, entityClass.java.toClassId()), null)
if (entityId == null) return
val entity = storage.entityDataByIdOrDie(entityId).createEntity(storage) as E
val modifications = env.generateValue(Generator.sampledFrom(modifyEntity(env)), null)
try {
storage.modifyEntity(modifiableClass, entity, modifications)
env.logMessage("$entity modified")
}
catch (e: PersistentIdAlreadyExistsException) {
env.logMessage("Cannot modify ${entityClass.simpleName} entity. Persistent id ${e.id} already exists")
}
env.logMessage("----------------------------------")
}
}
private object NamedEntityManipulation : EntityManipulation {
override fun addManipulation(storage: WorkspaceEntityStorageBuilderImpl): AddEntity {
return object : AddEntity(storage, "NamedEntity") {
override fun makeEntity(source: EntitySource,
someProperty: String,
env: ImperativeCommand.Environment): Pair<WorkspaceEntity?, String> {
return try {
storage.addNamedEntity(someProperty, source = source) to "Set property for NamedEntity: $someProperty"
}
catch (e: PersistentIdAlreadyExistsException) {
val persistentId = e.id as NameId
assert(storage.entities(NamedEntity::class.java).any { it.persistentId() == persistentId }) {
"$persistentId reported as existing, but it's not found"
}
null to "NamedEntity with this property isn't added because this persistent id already exists"
}
}
}
}
override fun modifyManipulation(storage: WorkspaceEntityStorageBuilderImpl): ModifyEntity<out WorkspaceEntity, out ModifiableWorkspaceEntity<out WorkspaceEntity>> {
return object : ModifyEntity<NamedEntity, ModifiableNamedEntity>(NamedEntity::class, storage) {
override fun modifyEntity(env: ImperativeCommand.Environment): List<ModifiableNamedEntity.() -> Unit> {
return listOf(modifyStringProperty(ModifiableNamedEntity::name, env))
}
}
}
}
private object ChildWithOptionalParentManipulation : EntityManipulation {
override fun addManipulation(storage: WorkspaceEntityStorageBuilderImpl): AddEntity {
return object : AddEntity(storage, "ChildWithOptionalDependency") {
override fun makeEntity(source: EntitySource,
someProperty: String,
env: ImperativeCommand.Environment): Pair<WorkspaceEntity?, String> {
val classId = ParentEntity::class.java.toClassId()
val parentId = env.generateValue(Generator.anyOf(
Generator.constant(null),
EntityIdOfFamilyGenerator.create(storage, classId)
), null)
val parentEntity = parentId?.let { storage.entityDataByIdOrDie(it).createEntity(storage) as ParentEntity }
return storage.addChildWithOptionalParentEntity(parentEntity, someProperty, source) to "Select parent for child: $parentId"
}
}
}
override fun modifyManipulation(storage: WorkspaceEntityStorageBuilderImpl): ModifyEntity<ChildWithOptionalParentEntity, ModifiableChildWithOptionalParentEntity> {
return object : ModifyEntity<ChildWithOptionalParentEntity, ModifiableChildWithOptionalParentEntity>(
ChildWithOptionalParentEntity::class, storage) {
override fun modifyEntity(env: ImperativeCommand.Environment): List<ModifiableChildWithOptionalParentEntity.() -> Unit> {
return listOf(
modifyStringProperty(ModifiableChildWithOptionalParentEntity::childProperty, env),
modifyNullableProperty(ModifiableChildWithOptionalParentEntity::optionalParent, parentGenerator(storage), env)
)
}
}
}
}
private object OoParentManipulation : EntityManipulation {
override fun addManipulation(storage: WorkspaceEntityStorageBuilderImpl): AddEntity {
return object : AddEntity(storage, "OoParent") {
override fun makeEntity(source: EntitySource,
someProperty: String,
env: ImperativeCommand.Environment): Pair<WorkspaceEntity?, String> {
return storage.addOoParentEntity(someProperty, source) to "OoParent. $someProperty"
}
}
}
override fun modifyManipulation(storage: WorkspaceEntityStorageBuilderImpl): ModifyEntity<out WorkspaceEntity, out ModifiableWorkspaceEntity<out WorkspaceEntity>> {
return object : ModifyEntity<OoParentEntity, ModifiableOoParentEntity>(OoParentEntity::class, storage) {
override fun modifyEntity(env: ImperativeCommand.Environment): List<ModifiableOoParentEntity.() -> Unit> {
return listOf(modifyStringProperty(ModifiableOoParentEntity::parentProperty, env))
}
}
}
}
private object OoChildManipulation : EntityManipulation {
override fun addManipulation(storage: WorkspaceEntityStorageBuilderImpl): AddEntity {
return object : AddEntity(storage, "OoChild") {
override fun makeEntity(source: EntitySource,
someProperty: String,
env: ImperativeCommand.Environment): Pair<WorkspaceEntity?, String> {
val parentEntity = selectParent(storage, env) ?: return null to "Cannot select parent"
return storage.addOoChildEntity(parentEntity, someProperty, source) to "Selected parent: $parentEntity"
}
}
}
override fun modifyManipulation(storage: WorkspaceEntityStorageBuilderImpl): ModifyEntity<out WorkspaceEntity, out ModifiableWorkspaceEntity<out WorkspaceEntity>> {
return object : ModifyEntity<OoChildEntity, ModifiableOoChildEntity>(OoChildEntity::class, storage) {
override fun modifyEntity(env: ImperativeCommand.Environment): List<ModifiableOoChildEntity.() -> Unit> {
return listOf(modifyStringProperty(ModifiableOoChildEntity::childProperty, env))
}
}
}
private fun selectParent(storage: WorkspaceEntityStorageBuilderImpl, env: ImperativeCommand.Environment): OoParentEntity? {
val parents = storage.entities(OoParentEntity::class.java).filter { it.child == null }.toList()
if (parents.isEmpty()) return null
return env.generateValue(Generator.sampledFrom(parents), null)
}
}
private object MiddleEntityManipulation : EntityManipulation {
override fun addManipulation(storage: WorkspaceEntityStorageBuilderImpl): AddEntity {
return object : AddEntity(storage, "MiddleEntity") {
override fun makeEntity(source: EntitySource,
someProperty: String,
env: ImperativeCommand.Environment): Pair<WorkspaceEntity?, String> {
return storage.addMiddleEntity(someProperty, source) to "Property: $someProperty"
}
}
}
override fun modifyManipulation(storage: WorkspaceEntityStorageBuilderImpl): ModifyEntity<out WorkspaceEntity, out ModifiableWorkspaceEntity<out WorkspaceEntity>> {
return object : ModifyEntity<MiddleEntity, ModifiableMiddleEntity>(MiddleEntity::class, storage) {
override fun modifyEntity(env: ImperativeCommand.Environment): List<ModifiableMiddleEntity.() -> Unit> {
return listOf(modifyStringProperty(ModifiableMiddleEntity::property, env))
}
}
}
}
private object AbstractEntities {
object Left : EntityManipulation {
override fun addManipulation(storage: WorkspaceEntityStorageBuilderImpl): AddEntity {
return object : AddEntity(storage, "LeftEntity") {
override fun makeEntity(source: EntitySource,
someProperty: String,
env: ImperativeCommand.Environment): Pair<WorkspaceEntity?, String> {
val children = selectChildren(env, storage).asSequence()
return storage.addLeftEntity(children, source) to ""
}
}
}
override fun modifyManipulation(storage: WorkspaceEntityStorageBuilderImpl): ModifyEntity<out WorkspaceEntity, out ModifiableWorkspaceEntity<out WorkspaceEntity>> {
return object : ModifyEntity<LeftEntity, ModifiableLeftEntity>(LeftEntity::class, storage) {
override fun modifyEntity(env: ImperativeCommand.Environment): List<ModifiableLeftEntity.() -> Unit> {
return listOf(
swapElementsInSequence(ModifiableLeftEntity::children, env),
removeInSequence(ModifiableLeftEntity::children, env)
)
}
}
}
}
object Right : EntityManipulation {
override fun addManipulation(storage: WorkspaceEntityStorageBuilderImpl): AddEntity {
return object : AddEntity(storage, "RightEntity") {
override fun makeEntity(source: EntitySource,
someProperty: String,
env: ImperativeCommand.Environment): Pair<WorkspaceEntity?, String> {
val children = selectChildren(env, storage).asSequence()
return storage.addRightEntity(children, source) to ""
}
}
}
override fun modifyManipulation(storage: WorkspaceEntityStorageBuilderImpl): ModifyEntity<out WorkspaceEntity, out ModifiableWorkspaceEntity<out WorkspaceEntity>> {
return object : ModifyEntity<RightEntity, ModifiableRightEntity>(RightEntity::class, storage) {
override fun modifyEntity(env: ImperativeCommand.Environment): List<ModifiableRightEntity.() -> Unit> {
return listOf(
swapElementsInSequence(ModifiableRightEntity::children, env),
removeInSequence(ModifiableRightEntity::children, env)
)
}
}
}
}
private fun selectChildren(env: ImperativeCommand.Environment, storage: WorkspaceEntityStorageBuilderImpl): Set<BaseEntity> {
val children = env.generateValue(Generator.integers(0, 3), null)
val newChildren = mutableSetOf<BaseEntity>()
repeat(children) {
val possibleEntities = (storage.entities(LeftEntity::class.java) +
storage.entities(RightEntity::class.java) +
storage.entities(MiddleEntity::class.java)).toList()
if (possibleEntities.isNotEmpty()) {
val newEntity = env.generateValue(Generator.sampledFrom(possibleEntities), null)
newChildren += newEntity
}
}
return newChildren
}
}
private object ChildEntityManipulation : EntityManipulation {
override fun addManipulation(storage: WorkspaceEntityStorageBuilderImpl): AddEntity {
return object : AddEntity(storage, "Child") {
override fun makeEntity(source: EntitySource,
someProperty: String,
env: ImperativeCommand.Environment): Pair<WorkspaceEntity?, String> {
val parent = selectParent(storage, env) ?: return null to "Cannot select parent"
return storage.addChildEntity(parent, someProperty, null, source) to "Selected parent: $parent"
}
}
}
override fun modifyManipulation(storage: WorkspaceEntityStorageBuilderImpl): ModifyEntity<ChildEntity, ModifiableChildEntity> {
return object : ModifyEntity<ChildEntity, ModifiableChildEntity>(ChildEntity::class, storage) {
override fun modifyEntity(env: ImperativeCommand.Environment): List<ModifiableChildEntity.() -> Unit> {
return listOf(
modifyStringProperty(ModifiableChildEntity::childProperty, env),
modifyNotNullProperty(ModifiableChildEntity::parent, parentGenerator(storage), env)
)
}
}
}
private fun selectParent(storage: WorkspaceEntityStorageBuilderImpl, env: ImperativeCommand.Environment): ParentEntity? {
val classId = ParentEntity::class.java.toClassId()
val parentId = env.generateValue(EntityIdOfFamilyGenerator.create(storage, classId), null) ?: return null
return storage.entityDataByIdOrDie(parentId).createEntity(storage) as ParentEntity
}
}
private object ParentEntityManipulation : EntityManipulation {
override fun addManipulation(storage: WorkspaceEntityStorageBuilderImpl): AddEntity {
return object : AddEntity(storage, "Parent") {
override fun makeEntity(source: EntitySource,
someProperty: String,
env: ImperativeCommand.Environment): Pair<WorkspaceEntity?, String> {
return storage.addParentEntity(someProperty, source) to "parentProperty: $someProperty"
}
}
}
override fun modifyManipulation(storage: WorkspaceEntityStorageBuilderImpl): ModifyEntity<ParentEntity, ModifiableParentEntity> {
return object : ModifyEntity<ParentEntity, ModifiableParentEntity>(ParentEntity::class, storage) {
override fun modifyEntity(env: ImperativeCommand.Environment): List<ModifiableParentEntity.() -> Unit> {
return listOf(
modifyStringProperty(ModifiableParentEntity::parentProperty, env),
swapElementsInSequence(ModifiableParentEntity::children, env),
removeInSequence(ModifiableParentEntity::optionalChildren, env)
)
}
}
}
}
private object SampleEntityManipulation : EntityManipulation {
override fun addManipulation(storage: WorkspaceEntityStorageBuilderImpl): AddEntity {
return object : AddEntity(storage, "Sample") {
override fun makeEntity(source: EntitySource,
someProperty: String,
env: ImperativeCommand.Environment): Pair<WorkspaceEntity?, String> {
return storage.addSampleEntity(someProperty, source) to "property: $someProperty"
}
}
}
override fun modifyManipulation(storage: WorkspaceEntityStorageBuilderImpl): ModifyEntity<SampleEntity, ModifiableSampleEntity> {
return object : ModifyEntity<SampleEntity, ModifiableSampleEntity>(SampleEntity::class, storage) {
override fun modifyEntity(env: ImperativeCommand.Environment): List<ModifiableSampleEntity.() -> Unit> {
return listOf(
modifyBooleanProperty(ModifiableSampleEntity::booleanProperty, env),
modifyStringProperty(ModifiableSampleEntity::stringProperty, env),
addOrRemoveInList(ModifiableSampleEntity::stringListProperty, randomNames, env)
)
}
}
}
}
private fun <B : WorkspaceEntity, A : ModifiableWorkspaceEntity<B>, T> modifyNotNullProperty(
property: KMutableProperty1<A, T>,
takeFrom: Generator<T?>,
env: ImperativeCommand.Environment
): A.() -> Unit {
return {
val value = env.generateValue(takeFrom, null)
if (value != null) {
env.logMessage("Change `${property.name}` to $value")
property.set(this, value)
}
}
}
private fun <B : WorkspaceEntity, A : ModifiableWorkspaceEntity<B>, T> modifyNullableProperty(
property: KMutableProperty1<A, T?>,
takeFrom: Generator<T?>,
env: ImperativeCommand.Environment
): A.() -> Unit {
return {
val value = env.generateValue(takeFrom, null)
env.logMessage("Change `${property.name}` to $value")
property.set(this, value)
}
}
private fun <B : WorkspaceEntity, A : ModifiableWorkspaceEntity<B>> modifyStringProperty(property: KMutableProperty1<A, String>,
env: ImperativeCommand.Environment): A.() -> Unit {
return modifyNotNullProperty(property, randomNames, env)
}
private fun <B : WorkspaceEntity, A : ModifiableWorkspaceEntity<B>> modifyBooleanProperty(property: KMutableProperty1<A, Boolean>,
env: ImperativeCommand.Environment): A.() -> Unit {
return modifyNotNullProperty(property, Generator.booleans(), env)
}
private fun <B : WorkspaceEntity, A : ModifiableWorkspaceEntity<B>, T> addOrRemoveInList(property: KMutableProperty1<A, List<T>>,
takeFrom: Generator<T>,
env: ImperativeCommand.Environment): A.() -> Unit {
return {
val removeValue = env.generateValue(Generator.booleans(), null)
val value = property.getter.call(this)
if (removeValue) {
if (value.isNotEmpty()) {
val i = env.generateValue(Generator.integers(0, value.lastIndex), null)
env.logMessage("Remove item from ${property.name}. Index: $i, Element ${value[i]}")
property.set(this, value.toMutableList().also { it.removeAt(i) })
}
}
else {
val newElement = env.generateValue(takeFrom, "Adding new element to ${property.name}: %s")
property.set(this, value + newElement)
}
}
}
private fun <B : WorkspaceEntity, A : ModifiableWorkspaceEntity<B>, T> swapElementsInSequence(property: KMutableProperty1<A, Sequence<T>>,
env: ImperativeCommand.Environment): A.() -> Unit {
return {
val propertyList = property.getter.call(this).toMutableList()
if (propertyList.size > 2) {
val index1 = env.generateValue(Generator.integers(0, propertyList.lastIndex), null)
val index2 = env.generateValue(Generator.integers(0, propertyList.lastIndex), null)
env.logMessage(
"Change ${property.name}. Swap 2 elements: idx1: $index1, idx2: $index2, value1: ${propertyList[index1]}, value2: ${propertyList[index2]}")
property.set(this, propertyList.also { it.swap(index1, index2) }.asSequence())
}
}
}
private fun <B : WorkspaceEntity, A : ModifiableWorkspaceEntity<B>, T> removeInSequence(property: KMutableProperty1<A, Sequence<T>>,
env: ImperativeCommand.Environment): A.() -> Unit {
return {
val value = property.getter.call(this)
if (value.any()) {
val valueList = value.toMutableList()
val i = env.generateValue(Generator.integers(0, valueList.lastIndex), null)
env.logMessage("Remove item from ${property.name}. Index: $i, Element ${valueList[i]}")
valueList.removeAt(i)
property.set(this, valueList.asSequence())
}
}
}
private fun <A> MutableList<A>.swap(index1: Int, index2: Int) {
val tmp = this[index1]
this[index1] = this[index2]
this[index2] = tmp
}
| apache-2.0 | 41a84442f77f0c26e878139fb52e2fe8 | 46.635458 | 171 | 0.705307 | 5.292829 | false | false | false | false |
allotria/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/checkin/TodoCheckinHandler.kt | 1 | 9213 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.checkin
import com.intellij.CommonBundle.getCancelButtonText
import com.intellij.ide.IdeBundle
import com.intellij.ide.todo.*
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.service
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbService.isDumb
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.JBPopupMenu
import com.intellij.openapi.ui.MessageDialogBuilder.Companion.yesNo
import com.intellij.openapi.ui.MessageDialogBuilder.Companion.yesNoCancel
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.Messages.YesNoCancelResult
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsContexts.DialogMessage
import com.intellij.openapi.util.text.StringUtil.removeEllipsisSuffix
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsConfiguration
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.changes.CommitExecutor
import com.intellij.openapi.vcs.changes.ui.BooleanCommitOption
import com.intellij.openapi.vcs.ui.RefreshableOnComponent
import com.intellij.openapi.wm.ToolWindowId.TODO_VIEW
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.psi.search.TodoItem
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.labels.LinkListener
import com.intellij.util.PairConsumer
import com.intellij.util.text.DateFormatUtil.formatDateTime
import com.intellij.util.ui.JBUI.Panels.simplePanel
import com.intellij.util.ui.UIUtil.getWarningIcon
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.swing.JComponent
class TodoCheckinHandlerFactory : CheckinHandlerFactory() {
override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler = TodoCheckinHandler(panel)
}
class TodoCommitProblem(val changes: Collection<Change>, val todoItems: Collection<TodoItem>) : CommitProblem {
override val text: String get() = message("label.todo.items.found", todoItems.size)
}
class TodoCheckinHandler(private val commitPanel: CheckinProjectPanel) : CheckinHandler(), CommitCheck<TodoCommitProblem> {
private val project: Project get() = commitPanel.project
private val settings: VcsConfiguration get() = VcsConfiguration.getInstance(project)
private val todoSettings: TodoPanelSettings get() = settings.myTodoPanelSettings
private var todoFilter: TodoFilter? = null
override fun isEnabled(): Boolean = settings.CHECK_NEW_TODO
override suspend fun runCheck(indicator: ProgressIndicator): TodoCommitProblem? {
indicator.text = message("progress.text.checking.for.todo")
val changes = commitPanel.selectedChanges
val worker = TodoCheckinHandlerWorker(project, changes, todoFilter)
withContext(Dispatchers.Default) { worker.execute() }
val todoItems = worker.inOneList()
return if (todoItems.isNotEmpty()) TodoCommitProblem(changes, todoItems) else null
}
override fun showDetails(problem: TodoCommitProblem) = showTodoItems(problem.changes, problem.todoItems)
override fun getBeforeCheckinConfigurationPanel(): RefreshableOnComponent =
object : BooleanCommitOption(commitPanel, "", true, settings::CHECK_NEW_TODO) {
override fun getComponent(): JComponent {
setFilterText(todoSettings.todoFilterName)
todoSettings.todoFilterName?.let { todoFilter = TodoConfiguration.getInstance().getTodoFilter(it) }
val showFiltersPopup = LinkListener<Any> { sourceLink, _ ->
val group = SetTodoFilterAction.createPopupActionGroup(project, todoSettings) { setFilter(it) }
JBPopupMenu.showBelow(sourceLink, ActionPlaces.TODO_VIEW_TOOLBAR, group)
}
val configureFilterLink = LinkLabel(message("settings.filter.configure.link"), null, showFiltersPopup)
return simplePanel(4, 0).addToLeft(checkBox).addToCenter(configureFilterLink)
}
private fun setFilter(filter: TodoFilter?) {
todoFilter = filter
todoSettings.todoFilterName = filter?.name
setFilterText(filter?.name)
}
private fun setFilterText(filterName: String?) {
val text = if (filterName != null) message("checkin.filter.filter.name", filterName) else IdeBundle.message("action.todo.show.all")
checkBox.text = message("before.checkin.new.todo.check", text)
}
}
override fun beforeCheckin(executor: CommitExecutor?, additionalDataConsumer: PairConsumer<Any, Any>): ReturnResult {
if (!isEnabled()) return ReturnResult.COMMIT
if (isDumb(project)) return if (confirmCommitInDumbMode(project)) ReturnResult.COMMIT else ReturnResult.CANCEL
val worker = FindTodoItemsTask(project, commitPanel.selectedChanges, todoFilter).find() ?: return ReturnResult.CANCEL
val commitActionText = removeEllipsisSuffix(executor?.actionText ?: commitPanel.commitActionName)
val noTodo = worker.addedOrEditedTodos.isEmpty() && worker.inChangedTodos.isEmpty()
val noSkipped = worker.skipped.isEmpty()
return when {
noTodo && noSkipped -> ReturnResult.COMMIT
noTodo -> if (confirmCommitWithSkippedFiles(worker, commitActionText)) ReturnResult.COMMIT else ReturnResult.CANCEL
else -> processFoundTodoItems(worker, commitActionText)
}
}
private fun processFoundTodoItems(worker: TodoCheckinHandlerWorker, @NlsContexts.Button commitActionText: String): ReturnResult =
when (askReviewCommitCancel(worker, commitActionText)) {
Messages.YES -> {
showTodoItems(worker.changes, worker.inOneList())
ReturnResult.CLOSE_WINDOW
}
Messages.NO -> ReturnResult.COMMIT
else -> ReturnResult.CANCEL
}
private fun showTodoItems(changes: Collection<Change>, todoItems: Collection<TodoItem>) {
project.service<TodoView>().addCustomTodoView(
TodoTreeBuilderFactory { tree, project -> CustomChangelistTodosTreeBuilder(tree, project, changes, todoItems) },
message("checkin.title.for.commit.0", formatDateTime(System.currentTimeMillis())),
TodoPanelSettings(todoSettings)
)
runInEdt(ModalityState.NON_MODAL) {
if (project.isDisposed) return@runInEdt
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(TODO_VIEW) ?: return@runInEdt
toolWindow.show {
val lastContent = toolWindow.contentManager.contents.lastOrNull()
if (lastContent != null) toolWindow.contentManager.setSelectedContent(lastContent, true)
}
}
}
}
private class FindTodoItemsTask(project: Project, changes: Collection<Change>, todoFilter: TodoFilter?) :
Task.Modal(project, message("checkin.dialog.title.looking.for.new.edited.todo.items"), true) {
private val worker = TodoCheckinHandlerWorker(myProject, changes, todoFilter)
private var result: TodoCheckinHandlerWorker? = null
fun find(): TodoCheckinHandlerWorker? {
queue()
return result
}
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
worker.execute()
}
override fun onSuccess() {
result = worker
}
}
private fun confirmCommitInDumbMode(project: Project): Boolean =
!yesNo(message("checkin.dialog.title.not.possible.right.now"),
message("checkin.dialog.message.cant.be.performed", ApplicationNamesInfo.getInstance().fullProductName))
.icon(null)
.yesText(message("checkin.wait"))
.noText(message("checkin.commit"))
.ask(project)
private fun confirmCommitWithSkippedFiles(worker: TodoCheckinHandlerWorker, @NlsContexts.Button commitActionText: String) =
yesNo(message("checkin.dialog.title.todo"), getDescription(worker))
.icon(getWarningIcon())
.yesText(commitActionText)
.noText(getCancelButtonText())
.ask(worker.project)
@YesNoCancelResult
private fun askReviewCommitCancel(worker: TodoCheckinHandlerWorker, @NlsContexts.Button commitActionText: String): Int =
yesNoCancel(message("checkin.dialog.title.todo"), getDescription(worker))
.icon(getWarningIcon())
.yesText(message("todo.in.new.review.button"))
.noText(commitActionText)
.cancelText(getCancelButtonText())
.show(worker.project)
@DialogMessage
private fun getDescription(worker: TodoCheckinHandlerWorker): String {
val added = worker.addedOrEditedTodos.size
val changed = worker.inChangedTodos.size
val skipped = worker.skipped.size
return when {
added == 0 && changed == 0 -> message("todo.handler.only.skipped", skipped)
changed == 0 -> message("todo.handler.only.added", added, skipped)
added == 0 -> message("todo.handler.only.in.changed", changed, skipped)
else -> message("todo.handler.only.both", added, changed, skipped)
}
} | apache-2.0 | 94f47b60541d7781d64dd1d3ef0ce348 | 43.946341 | 140 | 0.772821 | 4.491955 | false | false | false | false |
zdary/intellij-community | community-guitests/testSrc/com/intellij/ide/projectWizard/kotlin/installKotlinPlugin/CreateSdksGuiTest.kt | 6 | 1733 | // 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 com.intellij.ide.projectWizard.kotlin.installKotlinPlugin
import com.intellij.ide.projectWizard.kotlin.model.KotlinGuiTestCase
import com.intellij.testGuiFramework.framework.Timeouts
import com.intellij.testGuiFramework.impl.*
import com.intellij.testGuiFramework.util.*
import org.fest.swing.exception.ComponentLookupException
import org.junit.Test
class CreateSdksGuiTest : KotlinGuiTestCase() {
private val dialogName = "Project Structure for New Projects"
@Test
fun createKotlinSdk(){
step("create a Kotlin SDK") {
welcomeFrame {
actionLink("Configure").click()
// starting from 191
popupMenu("Structure for New Projects").clickSearchedItem()
dialog(dialogName) {
jList("SDKs").clickItem("SDKs")
val kotlinSdk = "Kotlin SDK"
try {
jTree(kotlinSdk, timeout = Timeouts.noTimeout)
logInfo("'$kotlinSdk' exists")
}
catch (e: ComponentLookupException) {
step("create '$kotlinSdk' as it's absent") {
actionButton("Add New SDK").click()
popupMenu(kotlinSdk).clickSearchedItem()
step("check whether '$kotlinSdk' created") {
jTree(kotlinSdk, timeout = Timeouts.seconds05)
}
}
}
finally {
step("close `$dialogName` dialog with OK") {
button("OK").clickWhenEnabled(Timeouts.seconds05)
}
}
}
}
}
}
override fun isIdeFrameRun() = false
} | apache-2.0 | b97e829c13fe785e4d5630f87a28ab61 | 35.125 | 140 | 0.619158 | 4.854342 | false | true | false | false |
romannurik/muzei | main/src/main/java/com/google/android/apps/muzei/ChooseProviderViewModel.kt | 1 | 7903 | /*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei
import android.app.Application
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.net.Uri
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.google.android.apps.muzei.legacy.BuildConfig.LEGACY_AUTHORITY
import com.google.android.apps.muzei.legacy.LegacySourceManager
import com.google.android.apps.muzei.room.Artwork
import com.google.android.apps.muzei.room.MuzeiDatabase
import com.google.android.apps.muzei.room.getInstalledProviders
import com.google.android.apps.muzei.sync.ProviderManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.shareIn
data class ProviderInfo(
val authority: String,
val packageName: String,
val title: String,
val description: String?,
val currentArtworkUri: Uri?,
val icon: Drawable,
val setupActivity: ComponentName?,
val settingsActivity: ComponentName?,
val selected: Boolean
) {
constructor(
packageManager: PackageManager,
providerInfo: android.content.pm.ProviderInfo,
description: String? = null,
currentArtworkUri: Uri? = null,
selected: Boolean = false
) : this(
providerInfo.authority,
providerInfo.packageName,
providerInfo.loadLabel(packageManager).toString(),
description,
currentArtworkUri,
providerInfo.loadIcon(packageManager),
providerInfo.metaData?.getString("setupActivity")?.run {
ComponentName(providerInfo.packageName, this)
},
providerInfo.metaData?.getString("settingsActivity")?.run {
ComponentName(providerInfo.packageName, this)
},
selected)
}
class ChooseProviderViewModel(application: Application) : AndroidViewModel(application) {
private val database = MuzeiDatabase.getInstance(application)
val currentProvider = database.providerDao().currentProvider
.shareIn(viewModelScope, SharingStarted.WhileSubscribed(5000L), 1)
val unsupportedSources = LegacySourceManager.getInstance(application).unsupportedSources
.shareIn(viewModelScope, SharingStarted.WhileSubscribed(5000L), 1)
private val comparator = Comparator<ProviderInfo> { p1, p2 ->
// The SourceArtProvider should always the last provider listed
if (p1.authority == LEGACY_AUTHORITY) {
return@Comparator 1
} else if (p2.authority == LEGACY_AUTHORITY) {
return@Comparator -1
}
// Then put providers from Muzei on top
val pn1 = p1.packageName
val pn2 = p2.packageName
if (pn1 != pn2) {
if (application.packageName == pn1) {
return@Comparator -1
} else if (application.packageName == pn2) {
return@Comparator 1
}
}
// Finally, sort providers by their title
p1.title.compareTo(p2.title)
}
/**
* The set of installed providers, transformed into a list of [ProviderInfo] objects
*/
private val installedProviders = getInstalledProviders(application).map { providerInfos ->
val packageManager = application.packageManager
providerInfos.map { providerInfo ->
ProviderInfo(packageManager, providerInfo)
}
}
/**
* The authority of the current MuzeiArtProvider
*/
private val currentProviderAuthority = database.providerDao().currentProvider.map { provider ->
provider?.authority
}
/**
* An authority to current artwork URI map
*/
private val currentArtworkByProvider = database.artworkDao().currentArtworkByProvider.map { artworkForProvider ->
val artworkMap = mutableMapOf<String, Artwork>()
artworkForProvider.forEach { artwork ->
artworkMap[artwork.providerAuthority] = artwork
}
artworkMap
}
/**
* An authority to description map used to avoid querying each
* MuzeiArtProvider every time.
*/
private val descriptions = mutableMapOf<String, String>()
/**
* MutableStateFlow that should be updated with the current nano time
* when the descriptions are invalidated.
*/
private val descriptionInvalidationNanoTime = MutableStateFlow(0L)
/**
* Combine all of the separate signals we have into one final set of [ProviderInfo]:
* - The set of installed providers
* - the currently selected provider
* - the current artwork for each provider
* - the input signal for when the descriptions have been invalidated (we don't
* care about the value, but we do want to recompute the [ProviderInfo] values)
*/
val providers = combine(
installedProviders,
currentProviderAuthority,
currentArtworkByProvider,
descriptionInvalidationNanoTime
) { installedProviders, providerAuthority, artworkForProvider, _ ->
installedProviders.map { providerInfo ->
val authority = providerInfo.authority
val selected = authority == providerAuthority
val description = descriptions[authority] ?: run {
// Populate the description if we don't already have one
val newDescription = ProviderManager.getDescription(application, authority)
descriptions[authority] = newDescription
newDescription
}
val currentArtwork = artworkForProvider[authority]
providerInfo.copy(
selected = selected,
description = description,
currentArtworkUri = currentArtwork?.imageUri
)
}.sortedWith(comparator)
}.shareIn(viewModelScope, SharingStarted.WhileSubscribed(5000L), 1)
internal fun refreshDescription(authority: String) {
// Remove the current description and trigger the invalidation
// to recompute the description
descriptions.remove(authority)
descriptionInvalidationNanoTime.value = System.nanoTime()
}
private val localeChangeReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
// Our cached descriptions need to be invalidated when the locale changes
// so that we re-query for descriptions in the new language
descriptions.clear()
descriptionInvalidationNanoTime.value = System.nanoTime()
}
}
init {
application.registerReceiver(localeChangeReceiver, IntentFilter().apply {
addAction(Intent.ACTION_LOCALE_CHANGED)
})
}
override fun onCleared() {
super.onCleared()
getApplication<Application>().unregisterReceiver(localeChangeReceiver)
}
} | apache-2.0 | fd3979f292429e7c69e45817135c4160 | 37.935961 | 117 | 0.673921 | 5.311156 | false | false | false | false |
leafclick/intellij-community | platform/built-in-server/testSrc/org/jetbrains/ide/BuiltInServerTestCase.kt | 1 | 2408 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.ide
import com.intellij.testFramework.DisposeModulesRule
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.RuleChain
import com.intellij.testFramework.TemporaryDirectory
import io.netty.handler.codec.http.HttpResponseStatus
import org.assertj.core.api.Assertions.assertThat
import org.junit.BeforeClass
import org.junit.ClassRule
import org.junit.Rule
import org.junit.rules.Timeout
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.TimeUnit
internal abstract class BuiltInServerTestCase {
companion object {
@JvmField
@ClassRule
val projectRule = ProjectRule()
@BeforeClass
@JvmStatic
fun runServer() {
BuiltInServerManager.getInstance().waitForStart()
}
}
protected val tempDirManager = TemporaryDirectory()
protected val manager = TestManager(projectRule, tempDirManager)
@Rule
@JvmField
val ruleChain = RuleChain(
tempDirManager,
Timeout(60, TimeUnit.SECONDS),
manager,
DisposeModulesRule(projectRule)
)
protected open val urlPathPrefix = ""
protected fun doTest(filePath: String? = manager.filePath, additionalCheck: ((connection: HttpURLConnection) -> Unit)? = null) {
val serviceUrl = "http://localhost:${BuiltInServerManager.getInstance().port}$urlPathPrefix"
var url = serviceUrl + (if (filePath == null) "" else ("/$filePath"))
val line = manager.annotation?.line ?: -1
if (line != -1) {
url += ":$line"
}
val column = manager.annotation?.column ?: -1
if (column != -1) {
url += ":$column"
}
val expectedStatus = HttpResponseStatus.valueOf(manager.annotation?.status ?: 200)
val connection = testUrl(url, expectedStatus)
check(serviceUrl, expectedStatus)
additionalCheck?.invoke(connection)
}
protected open fun check(serviceUrl: String, expectedStatus: HttpResponseStatus) {
}
}
internal fun testUrl(url: String, expectedStatus: HttpResponseStatus): HttpURLConnection {
val connection = URL(url).openConnection() as HttpURLConnection
BuiltInServerManager.getInstance().configureRequestToWebServer(connection)
assertThat(HttpResponseStatus.valueOf(connection.responseCode)).isEqualTo(expectedStatus)
return connection
} | apache-2.0 | 516b6f20ee68f3cc3f3ffcf39048df77 | 32.458333 | 140 | 0.750831 | 4.721569 | false | true | false | false |
mtransitapps/mtransit-for-android | src/main/java/org/mtransit/android/ui/pref/PreferencesViewModel.kt | 1 | 827 | package org.mtransit.android.ui.pref
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import org.mtransit.android.commons.MTLog
import org.mtransit.android.ui.view.common.getLiveDataDistinct
import javax.inject.Inject
@HiltViewModel
class PreferencesViewModel @Inject constructor(
private val savedStateHandle: SavedStateHandle,
) : ViewModel(), MTLog.Loggable {
companion object {
private val LOG_TAG = PreferencesViewModel::class.java.simpleName
internal const val EXTRA_SUPPORT = "extra_support"
}
override fun getLogTag(): String = LOG_TAG
val showSupport = savedStateHandle.getLiveDataDistinct(EXTRA_SUPPORT, false)
fun onSupportShown() {
savedStateHandle[EXTRA_SUPPORT] = false
}
} | apache-2.0 | dde478a4185d6938b72d19a63310304f | 28.571429 | 80 | 0.771463 | 4.569061 | false | false | false | false |
JuliusKunze/kotlin-native | samples/csvparser/src/main/kotlin/CsvParser.kt | 1 | 2284 | /*
* 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.
*/
import kotlinx.cinterop.*
import platform.posix.*
fun parseLine(line: String, separator: Char) : List<String> {
val result = mutableListOf<String>()
val builder = StringBuilder()
var quotes = 0
for (ch in line) {
when {
ch == '\"' -> {
quotes++
builder.append(ch)
}
(ch == '\n') || (ch == '\r') -> {}
(ch == separator) && (quotes % 2 == 0) -> {
result.add(builder.toString())
builder.length = 0
}
else -> builder.append(ch)
}
}
return result
}
fun main(args: Array<String>) {
if (args.size != 3) {
println("usage: csvparser.kexe file.csv column count")
return
}
val fileName = args[0]
val column = args[1].toInt()
val count = args[2].toInt()
val file = fopen(fileName, "r")
if (file == null) {
perror("cannot open input file $fileName")
return
}
val keyValue = mutableMapOf<String, Int>()
try {
memScoped {
val bufferLength = 64 * 1024
val buffer = allocArray<ByteVar>(bufferLength)
for (i in 1..count) {
val nextLine = fgets(buffer, bufferLength, file)?.toKString()
if (nextLine == null || nextLine.isEmpty()) break
val records = parseLine(nextLine, ',')
val key = records[column]
val current = keyValue[key] ?: 0
keyValue[key] = current + 1
}
}
} finally {
fclose(file)
}
keyValue.forEach {
println("${it.key} -> ${it.value}")
}
}
| apache-2.0 | 0c88c6aa38574f8e6476212c187b0b97 | 27.55 | 77 | 0.552539 | 4.167883 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/vararg/kt581.kt | 2 | 475 | package whats.the.difference
fun iarray(vararg a : Int) = a // BUG
val IntArray.indices: IntRange get() = IntRange(0, lastIndex())
fun IntArray.lastIndex() = size - 1
fun box() : String {
val vals = iarray(789, 678, 567, 456, 345, 234, 123, 12)
val diffs = HashSet<Int>()
for (i in vals.indices)
for (j in i..vals.lastIndex())
diffs.add(vals[i] - vals[j])
val size = diffs.size
if (size != 8) return "Fail $size"
return "OK"
}
| apache-2.0 | 75b59f639a3ffadf567c597b2e63757e | 26.941176 | 63 | 0.602105 | 3.166667 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/pull/GitPullOption.kt | 12 | 1454 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.pull
import com.intellij.openapi.util.NlsSafe
import git4idea.i18n.GitBundle
import org.jetbrains.annotations.Nls
enum class GitPullOption(@NlsSafe val option: String,
@Nls val description: String) {
REBASE("--rebase", GitBundle.message("pull.option.rebase")),
FF_ONLY("--ff-only", GitBundle.message("pull.option.ff.only")),
NO_FF("--no-ff", GitBundle.message("pull.option.no.ff")),
SQUASH("--squash", GitBundle.message("pull.option.squash.commit")),
NO_COMMIT("--no-commit", GitBundle.message("pull.option.no.commit")),
NO_VERIFY("--no-verify", GitBundle.message("merge.option.no.verify"));
fun isOptionSuitable(option: GitPullOption): Boolean {
return when (this) {
REBASE -> option !in REBASE_INCOMPATIBLE
FF_ONLY -> option !in FF_ONLY_INCOMPATIBLE
NO_FF -> option !in NO_FF_INCOMPATIBLE
SQUASH -> option !in SQUASH_COMMIT_INCOMPATIBLE
NO_COMMIT -> option != REBASE
else -> true
}
}
companion object {
private val REBASE_INCOMPATIBLE = listOf(FF_ONLY, NO_FF, SQUASH, NO_COMMIT)
private val FF_ONLY_INCOMPATIBLE = listOf(NO_FF, SQUASH, REBASE)
private val NO_FF_INCOMPATIBLE = listOf(FF_ONLY, SQUASH, REBASE)
private val SQUASH_COMMIT_INCOMPATIBLE = listOf(NO_FF, FF_ONLY, REBASE)
}
} | apache-2.0 | 6a19e882c2b3379a18873a47cfe9edbc | 40.571429 | 140 | 0.695323 | 3.806283 | false | false | false | false |
android/compose-samples | Jetsnack/app/src/main/java/com/example/jetsnack/ui/home/Home.kt | 1 | 13314 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetsnack.ui.home
import androidx.annotation.FloatRange
import androidx.annotation.StringRes
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.SpringSpec
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.AccountCircle
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material.icons.outlined.ShoppingCart
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.layout.Placeable
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.lerp
import androidx.core.os.ConfigurationCompat
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import com.example.jetsnack.R
import com.example.jetsnack.ui.components.JetsnackSurface
import com.example.jetsnack.ui.home.cart.Cart
import com.example.jetsnack.ui.home.search.Search
import com.example.jetsnack.ui.theme.JetsnackTheme
import java.util.Locale
fun NavGraphBuilder.addHomeGraph(
onSnackSelected: (Long, NavBackStackEntry) -> Unit,
modifier: Modifier = Modifier
) {
composable(HomeSections.FEED.route) { from ->
Feed(onSnackClick = { id -> onSnackSelected(id, from) }, modifier)
}
composable(HomeSections.SEARCH.route) { from ->
Search(onSnackClick = { id -> onSnackSelected(id, from) }, modifier)
}
composable(HomeSections.CART.route) { from ->
Cart(onSnackClick = { id -> onSnackSelected(id, from) }, modifier)
}
composable(HomeSections.PROFILE.route) {
Profile(modifier)
}
}
enum class HomeSections(
@StringRes val title: Int,
val icon: ImageVector,
val route: String
) {
FEED(R.string.home_feed, Icons.Outlined.Home, "home/feed"),
SEARCH(R.string.home_search, Icons.Outlined.Search, "home/search"),
CART(R.string.home_cart, Icons.Outlined.ShoppingCart, "home/cart"),
PROFILE(R.string.home_profile, Icons.Outlined.AccountCircle, "home/profile")
}
@Composable
fun JetsnackBottomBar(
tabs: Array<HomeSections>,
currentRoute: String,
navigateToRoute: (String) -> Unit,
color: Color = JetsnackTheme.colors.iconPrimary,
contentColor: Color = JetsnackTheme.colors.iconInteractive
) {
val routes = remember { tabs.map { it.route } }
val currentSection = tabs.first { it.route == currentRoute }
JetsnackSurface(
color = color,
contentColor = contentColor
) {
val springSpec = SpringSpec<Float>(
// Determined experimentally
stiffness = 800f,
dampingRatio = 0.8f
)
JetsnackBottomNavLayout(
selectedIndex = currentSection.ordinal,
itemCount = routes.size,
indicator = { JetsnackBottomNavIndicator() },
animSpec = springSpec,
modifier = Modifier.navigationBarsPadding()
) {
val configuration = LocalConfiguration.current
val currentLocale: Locale =
ConfigurationCompat.getLocales(configuration).get(0) ?: Locale.getDefault()
tabs.forEach { section ->
val selected = section == currentSection
val tint by animateColorAsState(
if (selected) {
JetsnackTheme.colors.iconInteractive
} else {
JetsnackTheme.colors.iconInteractiveInactive
}
)
val text = stringResource(section.title).uppercase(currentLocale)
JetsnackBottomNavigationItem(
icon = {
Icon(
imageVector = section.icon,
tint = tint,
contentDescription = text
)
},
text = {
Text(
text = text,
color = tint,
style = MaterialTheme.typography.button,
maxLines = 1
)
},
selected = selected,
onSelected = { navigateToRoute(section.route) },
animSpec = springSpec,
modifier = BottomNavigationItemPadding
.clip(BottomNavIndicatorShape)
)
}
}
}
}
@Composable
private fun JetsnackBottomNavLayout(
selectedIndex: Int,
itemCount: Int,
animSpec: AnimationSpec<Float>,
indicator: @Composable BoxScope.() -> Unit,
modifier: Modifier = Modifier,
content: @Composable () -> Unit
) {
// Track how "selected" each item is [0, 1]
val selectionFractions = remember(itemCount) {
List(itemCount) { i ->
Animatable(if (i == selectedIndex) 1f else 0f)
}
}
selectionFractions.forEachIndexed { index, selectionFraction ->
val target = if (index == selectedIndex) 1f else 0f
LaunchedEffect(target, animSpec) {
selectionFraction.animateTo(target, animSpec)
}
}
// Animate the position of the indicator
val indicatorIndex = remember { Animatable(0f) }
val targetIndicatorIndex = selectedIndex.toFloat()
LaunchedEffect(targetIndicatorIndex) {
indicatorIndex.animateTo(targetIndicatorIndex, animSpec)
}
Layout(
modifier = modifier.height(BottomNavHeight),
content = {
content()
Box(Modifier.layoutId("indicator"), content = indicator)
}
) { measurables, constraints ->
check(itemCount == (measurables.size - 1)) // account for indicator
// Divide the width into n+1 slots and give the selected item 2 slots
val unselectedWidth = constraints.maxWidth / (itemCount + 1)
val selectedWidth = 2 * unselectedWidth
val indicatorMeasurable = measurables.first { it.layoutId == "indicator" }
val itemPlaceables = measurables
.filterNot { it == indicatorMeasurable }
.mapIndexed { index, measurable ->
// Animate item's width based upon the selection amount
val width = lerp(unselectedWidth, selectedWidth, selectionFractions[index].value)
measurable.measure(
constraints.copy(
minWidth = width,
maxWidth = width
)
)
}
val indicatorPlaceable = indicatorMeasurable.measure(
constraints.copy(
minWidth = selectedWidth,
maxWidth = selectedWidth
)
)
layout(
width = constraints.maxWidth,
height = itemPlaceables.maxByOrNull { it.height }?.height ?: 0
) {
val indicatorLeft = indicatorIndex.value * unselectedWidth
indicatorPlaceable.placeRelative(x = indicatorLeft.toInt(), y = 0)
var x = 0
itemPlaceables.forEach { placeable ->
placeable.placeRelative(x = x, y = 0)
x += placeable.width
}
}
}
}
@Composable
fun JetsnackBottomNavigationItem(
icon: @Composable BoxScope.() -> Unit,
text: @Composable BoxScope.() -> Unit,
selected: Boolean,
onSelected: () -> Unit,
animSpec: AnimationSpec<Float>,
modifier: Modifier = Modifier
) {
Box(
modifier = modifier.selectable(selected = selected, onClick = onSelected),
contentAlignment = Alignment.Center
) {
// Animate the icon/text positions within the item based on selection
val animationProgress by animateFloatAsState(if (selected) 1f else 0f, animSpec)
JetsnackBottomNavItemLayout(
icon = icon,
text = text,
animationProgress = animationProgress
)
}
}
@Composable
private fun JetsnackBottomNavItemLayout(
icon: @Composable BoxScope.() -> Unit,
text: @Composable BoxScope.() -> Unit,
@FloatRange(from = 0.0, to = 1.0) animationProgress: Float
) {
Layout(
content = {
Box(
modifier = Modifier
.layoutId("icon")
.padding(horizontal = TextIconSpacing),
content = icon
)
val scale = lerp(0.6f, 1f, animationProgress)
Box(
modifier = Modifier
.layoutId("text")
.padding(horizontal = TextIconSpacing)
.graphicsLayer {
alpha = animationProgress
scaleX = scale
scaleY = scale
transformOrigin = BottomNavLabelTransformOrigin
},
content = text
)
}
) { measurables, constraints ->
val iconPlaceable = measurables.first { it.layoutId == "icon" }.measure(constraints)
val textPlaceable = measurables.first { it.layoutId == "text" }.measure(constraints)
placeTextAndIcon(
textPlaceable,
iconPlaceable,
constraints.maxWidth,
constraints.maxHeight,
animationProgress
)
}
}
private fun MeasureScope.placeTextAndIcon(
textPlaceable: Placeable,
iconPlaceable: Placeable,
width: Int,
height: Int,
@FloatRange(from = 0.0, to = 1.0) animationProgress: Float
): MeasureResult {
val iconY = (height - iconPlaceable.height) / 2
val textY = (height - textPlaceable.height) / 2
val textWidth = textPlaceable.width * animationProgress
val iconX = (width - textWidth - iconPlaceable.width) / 2
val textX = iconX + iconPlaceable.width
return layout(width, height) {
iconPlaceable.placeRelative(iconX.toInt(), iconY)
if (animationProgress != 0f) {
textPlaceable.placeRelative(textX.toInt(), textY)
}
}
}
@Composable
private fun JetsnackBottomNavIndicator(
strokeWidth: Dp = 2.dp,
color: Color = JetsnackTheme.colors.iconInteractive,
shape: Shape = BottomNavIndicatorShape
) {
Spacer(
modifier = Modifier
.fillMaxSize()
.then(BottomNavigationItemPadding)
.border(strokeWidth, color, shape)
)
}
private val TextIconSpacing = 2.dp
private val BottomNavHeight = 56.dp
private val BottomNavLabelTransformOrigin = TransformOrigin(0f, 0.5f)
private val BottomNavIndicatorShape = RoundedCornerShape(percent = 50)
private val BottomNavigationItemPadding = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
@Preview
@Composable
private fun JetsnackBottomNavPreview() {
JetsnackTheme {
JetsnackBottomBar(
tabs = HomeSections.values(),
currentRoute = "home/feed",
navigateToRoute = { }
)
}
}
| apache-2.0 | 8ae9707c1795e1536c728c40d39c8292 | 34.886792 | 97 | 0.644209 | 4.811709 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/scene/animation/Animator.kt | 1 | 5948 | package de.fabmax.kool.scene.animation
import de.fabmax.kool.KoolContext
import de.fabmax.kool.math.clamp
import de.fabmax.kool.math.isFuzzyZero
import de.fabmax.kool.util.MutableColor
import de.fabmax.kool.util.Time
import kotlin.math.*
/**
* @author fabmax
*/
abstract class Animator<V, out T: InterpolatedValue<V>>(val value: T) {
companion object {
val ONCE = 1
val REPEAT = 2
val REPEAT_TOGGLE_DIR = 3
}
var duration = 1f
var speed = 1f
var repeating = ONCE
var progress = 0f
open fun tick(ctx: KoolContext): V {
if (!speed.isFuzzyZero()) {
progress += Time.deltaT * speed / duration
if (progress >= 1f && speed > 0) {
when (repeating) {
ONCE -> {
// animation is done
progress = 1f
speed = 0f
}
REPEAT -> {
// repeat animation from beginning
progress = 0f
}
REPEAT_TOGGLE_DIR -> {
// invert speed to play animation backwards
progress = 1f
speed = -speed
}
}
} else if (progress <= 0f && speed < 0) {
when (repeating) {
ONCE -> {
// animation is done
progress = 0f
speed = 0f
}
REPEAT -> {
// repeat animation from end
progress = 1f
}
REPEAT_TOGGLE_DIR -> {
// invert speed to play animation backwards
progress = 0f
speed = -speed
}
}
}
progress = progress.clamp(0f, 1f)
value.interpolate(interpolate(progress))
}
return value.value
}
protected abstract fun interpolate(progress: Float): Float
}
class LinearAnimator<V, out T: InterpolatedValue<V>>(value: T) : Animator<V, T>(value) {
override fun interpolate(progress: Float): Float {
return progress
}
}
class SquareAnimator<V, out T: InterpolatedValue<V>>(value: T) : Animator<V, T>(value) {
override fun interpolate(progress: Float): Float {
return progress * progress
}
}
class InverseSquareAnimator<V, out T: InterpolatedValue<V>>(value: T) : Animator<V, T>(value) {
override fun interpolate(progress: Float): Float {
return 1f - (1f - progress) * (1f - progress)
}
}
class CosAnimator<V, out T: InterpolatedValue<V>>(value: T) : Animator<V, T>(value) {
override fun interpolate(progress: Float): Float {
return 0.5f - cos(progress * PI).toFloat() * 0.5f
}
}
abstract class InterpolatedValue<T>(initial: T) {
var value = initial
var onUpdate: ((T) -> Unit)? = null
open fun interpolate(progress: Float) {
updateValue(progress)
onUpdate?.invoke(value)
}
protected abstract fun updateValue(interpolationPos: Float)
}
class InterpolatedFloat(var from: Float, var to: Float) : InterpolatedValue<Float>(from) {
override fun updateValue(interpolationPos: Float) {
value = from + (to - from) * interpolationPos
}
}
class InterpolatedColor(var from: MutableColor, var to: MutableColor) : InterpolatedValue<MutableColor>(MutableColor()) {
init {
value.set(from)
}
override fun updateValue(interpolationPos: Float) {
value.set(to).subtract(from).scale(interpolationPos).add(from)
}
}
class SpringDamperFloat(value: Float) {
var desired = value
var actual = value
var speed = 0f
private set
private var damping = 0f
var stiffness = 0f
set(value) {
field = value
damping = 2f * sqrt(stiffness.toDouble()).toFloat()
}
init {
stiffness = 100f
}
fun set(value: Float) {
desired = value
actual = value
speed = 0f
}
fun animate(deltaT: Float): Float {
if (stiffness == 0f || deltaT > 0.2f) {
// don't care about smoothing on low frame rates
actual = desired
return actual
}
var t = 0f
while (t < deltaT) {
val dt = min(0.05f, (deltaT - t))
t += dt + 0.001f
val err = desired - actual
speed += (err * stiffness - speed * damping) * dt
val delta = speed * dt
if (!abs(delta).isFuzzyZero()) {
actual += delta
} else {
actual = desired
}
}
return actual
}
}
class SpringDamperDouble(value: Double) {
var desired = value
var actual = value
var speed = 0.0
private set
private var damping = 0.0
var stiffness = 0.0
set(value) {
field = value
damping = 2.0 * sqrt(stiffness)
}
init {
stiffness = 100.0
}
fun set(value: Double) {
desired = value
actual = value
speed = 0.0
}
fun animate(deltaT: Float): Double {
if (stiffness == 0.0 || deltaT > 0.2f) {
// don't care about smoothing on low frame rates
actual = desired
return actual
}
var t = 0.0
while (t < deltaT) {
val dt = min(0.05, (deltaT - t))
t += dt + 0.001
val err = desired - actual
speed += (err * stiffness - speed * damping) * dt
val delta = speed * dt
if (!abs(delta).isFuzzyZero()) {
actual += delta
} else {
actual = desired
}
}
return actual
}
} | apache-2.0 | 85926ac9c8e17985056dafc9e3c6bdef | 25.797297 | 121 | 0.504203 | 4.379971 | false | false | false | false |
webscene/webscene-client | src/main/kotlin/org/webscene/client/html/bootstrap/Row.kt | 1 | 1530 | package org.webscene.client.html.bootstrap
import org.w3c.dom.Element
import org.webscene.client.html.element.ParentHtmlElement
import kotlin.browser.document
import kotlin.dom.addClass
import kotlin.dom.createElement
/**
* Bootstrap Row element.
* @author Nick Apperley
* @see org.webscene.client.html.element.ParentHtmlElement
*/
class Row : ParentHtmlElement() {
@Suppress("RedundantSetter")
override var tagName
get() = "div"
set(value) {}
/**
* Creates a new [column][Column] in [Row] that can contain HTML elements.
* @param colSizes One or more column sizes to use for sizing the column.
* @param block Initialisation block for setting up the column.
* @return A new [Column].
*/
@Suppress("unused")
fun column(vararg colSizes: Pair<ColumnSize, Int>, block: Column.() -> Unit): Column {
val colElement = Column()
colSizes.forEach { colElement.colSizes[it.first] = it.second }
children.add(colElement)
colElement.block()
return colElement
}
override fun toDomElement(): Element {
val tmpId = id
val tmpAttributes = attributes
val tmpChildren = children
return document.createElement(tagName) {
addClass("row", *classes.toTypedArray())
tmpAttributes.forEach { (key, value) -> setAttribute(key, value) }
id = tmpId
tmpChildren.forEach { child ->
appendChild(child.toDomElement())
}
}
}
} | apache-2.0 | 5243ff542125963e7c767534c2d2c092 | 29.62 | 90 | 0.641176 | 4.25 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/gui/rcomponents/popup/EditTexture.kt | 1 | 7250 | package com.cout970.modeler.gui.rcomponents.popup
import com.cout970.modeler.api.model.material.IMaterial
import com.cout970.modeler.core.config.colorOf
import com.cout970.modeler.core.config.colorToHex
import com.cout970.modeler.core.model.material.ColoredMaterial
import com.cout970.modeler.core.model.material.MaterialNone
import com.cout970.modeler.core.model.material.TexturedMaterial
import com.cout970.modeler.core.resource.ResourcePath
import com.cout970.modeler.gui.GuiState
import com.cout970.modeler.gui.leguicomp.*
import com.cout970.modeler.input.dialogs.FileDialogs
import com.cout970.modeler.util.toIVector
import com.cout970.modeler.util.toResourcePath
import com.cout970.modeler.util.toVector3
import com.cout970.reactive.core.RBuilder
import com.cout970.reactive.core.RComponent
import com.cout970.reactive.core.RProps
import com.cout970.reactive.core.RState
import com.cout970.reactive.dsl.*
import com.cout970.reactive.nodes.DivBuilder
import com.cout970.reactive.nodes.comp
import com.cout970.reactive.nodes.div
import com.cout970.reactive.nodes.style
import com.cout970.vector.api.IVector3
import org.liquidengine.legui.component.TextInput
import org.liquidengine.legui.component.event.textinput.TextInputContentChangeEvent
import org.liquidengine.legui.component.optional.align.HorizontalAlign
import org.liquidengine.legui.style.color.ColorConstants
import java.io.File
import java.net.URI
data class EditTextureProps(val returnFunc: (Any?) -> Unit, val guiState: GuiState, val metadata: Map<String, Any>) : RProps
data class EditTextureState(
var textureName: String? = null,
val texturePath: ResourcePath? = null,
val color: IVector3? = null
) : RState
class EditTexture : RComponent<EditTextureProps, EditTextureState>() {
inline val material: IMaterial get() = props.metadata["material"] as IMaterial
override fun getInitialState() = EditTextureState()
override fun RBuilder.render() = div("EditTexture") {
style {
width = 460f
height = 170f
classes("popup_back")
}
postMount {
center()
}
val material = material
// first line
+FixedLabel("Config Material", 0f, 8f, 460f, 24f).apply {
style.fontSize = 22f
}
//second line
+FixedLabel("Name", 25f, 50f, 400f, 24f).apply {
style.fontSize = 20f
style.horizontalAlign = HorizontalAlign.LEFT
}
comp(TextInput(state.textureName ?: material.name, 90f, 50f, 250f, 24f)) {
style {
horizontalAlign = HorizontalAlign.LEFT
fontSize(20f)
if (material is MaterialNone) {
isEditable = false
isEnabled = false
style.background.color = ColorConstants.black()
focusedStyle.background.color = style.background.color
pressedStyle.background.color = style.background.color
hoveredStyle.background.color = style.background.color
}
}
on<TextInputContentChangeEvent<TextInput>> {
state.textureName = it.newValue
}
}
//third line
if (material is TexturedMaterial) {
texturedMaterial(material)
} else if (material is ColoredMaterial) {
coloredMaterial(material)
}
//fifth line
+TextButton("", "Accept", 270f, 130f, 80f, 24f).apply {
onClick {
if (state.textureName == null && state.texturePath == null && state.color == null) {
props.returnFunc(null)
} else {
when (material) {
is TexturedMaterial -> {
val newMaterial = material.copy(
name = state.textureName ?: material.name,
path = state.texturePath ?: material.path
)
props.returnFunc(newMaterial)
}
is ColoredMaterial -> {
val newMaterial = material.copy(
name = state.textureName ?: material.name,
color = state.color ?: material.color
)
props.returnFunc(newMaterial)
}
else -> props.returnFunc(null)
}
}
}
}
+TextButton("", "Cancel", 360f, 130f, 80f, 24f).apply {
onClick {
props.returnFunc(null)
}
}
}
fun DivBuilder.coloredMaterial(material: ColoredMaterial) {
+FixedLabel("Color", 25f, 90f, 400f, 24f).apply {
style.fontSize = 20f
style.horizontalAlign = HorizontalAlign.LEFT
}
val color = state.color ?: material.color
comp(TextInput(colorToHex(color), 90f, 90f, 250f, 24f)) {
on<TextInputContentChangeEvent<TextInput>> {
if (it.newValue.length == 6) {
val newColor = colorOf(it.newValue).toIVector().toVector3()
if (newColor != color) {
setState { copy(color = newColor) }
}
}
}
}
div {
style {
posX = 360f
posY = 90f
sizeX = 80f
sizeY = 24f
style.background.setColor(color.xf, color.yf, color.zf, 1.0f)
}
}
}
fun DivBuilder.texturedMaterial(material: TexturedMaterial) {
+FixedLabel("Path", 25f, 90f, 400f, 24f).apply {
style.fontSize = 20f
style.horizontalAlign = HorizontalAlign.LEFT
}
val path = state.texturePath ?: material.path
comp(TextInput(path.toString(), 90f, 90f, 250f, 24f)) {
on<TextInputContentChangeEvent<TextInput>> {
try {
val newPath = ResourcePath(URI.create(it.newValue))
if (newPath != path) {
setState { copy(texturePath = newPath) }
}
} catch (e: Exception) {
val newPath = File(it.newValue).toResourcePath()
if (newPath != path) {
setState { copy(texturePath = newPath) }
}
}
}
}
comp(TextButton("", "Select", 360f, 90f, 80f, 24f)) {
onRelease {
val file = FileDialogs.openFile(
title = "Load Texture",
description = "PNG texture (*.png)",
filters = listOf("*.png")
)
if (file != null) {
val newPath = File(file).toResourcePath()
if (newPath != path) {
setState { copy(texturePath = newPath) }
}
}
}
}
}
} | gpl-3.0 | 7eed2f82a5c3fb75932a2ccdd3e10155 | 35.074627 | 124 | 0.54331 | 4.695596 | false | false | false | false |
Flank/flank | test_runner/src/main/kotlin/ftl/environment/ios/IosSoftwareVersionDescription.kt | 1 | 1194 | package ftl.environment.ios
import com.google.testing.model.IosVersion
import ftl.run.exception.FlankGeneralError
fun List<IosVersion>.getDescription(versionId: String) = findVersion(versionId)?.prepareDescription().orErrorMessage(versionId)
private fun List<IosVersion>.findVersion(versionId: String) = firstOrNull { it.id == versionId }
private fun IosVersion.prepareDescription() = """
id: '$id'
majorVersion: $majorVersion
minorVersion: $minorVersion
""".trimIndent().addDataIfExists(SUPPORTED_VERSIONS_HEADER, supportedXcodeVersionIds).addDataIfExists(TAGS_HEADER, tags)
private fun String.addDataIfExists(header: String, data: List<String?>?) =
if (!data.isNullOrEmpty()) StringBuilder(this).appendLine("\n$header:").appendDataToList(data)
else this
private fun StringBuilder.appendDataToList(data: List<String?>) = apply {
data.filterNotNull().forEach { item -> appendLine("- $item") }
}.toString().trim()
private fun String?.orErrorMessage(versionId: String) = this ?: throw FlankGeneralError("ERROR: '$versionId' is not a valid OS version")
private const val TAGS_HEADER = "tags"
private const val SUPPORTED_VERSIONS_HEADER = "supportedXcodeVersionIds"
| apache-2.0 | b467388f5381c91c57debabd43107c74 | 43.222222 | 136 | 0.768007 | 4.264286 | false | false | false | false |
siosio/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHSubmittableTextFieldFactory.kt | 2 | 1865 | // 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 org.jetbrains.plugins.github.pullrequest.comment.ui
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.util.NlsActions
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.collaboration.ui.codereview.timeline.comment.SubmittableTextField
import com.intellij.collaboration.ui.codereview.timeline.comment.SubmittableTextField.Companion.getEditorTextFieldVerticalOffset
import com.intellij.collaboration.ui.codereview.timeline.comment.SubmittableTextFieldModel
import org.jetbrains.plugins.github.api.data.GHUser
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider
import javax.swing.JComponent
class GHSubmittableTextFieldFactory(private val model: SubmittableTextFieldModel) {
fun create(
@NlsActions.ActionText actionName: String = GithubBundle.message("action.comment.text"),
onCancel: (() -> Unit)? = null
): JComponent = SubmittableTextField(actionName, model, onCancel = onCancel)
fun create(
avatarIconsProvider: GHAvatarIconsProvider, author: GHUser,
@NlsActions.ActionText actionName: String = GithubBundle.message("action.comment.text"),
onCancel: (() -> Unit)? = null
): JComponent {
val authorLabel = LinkLabel.create("") {
BrowserUtil.browse(author.url)
}.apply {
icon = avatarIconsProvider.getIcon(author.avatarUrl)
isFocusable = true
border = JBUI.Borders.empty(getEditorTextFieldVerticalOffset() - 2, 0)
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
}
return SubmittableTextField(actionName, model, authorLabel, onCancel)
}
}
| apache-2.0 | 706e98cfdae7f3ab37a61757a5f80584 | 45.625 | 140 | 0.78874 | 4.483173 | false | false | false | false |
yschimke/okhttp | okhttp-sse/src/main/kotlin/okhttp3/sse/internal/RealEventSource.kt | 2 | 3441 | /*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.sse.internal
import java.io.IOException
import okhttp3.Call
import okhttp3.Callback
import okhttp3.EventListener
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.internal.EMPTY_RESPONSE
import okhttp3.internal.connection.RealCall
import okhttp3.sse.EventSource
import okhttp3.sse.EventSourceListener
internal class RealEventSource(
private val request: Request,
private val listener: EventSourceListener
) : EventSource, ServerSentEventReader.Callback, Callback {
private var call: RealCall? = null
@Volatile private var canceled = false
fun connect(client: OkHttpClient) {
val client = client.newBuilder()
.eventListener(EventListener.NONE)
.build()
val realCall = client.newCall(request) as RealCall
call = realCall
realCall.enqueue(this)
}
override fun onResponse(call: Call, response: Response) {
processResponse(response)
}
fun processResponse(response: Response) {
response.use {
if (!response.isSuccessful) {
listener.onFailure(this, null, response)
return
}
val body = response.body!!
if (!body.isEventStream()) {
listener.onFailure(this,
IllegalStateException("Invalid content-type: ${body.contentType()}"), response)
return
}
// This is a long-lived response. Cancel full-call timeouts.
call?.timeoutEarlyExit()
// Replace the body with an empty one so the callbacks can't see real data.
val response = response.newBuilder()
.body(EMPTY_RESPONSE)
.build()
val reader = ServerSentEventReader(body.source(), this)
try {
if (!canceled) {
listener.onOpen(this, response)
while (!canceled && reader.processNextEvent()) {
}
}
} catch (e: Exception) {
val exception = when {
canceled -> IOException("canceled", e)
else -> e
}
listener.onFailure(this, exception, response)
return
}
if (canceled) {
listener.onFailure(this, IOException("canceled"), response)
} else {
listener.onClosed(this)
}
}
}
private fun ResponseBody.isEventStream(): Boolean {
val contentType = contentType() ?: return false
return contentType.type == "text" && contentType.subtype == "event-stream"
}
override fun onFailure(call: Call, e: IOException) {
listener.onFailure(this, e, null)
}
override fun request(): Request = request
override fun cancel() {
canceled = true
call?.cancel()
}
override fun onEvent(id: String?, type: String?, data: String) {
listener.onEvent(this, id, type, data)
}
override fun onRetryChange(timeMs: Long) {
// Ignored. We do not auto-retry.
}
}
| apache-2.0 | 19ddd87d9ffc7b241af626f3fdb2e972 | 27.675 | 91 | 0.67277 | 4.31744 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/notifications/profiles/EditNotificationProfileFragment.kt | 1 | 8262 | package org.thoughtcrime.securesms.components.settings.app.notifications.profiles
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.google.android.material.textfield.TextInputLayout
import io.reactivex.rxjava3.kotlin.subscribeBy
import org.signal.core.util.BreakIteratorCompat
import org.signal.core.util.EditTextUtil
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.emoji.EmojiUtil
import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment
import org.thoughtcrime.securesms.components.settings.app.notifications.profiles.EditNotificationProfileViewModel.SaveNotificationProfileResult
import org.thoughtcrime.securesms.components.settings.app.notifications.profiles.models.NotificationProfileNamePreset
import org.thoughtcrime.securesms.reactions.any.ReactWithAnyEmojiBottomSheetDialogFragment
import org.thoughtcrime.securesms.util.BottomSheetUtil
import org.thoughtcrime.securesms.util.LifecycleDisposable
import org.thoughtcrime.securesms.util.ViewUtil
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.navigation.safeNavigate
import org.thoughtcrime.securesms.util.text.AfterTextChanged
import org.thoughtcrime.securesms.util.views.CircularProgressMaterialButton
/**
* Dual use Edit/Create notification profile fragment. Use to create in the create profile flow,
* and then to edit from profile details. Responsible for naming and emoji.
*/
class EditNotificationProfileFragment : DSLSettingsFragment(layoutId = R.layout.fragment_edit_notification_profile), ReactWithAnyEmojiBottomSheetDialogFragment.Callback {
private val viewModel: EditNotificationProfileViewModel by viewModels(factoryProducer = this::createFactory)
private val lifecycleDisposable = LifecycleDisposable()
private var emojiView: ImageView? = null
private var nameView: EditText? = null
private fun createFactory(): ViewModelProvider.Factory {
val profileId = EditNotificationProfileFragmentArgs.fromBundle(requireArguments()).profileId
return EditNotificationProfileViewModel.Factory(profileId)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val toolbar: Toolbar = view.findViewById(R.id.toolbar)
toolbar.setNavigationOnClickListener {
ViewUtil.hideKeyboard(requireContext(), requireView())
requireActivity().onBackPressed()
}
val title: TextView = view.findViewById(R.id.edit_notification_profile_title)
val countView: TextView = view.findViewById(R.id.edit_notification_profile_count)
val saveButton: CircularProgressMaterialButton = view.findViewById(R.id.edit_notification_profile_save)
val emojiView: ImageView = view.findViewById(R.id.edit_notification_profile_emoji)
val nameView: EditText = view.findViewById(R.id.edit_notification_profile_name)
val nameTextWrapper: TextInputLayout = view.findViewById(R.id.edit_notification_profile_name_wrapper)
EditTextUtil.addGraphemeClusterLimitFilter(nameView, NOTIFICATION_PROFILE_NAME_MAX_GLYPHS)
nameView.addTextChangedListener(
AfterTextChanged { editable: Editable ->
presentCount(countView, editable.toString())
nameTextWrapper.error = null
}
)
emojiView.setOnClickListener {
ReactWithAnyEmojiBottomSheetDialogFragment.createForAboutSelection()
.show(childFragmentManager, BottomSheetUtil.STANDARD_BOTTOM_SHEET_FRAGMENT_TAG)
}
view.findViewById<View>(R.id.edit_notification_profile_clear).setOnClickListener {
nameView.setText("")
onEmojiSelectedInternal("")
}
lifecycleDisposable.bindTo(viewLifecycleOwner.lifecycle)
saveButton.setOnClickListener {
if (TextUtils.isEmpty(nameView.text)) {
nameTextWrapper.error = getString(R.string.EditNotificationProfileFragment__profile_must_have_a_name)
return@setOnClickListener
}
lifecycleDisposable += viewModel.save(nameView.text.toString())
.doOnSubscribe { saveButton.setSpinning() }
.doAfterTerminate { saveButton.cancelSpinning() }
.subscribeBy(
onSuccess = { saveResult ->
when (saveResult) {
is SaveNotificationProfileResult.Success -> {
ViewUtil.hideKeyboard(requireContext(), nameView)
if (saveResult.createMode) {
findNavController().safeNavigate(EditNotificationProfileFragmentDirections.actionEditNotificationProfileFragmentToAddAllowedMembersFragment(saveResult.profile.id))
} else {
findNavController().navigateUp()
}
}
SaveNotificationProfileResult.DuplicateNameFailure -> {
nameTextWrapper.error = getString(R.string.EditNotificationProfileFragment__a_profile_with_this_name_already_exists)
}
}
}
)
}
lifecycleDisposable += viewModel.getInitialState()
.subscribeBy(
onSuccess = { initial ->
if (initial.createMode) {
saveButton.text = getString(R.string.EditNotificationProfileFragment__create)
title.setText(R.string.EditNotificationProfileFragment__name_your_profile)
} else {
saveButton.text = getString(R.string.EditNotificationProfileFragment__save)
title.setText(R.string.EditNotificationProfileFragment__edit_this_profile)
}
nameView.setText(initial.name)
onEmojiSelectedInternal(initial.emoji)
ViewUtil.focusAndMoveCursorToEndAndOpenKeyboard(nameView)
}
)
this.nameView = nameView
this.emojiView = emojiView
}
override fun bindAdapter(adapter: MappingAdapter) {
NotificationProfileNamePreset.register(adapter)
val onClick = { preset: NotificationProfileNamePreset.Model ->
nameView?.apply {
setText(preset.bodyResource)
setSelection(length(), length())
}
onEmojiSelectedInternal(preset.emoji)
}
adapter.submitList(
listOf(
NotificationProfileNamePreset.Model("\uD83D\uDCAA", R.string.EditNotificationProfileFragment__work, onClick),
NotificationProfileNamePreset.Model("\uD83D\uDE34", R.string.EditNotificationProfileFragment__sleep, onClick),
NotificationProfileNamePreset.Model("\uD83D\uDE97", R.string.EditNotificationProfileFragment__driving, onClick),
NotificationProfileNamePreset.Model("\uD83D\uDE0A", R.string.EditNotificationProfileFragment__downtime, onClick),
NotificationProfileNamePreset.Model("\uD83D\uDCA1", R.string.EditNotificationProfileFragment__focus, onClick),
)
)
}
override fun onReactWithAnyEmojiSelected(emoji: String) {
onEmojiSelectedInternal(emoji)
}
override fun onReactWithAnyEmojiDialogDismissed() = Unit
private fun presentCount(countView: TextView, profileName: String) {
val breakIterator = BreakIteratorCompat.getInstance()
breakIterator.setText(profileName)
val glyphCount = breakIterator.countBreaks()
if (glyphCount >= NOTIFICATION_PROFILE_NAME_LIMIT_DISPLAY_THRESHOLD) {
countView.visibility = View.VISIBLE
countView.text = resources.getString(R.string.EditNotificationProfileFragment__count, glyphCount, NOTIFICATION_PROFILE_NAME_MAX_GLYPHS)
} else {
countView.visibility = View.GONE
}
}
private fun onEmojiSelectedInternal(emoji: String) {
val drawable = EmojiUtil.convertToDrawable(requireContext(), emoji)
if (drawable != null) {
emojiView?.setImageDrawable(drawable)
viewModel.onEmojiSelected(emoji)
} else {
emojiView?.setImageResource(R.drawable.ic_add_emoji)
viewModel.onEmojiSelected("")
}
}
companion object {
private const val NOTIFICATION_PROFILE_NAME_MAX_GLYPHS = 32
private const val NOTIFICATION_PROFILE_NAME_LIMIT_DISPLAY_THRESHOLD = 22
}
}
| gpl-3.0 | cef9add512ac2cefd11d1717830f6aa2 | 42.484211 | 181 | 0.755628 | 4.874336 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/dfa/KtDfaHelpers.kt | 3 | 12305 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.dfa
import com.intellij.codeInspection.dataFlow.DfaNullability
import com.intellij.codeInspection.dataFlow.TypeConstraint
import com.intellij.codeInspection.dataFlow.TypeConstraints
import com.intellij.codeInspection.dataFlow.jvm.SpecialField
import com.intellij.codeInspection.dataFlow.rangeSet.LongRangeBinOp
import com.intellij.codeInspection.dataFlow.rangeSet.LongRangeSet
import com.intellij.codeInspection.dataFlow.types.DfPrimitiveType
import com.intellij.codeInspection.dataFlow.types.DfReferenceType
import com.intellij.codeInspection.dataFlow.types.DfType
import com.intellij.codeInspection.dataFlow.types.DfTypes
import com.intellij.codeInspection.dataFlow.value.RelationType
import com.intellij.psi.PsiPrimitiveType
import com.intellij.psi.PsiType
import com.intellij.psi.tree.IElementType
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.StandardNames.FqNames
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType
import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch
import org.jetbrains.kotlin.resolve.constants.*
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isNullabilityFlexible
import org.jetbrains.kotlin.types.typeUtil.builtIns
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.types.typeUtil.makeNullable
internal fun KotlinType?.toDfType(): DfType {
if (this == null) return DfType.TOP
if (canBeNull()) {
var notNullableType = makeNotNullable().toDfTypeNotNullable()
if (notNullableType is DfPrimitiveType) {
val cls = this.constructor.declarationDescriptor as? ClassDescriptor
val boxedType: DfType
if (cls != null) {
boxedType = TypeConstraints.exactClass(KtClassDef(cls)).asDfType()
} else {
boxedType = DfTypes.OBJECT_OR_NULL
}
notNullableType = SpecialField.UNBOX.asDfType(notNullableType).meet(boxedType)
}
return when (notNullableType) {
is DfReferenceType -> {
notNullableType.dropNullability().meet(DfaNullability.NULLABLE.asDfType())
}
DfType.BOTTOM -> {
DfTypes.NULL
}
else -> {
notNullableType
}
}
}
return toDfTypeNotNullable()
}
private fun KotlinType.toDfTypeNotNullable(): DfType {
return when (val descriptor = this.constructor.declarationDescriptor) {
is TypeAliasDescriptor -> {
descriptor.expandedType.toDfType()
}
is ClassDescriptor -> when (descriptor.fqNameUnsafe) {
FqNames._boolean -> DfTypes.BOOLEAN
FqNames._byte -> DfTypes.intRange(LongRangeSet.range(Byte.MIN_VALUE.toLong(), Byte.MAX_VALUE.toLong()))
FqNames._char -> DfTypes.intRange(LongRangeSet.range(Character.MIN_VALUE.code.toLong(), Character.MAX_VALUE.code.toLong()))
FqNames._short -> DfTypes.intRange(LongRangeSet.range(Short.MIN_VALUE.toLong(), Short.MAX_VALUE.toLong()))
FqNames._int -> DfTypes.INT
FqNames._long -> DfTypes.LONG
FqNames._float -> DfTypes.FLOAT
FqNames._double -> DfTypes.DOUBLE
FqNames.array -> {
val elementType = getArrayElementType()?.constructor?.declarationDescriptor as? ClassDescriptor ?: return DfType.TOP
elementType.getTypeConstraint().arrayOf().asDfType().meet(DfTypes.NOT_NULL_OBJECT)
}
FqNames.any -> DfTypes.NOT_NULL_OBJECT
else -> descriptor.getTypeConstraint().asDfType().meet(DfTypes.NOT_NULL_OBJECT)
}
is TypeParameterDescriptor -> descriptor.upperBounds.map { type -> type.toDfType() }.fold(DfType.TOP, DfType::meet)
else -> DfType.TOP
}
}
private fun ClassDescriptor.getTypeConstraint(): TypeConstraint {
val fqNameUnsafe = fqNameUnsafe
if (fqNameUnsafe.shortNameOrSpecial().isSpecial) {
val source = source
if (source is KotlinSourceElement) {
val psi = source.psi
if (psi is KtObjectDeclaration) {
val bindingContext = psi.safeAnalyzeNonSourceRootCode()
val superTypes: List<KtClassDef?> = psi.superTypeListEntries
.map { entry ->
val classDescriptor = entry.typeReference?.getAbbreviatedTypeOrType(bindingContext)
?.constructor?.declarationDescriptor as? ClassDescriptor
if (classDescriptor == null) null else KtClassDef(classDescriptor)
}
return if (superTypes.contains(null))
TypeConstraints.TOP
else
TypeConstraints.exactSubtype(psi, superTypes)
}
}
}
return when (fqNameUnsafe.asString()) {
"kotlin.ByteArray" -> TypeConstraints.exact(PsiType.BYTE.createArrayType())
"kotlin.IntArray" -> TypeConstraints.exact(PsiType.INT.createArrayType())
"kotlin.LongArray" -> TypeConstraints.exact(PsiType.LONG.createArrayType())
"kotlin.ShortArray" -> TypeConstraints.exact(PsiType.SHORT.createArrayType())
"kotlin.CharArray" -> TypeConstraints.exact(PsiType.CHAR.createArrayType())
"kotlin.BooleanArray" -> TypeConstraints.exact(PsiType.BOOLEAN.createArrayType())
"kotlin.FloatArray" -> TypeConstraints.exact(PsiType.FLOAT.createArrayType())
"kotlin.DoubleArray" -> TypeConstraints.exact(PsiType.DOUBLE.createArrayType())
else -> {
val classDef = KtClassDef(this)
if (kind == ClassKind.OBJECT && classDef.isFinal) {
TypeConstraints.singleton(classDef)
} else {
TypeConstraints.exactClass(classDef).instanceOf()
}
}
}
}
internal fun KotlinType?.fqNameEquals(fqName: String): Boolean {
return this != null && this.constructor.declarationDescriptor?.fqNameUnsafe?.asString() == fqName
}
internal fun KotlinType.canBeNull() = isMarkedNullable || isNullabilityFlexible()
internal fun getConstant(expr: KtConstantExpression): DfType {
val bindingContext = expr.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
val type = bindingContext.getType(expr)
val constant: ConstantValue<Any?>? =
if (type == null) null else ConstantExpressionEvaluator.getConstant(expr, bindingContext)?.toConstantValue(type)
return when (constant) {
is NullValue -> DfTypes.NULL
is BooleanValue -> DfTypes.booleanValue(constant.value)
is ByteValue -> DfTypes.intValue(constant.value.toInt())
is ShortValue -> DfTypes.intValue(constant.value.toInt())
is CharValue -> DfTypes.intValue(constant.value.code)
is IntValue -> DfTypes.intValue(constant.value)
is LongValue -> DfTypes.longValue(constant.value)
is FloatValue -> DfTypes.floatValue(constant.value)
is DoubleValue -> DfTypes.doubleValue(constant.value)
else -> DfType.TOP
}
}
internal fun KtExpression.getKotlinType(): KotlinType? {
var parent = this.parent
if (parent is KtDotQualifiedExpression && parent.selectorExpression == this) {
parent = parent.parent
}
while (parent is KtParenthesizedExpression) {
parent = parent.parent
}
// In (call() as? X), the call() type might be inferred to be X due to peculiarities
// of Kotlin type system. This produces an unpleasant effect for data flow analysis:
// it assumes that this cast never fails, thus result is never null, which is actually wrong
// So we have to patch the original call type, widening it to its upper bound.
// Current implementation is not always precise and may result in skipping a useful warning.
if (parent is KtBinaryExpressionWithTypeRHS && parent.operationReference.text == "as?") {
val call = resolveToCall()
if (call != null) {
val descriptor = call.resultingDescriptor
val typeDescriptor = descriptor.original.returnType?.constructor?.declarationDescriptor
if (typeDescriptor is TypeParameterDescriptor) {
val upperBound = typeDescriptor.upperBounds.singleOrNull()
if (upperBound != null) {
return upperBound
}
}
}
}
return safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL).getType(this)
}
/**
* JVM-patched array element type (e.g. Int? for Array<Int>)
*/
internal fun KotlinType.getArrayElementType(): KotlinType? {
if (!KotlinBuiltIns.isArrayOrPrimitiveArray(this)) return null
val type = builtIns.getArrayElementType(this)
if (KotlinBuiltIns.isArray(this) && KotlinBuiltIns.isPrimitiveType(type)) {
return type.makeNullable()
}
return type
}
internal fun KotlinType.toPsiPrimitiveType(): PsiPrimitiveType {
return when (this.constructor.declarationDescriptor?.fqNameUnsafe) {
FqNames._int -> PsiType.INT
FqNames._long -> PsiType.LONG
FqNames._short -> PsiType.SHORT
FqNames._boolean -> PsiType.BOOLEAN
FqNames._byte -> PsiType.BYTE
FqNames._char -> PsiType.CHAR
FqNames._double -> PsiType.DOUBLE
FqNames._float -> PsiType.FLOAT
else -> throw IllegalArgumentException("Not a primitive analog: $this")
}
}
internal fun relationFromToken(token: IElementType): RelationType? = when (token) {
KtTokens.LT -> RelationType.LT
KtTokens.GT -> RelationType.GT
KtTokens.LTEQ -> RelationType.LE
KtTokens.GTEQ -> RelationType.GE
KtTokens.EQEQ -> RelationType.EQ
KtTokens.EXCLEQ -> RelationType.NE
KtTokens.EQEQEQ -> RelationType.EQ
KtTokens.EXCLEQEQEQ -> RelationType.NE
else -> null
}
internal fun mathOpFromToken(ref: KtOperationReferenceExpression): LongRangeBinOp? =
when (ref.text) {
"+" -> LongRangeBinOp.PLUS
"-" -> LongRangeBinOp.MINUS
"*" -> LongRangeBinOp.MUL
"/" -> LongRangeBinOp.DIV
"%" -> LongRangeBinOp.MOD
"and" -> LongRangeBinOp.AND
"or" -> LongRangeBinOp.OR
"xor" -> LongRangeBinOp.XOR
"shl" -> LongRangeBinOp.SHL
"shr" -> LongRangeBinOp.SHR
"ushr" -> LongRangeBinOp.USHR
else -> null
}
internal fun mathOpFromAssignmentToken(token: IElementType): LongRangeBinOp? = when(token) {
KtTokens.PLUSEQ -> LongRangeBinOp.PLUS
KtTokens.MINUSEQ -> LongRangeBinOp.MINUS
KtTokens.MULTEQ -> LongRangeBinOp.MUL
KtTokens.DIVEQ -> LongRangeBinOp.DIV
KtTokens.PERCEQ -> LongRangeBinOp.MOD
else -> null
}
internal fun getInlineableLambda(expr: KtCallExpression): LambdaAndParameter? {
val lambdaArgument = expr.lambdaArguments.singleOrNull() ?: return null
val lambdaExpression = lambdaArgument.getLambdaExpression() ?: return null
val index = expr.valueArguments.indexOf(lambdaArgument)
assert(index >= 0)
val resolvedCall = expr.resolveToCall() ?: return null
val descriptor = resolvedCall.resultingDescriptor as? FunctionDescriptor
if (descriptor == null || !descriptor.isInline) return null
val parameterDescriptor = (resolvedCall.getArgumentMapping(lambdaArgument) as? ArgumentMatch)?.valueParameter ?: return null
if (parameterDescriptor.isNoinline) return null
return LambdaAndParameter(lambdaExpression, parameterDescriptor)
}
internal data class LambdaAndParameter(val lambda: KtLambdaExpression, val descriptor: ValueParameterDescriptor) | apache-2.0 | 8ff4fc6cc38eee658c2414a6f715395b | 45.263158 | 158 | 0.696546 | 4.997969 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/output/PreviewEditorScratchOutputHandler.kt | 2 | 8257 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.scratch.output
import com.intellij.diff.util.DiffUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.TransactionGuard
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.command.executeCommand
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.FoldRegion
import com.intellij.openapi.editor.FoldingModel
import com.intellij.openapi.editor.markup.*
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.idea.scratch.ScratchExpression
import org.jetbrains.kotlin.idea.scratch.ScratchFile
import java.util.*
import kotlin.math.max
/**
* Output handler to print scratch output to separate window using [previewOutputBlocksManager].
*
* Multiline outputs from single expressions are folded.
*/
class PreviewEditorScratchOutputHandler(
private val previewOutputBlocksManager: PreviewOutputBlocksManager,
private val toolwindowHandler: ScratchOutputHandler,
private val parentDisposable: Disposable
) : ScratchOutputHandler {
override fun onStart(file: ScratchFile) {
toolwindowHandler.onStart(file)
}
override fun handle(file: ScratchFile, expression: ScratchExpression, output: ScratchOutput) {
printToPreviewEditor(expression, output)
}
override fun error(file: ScratchFile, message: String) {
toolwindowHandler.error(file, message)
}
override fun onFinish(file: ScratchFile) {
toolwindowHandler.onFinish(file)
}
override fun clear(file: ScratchFile) {
toolwindowHandler.clear(file)
clearOutputManager()
}
private fun printToPreviewEditor(expression: ScratchExpression, output: ScratchOutput) {
TransactionGuard.submitTransaction(parentDisposable, Runnable {
val targetCell = previewOutputBlocksManager.getBlock(expression) ?: previewOutputBlocksManager.addBlockToTheEnd(expression)
targetCell.addOutput(output)
})
}
private fun clearOutputManager() {
TransactionGuard.submitTransaction(parentDisposable, Runnable {
previewOutputBlocksManager.clear()
})
}
}
private val ScratchExpression.height: Int get() = lineEnd - lineStart + 1
interface ScratchOutputBlock {
val sourceExpression: ScratchExpression
val lineStart: Int
val lineEnd: Int
fun addOutput(output: ScratchOutput)
}
class PreviewOutputBlocksManager(editor: Editor) {
private val targetDocument: Document = editor.document
private val foldingModel: FoldingModel = editor.foldingModel
private val markupModel: MarkupModel = editor.markupModel
private val blocks: NavigableMap<ScratchExpression, OutputBlock> = TreeMap(Comparator.comparingInt { it.lineStart })
fun computeSourceToPreviewAlignments(): List<Pair<Int, Int>> = blocks.values.map { it.sourceExpression.lineStart to it.lineStart }
fun getBlock(expression: ScratchExpression): ScratchOutputBlock? = blocks[expression]
fun addBlockToTheEnd(expression: ScratchExpression): ScratchOutputBlock = OutputBlock(expression).also {
if (blocks.putIfAbsent(expression, it) != null) {
error("There is already a cell for $expression!")
}
}
fun clear() {
blocks.clear()
runWriteAction {
executeCommand {
targetDocument.setText("")
}
}
}
private inner class OutputBlock(override val sourceExpression: ScratchExpression) : ScratchOutputBlock {
private val outputs: MutableList<ScratchOutput> = mutableListOf()
override var lineStart: Int = computeCellLineStart(sourceExpression)
private set
override val lineEnd: Int get() = lineStart + countNewLines(outputs)
val height: Int get() = lineEnd - lineStart + 1
private var foldRegion: FoldRegion? = null
override fun addOutput(output: ScratchOutput) {
printAndSaveOutput(output)
blocks.lowerEntry(sourceExpression)?.value?.updateFolding()
blocks.tailMap(sourceExpression).values.forEach {
it.recalculatePosition()
it.updateFolding()
}
}
/**
* We want to make sure that changes in document happen in single edit, because if they are not,
* listeners may see inconsistent document, which may cause troubles if they will try to highlight it
* in some way. That's why it is important that [insertStringAtLine] does only one insert in the document,
* and [output] is inserted into the [outputs] before the edits, so [OutputBlock] can correctly see
* all its output expressions and highlight the whole block.
*/
private fun printAndSaveOutput(output: ScratchOutput) {
val beforeAdding = lineEnd
val currentOutputStartLine = if (outputs.isEmpty()) lineStart else beforeAdding + 1
outputs.add(output)
runWriteAction {
executeCommand {
targetDocument.insertStringAtLine(currentOutputStartLine, output.text)
}
}
markupModel.highlightLines(currentOutputStartLine, lineEnd, getAttributesForOutputType(output.type))
}
private fun recalculatePosition() {
lineStart = computeCellLineStart(sourceExpression)
}
private fun updateFolding() {
foldingModel.runBatchFoldingOperation {
foldRegion?.let(foldingModel::removeFoldRegion)
if (height <= sourceExpression.height) return@runBatchFoldingOperation
val firstFoldedLine = lineStart + (sourceExpression.height - 1)
val placeholderLine = "${targetDocument.getLineContent(firstFoldedLine)}..."
foldRegion = foldingModel.addFoldRegion(
targetDocument.getLineStartOffset(firstFoldedLine),
targetDocument.getLineEndOffset(lineEnd),
placeholderLine
)
foldRegion?.isExpanded = isLastCell && isOutputSmall
}
}
private val isLastCell: Boolean get() = false // blocks.higherEntry(sourceExpression) == null
private val isOutputSmall: Boolean get() = true
}
private fun computeCellLineStart(scratchExpression: ScratchExpression): Int {
val previous = blocks.lowerEntry(scratchExpression)?.value ?: return scratchExpression.lineStart
val distanceBetweenSources = scratchExpression.lineStart - previous.sourceExpression.lineEnd
val differenceBetweenSourceAndOutputHeight = previous.sourceExpression.height - previous.height
val compensation = max(differenceBetweenSourceAndOutputHeight, 0)
return previous.lineEnd + compensation + distanceBetweenSources
}
fun getBlockAtLine(line: Int): ScratchOutputBlock? = blocks.values.find { line in it.lineStart..it.lineEnd }
}
private fun countNewLines(list: List<ScratchOutput>) = list.sumOf { StringUtil.countNewLines(it.text) } + max(list.size - 1, 0)
private fun Document.getLineContent(lineNumber: Int) =
DiffUtil.getLinesContent(this, lineNumber, lineNumber + 1).toString()
private fun Document.insertStringAtLine(lineNumber: Int, text: String) {
val missingNewLines = lineNumber - (DiffUtil.getLineCount(this) - 1)
if (missingNewLines > 0) {
insertString(textLength, "${"\n".repeat(missingNewLines)}$text")
} else {
insertString(getLineStartOffset(lineNumber), text)
}
}
fun MarkupModel.highlightLines(
from: Int,
to: Int,
attributes: TextAttributes,
targetArea: HighlighterTargetArea = HighlighterTargetArea.EXACT_RANGE
): RangeHighlighter {
val fromOffset = document.getLineStartOffset(from)
val toOffset = document.getLineEndOffset(to)
return addRangeHighlighter(
fromOffset,
toOffset,
HighlighterLayer.CARET_ROW,
attributes,
targetArea
)
}
| apache-2.0 | d51bb98be626d1e34954f5a6e314963d | 37.404651 | 158 | 0.702919 | 4.983102 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/configuration/KotlinMigrationProjectService.kt | 1 | 10892 | // 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.configuration
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx
import com.intellij.util.CommonProcessors
import com.intellij.util.text.VersionComparatorUtil
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl
import org.jetbrains.kotlin.idea.configuration.ui.showMigrationNotification
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.idea.framework.MAVEN_SYSTEM_ID
import org.jetbrains.kotlin.idea.migration.CodeMigrationToggleAction
import org.jetbrains.kotlin.idea.migration.applicableMigrationTools
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.util.application.*
import org.jetbrains.kotlin.idea.util.runReadActionInSmartMode
import org.jetbrains.kotlin.idea.versions.LibInfo
import java.io.File
typealias MigrationTestState = KotlinMigrationProjectService.MigrationTestState
class KotlinMigrationProjectService(val project: Project) {
@Volatile
private var old: MigrationState? = null
@Volatile
private var importFinishListener: ((MigrationTestState?) -> Unit)? = null
class MigrationTestState(val migrationInfo: MigrationInfo?, val hasApplicableTools: Boolean)
@TestOnly
fun setImportFinishListener(newListener: ((MigrationTestState?) -> Unit)?) {
synchronized(this) {
if (newListener != null && importFinishListener != null) {
importFinishListener!!.invoke(null)
}
importFinishListener = newListener
}
}
private fun notifyFinish(migrationInfo: MigrationInfo?, hasApplicableTools: Boolean) {
importFinishListener?.invoke(MigrationTestState(migrationInfo, hasApplicableTools))
}
fun onImportAboutToStart() {
if (!CodeMigrationToggleAction.isEnabled(project) || !hasChangesInProjectFiles(project)) {
old = null
return
}
old = MigrationState.build(project)
}
fun onImportFinished() {
if (!CodeMigrationToggleAction.isEnabled(project) || old == null) {
notifyFinish(null, false)
return
}
executeOnPooledThread {
var migrationInfo: MigrationInfo? = null
var hasApplicableTools = false
try {
val new = project.runReadActionInSmartMode {
MigrationState.build(project)
}
val localOld = old.also {
old = null
} ?: return@executeOnPooledThread
migrationInfo = prepareMigrationInfo(localOld, new) ?: return@executeOnPooledThread
if (applicableMigrationTools(migrationInfo).isEmpty()) {
hasApplicableTools = false
return@executeOnPooledThread
} else {
hasApplicableTools = true
}
if (isUnitTestMode()) {
return@executeOnPooledThread
}
invokeLater {
showMigrationNotification(project, migrationInfo)
}
} finally {
notifyFinish(migrationInfo, hasApplicableTools)
}
}
}
companion object {
fun getInstance(project: Project): KotlinMigrationProjectService = project.getServiceSafe()
private fun prepareMigrationInfo(old: MigrationState?, new: MigrationState?): MigrationInfo? {
if (old == null || new == null) {
return null
}
val oldLibraryVersion = old.stdlibInfo?.version
val newLibraryVersion = new.stdlibInfo?.version
if (oldLibraryVersion == null || newLibraryVersion == null) {
return null
}
if (VersionComparatorUtil.COMPARATOR.compare(newLibraryVersion, oldLibraryVersion) > 0 ||
old.apiVersion < new.apiVersion || old.languageVersion < new.languageVersion
) {
return MigrationInfo(
oldLibraryVersion, newLibraryVersion,
old.apiVersion, new.apiVersion,
old.languageVersion, new.languageVersion
)
}
return null
}
private fun hasChangesInProjectFiles(project: Project): Boolean {
if (ProjectLevelVcsManagerEx.getInstance(project).allVcsRoots.isEmpty()) {
return true
}
val checkedFiles = HashSet<File>()
project.basePath?.let { projectBasePath ->
checkedFiles.add(File(projectBasePath))
}
val changedFiles = ChangeListManager.getInstance(project).affectedPaths
for (changedFile in changedFiles) {
when (changedFile.extension) {
"gradle" -> return true
"properties" -> return true
"kts" -> return true
"iml" -> return true
"xml" -> {
if (changedFile.name == "pom.xml") return true
val parentDir = changedFile.parentFile
if (parentDir.isDirectory && parentDir.name == Project.DIRECTORY_STORE_FOLDER) {
return true
}
}
"kt", "java", "groovy" -> {
val dirs: Sequence<File> = generateSequence(changedFile) { it.parentFile }
.drop(1) // Drop original file
.takeWhile { it.isDirectory }
val isInBuildSrc = dirs
.takeWhile { checkedFiles.add(it) }
.any { it.name == BUILD_SRC_FOLDER_NAME }
if (isInBuildSrc) {
return true
}
}
}
}
return false
}
}
}
private class MigrationState(
var stdlibInfo: LibInfo?,
var apiVersion: ApiVersion,
var languageVersion: LanguageVersion
) {
companion object {
fun build(project: Project): MigrationState {
val libraries = maxKotlinLibVersion(project)
val languageVersionSettings = collectMaxCompilerSettings(project)
return MigrationState(libraries, languageVersionSettings.apiVersion, languageVersionSettings.languageVersion)
}
}
}
data class MigrationInfo(
val oldStdlibVersion: String,
val newStdlibVersion: String,
val oldApiVersion: ApiVersion,
val newApiVersion: ApiVersion,
val oldLanguageVersion: LanguageVersion,
val newLanguageVersion: LanguageVersion
) {
companion object {
fun create(
oldStdlibVersion: String,
oldApiVersion: ApiVersion,
oldLanguageVersion: LanguageVersion,
newStdlibVersion: String = oldStdlibVersion,
newApiVersion: ApiVersion = oldApiVersion,
newLanguageVersion: LanguageVersion = oldLanguageVersion
): MigrationInfo {
return MigrationInfo(
oldStdlibVersion, newStdlibVersion,
oldApiVersion, newApiVersion,
oldLanguageVersion, newLanguageVersion
)
}
}
}
fun MigrationInfo.isLanguageVersionUpdate(old: LanguageVersion, new: LanguageVersion): Boolean {
return oldLanguageVersion <= old && newLanguageVersion >= new
}
private const val BUILD_SRC_FOLDER_NAME = "buildSrc"
private const val KOTLIN_GROUP_ID = "org.jetbrains.kotlin"
private fun maxKotlinLibVersion(project: Project): LibInfo? {
return runReadAction {
var maxStdlibInfo: LibInfo? = null
val allLibProcessor = CommonProcessors.CollectUniquesProcessor<Library>()
ProjectRootManager.getInstance(project).orderEntries().forEachLibrary(allLibProcessor)
for (library in allLibProcessor.results) {
if (!ExternalSystemApiUtil.isExternalSystemLibrary(library, GRADLE_SYSTEM_ID) &&
!ExternalSystemApiUtil.isExternalSystemLibrary(library, MAVEN_SYSTEM_ID)
) {
continue
}
if (library.name?.contains(" $KOTLIN_GROUP_ID:kotlin-stdlib") != true) {
continue
}
val libraryInfo = parseExternalLibraryName(library) ?: continue
if (maxStdlibInfo == null || VersionComparatorUtil.COMPARATOR.compare(libraryInfo.version, maxStdlibInfo.version) > 0) {
maxStdlibInfo = LibInfo(KOTLIN_GROUP_ID, libraryInfo.artifactId, libraryInfo.version)
}
}
maxStdlibInfo
}
}
private fun collectMaxCompilerSettings(project: Project): LanguageVersionSettings {
return runReadAction {
var maxApiVersion: ApiVersion? = null
var maxLanguageVersion: LanguageVersion? = null
for (module in ModuleManager.getInstance(project).modules) {
if (!module.isKotlinModule()) {
// Otherwise project compiler settings will give unreliable maximum for compiler settings
continue
}
val languageVersionSettings = module.languageVersionSettings
if (maxApiVersion == null || languageVersionSettings.apiVersion > maxApiVersion) {
maxApiVersion = languageVersionSettings.apiVersion
}
if (maxLanguageVersion == null || languageVersionSettings.languageVersion > maxLanguageVersion) {
maxLanguageVersion = languageVersionSettings.languageVersion
}
}
LanguageVersionSettingsImpl(maxLanguageVersion ?: LanguageVersion.LATEST_STABLE, maxApiVersion ?: ApiVersion.LATEST_STABLE)
}
}
private fun Module.isKotlinModule(): Boolean {
if (isDisposed) return false
if (KotlinFacet.get(this) != null) {
return true
}
// This code works only for Maven and Gradle import, and it's expected that Kotlin facets are configured for
// all modules with external system.
return false
} | apache-2.0 | 057aa07994add17985e504525027874e | 35.925424 | 158 | 0.632207 | 5.588507 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/resolve/AbstractReferenceResolveInJavaTest.kt | 2 | 2402 | // 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.resolve
import com.intellij.openapi.util.io.FileUtil
import com.intellij.psi.PsiElement
import com.intellij.util.ThrowableRunnable
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.idea.decompiler.classFile.KtClsFile
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.idea.test.MockLibraryFacility
import org.jetbrains.kotlin.idea.test.runAll
import org.jetbrains.kotlin.psi.KtDeclaration
import org.junit.Assert
private val FILE_WITH_KOTLIN_CODE = IDEA_TEST_DATA_DIR.resolve("resolve/referenceInJava/dependency/dependencies.kt")
abstract class AbstractReferenceResolveInJavaTest : AbstractReferenceResolveTest() {
override fun doTest(path: String) {
val fileName = fileName()
assert(fileName.endsWith(".java")) { fileName }
myFixture.configureByText("dependencies.kt", FileUtil.loadFile(FILE_WITH_KOTLIN_CODE, true))
myFixture.configureByFile(fileName)
performChecks()
}
}
abstract class AbstractReferenceToCompiledKotlinResolveInJavaTest : AbstractReferenceResolveTest() {
private val mockLibraryFacility = MockLibraryFacility(FILE_WITH_KOTLIN_CODE)
override fun doTest(path: String) {
myFixture.configureByFile(fileName())
performChecks()
}
override fun setUp() {
super.setUp()
mockLibraryFacility.setUp(module)
}
override fun tearDown() {
runAll(
ThrowableRunnable { mockLibraryFacility.tearDown(module) },
ThrowableRunnable { super.tearDown() }
)
}
override val refMarkerText: String
get() = "CLS_REF"
override fun checkResolvedTo(element: PsiElement) {
val navigationElement = element.navigationElement
Assert.assertFalse(
"Reference should not navigate to a light element\nWas: ${navigationElement::class.java.simpleName}",
navigationElement is KtLightElement<*, *>
)
Assert.assertTrue(
"Reference should navigate to a kotlin declaration\nWas: ${navigationElement::class.java.simpleName}",
navigationElement is KtDeclaration || navigationElement is KtClsFile
)
}
}
| apache-2.0 | cca8edb4d1b6f3866394fd0fad874680 | 37.741935 | 158 | 0.727311 | 4.756436 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SuspiciousCollectionReassignmentInspection.kt | 1 | 10525 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.intentions.ReplaceWithOrdinaryAssignmentIntention
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.quickfix.ChangeToMutableCollectionFix
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.SimpleType
class SuspiciousCollectionReassignmentInspection : AbstractKotlinInspection() {
private val targetOperations: List<KtSingleValueToken> = listOf(KtTokens.PLUSEQ, KtTokens.MINUSEQ)
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor =
binaryExpressionVisitor(fun(binaryExpression) {
if (binaryExpression.right == null) return
val operationToken = binaryExpression.operationToken as? KtSingleValueToken ?: return
if (operationToken !in targetOperations) return
val left = binaryExpression.left ?: return
val property = left.mainReference?.resolve() as? KtProperty ?: return
if (!property.isVar) return
val context = binaryExpression.analyze()
val leftType = left.getType(context) ?: return
val leftDefaultType = leftType.constructor.declarationDescriptor?.defaultType ?: return
if (!leftType.isReadOnlyCollectionOrMap(binaryExpression.builtIns)) return
if (context.diagnostics.forElement(binaryExpression).any { it.severity == Severity.ERROR }) return
val fixes = mutableListOf<LocalQuickFix>()
if (ChangeTypeToMutableFix.isApplicable(property)) {
fixes.add(ChangeTypeToMutableFix(leftType))
}
if (ReplaceWithFilterFix.isApplicable(binaryExpression, leftDefaultType, context)) {
fixes.add(ReplaceWithFilterFix())
}
when {
ReplaceWithAssignmentFix.isApplicable(binaryExpression, property, context) -> fixes.add(ReplaceWithAssignmentFix())
JoinWithInitializerFix.isApplicable(binaryExpression, property) -> fixes.add(JoinWithInitializerFix(operationToken))
else -> fixes.add(IntentionWrapper(ReplaceWithOrdinaryAssignmentIntention()))
}
val typeText = leftDefaultType.toString().takeWhile { it != '<' }.toLowerCase()
val operationReference = binaryExpression.operationReference
holder.registerProblem(
operationReference,
KotlinBundle.message("0.creates.new.1.under.the.hood", operationReference.text, typeText),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
*fixes.toTypedArray()
)
})
private class ChangeTypeToMutableFix(private val type: KotlinType) : LocalQuickFix {
override fun getName() = KotlinBundle.message("change.type.to.mutable.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return
val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return
val left = binaryExpression.left ?: return
val property = left.mainReference?.resolve() as? KtProperty ?: return
ChangeToMutableCollectionFix.applyFix(property, type)
property.valOrVarKeyword.replace(KtPsiFactory(property).createValKeyword())
binaryExpression.findExistingEditor()?.caretModel?.moveToOffset(property.endOffset)
}
companion object {
fun isApplicable(property: KtProperty): Boolean {
return ChangeToMutableCollectionFix.isApplicable(property)
}
}
}
private class ReplaceWithFilterFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.filter.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return
val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return
val left = binaryExpression.left ?: return
val right = binaryExpression.right ?: return
val psiFactory = KtPsiFactory(operationReference)
operationReference.replace(psiFactory.createOperationName(KtTokens.EQ.value))
right.replace(psiFactory.createExpressionByPattern("$0.filter { it !in $1 }", left, right))
}
companion object {
fun isApplicable(binaryExpression: KtBinaryExpression, leftType: SimpleType, context: BindingContext): Boolean {
if (binaryExpression.operationToken != KtTokens.MINUSEQ) return false
if (leftType == binaryExpression.builtIns.map.defaultType) return false
return binaryExpression.right?.getType(context)?.classDescriptor()?.isSubclassOf(binaryExpression.builtIns.iterable) == true
}
}
}
private class ReplaceWithAssignmentFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.with.assignment.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return
val psiFactory = KtPsiFactory(operationReference)
operationReference.replace(psiFactory.createOperationName(KtTokens.EQ.value))
}
companion object {
val emptyCollectionFactoryMethods =
listOf("emptyList", "emptySet", "emptyMap", "listOf", "setOf", "mapOf").map { "kotlin.collections.$it" }
fun isApplicable(binaryExpression: KtBinaryExpression, property: KtProperty, context: BindingContext): Boolean {
if (binaryExpression.operationToken != KtTokens.PLUSEQ) return false
if (!property.isLocal) return false
val initializer = property.initializer as? KtCallExpression ?: return false
if (initializer.valueArguments.isNotEmpty()) return false
val initializerResultingDescriptor = initializer.getResolvedCall(context)?.resultingDescriptor
val fqName = initializerResultingDescriptor?.fqNameOrNull()?.asString()
if (fqName !in emptyCollectionFactoryMethods) return false
val rightClassDescriptor = binaryExpression.right?.getType(context)?.classDescriptor() ?: return false
val initializerClassDescriptor = initializerResultingDescriptor?.returnType?.classDescriptor() ?: return false
if (!rightClassDescriptor.isSubclassOf(initializerClassDescriptor)) return false
if (binaryExpression.siblings(forward = false, withItself = false)
.filter { it != property }
.any { sibling -> sibling.anyDescendantOfType<KtSimpleNameExpression> { it.mainReference.resolve() == property } }
) return false
return true
}
}
}
private class JoinWithInitializerFix(private val op: KtSingleValueToken) : LocalQuickFix {
override fun getName() = KotlinBundle.message("join.with.initializer.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val operationReference = descriptor.psiElement as? KtOperationReferenceExpression ?: return
val binaryExpression = operationReference.parent as? KtBinaryExpression ?: return
val left = binaryExpression.left ?: return
val right = binaryExpression.right ?: return
val property = left.mainReference?.resolve() as? KtProperty ?: return
val initializer = property.initializer ?: return
val psiFactory = KtPsiFactory(operationReference)
val newOp = if (op == KtTokens.PLUSEQ) KtTokens.PLUS else KtTokens.MINUS
val replaced = initializer.replaced(psiFactory.createExpressionByPattern("$0 $1 $2", initializer, newOp.value, right))
binaryExpression.delete()
property.findExistingEditor()?.caretModel?.moveToOffset(replaced.endOffset)
}
companion object {
fun isApplicable(binaryExpression: KtBinaryExpression, property: KtProperty): Boolean {
if (!property.isLocal || property.initializer == null) return false
return binaryExpression.getPrevSiblingIgnoringWhitespaceAndComments() == property
}
}
}
}
private fun KotlinType.classDescriptor() = constructor.declarationDescriptor as? ClassDescriptor
internal fun KotlinType.isReadOnlyCollectionOrMap(builtIns: KotlinBuiltIns): Boolean {
val leftDefaultType = constructor.declarationDescriptor?.defaultType ?: return false
return leftDefaultType in listOf(builtIns.list.defaultType, builtIns.set.defaultType, builtIns.map.defaultType)
} | apache-2.0 | f93317ad37cf997d9af9adb419d50eec | 52.979487 | 158 | 0.709169 | 5.873326 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/ui/KotlinAwareMoveFilesOrDirectoriesDialog.kt | 4 | 10545 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.fileChooser.FileChooserFactory
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.options.ConfigurationException
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.TextComponentAccessors
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiFileSystemItem
import com.intellij.psi.PsiManager
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.copy.CopyFilesOrDirectoriesDialog
import com.intellij.refactoring.copy.CopyFilesOrDirectoriesHandler
import com.intellij.refactoring.move.MoveCallback
import com.intellij.refactoring.move.MoveHandler
import com.intellij.ui.NonFocusableCheckBox
import com.intellij.ui.RecentsManager
import com.intellij.ui.TextFieldWithHistoryWithBrowseButton
import com.intellij.ui.components.JBLabelDecorator
import com.intellij.util.ui.FormBuilder
import com.intellij.util.ui.UIUtil
import org.jetbrains.kotlin.idea.base.util.onTextChange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.packageMatchesDirectoryOrImplicit
import org.jetbrains.kotlin.idea.refactoring.isInKotlinAwareSourceRoot
import org.jetbrains.kotlin.idea.refactoring.move.logFusForMoveRefactoring
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.psi.KtFile
import javax.swing.JComponent
class KotlinAwareMoveFilesOrDirectoriesDialog(
private val project: Project,
private val initialDirectory: PsiDirectory?,
private val psiElements: List<PsiFileSystemItem>,
private val callback: MoveCallback?
) : DialogWrapper(project, true) {
companion object {
private const val RECENT_KEYS = "MoveFile.RECENT_KEYS"
private const val MOVE_FILES_OPEN_IN_EDITOR = "MoveFile.OpenInEditor"
private const val MOVE_FILES_SEARCH_REFERENCES = "MoveFile.SearchReferences"
private const val HELP_ID = "refactoring.moveFile"
private fun setConfigurationValue(id: String, value: Boolean, defaultValue: Boolean) {
if (!isUnitTestMode()) {
PropertiesComponent.getInstance().setValue(id, value, defaultValue)
}
}
private fun getConfigurationValue(id: String, defaultValue: Boolean) =
!isUnitTestMode() && PropertiesComponent.getInstance().getBoolean(id, defaultValue)
}
private data class CheckboxesState(
val searchReferences: Boolean,
val openInEditor: Boolean,
val updatePackageDirective: Boolean
)
private val nameLabel = JBLabelDecorator.createJBLabelDecorator().setBold(true)
private val targetDirectoryField = TextFieldWithHistoryWithBrowseButton()
private val searchReferencesCb = NonFocusableCheckBox(KotlinBundle.message("checkbox.text.search.references")).apply {
isSelected = true
}
private val openInEditorCb = NonFocusableCheckBox(KotlinBundle.message("checkbox.text.open.moved.files.in.editor"))
private val updatePackageDirectiveCb = NonFocusableCheckBox()
private val initializedCheckBoxesState: CheckboxesState
override fun getHelpId() = HELP_ID
init {
title = RefactoringBundle.message("move.title")
init()
initializeData()
initializedCheckBoxesState = getCheckboxesState(applyDefaults = true)
}
private fun getCheckboxesState(applyDefaults: Boolean) = CheckboxesState(
searchReferences = applyDefaults || searchReferencesCb.isSelected, //searchReferencesCb is true by default
openInEditor = !applyDefaults && openInEditorCb.isSelected, //openInEditorCb is false by default
updatePackageDirective = updatePackageDirectiveCb.isSelected
)
override fun createActions() = arrayOf(okAction, cancelAction, helpAction)
override fun getPreferredFocusedComponent() = targetDirectoryField.childComponent
override fun createCenterPanel(): JComponent? = null
override fun createNorthPanel(): JComponent {
RecentsManager.getInstance(project).getRecentEntries(RECENT_KEYS)?.let { targetDirectoryField.childComponent.history = it }
val descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor()
targetDirectoryField.addBrowseFolderListener(
RefactoringBundle.message("select.target.directory"),
RefactoringBundle.message("the.file.will.be.moved.to.this.directory"),
project,
descriptor,
TextComponentAccessors.TEXT_FIELD_WITH_HISTORY_WHOLE_TEXT
)
val textField = targetDirectoryField.childComponent.textEditor
FileChooserFactory.getInstance().installFileCompletion(textField, descriptor, true, disposable)
textField.onTextChange { validateOKButton() }
targetDirectoryField.setTextFieldPreferredWidth(CopyFilesOrDirectoriesDialog.MAX_PATH_LENGTH)
Disposer.register(disposable, targetDirectoryField)
openInEditorCb.isSelected = getConfigurationValue(id = MOVE_FILES_OPEN_IN_EDITOR, defaultValue = false)
searchReferencesCb.isSelected = getConfigurationValue(id = MOVE_FILES_SEARCH_REFERENCES, defaultValue = true)
val shortcutText = KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction(IdeActions.ACTION_CODE_COMPLETION))
return FormBuilder.createFormBuilder()
.addComponent(nameLabel)
.addLabeledComponent(RefactoringBundle.message("move.files.to.directory.label"), targetDirectoryField, UIUtil.LARGE_VGAP)
.addTooltip(RefactoringBundle.message("path.completion.shortcut", shortcutText))
.addComponentToRightColumn(searchReferencesCb, UIUtil.LARGE_VGAP)
.addComponentToRightColumn(openInEditorCb, UIUtil.LARGE_VGAP)
.addComponentToRightColumn(updatePackageDirectiveCb, UIUtil.LARGE_VGAP)
.panel
}
private fun initializeData() {
val psiElement = psiElements.singleOrNull()
if (psiElement != null) {
val shortenedPath = CopyFilesOrDirectoriesDialog.shortenPath(psiElement.virtualFile)
nameLabel.text = when (psiElement) {
is PsiFile -> RefactoringBundle.message("move.file.0", shortenedPath)
else -> RefactoringBundle.message("move.directory.0", shortenedPath)
}
} else {
val isFile = psiElements.all { it is PsiFile }
val isDirectory = psiElements.all { it is PsiDirectory }
nameLabel.text = when {
isFile -> RefactoringBundle.message("move.specified.files")
isDirectory -> RefactoringBundle.message("move.specified.directories")
else -> RefactoringBundle.message("move.specified.elements")
}
}
targetDirectoryField.childComponent.text = initialDirectory?.virtualFile?.presentableUrl ?: ""
validateOKButton()
with(updatePackageDirectiveCb) {
val ktFiles = psiElements.filterIsInstance<KtFile>().filter(KtFile::isInKotlinAwareSourceRoot)
if (ktFiles.isEmpty()) {
parent.remove(updatePackageDirectiveCb)
return
}
val singleFile = ktFiles.singleOrNull()
isSelected = singleFile == null || singleFile.packageMatchesDirectoryOrImplicit()
text = KotlinBundle.message("checkbox.text.update.package.directive")
}
}
private fun validateOKButton() {
isOKActionEnabled = targetDirectoryField.childComponent.text.isNotEmpty()
}
private val selectedDirectoryName: String
get() = targetDirectoryField.childComponent.text.let {
when {
it.startsWith(".") -> (initialDirectory?.virtualFile?.path ?: "") + "/" + it
else -> it
}
}
private fun getModel(): Model {
val directory = LocalFileSystem.getInstance().findFileByPath(selectedDirectoryName)?.let {
PsiManager.getInstance(project).findDirectory(it)
}
val elementsToMove = directory?.let { existentDirectory ->
val choice = if (psiElements.size > 1 || psiElements[0] is PsiDirectory) intArrayOf(-1) else null
psiElements.filterNot {
it is PsiFile && CopyFilesOrDirectoriesHandler.checkFileExist(existentDirectory, choice, it, it.name, title)
}
} ?: psiElements.toList()
return KotlinAwareMoveFilesOrDirectoriesModel(
project,
elementsToMove,
selectedDirectoryName,
updatePackageDirectiveCb.isSelected,
searchReferencesCb.isSelected,
callback
)
}
override fun doOKAction() {
val modelResult: ModelResultWithFUSData
try {
modelResult = getModel().computeModelResult()
} catch (e: ConfigurationException) {
setErrorText(e.message)
return
}
project.executeCommand(MoveHandler.getRefactoringName()) {
with(modelResult) {
logFusForMoveRefactoring(
numberOfEntities = elementsCount,
entity = entityToMove,
destination = destination,
isDefault = getCheckboxesState(applyDefaults = false) == initializedCheckBoxesState,
body = processor
)
}
}
setConfigurationValue(id = MOVE_FILES_SEARCH_REFERENCES, value = searchReferencesCb.isSelected, defaultValue = true)
setConfigurationValue(id = MOVE_FILES_OPEN_IN_EDITOR, value = openInEditorCb.isSelected, defaultValue = false)
RecentsManager.getInstance(project).registerRecentEntry(RECENT_KEYS, targetDirectoryField.childComponent.text)
close(OK_EXIT_CODE, /* isOk = */ true)
}
}
| apache-2.0 | 76d5ad4002e004f17a0a73f7648eb61f | 44.257511 | 158 | 0.715505 | 5.251494 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/ScriptTrafficLightRendererContributor.kt | 4 | 2731 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.core.script
import com.intellij.codeInsight.daemon.impl.SeverityRegistrar
import com.intellij.codeInsight.daemon.impl.TrafficLightRenderer
import com.intellij.codeInsight.daemon.impl.TrafficLightRendererContributor
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import org.jetbrains.kotlin.idea.base.scripting.KotlinBaseScriptingBundle
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal class ScriptTrafficLightRendererContributor : TrafficLightRendererContributor {
@RequiresBackgroundThread
override fun createRenderer(editor: Editor, file: PsiFile?): TrafficLightRenderer? {
val ktFile = file.safeAs<KtFile>() ?: return null
val isScript = runReadAction { ktFile.isScript() /* RequiresBackgroundThread */}
return if (isScript) {
ScriptTrafficLightRenderer(ktFile.project, editor.document, ktFile)
} else {
null
}
}
class ScriptTrafficLightRenderer(project: Project, document: Document, private val file: KtFile) :
TrafficLightRenderer(project, document) {
override fun getDaemonCodeAnalyzerStatus(severityRegistrar: SeverityRegistrar): DaemonCodeAnalyzerStatus {
val status = super.getDaemonCodeAnalyzerStatus(severityRegistrar)
val configurations = ScriptConfigurationManager.getServiceIfCreated(project)
if (configurations == null) {
// services not yet initialized (it should be initialized under the LoadScriptDefinitionsStartupActivity)
status.reasonWhySuspended = KotlinBaseScriptingBundle.message("text.loading.kotlin.script.configuration")
status.errorAnalyzingFinished = false
} else if (!ScriptDefinitionsManager.getInstance(project).isReady()) {
status.reasonWhySuspended = KotlinBaseScriptingBundle.message("text.loading.kotlin.script.definitions")
status.errorAnalyzingFinished = false
} else if (configurations.isConfigurationLoadingInProgress(file)) {
status.reasonWhySuspended = KotlinBaseScriptingBundle.message("text.loading.kotlin.script.configuration")
status.errorAnalyzingFinished = false
}
return status
}
}
}
| apache-2.0 | bf8be180b345de3e5c5822f0b6645ed0 | 53.62 | 158 | 0.747345 | 5.15283 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/inspections-shared/src/org/jetbrains/kotlin/idea/codeInsight/inspections/shared/SortModifiersInspection.kt | 4 | 3921 | // 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.codeInsight.inspections.shared
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtAnnotation
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.KtModifierList
import org.jetbrains.kotlin.psi.KtModifierListOwner
import org.jetbrains.kotlin.psi.addRemoveModifier.sortModifiers
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class SortModifiersInspection : AbstractApplicabilityBasedInspection<KtModifierList>(
KtModifierList::class.java
), CleanupLocalInspectionTool {
override fun isApplicable(element: KtModifierList): Boolean {
val modifiers = element.modifierKeywordTokens()
if (modifiers.isEmpty()) return false
val sortedModifiers = sortModifiers(modifiers)
if (modifiers == sortedModifiers && !element.modifiersBeforeAnnotations()) return false
return true
}
override fun inspectionHighlightRangeInElement(element: KtModifierList): TextRange? {
val modifierElements = element.allChildren.toList()
val startElement = modifierElements.firstOrNull { it.node.elementType is KtModifierKeywordToken } ?: return null
val endElement = modifierElements.lastOrNull { it.node.elementType is KtModifierKeywordToken } ?: return null
return TextRange(startElement.startOffset, endElement.endOffset).shiftLeft(element.startOffset)
}
override fun inspectionText(element: KtModifierList) =
if (element.modifiersBeforeAnnotations()) KotlinBundle.message("modifiers.should.follow.annotations") else KotlinBundle.message("non.canonical.modifiers.order")
override val defaultFixText get() = KotlinBundle.message("sort.modifiers")
override fun applyTo(element: KtModifierList, project: Project, editor: Editor?) {
val owner = element.parent as? KtModifierListOwner ?: return
val sortedModifiers = sortModifiers(element.modifierKeywordTokens())
val existingModifiers = sortedModifiers.filter { owner.hasModifier(it) }
existingModifiers.forEach { owner.removeModifier(it) }
// We add visibility / modality modifiers after all others,
// because they can be redundant or not depending on others (e.g. override)
existingModifiers
.partition { it in KtTokens.VISIBILITY_MODIFIERS || it in KtTokens.MODALITY_MODIFIERS }
.let { it.second + it.first }
.forEach { owner.addModifier(it) }
}
private fun KtModifierList.modifierKeywordTokens(): List<KtModifierKeywordToken> {
return allChildren.mapNotNull { it.node.elementType as? KtModifierKeywordToken }.toList()
}
private fun KtModifierList.modifiersBeforeAnnotations(): Boolean {
val modifierElements = this.allChildren.toList()
var modifiersBeforeAnnotations = false
var seenModifiers = false
for (modifierElement in modifierElements) {
if (modifierElement.node.elementType is KtModifierKeywordToken) {
seenModifiers = true
} else if (seenModifiers && (modifierElement is KtAnnotationEntry || modifierElement is KtAnnotation)) {
modifiersBeforeAnnotations = true
}
}
return modifiersBeforeAnnotations
}
} | apache-2.0 | 573b2bf3689ad944074a447896c75334 | 52 | 168 | 0.756185 | 5.200265 | false | false | false | false |
ianhanniballake/muzei | legacy-standalone/src/main/java/com/google/android/apps/muzei/legacy/Source.kt | 1 | 3810 | /*
* 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.android.apps.muzei.legacy
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.util.Log
import android.widget.Toast
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import com.google.android.apps.muzei.util.toastFromBackground
import net.nurik.roman.muzei.legacy.BuildConfig
import net.nurik.roman.muzei.legacy.R
import java.util.ArrayList
/**
* Source information's representation in Room
*/
@Entity(tableName = "sources")
class Source(
@field:TypeConverters(ComponentNameTypeConverter::class)
@field:ColumnInfo(name = "component_name")
@field:PrimaryKey
val componentName: ComponentName) {
var selected: Boolean = false
var label: String? = null
var defaultDescription: String? = null
var description: String? = null
val displayDescription: String?
get() = if (description.isNullOrEmpty()) defaultDescription else description
var color: Int = 0
var targetSdkVersion: Int = 0
@TypeConverters(ComponentNameTypeConverter::class)
var settingsActivity: ComponentName? = null
@TypeConverters(ComponentNameTypeConverter::class)
var setupActivity: ComponentName? = null
var wantsNetworkAvailable: Boolean = false
var supportsNextArtwork: Boolean = false
@TypeConverters(UserCommandTypeConverter::class)
var commands: MutableList<String> = ArrayList()
}
private const val TAG = "Source"
private const val ACTION_HANDLE_COMMAND = "com.google.android.apps.muzei.api.action.HANDLE_COMMAND"
private const val EXTRA_COMMAND_ID = "com.google.android.apps.muzei.api.extra.COMMAND_ID"
suspend fun Source.sendAction(context: Context, id: Int) {
try {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Sending command $id to $this")
}
// Ensure that we have a valid service before sending the action
context.packageManager.getServiceInfo(componentName, 0)
context.startService(Intent(ACTION_HANDLE_COMMAND)
.setComponent(componentName)
.putExtra(EXTRA_COMMAND_ID, id))
} catch (e: PackageManager.NameNotFoundException) {
Log.i(TAG, "Sending action $id to $componentName failed as it is no longer available", e)
context.toastFromBackground(R.string.legacy_source_unavailable, Toast.LENGTH_LONG)
LegacyDatabase.getInstance(context).sourceDao().delete(this)
} catch (e: IllegalStateException) {
Log.i(TAG, "Sending action $id to $componentName failed; unselecting it.", e)
context.toastFromBackground(R.string.legacy_source_unavailable, Toast.LENGTH_LONG)
LegacyDatabase.getInstance(context).sourceDao()
.update(apply { selected = false })
} catch (e: SecurityException) {
Log.i(TAG, "Sending action $id to $componentName failed; unselecting it.", e)
context.toastFromBackground(R.string.legacy_source_unavailable, Toast.LENGTH_LONG)
LegacyDatabase.getInstance(context).sourceDao()
.update(apply { selected = false })
}
}
| apache-2.0 | 20a707c0b9777c1ed210639decba8cf7 | 36.352941 | 99 | 0.724147 | 4.349315 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/openapi/roots/ui/distribution/AbstractDistributionInfo.kt | 9 | 702 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.roots.ui.distribution
abstract class AbstractDistributionInfo: DistributionInfo {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as DistributionInfo
if (name != other.name) return false
if (description != other.description) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + (description?.hashCode() ?: 0)
return result
}
} | apache-2.0 | ea81eba7276fdd330061a59f705f64b7 | 30.954545 | 158 | 0.707977 | 4.415094 | false | false | false | false |
smmribeiro/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/PackageOperations.kt | 2 | 1040 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageOperationType
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion
import kotlinx.coroutines.Deferred
internal data class PackageOperations(
val targetModules: TargetModules,
val primaryOperations: Deferred<List<PackageSearchOperation<*>>>,
val removeOperations: Deferred<List<PackageSearchOperation<*>>>,
val targetVersion: NormalizedPackageVersion<*>?,
val primaryOperationType: PackageOperationType?,
val repoToAddWhenInstalling: RepositoryModel?
) {
val canInstallPackage = primaryOperationType == PackageOperationType.INSTALL
val canUpgradePackage = primaryOperationType == PackageOperationType.UPGRADE
val canSetPackage = primaryOperationType == PackageOperationType.SET
}
| apache-2.0 | 0834dd19d339c48284270e0f54b1cabf | 51 | 105 | 0.831731 | 5.502646 | false | false | false | false |
LouisCAD/Splitties | modules/views-dsl/src/androidMain/kotlin/splitties/views/dsl/core/ScrollWrapping.kt | 1 | 1142 | /*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.views.dsl.core
import android.view.View
import android.widget.HorizontalScrollView
import android.widget.ScrollView
import androidx.annotation.IdRes
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
inline fun View.wrapInScrollView(
@IdRes id: Int = View.NO_ID,
height: Int = wrapContent,
initView: ScrollView.() -> Unit = {}
): ScrollView {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return view(::ScrollView, id) {
add(this@wrapInScrollView, lParams(width = matchParent, height = height))
}.apply(initView)
}
inline fun View.wrapInHorizontalScrollView(
@IdRes id: Int = View.NO_ID,
height: Int = wrapContent,
initView: HorizontalScrollView.() -> Unit = {}
): HorizontalScrollView {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return view(::HorizontalScrollView, id) {
add(this@wrapInHorizontalScrollView, lParams(width = matchParent, height = height))
}.apply(initView)
}
| apache-2.0 | 888b03ac2db394052915c10e11b5ee3d | 32.588235 | 109 | 0.732049 | 4.245353 | false | false | false | false |
TimePath/launcher | src/main/kotlin/com/timepath/launcher/ui/swing/RepositoryManagerPanel.kt | 1 | 6039 | package com.timepath.launcher.ui.swing
import com.timepath.launcher.data.Repository
import com.timepath.swing.ObjectBasedTableModel
import java.awt.event.ActionEvent
import javax.swing.*
abstract class RepositoryManagerPanel protected constructor() : JPanel() {
protected var addButton: JButton
protected var removeButton: JButton
protected var jPanel1: JPanel
protected var jScrollPane1: JScrollPane? = null
protected var jTable1: JTable? = null
protected var model: ObjectBasedTableModel<Repository>? = null
init {
jTable1 = JTable(object : ObjectBasedTableModel<Repository>() {
override fun columns(): Array<String> {
return COLUMNS
}
override fun getColumnClass(columnIndex: Int): Class<*> {
when (columnIndex) {
0 -> return javaClass<String>()
1 -> return javaClass<String>()
2 -> return javaClass<Boolean>()
}
return super.getColumnClass(columnIndex)
}
override fun get(o: Repository, columnIndex: Int): Any? {
when (columnIndex) {
0 -> return o.getName()
1 -> return o.location
2 -> return o.isEnabled()
}
return null
}
override fun isCellEditable(e: Repository, columnIndex: Int) = when (columnIndex) {
0 -> false
1 -> true
2 -> true
else -> super.isCellEditable(e, columnIndex)
}
}.let {
model = it
it
})
jScrollPane1 = JScrollPane(jTable1)
addButton = JButton(object : AbstractAction("Add from URL") {
override fun actionPerformed(e: ActionEvent) {
addActionPerformed(e)
}
})
removeButton = JButton(object : AbstractAction("Remove selected") {
override fun actionPerformed(e: ActionEvent) {
removeActionPerformed(e)
}
})
jPanel1 = JPanel()
val jPanel1Layout = GroupLayout(jPanel1)
jPanel1.setLayout(jPanel1Layout)
jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addContainerGap().addComponent(addButton).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(removeButton).addContainerGap(150, java.lang.Short.MAX_VALUE.toInt())))
jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(jPanel1Layout.createSequentialGroup().addContainerGap().addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(addButton).addComponent(removeButton)).addContainerGap(GroupLayout.DEFAULT_SIZE, java.lang.Short.MAX_VALUE.toInt())))
val layout = GroupLayout(this)
setLayout(layout)
layout.setHorizontalGroup(
layout.createParallelGroup(
GroupLayout.Alignment.LEADING)
.addGroup(
GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addContainerGap()
.addGroup(
layout.createParallelGroup(
GroupLayout.Alignment.TRAILING)
.addComponent(
jPanel1,
GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE,
java.lang.Short.MAX_VALUE.toInt())
.addComponent(
jScrollPane1!!,
GroupLayout.PREFERRED_SIZE,
0,
java.lang.Short.MAX_VALUE.toInt()))
.addContainerGap()))
layout.setVerticalGroup(
layout.createParallelGroup(
GroupLayout.Alignment.LEADING)
.addGroup(
GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addContainerGap()
.addComponent(
jScrollPane1!!,
GroupLayout.DEFAULT_SIZE,
275,
java.lang.Short.MAX_VALUE.toInt())
.addPreferredGap(
LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1,
GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE,
GroupLayout.PREFERRED_SIZE).
addContainerGap()))
}
protected abstract fun addActionPerformed(evt: ActionEvent)
protected abstract fun removeActionPerformed(evt: ActionEvent)
public fun setRepositories(repositories: MutableList<Repository>) {
model!!.setRows(repositories)
}
companion object {
public val COLUMNS: Array<String> = arrayOf("Repository", "Location", "Enabled")
}
}
| artistic-2.0 | aa8f4916ce981b80eb367ded9e473a59 | 48.097561 | 374 | 0.485676 | 6.493548 | false | false | false | false |
erdo/asaf-project | fore-kt-android-network/src/main/java/co/early/fore/kt/net/apollo/CallProcessorApollo.kt | 1 | 5513 | package co.early.fore.kt.net.apollo
import co.early.fore.core.WorkMode
import co.early.fore.kt.core.Either
import co.early.fore.kt.core.coroutine.asyncMain
import co.early.fore.kt.core.delegate.Fore
import co.early.fore.kt.core.logging.Logger
import co.early.fore.net.apollo.ErrorHandler
import com.apollographql.apollo.ApolloCall
import com.apollographql.apollo.api.Error
import com.apollographql.apollo.api.Response
import com.apollographql.apollo.exception.ApolloException
import kotlinx.coroutines.Deferred
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
interface ApolloCaller<F> {
suspend fun <S> processCallAwait(
call: () -> ApolloCall<S>
): Either<F, CallProcessorApollo.SuccessResult<S>>
suspend fun <S> processCallAsync(
call: () -> ApolloCall<S>
): Deferred<Either<F, CallProcessorApollo.SuccessResult<S>>>
}
/**
* @param errorHandler Error handler for the service (interpreting HTTP codes, GraphQL errors
* etc). This error handler is often the same across a range of services required by the app.
* However, sometimes the APIs all have different error behaviours (say when the service APIs have
* been developed at different times, or by different teams or different third parties). In this
* case it might be easier to use a separate CallProcessorApollo instance (and ErrorHandler) for
* each micro service.
* @param logger (optional: ForeDelegateHolder will choose a sensible default)
* @param workMode (optional: ForeDelegateHolder will choose a sensible default) Testing: Apollo
* library is NOT setup to be able to run calls in a synchronous manner (unlike Retrofit), for this
* reason when testing the fore ApolloCallProcessor we still need to use count down latches even with
* workMode = SYNCHRONOUS
* @param allowPartialSuccesses (defaults to false) The GraphQL spec allows for success responses
* with qualified errors, like this: https://spec.graphql.org/draft/#example-90475 if true, you will
* receive these responses as successes, together with the list of partial errors that were attached
* in the response. If allowPartialSuccesses=false, these types of responses will be delivered as
* errors and the successful parts of the response will be dropped. Setting it to true is going to
* make keeping your domain layer and api layers separate a lot harder, and apart from in some highly
* optimised situations I'd recommend you keep it set to false.
*
* @param <F> The class type passed back in the event of a failure, Globally applicable
* failure message class, like an enum for example
*/
class CallProcessorApollo<F>(
private val errorHandler: ErrorHandler<F>,
private val logger: Logger? = null,
private val workMode: WorkMode? = null,
private val allowPartialSuccesses: Boolean = false
) : ApolloCaller<F> {
data class SuccessResult<S>(
val data: S,
val partialErrors: List<Error> = listOf(),
val extensions: Map<String, Any?> = hashMapOf(),
val isFromCache: Boolean = false
)
/**
* @param call functional type that returns a fresh instance of the ApolloCall to be processed
* @param <S> Success class you expect to be returned from the call (or Unit for an empty response)
*
* @returns Either<F, SuccessResult<S>>
*/
override suspend fun <S> processCallAwait(call: () -> ApolloCall<S>): Either<F, SuccessResult<S>> {
return processCallAsync(call).await()
}
/**
* @param call functional type that returns a fresh instance of the ApolloCall to be processed
* @param <S> Success class you expect to be returned from the call (or Unit for an empty response)
*
* @returns Deferred<Either<F, SuccessResult<S>>>
*/
override suspend fun <S> processCallAsync(call: () -> ApolloCall<S>): Deferred<Either<F, SuccessResult<S>>> {
return asyncMain(Fore.getWorkMode(workMode)) {
try {
suspendCoroutine { continuation ->
call().enqueue(object : ApolloCall.Callback<S>() {
override fun onResponse(response: Response<S>) {
continuation.resume(processSuccessResponse(response))
}
override fun onFailure(e: ApolloException) {
continuation.resume(processFailResponse(e, null))
}
})
}
} catch (t: Throwable) {
processFailResponse(t, null)
}
}
}
private fun <S> processSuccessResponse(
response: Response<S>
): Either<F, SuccessResult<S>> {
val data: S? = response.data
return if (data != null) {
if (!response.hasErrors() || allowPartialSuccesses) {
Either.right(SuccessResult(data, response.errors
?: mutableListOf(), response.extensions, response.isFromCache))
} else {
processFailResponse(null, response)
}
} else {
processFailResponse(null, response)
}
}
private fun <S> processFailResponse(
t: Throwable?, errorResponse: Response<*>?
): Either<F, SuccessResult<S>> {
if (t != null) {
Fore.getLogger(logger).e("processFailResponse() t:" + Thread.currentThread(), t)
}
return Either.left(errorHandler.handleError(t, errorResponse))
}
} | apache-2.0 | ff97f5f05eea9ee9c588221f5efa8004 | 42.078125 | 113 | 0.670053 | 4.504085 | false | false | false | false |
tlaukkan/kotlin-web-vr | client/src/vr/webvr/actuators/NodeActuator.kt | 1 | 3814 | package vr.webvr.actuators
import vr.CLIENT
import lib.threejs.Object3D
import lib.threejs.Texture
import lib.threejs.Vector3
import vr.network.model.Node
import vr.util.toJson
import vr.webvr.VrController
abstract class NodeActuator(var controller: VrController, var type: String) {
abstract fun construct(node: Node, onConstructed:(obj: Object3D?) -> Unit): Unit
abstract fun add(node: Node): Unit
protected fun add(node: Node, obj: Object3D) {
obj.name = node.url
updateObjectFromNode(obj, node)
updateInterpolator(node, null)
add(node.parentUrl, obj)
//controller.scene.add(obj)
}
protected fun add(parentUrl: String?, obj: Object3D) {
if (controller.orphans.containsKey(obj.name)) {
val orphanList = controller.orphans[obj.name]!!
for (orphan in orphanList) {
obj.add(orphan)
}
orphanList.clear()
controller.orphans.remove(obj.name)
}
if (parentUrl != null && parentUrl!!.size != 0) {
val parentObject = controller.scene.getObjectByName(parentUrl)
if (parentObject != null) {
parentObject.add(obj)
println("Added ${obj.name} to parent $parentUrl.")
} else {
if (!controller.orphans.containsKey(parentUrl)) {
controller.orphans[parentUrl] = mutableListOf()
}
controller.orphans[parentUrl]!!.add(obj)
println("Added orphan ${obj.name} as parent $parentUrl was not found.")
}
} else {
CLIENT!!.vrController!!.roomGroup.add(obj)
}
}
open fun update(node: Node, oldNode: Node) {
updateInterpolator(node, oldNode)
/*
val obj = controller.scene.getObjectByName(node.url)
if (obj != null) {
updateObjectFromNode(obj, node)
}
*/
}
private fun updateInterpolator(node: Node, oldNode: Node?) {
if (!controller.nodeInterpolators.containsKey(node.url)) {
val interpolator = NodeInterpolator(node.url)
controller.nodeInterpolators.put(node.url, interpolator)
if (oldNode != null) {
interpolator.initialize(CLIENT!!.renderTime, oldNode)
interpolator.update(CLIENT!!.renderTime, node)
//println("Added node interpolator for old node: " + node.url)
/*val oldPosition = Vector3()
CLIENT!!.vrController.getNodePositionToLocalCoordinates(oldNode, oldPosition)
val newPosition = Vector3()
CLIENT!!.vrController.getNodePositionToLocalCoordinates(node, newPosition)
println(newPosition.distanceTo(oldPosition))
println(toJson(node))
println(toJson(oldNode))*/
} else {
interpolator.initialize(CLIENT!!.renderTime, node)
//println("Added node interpolator for new node: " + node.url)
}
} else {
controller.nodeInterpolators[node.url]!!.update(CLIENT!!.renderTime, node)
}
}
open fun remove(node: Node) {
val obj = controller.scene.getObjectByName(node.url)
if (obj != null) {
controller.roomGroup.remove(obj)
}
}
fun updateObjectFromNode(obj: Object3D, node: Node) {
CLIENT!!.vrController!!.getNodePositionToLocalCoordinates(node, obj.position)
obj.quaternion.x = node.orientation.x
obj.quaternion.y = node.orientation.y
obj.quaternion.z = node.orientation.z
obj.quaternion.w = node.orientation.w
obj.scale.x = node.scale.x
obj.scale.y = node.scale.y
obj.scale.z = node.scale.z
}
} | mit | dc4428e073f2fbd9f511735feafa90c4 | 34.324074 | 93 | 0.5957 | 4.31448 | false | false | false | false |
TachiWeb/TachiWeb-Server | TachiServer/src/main/java/xyz/nulldev/ts/api/task/Task.kt | 1 | 1328 | /*
* Copyright 2016 Andy Bao
*
* 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 xyz.nulldev.ts.api.task
import java.time.LocalDateTime
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
/**
* Project: TachiServer
* Author: nulldev
* Creation Date: 30/09/16
*/
data class Task internal constructor(val taskID: Long) {
private val internalComplete = AtomicBoolean(false)
private val internalTaskStatus = AtomicReference("")
val creationTime: LocalDateTime = LocalDateTime.now()
var complete: Boolean
get() = internalComplete.get()
set(complete) = this.internalComplete.set(complete)
var taskStatus: String
get() = internalTaskStatus.get()
set(newTaskStatus) = this.internalTaskStatus.set(newTaskStatus)
} | apache-2.0 | 587a04c9131521cc37f068ae2ca23e44 | 32.225 | 75 | 0.738705 | 4.215873 | false | false | false | false |
sksamuel/ktest | kotest-assertions/kotest-assertions-shared/src/commonMain/kotlin/io/kotest/assertions/show/StringShow.kt | 1 | 494 | package io.kotest.assertions.show
object StringShow : Show<String> {
private fun String.wrap() = """"$this""""
fun showNoWrap(a: String): Printed = when {
a == "" -> "<empty string>".printed()
a.isBlank() -> a.replace(" ", "\\s").wrap().printed()
else -> a.printed()
}
override fun show(a: String): Printed = when {
a == "" -> "<empty string>".printed()
a.isBlank() -> a.replace(" ", "\\s").wrap().printed()
else -> a.wrap().printed()
}
}
| mit | 84ff0eee4ee1bb53d0ffb6dbbc8ed55b | 26.444444 | 59 | 0.536437 | 3.553957 | false | true | false | false |
naivesound/scherzo | android/app/src/main/java/com/naivesound/scherzo/PianoKeyboard.kt | 1 | 6479 | package com.naivesound.scherzo
import android.content.Context
import android.graphics.Rect
import android.util.DisplayMetrics
import android.util.SparseIntArray
import android.view.MotionEvent
import android.view.View
import java.util.HashSet
import trikita.anvil.DSL.*
import trikita.anvil.Anvil
import trikita.anvil.RenderableView
class PianoKeyboard(c: Context) : RenderableView(c) {
private var mWidth: Int = 0
private var mHeight: Int = 0
private val mTouchedViews: MutableMap<View, MutableSet<Int>> = HashMap()
private val mPrevX = SparseIntArray()
private val mPrevY = SparseIntArray()
private val mKeyCount = 12
private val mFirstKey = 48
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
mWidth = View.MeasureSpec.getSize(widthMeasureSpec)
mHeight = View.MeasureSpec.getSize(heightMeasureSpec)
this.setMeasuredDimension(mWidth, mHeight)
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
Anvil.render()
}
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
return true
}
override fun onTouchEvent(ev: MotionEvent): Boolean {
val action = ev.actionMasked
when (action) {
MotionEvent.ACTION_POINTER_DOWN, MotionEvent.ACTION_DOWN -> {
val pointerId = ev.getPointerId(ev.actionIndex)
mPrevX.put(pointerId, ev.getX(ev.actionIndex).toInt())
mPrevY.put(pointerId, ev.getY(ev.actionIndex).toInt())
dispatchTouchDown(findViewByPointer(ev, ev.actionIndex), ev)
}
MotionEvent.ACTION_OUTSIDE, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_UP -> run {
val it = mTouchedViews.keys.iterator()
while (it.hasNext()) {
val v = it.next()
if (dispatchTouchUp(v, ev)) {
it.remove()
}
}
}
MotionEvent.ACTION_MOVE -> for (i in 0..ev.pointerCount - 1) {
val id = ev.getPointerId(i)
val x = ev.getX(i).toInt()
val y = ev.getY(i).toInt()
val minDistance = (24 * (resources.displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)).toInt()
if (Math.abs(mPrevX.get(id, x) - x) > minDistance || Math.abs(mPrevY.get(id, y) - y) > minDistance) {
mPrevX.put(id, x)
mPrevY.put(id, y)
} else {
continue
}
val newView = findViewByPointer(ev, i)
if (newView != null) {
val it = mTouchedViews.keys.iterator()
while (it.hasNext()) {
val oldView = it.next()
if (oldView !== newView) {
if (dispatchTouchUp(oldView, ev)) {
it.remove()
}
}
}
dispatchTouchDown(newView, ev)
}
}
}
return true
}
private fun dispatchTouchDown(v: View?, ev: MotionEvent) {
if (v != null) {
if (mTouchedViews[v] == null) {
val e = MotionEvent.obtain(ev.downTime, ev.eventTime,
MotionEvent.ACTION_DOWN,
ev.getX(ev.actionIndex), ev.getY(ev.actionIndex), 0)
mTouchedViews.put(v, HashSet<Int>())
v.dispatchTouchEvent(e)
}
mTouchedViews[v]!!.add(ev.getPointerId(ev.actionIndex))
}
}
private fun dispatchTouchUp(v: View?, ev: MotionEvent): Boolean {
val id = ev.getPointerId(ev.actionIndex)
if (v != null && mTouchedViews[v] != null && mTouchedViews[v]!!.contains(id)) {
mTouchedViews[v]!!.remove(id)
if (mTouchedViews[v]!!.isEmpty()) {
val e = MotionEvent.obtain(ev.downTime, ev.eventTime,
MotionEvent.ACTION_UP,
ev.getX(ev.actionIndex), ev.getY(ev.actionIndex), 0)
v.dispatchTouchEvent(e)
return true
}
}
return false
}
private fun findViewByPointer(ev: MotionEvent, index: Int): View? {
val x = (ev.getX(index) + x).toInt()
val y = (ev.getY(index) + y).toInt()
return findViewByPos(x, y)
}
private fun findViewByPos(x: Int, y: Int): View? {
for (i in childCount - 1 downTo 0) {
val v = getChildAt(i)
val pos = IntArray(2)
v.getLocationOnScreen(pos)
val rect = Rect(pos[0], pos[1], pos[0] + v.width, pos[1] + v.height)
if (rect.contains(x, y)) {
return v
}
}
return null
}
override fun view() {
keys(false)
keys(true)
}
private fun keys(black: Boolean) {
var numWhiteKeys = 0
for (i in 0..mKeyCount - 1) {
if (!BLACK_KEYS[(mFirstKey + i) % 12]) {
numWhiteKeys++
}
}
val keyWidth = mWidth / numWhiteKeys
var leftOffset = 0
for (i in 0..mKeyCount - 1) {
val index = (mFirstKey + i) % 12
val offset = leftOffset
val key = mFirstKey + i
if (BLACK_KEYS[index] && black) {
v(MidiKeyView::class.java, {
size(keyWidth - 2 * dip(3), mHeight / 2)
x((offset - keyWidth / 2).toFloat())
tag(key)
margin(dip(3))
backgroundColor(0xff333333.toInt())
})
}
if (!BLACK_KEYS[index] && !black) {
v(MidiKeyView::class.java, {
size(keyWidth - 2 * dip(3), FILL)
tag(key)
x(offset.toFloat())
margin(dip(3))
backgroundColor(0xffe1e1e1.toInt())
})
}
if (!BLACK_KEYS[index]) {
leftOffset = leftOffset + keyWidth
}
}
}
companion object {
private val TAG = "PianoKeyboard"
internal var BLACK_KEYS = booleanArrayOf(false, true, false, true, false, false, true, false, true, false, true, false)
}
}
| gpl-3.0 | 5cb9a8539056b1ef95a19228e5e37969 | 34.021622 | 128 | 0.514277 | 4.380663 | false | false | false | false |
DarkToast/JavaDeepDive | src/main/kotlin/deepdive/functional/monads/ResultUsage.kt | 1 | 2605 | package deepdive.functional.monads
import com.fasterxml.jackson.databind.ObjectMapper
// Domain model
data class BaseFee(val value: Float)
data class Tariff(val baseFee: BaseFee)
data class Contract(val tariff: Tariff)
data class Customer(val contract: Contract)
// Data validation
data class ValidationFailure(val failure: String)
data class ValidationFailed(val failures: List<ValidationFailure>)
// Http response stuff
data class HttpStatus(val value: Int)
data class HttpResponse<out T>(val httpStatus: HttpStatus, val entity: T)
// Business functions:
fun getBaseFee(tariff: Tariff): Result<BaseFee, ValidationFailed> = Success(tariff.baseFee)
fun getTariff(contract: Contract): Result<Tariff, ValidationFailed> = Success(contract.tariff)
fun getContract(customer: Customer): Result<Contract, ValidationFailed> = Success(customer.contract)
// Mapping function -> Business rules etc.
val customerToTariffBaseFee: (Customer) -> Result<BaseFee, ValidationFailed> = { customer ->
getContract(customer)
.flatMap { contract -> getTariff(contract) }
.flatMap { tariff -> getBaseFee(tariff) }
}
// Helper function as "get entity from ... db, http, ... etc." side effect.
fun getCustomer(): Customer = Customer(Contract(Tariff(BaseFee(12.99F))))
// The overall application.
fun main(args: Array<String>) {
val customerInput = getCustomer()
val responseOutput: HttpResponse<String> =
Result.of<Customer, ValidationFailed>(customerInput)
.flatMap(customerToTariffBaseFee) // Returns `Result<BaseFee, ValidationFailed>`
.map { baseFee ->
val json = ObjectMapper().writer().writeValueAsString(baseFee)
HttpResponse(HttpStatus(200), json)
} // Returns `Result<HttpResponse, ValidationFailed>`
.recover { failure ->
val json = ObjectMapper().writer().withDefaultPrettyPrinter().writeValueAsString(failure)
Success(HttpResponse(HttpStatus(400), json))
} // Returns `Result<HttpResponse, ValidationFailed>`
.getOrElse(HttpResponse(HttpStatus(500), "Unknown error occurred"))
println(responseOutput)
}
/*
Failure(ValidationFailed(listOf(
ValidationFailure("contract has no tariff"),
ValidationFailure("contract is expired")
)))
*/ | gpl-3.0 | 62bcd53536da95b147ae000c5f059cbb | 32.410256 | 139 | 0.635701 | 4.75365 | false | false | false | false |
google-developer-training/basic-android-kotlin-compose-training-superheroes | app/src/main/java/com/example/superheroes/MainActivity.kt | 1 | 2942 | /*
* Copyright (c) 2022 The Android Open Source Project
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.superheroes
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
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.example.superheroes.model.HeroesRepository
import com.example.superheroes.ui.theme.SuperheroesTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
SuperheroesTheme {
SuperheroesApp()
}
}
}
}
/**
* Composable that displays an app bar and a list of heroes.
*/
@Composable
fun SuperheroesApp() {
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar = {
TopAppBar()
}
) {
/* Important: It is not a good practice to access data source directly from the UI.
In later units you will learn how to use ViewModel in such scenarios that takes the
data source as a dependency and exposes heroes.
*/
val heroes = HeroesRepository.heroes
HeroesList(heroes = heroes, Modifier.padding(it))
}
}
/**
* Composable that displays a Top Bar with an icon and text.
*
* @param modifier modifiers to set to this composable
*/
@Composable
fun TopAppBar(modifier: Modifier = Modifier) {
Box(
modifier = modifier
.fillMaxWidth()
.size(56.dp),
contentAlignment = Alignment.Center
) {
Text(
text = stringResource(R.string.app_name),
style = MaterialTheme.typography.h1,
)
}
}
@Preview(showBackground = true)
@Composable
fun SuperHeroesPreview() {
SuperheroesTheme {
SuperheroesApp()
}
}
| apache-2.0 | 3e7e0f0bb3267bbdcf9e4323e21ecf71 | 29.645833 | 91 | 0.71346 | 4.42406 | false | false | false | false |
blademainer/intellij-community | plugins/settings-repository/src/copyAppSettingsToRepository.kt | 1 | 3393 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository
import com.intellij.configurationStore.ROOT_CONFIG
import com.intellij.configurationStore.StateStorageManagerImpl
import com.intellij.ide.actions.ExportSettingsAction
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtilRt
import java.io.File
fun copyLocalConfig(storageManager: StateStorageManagerImpl = ApplicationManager.getApplication()!!.stateStore.stateStorageManager as StateStorageManagerImpl) {
val streamProvider = storageManager.streamProvider!! as IcsManager.IcsStreamProvider
val fileToComponents = ExportSettingsAction.getExportableComponentsMap(true, false, storageManager)
for (file in fileToComponents.keySet()) {
val absolutePath = FileUtilRt.toSystemIndependentName(file.absolutePath)
var fileSpec = storageManager.collapseMacros(absolutePath)
LOG.assertTrue(!fileSpec.contains(ROOT_CONFIG))
if (fileSpec.equals(absolutePath)) {
// we have not experienced such problem yet, but we are just aware
val canonicalPath = FileUtilRt.toSystemIndependentName(file.canonicalPath)
if (!canonicalPath.equals(absolutePath)) {
fileSpec = storageManager.collapseMacros(canonicalPath)
}
}
val roamingType = getRoamingType(fileToComponents.get(file))
if (file.isFile) {
val fileBytes = FileUtil.loadFileBytes(file)
streamProvider.doSave(fileSpec, fileBytes, fileBytes.size(), roamingType)
}
else {
saveDirectory(file, fileSpec, roamingType, streamProvider)
}
}
}
private fun saveDirectory(parent: File, parentFileSpec: String, roamingType: RoamingType, streamProvider: IcsManager.IcsStreamProvider) {
val files = parent.listFiles()
if (files != null) {
for (file in files) {
val childFileSpec = parentFileSpec + '/' + file.name
if (file.isFile) {
val fileBytes = FileUtil.loadFileBytes(file)
streamProvider.doSave(childFileSpec, fileBytes, fileBytes.size(), roamingType)
}
else {
saveDirectory(file, childFileSpec, roamingType, streamProvider)
}
}
}
}
private fun getRoamingType(components: Collection<ExportableComponent>): RoamingType {
for (component in components) {
if (component is ExportSettingsAction.ExportableComponentItem) {
return component.roamingType
}
else if (component is PersistentStateComponent<*>) {
val stateAnnotation = component.javaClass.getAnnotation(State::class.java)
if (stateAnnotation != null) {
val storages = stateAnnotation.storages
if (!storages.isEmpty()) {
return storages[0].roamingType
}
}
}
}
return RoamingType.DEFAULT
} | apache-2.0 | 2402a9ed374bce746821fc41ec6b2155 | 38.465116 | 160 | 0.744179 | 4.931686 | false | true | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/ui/txdetails/TxDetailsController.kt | 1 | 16130 | /**
* BreadWallet
*
* Created by Drew Carlson <[email protected]> on 9/17/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.txdetails
import android.animation.LayoutTransition
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.breadwallet.R
import com.breadwallet.breadbox.formatCryptoForUi
import com.breadwallet.databinding.TransactionDetailsBinding
import com.breadwallet.ui.formatFiatForUi
import com.breadwallet.tools.manager.BRClipboardManager
import com.breadwallet.tools.manager.BRSharedPrefs
import com.breadwallet.tools.util.BRDateUtil
import com.breadwallet.tools.util.Utils
import com.breadwallet.ui.BaseMobiusController
import com.breadwallet.ui.ViewEffect
import com.breadwallet.ui.changehandlers.DialogChangeHandler
import com.breadwallet.ui.flowbind.clicks
import com.breadwallet.ui.flowbind.textChanges
import com.breadwallet.ui.models.TransactionState
import com.breadwallet.ui.txdetails.TxDetails.E
import com.breadwallet.ui.txdetails.TxDetails.F
import com.breadwallet.ui.txdetails.TxDetails.M
import com.breadwallet.util.isBitcoinLike
import drewcarlson.mobius.flow.FlowTransformer
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import org.kodein.di.direct
import org.kodein.di.erased.instance
import java.math.BigDecimal
import java.text.NumberFormat
import java.util.Date
/**
* TODO: Updated to support new APIs and improve general UX.
* Remaining Issues:
* - Expose formatted currencies in Model
* - Improve gas price handling
* - Validate state displays (handle deleted state?)
* - For received transactions, retrieve historical exchange rate at time of first confirmation
*/
class TxDetailsController(
args: Bundle? = null
) : BaseMobiusController<M, E, F>(args) {
companion object {
private const val CURRENCY_CODE = "currencyCode"
private const val TRANSFER_HASH = "transferHash"
}
constructor(currencyCode: String, transferHash: String) : this(
bundleOf(
CURRENCY_CODE to currencyCode,
TRANSFER_HASH to transferHash
)
)
private val currencyCode = arg<String>(CURRENCY_CODE)
private val transactionHash = arg<String>(TRANSFER_HASH)
init {
overridePopHandler(DialogChangeHandler())
overridePushHandler(DialogChangeHandler())
}
override val init = TxDetailsInit
override val update = TxDetailsUpdate
override val defaultModel: M
get() = M.createDefault(
currencyCode,
transactionHash,
BRSharedPrefs.getPreferredFiatIso(),
BRSharedPrefs.isCryptoPreferred()
)
override val flowEffectHandler: FlowTransformer<F, E>
get() = createTxDetailsHandler(
checkNotNull(applicationContext),
direct.instance(),
direct.instance()
)
private val binding by viewBinding(TransactionDetailsBinding::inflate)
override fun onCreateView(view: View) {
super.onCreateView(view)
// NOTE: This allows animateLayoutChanges to properly animate details show/hide
(view as ViewGroup).layoutTransition.enableTransitionType(LayoutTransition.CHANGING)
with(binding) {
val color = txToFromAddress.textColors.defaultColor
memoInput.setTextColor(color)
feePrimaryLabel.text = resources!!.getString(R.string.Send_fee, "")
view.setOnClickListener {
router.popCurrentController()
}
}
}
override fun bindView(modelFlow: Flow<M>): Flow<E> {
return with(binding) {
merge(
closeButton.clicks().map { E.OnClosedClicked },
showHideDetails.clicks().map { E.OnShowHideDetailsClicked },
memoInput.textChanges().map { E.OnMemoChanged(it) },
transactionId.clicks().map { E.OnTransactionHashClicked },
txToFromAddress.clicks().map { E.OnAddressClicked },
)
}
}
override fun onDetach(view: View) {
super.onDetach(view)
view.setOnClickListener(null)
Utils.hideKeyboard(activity)
}
override fun handleViewEffect(effect: ViewEffect) {
when (effect) {
is F.CopyToClipboard -> copyToClipboard(effect.text)
}
}
@Suppress("LongMethod", "ComplexMethod")
override fun M.render() {
val res = checkNotNull(resources)
with(binding) {
ifChanged(M::showDetails) {
detailsContainer.isVisible = showDetails
showHideDetails.setText(
when {
showDetails -> R.string.TransactionDetails_hideDetails
else -> R.string.TransactionDetails_showDetails
}
)
}
ifChanged(M::isFeeForToken) {
if (isFeeForToken) { // it's a token transfer ETH tx
memoInput.setText(
String.format(
res.getString(R.string.Transaction_tokenTransfer),
feeToken
)
)
memoInput.isFocusable = false
}
}
ifChanged(M::isReceived) {
showSentViews(!isReceived)
txAction.setText(
when {
isReceived -> R.string.TransactionDetails_titleReceived
else -> R.string.TransactionDetails_titleSent
}
)
txToFrom.setText(
when {
isReceived -> if (currencyCode.isBitcoinLike()) {
R.string.TransactionDetails_addressViaHeader
} else {
R.string.TransactionDetails_addressFromHeader
}
else -> R.string.TransactionDetails_addressToHeader
}
)
txAmount.setTextColor(
res.getColor(
when {
isReceived -> R.color.transaction_amount_received_color
else -> R.color.total_assets_usd_color
}
)
)
}
if (!isReceived) {
ifChanged(
M::isEth,
M::gasPrice,
M::gasLimit
) {
showEthViews(isEth)
if (isEth) {
val formatter = NumberFormat.getIntegerInstance().apply {
maximumFractionDigits = 0
isGroupingUsed = false
}
gasPrice.text = "%s %s".format([email protected](), "gwei")
gasLimit.text = formatter.format([email protected]).toString()
}
}
ifChanged(M::transactionTotal) {
feeSecondary.text =
transactionTotal.formatCryptoForUi(currencyCode, MAX_CRYPTO_DIGITS)
}
ifChanged(
M::fee,
M::isErc20
) {
showTotalCost(!isErc20)
feePrimary.text = fee.formatCryptoForUi(feeCurrency, MAX_CRYPTO_DIGITS)
}
}
ifChanged(M::blockNumber) {
showConfirmedView(blockNumber != 0)
}
ifChanged(
M::fiatAmountWhenSent,
M::exchangeCurrencyCode,
M::fiatAmountNow,
M::preferredFiatIso
) {
val formattedAmountNow = fiatAmountNow.formatFiatForUi(preferredFiatIso)
val showWhenSent = fiatAmountWhenSent.compareTo(BigDecimal.ZERO) != 0
labelWhenSent.text = res.getString(
when {
isReceived -> R.string.TransactionDetails_amountWhenReceived
else -> R.string.TransactionDetails_amountWhenSent
},
fiatAmountWhenSent.formatFiatForUi(exchangeCurrencyCode),
formattedAmountNow
)
amountNow.text = formattedAmountNow
labelWhenSent.visibility = if (showWhenSent) View.VISIBLE else View.INVISIBLE
amountNow.visibility = if (!showWhenSent) View.VISIBLE else View.INVISIBLE
}
ifChanged(M::toOrFromAddress) {
// TODO: Do we need a string res for no hash text?
txToFromAddress.text = when {
toOrFromAddress.isNotBlank() -> toOrFromAddress
else -> "<unknown>"
}
}
ifChanged(M::cryptoTransferredAmount) {
txAmount.text = cryptoTransferredAmount.formatCryptoForUi(
currencyCode,
MAX_CRYPTO_DIGITS,
!isReceived
)
}
ifChanged(M::memoLoaded) {
if (memoLoaded && !isFeeForToken) {
memoInput.setText(
if (gift?.recipientName.isNullOrBlank()) {
memo
} else {
String.format(res.getString(R.string.TransactionDetails_giftedTo, gift?.recipientName))
}
)
}
}
ifChanged(
M::exchangeCurrencyCode,
M::preferredFiatIso,
M::exchangeRate,
M::isReceived
) {
if (isReceived) {
groupExchangeRateSection.isVisible = false
} else {
exchangeRateLabel.setText(R.string.Transaction_exchangeOnDaySent)
exchangeRate.text = [email protected](
when {
exchangeCurrencyCode.isNotBlank() -> exchangeCurrencyCode
else -> preferredFiatIso
}
)
}
}
ifChanged(M::confirmationDate) {
txDate.text = BRDateUtil.getFullDate((confirmationDate ?: Date()).time)
}
ifChanged(M::transactionHash) {
transactionId.text = transactionHash
}
ifChanged(M::confirmedInBlockNumber) {
confirmedInBlockNumber.text = [email protected]
}
ifChanged(M::confirmations) {
confirmationsValue.text = confirmations.toString()
}
ifChanged(M::transactionState) {
when (transactionState) {
TransactionState.CONFIRMED -> {
if (isCompleted) {
txStatus.setCompoundDrawablesRelativeWithIntrinsicBounds(
R.drawable.checkmark_circled,
0,
0,
0
)
txStatus.setText(R.string.Transaction_complete)
} else {
txStatus.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)
txStatus.setText(R.string.Transaction_confirming)
}
}
TransactionState.FAILED -> {
txStatus.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)
txStatus.setText(R.string.TransactionDetails_initializedTimestampHeader)
}
TransactionState.CONFIRMING -> {
txStatus.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)
txStatus.setText(R.string.Transaction_confirming)
}
}
}
ifChanged(M::destinationTag) {
if (destinationTag != null) {
layoutDestinationTag.isVisible = true
destinationTagDivider.isVisible = true
if (destinationTag.value.isNullOrEmpty()) {
destinationTagValue.setText(R.string.TransactionDetails_destinationTag_EmptyHint)
} else {
destinationTagValue.text = destinationTag.value
}
}
}
ifChanged(M::hederaMemo) {
val hederaMemo = hederaMemo
if (hederaMemo != null) {
layoutHederaMemo.isVisible = true
hederaMemoDivider.isVisible = true
if (hederaMemo.value.isNullOrEmpty()) {
hederaMemoValue.setText(R.string.TransactionDetails_destinationTag_EmptyHint)
} else {
hederaMemoValue.text = hederaMemo.value
}
}
}
ifChanged(M::gift) { gift ->
val gone = gift?.keyData.isNullOrBlank() ||
gift?.reclaimed == true ||
gift?.claimed == true
layoutGift.isGone = gone
giftDivider.isGone = gone
}
}
}
private fun showSentViews(show: Boolean) {
with(binding) {
feePrimaryContainer.isVisible = show
feeSecondaryContainer.isVisible = show
feePrimaryDivider.isVisible = show
feeSecondaryDivider.isVisible = show
}
showEthViews(show)
}
private fun showEthViews(show: Boolean) {
with(binding) {
gasPriceContainer.isVisible = show
gasLimitContainer.isVisible = show
gasPriceDivider.isVisible = show
gasLimitDivider.isVisible = show
}
}
private fun showTotalCost(show: Boolean) {
with(binding) {
feeSecondaryContainer.isVisible = show
feeSecondaryDivider.isVisible = show
}
}
private fun showConfirmedView(show: Boolean) {
with(binding) {
confirmedContainer.isVisible = show
confirmedDivider.isVisible = show
confirmationsDivider.isVisible = show
confirmationsContainer.isVisible = show
}
}
private fun copyToClipboard(text: String) {
BRClipboardManager.putClipboard(text)
toastLong(R.string.Receive_copied)
}
}
| mit | c82f774ccb1fddc7ffc7254d0319158b | 36.165899 | 115 | 0.554495 | 5.405496 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/tracer/Traceable.kt | 1 | 4262 | package org.evomaster.core.search.tracer
import org.evomaster.core.search.service.mutator.EvaluatedMutation
/**
* Traceable represents an element whose history can be tracked.
* @property trackOperator is used to attach additional information regarding how it evolved, e.g., structure mutator or standard mutator. it is only nullable when tracking is disabled.
* @property index indicates when the element is created. with mio algorithm, it can be assigned as evaluated actions/individuals
* @property evaluatedResult represents a result of the element evaluated based on eg Archive when it is created. it is nullable if it is not necessary to collect such info, eg, only tracking individual
* @property tracking contains a history of the element.
*
* Note that [this] element might be not the last one in this history because the evolution is not always towards optimal direction.
*/
interface Traceable {
var trackOperator: TrackOperator?
var index : Int
var evaluatedResult: EvaluatedMutation?
var tracking: TrackingHistory<out Traceable>?
fun tagOperator(operator: TrackOperator?, index: Int){
trackOperator = operator
this.index = index
}
companion object{
const val DEFAULT_INDEX = -1
}
fun <T: Traceable> wrapWithTracking(evaluatedResult: EvaluatedMutation?, maxLength: Int, history: MutableList<T>){
wrapped()
this.evaluatedResult = evaluatedResult
this.tracking = TrackingHistory(maxLength, history)
}
fun <T: Traceable> wrapWithTracking(evaluatedResult: EvaluatedMutation?, trackingHistory: TrackingHistory<T>?){
wrapped()
if (this.evaluatedResult == null || evaluatedResult!=null)
this.evaluatedResult = evaluatedResult
this.tracking = trackingHistory
}
fun wrapWithEvaluatedResults(evaluatedResult: EvaluatedMutation?){
this.evaluatedResult = evaluatedResult
}
private fun wrapped(){
if (evaluatedResult != null || tracking != null) throw IllegalStateException("evaluated result or history has been initialized")
}
/**
* @param next is an evolved/refined element based on [this],
* e.g., EvaluatedIndividual is always created from fitness function based on individual, which does not rely on previous Evaluated individual
*
* @param copyFilter indicates how to restore element in tracking
* @param evaluatedResult indicates if the next is effective mutation
*
* @return an newly created TraceableElement regarding [next]
*/
fun next(next: Traceable, copyFilter: TraceableElementCopyFilter, evaluatedResult: EvaluatedMutation) : Traceable?
/**
* @param options indicates the option to copy the element in the tracking
*/
fun copy(options: TraceableElementCopyFilter) : Traceable
/**
* push latest element the tracking
*/
fun <T : Traceable> pushLatest(next: T){
(tracking as? TrackingHistory<T>)?.update(next)
?: throw IllegalStateException("tracking history should not be null")
}
fun <T : Traceable> getLast(n : Int, resultRange: IntRange? = null) : List<T>{
return (tracking as? TrackingHistory<T>)?.history?.filter { resultRange == null || (it.evaluatedResult?.run { this.value in resultRange } ?: true)}?.
run {
if (size < n)
this
else
subList(size - n, size)
} ?: throw IllegalStateException("the element is not tracked")
}
fun <T: Traceable> getByIndex(index : Int) : T?{
return ((tracking as? TrackingHistory<T>)?: throw IllegalStateException("tracking should not be null")).history?.find {
it.index == index
}
}
}
data class TrackingHistory<T : Traceable>(
val maxLength: Int,
val history : MutableList<T> = mutableListOf()
){
fun copy(copyFilter: TraceableElementCopyFilter) : TrackingHistory<T> {
return TrackingHistory(maxLength, history.map { (it.copy(copyFilter) as T)}.toMutableList())
}
fun update(next: T){
if (maxLength == 0) return
if (history.size == maxLength)
history.removeAt(0)
history.add(next)
}
}
| lgpl-3.0 | 52aca80772e7ed4a172f917567281d3d | 36.385965 | 202 | 0.679962 | 4.688669 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/korau/format/atrac3plus/ChannelUnitContext.kt | 1 | 1970 | package com.soywiz.korau.format.atrac3plus
import com.soywiz.korau.format.atrac3plus.Atrac3plusDecoder.Companion.ATRAC3P_PQF_FIR_LEN
import com.soywiz.korau.format.atrac3plus.Atrac3plusDecoder.Companion.ATRAC3P_SUBBANDS
/** Channel unit parameters */
class ChannelUnitContext {
// Channel unit variables
var unitType: Int = 0 ///< unit type (mono/stereo)
var numQuantUnits: Int = 0
var numSubbands: Int = 0
var usedQuantUnits: Int = 0 ///< number of quant units with coded spectrum
var numCodedSubbands: Int = 0 ///< number of subbands with coded spectrum
var muteFlag: Boolean = false ///< mute flag
var useFullTable: Boolean = false ///< 1 - full table list, 0 - restricted one
var noisePresent: Boolean = false ///< 1 - global noise info present
var noiseLevelIndex: Int = 0 ///< global noise level index
var noiseTableIndex: Int = 0 ///< global noise RNG table index
var swapChannels = BooleanArray(ATRAC3P_SUBBANDS) ///< 1 - perform subband-wise channel swapping
var negateCoeffs = BooleanArray(ATRAC3P_SUBBANDS) ///< 1 - subband-wise IMDCT coefficients negation
var channels = arrayOf(Channel(0), Channel(1))
// Variables related to GHA tones
var waveSynthHist = arrayOf(WaveSynthParams(), WaveSynthParams()) ///< waves synth history for two frames
var wavesInfo: WaveSynthParams = waveSynthHist[0]
var wavesInfoPrev: WaveSynthParams = waveSynthHist[1]
var ipqfCtx = arrayOf(IPQFChannelContext(), IPQFChannelContext())
var prevBuf = Array(2) { FloatArray(Atrac3plusDecoder.ATRAC3P_FRAME_SAMPLES) } ///< overlapping buffer
class IPQFChannelContext {
var buf1 = Array(ATRAC3P_PQF_FIR_LEN * 2) { FloatArray(8) }
var buf2 = Array(ATRAC3P_PQF_FIR_LEN * 2) { FloatArray(8) }
var pos: Int = 0
}
}
| mit | 561a47b2c90c10fc2324980cbfc484a6 | 53.722222 | 107 | 0.655838 | 3.499112 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/kpspemu/hle/modules/sceSuspendForUser.kt | 1 | 1488 | package com.soywiz.kpspemu.hle.modules
import com.soywiz.kpspemu.*
import com.soywiz.kpspemu.cpu.*
import com.soywiz.kpspemu.hle.*
@Suppress("UNUSED_PARAMETER")
class sceSuspendForUser(emulator: Emulator) :
SceModule(emulator, "sceSuspendForUser", 0x40000011, "sysmem.prx", "sceSystemMemoryManager") {
fun sceKernelPowerLock(lockType: Int): Int {
return 0
}
fun sceKernelPowerUnlock(lockType: Int): Int {
return 0
}
fun sceKernelPowerTick(value: Int): Int {
return 0
}
fun sceKernelVolatileMemLock(cpu: CpuState): Unit = UNIMPLEMENTED(0x3E0271D3)
fun sceKernelVolatileMemTryLock(cpu: CpuState): Unit = UNIMPLEMENTED(0xA14F40B2)
fun sceKernelVolatileMemUnlock(cpu: CpuState): Unit = UNIMPLEMENTED(0xA569E425)
override fun registerModule() {
registerFunctionInt("sceKernelPowerLock", 0xEADB1BD7, since = 150) { sceKernelPowerLock(int) }
registerFunctionInt("sceKernelPowerUnlock", 0x3AEE7261, since = 150) { sceKernelPowerUnlock(int) }
registerFunctionInt("sceKernelPowerTick", 0x090CCB3F, since = 150) { sceKernelPowerTick(int) }
registerFunctionRaw("sceKernelVolatileMemLock", 0x3E0271D3, since = 150) { sceKernelVolatileMemLock(it) }
registerFunctionRaw("sceKernelVolatileMemTryLock", 0xA14F40B2, since = 150) { sceKernelVolatileMemTryLock(it) }
registerFunctionRaw("sceKernelVolatileMemUnlock", 0xA569E425, since = 150) { sceKernelVolatileMemUnlock(it) }
}
}
| mit | 87bf3da393435f5e1ac22189d0891905 | 41.514286 | 119 | 0.735215 | 3.825193 | false | false | false | false |
FirebaseExtended/make-it-so-android | app/src/main/java/com/example/makeitso/screens/settings/SettingsScreen.kt | 1 | 3828 | /*
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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.example.makeitso.screens.settings
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.makeitso.R.drawable as AppIcon
import com.example.makeitso.R.string as AppText
import com.example.makeitso.common.composable.*
import com.example.makeitso.common.ext.card
import com.example.makeitso.common.ext.spacer
@ExperimentalMaterialApi
@Composable
fun SettingsScreen(
restartApp: (String) -> Unit,
openScreen: (String) -> Unit,
modifier: Modifier = Modifier,
viewModel: SettingsViewModel = hiltViewModel()
) {
val uiState by viewModel.uiState.collectAsState(initial = SettingsUiState(false))
Column(
modifier = modifier.fillMaxWidth().fillMaxHeight().verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
) {
BasicToolbar(AppText.settings)
Spacer(modifier = Modifier.spacer())
if (uiState.isAnonymousAccount) {
RegularCardEditor(AppText.sign_in, AppIcon.ic_sign_in, "", Modifier.card()) {
viewModel.onLoginClick(openScreen)
}
RegularCardEditor(AppText.create_account, AppIcon.ic_create_account, "", Modifier.card()) {
viewModel.onSignUpClick(openScreen)
}
} else {
SignOutCard { viewModel.onSignOutClick(restartApp) }
DeleteMyAccountCard { viewModel.onDeleteMyAccountClick(restartApp) }
}
}
}
@ExperimentalMaterialApi
@Composable
private fun SignOutCard(signOut: () -> Unit) {
var showWarningDialog by remember { mutableStateOf(false) }
RegularCardEditor(AppText.sign_out, AppIcon.ic_exit, "", Modifier.card()) {
showWarningDialog = true
}
if (showWarningDialog) {
AlertDialog(
title = { Text(stringResource(AppText.sign_out_title)) },
text = { Text(stringResource(AppText.sign_out_description)) },
dismissButton = { DialogCancelButton(AppText.cancel) { showWarningDialog = false } },
confirmButton = {
DialogConfirmButton(AppText.sign_out) {
signOut()
showWarningDialog = false
}
},
onDismissRequest = { showWarningDialog = false }
)
}
}
@ExperimentalMaterialApi
@Composable
private fun DeleteMyAccountCard(deleteMyAccount: () -> Unit) {
var showWarningDialog by remember { mutableStateOf(false) }
DangerousCardEditor(
AppText.delete_my_account,
AppIcon.ic_delete_my_account,
"",
Modifier.card()
) {
showWarningDialog = true
}
if (showWarningDialog) {
AlertDialog(
title = { Text(stringResource(AppText.delete_account_title)) },
text = { Text(stringResource(AppText.delete_account_description)) },
dismissButton = { DialogCancelButton(AppText.cancel) { showWarningDialog = false } },
confirmButton = {
DialogConfirmButton(AppText.delete_my_account) {
deleteMyAccount()
showWarningDialog = false
}
},
onDismissRequest = { showWarningDialog = false }
)
}
}
| apache-2.0 | a50b3cebc6edde77a0bd678d2904309f | 30.9 | 97 | 0.728579 | 4.286674 | false | false | false | false |
gradle/gradle | .teamcity/src/main/kotlin/promotion/PublishBranchSnapshotFromQuickFeedback.kt | 2 | 2006 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 promotion
import jetbrains.buildServer.configs.kotlin.v2019_2.ParameterDisplay
import jetbrains.buildServer.configs.kotlin.v2019_2.RelativeId
import vcsroots.gradlePromotionBranches
object PublishBranchSnapshotFromQuickFeedback : PublishGradleDistributionFullBuild(
promotedBranch = "%branch.to.promote%",
triggerName = "QuickFeedback",
prepTask = "prepSnapshot",
promoteTask = "promoteSnapshot",
extraParameters = "-PpromotedBranch=%branch.qualifier% ",
vcsRootId = gradlePromotionBranches
) {
init {
id("Promotion_PublishBranchSnapshotFromQuickFeedback")
name = "Publish Branch Snapshot (from Quick Feedback)"
description = "Deploys a new distribution snapshot for the selected build/branch. Does not update master or the documentation."
val triggerName = this.triggerName
params {
param("branch.qualifier", "%dep.${RelativeId("Check_Stage_${triggerName}_Trigger")}.teamcity.build.branch%")
text(
"branch.to.promote",
"%branch.qualifier%",
label = "Branch to promote",
description = "Type in the branch of gradle/gradle you want to promote. Leave the default value when promoting an existing build.",
display = ParameterDisplay.PROMPT,
allowEmpty = false
)
}
}
}
| apache-2.0 | d0e0b9460e2d436cde86be78df4a0267 | 39.12 | 147 | 0.694915 | 4.764846 | false | false | false | false |
adgvcxz/RxTheme | rxtheme/src/main/java/com/adgvcxz/rxtheme/extensions/PrimaryColorEx.kt | 1 | 2445 | package com.adgvcxz.rxtheme.extensions
import android.os.Build
import android.support.v4.view.ViewPager
import android.support.v7.widget.RecyclerView
import android.widget.EdgeEffect
import android.widget.ScrollView
/**
* zhaowei
* Created by zhaowei on 2017/8/2.
*/
fun RecyclerView.setPrimaryColor(color: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
val clazz = RecyclerView::class.java
for (name in arrayOf("ensureTopGlow", "ensureBottomGlow")) {
val method = clazz.getDeclaredMethod(name)
method.isAccessible = true
method.invoke(this)
}
for (name in arrayOf("mTopGlow", "mBottomGlow")) {
val field = clazz.getDeclaredField(name)
field.isAccessible = true
val edge = field.get(this) // android.support.v4.widget.EdgeEffectCompat
val fEdgeEffect = edge.javaClass.getDeclaredField("mEdgeEffect")
fEdgeEffect.isAccessible = true
(fEdgeEffect.get(edge) as EdgeEffect).color = color
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
fun ScrollView.setPrimaryColor(color: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val edgeEffectTop = EdgeEffect(this.context)
edgeEffectTop.color = color
val edgeEffectBottom = EdgeEffect(this.context)
edgeEffectBottom.color = color
try {
val f1 = ScrollView::class.java.getDeclaredField("mEdgeGlowTop")
f1.isAccessible = true
f1.set(this, edgeEffectTop)
val f2 = ScrollView::class.java.getDeclaredField("mEdgeGlowBottom")
f2.isAccessible = true
f2.set(this, edgeEffectBottom)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
fun ViewPager.setPrimaryColor(color: Int) {
try {
val clazz = ViewPager::class.java
for (name in arrayOf("mLeftEdge", "mRightEdge")) {
val field = clazz.getDeclaredField(name)
field.isAccessible = true
val edge = field.get(this)
val fEdgeEffect = edge.javaClass.getDeclaredField("mEdgeEffect")
fEdgeEffect.isAccessible = true
(fEdgeEffect.get(edge) as EdgeEffect).color = color
}
} catch (ignored: Exception) {
}
} | apache-2.0 | 765d62595eab221abc31bc7094fa832d | 33.450704 | 88 | 0.611043 | 4.389587 | false | false | false | false |
duftler/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/CompleteExecutionHandler.kt | 1 | 5124 | /*
* Copyright 2017 Netflix, 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.netflix.spinnaker.orca.q.handler
import com.netflix.spectator.api.Registry
import com.netflix.spinnaker.orca.ExecutionStatus
import com.netflix.spinnaker.orca.ExecutionStatus.CANCELED
import com.netflix.spinnaker.orca.ExecutionStatus.FAILED_CONTINUE
import com.netflix.spinnaker.orca.ExecutionStatus.NOT_STARTED
import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.ExecutionStatus.SKIPPED
import com.netflix.spinnaker.orca.ExecutionStatus.STOPPED
import com.netflix.spinnaker.orca.ExecutionStatus.SUCCEEDED
import com.netflix.spinnaker.orca.ExecutionStatus.TERMINAL
import com.netflix.spinnaker.orca.events.ExecutionComplete
import com.netflix.spinnaker.orca.ext.allUpstreamStagesComplete
import com.netflix.spinnaker.orca.pipeline.model.Execution
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.CancelStage
import com.netflix.spinnaker.orca.q.CompleteExecution
import com.netflix.spinnaker.orca.q.StartWaitingExecutions
import com.netflix.spinnaker.q.AttemptsAttribute
import com.netflix.spinnaker.q.Queue
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.ApplicationEventPublisher
import org.springframework.stereotype.Component
import java.time.Duration
@Component
class CompleteExecutionHandler(
override val queue: Queue,
override val repository: ExecutionRepository,
@Qualifier("queueEventPublisher") private val publisher: ApplicationEventPublisher,
private val registry: Registry,
@Value("\${queue.retry.delay.ms:30000}") retryDelayMs: Long
) : OrcaMessageHandler<CompleteExecution> {
private val log = LoggerFactory.getLogger(javaClass)
private val retryDelay = Duration.ofMillis(retryDelayMs)
private val completedId = registry.createId("executions.completed")
override fun handle(message: CompleteExecution) {
message.withExecution { execution ->
if (execution.status.isComplete) {
log.info("Execution ${execution.id} already completed with ${execution.status} status")
} else {
message.determineFinalStatus(execution) { status ->
repository.updateStatus(execution.type, message.executionId, status)
publisher.publishEvent(
ExecutionComplete(this, message.executionType, message.executionId, status)
)
registry.counter(completedId.withTags(
"status", status.name,
"executionType", execution.type.name,
"application", execution.application,
"origin", execution.origin ?: "unknown"
)).increment()
if (status != SUCCEEDED) {
execution.topLevelStages.filter { it.status == RUNNING }.forEach {
queue.push(CancelStage(it))
}
}
}
}
execution.pipelineConfigId?.let {
queue.push(StartWaitingExecutions(it, purgeQueue = !execution.isKeepWaitingPipelines))
}
}
}
private fun CompleteExecution.determineFinalStatus(
execution: Execution,
block: (ExecutionStatus) -> Unit
) {
execution.topLevelStages.let { stages ->
if (stages.map { it.status }.all { it in setOf(SUCCEEDED, SKIPPED, FAILED_CONTINUE) }) {
block.invoke(SUCCEEDED)
} else if (stages.any { it.status == TERMINAL }) {
block.invoke(TERMINAL)
} else if (stages.any { it.status == CANCELED }) {
block.invoke(CANCELED)
} else if (stages.any { it.status == STOPPED } && !stages.otherBranchesIncomplete()) {
block.invoke(if (execution.shouldOverrideSuccess()) TERMINAL else SUCCEEDED)
} else {
val attempts = getAttribute<AttemptsAttribute>()?.attempts ?: 0
log.info("Re-queuing $this as the execution is not yet complete (attempts: $attempts)")
queue.push(this, retryDelay)
}
}
}
private val Execution.topLevelStages
get(): List<Stage> = stages.filter { it.parentStageId == null }
private fun Execution.shouldOverrideSuccess(): Boolean =
stages
.filter { it.status == STOPPED }
.any { it.context["completeOtherBranchesThenFail"] == true }
private fun List<Stage>.otherBranchesIncomplete() =
any { it.status == RUNNING } ||
any { it.status == NOT_STARTED && it.allUpstreamStagesComplete() }
override val messageType = CompleteExecution::class.java
}
| apache-2.0 | a1105bc5b5d50e1bc5cc0224a2f6f2d8 | 41 | 95 | 0.733411 | 4.486865 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-shops-bukkit/src/main/kotlin/com/rpkit/shops/bukkit/listener/PlayerQuitListener.kt | 1 | 1486 | package com.rpkit.shops.bukkit.listener
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import com.rpkit.shops.bukkit.shopcount.RPKShopCountService
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerQuitEvent
class PlayerQuitListener : Listener {
@EventHandler
fun onPlayerQuit(event: PlayerQuitEvent) {
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return
val characterService = Services[RPKCharacterService::class.java] ?: return
val shopCountService = Services[RPKShopCountService::class.java] ?: return
minecraftProfileService.getMinecraftProfile(event.player).thenAccept getMinecraftProfile@{ minecraftProfile ->
if (minecraftProfile == null) return@getMinecraftProfile
characterService.getActiveCharacter(minecraftProfile).thenAccept getCharacter@{ character ->
if (character == null) return@getCharacter
// If a player relogs quickly, then by the time the data has been retrieved, the player is sometimes back
// online. We only want to unload data if the player is offline.
if (!minecraftProfile.isOnline) {
shopCountService.unloadShopCount(character)
}
}
}
}
} | apache-2.0 | 57b5ddb56e62265dbff89b5351713c30 | 46.967742 | 121 | 0.725437 | 5.364621 | false | false | false | false |
commons-app/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/review/ReviewControllerTest.kt | 4 | 5797 | package fr.free.nrw.commons.review
import android.app.Activity
import android.content.Context
import android.os.Looper
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.soloader.SoLoader
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import fr.free.nrw.commons.Media
import fr.free.nrw.commons.R
import fr.free.nrw.commons.TestAppAdapter
import fr.free.nrw.commons.TestCommonsApplication
import fr.free.nrw.commons.delete.DeleteHelper
import junit.framework.Assert.assertEquals
import junit.framework.Assert.assertNotNull
import media
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.powermock.reflect.Whitebox
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import org.robolectric.shadows.ShadowNotificationManager
import org.robolectric.shadows.ShadowToast
import org.wikipedia.AppAdapter
import org.wikipedia.dataclient.mwapi.MwQueryPage
import java.lang.reflect.Method
import java.util.*
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [21], application = TestCommonsApplication::class)
@LooperMode(LooperMode.Mode.PAUSED)
class ReviewControllerTest {
private lateinit var controller: ReviewController
private lateinit var context: Context
private lateinit var activity: Activity
private lateinit var media: Media
@Mock
private lateinit var deleteHelper: DeleteHelper
@Mock
private lateinit var reviewCallback: ReviewController.ReviewCallback
@Mock
private lateinit var firstRevision: MwQueryPage.Revision
@Before
@Throws(Exception::class)
fun setUp() {
MockitoAnnotations.initMocks(this)
context = RuntimeEnvironment.application.applicationContext
AppAdapter.set(TestAppAdapter())
SoLoader.setInTestMode()
Fresco.initialize(context)
activity = Robolectric.buildActivity(ReviewActivity::class.java).create().get()
controller = ReviewController(deleteHelper, context)
media = media(filename = "test_file", dateUploaded = Date())
Whitebox.setInternalState(controller, "media", media)
}
@Test
fun testGetMedia() {
controller.onImageRefreshed(media)
assertEquals(controller.media, media)
}
@Test
fun testReportSpam() {
shadowOf(Looper.getMainLooper()).idle()
controller.reportSpam(activity, reviewCallback)
verify(deleteHelper).askReasonAndExecute(
media,
activity,
activity.resources.getString(R.string.review_spam_report_question),
ReviewController.DeleteReason.SPAM,
reviewCallback
)
}
@Test
fun testReportPossibleCopyRightViolation() {
shadowOf(Looper.getMainLooper()).idle()
controller.reportPossibleCopyRightViolation(activity, reviewCallback)
verify(deleteHelper).askReasonAndExecute(
media,
activity,
activity.resources.getString(R.string.review_c_violation_report_question),
ReviewController.DeleteReason.COPYRIGHT_VIOLATION,
reviewCallback
)
}
@Test
fun testReportWrongCategory() {
shadowOf(Looper.getMainLooper()).idle()
controller.reportWrongCategory(activity, reviewCallback)
assertEquals(
ShadowToast.getTextOfLatestToast().toString(),
context.getString(R.string.check_category_toast, media.displayTitle)
)
}
@Test
fun testPublishProgress() {
shadowOf(Looper.getMainLooper()).idle()
val method: Method = ReviewController::class.java.getDeclaredMethod(
"publishProgress", Context::class.java, Int::class.java
)
method.isAccessible = true
method.invoke(controller, context, 1)
assertNotNull(ShadowNotificationManager().allNotifications)
}
@Test
fun testShowNotification() {
shadowOf(Looper.getMainLooper()).idle()
val method: Method = ReviewController::class.java.getDeclaredMethod(
"showNotification", String::class.java, String::class.java
)
method.isAccessible = true
method.invoke(controller, "", "")
assertNotNull(ShadowNotificationManager().allNotifications)
}
@Test
fun testSendThanks() {
shadowOf(Looper.getMainLooper()).idle()
whenever(firstRevision.revisionId).thenReturn(1)
Whitebox.setInternalState(controller, "firstRevision", firstRevision)
controller.sendThanks(activity)
assertEquals(
ShadowToast.getTextOfLatestToast().toString(),
context.getString(
R.string.send_thank_toast, media.displayTitle
)
)
val method: Method = ReviewController::class.java.getDeclaredMethod(
"displayThanksToast", Context::class.java, Boolean::class.java
)
method.isAccessible = true
method.invoke(controller,context,true)
assertEquals(
ShadowToast.getTextOfLatestToast().toString(),
context.getString(
R.string.send_thank_success_message, media.displayTitle
)
)
}
@Test
fun testSendThanksCaseNull() {
shadowOf(Looper.getMainLooper()).idle()
controller.sendThanks(activity)
assertEquals(
ShadowToast.getTextOfLatestToast().toString(),
context.getString(
R.string.send_thank_toast, media.displayTitle
)
)
}
} | apache-2.0 | 3ba5eae98f56715a4ddad5dc3c668602 | 32.131429 | 87 | 0.699327 | 4.851046 | false | true | false | false |
azizbekian/Spyur | app/src/main/kotlin/com/incentive/yellowpages/data/model/ListingResponse.kt | 1 | 7206 | package com.incentive.yellowpages.data.model
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import com.google.android.gms.maps.model.LatLng
import com.incentive.yellowpages.misc.createParcel
import java.util.*
data class ListingResponse(val executives: List<String>?, val contactInfos: List<ListingResponse.ContactInfo>?,
val workingDays: ListingResponse.WorkingDays?, val websites: List<String>?,
val listingInSpyur: String?, val images: List<String>?, val videoUrl: String?,
val hasMapCoordinates: Boolean = false) : Parcelable {
data class ContactInfo constructor(val loc: LatLng?, val address: String?, val region: String?,
var phoneNumbers: List<String>) : Parcelable {
constructor(source: Parcel) : this(source.readParcelable<LatLng>(LatLng::class.java.classLoader),
source.readString(),
source.readString(),
source.createStringArrayList())
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeParcelable(loc, flags)
dest.writeString(address)
dest.writeString(region)
dest.writeStringList(phoneNumbers)
}
class Builder {
private var loc: LatLng? = null
private var address: String? = null
private var region: String? = null
private val phoneNumbers: MutableList<String> = ArrayList()
fun setLocation(lat: Double, lng: Double): Builder {
this.loc = LatLng(lat, lng)
return this
}
fun setAddress(address: String): Builder {
this.address = address
return this
}
fun setRegion(region: String): Builder {
this.region = region
return this
}
fun addPhoneNumber(phoneNumber: String): Builder {
this.phoneNumbers.add(phoneNumber)
return this
}
fun build(): ContactInfo {
return ContactInfo(loc, address, region, phoneNumbers)
}
}
companion object {
@JvmField @Suppress("unused") val CREATOR = createParcel(::ContactInfo)
}
}
data class WorkingDays(private val days: HashMap<WorkingDays.Day, Boolean>) : Parcelable {
enum class Day {
MON, TUE, WED, THU, FRI, SAT, SUN
}
companion object {
@JvmField val CREATOR: Parcelable.Creator<WorkingDays> = object : Parcelable.Creator<WorkingDays> {
override fun createFromParcel(source: Parcel): WorkingDays = WorkingDays(source)
override fun newArray(size: Int): Array<WorkingDays?> = arrayOfNulls(size)
}
}
@Suppress("UNCHECKED_CAST")
constructor(source: Parcel) : this(source.readBundle().getSerializable("map") as HashMap<Day, Boolean>)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel?, flags: Int) {
val bundle = Bundle()
bundle.putSerializable("map", days)
dest?.writeBundle(bundle)
}
class Builder {
var days: MutableMap<Day, Boolean> = HashMap(7)
init {
days.put(Day.MON, java.lang.Boolean.FALSE)
days.put(Day.TUE, java.lang.Boolean.FALSE)
days.put(Day.WED, java.lang.Boolean.FALSE)
days.put(Day.THU, java.lang.Boolean.FALSE)
days.put(Day.FRI, java.lang.Boolean.FALSE)
days.put(Day.SAT, java.lang.Boolean.FALSE)
days.put(Day.SUN, java.lang.Boolean.FALSE)
}
fun setWorkingDay(day: Day): Builder {
days.put(day, java.lang.Boolean.TRUE)
return this
}
fun build(): WorkingDays {
return WorkingDays(days as HashMap<Day, Boolean>)
}
}
}
class Builder {
private val executives: MutableList<String> = ArrayList()
private val contactInfos: MutableList<ContactInfo> = ArrayList()
private var workingDays: WorkingDays? = null
private val websites: MutableList<String> = ArrayList()
private var listingInSpyur: String? = null
private val images: MutableList<String> = ArrayList()
private var videoUrl: String? = null
fun addExecutive(executive: String): Builder {
executives.add(executive)
return this
}
fun addContactInfo(contactInfo: ContactInfo): Builder {
contactInfos.add(contactInfo)
return this
}
fun setWorkingDays(workingDays: WorkingDays): Builder {
this.workingDays = workingDays
return this
}
fun addWebsite(websiteUri: String): Builder {
this.websites.add(websiteUri)
return this
}
fun setListingInSpyur(listingInSpyur: String): Builder {
this.listingInSpyur = listingInSpyur
return this
}
fun addImage(imageUri: String): Builder {
this.images.add(imageUri)
return this
}
fun setVideoUrl(videoUrl: String): Builder {
this.videoUrl = videoUrl
return this
}
fun build(): ListingResponse {
val hasMapCoordinates = contactInfos.any { it.loc != null }
return ListingResponse(executives, contactInfos, workingDays, websites,
listingInSpyur, images, videoUrl, hasMapCoordinates)
}
}
companion object {
@JvmField val CREATOR: Parcelable.Creator<ListingResponse> = object : Parcelable.Creator<ListingResponse> {
override fun createFromParcel(source: Parcel): ListingResponse = ListingResponse(source)
override fun newArray(size: Int): Array<ListingResponse?> = arrayOfNulls(size)
}
}
constructor(source: Parcel) : this(ArrayList<String>().apply {
source.readList(this, String::class.java.classLoader)
},
source.createTypedArrayList(ContactInfo.CREATOR),
source.readParcelable<WorkingDays?>(WorkingDays::class.java.classLoader),
ArrayList<String>().apply { source.readList(this, String::class.java.classLoader) },
source.readString(), ArrayList<String>().apply { source.readList(this, String::class.java.classLoader) },
source.readString(), source.readByte().toInt() != 0)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel?, flags: Int) {
dest?.writeList(executives)
dest?.writeTypedList(contactInfos)
dest?.writeParcelable(workingDays, 0)
dest?.writeList(websites)
dest?.writeString(listingInSpyur)
dest?.writeList(images)
dest?.writeString(videoUrl)
dest?.writeByte(if (hasMapCoordinates) 1 else 0)
}
}
| gpl-2.0 | 38ba39d150caf41a723a64472db69d91 | 35.211055 | 117 | 0.594366 | 4.922131 | false | false | false | false |
t-yoshi/peca-android | ui/src/main/java/org/peercast/core/ui/tv/PlayerLauncher.kt | 1 | 6522 | package org.peercast.core.ui.tv
/**
* @author (c) 2014-2021, T Yoshizawa
* @licenses Dual licensed under the MIT or GPL licenses.
*/
import android.content.ActivityNotFoundException
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.leanback.app.ErrorSupportFragment
import org.koin.androidx.viewmodel.ext.android.getSharedViewModel
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import org.peercast.core.common.isFireTv
import org.peercast.core.lib.LibPeerCast.toStreamIntent
import org.peercast.core.lib.rpc.YpChannel
import org.peercast.core.ui.R
import org.peercast.core.ui.tv.util.finishFragment
import timber.log.Timber
import java.io.File
import java.io.IOException
class PlayerLauncher(private val f: Fragment, private val ypChannel: YpChannel) {
private val viewModel = f.getSharedViewModel<TvViewModel>()
private val c = f.requireContext()
private val launcher = f.registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { r ->
Timber.d("-> $r ${r?.data?.extras?.keySet()}")
val extras = r?.data?.extras ?: Bundle.EMPTY
extras.keySet().forEach {
Timber.d(" -> $it: ${extras[it]}")
}
}
private val listCreator = VlcPlayListCreator(c)
private fun startVlcPlayer() {
val u = listCreator.create(ypChannel, viewModel.config.port)
val i = Intent(Intent.ACTION_VIEW, u)
Timber.i("start vlc player: ${i.data}")
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
//@see https://wiki.videolan.org/Android_Player_Intents/
//@see https://code.videolan.org/videolan/vlc-android/-/blob/master/application/vlc-android/src/org/videolan/vlc/gui/video/VideoPlayerActivity.kt
i.component = ComponentName(
"org.videolan.vlc",
"org.videolan.vlc.gui.video.VideoPlayerActivity"
)
//i.`package` = "org.videolan.vlc"
i.putExtra("title", ypChannel.name)
try {
launcher.launch(i)
viewModel.bookmark.incrementPlayedCount(ypChannel)
} catch (e: ActivityNotFoundException) {
Timber.e(e)
viewModel.sendErrorToast(e)
}
}
private fun startMxPlayer() {
val i = ypChannel.toStreamIntent(viewModel.config.port)
Timber.i("start player: ${i.data}")
try {
f.startActivity(i)
viewModel.bookmark.incrementPlayedCount(ypChannel)
} catch (e: RuntimeException) {
//Timber.w(e)
PromptToInstallVlcPlayerFragment.start(f.parentFragmentManager)
}
}
class PromptToInstallVlcPlayerFragment : ErrorSupportFragment() {
private val viewModel by sharedViewModel<TvViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
message = getString(R.string.please_install_vlc_player)
if (requireContext().isFireTv) {
buttonText = getString(android.R.string.ok)
buttonClickListener = View.OnClickListener {
finishFragment()
}
} else {
buttonText = getString(R.string.google_play)
buttonClickListener = View.OnClickListener {
val u = Uri.parse("market://details?id=" + VLC_PLAYER_ACTIVITY.packageName)
try {
startActivity(Intent(Intent.ACTION_VIEW, u))
} catch (e: RuntimeException) {
viewModel.sendErrorToast(e)
}
finishFragment()
}
}
}
companion object {
fun start(fm: FragmentManager) {
fm.beginTransaction()
.replace(android.R.id.content, PromptToInstallVlcPlayerFragment())
.commit()
}
}
}
fun startPlayer() {
//return PromptToInstallVlcPlayerFragment.start(f.parentFragmentManager)
if (hasInstalledVlcPlayer())
startVlcPlayer()
else
startMxPlayer()
}
private fun hasInstalledVlcPlayer(): Boolean {
return try {
c.packageManager.getApplicationInfo(VLC_PLAYER_ACTIVITY.packageName, 0)
true
} catch (e: PackageManager.NameNotFoundException) {
false
}
}
private class VlcPlayListCreator(private val c: Context) {
val plsDir = File(c.cacheDir, "pls/")
init {
val now = System.currentTimeMillis()
plsDir.run {
if (!exists())
mkdirs()
//古いものを削除
listFiles { f ->
f.lastModified() < now - 7 * 24 * 60 * 60_000
}?.forEach { f ->
f.delete()
}
}
}
/**プレイリストにURLを5つ並べて再接続できるようにする*/
fun create(ypChannel: YpChannel, port: Int): Uri {
val stream = ypChannel.toStreamIntent(port).dataString!!
val f = File(plsDir, "${ypChannel.name.fileNameEscape()}.pls")
val now = System.currentTimeMillis()
return try {
f.printWriter().use { p ->
for (i in 0..4) {
p.println("$stream?v=${now / 1000 + i}")
}
}
FileProvider.getUriForFile(c, "org.peercast.core.fileprovider", f).also {
// c.grantUriPermission(VLC_PLAYER_ACTIVITY.packageName,
// it, Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
} catch (e: IOException) {
Uri.EMPTY
}
}
companion object {
private fun String.fileNameEscape() = replace("""\\W""".toRegex(), "_")
}
}
companion object {
private val VLC_PLAYER_ACTIVITY = ComponentName(
"org.videolan.vlc",
"org.videolan.vlc.gui.video.VideoPlayerActivity"
)
}
} | gpl-3.0 | 207b10aa9f807bc9f7bd3266692760bd | 33.561497 | 153 | 0.591922 | 4.547502 | false | false | false | false |
androidx/constraintlayout | desktop/ConstraintLayoutInspector/app/src/androidx/constraintLayout/desktop/link/kotlin/Main.kt | 2 | 19354 | /*
* 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.constraintLayout.desktop.link.kotlin
import androidx.constraintLayout.desktop.link.DesignSurfaceModification
import androidx.constraintLayout.desktop.link.MainUI
import androidx.constraintLayout.desktop.link.MotionLink
import androidx.constraintLayout.desktop.scan.CLScan
import androidx.constraintLayout.desktop.scan.CLTreeNode
import androidx.constraintLayout.desktop.scan.SyntaxHighlight
import androidx.constraintLayout.desktop.ui.utils.Debug
import androidx.constraintLayout.desktop.utils.Desk
import androidx.constraintlayout.core.parser.CLElement
import androidx.constraintlayout.core.parser.CLObject
import androidx.constraintlayout.core.parser.CLParser
import androidx.constraintlayout.core.parser.CLParsingException
import java.awt.*
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import java.io.File
import java.io.FileReader
import java.io.FileWriter
import java.io.IOException
import javax.swing.*
import javax.swing.event.CaretListener
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import javax.swing.event.TreeSelectionListener
import javax.swing.text.BadLocationException
import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter
import javax.swing.text.Highlighter
import javax.swing.text.StyledDocument
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.DefaultTreeModel
class Main internal constructor() : JPanel(BorderLayout()),
MainUI {
private var mSelectionHighlight: Any? = null
private var layoutInspectorWindow: JFrame? = null
var motionLink = MotionLink()
var mMainText = JTextPane()
var mMessages = JLabel()
var layoutListTree = JTree()
var scrollPaneList = JScrollPane(layoutListTree)
var highlight = SyntaxHighlight(mMainText)
var mMainTextScrollPane = JScrollPane(mMainText)
var drawDebug = false
var layoutInspector: LayoutInspector? = null
var showWest = true
init {
val hide = JButton("<")
val getButton = JButton("Get")
val connectButton = JButton("Connect")
val sendButton = JButton("Send")
val toggleDrawDebug = JButton("Toggle Debug")
val showLayout = JButton("Inspect")
val formatText = JButton("Format Text")
mMessages.horizontalAlignment = SwingConstants.RIGHT
val font = Font("Courier", Font.PLAIN, 20)
mMainText.font = font
scrollPaneList.preferredSize = Dimension(200, 100)
val northPanel = JPanel()
val bigNorth = JPanel(BorderLayout())
bigNorth.add(northPanel)
bigNorth.add(hide, BorderLayout.WEST)
northPanel.add(connectButton)
northPanel.add(showLayout)
// TODO: migrate to file menu?
// northPanel.add(toggleDrawDebug)
// northPanel.add(getButton)
// northPanel.add(sendButton)
northPanel.add(formatText)
val southPanel = JPanel(BorderLayout())
southPanel.add(mMessages, BorderLayout.SOUTH)
add(bigNorth, BorderLayout.NORTH)
add(scrollPaneList, BorderLayout.WEST)
add(mMainTextScrollPane, BorderLayout.CENTER)
add(southPanel, BorderLayout.SOUTH)
hide.preferredSize = hide.preferredSize
hide.background = Color(0, 0, 0, 0)
hide.isOpaque = false
hide.border = null
hide.addActionListener { e: ActionEvent? ->
if (showWest) {
remove(scrollPaneList)
hide.text = ">"
} else {
add(scrollPaneList, BorderLayout.WEST)
hide.text = "<"
}
showWest = !showWest
}
motionLink.addListener { event: MotionLink.Event, link: MotionLink ->
fromLink(
event,
link
)
}
layoutListTree.selectionModel.addTreeSelectionListener(TreeSelectionListener { e ->
val path = e.path
if (path.pathCount > 2) {
val selected = path.lastPathComponent as CLTreeNode
println("selected " + selected.mKeyStart + "," + selected.mKeyEnd)
mMainText.select(selected.mKeyStart, selected.mKeyEnd + 1)
mMainText.requestFocus()
return@TreeSelectionListener
}
val root =
path.getPathComponent(0) as DefaultMutableTreeNode
val selected =
path.getPathComponent(1) as DefaultMutableTreeNode
val index = root.getIndex(selected)
motionLink.selectMotionScene(index)
motionLink.getContent()
})
motionLink.getLayoutList()
mMessages.text = "ok"
connectButton.addActionListener { e: ActionEvent? -> motionLink.getLayoutList() }
toggleDrawDebug.addActionListener { e: ActionEvent? ->
motionLink.setDrawDebug(
!drawDebug.also { drawDebug = it }
)
}
showLayout.addActionListener { e: ActionEvent? ->
if (layoutInspectorWindow != null && layoutInspectorWindow!!.isVisible()) {
layoutInspector?.resetEdit()
layoutInspectorWindow!!.isVisible = false
} else {
motionLink.getLayoutList()
layoutInspector?.resetEdit()
layoutInspectorWindow?.isVisible = true
}
}
getButton.addActionListener { e: ActionEvent? -> motionLink.getContent() }
formatText.addActionListener {
try {
setText(formatJson(mMainText.text))
updateTree()
} catch (e: Exception) {
}
}
mMainText.addCaretListener(CaretListener {
val str = mMainText.text
highlight.opposingBracketColor(str, mMainText.caretPosition, str.length)
})
mMainText.addKeyListener(object : KeyAdapter() {
override fun keyTyped(e: KeyEvent) {
if ('\n' == e.keyChar) {
val str = mMainText.text
val offset = mMainText.caretPosition
var count = 0
for (i in offset - 2 downTo 1) {
val c = str[i]
if (Character.isAlphabetic(c.toInt())) {
count = 0
continue
} else if (Character.isSpaceChar(c)) {
count++
} else if (c == '\n') {
break
}
}
val s = String(CharArray(count)).replace(0.toChar(), ' ')
try {
mMainText.document.insertString(offset, s, null)
} catch (badLocationException: BadLocationException) {
badLocationException.printStackTrace()
}
}
}
})
mMainText.document.addDocumentListener(object : DocumentListener {
override fun insertUpdate(e: DocumentEvent) {
if (highlight.update) {
return
}
motionLink.sendContent(mMainText.text)
updateModel(mMainText.text)
}
override fun removeUpdate(e: DocumentEvent) {
if (highlight.update) {
return
}
motionLink.sendContent(mMainText.text)
updateModel(mMainText.text)
}
override fun changedUpdate(e: DocumentEvent) {
if (highlight.update) {
return
}
motionLink.sendContent(mMainText.text)
updateModel(mMainText.text)
}
})
}
private fun fromLink(event: MotionLink.Event, link: MotionLink) {
when (event) {
MotionLink.Event.ERROR -> { // ============ the ERROR case
mMessages.text = link.errorMessage
mMessages.foreground = Color.RED.darker()
link.errorMessage = ""
}
MotionLink.Event.STATUS -> { // ============ the STATUS case
mMessages.text = link.statusMessage
mMessages.foreground = Color.BLACK
link.errorMessage = ""
}
MotionLink.Event.LAYOUT_UPDATE -> { // ============ the LAYOUT_UPDATE case
if (layoutInspector == null) {
layoutInspector = showLayoutInspector(link, object :
DesignSurfaceModification {
override fun getElement(name: String): CLElement? {
if (jsonModel != null && jsonModel is CLObject) {
return jsonModel!!.get(name)
}
return null
}
override fun updateElement(name: String, content: CLElement) {
if (jsonModel != null && jsonModel is CLObject) {
jsonModel!!.put(name, content)
setText(jsonModel!!.toFormattedJSON(0, 2))
}
}
})
link.setUpdateLayoutPolling(true)
}
layoutInspector!!.setLayoutInformation(link.layoutInfos)
}
MotionLink.Event.LAYOUT_LIST_UPDATE -> { // ============ the LAYOUT_LIST_UPDATE case
val root = DefaultMutableTreeNode("root")
val model = DefaultTreeModel(root)
var i = 0
while (i < link.layoutNames.size) {
var name = link.layoutNames[i]
if (i == link.lastUpdateLayout) {
name = "<html><b>*" + name + "*</b></html>"
}
var node = DefaultMutableTreeNode(name)
root.add(node)
i++
}
layoutListTree.isRootVisible = false
layoutListTree.model = model
}
MotionLink.Event.MOTION_SCENE_UPDATE -> { // ============ the MOTION_SCENE_UPDATE case
try {
highlight.inOpposingBracketColor = true
setText(formatJson(link.motionSceneText))
updateTree()
highlight.inOpposingBracketColor = false
} catch (e: CLParsingException) {
Debug.log("exception $e")
}
}
}
}
var jsonModel: CLObject? = null
private fun setText(text: String) {
mMainText.text = text
updateModel(text)
}
private fun updateModel(text: String) {
try {
jsonModel = CLParser.parse(text)
if (layoutInspector != null && jsonModel is CLObject) {
layoutInspector!!.setModel(jsonModel!!)
layoutInspector!!.setSceneString(mMainText.text)
}
} catch (e: CLParsingException) {
// nothing here... (text might be malformed as edit happens)
}
}
private fun formatJson(text: String): String {
if (text.length == 0) {
return ""
}
try {
val json = CLParser.parse(text)
var indentation = 2
if (json.has("ConstraintSets")) {
indentation = 3
}
return json.toFormattedJSON(0, indentation)
} catch (e: CLParsingException) {
System.err.println("error in parsing text \"" + text + "\"")
throw RuntimeException("Parse error", e)
}
}
private fun updateTree() {
val model = layoutListTree.model as DefaultTreeModel
val root = model.root as DefaultMutableTreeNode
val n = root.childCount
for (i in 0 until n) {
val child =
root.getChildAt(i) as DefaultMutableTreeNode
child.removeAllChildren()
if (motionLink.mSelectedIndex == i) {
try {
CLTreeNode.parse(motionLink.motionSceneText, child)
} catch (e: CLParsingException) {
mMessages.text = e.message
mMessages.foreground = Color.RED.darker()
}
}
}
model.reload()
layoutListTree.expandRow(motionLink.mSelectedIndex)
}
var myTmpFile: File? = null
var myTempLastModified: Long = 0
var myTmpTimer: Timer? = null
fun remoteEditStop() {
myTmpTimer!!.stop()
myTmpFile!!.deleteOnExit()
myTmpFile = null
}
var widgetCount = 1;
override fun addDesign(type: String) {
val key = CLScan.findCLKey(CLParser.parse(mMainText.text), "Design")
val uType = upperCaseFirst(type)
if (key != null) {
val end = key.value.end.toInt() - 2
val document: StyledDocument = mMainText.getDocument() as StyledDocument
document.insertString(
end,
",\n $type$widgetCount:{ type: '$type' , text: '$uType$widgetCount' }",
null
)
} else {
val key = CLScan.findCLKey(CLParser.parse(mMainText.text), "Header")
if (key != null) {
widgetCount = 1;
val end = key.value.end.toInt() + 2
val document: StyledDocument = mMainText.getDocument() as StyledDocument
val str = "\n Design : { \n" +
" $type$widgetCount:{ type: '$type' , text: '$uType$widgetCount'} \n }";
document.insertString(end, str, null)
}
}
widgetCount++
}
override fun addConstraint(widget: String, constraint: String) {
val key = CLScan.findCLKeyInRoot(CLParser.parse(mMainText.text), widget)
if (key == null) {
val pos = mMainText.text.length - 2
val str = ",\n " + widget + ": {\n " +
constraint + ", \n" +
" }\n"
val document: StyledDocument = mMainText.getDocument() as StyledDocument
document.insertString(pos, str, null)
} else {
val pos = key.value.end.toInt() - 1
val str = ",\n " +constraint + ", \n"
val document: StyledDocument = mMainText.getDocument() as StyledDocument
document.insertString(pos, str, null)
}
}
fun upperCaseFirst(str: String): String? {
return str.substring(0, 1).toUpperCase() + str.substring(1)
}
override fun selectKey(widget: String) {
val key = CLScan.findCLKey(CLParser.parse(mMainText.text), widget)
clearSelectedKey();
if (key != null) {
val h: Highlighter = mMainText.getHighlighter()
try {
mSelectionHighlight = h.addHighlight(
key.start.toInt(),
key.end.toInt() + 1,
DefaultHighlightPainter(Color.PINK)
)
} catch (e: BadLocationException) {
e.printStackTrace()
}
}
}
override fun clearSelectedKey() {
if (mSelectionHighlight == null) {
return
}
val h: Highlighter = mMainText.getHighlighter()
h.removeHighlight(mSelectionHighlight)
}
fun remoteEdit() {
try {
val tmp = File.createTempFile(motionLink.selectedLayoutName, ".json5")
val fw = FileWriter(tmp)
fw.write(motionLink.motionSceneText)
fw.close()
myTempLastModified = tmp.lastModified()
Desktop.getDesktop().open(tmp)
myTmpFile = tmp;
myTmpTimer = Timer(500, ActionListener { e: ActionEvent? -> checkForUpdate() })
myTmpTimer!!.isRepeats = true
myTmpTimer!!.start()
} catch (e: IOException) {
e.printStackTrace()
}
}
private fun checkForUpdate() {
val lastM = myTmpFile!!.lastModified()
if (lastM - myTempLastModified > 0) {
try {
myTempLastModified = lastM
val fr = FileReader(myTmpFile)
val buff = CharArray(myTmpFile!!.length().toInt())
var off = 0
while (true) {
val len = fr.read(buff, off, buff.size - off)
println(len)
if (len <= 0) break
off += len
}
fr.close()
setText(String(buff, 0, off))
} catch (e: IOException) {
e.printStackTrace()
}
}
}
fun showLayoutInspector(link: MotionLink, callback: DesignSurfaceModification): LayoutInspector? {
val frame = JFrame("Layout Inspector")
val inspector = LayoutInspector(link, this)
frame.contentPane = inspector
Desk.rememberPosition(frame, null)
inspector.editorView.designSurfaceModificationCallback = callback
layoutInspectorWindow = frame
return inspector
}
companion object {
@JvmStatic
fun main(str: Array<String>) {
val frame = JFrame("ConstraintLayout Live Editor")
val panel = Main()
frame.contentPane = panel
val unlink: AbstractAction = object : AbstractAction("unlink") {
override fun actionPerformed(e: ActionEvent) {
panel.remoteEditStop()
}
}
val link: AbstractAction = object : AbstractAction("link") {
override fun actionPerformed(e: ActionEvent) {
panel.remoteEdit()
}
}
val menuBar = JMenuBar()
val fileMenu = JMenu("File")
val editMenu = JMenu("Edit")
val viewMenu = JMenu("View")
val advMenu = JMenu("Advanced")
menuBar.add(fileMenu)
menuBar.add(editMenu)
menuBar.add(viewMenu)
fileMenu.add(advMenu)
advMenu.add(unlink)
advMenu.add(link)
Desk.setupMenu(viewMenu)
frame.jMenuBar = menuBar
Desk.rememberPosition(frame, null)
frame.defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
frame.isVisible = true
}
}
}
| apache-2.0 | 64b744c5c1a4f9383ac2385f54690f07 | 36.219231 | 102 | 0.550791 | 4.904714 | false | false | false | false |
kittinunf/ReactiveAndroid | reactiveandroid-ui/src/main/kotlin/com/github/kittinunf/reactiveandroid/view/MenuItemProperty.kt | 1 | 2047 | package com.github.kittinunf.reactiveandroid.view
import android.graphics.drawable.Drawable
import android.view.MenuItem
import android.view.View
import com.github.kittinunf.reactiveandroid.MutableProperty
import com.github.kittinunf.reactiveandroid.createMainThreadMutableProperty
//================================================================================
// Properties
//================================================================================
val MenuItem.rx_actionView: MutableProperty<View>
get() {
val getter = { actionView }
val setter: (View) -> Unit = { actionView = it }
return createMainThreadMutableProperty(getter, setter)
}
val MenuItem.rx_icon: MutableProperty<Drawable>
get() {
val getter = { icon }
val setter: (Drawable) -> Unit = { icon = it }
return createMainThreadMutableProperty(getter, setter)
}
val MenuItem.rx_checkable: MutableProperty<Boolean>
get() {
val getter = { isCheckable }
val setter: (Boolean) -> Unit = { isCheckable = it }
return createMainThreadMutableProperty(getter, setter)
}
val MenuItem.rx_checked: MutableProperty<Boolean>
get() {
val getter = { isChecked }
val setter: (Boolean) -> Unit = { isChecked = it }
return createMainThreadMutableProperty(getter, setter)
}
val MenuItem.rx_enabled: MutableProperty<Boolean>
get() {
val getter = { isEnabled }
val setter: (Boolean) -> Unit = { isEnabled = it }
return createMainThreadMutableProperty(getter, setter)
}
val MenuItem.rx_visible: MutableProperty<Boolean>
get() {
val getter = { isVisible }
val setter: (Boolean) -> Unit = { isVisible = it }
return createMainThreadMutableProperty(getter, setter)
}
val MenuItem.rx_title: MutableProperty<CharSequence>
get() {
val getter = { title }
val setter: (CharSequence) -> Unit = { title = it }
return createMainThreadMutableProperty(getter, setter)
}
| mit | 473811cb7d82d7e64c1d3dfd06e8667a | 29.552239 | 82 | 0.613581 | 4.956416 | false | false | false | false |
shiguredo/sora-android-sdk | sora-android-sdk/src/main/kotlin/jp/shiguredo/sora/sdk/channel/option/SoraProxyOption.kt | 1 | 742 | package jp.shiguredo.sora.sdk.channel.option
import jp.shiguredo.sora.sdk.util.SDKInfo
import org.webrtc.ProxyType
/**
* プロキシに関するオプションをまとめるクラスです.
*/
class SoraProxyOption {
/** 種類 */
var type = ProxyType.NONE
/** エージェント */
var agent: String = SDKInfo.sdkInfo()
/** ホスト名 */
var hostname: String = ""
/** ポート */
var port: Int = 0
/** ユーザー名 */
var username: String = ""
/** パスワード */
var password: String = ""
override fun toString(): String {
return "type=$type, hostname=$hostname, port=$port, username=$username, password=${"*".repeat(password.length)}, agent=$agent"
}
}
| apache-2.0 | 506ddf0303cead35a4ee540ed5201e7f | 19.1875 | 134 | 0.606811 | 3.090909 | false | false | false | false |
luoyuan800/NeverEnd | server_core/src/cn/luo/yuan/maze/server/persistence/CDKEYTable.kt | 1 | 4246 | package cn.luo.yuan.maze.server.persistence
import cn.luo.yuan.maze.model.CDKey
import cn.luo.yuan.maze.model.KeyResult
import cn.luo.yuan.maze.server.LogHelper
import cn.luo.yuan.maze.persistence.DatabaseConnection
import cn.luo.yuan.maze.utils.Random
import java.sql.Connection
import java.sql.PreparedStatement
import java.sql.Statement
/**
* Copyright @Luo
* Created by Gavin Luo on 8/15/2017.
*/
class CDKEYTable(private val database: DatabaseConnection) {
init {
var statement: Statement? = null
var connection: Connection? = null
try {
connection = database.getConnection()
statement = connection.createStatement()
statement.execute("CREATE TABLE IF NOT EXISTS `cdkey` (`id` VARCHAR(100) NOT NULL, `gift` INT(11), `debris` INT(11), `mate` INT(11), `used` INT(11), `single` INT(11), PRIMARY KEY (`id`)) ENGINE = InnoDB;");
} catch (e: Exception) {
LogHelper.error(e)
} finally {
statement?.close()
connection?.close()
}
}
fun use(id: String): KeyResult {
val ur = KeyResult()
val con = database.getConnection()
var verify = false
try {
val stat = con.createStatement();
val rs = stat.executeQuery("select * from cdkey where id = '$id'")
var gift = 0
var debris = 0
if (rs.next()) {
gift = rs.getInt("gift")
debris = rs.getInt("debris")
ur.mate = rs.getLong("mate")
if (rs.getBoolean("single")) {
verify = rs.getInt("used") <= 0
} else {
verify = true
}
}
rs.close()
if (verify) {
stat.execute("update cdkey set used = used + 1 where id ='$id'")
if (verify) {
val r = Random(System.currentTimeMillis())
if (gift > 0) {
ur.gift = if (ur.mate > 0) r.nextInt(gift) + 1 else gift
}
if (debris > 0) {
ur.debris = if (ur.mate > 0) r.nextInt(debris) + 1 else debris
}
}
}
} catch (e: Exception) {
LogHelper.error(e)
}
con.close()
ur.verify = verify
return ur
}
fun newCdKey(): String {
return newCdKey(1, 100000, 5)
}
fun newCdKey(deris: Int, mate: Int, gift: Int): String {
val con = database.getConnection()
try {
val random = Random(System.currentTimeMillis())
val stat = con.createStatement()
val id = buildId(random)
stat.execute("insert into cdkey(id, gift, debris, mate, used, single) values('$id',$gift, $deris,$mate,0,1)")
stat.close();
return id;
} finally {
con?.close()
}
}
fun queryMyCdKey(ids:List<String>): List<CDKey>{
val cks = mutableListOf<CDKey>()
var con:Connection? = null
try{
con = database.getConnection()
val builder = StringBuilder()
ids.forEach {
builder.append("'$it',")
}
val idss = builder.replaceFirst(Regex(",$"), "")
val ps = con.prepareStatement("select * from `cdkey` where id in ($idss)")
val rs = ps.executeQuery()
while(rs.next()){
if(rs.getLong("used") <= 0) {
val ck = CDKey()
ck.id = rs.getString("id")
ck.debris = rs.getLong("debris")
ck.mate = rs.getLong("mate")
ck.used = rs.getLong("used")
ck.isSingle = rs.getBoolean("single")
cks.add(ck)
}
}
ps.close()
}finally {
con?.close()
}
return cks;
}
private fun buildId(random: Random): String {
val sb = StringBuilder()
while (sb.length < 5) {
sb.append((random.nextInt(25) + 97).toChar())
}
return sb.toString()
}
} | bsd-3-clause | ffe8393a6fac9e18ddff9789d467ad6c | 31.922481 | 218 | 0.491757 | 4.142439 | false | false | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/util/identitymapper.kt | 1 | 1388 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.util.IdentityMapper
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
interface IIdentityMapperNested {
fun identitymapper(
from: String? = null,
to: String? = null)
{
_addIdentityMapper(IdentityMapper().apply {
_init(from, to)
})
}
fun _addIdentityMapper(value: IdentityMapper)
}
fun IFileNameMapperNested.identitymapper(
from: String? = null,
to: String? = null)
{
_addFileNameMapper(IdentityMapper().apply {
_init(from, to)
})
}
fun IdentityMapper._init(
from: String?,
to: String?)
{
if (from != null)
setFrom(from)
if (to != null)
setTo(to)
}
| apache-2.0 | e0061264c8daaea777d089153e0cc59c | 24.236364 | 79 | 0.634006 | 3.887955 | false | false | false | false |
Shynixn/PetBlocks | petblocks-sponge-plugin/src/main/java/com/github/shynixn/petblocks/sponge/logic/business/pathfinder/PathfinderFollowOwner.kt | 1 | 3498 | package com.github.shynixn.petblocks.sponge.logic.business.pathfinder
import com.github.shynixn.petblocks.api.PetBlocksApi
import com.github.shynixn.petblocks.api.business.proxy.PetProxy
import com.github.shynixn.petblocks.api.business.service.LoggingService
import com.github.shynixn.petblocks.api.business.service.NavigationService
import com.github.shynixn.petblocks.api.persistence.entity.AIFollowOwner
import com.github.shynixn.petblocks.api.persistence.entity.AIHopping
import com.github.shynixn.petblocks.api.persistence.entity.Position
import com.github.shynixn.petblocks.core.logic.business.pathfinder.BasePathfinder
import com.github.shynixn.petblocks.sponge.logic.business.extension.distance
import com.github.shynixn.petblocks.sponge.logic.business.extension.gameMode
import com.github.shynixn.petblocks.sponge.logic.business.extension.toPosition
import com.github.shynixn.petblocks.sponge.logic.business.extension.toTransform
import org.spongepowered.api.entity.Transform
import org.spongepowered.api.entity.living.Living
import org.spongepowered.api.entity.living.player.Player
import org.spongepowered.api.entity.living.player.gamemode.GameModes
import org.spongepowered.api.world.World
class PathfinderFollowOwner(
private val pet: PetProxy,
private val aiFollowBack: AIFollowOwner,
private val livingEntity: Living,
private val player: Player
) : BasePathfinder(aiFollowBack) {
private var lastLocation: Transform<World>? = null
private val navigationService = PetBlocksApi.resolve(NavigationService::class.java)
private val loggingService = PetBlocksApi.resolve(LoggingService::class.java)
/**
* Should the goal be executed.
*/
override fun shouldGoalBeExecuted(): Boolean {
return try {
!livingEntity.isRemoved && player.gameMode != GameModes.SPECTATOR && player.transform.distance(livingEntity.transform) >= aiFollowBack.distanceToOwner
} catch (e: Exception) {
loggingService.warn("Failed to execute PathfinderFollowOwner.", e)
false
}
}
/**
* Should the goal continue executing.
*/
override fun shouldGoalContinueExecuting(): Boolean {
return try {
when {
player.transform.distance(livingEntity.transform) > aiFollowBack.maxRange -> {
pet.teleport(player.transform)
false
}
player.transform.distance(livingEntity.transform) < aiFollowBack.distanceToOwner -> false
else -> !(lastLocation != null && lastLocation!!.distance(player.transform) > 2)
}
} catch (e: Exception) {
loggingService.warn("Failed to execute PathfinderFollowOwner.", e)
false
}
}
/**
* On stop executing.
*/
override fun onStopExecuting() {
navigationService.clearNavigation(pet)
}
/**
* On start executing.
*/
override fun onStartExecuting() {
try {
lastLocation = player.transform.toPosition().toTransform()
val speed = if (pet.meta.aiGoals.firstOrNull { p -> p is AIHopping } != null) {
aiFollowBack.speed + 1.0
} else {
aiFollowBack.speed
}
navigationService.navigateToLocation(pet, player.transform, speed)
} catch (e: Exception) {
loggingService.warn("Failed to execute PathfinderFollowOwner.", e)
}
}
} | apache-2.0 | 4bab4e508559ac18e1d338cbda390104 | 38.314607 | 162 | 0.694969 | 4.51938 | false | false | false | false |
Shynixn/PetBlocks | petblocks-sponge-plugin/src/test/java/integrationtest/PersistenceMySQLIT.kt | 1 | 23407 | @file:Suppress("UNCHECKED_CAST")
package integrationtest
import ch.vorburger.mariadb4j.DB
import ch.vorburger.mariadb4j.DBConfigurationBuilder
import com.github.shynixn.petblocks.api.PetBlocksApi
import com.github.shynixn.petblocks.api.business.enumeration.ParticleType
import com.github.shynixn.petblocks.api.business.enumeration.Permission
import com.github.shynixn.petblocks.api.business.enumeration.Version
import com.github.shynixn.petblocks.api.business.proxy.PluginProxy
import com.github.shynixn.petblocks.api.business.service.*
import com.github.shynixn.petblocks.api.persistence.context.SqlDbContext
import com.github.shynixn.petblocks.api.persistence.entity.*
import com.github.shynixn.petblocks.core.logic.business.service.*
import com.github.shynixn.petblocks.core.logic.persistence.context.SqlDbContextImpl
import com.github.shynixn.petblocks.core.logic.persistence.entity.AIMovementEntity
import com.github.shynixn.petblocks.core.logic.persistence.repository.PetMetaSqlRepository
import com.github.shynixn.petblocks.sponge.logic.business.service.ConfigurationServiceImpl
import com.github.shynixn.petblocks.sponge.logic.business.service.EntityServiceImpl
import com.github.shynixn.petblocks.sponge.logic.business.service.ItemTypeServiceImpl
import com.github.shynixn.petblocks.sponge.logic.business.service.YamlServiceImpl
import helper.MockedLoggingService
import org.apache.commons.io.FileUtils
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.mockito.Mockito
import org.spongepowered.api.asset.Asset
import org.spongepowered.api.entity.living.player.Player
import org.spongepowered.api.plugin.PluginContainer
import java.io.File
import java.nio.file.Paths
import java.sql.DriverManager
import java.util.*
import java.util.logging.Logger
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
class PersistenceMySQLIT {
/**
* Given
* initial empty database and production configuration in config.yml
* When
* getAll is called the database should still be empty and when getOrCreateFromPlayerUUID with a new uuid is called
* Then
* the default pet with the default production configuration from the config.yml should be generated.
*/
@Test
fun getOrCreateFromPlayerUUID_ProductionConfiguration_ShouldGenerateCorrectPet() {
// Arrange
val classUnderTest = createWithDependencies()
val uuid = UUID.fromString("c7d21810-d2a0-407d-a389-14efd3eb79d2")
val player = Mockito.mock(Player::class.java)
Mockito.`when`(player.uniqueId).thenReturn(uuid)
// Act
val initialSize = classUnderTest.getAll().get().size
val actual = classUnderTest.getPetMetaFromPlayer(player)
// Assert
Assertions.assertEquals(0, initialSize)
Assertions.assertEquals(1, actual.id)
Assertions.assertEquals(false, actual.enabled)
Assertions.assertEquals("Kenny's Pet", actual.displayName)
Assertions.assertEquals(true, actual.soundEnabled)
Assertions.assertEquals(true, actual.particleEnabled)
Assertions.assertEquals(1, actual.skin.id)
Assertions.assertEquals("GRASS", actual.skin.typeName)
Assertions.assertEquals(0, actual.skin.dataValue)
Assertions.assertEquals("", actual.skin.nbtTag)
Assertions.assertEquals("", actual.skin.owner)
Assertions.assertEquals(1, actual.playerMeta.id)
Assertions.assertEquals("Kenny", actual.playerMeta.name)
Assertions.assertEquals(9, actual.aiGoals.size)
Assertions.assertEquals("hopping", (actual.aiGoals[0] as AIMovementEntity).type)
Assertions.assertEquals(1.0, (actual.aiGoals[0] as AIMovementEntity).climbingHeight)
Assertions.assertEquals(1.0, (actual.aiGoals[0] as AIMovementEntity).movementSpeed)
Assertions.assertEquals(-1.0, (actual.aiGoals[0] as AIMovementEntity).movementYOffSet)
Assertions.assertEquals("CHICKEN_WALK", (actual.aiGoals[0] as AIMovementEntity).movementSound.name)
Assertions.assertEquals(1.0, (actual.aiGoals[0] as AIMovementEntity).movementSound.volume)
Assertions.assertEquals(1.0, (actual.aiGoals[0] as AIMovementEntity).movementSound.pitch)
Assertions.assertEquals(
ParticleType.NONE.name,
(actual.aiGoals[0] as AIMovementEntity).movementParticle.typeName
)
Assertions.assertEquals(1, (actual.aiGoals[0] as AIMovementEntity).movementParticle.amount)
Assertions.assertEquals("follow-owner", (actual.aiGoals[1] as AIFollowOwner).type)
Assertions.assertEquals(3.0, (actual.aiGoals[1] as AIFollowOwner).distanceToOwner)
Assertions.assertEquals(50.0, (actual.aiGoals[1] as AIFollowOwner).maxRange)
Assertions.assertEquals(1.5, (actual.aiGoals[1] as AIFollowOwner).speed)
Assertions.assertEquals("float-in-water", (actual.aiGoals[2] as AIFloatInWater).type)
Assertions.assertEquals("feeding", (actual.aiGoals[3] as AIFeeding).type)
Assertions.assertEquals("391", (actual.aiGoals[3] as AIFeeding).typeName)
Assertions.assertEquals(ParticleType.HEART.name, (actual.aiGoals[3] as AIFeeding).clickParticle.typeName)
Assertions.assertEquals("EAT", (actual.aiGoals[3] as AIFeeding).clickSound.name)
Assertions.assertEquals("ambient-sound", (actual.aiGoals[5] as AIAmbientSound).type)
Assertions.assertEquals("CHICKEN_IDLE", (actual.aiGoals[5] as AIAmbientSound).sound.name)
}
/**
* Given
* initial empty database and production configuration in config.yml
* When
* getAll is called the database should still be empty and when getOrCreateFromPlayerUUID is called
* Then
* the default pet with the default production configuration should be correctly editable and storeAble again.
*/
@Test
fun getOrCreateFromPlayerUUID_ProductionConfiguration_ShouldAllowChangingPet() {
// Arrange
val classUnderTest = createWithDependencies()
val uuid = UUID.fromString("c7d21810-d2a0-407d-a389-14efd3eb79d2")
val player = Mockito.mock(Player::class.java)
Mockito.`when`(player.uniqueId).thenReturn(uuid)
// Act
val initialSize = classUnderTest.getAll().get().size
val petMeta = classUnderTest.getPetMetaFromPlayer(player)
petMeta.enabled = true
petMeta.displayName = "This is a very long displayname in order to check if column size is dynamic"
petMeta.soundEnabled = false
petMeta.particleEnabled = false
petMeta.skin.typeName = "DIRT"
petMeta.skin.dataValue = 2
petMeta.skin.nbtTag = "{Unbreakable:1}"
petMeta.skin.owner = "Pikachu"
petMeta.playerMeta.name = "Superman"
(petMeta.aiGoals[0] as AIHopping).climbingHeight = 23.5
(petMeta.aiGoals[0] as AIHopping).movementSpeed = 105.3
(petMeta.aiGoals[0] as AIHopping).movementYOffSet = 93.4
(petMeta.aiGoals[0] as AIHopping).movementParticle.offSetY = 471.2
(petMeta.aiGoals[0] as AIHopping).movementSound.pitch = 44.2
(petMeta.aiGoals[1] as AIFollowOwner).maxRange = 100.2
(petMeta.aiGoals[1] as AIFollowOwner).distanceToOwner = 14.45
(petMeta.aiGoals[1] as AIFollowOwner).speed = 42.2
(petMeta.aiGoals[2] as AIFloatInWater).userId = "43"
(petMeta.aiGoals[3] as AIFeeding).clickParticle.offSetZ = 25.4
(petMeta.aiGoals[3] as AIFeeding).clickSound.name = "COOKIE_SOUND"
(petMeta.aiGoals[3] as AIFeeding).dataValue = 4
(petMeta.aiGoals[3] as AIFeeding).typeName = "POWER_BANK"
(petMeta.aiGoals[5] as AIAmbientSound).sound.volume = 41.55
classUnderTest.save(petMeta).get()
val actual = classUnderTest.getPetMetaFromPlayer(player)
// Assert
Assertions.assertEquals(0, initialSize)
Assertions.assertEquals(1, actual.id)
Assertions.assertEquals(true, actual.enabled)
Assertions.assertEquals(
"This is a very long displayname in order to check if column size is dynamic",
actual.displayName
)
Assertions.assertEquals(false, actual.soundEnabled)
Assertions.assertEquals(false, actual.particleEnabled)
Assertions.assertEquals(1, actual.skin.id)
Assertions.assertEquals("DIRT", actual.skin.typeName)
Assertions.assertEquals(2, actual.skin.dataValue)
Assertions.assertEquals("{Unbreakable:1}", actual.skin.nbtTag)
Assertions.assertEquals("Pikachu", actual.skin.owner)
Assertions.assertEquals(1, actual.playerMeta.id)
Assertions.assertEquals("Superman", actual.playerMeta.name)
Assertions.assertEquals("hopping", (actual.aiGoals[0] as AIMovementEntity).type)
Assertions.assertEquals(23.5, (actual.aiGoals[0] as AIMovementEntity).climbingHeight)
Assertions.assertEquals(105.3, (actual.aiGoals[0] as AIMovementEntity).movementSpeed)
Assertions.assertEquals(93.4, (actual.aiGoals[0] as AIMovementEntity).movementYOffSet)
Assertions.assertEquals(44.2, (actual.aiGoals[0] as AIMovementEntity).movementSound.pitch)
Assertions.assertEquals(471.2, (actual.aiGoals[0] as AIMovementEntity).movementParticle.offSetY)
Assertions.assertEquals("follow-owner", (actual.aiGoals[1] as AIFollowOwner).type)
Assertions.assertEquals(14.45, (actual.aiGoals[1] as AIFollowOwner).distanceToOwner)
Assertions.assertEquals(100.2, (actual.aiGoals[1] as AIFollowOwner).maxRange)
Assertions.assertEquals(42.2, (actual.aiGoals[1] as AIFollowOwner).speed)
Assertions.assertEquals("43", (actual.aiGoals[2] as AIFloatInWater).userId!!)
Assertions.assertEquals("feeding", (actual.aiGoals[3] as AIFeeding).type)
Assertions.assertEquals("POWER_BANK", (actual.aiGoals[3] as AIFeeding).typeName)
Assertions.assertEquals(4, (actual.aiGoals[3] as AIFeeding).dataValue)
Assertions.assertEquals("COOKIE_SOUND", (actual.aiGoals[3] as AIFeeding).clickSound.name)
Assertions.assertEquals(25.4, (actual.aiGoals[3] as AIFeeding).clickParticle.offSetZ)
Assertions.assertEquals("ambient-sound", (actual.aiGoals[5] as AIAmbientSound).type)
Assertions.assertEquals(41.55, (actual.aiGoals[5] as AIAmbientSound).sound.volume)
}
companion object {
private var database: DB? = null
private var dbContext: SqlDbContext? = null
fun createWithDependencies(): PersistencePetMetaService {
if (dbContext != null) {
dbContext!!.close()
}
if (database != null) {
database!!.stop()
}
val config = DBConfigurationBuilder.newBuilder()
config.setPort(3306)
config.addArg("--user=root")
database = DB.newEmbeddedDB(config.build())
database!!.start()
val sourceFolder = File("../petblocks-core/src/main/resources")
val integrationDirectory = File("integration-test")
if (integrationDirectory.exists()) {
integrationDirectory.deleteRecursively()
integrationDirectory.mkdir()
}
FileUtils.copyDirectory(sourceFolder, integrationDirectory)
var content = FileUtils.readFileToString(File("integration-test/assets/petblocks", "config.yml"), "UTF-8")
content = content.replace("type: 'sqlite'", "type: 'mysql'").replace("database: ''", "database: 'db'")
.replace("username: ''", "username: 'root'")
FileUtils.write(File("integration-test/assets/petblocks", "config.yml"), content, "UTF-8")
DriverManager.getConnection("jdbc:mysql://localhost:3306/?user=root&password=&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC")
.use { conn ->
conn.createStatement().use { statement ->
statement.executeUpdate("CREATE DATABASE db")
}
}
val plugin = Mockito.mock(PluginContainer::class.java)
Mockito.`when`(plugin.getAsset(Mockito.anyString())).then { p ->
val path = p.getArgument<String>(0)
val url = File("integration-test/$path").toURI()
val asset = Mockito.mock(Asset::class.java)
Mockito.`when`(asset.url).thenReturn(url.toURL())
Optional.of(asset)
}
val configurationService = ConfigurationServiceImpl(
Paths.get("integration-test/assets/petblocks")
, LoggingUtilServiceImpl(Logger.getAnonymousLogger()), plugin
)
val aiService = AIServiceImpl(
LoggingUtilServiceImpl(Logger.getAnonymousLogger()),
MockedProxyService(),
YamlServiceImpl(),
configurationService
)
val localizationService =
LocalizationServiceImpl(configurationService, LoggingUtilServiceImpl(Logger.getAnonymousLogger()))
localizationService.reload()
val guiItemLoadService =
GUIItemLoadServiceImpl(
configurationService,
ItemTypeServiceImpl(),
aiService,
localizationService
)
val method = PetBlocksApi::class.java.getDeclaredMethod("initializePetBlocks", PluginProxy::class.java)
method.isAccessible = true
method.invoke(PetBlocksApi, MockedPluginProxy())
EntityServiceImpl(
MockedProxyService(),
Mockito.mock(PetService::class.java),
YamlSerializationServiceImpl(),
Version.VERSION_1_12_R1,
aiService,
LoggingUtilServiceImpl(Logger.getAnonymousLogger()),
ItemTypeServiceImpl()
)
dbContext = SqlDbContextImpl(configurationService, LoggingUtilServiceImpl(Logger.getAnonymousLogger()))
val sqlite = PetMetaSqlRepository(dbContext!!, aiService, guiItemLoadService, configurationService)
return PersistencePetMetaServiceImpl(
MockedProxyService(),
sqlite,
MockedConcurrencyService(),
MockedEventService(),
aiService,
MockedLoggingService()
)
}
}
class MockedPluginProxy : PluginProxy {
/**
* Gets the installed version of the plugin.
*/
override val version: String
get() = ""
/**
* Gets the server version this plugin is currently running on.
*/
override fun getServerVersion(): Version {
return Version.VERSION_UNKNOWN
}
/**
* Gets a business logic from the PetBlocks plugin.
* All types in the service package can be accessed.
* Throws a [IllegalArgumentException] if the service could not be found.
* @param S the type of service class.
*/
override fun <S> resolve(service: Any): S {
throw IllegalArgumentException()
}
/**
* Creates a new entity from the given [entity].
* Throws a [IllegalArgumentException] if the entity could not be found.
* @param E the type of entity class.
*/
override fun <E> create(entity: Any): E {
throw IllegalArgumentException()
}
}
class MockedProxyService : ProxyService {
/**
* Gets a list of points between 2 locations.
*/
override fun <L> getPointsBetweenLocations(location1: L, location2: L, amount: Int): List<L> {
throw IllegalArgumentException()
}
/**
* Applies the given [potionEffect] to the given [player].
*/
override fun <P> applyPotionEffect(player: P, potionEffect: PotionEffect) {
}
/**
* Drops the given item at the given position.
*/
override fun <L, I> dropInventoryItem(location: L, item: I) {
throw IllegalArgumentException()
}
/**
* Gets the inventory item at the given index.
*/
override fun <I, IT> getInventoryItem(inventory: I, index: Int): IT? {
throw IllegalArgumentException()
}
/**
* Gets if the given player has got the given permission.
*/
override fun <P> hasPermission(player: P, permission: String): Boolean {
throw IllegalArgumentException()
}
/**
* Closes the inventory of the given player.
*/
override fun <P> closeInventory(player: P) {
throw IllegalArgumentException()
}
/**
* Gets if the given inventory belongs to a player. Returns null if not.
*/
override fun <P, I> getPlayerFromInventory(inventory: I): P? {
throw IllegalArgumentException()
}
/**
* Gets the lower inventory of an inventory.
*/
override fun <I> getLowerInventory(inventory: I): I {
throw IllegalArgumentException()
}
/**
* Clears the given inventory.
*/
override fun <I> clearInventory(inventory: I) {
throw IllegalArgumentException()
}
/**
* Opens a new inventory for the given player.
*/
override fun <P, I> openInventory(player: P, title: String, size: Int): I {
throw IllegalArgumentException()
}
/**
* Updates the inventory.
*/
override fun <I, IT> setInventoryItem(inventory: I, index: Int, item: IT) {
throw IllegalArgumentException()
}
/**
* Updates the given player inventory.
*/
override fun <P> updateInventory(player: P) {
throw IllegalArgumentException()
}
/**
* Gets if the given instance can be converted to a player.
*/
override fun <P> isPlayer(instance: P): Boolean {
return true
}
/**
* Gets the name of a player.
*/
override fun <P> getPlayerName(player: P): String {
return "Kenny"
}
/**
* Gets the player from the given UUID.
*/
override fun <P> getPlayerFromUUID(uuid: String): P {
throw IllegalArgumentException()
}
/**
* Gets the entity id.
*/
override fun <E> getEntityId(entity: E): Int {
throw IllegalArgumentException()
}
/**
* Gets the location of the player.
*/
override fun <L, P> getPlayerLocation(player: P): L {
throw IllegalArgumentException()
}
/**
* Converts the given [location] to a [Position].
*/
override fun <L> toPosition(location: L): Position {
throw IllegalArgumentException()
}
/**
* Converts the given [position] to a Location..
*/
override fun <L> toLocation(position: Position): L {
throw IllegalArgumentException()
}
/**
* Gets the looking direction of the player.
*/
override fun <P> getDirectionVector(player: P): Position {
throw IllegalArgumentException()
}
/**
* Gets the item in the player hand.
*/
override fun <P, I> getPlayerItemInHand(player: P, offhand: Boolean): I? {
throw IllegalArgumentException()
}
/**
* Sets the item in the player hand.
*/
override fun <P, I> setPlayerItemInHand(player: P, itemStack: I, offhand: Boolean) {
throw IllegalArgumentException()
}
/**
* Gets if the given player has got the given permission.
*/
override fun <P> hasPermission(player: P, permission: Permission): Boolean {
throw IllegalArgumentException()
}
/**
* Gets the player uuid.
*/
override fun <P> getPlayerUUID(player: P): String {
return (player as Player).uniqueId.toString()
}
/**
* Sends a message to the [sender].
*/
override fun <S> sendMessage(sender: S, message: String) {
throw IllegalArgumentException()
}
/**
* Executes a server command.
*/
override fun executeServerCommand(message: String) {
throw IllegalArgumentException()
}
/**
* Executes a player command.
*/
override fun <P> executePlayerCommand(player: P, message: String) {
throw IllegalArgumentException()
}
/**
* Gets if the player is currently online.
*/
override fun <P> isPlayerOnline(player: P): Boolean {
TODO("Not yet implemented")
}
/**
* Gets if the player with the given uuid is currently online.
*/
override fun isPlayerUUIDOnline(uuid: String): Boolean {
TODO("Not yet implemented")
}
}
class MockedConcurrencyService : ConcurrencyService {
/**
* Runs the given [function] synchronised with the given [delayTicks] and [repeatingTicks].
*/
override fun runTaskSync(delayTicks: Long, repeatingTicks: Long, function: () -> Unit) {
function.invoke()
}
/**
* Runs the given [function] asynchronous with the given [delayTicks] and [repeatingTicks].
*/
override fun runTaskAsync(delayTicks: Long, repeatingTicks: Long, function: () -> Unit) {
function.invoke()
}
}
class MockedEventService : EventService {
/**
* Calls a framework event and returns if it was cancelled.
*/
override fun callEvent(event: Any): Boolean {
return false
}
}
}
| apache-2.0 | 63d9e3d16873b87a08b3f40a623c0c40 | 38.672881 | 189 | 0.638484 | 4.65533 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/support/ClassBytesRepository.kt | 1 | 6129 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.gradle.kotlin.dsl.support
import org.gradle.internal.classpath.ClassPath
import org.gradle.internal.classpath.DefaultClassPath
import org.gradle.util.TextUtil.normaliseFileSeparators
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import com.google.common.annotations.VisibleForTesting
import java.io.Closeable
import java.io.File
import java.util.jar.JarFile
@VisibleForTesting
fun classPathBytesRepositoryFor(classPath: List<File>, classPathDependencies: List<File> = emptyList()) =
ClassBytesRepository(DefaultClassPath.of(classPath), DefaultClassPath.of(classPathDependencies))
private
typealias ClassBytesSupplier = () -> ByteArray
private
typealias ClassBytesIndex = (String) -> ClassBytesSupplier?
/**
* Repository providing access to class bytes by Kotlin source names.
*
* Follows the one directory per package name segment convention.
* Keeps JAR files open for fast lookup, must be closed.
*/
@VisibleForTesting
class ClassBytesRepository(classPath: ClassPath, classPathDependencies: ClassPath = ClassPath.EMPTY) : Closeable {
private
val openJars = mutableMapOf<File, JarFile>()
private
val classPathFiles: List<File> = classPath.asFiles
private
val classBytesIndex = (classPathFiles + classPathDependencies.asFiles).map { classBytesIndexFor(it) }
/**
* Class file bytes for Kotlin source name, if found.
*/
fun classBytesFor(sourceName: String): ByteArray? =
classBytesSupplierForSourceName(sourceName)?.let { it() }
/**
* All found class files bytes by Kotlin source name.
*/
fun allClassesBytesBySourceName(): Sequence<Pair<String, ClassBytesSupplier>> =
classPathFiles.asSequence()
.flatMap { sourceNamesFrom(it) }
.mapNotNull { sourceName ->
classBytesSupplierForSourceName(sourceName)?.let { sourceName to it }
}
private
fun classBytesSupplierForSourceName(sourceName: String): ClassBytesSupplier? =
classFilePathCandidatesFor(sourceName)
.mapNotNull(::classBytesSupplierForFilePath)
.firstOrNull()
private
fun classBytesSupplierForFilePath(classFilePath: String): ClassBytesSupplier? =
classBytesIndex.firstNotNullResult { it(classFilePath) }
private
fun sourceNamesFrom(entry: File): Sequence<String> =
when {
entry.isClassPathArchive -> sourceNamesFromJar(entry)
entry.isDirectory -> sourceNamesFromDir(entry)
else -> emptySequence()
}
private
fun sourceNamesFromJar(jar: File): Sequence<String> =
openJarFile(jar).run {
entries().asSequence()
.filter { it.name.isClassFilePath }
.map { kotlinSourceNameOf(it.name) }
}
private
fun sourceNamesFromDir(dir: File): Sequence<String> =
dir.walkTopDown()
.filter { it.name.isClassFilePath }
.map { kotlinSourceNameOf(normaliseFileSeparators(it.relativeTo(dir).path)) }
private
fun classBytesIndexFor(entry: File): ClassBytesIndex =
when {
entry.isClassPathArchive -> jarClassBytesIndexFor(entry)
entry.isDirectory -> directoryClassBytesIndexFor(entry)
else -> { _ -> null }
}
private
fun jarClassBytesIndexFor(jar: File): ClassBytesIndex = { classFilePath ->
openJarFile(jar).run {
getJarEntry(classFilePath)?.let { jarEntry ->
{ getInputStream(jarEntry).use { jarInput -> jarInput.readBytes() } }
}
}
}
private
fun directoryClassBytesIndexFor(dir: File): ClassBytesIndex = { classFilePath ->
dir.resolve(classFilePath).takeIf { it.isFile }?.let { classFile -> { classFile.readBytes() } }
}
private
fun openJarFile(file: File) =
openJars.computeIfAbsent(file, ::JarFile)
override fun close() {
openJars.values.forEach(JarFile::close)
}
}
/**
* See https://docs.oracle.com/javase/8/docs/technotes/tools/findingclasses.html#userclass
*/
private
val File.isClassPathArchive
get() = extension.run { equals("jar", ignoreCase = true) || equals("zip", ignoreCase = true) }
private
val String.isClassFilePath
get() = endsWith(classFileExtension)
&& !endsWith("package-info$classFileExtension")
&& !matches(compilerGeneratedClassFilePath)
private
const val classFileExtension = ".class"
private
val compilerGeneratedClassFilePath = Regex(".*\\$\\d+\\.class$")
private
val slashOrDollar = Regex("[/$]")
@VisibleForTesting
fun kotlinSourceNameOf(classFilePath: String): String =
classFilePath
.removeSuffix(classFileExtension)
.removeSuffix("Kt")
.replace(slashOrDollar, ".")
@VisibleForTesting
fun classFilePathCandidatesFor(sourceName: String): Sequence<String> =
sourceName.replace(".", "/").let { path ->
candidateClassFiles(path) + nestedClassFilePathCandidatesFor(path)
}
private
fun nestedClassFilePathCandidatesFor(path: String): Sequence<String> =
generateSequence({ nestedClassNameFor(path) }, ::nestedClassNameFor)
.flatMap(::candidateClassFiles)
private
fun candidateClassFiles(path: String) =
sequenceOf("$path$classFileExtension", "${path}Kt$classFileExtension")
private
fun nestedClassNameFor(path: String) = path.run {
lastIndexOf('/').takeIf { it > 0 }?.let { index ->
substring(0, index) + '$' + substring(index + 1)
}
}
| apache-2.0 | fd937b5150306f88a2294c30d5e651b5 | 29.492537 | 114 | 0.694077 | 4.509934 | false | false | false | false |
facebook/litho | sample/src/main/java/com/facebook/samples/litho/documentation/props/PropResourceTypeParentKComponent.kt | 1 | 1933 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.samples.litho.documentation.props
import android.content.res.Resources
import androidx.core.content.ContextCompat
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.colorRes
import com.facebook.litho.dimenRes
import com.facebook.litho.stringRes
import com.facebook.samples.litho.R
// start_example
class PropResourceTypeParentKComponent(
private val useResourceType: Boolean,
) : KComponent() {
override fun ComponentScope.render(): Component {
if (!useResourceType) {
// start_prop_without_resource_type_usage
val res: Resources = context.getResources()
return PropWithoutResourceTypeKComponent(
name = res.getString(R.string.name_string),
size = dimenRes(R.dimen.primary_text_size),
color = ContextCompat.getColor(context.getAndroidContext(), R.color.primaryColor))
// end_prop_without_resource_type_usage
} else {
// start_prop_with_resource_type_usage
return PropWithResourceTypeKComponent(
name = stringRes(R.string.name_string),
size = dimenRes(R.dimen.primary_text_size),
color = colorRes(R.color.primaryColor))
// end_prop_with_resource_type_usage
}
}
}
// end_example
| apache-2.0 | c061efecbca9c4b2355a25ad972d820f | 34.796296 | 92 | 0.731505 | 4.104034 | false | false | false | false |
albertoruibal/karballo | karballo-jvm/src/test/kotlin/karballo/PerformanceTest.kt | 1 | 7198 | package karballo
import karballo.bitboard.AttacksInfo
import karballo.evaluation.CompleteEvaluator
import karballo.evaluation.SimplifiedEvaluator
import karballo.hash.ZobristKey
import karballo.movegen.LegalMoveGenerator
import karballo.movegen.MagicMoveGenerator
import karballo.movegen.MoveGenerator
import karballo.search.SearchEngine
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.experimental.categories.Category
/**
* Helps searching for bottlenecks
*/
class PerformanceTest {
lateinit var movegen: MoveGenerator
lateinit var legalMovegen: MoveGenerator
lateinit var testBoards: Array<Board>
var tests = arrayOf("4r1k1/p1pb1ppp/Qbp1r3/8/1P6/2Pq1B2/R2P1PPP/2B2RK1 b - - ",
"7r/2qpkp2/p3p3/6P1/1p2b2r/7P/PPP2QP1/R2N1RK1 b - - ",
"r1bq1rk1/pp4bp/2np4/2p1p1p1/P1N1P3/1P1P1NP1/1BP1QPKP/1R3R2 b - - ",
"8/2kPR3/5q2/5N2/8/1p1P4/1p6/1K6 w - - ",
"2r1r3/p3bk1p/1pnqpppB/3n4/3P2Q1/PB3N2/1P3PPP/3RR1K1 w - - ",
"8/2p5/7p/pP2k1pP/5pP1/8/1P2PPK1/8 w - - ",
"8/5p1p/1p2pPk1/p1p1P3/P1P1K2b/4B3/1P5P/8 w - - ",
"rn2r1k1/pp3ppp/8/1qNp4/3BnQb1/5N2/PPP2PPP/2KR3R b - - ",
"r3kb1r/1p1b1p2/p1nppp2/7p/4PP2/qNN5/P1PQB1PP/R4R1K w kq - ",
"r3r1k1/pp1bp2p/1n2q1P1/6b1/1B2B3/5Q2/5PPP/1R3RK1 w - - ",
"r3k2r/pb3pp1/2p1qnnp/1pp1P3/Q1N4B/2PB1P2/P5PP/R4RK1 w kq - ",
"r1b1r1k1/ppp2ppp/2nb1q2/8/2B5/1P1Q1N2/P1PP1PPP/R1B2RK1 w - - ",
"rnb1kb1r/1p3ppp/p5q1/4p3/3N4/4BB2/PPPQ1P1P/R3K2R w KQkq - ",
"r1bqr1k1/pp1n1ppp/5b2/4N1B1/3p3P/8/PPPQ1PP1/2K1RB1R w - - ",
"2r2rk1/1bpR1p2/1pq1pQp1/p3P2p/P1PR3P/5N2/2P2PPK/8 w - - ",
"8/pR4pk/1b6/2p5/N1p5/8/PP1r2PP/6K1 b - - ",
"r1b1qrk1/ppBnppb1/2n4p/1NN1P1p1/3p4/8/PPP1BPPP/R2Q1R1K w - - ",
"8/8/4b1p1/2Bp3p/5P1P/1pK1Pk2/8/8 b - - ",
"r3k2r/pp1n1ppp/1qpnp3/3bN1PP/3P2Q1/2B1R3/PPP2P2/2KR1B2 w kq - ",
"r1bqk2r/pppp1Npp/8/2bnP3/8/6K1/PB4PP/RN1Q3R b kq - ",
"r4r1k/pbnq1ppp/np3b2/3p1N2/5B2/2N3PB/PP3P1P/R2QR1K1 w - - ",
"r2qr2k/pbp3pp/1p2Bb2/2p5/2P2P2/3R2P1/PP2Q1NP/5RK1 b - - ",
"5r2/1p4r1/3kp1b1/1Pp1p2p/2PpP3/q2B1PP1/3Q2K1/1R5R b - - ",
"8/7p/8/7P/1p6/1p5P/1P2Q1pk/1K6 w - - ",
"r5k1/p4n1p/6p1/2qPp3/2p1P1Q1/8/1rB3PP/R4R1K b - - ",
"1r4k1/1q2pN1p/3pPnp1/8/2pQ4/P5PP/5P2/3R2K1 b - - ",
"2rq1rk1/pb3ppp/1p2pn2/4N3/1b1PPB2/4R1P1/P4PBP/R2Q2K1 w - - ")
@Before
@Throws(Exception::class)
fun setUp() {
movegen = MagicMoveGenerator()
legalMovegen = LegalMoveGenerator()
testBoards = Array(tests.size, { Board() })
for (i in tests.indices) {
testBoards[i] = Board()
testBoards[i].fen = tests[i]
}
}
@Test
@Category(SlowTest::class)
fun testCompleteEvaluatorPerf() {
val attacksInfo = AttacksInfo()
val completeEvaluator = CompleteEvaluator()
val t1 = System.currentTimeMillis()
var positions: Long = 0
for (i in 0..9999) {
for (testBoard in testBoards) {
completeEvaluator.evaluate(testBoard, attacksInfo)
positions++
}
}
val t2 = System.currentTimeMillis()
val pps = 1000 * positions / (t2 - t1 + 1)
println("Positions evaluated per second (complete) = " + pps)
assertTrue(pps > 100000)
}
@Test
@Category(SlowTest::class)
fun testSimplifiedEvaluatorPerf() {
val attacksInfo = AttacksInfo()
val simplifiedEvaluator = SimplifiedEvaluator()
val t1 = System.currentTimeMillis()
var positions: Long = 0
for (i in 0..9999) {
for (testBoard in testBoards) {
simplifiedEvaluator.evaluate(testBoard, attacksInfo)
positions++
}
}
val t2 = System.currentTimeMillis()
val pps = 1000 * positions / (t2 - t1 + 1)
println("Positions evaluated per second (simplified) = " + pps)
assertTrue(pps > 100000)
}
@Test
@Category(SlowTest::class)
fun testPseudoLegalMoveGenPerf() {
val t1 = System.currentTimeMillis()
var positions: Long = 0
val moves = IntArray(256)
for (i in 0..9999) {
for (j in tests.indices) {
movegen.generateMoves(testBoards[j], moves, 0)
positions++
}
}
val t2 = System.currentTimeMillis()
val pps = 1000 * positions / (t2 - t1 + 1)
println("Positions with Pseudo legal moves generated per second = " + pps)
}
@Test
@Category(SlowTest::class)
fun testMoveIteratorNewNewPerf() {
val searchEngine = SearchEngine(Config())
val moveIterator = searchEngine.nodes[0].moveIterator
val t1 = System.currentTimeMillis()
var positions: Long = 0
for (i in 0..49999) {
for (j in tests.indices) {
moveIterator.setBoard(testBoards[j])
moveIterator.genMoves(0)
while (moveIterator.next() != 0) {
}
positions++
}
}
val t2 = System.currentTimeMillis()
val pps = 1000 * positions / (t2 - t1 + 1)
println("Positions with all moves generated, sorted and transversed per second = " + pps)
}
@Test
@Category(SlowTest::class)
fun testDoMovePerf() {
val t1 = System.currentTimeMillis()
var moveCount: Long = 0
val moves = IntArray(256)
for (j in tests.indices) {
val moveIndex = movegen.generateMoves(testBoards[j], moves, 0)
for (k in 0..moveIndex - 1) {
for (i in 0..9999) {
if (testBoards[j].doMove(moves[k])) {
testBoards[j].undoMove()
}
moveCount++
}
}
}
val t2 = System.currentTimeMillis()
println("Moves done/undone per second = " + 1000 * moveCount / (t2 - t1 + 1))
}
@Test
@Category(SlowTest::class)
fun testLegalMoveGenPerf() {
val t1 = System.currentTimeMillis()
var positions: Long = 0
val moves = IntArray(256)
for (i in 0..9999) {
for (j in tests.indices) {
legalMovegen.generateMoves(testBoards[j], moves, 0)
positions++
}
}
val t2 = System.currentTimeMillis()
val pps = 1000 * positions / (t2 - t1 + 1)
println("Positions with legal moves generated per second = " + pps)
}
@Test
@Category(SlowTest::class)
fun testZobrishKeyPerf() {
val t1 = System.currentTimeMillis()
var keys: Long = 0
for (i in 0..9999) {
for (j in tests.indices) {
ZobristKey.getKey(testBoards[j])
keys++
}
}
val t2 = System.currentTimeMillis()
val pps = 1000 * keys / (t2 - t1 + 1)
println("keys generated per second = " + pps)
}
} | mit | dc4ee04fd0cda4885c9488ae4ffbd253 | 34.995 | 97 | 0.57516 | 2.834974 | false | true | false | false |
camsteffen/polite | src/main/java/me/camsteffen/polite/model/DaysOfWeekEntity.kt | 1 | 1449 | package me.camsteffen.polite.model
import org.threeten.bp.DayOfWeek
import org.threeten.bp.DayOfWeek.FRIDAY
import org.threeten.bp.DayOfWeek.MONDAY
import org.threeten.bp.DayOfWeek.SATURDAY
import org.threeten.bp.DayOfWeek.SUNDAY
import org.threeten.bp.DayOfWeek.THURSDAY
import org.threeten.bp.DayOfWeek.TUESDAY
import org.threeten.bp.DayOfWeek.WEDNESDAY
import java.util.EnumSet
class DaysOfWeekEntity(
val monday: Int,
val tuesday: Int,
val wednesday: Int,
val thursday: Int,
val friday: Int,
val saturday: Int,
val sunday: Int
) {
constructor(days: Set<DayOfWeek>) : this(
monday = days.contains(MONDAY).toInt(),
tuesday = days.contains(TUESDAY).toInt(),
wednesday = days.contains(WEDNESDAY).toInt(),
thursday = days.contains(THURSDAY).toInt(),
friday = days.contains(FRIDAY).toInt(),
saturday = days.contains(SATURDAY).toInt(),
sunday = days.contains(SUNDAY).toInt()
)
fun toDayOfWeekSet(): Set<DayOfWeek> {
return EnumSet.noneOf(DayOfWeek::class.java).apply {
if (monday != 0) add(MONDAY)
if (tuesday != 0) add(TUESDAY)
if (wednesday != 0) add(WEDNESDAY)
if (thursday != 0) add(THURSDAY)
if (friday != 0) add(FRIDAY)
if (saturday != 0) add(SATURDAY)
if (sunday != 0) add(SUNDAY)
}
}
}
private fun Boolean.toInt(): Int = if (this) 1 else 0
| mpl-2.0 | f61aeca3aca35f63466edad7f4328279 | 31.2 | 60 | 0.647343 | 3.895161 | false | false | false | false |
google/horologist | network-awareness/src/main/java/com/google/android/horologist/networks/rules/NetworkingRules.kt | 1 | 5897 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.networks.rules
import com.google.android.horologist.networks.ExperimentalHorologistNetworksApi
import com.google.android.horologist.networks.data.NetworkInfo
import com.google.android.horologist.networks.data.NetworkInfo.Bluetooth
import com.google.android.horologist.networks.data.NetworkInfo.Cellular
import com.google.android.horologist.networks.data.NetworkInfo.Wifi
import com.google.android.horologist.networks.data.NetworkStatus
import com.google.android.horologist.networks.data.Networks
import com.google.android.horologist.networks.data.RequestType
import com.google.android.horologist.networks.data.RequestType.MediaRequest
import com.google.android.horologist.networks.data.RequestType.MediaRequest.MediaRequestType.Download
/**
* Implementation of app rules for network usage. A way to implement logic such as
* - Don't download large media items over BLE.
* - Only use LTE for downloads if user enabled.
* - Don't use metered LTE for logs and metrics.
*/
@ExperimentalHorologistNetworksApi
public interface NetworkingRules {
/**
* Is this request considered high bandwidth and should activate LTE or Wifi.
*/
public fun isHighBandwidthRequest(requestType: RequestType): Boolean
/**
* Checks whether this request is allowed on the current network type.
*/
public fun checkValidRequest(
requestType: RequestType,
currentNetworkInfo: NetworkInfo
): RequestCheck
/**
* Returns the preferred network for a request.
*
* Null means no suitable network.
*/
public fun getPreferredNetwork(
networks: Networks,
requestType: RequestType
): NetworkStatus?
/**
* Lenient rules that allow most request types on any network but prefer
* Wifi when available.
*/
@ExperimentalHorologistNetworksApi
public object Lenient : NetworkingRules {
override fun isHighBandwidthRequest(requestType: RequestType): Boolean {
return requestType is MediaRequest
}
override fun checkValidRequest(
requestType: RequestType,
currentNetworkInfo: NetworkInfo
): RequestCheck {
return Allow
}
override fun getPreferredNetwork(
networks: Networks,
requestType: RequestType
): NetworkStatus? {
val wifi = networks.networks.firstOrNull { it.networkInfo is Wifi }
return wifi ?: networks.networks.firstOrNull()
}
}
/**
* Conservative rules that don't allow Streaming, and only allow Downloads
* over high bandwidth networks.
*/
@ExperimentalHorologistNetworksApi
public object Conservative : NetworkingRules {
override fun isHighBandwidthRequest(requestType: RequestType): Boolean {
return requestType is MediaRequest
}
override fun checkValidRequest(
requestType: RequestType,
currentNetworkInfo: NetworkInfo
): RequestCheck {
if (requestType is MediaRequest) {
return when (requestType.type) {
Download -> {
// Only allow Downloads over Wifi
// BT will hog the limited bandwidth
// Cell may include charges and should be checked with user
if (currentNetworkInfo is Wifi) {
Allow
} else {
Fail("downloads only possible over Wifi")
}
}
MediaRequest.MediaRequestType.Stream -> {
// Only allow Stream over Wifi or BT
// BT may hog the limited bandwidth, but hopefully is small stream.
if (currentNetworkInfo is Wifi || currentNetworkInfo is Bluetooth) {
Allow
} else {
Fail("streaming only possible over Wifi or BT")
}
}
MediaRequest.MediaRequestType.Live -> {
// Only allow Live (continuous) Stream over BT
if (currentNetworkInfo is Bluetooth) {
Allow
} else {
Fail("live streams only possible over BT")
}
}
}
}
return Allow
}
override fun getPreferredNetwork(
networks: Networks,
requestType: RequestType
): NetworkStatus? {
val wifi = networks.networks.firstOrNull { it.networkInfo is Wifi }
if (wifi != null) return wifi
val cell = networks.networks.firstOrNull { it.networkInfo is Cellular }
val ble = networks.networks.firstOrNull { it.networkInfo is Bluetooth }
return if (requestType is MediaRequest) {
if (requestType.type == Download) {
null
} else {
ble
}
} else {
ble ?: cell
}
}
}
}
| apache-2.0 | ddb1185e001df98ce256fc23f0705185 | 36.322785 | 101 | 0.605393 | 5.521536 | false | false | false | false |
yshrsmz/monotweety | includedBuild/build-helper/src/main/java/net/yslibrary/monotweety/buildhelper/secrets.kt | 1 | 868 | package net.yslibrary.monotweety.buildhelper
import org.gradle.api.Project
import java.util.Properties
private fun Project.loadProperties(path: String): Properties {
val propertiesFile = rootProject.rootDir.resolve(path)
if (!propertiesFile.exists()) {
throw IllegalStateException("'$path' does not exist")
}
val props = Properties()
props.load(propertiesFile.inputStream())
return props
}
internal fun Project.loadSecrets(): Properties = loadProperties("secret.properties")
fun splitAlternately(source: String): Pair<String, String> {
var result1 = ""
var result2 = ""
var i = 0
val len = source.length
while (i < len) {
if (i % 2 == 0) {
// even
result1 += source[i]
} else {
result2 += source[i]
}
i++
}
return result1 to result2
}
| apache-2.0 | 653b556acfa26344dc3e0d8775a3f075 | 24.529412 | 84 | 0.62788 | 4.173077 | false | false | false | false |
SUPERCILEX/Robot-Scouter | library/core/src/main/java/com/supercilex/robotscouter/core/Logging.kt | 1 | 2789 | package com.supercilex.robotscouter.core
import android.util.Log
import androidx.annotation.Keep
import com.crashlytics.android.Crashlytics
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.OnFailureListener
import com.google.android.gms.tasks.Task
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletionHandler
import kotlinx.coroutines.CoroutineExceptionHandler
import java.util.concurrent.ExecutionException
import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.CoroutineContext
fun logBreadcrumb(message: String, error: Throwable? = null) {
Crashlytics.log(message)
if (BuildConfig.DEBUG) Log.d("Breadcrumbs", message)
CrashLogger.invoke(error)
}
/**
* Used to bridge a non-coroutine exception into the coroutine world by marking its call site stack
* trace. Otherwise, we'd only get the stack trace of the remote exception and have no idea where it
* came from in our code.
*/
class InvocationMarker(actual: Throwable) : ExecutionException(actual)
object CrashLogger : OnFailureListener, OnCompleteListener<Any>, CompletionHandler {
override fun onFailure(e: Exception) {
invoke(e)
}
override fun onComplete(task: Task<Any>) {
invoke(task.exception)
}
override fun invoke(t: Throwable?) {
if (t == null || t is CancellationException) return
if (BuildConfig.DEBUG || isInTestMode) {
Log.e("CrashLogger", "An error occurred", t)
} else {
Crashlytics.logException(t)
}
}
}
@Keep
internal class LoggingHandler : AbstractCoroutineContextElement(CoroutineExceptionHandler),
CoroutineExceptionHandler {
override fun handleException(context: CoroutineContext, exception: Throwable) {
CrashLogger.invoke(exception)
// Since we don't want to crash and Coroutines will call the current thread's handler, we
// install a noop handler and then reinstall the existing one once coroutines calls the new
// handler.
Thread.currentThread().apply {
// _Do_ crash the main thread to ensure we're not left in a bad state
if (isMain) return@apply
val removed = uncaughtExceptionHandler
uncaughtExceptionHandler = Thread.UncaughtExceptionHandler { t, _ ->
// The AndroidExceptionPreHandler breaks out assumption that this will be the last
// method call. This check ensures that we've made it to the end of the exception
// handler loop.
if (t.stackTrace.orEmpty()[3].methodName == "handleCoroutineExceptionImpl") {
t.uncaughtExceptionHandler = removed
}
}
}
}
}
| gpl-3.0 | 5bf1970ff3a693366af3a35ff76f1fb9 | 37.736111 | 100 | 0.703837 | 4.945035 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.