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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/receivers/TimeDateOrTZChangeReceiver.kt | 1 | 3104 | package info.nightscout.androidaps.receivers
import android.content.Context
import android.content.Intent
import com.google.gson.Gson
import dagger.android.DaggerBroadcastReceiver
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.Pump
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.BundleLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.utils.TimeChangeType
import java.util.*
import javax.inject.Inject
class TimeDateOrTZChangeReceiver : DaggerBroadcastReceiver() {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var activePlugin: ActivePlugin
val gson: Gson = Gson()
private var isDST = false
init {
isDST = calculateDST()
}
private fun calculateDST(): Boolean {
val timeZone = TimeZone.getDefault()
val nowDate = Date()
return if (timeZone.useDaylightTime()) {
timeZone.inDaylightTime(nowDate)
} else {
false
}
}
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
val action = intent.action
val activePump: Pump = activePlugin.activePump
aapsLogger.debug(LTag.PUMP, "TimeDateOrTZChangeReceiver::Date, Time and/or TimeZone changed. [action={}]", action)
aapsLogger.debug(LTag.PUMP, "TimeDateOrTZChangeReceiver::Intent::{}", BundleLogger.log(intent.extras))
when {
action == null -> {
aapsLogger.error(LTag.PUMP, "TimeDateOrTZChangeReceiver::Action is null. Exiting.")
}
Intent.ACTION_TIMEZONE_CHANGED == action -> {
aapsLogger.info(LTag.PUMP, "TimeDateOrTZChangeReceiver::Timezone changed. Notifying pump driver.")
activePump.timezoneOrDSTChanged(TimeChangeType.TimezoneChanged)
}
Intent.ACTION_TIME_CHANGED == action -> {
val currentDst = calculateDST()
if (currentDst == isDST) {
aapsLogger.info(LTag.PUMP, "TimeDateOrTZChangeReceiver::Time changed (manual). Notifying pump driver.")
activePump.timezoneOrDSTChanged(TimeChangeType.TimeChanged)
} else {
if (currentDst) {
aapsLogger.info(LTag.PUMP, "TimeDateOrTZChangeReceiver::DST started. Notifying pump driver.")
activePump.timezoneOrDSTChanged(TimeChangeType.DSTStarted)
} else {
aapsLogger.info(LTag.PUMP, "TimeDateOrTZChangeReceiver::DST ended. Notifying pump driver.")
activePump.timezoneOrDSTChanged(TimeChangeType.DSTEnded)
}
}
isDST = currentDst
}
else -> {
aapsLogger.error(LTag.PUMP, "TimeDateOrTZChangeReceiver::Unknown action received [name={}]. Exiting.", action)
}
}
}
}
| agpl-3.0 | 86eae4bf67c9ed1363d52496282a9d03 | 39.311688 | 126 | 0.627577 | 4.950558 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/core/host/ArcStateChangeRegistrationTest.kt | 1 | 1507 | package arcs.core.host
import arcs.core.common.ArcId
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
@OptIn(ExperimentalCoroutinesApi::class)
class ArcStateChangeRegistrationTest {
@Test
fun arcStateChangeRegistration_roundTrip() {
val arcId = ArcId.newForTest("foo")
val registration = ArcStateChangeRegistration(arcId) { }
assertThat(registration.arcId()).isEqualTo(arcId.toString())
}
@Test
fun arcStateChangeRegistration_withDifferentCallbacks_givesDifferentRegistrations() {
val arcId = ArcId.newForTest("foo")
val registration1 = ArcStateChangeRegistration(arcId) { }
val registration2 = ArcStateChangeRegistration(arcId) { }
assertThat(registration1).isNotEqualTo(registration2)
assertThat(registration1.arcId()).isEqualTo(arcId.toString())
assertThat(registration2.arcId()).isEqualTo(arcId.toString())
}
@Test
fun arcStateChangeRegistration_withSameCallbacks_givesSameRegistrations() {
val arcId = ArcId.newForTest("foo")
val callback = { }
val registration1 = ArcStateChangeRegistration(arcId, callback)
val registration2 = ArcStateChangeRegistration(arcId, callback)
assertThat(registration1).isEqualTo(registration2)
assertThat(registration1.arcId()).isEqualTo(arcId.toString())
assertThat(registration2.arcId()).isEqualTo(arcId.toString())
}
}
| bsd-3-clause | 7e4cb83d6dd728dd8d2e005228b0f675 | 34.046512 | 87 | 0.776377 | 4.45858 | false | true | false | false |
Maccimo/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/cache/CallSaulAction.kt | 3 | 2884 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions.cache
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.psi.util.CachedValueProvider
import com.intellij.util.SystemProperties
internal class CallSaulAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) = service<Saul>().sortThingsOut(RecoveryScope.createInstance(e))
override fun update(e: AnActionEvent) {
val isEnabled = e.project != null
e.presentation.isEnabledAndVisible = isEnabled
if (isEnabled) {
val recoveryScope = RecoveryScope.createInstance(e)
if (recoveryScope is FilesRecoveryScope) {
e.presentation.text = ActionsBundle.message("action.CallSaul.on.file.text", recoveryScope.files.size)
}
}
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
}
internal class CacheRecoveryActionGroup: ComputableActionGroup() {
override fun createChildrenProvider(actionManager: ActionManager): CachedValueProvider<Array<AnAction>> {
return CachedValueProvider {
isPopup = ApplicationManager.getApplication().isInternal
val actions = if (isSaulHere) {
val baseActions = arrayListOf<AnAction>(actionManager.getAction("CallSaul"))
if (isPopup) {
baseActions.add(Separator.getInstance())
}
(baseActions + service<Saul>().sortedActions.map {
it.toAnAction()
}).toTypedArray()
}
else emptyArray()
CachedValueProvider.Result.create(actions, service<Saul>().modificationRecoveryActionTracker)
}
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
private fun RecoveryAction.toAnAction(): AnAction {
val recoveryAction = this
return object: DumbAwareAction(recoveryAction.presentableName) {
override fun actionPerformed(e: AnActionEvent) {
val scope = RecoveryScope.createInstance(e)
recoveryAction.performUnderProgress(scope,false)
}
override fun update(e: AnActionEvent) {
if (e.project == null) {
e.presentation.isEnabledAndVisible = false
return
}
val scope = RecoveryScope.createInstance(e)
e.presentation.isEnabledAndVisible = recoveryAction.canBeApplied(scope) && ApplicationManager.getApplication().isInternal
}
}
}
}
private val isSaulHere: Boolean
get() = ApplicationManager.getApplication().isInternal ||
SystemProperties.getBooleanProperty("idea.cache.recovery.enabled", true) | apache-2.0 | b22789f42cba65f5bc8dfd3eee8b8db3 | 36.467532 | 158 | 0.73301 | 4.855219 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/history/HistoryBlock.kt | 1 | 1220 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.history
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.options.OptionConstants
import com.maddyhome.idea.vim.options.OptionScope
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimInt
class HistoryBlock {
private val entries: MutableList<HistoryEntry> = ArrayList()
private var counter = 0
fun addEntry(text: String) {
for (i in entries.indices) {
val entry = entries[i]
if (text == entry.entry) {
entries.removeAt(i)
break
}
}
entries.add(HistoryEntry(++counter, text))
if (entries.size > maxLength()) {
entries.removeAt(0)
}
}
fun getEntries(): List<HistoryEntry> {
return entries
}
companion object {
private fun maxLength(): Int {
return (
injector.optionService
.getOptionValue(
OptionScope.GLOBAL, OptionConstants.historyName,
OptionConstants.historyName
) as VimInt
).value
}
}
}
| mit | 990988ec0f84a0caf59d63e59829cd80 | 23.4 | 62 | 0.665574 | 4.135593 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/jetpack/backup/download/BackupDownloadViewModel.kt | 1 | 21297 | package org.wordpress.android.ui.jetpack.backup.download
import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Parcelable
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import kotlinx.parcelize.Parcelize
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.collect
import org.json.JSONObject
import org.wordpress.android.R.string
import org.wordpress.android.analytics.AnalyticsTracker
import org.wordpress.android.analytics.AnalyticsTracker.Stat.JETPACK_BACKUP_DOWNLOAD_CONFIRMED
import org.wordpress.android.analytics.AnalyticsTracker.Stat.JETPACK_BACKUP_DOWNLOAD_ERROR
import org.wordpress.android.analytics.AnalyticsTracker.Stat.JETPACK_BACKUP_DOWNLOAD_FILE_DOWNLOAD_TAPPED
import org.wordpress.android.analytics.AnalyticsTracker.Stat.JETPACK_BACKUP_DOWNLOAD_SHARE_LINK_TAPPED
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.ActivityLogStore.BackupDownloadRequestTypes
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadNavigationEvents.DownloadFile
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadNavigationEvents.ShareLink
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadRequestState.Complete
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadRequestState.Empty
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadRequestState.Failure.NetworkUnavailable
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadRequestState.Failure.OtherRequestRunning
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadRequestState.Failure.RemoteRequestFailure
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadRequestState.Progress
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadRequestState.Success
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadStep.COMPLETE
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadStep.DETAILS
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadStep.ERROR
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadStep.PROGRESS
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadUiState.ContentState.CompleteState
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadUiState.ContentState.DetailsState
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadUiState.ContentState.ProgressState
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadUiState.ErrorState
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadViewModel.BackupDownloadWizardState.BackupDownloadCanceled
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadViewModel.BackupDownloadWizardState.BackupDownloadCompleted
import org.wordpress.android.ui.jetpack.backup.download.BackupDownloadViewModel.BackupDownloadWizardState.BackupDownloadInProgress
import org.wordpress.android.ui.jetpack.backup.download.builders.BackupDownloadStateListItemBuilder
import org.wordpress.android.ui.jetpack.backup.download.usecases.GetBackupDownloadStatusUseCase
import org.wordpress.android.ui.jetpack.backup.download.usecases.PostBackupDownloadUseCase
import org.wordpress.android.ui.jetpack.common.JetpackListItemState
import org.wordpress.android.ui.jetpack.common.JetpackListItemState.CheckboxState
import org.wordpress.android.ui.jetpack.common.ViewType
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider.JetpackAvailableItemType
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider.JetpackAvailableItemType.CONTENTS
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider.JetpackAvailableItemType.MEDIA_UPLOADS
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider.JetpackAvailableItemType.PLUGINS
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider.JetpackAvailableItemType.ROOTS
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider.JetpackAvailableItemType.SQLS
import org.wordpress.android.ui.jetpack.common.providers.JetpackAvailableItemsProvider.JetpackAvailableItemType.THEMES
import org.wordpress.android.ui.jetpack.usecases.GetActivityLogItemUseCase
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.ui.utils.UiString.UiStringText
import org.wordpress.android.util.text.PercentFormatter
import org.wordpress.android.util.wizard.WizardManager
import org.wordpress.android.util.wizard.WizardNavigationTarget
import org.wordpress.android.util.wizard.WizardState
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ScopedViewModel
import java.util.Date
import java.util.HashMap
import javax.inject.Inject
import javax.inject.Named
const val KEY_BACKUP_DOWNLOAD_ACTIVITY_ID_KEY = "key_backup_download_activity_id_key"
const val KEY_BACKUP_DOWNLOAD_CURRENT_STEP = "key_backup_download_current_step"
const val KEY_BACKUP_DOWNLOAD_STATE = "key_backup_download_state"
private const val TRACKING_ERROR_CAUSE_OFFLINE = "offline"
private const val TRACKING_ERROR_CAUSE_REMOTE = "remote"
private const val TRACKING_ERROR_CAUSE_OTHER = "other"
@Parcelize
@SuppressLint("ParcelCreator")
data class BackupDownloadState(
val siteId: Long? = null,
val activityId: String? = null,
val rewindId: String? = null,
val downloadId: Long? = null,
val published: Date? = null,
val url: String? = null,
val errorType: Int? = null
) : WizardState, Parcelable
typealias NavigationTarget = WizardNavigationTarget<BackupDownloadStep, BackupDownloadState>
class BackupDownloadViewModel @Inject constructor(
private val wizardManager: WizardManager<BackupDownloadStep>,
private val availableItemsProvider: JetpackAvailableItemsProvider,
private val getActivityLogItemUseCase: GetActivityLogItemUseCase,
private val stateListItemBuilder: BackupDownloadStateListItemBuilder,
private val postBackupDownloadUseCase: PostBackupDownloadUseCase,
private val getBackupDownloadStatusUseCase: GetBackupDownloadStatusUseCase,
@Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher,
private val percentFormatter: PercentFormatter
) : ScopedViewModel(mainDispatcher) {
private var isStarted = false
private lateinit var site: SiteModel
private lateinit var activityId: String
private lateinit var backupDownloadState: BackupDownloadState
private val progressStart = 0
private val _wizardFinishedObservable = MutableLiveData<Event<BackupDownloadWizardState>>()
val wizardFinishedObservable: LiveData<Event<BackupDownloadWizardState>> = _wizardFinishedObservable
private val _snackbarEvents = MediatorLiveData<Event<SnackbarMessageHolder>>()
val snackbarEvents: LiveData<Event<SnackbarMessageHolder>> = _snackbarEvents
private val _navigationEvents = MediatorLiveData<Event<BackupDownloadNavigationEvents>>()
val navigationEvents: LiveData<Event<BackupDownloadNavigationEvents>> = _navigationEvents
private val _uiState = MutableLiveData<BackupDownloadUiState>()
val uiState: LiveData<BackupDownloadUiState> = _uiState
private val wizardObserver = Observer { data: BackupDownloadStep? ->
data?.let {
clearOldBackupDownloadState(it)
showStep(NavigationTarget(it, backupDownloadState))
}
}
fun start(site: SiteModel, activityId: String, savedInstanceState: Bundle?) {
if (isStarted) return
isStarted = true
this.site = site
this.activityId = activityId
wizardManager.navigatorLiveData.observeForever(wizardObserver)
if (savedInstanceState == null) {
backupDownloadState = BackupDownloadState()
// Show the next step only if it's a fresh activity so we can handle the navigation
wizardManager.showNextStep()
} else {
backupDownloadState = requireNotNull(savedInstanceState.getParcelable(KEY_BACKUP_DOWNLOAD_STATE))
val currentStepIndex = savedInstanceState.getInt(KEY_BACKUP_DOWNLOAD_CURRENT_STEP)
wizardManager.setCurrentStepIndex(currentStepIndex)
}
}
fun onBackPressed() {
when (wizardManager.currentStep) {
DETAILS.id -> _wizardFinishedObservable.value = Event(BackupDownloadCanceled)
PROGRESS.id -> constructProgressEvent()
COMPLETE.id -> constructCompleteEvent()
ERROR.id -> _wizardFinishedObservable.value = Event(BackupDownloadCanceled)
}
}
private fun constructProgressEvent() {
_wizardFinishedObservable.value = if (backupDownloadState.downloadId != null) {
Event(
BackupDownloadInProgress(
backupDownloadState.rewindId as String,
backupDownloadState.downloadId as Long
)
)
} else {
Event(BackupDownloadCanceled)
}
}
private fun constructCompleteEvent() {
_wizardFinishedObservable.value = if (backupDownloadState.downloadId != null) {
Event(
BackupDownloadCompleted(
backupDownloadState.rewindId as String,
backupDownloadState.downloadId as Long
)
)
} else {
Event(BackupDownloadCanceled)
}
}
fun writeToBundle(outState: Bundle) {
outState.putInt(KEY_BACKUP_DOWNLOAD_CURRENT_STEP, wizardManager.currentStep)
outState.putParcelable(KEY_BACKUP_DOWNLOAD_STATE, backupDownloadState)
}
private fun buildDetails() {
launch {
val availableItems = availableItemsProvider.getAvailableItems()
val activityLogModel = getActivityLogItemUseCase.get(activityId)
if (activityLogModel != null) {
_uiState.value = DetailsState(
activityLogModel = activityLogModel,
items = stateListItemBuilder.buildDetailsListStateItems(
availableItems = availableItems,
published = activityLogModel.published,
onCreateDownloadClick = this@BackupDownloadViewModel::onCreateDownloadClick,
onCheckboxItemClicked = this@BackupDownloadViewModel::onCheckboxItemClicked
),
type = StateType.DETAILS
)
} else {
trackError(TRACKING_ERROR_CAUSE_OTHER)
transitionToError(BackupDownloadErrorTypes.GenericFailure)
}
}
}
private fun buildProgress() {
_uiState.value = ProgressState(
items = stateListItemBuilder.buildProgressListStateItems(
progress = progressStart,
published = backupDownloadState.published as Date
),
type = StateType.PROGRESS
)
queryStatus()
}
private fun buildComplete() {
_uiState.value = CompleteState(
items = stateListItemBuilder.buildCompleteListStateItems(
published = backupDownloadState.published as Date,
onDownloadFileClick = this@BackupDownloadViewModel::onDownloadFileClick,
onShareLinkClick = this@BackupDownloadViewModel::onShareLinkClick
), type = StateType.COMPLETE
)
}
private fun buildError(errorType: BackupDownloadErrorTypes) {
_uiState.value = ErrorState(
errorType = errorType,
items = stateListItemBuilder.buildErrorListStateErrorItems(
errorType = errorType,
onDoneClick = this@BackupDownloadViewModel::onDoneClick
)
)
}
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
fun showStep(target: WizardNavigationTarget<BackupDownloadStep, BackupDownloadState>) {
when (target.wizardStep) {
DETAILS -> buildDetails()
PROGRESS -> buildProgress()
COMPLETE -> buildComplete()
ERROR -> buildError(
BackupDownloadErrorTypes.fromInt(
target.wizardState.errorType ?: BackupDownloadErrorTypes.GenericFailure.id
)
)
}
}
private fun transitionToError(errorType: BackupDownloadErrorTypes) {
backupDownloadState = backupDownloadState.copy(errorType = errorType.id)
wizardManager.setCurrentStepIndex(BackupDownloadStep.indexForErrorTransition())
wizardManager.showNextStep()
}
private fun getParams(): Pair<String?, BackupDownloadRequestTypes> {
val rewindId = (_uiState.value as? DetailsState)?.activityLogModel?.rewindID
val items = _uiState.value?.items ?: mutableListOf()
val types = buildBackupDownloadRequestTypes(items)
return rewindId to types
}
private fun buildBackupDownloadRequestTypes(items: List<JetpackListItemState>): BackupDownloadRequestTypes {
val checkboxes = items.filterIsInstance(CheckboxState::class.java)
return BackupDownloadRequestTypes(
themes = checkboxes.firstOrNull { it.availableItemType == THEMES }?.checked ?: true,
plugins = checkboxes.firstOrNull { it.availableItemType == PLUGINS }?.checked
?: true,
uploads = checkboxes.firstOrNull { it.availableItemType == MEDIA_UPLOADS }?.checked
?: true,
sqls = checkboxes.firstOrNull { it.availableItemType == SQLS }?.checked ?: true,
roots = checkboxes.firstOrNull { it.availableItemType == ROOTS }?.checked ?: true,
contents = checkboxes.firstOrNull { it.availableItemType == CONTENTS }?.checked
?: true
)
}
private fun handleBackupDownloadRequestResult(result: BackupDownloadRequestState) {
when (result) {
is NetworkUnavailable -> {
trackError(TRACKING_ERROR_CAUSE_OFFLINE)
_snackbarEvents.postValue(Event(NetworkUnavailableMsg))
}
is RemoteRequestFailure -> {
trackError(TRACKING_ERROR_CAUSE_REMOTE)
_snackbarEvents.postValue(Event(GenericFailureMsg))
}
is Success -> handleBackupDownloadRequestSuccess(result)
is OtherRequestRunning -> {
trackError(TRACKING_ERROR_CAUSE_OTHER)
_snackbarEvents.postValue(Event(OtherRequestRunningMsg))
}
else -> Unit // Do nothing
}
}
private fun handleBackupDownloadRequestSuccess(result: Success) {
backupDownloadState = backupDownloadState.copy(
rewindId = result.rewindId,
downloadId = result.downloadId,
published = extractPublishedDate()
)
wizardManager.showNextStep()
}
private fun extractPublishedDate(): Date {
return (_uiState.value as? DetailsState)?.activityLogModel?.published as Date
}
private fun queryStatus() {
launch {
getBackupDownloadStatusUseCase.getBackupDownloadStatus(site, backupDownloadState.downloadId as Long)
.collect { state -> handleQueryStatus(state) }
}
}
private fun handleQueryStatus(state: BackupDownloadRequestState) {
when (state) {
is NetworkUnavailable -> {
trackError(TRACKING_ERROR_CAUSE_OFFLINE)
transitionToError(BackupDownloadErrorTypes.RemoteRequestFailure)
}
is RemoteRequestFailure -> {
trackError(TRACKING_ERROR_CAUSE_REMOTE)
transitionToError(BackupDownloadErrorTypes.RemoteRequestFailure)
}
is Progress -> transitionToProgress(state)
is Complete -> transitionToComplete(state)
is Empty -> {
trackError(TRACKING_ERROR_CAUSE_REMOTE)
transitionToError(BackupDownloadErrorTypes.RemoteRequestFailure)
}
else -> Unit // Do nothing
}
}
private fun transitionToProgress(state: Progress) {
(_uiState.value as? ProgressState)?.let { content ->
val updatedList = content.items.map { contentState ->
if (contentState.type == ViewType.PROGRESS) {
contentState as JetpackListItemState.ProgressState
contentState.copy(
progress = state.progress ?: 0,
progressLabel = UiStringText(percentFormatter.format(state.progress ?: 0))
)
} else {
contentState
}
}
_uiState.postValue(content.copy(items = updatedList))
}
}
private fun transitionToComplete(state: Complete) {
backupDownloadState = backupDownloadState.copy(url = state.url)
wizardManager.showNextStep()
}
private fun clearOldBackupDownloadState(wizardStep: BackupDownloadStep) {
if (wizardStep == DETAILS) {
backupDownloadState = backupDownloadState.copy(
rewindId = null,
downloadId = null,
url = null,
errorType = null
)
}
}
private fun onCheckboxItemClicked(itemType: JetpackAvailableItemType) {
(_uiState.value as? DetailsState)?.let {
val updatedItems = stateListItemBuilder.updateCheckboxes(it, itemType)
_uiState.postValue(it.copy(items = updatedItems))
}
}
private fun onCreateDownloadClick() {
val (rewindId, types) = getParams()
if (rewindId == null) {
transitionToError(BackupDownloadErrorTypes.GenericFailure)
} else {
trackBackupDownloadConfirmed(types)
launch {
val result = postBackupDownloadUseCase.postBackupDownloadRequest(
rewindId,
site,
types
)
handleBackupDownloadRequestResult(result)
}
}
}
private fun onDownloadFileClick() {
AnalyticsTracker.track(JETPACK_BACKUP_DOWNLOAD_FILE_DOWNLOAD_TAPPED)
backupDownloadState.url?.let { _navigationEvents.postValue(Event(DownloadFile(it))) }
}
private fun onShareLinkClick() {
AnalyticsTracker.track(JETPACK_BACKUP_DOWNLOAD_SHARE_LINK_TAPPED)
backupDownloadState.url?.let { _navigationEvents.postValue(Event(ShareLink(it))) }
}
private fun onDoneClick() {
_wizardFinishedObservable.value = Event(BackupDownloadCanceled)
}
override fun onCleared() {
super.onCleared()
wizardManager.navigatorLiveData.removeObserver(wizardObserver)
}
private fun trackBackupDownloadConfirmed(types: BackupDownloadRequestTypes) {
val propertiesSetup = mapOf(
"themes" to types.themes,
"plugins" to types.plugins,
"uploads" to types.uploads,
"sqls" to types.sqls,
"roots" to types.roots,
"contents" to types.contents
)
val map = mapOf("restore_types" to JSONObject(propertiesSetup))
AnalyticsTracker.track(JETPACK_BACKUP_DOWNLOAD_CONFIRMED, map)
}
private fun trackError(cause: String) {
val properties: MutableMap<String, String?> = HashMap()
properties["cause"] = cause
AnalyticsTracker.track(JETPACK_BACKUP_DOWNLOAD_ERROR, properties)
}
companion object {
private val NetworkUnavailableMsg = SnackbarMessageHolder(UiStringRes(string.error_network_connection))
private val GenericFailureMsg = SnackbarMessageHolder(UiStringRes(string.backup_download_generic_failure))
private val OtherRequestRunningMsg = SnackbarMessageHolder(
UiStringRes(string.backup_download_another_download_running)
)
}
@SuppressLint("ParcelCreator")
sealed class BackupDownloadWizardState : Parcelable {
@Parcelize
object BackupDownloadCanceled : BackupDownloadWizardState()
@Parcelize
data class BackupDownloadInProgress(
val rewindId: String,
val downloadId: Long
) : BackupDownloadWizardState()
@Parcelize
data class BackupDownloadCompleted(
val rewindId: String,
val downloadId: Long
) : BackupDownloadWizardState()
}
}
| gpl-2.0 | 9dfb0e8b7612df542a5675b1a722c639 | 44.8 | 130 | 0.696342 | 5.54465 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/notifications/NotificationsListViewModel.kt | 1 | 1784 | package org.wordpress.android.ui.notifications
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalOverlayUtil
import org.wordpress.android.ui.jetpackoverlay.JetpackOverlayConnectedFeature.NOTIFICATIONS
import org.wordpress.android.util.JetpackBrandingUtils
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ScopedViewModel
import javax.inject.Inject
import javax.inject.Named
@HiltViewModel
class NotificationsListViewModel@Inject constructor(
@Named(UI_THREAD) mainDispatcher: CoroutineDispatcher,
private val jetpackBrandingUtils: JetpackBrandingUtils,
private val jetpackFeatureRemovalOverlayUtil: JetpackFeatureRemovalOverlayUtil
) : ScopedViewModel(mainDispatcher) {
private val _showJetpackPoweredBottomSheet = MutableLiveData<Event<Boolean>>()
val showJetpackPoweredBottomSheet: LiveData<Event<Boolean>> = _showJetpackPoweredBottomSheet
private val _showJetpackOverlay = MutableLiveData<Event<Boolean>>()
val showJetpackOverlay: LiveData<Event<Boolean>> = _showJetpackOverlay
init {
if (jetpackBrandingUtils.shouldShowJetpackPoweredBottomSheet()) showJetpackPoweredBottomSheet()
}
private fun showJetpackPoweredBottomSheet() {
// _showJetpackPoweredBottomSheet.value = Event(true)
}
fun onResume() {
if(jetpackFeatureRemovalOverlayUtil.shouldShowFeatureSpecificJetpackOverlay(NOTIFICATIONS))
showJetpackOverlay()
}
private fun showJetpackOverlay() {
_showJetpackOverlay.value = Event(true)
}
}
| gpl-2.0 | e3af33b2bd578cc1d55af1b1cfae6254 | 38.644444 | 103 | 0.809417 | 5.011236 | false | false | false | false |
NativeScript/android-runtime | test-app/build-tools/android-metadata-generator/src/src/com/telerik/metadata/parsing/kotlin/extensions/bytecode/BytecodeExtensionFunctionsCollector.kt | 1 | 2518 | package com.telerik.metadata.parsing.kotlin.extensions.bytecode
import com.telerik.metadata.ClassUtil
import com.telerik.metadata.parsing.kotlin.classes.KotlinClassDescriptor
import com.telerik.metadata.parsing.kotlin.extensions.ClassNameAndFunctionPair
import com.telerik.metadata.parsing.kotlin.extensions.KotlinExtensionFunctionDescriptor
import com.telerik.metadata.parsing.kotlin.extensions.ExtensionFunctionsCollector
import com.telerik.metadata.parsing.kotlin.metadata.ClassMetadataParser
import com.telerik.metadata.parsing.kotlin.methods.KotlinMethodDescriptor
import kotlinx.metadata.jvm.signature
import java.util.*
class BytecodeExtensionFunctionsCollector(private val kotlinClassMetadataParser: ClassMetadataParser) : ExtensionFunctionsCollector {
override fun collectExtensionFunctions(kotlinClassDescriptor: KotlinClassDescriptor): Collection<ClassNameAndFunctionPair<KotlinExtensionFunctionDescriptor>> {
val kotlinMetadata = kotlinClassDescriptor.kotlinMetadata ?: return emptyList()
val extensionFunctionsDescriptors = ArrayList<ClassNameAndFunctionPair<KotlinExtensionFunctionDescriptor>>()
val extensionFunctions = kotlinClassMetadataParser.getKotlinExtensionFunctions(kotlinMetadata)
for (extensionFunction in extensionFunctions) {
val signature = extensionFunction.signature
if (signature != null) {
val functionName = signature.name
val functionSignature = signature.desc
val extensionFunctionDescriptor: KotlinMethodDescriptor = Arrays
.stream(kotlinClassDescriptor.methods)
.filter { x -> x.name == functionName && x.signature == functionSignature }
.findFirst()
.get()
if (extensionFunctionDescriptor.isStatic) {
val receiverType = extensionFunctionDescriptor.argumentTypes[0] // kotlin extension functions' first argument is the receiver type
val receiverClassName = ClassUtil.getCanonicalName(receiverType.signature)
val classNameAndFunctionPair: ClassNameAndFunctionPair<KotlinExtensionFunctionDescriptor> = ClassNameAndFunctionPair(receiverClassName, KotlinExtensionFunctionBytecodeDescriptor(extensionFunctionDescriptor))
extensionFunctionsDescriptors.add(classNameAndFunctionPair)
}
}
}
return extensionFunctionsDescriptors
}
}
| apache-2.0 | 03a359fe0506c094bdaa3d8da2ccaa85 | 53.73913 | 227 | 0.746624 | 6.009547 | false | false | false | false |
mantono/GymData | src/main/kotlin/com/mantono/gym/WeightComputer.kt | 1 | 1315 | package com.mantono.gym
import java.time.Duration
import java.util.*
import kotlin.math.absoluteValue
fun nextWeight(history: History, load: Load): Weight
{
val rand = Random(history.size.toLong())
val baseWeight: Double = history.sequenceLastYear()
.filter { it.repetitions in load }
.sortedByDescending { it.weight }
.take(50)
.map { it.weight.kilograms }
.average()
val options: List<Double> = listOf(-2.5, 0.0, 2.5, 5.0)
val randAdd: Double = options[rand.nextInt().absoluteValue % options.size]
return Kilogram(baseWeight + randAdd)
}
fun maxWeight(history: History): Weight = history.sequenceLastYear()
.sortedByDescending { it.weight }
.first()
.weight
fun range(history: History, load: Load): Weight
{
val insideLoad: List<SetResult> = history.sequenceLastYear()
.filter { it.repetitions in load }
.sortedBy { it.weight }
.toList()
val max: Weight = insideLoad.last().weight
val min: Weight = insideLoad.first().weight
return max - min
}
private operator fun Duration.div(divider: Duration): Double = this.toMillis().toDouble() / divider.toMillis().toDouble()
private tailrec operator fun Duration.rem(timeSinceLastAttempt: Duration): Duration
{
if (timeSinceLastAttempt < this)
return timeSinceLastAttempt
return rem(timeSinceLastAttempt.minus(this))
} | gpl-3.0 | 5a03dda338b8c4a9fb1542842fc83377 | 25.857143 | 121 | 0.730798 | 3.415584 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/time/Timestamp.kt | 1 | 21430 | /*
* Timestamp.kt
*
* Copyright 2019 Google
*
* This file is open to relicensing, if you need it under another
* license, contact phcoder
*
* 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 au.id.micolous.metrodroid.time
import au.id.micolous.metrodroid.multi.FormattedString
import au.id.micolous.metrodroid.multi.Parcelable
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.util.NumberUtils
import au.id.micolous.metrodroid.util.Preferences
import au.id.micolous.metrodroid.util.TripObfuscator
import kotlinx.serialization.*
import kotlin.native.concurrent.SharedImmutable
@Parcelize
@Serializable(with = MetroTimeZone.Companion::class)
data class MetroTimeZone(val olson: String): Parcelable {
override fun toString(): String = olson
@Serializer(forClass = MetroTimeZone::class)
companion object : KSerializer<MetroTimeZone> {
override fun serialize(encoder: Encoder, obj: MetroTimeZone) {
encoder.encodeString(obj.olson)
}
override fun deserialize(decoder: Decoder) = MetroTimeZone(decoder.decodeString())
// Time zone not specified
val UNKNOWN = MetroTimeZone(olson = "UNKNOWN")
// Local device time zone
val LOCAL = MetroTimeZone(olson = "LOCAL")
// UTC
val UTC = MetroTimeZone(olson = "Etc/UTC")
val ADELAIDE = MetroTimeZone(olson = "Australia/Adelaide")
val AMSTERDAM = MetroTimeZone(olson = "Europe/Amsterdam")
val AUCKLAND = MetroTimeZone(olson = "Pacific/Auckland")
val BEIJING = MetroTimeZone(olson = "Asia/Shanghai")
val BRISBANE = MetroTimeZone(olson = "Australia/Brisbane")
val BRUXELLES = MetroTimeZone(olson = "Europe/Brussels")
val CHICAGO = MetroTimeZone(olson = "America/Chicago")
val COPENHAGEN = MetroTimeZone(olson = "Europe/Copenhagen")
val DUBAI = MetroTimeZone(olson = "Asia/Dubai")
val DUBLIN = MetroTimeZone(olson = "Europe/Dublin")
val HELSINKI = MetroTimeZone(olson = "Europe/Helsinki")
val HOUSTON = MetroTimeZone(olson = "America/Chicago")
val JAKARTA = MetroTimeZone(olson = "Asia/Jakarta")
val JERUSALEM = MetroTimeZone(olson = "Asia/Jerusalem")
val JOHANNESBURG = MetroTimeZone(olson ="Africa/Johannesburg")
val KAMCHATKA = MetroTimeZone(olson = "Asia/Kamchatka")
val KIEV = MetroTimeZone(olson = "Europe/Kiev")
val KIROV = MetroTimeZone(olson = "Europe/Kirov")
val KRASNOYARSK = MetroTimeZone(olson = "Asia/Krasnoyarsk")
val KUALA_LUMPUR = MetroTimeZone(olson = "Asia/Kuala_Lumpur")
val LISBON = MetroTimeZone(olson = "Europe/Lisbon")
val LONDON = MetroTimeZone(olson = "Europe/London")
val LOS_ANGELES = MetroTimeZone(olson = "America/Los_Angeles")
val MADRID = MetroTimeZone(olson = "Europe/Madrid")
val MONTREAL = MetroTimeZone(olson = "America/Montreal")
val MOSCOW = MetroTimeZone(olson = "Europe/Moscow")
val NEW_YORK = MetroTimeZone(olson = "America/New_York")
val OSLO = MetroTimeZone(olson = "Europe/Oslo")
val PARIS = MetroTimeZone(olson = "Europe/Paris")
val PERTH = MetroTimeZone(olson = "Australia/Perth")
val ROME = MetroTimeZone(olson = "Europe/Rome")
val SAKHALIN = MetroTimeZone(olson = "Asia/Sakhalin")
val SANTIAGO_CHILE = MetroTimeZone("America/Santiago")
val SAO_PAULO = MetroTimeZone(olson = "America/Sao_Paulo")
val SEOUL = MetroTimeZone(olson = "Asia/Seoul")
val SIMFEROPOL = MetroTimeZone(olson = "Europe/Simferopol")
val SINGAPORE = MetroTimeZone(olson = "Asia/Singapore")
val STOCKHOLM = MetroTimeZone(olson = "Europe/Stockholm")
val SYDNEY = MetroTimeZone(olson = "Australia/Sydney")
val TAIPEI = MetroTimeZone(olson = "Asia/Taipei")
val TBILISI = MetroTimeZone(olson = "Asia/Tbilisi")
val TOKYO = MetroTimeZone(olson = "Asia/Tokyo")
val VANCOUVER = MetroTimeZone(olson = "America/Vancouver")
val VLADIVOSTOK = MetroTimeZone(olson = "Asia/Vladivostok")
val YEKATERINBURG = MetroTimeZone(olson = "Asia/Yekaterinburg")
val SAMARA = MetroTimeZone(olson = "Europe/Samara")
val YAKUTSK = MetroTimeZone(olson = "Asia/Yakutsk")
val OMSK = MetroTimeZone(olson = "Asia/Omsk")
val NOVOSIBIRSK = MetroTimeZone(olson = "Asia/Novosibirsk")
val NOVOKUZNETSK = MetroTimeZone(olson = "Asia/Novokuznetsk")
val WARSAW = MetroTimeZone(olson = "Europe/Warsaw")
}
}
data class DHM(val days: Int, val hour: Int, val min: Int) {
val yd: YD
get() = getYD(days)
}
internal expect fun makeNow(): TimestampFull
internal expect fun epochDayHourMinToMillis(tz: MetroTimeZone, daysSinceEpoch: Int, hour: Int, min: Int): Long
internal expect fun getDaysFromMillis(millis: Long, tz: MetroTimeZone): DHM
internal const val SEC = 1000L
internal const val MIN = 60L * SEC
internal const val HOUR = 60L * MIN
internal const val DAY = 24L * HOUR
fun isBisextile(year: Int): Boolean = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)
data class YD(val year: Int, val dayOfYear: Int) {
val daysSinceEpoch: Int = yearToDays(year) + dayOfYear
}
fun getYD(daysSinceEpoch: Int): YD {
val daysSinceX = daysSinceEpoch + 719162
// 400 years has 97 bisextile years
val groups400y = daysSinceX / (400 * 365 + 97)
val remainder400y = daysSinceX % (400 * 365 + 97)
val groups100y = minOf(remainder400y / (100 * 365 + 24), 3)
val remainder100y = remainder400y - (100 * 365 + 24) * groups100y
val groups4y = remainder100y / (365 * 4 + 1)
val remainder4y = remainder100y % (365 * 4 + 1)
val group1y = minOf(remainder4y / 365, 3)
val remainder1y = remainder4y - group1y * 365
val y = 1 + groups400y * 400 + groups100y * 100 + groups4y * 4 + group1y
return YD(y, remainder1y)
}
fun getYMD(daysSinceEpoch: Int): YMD {
val (y, dy) = getYD(daysSinceEpoch)
val correctionD = if (!isBisextile(y) && dy >= 31 + 28) 1 else 0
val correctedDays = dy + correctionD
val (m, d) = when (correctedDays) {
in 0..30 -> Pair(Month.JANUARY, correctedDays + 1)
in 31..59 -> Pair(Month.FEBRUARY, correctedDays - 30)
in 60..90 -> Pair(Month.MARCH, correctedDays - 59)
in 91..120 -> Pair(Month.APRIL, correctedDays - 90)
in 121..151 -> Pair(Month.MAY, correctedDays - 120)
in 152..181 -> Pair(Month.JUNE, correctedDays - 151)
in 182..212 -> Pair(Month.JULY, correctedDays - 181)
in 213..243 -> Pair(Month.AUGUST, correctedDays - 212)
in 244..273 -> Pair(Month.SEPTEMBER, correctedDays - 243)
in 274..304 -> Pair(Month.OCTOBER, correctedDays - 273)
in 305..334 -> Pair(Month.NOVEMBER, correctedDays - 304)
else -> Pair(Month.DECEMBER, correctedDays - 334)
}
return YMD(year = y, month = m, day = d)
}
fun yearToDays(year: Int): Int {
val offYear = year - 1
var days = offYear * 365
days += offYear / 4
days -= offYear / 100
days += offYear / 400
return days - 719162
}
@SharedImmutable
private val monthToDays = listOf(0, 31, 59, 90, 120, 151, 181,
212, 243, 273, 304, 334)
/**
* Enum of 0-indexed months in the Gregorian calendar
*/
enum class Month(val zeroBasedIndex: Int) {
JANUARY(0),
FEBRUARY(1),
MARCH(2),
APRIL(3),
MAY(4),
JUNE(5),
JULY(6),
AUGUST(7),
SEPTEMBER(8),
OCTOBER(9),
NOVEMBER(10),
DECEMBER(11);
val oneBasedIndex: Int get() = zeroBasedIndex + 1
companion object {
fun zeroBased(idx: Int): Month = values()[idx]
}
}
/**
* Represents a year, month and day in the Gregorian calendar.
*
* @property month Month, where January = Month.JANUARY.
* @property day Day of the month, where the first day of the month = 1.
*/
data class YMD(val year: Int, val month: Month, val day: Int) {
constructor(other: YMD): this(other.year, other.month, other.day)
constructor(year: Int, month: Int, day: Int) : this(normalize(year, month, day))
val daysSinceEpoch: Int get() = countDays(year, month.zeroBasedIndex, day)
companion object {
private fun countDays(year: Int, month: Int, day: Int): Int {
val ym = 12 * year + month
var y: Int = ym / 12
var m: Int = ym % 12
// We don't really care for dates before 1 CE
// but at least we shouldn't crash on them
// This code results in astronomical year numbering
// that includes year 0
if (m < 0) {
m += 12
y -= 1
}
return yearToDays(y) + (day - 1) + monthToDays[m] + (
if (isBisextile(y) && m > Month.FEBRUARY.zeroBasedIndex) 1 else 0)
}
private fun normalize(year: Int, month: Int, day: Int): YMD =
getYMD(countDays(year, month, day))
}
}
internal fun yearToMillis(year: Int) = yearToDays(year) * DAY
fun addYearToDays(from: Int, years: Int): Int {
val ymd = getYMD(from)
return YMD(ymd.year + years, ymd.month, ymd.day).daysSinceEpoch
}
fun addMonthToDays(from: Int, months: Int): Int {
val ymd = getYMD(from)
return YMD(ymd.year, ymd.month.zeroBasedIndex + months, ymd.day).daysSinceEpoch
}
internal fun addYearToMillis(from: Long, tz: MetroTimeZone, years: Int): Long {
val ms = from % MIN
val (days, h, m) = getDaysFromMillis(from, tz)
return epochDayHourMinToMillis(tz = tz,
daysSinceEpoch = addYearToDays(from = days, years = years),
hour = h, min = m) + ms
}
internal fun addMonthToMillis(from: Long, tz: MetroTimeZone, months: Int): Long {
val ms = from % MIN
val (days, h, m) = getDaysFromMillis(from, tz)
return epochDayHourMinToMillis(tz = tz,
daysSinceEpoch = addMonthToDays(from = days, months = months),
hour = h, min = m) + ms
}
internal fun addDay(from: Long, tz: MetroTimeZone, days: Int): Long {
val ms = from % MIN
val (d, h, m) = getDaysFromMillis(from, tz)
return epochDayHourMinToMillis(tz = tz,
daysSinceEpoch = d + days,
hour = h, min = m) + ms
}
interface Duration {
fun addFull (ts: TimestampFull): TimestampFull
companion object {
fun daysLocal(d: Int) = DurationDaysLocal(d)
fun mins(m: Int) = DurationSec(m * 60)
fun yearsLocal(y: Int) = DurationYearsLocal(y)
fun monthsLocal(m: Int) = DurationMonthsLocal(m)
}
}
interface DayDuration : Duration {
fun addDays(ts: Daystamp): Daystamp
fun addAny (ts: Timestamp): Timestamp = when (ts) {
is Daystamp -> addDays(ts)
is TimestampFull -> addFull(ts)
}
}
class DurationDaysLocal(private val d: Int) : DayDuration {
override fun addFull(ts: TimestampFull) = TimestampFull(
timeInMillis = addDay(ts.timeInMillis, ts.tz, d),
tz = ts.tz)
override fun addDays(ts: Daystamp) = Daystamp(daysSinceEpoch = ts.daysSinceEpoch + d)
}
class DurationMonthsLocal(private val m: Int) : DayDuration {
override fun addFull(ts: TimestampFull) = TimestampFull(
timeInMillis = addMonthToMillis(ts.timeInMillis, ts.tz, m),
tz = ts.tz)
override fun addDays(ts: Daystamp) = Daystamp (daysSinceEpoch = addMonthToDays(ts.daysSinceEpoch, m))
}
class DurationYearsLocal(private val y: Int) : DayDuration {
override fun addFull(ts: TimestampFull) = TimestampFull(
timeInMillis = addYearToMillis(ts.timeInMillis, ts.tz, y),
tz = ts.tz)
override fun addDays(ts: Daystamp) = Daystamp (daysSinceEpoch = addYearToDays(ts.daysSinceEpoch, y))
}
class DurationSec(private val s: Int) : Duration {
override fun addFull(ts: TimestampFull) = TimestampFull(
timeInMillis = ts.timeInMillis + s * SEC,
tz = ts.tz)
}
interface Epoch : Parcelable {
companion object {
fun utc(year: Int, tz: MetroTimeZone, minOffset: Int = 0) = EpochUTC(
baseDays = yearToDays(year),
baseMillis = yearToMillis(year) + minOffset * MIN, outputTz = tz)
fun local(year: Int, tz: MetroTimeZone) = EpochLocal(yearToDays(year), tz)
}
}
// This is used when timestamps observe regular progression without any DST
@Parcelize
class EpochUTC internal constructor(private val baseMillis: Long,
private val baseDays: Int,
private val outputTz: MetroTimeZone) : Epoch {
fun mins(offset: Int) =
TimestampFull(timeInMillis = baseMillis + offset * MIN, tz = outputTz)
fun days(offset: Int) =
Daystamp(daysSinceEpoch = baseDays + offset)
fun seconds(offset: Long) =
TimestampFull(timeInMillis = baseMillis + offset * SEC, tz = outputTz)
fun dayMinute(d: Int, m: Int) = TimestampFull(
timeInMillis = baseMillis + d * DAY + m * MIN, tz = outputTz)
fun daySecond(d: Int, s: Int) = TimestampFull(
timeInMillis = baseMillis + d * DAY + s * SEC, tz = outputTz)
fun dayHourMinuteSecond(d: Int, h: Int, m: Int, s: Int) = TimestampFull(
timeInMillis = baseMillis + d * DAY + h * HOUR + m * MIN + s * SEC, tz = outputTz)
}
//The nasty timestamps: day is equal to calendar day
@Parcelize
class EpochLocal internal constructor(private val baseDays: Int,
private val tz: MetroTimeZone) : Epoch {
fun days(d: Int) =
Daystamp(daysSinceEpoch = baseDays + d)
fun dayMinute(d: Int, m: Int) = TimestampFull(
timeInMillis = epochDayHourMinToMillis(tz, baseDays + d,
m / 60, m % 60), tz = tz)
fun daySecond(d: Int, s: Int) = TimestampFull(
timeInMillis = epochDayHourMinToMillis(tz, baseDays + d,
s / 3600, (s / 60) % 60) + (s%60) * SEC, tz = tz)
}
sealed class Timestamp: Parcelable {
@Transient
val ymd: YMD
get () = getYMD(toDaystamp().daysSinceEpoch)
@Transient
val yd: YD
get() = getYD(toDaystamp().daysSinceEpoch)
abstract fun format(): FormattedString
open operator fun plus(duration: DayDuration): Timestamp = duration.addAny(this)
abstract fun toDaystamp(): Daystamp
abstract fun obfuscateDelta(delta: Long): Timestamp
fun isSameDay(other: Timestamp): Boolean = this.toDaystamp() == other.toDaystamp()
abstract fun getMonth(): Month
abstract fun getYear(): Int
}
@Parcelize
@Serializable
// Only date is known
data class Daystamp internal constructor(val daysSinceEpoch: Int): Timestamp(), Comparable<Daystamp> {
override fun getMonth(): Month = getYMD(daysSinceEpoch).month
override fun getYear(): Int = getYMD(daysSinceEpoch).year
override fun toDaystamp(): Daystamp = this
override fun compareTo(other: Daystamp): Int = daysSinceEpoch.compareTo(other.daysSinceEpoch)
override fun obfuscateDelta(delta: Long) = Daystamp(daysSinceEpoch = daysSinceEpoch + ((delta + DAY/2) / DAY).toInt())
override fun format(): FormattedString =
TimestampFormatter.longDateFormat(this)
fun adjust() : Daystamp = this
fun promote(tz: MetroTimeZone, hour: Int, min: Int): TimestampFull = TimestampFull(
tz = tz, timeInMillis = epochDayHourMinToMillis(tz, daysSinceEpoch, hour, min))
/**
* Formats a GregorianCalendar in to ISO8601 date format in local time (ie: without any timezone
* conversion). This is designed for [Daystamp] values which only have a valid date
* component.
*
* This should only be used for debugging logs, in order to ensure consistent
* information.
*
* @receiver Date to format
* @return String representing the date in ISO8601 format.
*/
private fun isoDateFormat(): String {
// ISO_DATE_FORMAT = SimpleDateFormat ("yyyy-MM-dd", Locale.US)
val ymd = getYMD(daysSinceEpoch = daysSinceEpoch)
return NumberUtils.zeroPad(ymd.year, 4) + "-" +
NumberUtils.zeroPad(ymd.month.oneBasedIndex, 2) + "-" +
NumberUtils.zeroPad(ymd.day, 2)
}
override fun toString(): String = isoDateFormat()
/**
* Represents a year, month and day in the Gregorian calendar.
*
* @param month Month, where January = 0.
* @param day Day of the month, where the first day of the month = 1.
*/
constructor(year: Int, month: Int, day: Int) : this(YMD(year, month, day))
constructor(year: Int, month: Month, day: Int) : this(YMD(year, month, day))
constructor(ymd: YMD) : this(
daysSinceEpoch = ymd.daysSinceEpoch
)
constructor(yd: YD) : this(
daysSinceEpoch = yd.daysSinceEpoch
)
}
@Parcelize
@Serializable
// Precision or minutes and higher
data class TimestampFull internal constructor(val timeInMillis: Long,
val tz: MetroTimeZone): Parcelable, Comparable<TimestampFull>, Timestamp() {
override fun getMonth(): Month = toDaystamp().getMonth()
override fun getYear(): Int = toDaystamp().getYear()
override fun toDaystamp() = Daystamp(dhm.days)
@Transient
val dhm get() = getDaysFromMillis(timeInMillis, tz)
override fun compareTo(other: TimestampFull): Int = timeInMillis.compareTo(other = other.timeInMillis)
fun adjust() : TimestampFull =
TripObfuscator.maybeObfuscateTS(if (Preferences.convertTimezone)
TimestampFull(timeInMillis, MetroTimeZone.LOCAL) else this)
operator fun plus(duration: Duration) = duration.addFull(this)
override operator fun plus(duration: DayDuration) = duration.addFull(this)
override fun format(): FormattedString = TimestampFormatter.dateTimeFormat(this)
constructor(tz : MetroTimeZone, year: Int, month: Int, day: Int, hour: Int,
min: Int, sec: Int = 0) : this(
timeInMillis = epochDayHourMinToMillis(
tz, YMD(year, month, day).daysSinceEpoch, hour, min) + sec * SEC,
tz = tz
)
constructor(tz : MetroTimeZone, year: Int, month: Month, day: Int, hour: Int,
min: Int, sec: Int = 0) : this(
year = year, month = month.zeroBasedIndex, day = day,
hour = hour, min = min, sec = sec,
tz = tz
)
constructor(tz: MetroTimeZone, dhm: DHM) : this(
timeInMillis = epochDayHourMinToMillis(
tz, dhm.days, dhm.hour, dhm.min),
tz = tz
)
/**
* Formats a GregorianCalendar in to ISO8601 date and time format in UTC. This should only be
* used for debugging logs, in order to ensure consistent information.
*
* @receiver Date/time to format
* @return String representing the date and time in ISO8601 format.
*/
fun isoDateTimeFormat(): String {
// SimpleDateFormat ("yyyy-MM-dd HH:mm", Locale.US)
val daysSinceEpoch = timeInMillis / DAY
val timeInDay = (timeInMillis % DAY) / MIN
val ymd = getYMD(daysSinceEpoch = daysSinceEpoch.toInt())
return NumberUtils.zeroPad(ymd.year, 4) + "-" +
NumberUtils.zeroPad(ymd.month.oneBasedIndex, 2) + "-" +
NumberUtils.zeroPad(ymd.day, 2) + " " +
NumberUtils.zeroPad(timeInDay / 60, 2) + ":" +
NumberUtils.zeroPad(timeInDay % 60, 2)
}
/**
* Formats a GregorianCalendar in to ISO8601 date and time format in UTC, but with only
* characters that can be used in filenames on most filesystems.
*
* @receiver Date/time to format
* @return String representing the date and time in ISO8601 format.
*/
fun isoDateTimeFilenameFormat(): String {
// SimpleDateFormat ("yyyyMMdd-HHmmss", Locale.US)
val daysSinceEpoch = timeInMillis / DAY
val sec = (timeInMillis % MIN) / SEC
val timeInDay = (timeInMillis % DAY) / MIN
val ymd = getYMD(daysSinceEpoch = daysSinceEpoch.toInt())
return NumberUtils.zeroPad(ymd.year, 4) +
NumberUtils.zeroPad(ymd.month.oneBasedIndex, 2) +
NumberUtils.zeroPad(ymd.day, 2) + "-" +
NumberUtils.zeroPad(timeInDay / 60, 2) +
NumberUtils.zeroPad(timeInDay % 60, 2) +
NumberUtils.zeroPad(sec, 2)
}
override fun toString(): String = isoDateTimeFormat() + "/$tz"
override fun obfuscateDelta(delta: Long) = TimestampFull(timeInMillis = timeInMillis + delta, tz = tz)
companion object {
fun now() = makeNow()
}
}
expect object TimestampFormatter {
fun longDateFormat(ts: Timestamp): FormattedString
fun dateTimeFormat(ts: TimestampFull): FormattedString
fun timeFormat(ts: TimestampFull): FormattedString
}
| gpl-3.0 | 381b0087da588a3b078500aa2fa6ada5 | 38.90689 | 122 | 0.645544 | 3.768243 | false | false | false | false |
eneim/android-UniversalMusicPlayer | app/src/main/java/com/example/android/uamp/MediaSessionConnection.kt | 1 | 6204 | /*
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp
import androidx.lifecycle.MutableLiveData
import android.content.ComponentName
import android.content.Context
import android.support.v4.media.MediaBrowserCompat
import androidx.media.MediaBrowserServiceCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import com.example.android.uamp.utils.InjectorUtils
/**
* Class that manages a connection to a [MediaBrowserServiceCompat] instance.
*
* Typically it's best to construct/inject dependencies either using DI or, as UAMP does,
* using [InjectorUtils]. There are a few difficulties for that here:
* - [MediaBrowserCompat] is a final class, so mocking it directly is difficult.
* - A [MediaBrowserConnectionCallback] is a parameter into the construction of
* a [MediaBrowserCompat], and provides callbacks to this class.
* - [MediaBrowserCompat.ConnectionCallback.onConnected] is the best place to construct
* a [MediaControllerCompat] that will be used to control the [MediaSessionCompat].
*
* Because of these reasons, rather than constructing additional classes, this is treated as
* a black box (which is why there's very little logic here).
*
* This is also why the parameters to construct a [MediaSessionConnection] are simple
* parameters, rather than private properties. They're only required to build the
* [MediaBrowserConnectionCallback] and [MediaBrowserCompat] objects.
*/
class MediaSessionConnection(context: Context, serviceComponent: ComponentName) {
val isConnected = MutableLiveData<Boolean>()
.apply { postValue(false) }
val rootMediaId: String get() = mediaBrowser.root
val playbackState = MutableLiveData<PlaybackStateCompat>()
.apply { postValue(EMPTY_PLAYBACK_STATE) }
val nowPlaying = MutableLiveData<MediaMetadataCompat>()
.apply { postValue(NOTHING_PLAYING) }
val transportControls: MediaControllerCompat.TransportControls
get() = mediaController.transportControls
private val mediaBrowserConnectionCallback = MediaBrowserConnectionCallback(context)
private val mediaBrowser = MediaBrowserCompat(context,
serviceComponent,
mediaBrowserConnectionCallback, null)
.apply { connect() }
private lateinit var mediaController: MediaControllerCompat
fun subscribe(parentId: String, callback: MediaBrowserCompat.SubscriptionCallback) {
mediaBrowser.subscribe(parentId, callback)
}
fun unsubscribe(parentId: String, callback: MediaBrowserCompat.SubscriptionCallback) {
mediaBrowser.unsubscribe(parentId, callback)
}
private inner class MediaBrowserConnectionCallback(private val context: Context)
: MediaBrowserCompat.ConnectionCallback() {
/**
* Invoked after [MediaBrowserCompat.connect] when the request has successfully
* completed.
*/
override fun onConnected() {
// Get a MediaController for the MediaSession.
mediaController = MediaControllerCompat(context, mediaBrowser.sessionToken).apply {
registerCallback(MediaControllerCallback())
}
isConnected.postValue(true)
}
/**
* Invoked when the client is disconnected from the media browser.
*/
override fun onConnectionSuspended() {
isConnected.postValue(false)
}
/**
* Invoked when the connection to the media browser failed.
*/
override fun onConnectionFailed() {
isConnected.postValue(false)
}
}
private inner class MediaControllerCallback : MediaControllerCompat.Callback() {
override fun onPlaybackStateChanged(state: PlaybackStateCompat?) {
playbackState.postValue(state ?: EMPTY_PLAYBACK_STATE)
}
override fun onMetadataChanged(metadata: MediaMetadataCompat?) {
nowPlaying.postValue(metadata ?: NOTHING_PLAYING)
}
override fun onQueueChanged(queue: MutableList<MediaSessionCompat.QueueItem>?) {
}
/**
* Normally if a [MediaBrowserServiceCompat] drops its connection the callback comes via
* [MediaControllerCompat.Callback] (here). But since other connection status events
* are sent to [MediaBrowserCompat.ConnectionCallback], we catch the disconnect here and
* send it on to the other callback.
*/
override fun onSessionDestroyed() {
mediaBrowserConnectionCallback.onConnectionSuspended()
}
}
companion object {
// For Singleton instantiation.
@Volatile
private var instance: MediaSessionConnection? = null
fun getInstance(context: Context, serviceComponent: ComponentName) =
instance ?: synchronized(this) {
instance ?: MediaSessionConnection(context, serviceComponent)
.also { instance = it }
}
}
}
@Suppress("PropertyName")
val EMPTY_PLAYBACK_STATE: PlaybackStateCompat = PlaybackStateCompat.Builder()
.setState(PlaybackStateCompat.STATE_NONE, 0, 0f)
.build()
@Suppress("PropertyName")
val NOTHING_PLAYING: MediaMetadataCompat = MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, "")
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, 0)
.build()
| apache-2.0 | fecbc34df14f3ec319a0bcf97e1ffa45 | 39.285714 | 96 | 0.708736 | 5.404181 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/facet/impl/FacetTypeRegistryImpl.kt | 3 | 7891 | // 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.facet.impl
import com.intellij.facet.*
import com.intellij.facet.impl.invalid.InvalidFacetManager
import com.intellij.facet.impl.invalid.InvalidFacetType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.RootsChangeRescanningInfo
import com.intellij.openapi.roots.ex.ProjectRootManagerEx
import com.intellij.workspaceModel.ide.impl.legacyBridge.facet.FacetManagerBridge
import org.jetbrains.jps.model.serialization.facet.FacetState
import java.util.*
class FacetTypeRegistryImpl : FacetTypeRegistry() {
private val myTypeIds: MutableMap<String, FacetTypeId<*>> = HashMap()
private val myFacetTypes: MutableMap<FacetTypeId<*>, FacetType<*, *>> = HashMap()
@Volatile private var myExtensionsLoaded = false
private val myTypeRegistrationLock = Object()
@Synchronized
override fun registerFacetType(facetType: FacetType<*, *>) {
val typeId = facetType.id
val id = facetType.stringId
LOG.assertTrue(!id.contains("/"), "Facet type id '$id' contains illegal character '/'")
LOG.assertTrue(!myFacetTypes.containsKey(typeId), "Facet type '$id' is already registered")
myFacetTypes[typeId] = facetType
LOG.assertTrue(!myTypeIds.containsKey(id), "Facet type id '$id' is already registered")
myTypeIds[id] = typeId
}
private fun loadInvalidFacetsOfType(project: Project, facetType: FacetType<*, *>) {
val modulesWithFacets = InvalidFacetManager.getInstance(project).invalidFacets
.filter { it.configuration.facetState.facetType == facetType.stringId }
.mapTo(HashSet()) { it.module }
for (module in modulesWithFacets) {
val model = FacetManager.getInstance(module).createModifiableModel()
val invalidFacets = model.getFacetsByType(InvalidFacetType.TYPE_ID).filter { it.configuration.facetState.facetType == facetType.stringId }
for (invalidFacet in invalidFacets) {
val newFacet = FacetUtil.createFacetFromStateRawJ(module, facetType, invalidFacet)
model.replaceFacet(invalidFacet, newFacet)
for (subFacet in invalidFacet.configuration.facetState.subFacets) {
model.addFacet(FacetManagerBase.createInvalidFacet(module, subFacet, newFacet, invalidFacet.configuration.errorMessage, false, false))
}
}
model.commit()
}
}
@Synchronized
private fun unregisterFacetType(facetType: FacetType<*, *>) {
val id = facetType.id
val stringId = facetType.stringId
LOG.assertTrue(myFacetTypes.remove(id) != null, "Facet type '$stringId' is not registered")
myFacetTypes.remove(id)
myTypeIds.remove(stringId)
ProjectManager.getInstance().openProjects.forEach {
convertFacetsToInvalid(it, facetType)
}
}
private fun convertFacetsToInvalid(project: Project, facetType: FacetType<*, *>) {
val modulesWithFacets = ProjectFacetManager.getInstance(project).getFacets(facetType.id).mapTo(HashSet()) { it.module }
for (module in modulesWithFacets) {
val model = FacetManager.getInstance(module).createModifiableModel()
val subFacets = model.allFacets.groupBy { it.underlyingFacet }
val facets = model.getFacetsByType(facetType.id)
for (facet in facets) {
val facetState = saveFacetWithSubFacets(facet, subFacets) ?: continue
val pluginName = facetType.pluginDescriptor?.name?.let { " '$it'" } ?: ""
val errorMessage = ProjectBundle.message("error.message.plugin.for.facets.unloaded", pluginName, facetType.presentableName)
val reportError = !ApplicationManager.getApplication().isUnitTestMode
val invalidFacet = FacetManagerBase.createInvalidFacet(module, facetState, facet.underlyingFacet, errorMessage, true, reportError)
removeAllSubFacets(model, facet, subFacets)
model.replaceFacet(facet, invalidFacet)
}
model.commit()
}
if (modulesWithFacets.isNotEmpty()) {
/* this is needed to recompute RootIndex, otherwise its DirectoryInfoImpl instances will keep references to SourceFolderBridges,
which will keep references to Facet instances from unloaded plugin via WorkspaceEntityStorage making it impossible to unload plugins without restart */
ProjectRootManagerEx.getInstanceEx(project).makeRootsChange({}, RootsChangeRescanningInfo.NO_RESCAN_NEEDED)
}
}
private fun removeAllSubFacets(model: ModifiableFacetModel, facet: Facet<*>, subFacets: Map<Facet<*>, List<Facet<*>>>) {
val toRemove = subFacets[facet] ?: return
for (subFacet in toRemove) {
removeAllSubFacets(model, subFacet, subFacets)
model.removeFacet(subFacet)
}
}
private fun saveFacetWithSubFacets(facet: Facet<*>, subFacets: Map<Facet<FacetConfiguration>, List<Facet<*>>>): FacetState? {
val state = FacetManagerBridge.saveFacetConfiguration(facet) ?: return null
(subFacets[facet] ?: emptyList()).mapNotNullTo(state.subFacets) { saveFacetWithSubFacets(it, subFacets) }
return state
}
@Synchronized
override fun getFacetTypeIds(): Array<FacetTypeId<*>> {
loadExtensions()
return myFacetTypes.keys.toTypedArray()
}
@Synchronized
override fun getFacetTypes(): Array<FacetType<*, *>> {
loadExtensions()
val facetTypes = myFacetTypes.values.toTypedArray()
Arrays.sort(facetTypes, FACET_TYPE_COMPARATOR)
return facetTypes
}
override fun getSortedFacetTypes(): Array<FacetType<*, *>> {
val types = facetTypes
Arrays.sort(types, FACET_TYPE_COMPARATOR)
return types
}
@Synchronized
override fun findFacetType(id: String): FacetType<*, *>? {
loadExtensions()
val typeId = myTypeIds[id] ?: return null
return myFacetTypes[typeId]
}
@Synchronized
override fun <F : Facet<C>?, C : FacetConfiguration?> findFacetType(typeId: FacetTypeId<F>): FacetType<F, C> {
loadExtensions()
@Suppress("UNCHECKED_CAST")
val type = myFacetTypes[typeId] as FacetType<F, C>?
LOG.assertTrue(type != null, "Cannot find facet by id '$typeId'")
return type!!
}
private fun loadExtensions() {
if (myExtensionsLoaded) {
return
}
synchronized(myTypeRegistrationLock) {
if (myExtensionsLoaded) return
//we cannot use forEachExtensionSafe here because it may throw ProcessCanceledException during iteration
// and we'll get partially initialized state here
for (type in FacetType.EP_NAME.extensions) {
registerFacetType(type)
}
FacetType.EP_NAME.addExtensionPointListener(
object : ExtensionPointListener<FacetType<*, *>> {
override fun extensionAdded(extension: FacetType<*, *>, pluginDescriptor: PluginDescriptor) {
registerFacetType(extension)
runWriteAction {
ProjectManager.getInstance().openProjects.forEach {
loadInvalidFacetsOfType(it, extension)
}
}
}
override fun extensionRemoved(extension: FacetType<*, *>,
pluginDescriptor: PluginDescriptor) {
unregisterFacetType(extension)
}
}, null)
myExtensionsLoaded = true
}
}
companion object {
private val LOG = Logger.getInstance(FacetTypeRegistryImpl::class.java)
private val FACET_TYPE_COMPARATOR = Comparator { o1: FacetType<*, *>, o2: FacetType<*, *> ->
o1.presentableName.compareTo(o2.presentableName, ignoreCase = true)
}
}
} | apache-2.0 | 0646d358f45b245351115ca396816cdf | 42.60221 | 160 | 0.722849 | 4.69423 | false | false | false | false |
google/accompanist | permissions-lint/src/main/java/com/google/accompanist/permissions/lint/util/KotlinMetadataUtils.kt | 1 | 5307 | /*
* 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
*
* 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.accompanist.permissions.lint.util
import com.intellij.lang.jvm.annotation.JvmAnnotationArrayValue
import com.intellij.lang.jvm.annotation.JvmAnnotationAttributeValue
import com.intellij.lang.jvm.annotation.JvmAnnotationConstantValue
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMethod
import com.intellij.psi.impl.compiled.ClsMethodImpl
import com.intellij.psi.util.ClassUtil
import kotlinx.metadata.KmDeclarationContainer
import kotlinx.metadata.KmFunction
import kotlinx.metadata.jvm.KotlinClassHeader
import kotlinx.metadata.jvm.KotlinClassMetadata
import kotlinx.metadata.jvm.signature
// FILE COPIED FROM:
// https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/lint/common/src/main/java/androidx/compose/lint/KotlinMetadataUtils.kt
/**
* @return the corresponding [KmFunction] for this [PsiMethod], or `null` if there is no
* corresponding [KmFunction]. This method is only meaningful if this [PsiMethod] represents a
* method defined in bytecode (most often a [ClsMethodImpl]).
*/
public fun PsiMethod.toKmFunction(): KmFunction? =
containingClass!!.getKmDeclarationContainer()?.findKmFunctionForPsiMethod(this)
// TODO: https://youtrack.jetbrains.com/issue/KT-45310
// Currently there is no built in support for parsing kotlin metadata from kotlin class files, so
// we need to manually inspect the annotations and work with Cls* (compiled PSI).
/**
* Returns the [KmDeclarationContainer] using the kotlin.Metadata annotation present on this
* [PsiClass]. Returns null if there is no annotation (not parsing a Kotlin
* class file), the annotation data is for an unsupported version of Kotlin, or if the metadata
* represents a synthetic class.
*/
private fun PsiClass.getKmDeclarationContainer(): KmDeclarationContainer? {
val classKotlinMetadataAnnotation = annotations.find {
// hasQualifiedName() not available on the min version of Lint we compile against
it.qualifiedName == KotlinMetadataFqn
} ?: return null
val metadata = KotlinClassMetadata.read(classKotlinMetadataAnnotation.toHeader())
?: return null
return when (metadata) {
is KotlinClassMetadata.Class -> metadata.toKmClass()
is KotlinClassMetadata.FileFacade -> metadata.toKmPackage()
is KotlinClassMetadata.SyntheticClass -> null
is KotlinClassMetadata.MultiFileClassFacade -> null
is KotlinClassMetadata.MultiFileClassPart -> metadata.toKmPackage()
is KotlinClassMetadata.Unknown -> null
}
}
/**
* Returns a [KotlinClassHeader] by parsing the attributes of this @kotlin.Metadata annotation.
*
* See: https://github.com/udalov/kotlinx-metadata-examples/blob/master/src/main/java
* /examples/FindKotlinGeneratedMethods.java
*/
private fun PsiAnnotation.toHeader(): KotlinClassHeader {
val attributes = attributes.associate { it.attributeName to it.attributeValue }
fun JvmAnnotationAttributeValue.parseString(): String =
(this as JvmAnnotationConstantValue).constantValue as String
fun JvmAnnotationAttributeValue.parseInt(): Int =
(this as JvmAnnotationConstantValue).constantValue as Int
fun JvmAnnotationAttributeValue.parseStringArray(): Array<String> =
(this as JvmAnnotationArrayValue).values.map {
it.parseString()
}.toTypedArray()
fun JvmAnnotationAttributeValue.parseIntArray(): IntArray =
(this as JvmAnnotationArrayValue).values.map {
it.parseInt()
}.toTypedArray().toIntArray()
val kind = attributes["k"]?.parseInt()
val metadataVersion = attributes["mv"]?.parseIntArray()
val data1 = attributes["d1"]?.parseStringArray()
val data2 = attributes["d2"]?.parseStringArray()
val extraString = attributes["xs"]?.parseString()
val packageName = attributes["pn"]?.parseString()
val extraInt = attributes["xi"]?.parseInt()
return KotlinClassHeader(
kind,
metadataVersion,
data1,
data2,
extraString,
packageName,
extraInt
)
}
/**
* @return the corresponding [KmFunction] in [this] for the given [method], matching by name and
* signature.
*/
private fun KmDeclarationContainer.findKmFunctionForPsiMethod(method: PsiMethod): KmFunction? {
// Strip any mangled part of the name in case of inline classes
val expectedName = method.name.substringBefore("-")
val expectedSignature = ClassUtil.getAsmMethodSignature(method)
return functions.find {
it.name == expectedName && it.signature?.desc == expectedSignature
}
}
private const val KotlinMetadataFqn = "kotlin.Metadata"
| apache-2.0 | 70510a0dd1e04ad7ca16bcea6450aadc | 39.823077 | 157 | 0.745807 | 4.582902 | false | false | false | false |
marius-m/wt4 | app/src/main/java/lt/markmerkk/widgets/tickets/TicketFilterSettingsWidget.kt | 1 | 5939 | package lt.markmerkk.widgets.tickets
import com.jfoenix.controls.JFXCheckBox
import com.jfoenix.controls.JFXSpinner
import com.jfoenix.svg.SVGGlyph
import javafx.geometry.Pos
import javafx.scene.Parent
import javafx.scene.control.CheckBox
import javafx.scene.control.TableView
import javafx.scene.layout.VBox
import lt.markmerkk.*
import lt.markmerkk.entities.TicketStatus
import lt.markmerkk.events.EventTicketFilterChange
import lt.markmerkk.mvp.HostServicesInteractor
import lt.markmerkk.tickets.TicketApi
import lt.markmerkk.tickets.TicketStatusesLoader
import lt.markmerkk.ui_2.views.jfxButton
import lt.markmerkk.ui_2.views.jfxSpinner
import lt.markmerkk.utils.AccountAvailablility
import tornadofx.*
import javax.inject.Inject
class TicketFilterSettingsWidget: Fragment(), TicketFilterSettingsContract.View {
@Inject lateinit var ticketStorage: TicketStorage
@Inject lateinit var ticketApi: TicketApi
@Inject lateinit var timeProvider: TimeProvider
@Inject lateinit var graphics: Graphics<SVGGlyph>
@Inject lateinit var userSettings: UserSettings
@Inject lateinit var eventBus: com.google.common.eventbus.EventBus
@Inject lateinit var schedulerProvider: SchedulerProvider
@Inject lateinit var hostServicesInteractor: HostServicesInteractor
@Inject lateinit var accountAvailablility: AccountAvailablility
private lateinit var viewContainerMain: VBox
private lateinit var viewProgress: JFXSpinner
private lateinit var viewStatusList: TableView<TicketStatusViewModel>
private lateinit var viewOnlyCurrentUser: CheckBox
private lateinit var viewFilterIncludeAssignee: CheckBox
private lateinit var viewFilterIncludeReporter: CheckBox
private lateinit var viewFilterIncludeIsWatching: CheckBox
private lateinit var presenter: TicketFilterSettingsContract.Presenter
private val ticketStatusViewModels = mutableListOf<TicketStatusViewModel>()
.asObservable()
init {
Main.component().inject(this)
}
override val root: Parent = borderpane {
addClass(Styles.dialogContainer)
style {
minHeight = 300.0.px
}
top {
label("Ticket filter") {
addClass(Styles.dialogHeader)
}
}
center {
stackpane {
viewContainerMain = vbox(spacing = 4) {
viewFilterIncludeAssignee = checkbox("Include assigned tickets") {
isSelected = userSettings.ticketFilterIncludeAssignee
}
viewFilterIncludeReporter = checkbox("Include reported tickets") {
isSelected = userSettings.ticketFilterIncludeReporter
}
viewFilterIncludeIsWatching = checkbox("Include watching tickets") {
isSelected = userSettings.ticketFilterIncludeIsWatching
}
viewStatusList = tableview(ticketStatusViewModels) {
columnResizePolicy = TableView.CONSTRAINED_RESIZE_POLICY
column("Status", TicketStatusViewModel::nameProperty) { }
column("Enabled", TicketStatusViewModel::enableProperty)
.useCheckbox()
}
// viewOnlyCurrentUser = checkbox("Only current user tickets") {
// isSelected = userSettings.onlyCurrentUserIssues
// }
}
viewProgress = jfxSpinner {
style {
padding = box(2.0.px)
}
minWidth = 24.0
minHeight = 24.0
prefWidth = 24.0
prefHeight = 24.0
maxWidth = 24.0
maxHeight = 24.0
hide()
}
}
}
bottom {
hbox(alignment = Pos.CENTER_RIGHT, spacing = 4) {
addClass(Styles.dialogContainerActionsButtons)
jfxButton("Save and exit".toUpperCase()) {
setOnAction {
presenter.saveTicketStatuses(
ticketStatusViewModels = ticketStatusViewModels,
useOnlyCurrentUser = true, // todo disable user selection to display all tickets
filterIncludeAssignee = viewFilterIncludeAssignee.isSelected,
filterIncludeReporter = viewFilterIncludeReporter.isSelected,
filterIncludeIsWatching = viewFilterIncludeIsWatching.isSelected
)
}
}
}
}
}
override fun onDock() {
super.onDock()
presenter = TicketFilterSettingsPresenter(
this,
ticketApi,
timeProvider,
ticketStorage,
userSettings,
schedulerProvider
)
presenter.onAttach()
presenter.loadTicketStatuses()
}
override fun onUndock() {
presenter.onDetach()
super.onUndock()
}
override fun showProgress() {
viewContainerMain.hide()
viewProgress.show()
}
override fun hideProgress() {
viewContainerMain.show()
viewProgress.hide()
}
override fun showStatuses(statuses: List<TicketStatus>) {
val statusesAsViewModels = statuses
.map { TicketStatusViewModel(it.name, it.enabled) }
ticketStatusViewModels.clear()
ticketStatusViewModels.addAll(statusesAsViewModels)
}
override fun noStatuses() {
ticketStatusViewModels.clear()
}
override fun cleanUpAndExit() {
eventBus.post(EventTicketFilterChange())
close()
}
}
| apache-2.0 | fe2eab57c5da6470ea24ca5484d9d746 | 35.888199 | 112 | 0.609362 | 5.666985 | false | false | false | false |
evanchooly/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/archive/Archives.kt | 1 | 2919 | package com.beust.kobalt.archive
import com.beust.kobalt.Features
import com.beust.kobalt.api.KobaltContext
import com.beust.kobalt.api.Project
import com.beust.kobalt.api.annotation.ExportedProjectProperty
import com.beust.kobalt.misc.IncludedFile
import com.beust.kobalt.misc.JarUtils
import com.beust.kobalt.misc.KFiles
import com.beust.kobalt.misc.log
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream
import java.util.*
import java.util.zip.ZipOutputStream
class Archives {
companion object {
@ExportedProjectProperty(doc = "The name of the jar file", type = "String")
const val JAR_NAME = "jarName"
private val DEFAULT_STREAM_FACTORY = { os : OutputStream -> ZipOutputStream(os) }
fun generateArchive(project: Project,
context: KobaltContext,
archiveName: String?,
suffix: String,
includedFiles: List<IncludedFile>,
expandJarFiles : Boolean = false,
outputStreamFactory: (OutputStream) -> ZipOutputStream = DEFAULT_STREAM_FACTORY) : File {
val fullArchiveName = context.variant.archiveName(project, archiveName, suffix)
val archiveDir = File(KFiles.libsDir(project))
val result = File(archiveDir.path, fullArchiveName)
log(3, "Creating $result")
if (! Features.USE_TIMESTAMPS || isOutdated(project.directory, includedFiles, result)) {
val outStream = outputStreamFactory(FileOutputStream(result))
JarUtils.addFiles(project.directory, includedFiles, outStream, expandJarFiles)
log(2, text = "Added ${includedFiles.size} files to $result")
outStream.flush()
outStream.close()
log(1, " Created $result")
} else {
log(3, " $result is up to date")
}
project.projectProperties.put(JAR_NAME, result.absolutePath)
return result
}
private fun isOutdated(directory: String, includedFiles: List<IncludedFile>, output: File): Boolean {
if (! output.exists()) return true
val lastModified = output.lastModified()
includedFiles.forEach { root ->
val allFiles = root.allFromFiles(directory)
allFiles.forEach { relFile ->
val file = File(KFiles.joinDir(directory, root.from, relFile.path))
if (file.isFile) {
if (file.lastModified() > lastModified) {
log(3, " TS - Outdated $file and $output "
+ Date(file.lastModified()) + " " + Date(output.lastModified()))
return true
}
}
}
}
return false
}
}
}
| apache-2.0 | 5358577c8d9967755dcd54d932743710 | 40.112676 | 109 | 0.589928 | 4.832781 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-core/common/src/io/ktor/client/engine/Utils.kt | 1 | 3226 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine
import io.ktor.client.utils.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.util.*
import kotlinx.coroutines.*
import kotlin.coroutines.*
/**
* Default user agent to use in ktor client.
*/
@InternalAPI
public val KTOR_DEFAULT_USER_AGENT: String = "Ktor client"
private val DATE_HEADERS = setOf(
HttpHeaders.Date,
HttpHeaders.Expires,
HttpHeaders.LastModified,
HttpHeaders.IfModifiedSince,
HttpHeaders.IfUnmodifiedSince
)
/**
* Merge headers from [content] and [requestHeaders] according to [OutgoingContent] properties
*/
@InternalAPI
public fun mergeHeaders(
requestHeaders: Headers,
content: OutgoingContent,
block: (key: String, value: String) -> Unit
) {
buildHeaders {
appendAll(requestHeaders)
appendAll(content.headers)
}.forEach { key, values ->
if (HttpHeaders.ContentLength == key) return@forEach // set later
if (HttpHeaders.ContentType == key) return@forEach // set later
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
if (DATE_HEADERS.contains(key)) {
values.forEach { value ->
block(key, value)
}
} else {
block(key, values.joinToString(","))
}
}
val missingAgent = requestHeaders[HttpHeaders.UserAgent] == null && content.headers[HttpHeaders.UserAgent] == null
if (missingAgent && needUserAgent()) {
block(HttpHeaders.UserAgent, KTOR_DEFAULT_USER_AGENT)
}
val type = content.contentType?.toString()
?: content.headers[HttpHeaders.ContentType]
?: requestHeaders[HttpHeaders.ContentType]
val length = content.contentLength?.toString()
?: content.headers[HttpHeaders.ContentLength]
?: requestHeaders[HttpHeaders.ContentLength]
type?.let { block(HttpHeaders.ContentType, it) }
length?.let { block(HttpHeaders.ContentLength, it) }
}
/**
* Returns current call context if exists, otherwise null.
*/
@InternalAPI
public suspend fun callContext(): CoroutineContext = coroutineContext[KtorCallContextElement]!!.callContext
/**
* Coroutine context element containing call job.
*/
internal class KtorCallContextElement(val callContext: CoroutineContext) : CoroutineContext.Element {
override val key: CoroutineContext.Key<*>
get() = KtorCallContextElement
public companion object : CoroutineContext.Key<KtorCallContextElement>
}
/**
* Attach [callJob] to user job using the following logic: when user job completes with exception, [callJob] completes
* with exception too.
*/
@OptIn(InternalCoroutinesApi::class)
internal suspend inline fun attachToUserJob(callJob: Job) {
val userJob = coroutineContext[Job] ?: return
val cleanupHandler = userJob.invokeOnCompletion(onCancelling = true) { cause ->
cause ?: return@invokeOnCompletion
callJob.cancel(CancellationException(cause.message))
}
callJob.invokeOnCompletion {
cleanupHandler.dispose()
}
}
private fun needUserAgent(): Boolean = !PlatformUtils.IS_BROWSER
| apache-2.0 | 5054d8774597c114d3d4e17c8c840423 | 29.72381 | 118 | 0.702418 | 4.389116 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/browse/extension/details/ExtensionDetailsPresenter.kt | 2 | 1611 | package eu.kanade.tachiyomi.ui.browse.extension.details
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import eu.kanade.tachiyomi.extension.ExtensionManager
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import rx.android.schedulers.AndroidSchedulers
import uy.kohesive.injekt.injectLazy
class ExtensionDetailsPresenter(
private val controller: ExtensionDetailsController,
private val pkgName: String,
) : BasePresenter<ExtensionDetailsController>() {
private val extensionManager: ExtensionManager by injectLazy()
val extension = extensionManager.installedExtensions.find { it.pkgName == pkgName }
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
bindToUninstalledExtension()
}
private fun bindToUninstalledExtension() {
extensionManager.getInstalledExtensionsObservable()
.skip(1)
.filter { extensions -> extensions.none { it.pkgName == pkgName } }
.map { }
.take(1)
.observeOn(AndroidSchedulers.mainThread())
.subscribeFirst({ view, _ ->
view.onExtensionUninstalled()
})
}
fun uninstallExtension() {
val extension = extension ?: return
extensionManager.uninstallExtension(extension.pkgName)
}
fun openInSettings() {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
data = Uri.fromParts("package", pkgName, null)
}
controller.startActivity(intent)
}
}
| apache-2.0 | e60abfa4c27c64b046a746cb5999fd0f | 31.22 | 87 | 0.69522 | 5.034375 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/OrientedBoundingBox.kt | 2 | 4086 | package graphics.scenery
import graphics.scenery.utils.extensions.minus
import graphics.scenery.utils.extensions.plus
import graphics.scenery.utils.extensions.times
import org.joml.Vector3f
import java.lang.Math.max
import java.lang.Math.min
/**
* Oriented bounding box class to perform easy intersection tests.
*
* @property[min] The x/y/z minima for the bounding box.
* @property[max] The x/y/z maxima for the bounding box.
*/
open class OrientedBoundingBox(val n: Node, val min: Vector3f, val max: Vector3f) {
/**
* Bounding sphere class, a bounding sphere is defined by an origin and a radius,
* to enclose all of the Node's geometry.
*/
data class BoundingSphere(val origin: Vector3f, val radius: Float)
/**
* Alternative [OrientedBoundingBox] constructor taking the [min] and [max] as a series of floats.
*/
constructor(n: Node, xMin: Float, yMin: Float, zMin: Float, xMax: Float, yMax: Float, zMax: Float) : this(n, Vector3f(xMin, yMin, zMin), Vector3f(xMax, yMax, zMax))
/**
* Alternative [OrientedBoundingBox] constructor, taking a 6-element float array for [min] and [max].
*/
constructor(n: Node, boundingBox: FloatArray) : this(n, Vector3f(boundingBox[0], boundingBox[2], boundingBox[4]), Vector3f(boundingBox[1], boundingBox[3], boundingBox[5]))
/**
* Returns the maximum bounding sphere of this bounding box.
*/
fun getBoundingSphere(): BoundingSphere {
var origin = Vector3f(0f, 0f, 0f)
var radius = 0f
n.ifSpatial {
if(needsUpdate || needsUpdateWorld) {
updateWorld(true, false)
}
val worldMin = worldPosition(min)
val worldMax = worldPosition(max)
origin = worldMin + (worldMax - worldMin) * 0.5f
radius = (worldMax - origin).length()
}
return BoundingSphere(origin, radius)
}
/**
* Checks this [OrientedBoundingBox] for intersection with [other], and returns
* true if the bounding boxes do intersect.
*/
fun intersects(other: OrientedBoundingBox): Boolean {
return other.getBoundingSphere().radius + getBoundingSphere().radius > (other.getBoundingSphere().origin - getBoundingSphere().origin).length()
}
/**
* Returns the hash code of this [OrientedBoundingBox], taking [min] and [max] into consideration.
*/
override fun hashCode(): Int {
return min.hashCode() + max.hashCode()
}
/**
* Compares this bounding box to [other], returning true if they are equal.
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as? OrientedBoundingBox ?: return false
if (min.hashCode() != other.min.hashCode()) return false
if (max.hashCode() != other.max.hashCode()) return false
return true
}
/**
* Return an [OrientedBoundingBox] that covers both [lhs] and [rhs].
*/
fun expand(lhs: OrientedBoundingBox, rhs: OrientedBoundingBox): OrientedBoundingBox {
return OrientedBoundingBox(lhs.n,
min(lhs.min.x(), rhs.min.x()),
min(lhs.min.y(), rhs.min.y()),
min(lhs.min.z(), rhs.min.z()),
max(lhs.max.x(), rhs.max.x()),
max(lhs.max.y(), rhs.max.y()),
max(lhs.max.z(), rhs.max.z()))
}
/**
* Return an [OrientedBoundingBox] in World coordinates.
*/
fun asWorld(): OrientedBoundingBox {
return OrientedBoundingBox(n,
n.spatialOrNull()?.worldPosition(min) ?: Vector3f(0.0f, 0.0f, 0.0f),
n.spatialOrNull()?.worldPosition(max)?: Vector3f(0.0f, 0.0f, 0.0f))
}
/**
* Return an [OrientedBoundingBox] with min/max translated by offset vector.
*/
fun translate(offset: Vector3f): OrientedBoundingBox {
return OrientedBoundingBox(n, min + offset, max + offset)
}
override fun toString(): String {
return "OrientedBoundingBox(min=$min, max=$max)"
}
}
| lgpl-3.0 | 65e188157d016dbd88162981d60a0caf | 34.224138 | 175 | 0.631914 | 3.829428 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/repl/REPL.kt | 1 | 3887 | package graphics.scenery.repl
import graphics.scenery.Hub
import graphics.scenery.Hubable
import net.imagej.lut.LUTService
import org.scijava.Context
import org.scijava.`object`.ObjectService
import org.scijava.script.ScriptREPL
import org.scijava.ui.swing.script.InterpreterWindow
import java.util.*
import javax.swing.SwingUtilities
/**
* Constructs a read-eval-print loop (REPL) to interactive manipulate scenery's
* scene rendering.
*
* @author Ulrik Günther <[email protected]>
* @property[addAccessibleObject] A list of objects that should be accessible right away in the REPL
* @constructor Returns a REPL, equipped with a window for input/output.
*/
class REPL @JvmOverloads constructor(override var hub : Hub?, scijavaContext: Context? = null, vararg accessibleObjects: Any) : Hubable {
/** SciJava context for the REPL */
protected var context: Context
/** SciJava interpreter window, handles input and output. */
protected var interpreterWindow: InterpreterWindow? = null
/** SciJava REPL **/
protected var repl: ScriptREPL? = null
/** Code to evaluate upon launch. */
protected var startupScriptCode: String = ""
/** A startup script to evaluate upon launch. */
protected var startupScript = "startup.py"
/** The [startupScript] will be searched for in the resources of this class. */
protected var startupScriptClass: Class<*> = REPL::class.java
/** Whether we are running headless or not */
protected val headless = (System.getProperty("scenery.Headless", "false")?.toBoolean() ?: false) || (System.getProperty("java.awt.headless", "false")?.toBoolean() ?: false)
init {
hub?.add(this)
context = scijavaContext ?: Context(ObjectService::class.java, LUTService::class.java)
if(!headless) {
interpreterWindow = InterpreterWindow(context)
interpreterWindow?.isVisible = false
repl = interpreterWindow?.repl
} else {
repl = ScriptREPL(context, System.out)
repl?.lang("Python")
repl?.initialize()
}
setStartupScript(startupScript, startupScriptClass)
accessibleObjects.forEach { context.getService(ObjectService::class.java).addObject(it) }
}
/**
* Sets a startup script and its class to find it in its resources.
*
* @param[scriptFileName] The file name of the script
* @param[baseClass] The class whose resources to search for the script
*/
fun setStartupScript(scriptFileName: String, baseClass: Class<*>) {
startupScriptClass = baseClass
startupScript = scriptFileName
startupScriptCode = Scanner(startupScriptClass.getResourceAsStream(startupScript), "UTF-8").useDelimiter("\\A").next()
}
/**
* Adds an object to the REPL's accessible objects
*
* @param[obj] The object to add.
*/
fun addAccessibleObject(obj: Any) {
context.getService(ObjectService::class.java).addObject(obj)
}
/**
* Shows the interpreter window
*/
fun showConsoleWindow() {
interpreterWindow?.isVisible = true
}
/**
* Hides the interpreter window
*/
fun hideConsoleWindow() {
interpreterWindow?.isVisible = false
}
/**
* Launches the REPL and evaluates any set startup code.
*/
fun start() {
repl?.lang("Python")
eval(startupScriptCode)
}
/**
* Evaluate a string in the REPL
*
* @param[code] The code to evaluate.
*/
fun eval(code: String): Any? {
return repl?.interpreter?.eval(code)
}
/**
* Closes the REPL instance.
*/
fun close() {
if(!headless) {
SwingUtilities.invokeAndWait {
interpreterWindow?.isVisible = false
interpreterWindow?.dispose()
}
}
}
}
| lgpl-3.0 | 5f5acbb46da5da6d8ef7b94a0ff675dd | 30.852459 | 176 | 0.651312 | 4.497685 | false | false | false | false |
android/project-replicator | code/codegen/src/main/kotlin/com/android/gradle/replicator/resgen/FontResourceGenerator.kt | 1 | 2929 | package com.android.gradle.replicator.resgen
import com.android.gradle.replicator.model.internal.filedata.AbstractAndroidResourceProperties
import com.android.gradle.replicator.model.internal.filedata.DefaultAndroidResourceProperties
import com.android.gradle.replicator.model.internal.filedata.ResourcePropertyType
import com.android.gradle.replicator.resgen.resourceModel.ResourceData
import com.android.gradle.replicator.resgen.util.copyResourceFile
import com.android.gradle.replicator.resgen.util.getFileType
import com.android.gradle.replicator.resgen.util.getResourceClosestToSize
import java.io.File
class FontResourceGenerator(params: ResourceGenerationParams): ResourceGenerator(params) {
override fun generateResource(
properties: AbstractAndroidResourceProperties,
outputFolder: File
) {
// Sanity check. This should not happen unless there is a bug in the metadata reader.
if (properties.propertyType != ResourcePropertyType.DEFAULT) {
throw RuntimeException ("Unexpected property type. Got ${properties.propertyType} instead of ${ResourcePropertyType.DEFAULT}")
}
if (getFileType(properties.extension) == null) {
println("Unsupported file type $properties.extension")
return
}
(properties as DefaultAndroidResourceProperties).fileData.forEach { fileSize ->
val fileName = "font_${params.uniqueIdGenerator.genIdByCategory("font.fileName.${properties.qualifiers}")}"
val outputFile = File(outputFolder, "$fileName.${properties.extension}")
when (properties.extension) {
"xml" -> {
println("Generating ${outputFile.absolutePath}")
generateFontReferenceResource(outputFile, properties.splitQualifiers, fileSize)
}
else -> {
println("Generating ${outputFile.absolutePath}")
generateFontResource(outputFile, properties.extension, fileSize)
}
}
params.resourceModel.resourceList.add(
ResourceData(
pkg = "",
name = fileName,
type = "font",
extension = properties.extension,
qualifiers = properties.splitQualifiers)
)
}
}
private fun generateFontResource (
outputFile: File,
resourceExtension: String,
fileSize: Long
) {
val fileType = getFileType(resourceExtension)!!
val resourcePath = getResourceClosestToSize(fileType, fileSize) ?: return
copyResourceFile(resourcePath, outputFile)
}
private fun generateFontReferenceResource (
outputFile: File,
resourceQualifiers: List<String>,
fileSize: Long
) {
// TODO: Implement this (needs resource context)
}
} | apache-2.0 | 540347a84867beb2ae08a09127d783e6 | 41.463768 | 138 | 0.660976 | 5.374312 | false | false | false | false |
mdanielwork/intellij-community | plugins/stats-collector/src/com/intellij/stats/completion/TimeBetweenTypingTracker.kt | 7 | 1818 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.stats.completion
import com.intellij.codeInsight.lookup.impl.PrefixChangeListener
import com.intellij.openapi.project.Project
import com.intellij.stats.personalization.UserFactorDescriptions
import com.intellij.stats.personalization.UserFactorStorage
import java.util.concurrent.TimeUnit
/**
* @author Vitaliy.Bibaev
*/
class TimeBetweenTypingTracker(private val project: Project) : PrefixChangeListener {
private companion object {
val MAX_ALLOWED_DELAY = TimeUnit.SECONDS.toMillis(10)
}
private var lastTypingTime: Long = -1L
override fun beforeAppend(c: Char): Unit = prefixChanged()
override fun beforeTruncate(): Unit = prefixChanged()
private fun prefixChanged() {
if (lastTypingTime == -1L) {
lastTypingTime = System.currentTimeMillis()
return
}
val currentTime = System.currentTimeMillis()
val delay = currentTime - lastTypingTime
if (delay > MAX_ALLOWED_DELAY) return
UserFactorStorage.applyOnBoth(project, UserFactorDescriptions.TIME_BETWEEN_TYPING) { updater ->
updater.fireTypingPerformed(delay.toInt())
}
lastTypingTime = currentTime
}
} | apache-2.0 | b92aa72f0d4d65659272ff8c66324500 | 33.320755 | 103 | 0.724422 | 4.412621 | false | false | false | false |
cdcalc/cdcalc | core/src/test/kotlin/com/github/cdcalc/TestDataFactory.kt | 1 | 1835 | package com.github.cdcalc
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.PersonIdent
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.util.*
@Suppress("unused")
fun Git.prettyLog() {
val process = ProcessBuilder().directory(this.repository.directory).command("git", "lg").start()
val stream = process.inputStream;
val reader = InputStreamReader(stream);
val bufferedReader = BufferedReader(reader);
bufferedReader.lineSequence().forEach {
println(it)
}
bufferedReader.close()
reader.close()
stream.close()
process.waitFor()
}
fun Git.checkout(branch: String, create: Boolean = false): Git {
this.checkout()
.setCreateBranch(create)
.setName(branch)
.call()
return this
}
fun Git.createTaggedCommit(tag: String): Git {
this.createCommit()
this.tag().let {
it.name = tag
it.message = "Released $tag"
it.call()
}
this.commit()
return this
}
fun Git.createCommit(message: String = "create file"): Git {
val commit = this.commit()
val id = UUID.randomUUID();
val file = File(this.repository.workTree, id.toString())
file.createNewFile()
commit.author = PersonIdent("Örjan Sjöholm", "[email protected]")
commit.setAll(true)
commit.message = message + " > " + id.toString() + " @ " + this.repository.branch
commit.call()
return this
}
fun initGitFlow(): Git {
val property = System.getProperty("java.io.tmpdir")
val file = File(property, "test-repo")
file.deleteRecursively()
file.mkdirs()
val git = Git.init().setDirectory(file).call()
git.createCommit()
git.tag().setName("v1.0.0").call()
git.checkout("develop", true).createCommit()
return git
}
| mit | ff425aa973143eb62ccfe6e38a02ed7f | 22.5 | 100 | 0.652482 | 3.72561 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/shuntingYard/ShuntingYard1.kt | 1 | 1562 | package katas.kotlin.shuntingYard
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.junit.Test
class ShuntingYard1 {
@Test fun `converts infix expression to RPN`() {
assertThat(listOf("1", "+", "2").toRPN(), equalTo(listOf("1", "2", "+")))
assertThat(listOf("1", "+", "2", "+", "3").toRPN(), equalTo(listOf("1", "2", "+", "3", "+")))
assertThat(listOf("1", "*", "2", "+", "3").toRPN(), equalTo(listOf("1", "2", "*", "3", "+")))
assertThat(listOf("1", "+", "2", "*", "3").toRPN(), equalTo(listOf("1", "2", "3", "*", "+")))
}
private fun List<String>.toRPN(): List<String> {
val result = ArrayList<String>()
val stack = ArrayList<String>()
forEach { token ->
if (token.isOperator()) {
if (stack.isNotEmpty() && token.priority <= stack.last().priority) {
result.consume(stack)
}
stack.addFirst(token)
} else {
result.add(token)
}
}
return result.consume(stack)
}
private fun <T> MutableList<T>.addFirst(element: T) = add(0, element)
private fun <T> MutableList<T>.consume(list: MutableList<T>): MutableList<T> = apply {
addAll(list)
list.clear()
}
private val operatorsPriority = mapOf(
"*" to 20,
"+" to 10
)
private fun String.isOperator() = operatorsPriority.contains(this)
private val String.priority get() = operatorsPriority[this]!!
}
| unlicense | 190711928b77388a77f283b0745a3687 | 32.956522 | 101 | 0.541613 | 3.934509 | false | false | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/dalatlaptop/ux/fragments/OrdersHistoryFragment.kt | 1 | 5744 | package com.tungnui.dalatlaptop.ux.fragments
import android.app.ProgressDialog
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.tungnui.dalatlaptop.R
import com.tungnui.dalatlaptop.SettingsMy
import com.tungnui.dalatlaptop.api.EndPoints
import com.tungnui.dalatlaptop.api.ServiceGenerator
import com.tungnui.dalatlaptop.models.Order
import com.tungnui.dalatlaptop.libraryhelper.EndlessRecyclerScrollListener
import com.tungnui.dalatlaptop.libraryhelper.RecyclerMarginDecorator
import com.tungnui.dalatlaptop.libraryhelper.Utils
import com.tungnui.dalatlaptop.utils.getNextUrl
import com.tungnui.dalatlaptop.ux.MainActivity
import com.tungnui.dalatlaptop.ux.adapters.OrdersHistoryRecyclerAdapter
import com.tungnui.dalatlaptop.ux.dialogs.LoginExpiredDialogFragment
import com.tungnui.dalatlaptop.api.OrderServices
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_orders_history.*
import timber.log.Timber
class OrdersHistoryFragment : Fragment() {
private var mCompositeDisposable: CompositeDisposable
val orderService: OrderServices
init {
mCompositeDisposable = CompositeDisposable()
orderService = ServiceGenerator.createService(OrderServices::class.java)
}
private var progressDialog: ProgressDialog? = null
private var order: Order? = null
private var orderNextLink:String? = null
private lateinit var ordersHistoryRecyclerAdapter: OrdersHistoryRecyclerAdapter
private var endlessRecyclerScrollListener: EndlessRecyclerScrollListener? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_orders_history, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
MainActivity.setActionBarTitle(getString(R.string.Order_history))
progressDialog = Utils.generateProgressDialog(activity, false)
prepareOrdersHistoryRecycler()
loadOrders(null)
}
private fun prepareOrdersHistoryRecycler() {
ordersHistoryRecyclerAdapter = OrdersHistoryRecyclerAdapter{
val activity = activity
(activity as? MainActivity)?.onOrderSelected(order)
}
orders_history_recycler.adapter = ordersHistoryRecyclerAdapter
val layoutManager = LinearLayoutManager(orders_history_recycler.context)
orders_history_recycler.layoutManager = layoutManager
orders_history_recycler.itemAnimator = DefaultItemAnimator()
orders_history_recycler.setHasFixedSize(true)
orders_history_recycler.addItemDecoration(RecyclerMarginDecorator(resources.getDimensionPixelSize(R.dimen.base_margin)))
endlessRecyclerScrollListener = object : EndlessRecyclerScrollListener(layoutManager) {
override fun onLoadMore(currentPage: Int) {
if (orderNextLink != null ) {
loadOrders(orderNextLink)
} else {
Timber.d("CustomLoadMoreDataFromApi NO MORE DATA")
}
}
}
orders_history_recycler.addOnScrollListener(endlessRecyclerScrollListener)
}
private fun loadOrders(url: String?) {
var user = SettingsMy.getActiveUser();
var url:String? = url
if (user != null) {
progressDialog?.show();
if (url == null) {
ordersHistoryRecyclerAdapter.clear();
url = EndPoints.ORDERS +"?customer=${user.id}"
}
var disposable = orderService.getAll(url)
.subscribeOn((Schedulers.io()))
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response ->
response.body()?.let { ordersHistoryRecyclerAdapter.addOrders(it) }
orderNextLink = response.headers()["Link"]?.getNextUrl()
if (ordersHistoryRecyclerAdapter.getItemCount() > 0) {
order_history_empty.setVisibility(View.GONE);
order_history_content.setVisibility(View.VISIBLE);
} else {
order_history_empty.setVisibility(View.VISIBLE);
order_history_content.setVisibility(View.GONE);
}
progressDialog?.cancel()
},
{ error ->
progressDialog?.cancel()
})
mCompositeDisposable.add(disposable)
} else {
var loginExpiredDialogFragment = LoginExpiredDialogFragment();
loginExpiredDialogFragment.show(getFragmentManager(), "loginExpiredDialogFragment");
}
}
override fun onStop() {
if (progressDialog != null) {
if (progressDialog!!.isShowing && endlessRecyclerScrollListener != null) {
endlessRecyclerScrollListener!!.resetLoading()
}
progressDialog!!.cancel()
}
super.onStop()
}
override fun onDestroyView() {
orders_history_recycler.clearOnScrollListeners()
super.onDestroyView()
}
}
| mit | 7dd561b39f78b9b8389b106ca5d20cf1 | 43.184615 | 128 | 0.666957 | 5.523077 | false | false | false | false |
RomanBelkov/workshop-jb | src/iii_conventions/_30_MultiAssignment.kt | 2 | 539 | package iii_conventions.multiAssignemnt
import util.*
fun todoTask30(): Nothing = TODO(
"""
Task 30.
Read about multi-declarations and make the following code compile by adding one word (after uncommenting it).
""",
documentation = doc30()
)
class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)
fun isLeapDay(date: MyDate): Boolean {
todoTask30()
// val (year, month, dayOfMonth) = date
//
// // 29 February of a leap year
// return year % 4 == 0 && month == 2 && dayOfMonth == 29
} | mit | 008f722bf443e2684120b5025fc64963 | 24.714286 | 117 | 0.64564 | 3.743056 | false | false | false | false |
MGaetan89/ShowsRage | app/src/main/kotlin/com/mgaetan89/showsrage/model/Schedule.kt | 1 | 934 | package com.mgaetan89.showsrage.model
import com.google.gson.annotations.SerializedName
import io.realm.RealmObject
import io.realm.annotations.Index
import io.realm.annotations.PrimaryKey
open class Schedule : RealmObject() {
@SerializedName("airdate")
open var airDate: String = ""
open var airs: String = ""
open var episode: Int = 0
@SerializedName("ep_name")
open var episodeName: String = ""
@SerializedName("ep_plot")
open var episodePlot: String? = ""
@PrimaryKey
open var id: String = ""
@SerializedName("indexerid")
open var indexerId: Int = 0
open var network: String = ""
open var paused: Int = 0
open var quality: String = ""
@Index
open var section: String = ""
open var season: Int = 0
@SerializedName("show_name")
open var showName: String = ""
@SerializedName("show_status")
open var showStatus: String? = null
@SerializedName("tvdbid")
open var tvDbId: Int = 0
open var weekday: Int = 0
}
| apache-2.0 | 7d7c07092e824d0ff00855f943739055 | 26.470588 | 49 | 0.719486 | 3.359712 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveUtils.kt | 1 | 30984 | // 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.refactoring.move
import com.intellij.ide.util.DirectoryUtil
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.*
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.move.moveMembers.MoveMemberHandler
import com.intellij.refactoring.move.moveMembers.MoveMembersOptions
import com.intellij.refactoring.move.moveMembers.MoveMembersProcessor
import com.intellij.refactoring.util.MoveRenameUsageInfo
import com.intellij.refactoring.util.NonCodeUsageInfo
import com.intellij.usageView.UsageInfo
import com.intellij.util.IncorrectOperationException
import com.intellij.util.SmartList
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.base.utils.fqname.isImported
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.codeInsight.shorten.addDelayedImportRequest
import org.jetbrains.kotlin.idea.core.getPackage
import org.jetbrains.kotlin.idea.core.util.toPsiDirectory
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference.ShorteningMode
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.statistics.KotlinMoveRefactoringFUSCollector
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
import org.jetbrains.kotlin.types.expressions.DoubleColonLHS
import org.jetbrains.kotlin.util.capitalizeDecapitalize.capitalizeAsciiOnly
import org.jetbrains.kotlin.utils.addIfNotNull
import java.io.File
import java.lang.System.currentTimeMillis
import java.util.*
sealed class ContainerInfo {
abstract val fqName: FqName?
abstract fun matches(descriptor: DeclarationDescriptor): Boolean
object UnknownPackage : ContainerInfo() {
override val fqName: FqName? = null
override fun matches(descriptor: DeclarationDescriptor) = descriptor is PackageViewDescriptor
}
class Package(override val fqName: FqName) : ContainerInfo() {
override fun matches(descriptor: DeclarationDescriptor): Boolean {
return descriptor is PackageFragmentDescriptor && descriptor.fqName == fqName
}
override fun equals(other: Any?) = other is Package && other.fqName == fqName
override fun hashCode() = fqName.hashCode()
}
class Class(override val fqName: FqName) : ContainerInfo() {
override fun matches(descriptor: DeclarationDescriptor): Boolean {
return descriptor is ClassDescriptor && descriptor.importableFqName == fqName
}
override fun equals(other: Any?) = other is Class && other.fqName == fqName
override fun hashCode() = fqName.hashCode()
}
}
data class ContainerChangeInfo(val oldContainer: ContainerInfo, val newContainer: ContainerInfo)
fun KtElement.getInternalReferencesToUpdateOnPackageNameChange(containerChangeInfo: ContainerChangeInfo): List<UsageInfo> {
val usages = ArrayList<UsageInfo>()
processInternalReferencesToUpdateOnPackageNameChange(containerChangeInfo) { expr, factory -> usages.addIfNotNull(factory(expr)) }
return usages
}
private typealias UsageInfoFactory = (KtSimpleNameExpression) -> UsageInfo?
fun KtElement.processInternalReferencesToUpdateOnPackageNameChange(
containerChangeInfo: ContainerChangeInfo,
body: (originalRefExpr: KtSimpleNameExpression, usageFactory: UsageInfoFactory) -> Unit
) {
val file = containingFile as? KtFile ?: return
val importPaths = file.importDirectives.mapNotNull { it.importPath }
tailrec fun isImported(descriptor: DeclarationDescriptor): Boolean {
val fqName = DescriptorUtils.getFqName(descriptor).let { if (it.isSafe) it.toSafe() else return@isImported false }
if (importPaths.any { fqName.isImported(it, false) }) return true
return when (val containingDescriptor = descriptor.containingDeclaration) {
is ClassDescriptor, is PackageViewDescriptor -> isImported(containingDescriptor)
else -> false
}
}
fun processReference(refExpr: KtSimpleNameExpression, bindingContext: BindingContext): (UsageInfoFactory)? {
val descriptor = bindingContext[BindingContext.REFERENCE_TARGET, refExpr]?.getImportableDescriptor() ?: return null
val containingDescriptor = descriptor.containingDeclaration ?: return null
val callableKind = (descriptor as? CallableMemberDescriptor)?.kind
if (callableKind != null && callableKind != CallableMemberDescriptor.Kind.DECLARATION) return null
// Special case for enum entry superclass references (they have empty text and don't need to be processed by the refactoring)
if (refExpr.textRange.isEmpty) return null
if (descriptor is ClassDescriptor && descriptor.isInner && refExpr.parent is KtCallExpression) return null
val isCallable = descriptor is CallableDescriptor
val isExtension = isCallable && refExpr.isExtensionRef(bindingContext)
val isCallableReference = isCallableReference(refExpr.mainReference)
val declaration by lazy {
var result = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) ?: return@lazy null
if (descriptor.isCompanionObject() &&
bindingContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, refExpr] !== null
) {
result = (result as? KtObjectDeclaration)?.containingClassOrObject ?: result
}
result
}
if (isCallable) {
if (!isCallableReference) {
if (isExtension && containingDescriptor is ClassDescriptor) {
val dispatchReceiver = refExpr.getResolvedCall(bindingContext)?.dispatchReceiver
val implicitClass = (dispatchReceiver as? ImplicitClassReceiver)?.classDescriptor
if (implicitClass?.isCompanionObject == true) {
return { ImplicitCompanionAsDispatchReceiverUsageInfo(it, implicitClass) }
}
if (dispatchReceiver != null || containingDescriptor.kind != ClassKind.OBJECT) return null
}
}
if (!isExtension) {
val isCompatibleDescriptor = containingDescriptor is PackageFragmentDescriptor ||
containingDescriptor is ClassDescriptor && containingDescriptor.kind == ClassKind.OBJECT ||
descriptor is JavaCallableMemberDescriptor && ((declaration as? PsiMember)?.hasModifierProperty(PsiModifier.STATIC) == true)
if (!isCompatibleDescriptor) return null
}
}
if (!DescriptorUtils.getFqName(descriptor).isSafe) return null
val (oldContainer, newContainer) = containerChangeInfo
val containerFqName = descriptor
.parents
.mapNotNull {
when {
oldContainer.matches(it) -> oldContainer.fqName
newContainer.matches(it) -> newContainer.fqName
else -> null
}
}
.firstOrNull()
val isImported = isImported(descriptor)
if (isImported && this is KtFile) return null
val declarationNotNull = declaration ?: return null
if (isExtension || containerFqName != null || isImported) return {
createMoveUsageInfoIfPossible(it.mainReference, declarationNotNull, addImportToOriginalFile = false, isInternal = true)
}
return null
}
@Suppress("DEPRECATION")
val bindingContext = analyzeWithAllCompilerChecks().bindingContext
forEachDescendantOfType<KtReferenceExpression> { refExpr ->
if (refExpr !is KtSimpleNameExpression || refExpr.parent is KtThisExpression) return@forEachDescendantOfType
processReference(refExpr, bindingContext)?.let { body(refExpr, it) }
}
}
internal var KtSimpleNameExpression.internalUsageInfo: UsageInfo? by CopyablePsiUserDataProperty(Key.create("INTERNAL_USAGE_INFO"))
internal fun markInternalUsages(usages: Collection<UsageInfo>) {
usages.forEach { (it.element as? KtSimpleNameExpression)?.internalUsageInfo = it }
}
internal fun restoreInternalUsages(
scope: KtElement,
oldToNewElementsMapping: Map<PsiElement, PsiElement>,
forcedRestore: Boolean = false
): List<UsageInfo> {
return scope.collectDescendantsOfType<KtSimpleNameExpression>().mapNotNull {
val usageInfo = it.internalUsageInfo
if (!forcedRestore && usageInfo?.element != null) return@mapNotNull usageInfo
val referencedElement = (usageInfo as? MoveRenameUsageInfo)?.referencedElement ?: return@mapNotNull null
val newReferencedElement = mapToNewOrThis(referencedElement, oldToNewElementsMapping)
if (!newReferencedElement.isValid) return@mapNotNull null
(usageInfo as? KotlinMoveUsage)?.refresh(it, newReferencedElement)
}
}
internal fun cleanUpInternalUsages(usages: Collection<UsageInfo>) {
usages.forEach { (it.element as? KtSimpleNameExpression)?.internalUsageInfo = null }
}
class ImplicitCompanionAsDispatchReceiverUsageInfo(
callee: KtSimpleNameExpression,
val companionDescriptor: ClassDescriptor
) : UsageInfo(callee)
interface KotlinMoveUsage {
val isInternal: Boolean
fun refresh(refExpr: KtSimpleNameExpression, referencedElement: PsiElement): UsageInfo?
}
class UnqualifiableMoveRenameUsageInfo(
element: PsiElement,
reference: PsiReference,
referencedElement: PsiElement,
val originalFile: PsiFile,
val addImportToOriginalFile: Boolean,
override val isInternal: Boolean
) : MoveRenameUsageInfo(
element,
reference,
reference.rangeInElement.startOffset,
reference.rangeInElement.endOffset,
referencedElement,
false
), KotlinMoveUsage {
override fun refresh(refExpr: KtSimpleNameExpression, referencedElement: PsiElement): UsageInfo {
return UnqualifiableMoveRenameUsageInfo(
refExpr,
refExpr.mainReference,
referencedElement,
originalFile,
addImportToOriginalFile,
isInternal
)
}
}
class QualifiableMoveRenameUsageInfo(
element: PsiElement,
reference: PsiReference,
referencedElement: PsiElement,
override val isInternal: Boolean
) : MoveRenameUsageInfo(
element,
reference,
reference.rangeInElement.startOffset,
reference.rangeInElement.endOffset,
referencedElement,
false
),
KotlinMoveUsage {
override fun refresh(refExpr: KtSimpleNameExpression, referencedElement: PsiElement): UsageInfo {
return QualifiableMoveRenameUsageInfo(refExpr, refExpr.mainReference, referencedElement, isInternal)
}
}
interface DeferredKotlinMoveUsage : KotlinMoveUsage {
fun resolve(newElement: PsiElement): UsageInfo?
}
class CallableReferenceMoveRenameUsageInfo(
element: PsiElement,
reference: PsiReference,
referencedElement: PsiElement,
val originalFile: PsiFile,
private val addImportToOriginalFile: Boolean,
override val isInternal: Boolean
) : MoveRenameUsageInfo(
element,
reference,
reference.rangeInElement.startOffset,
reference.rangeInElement.endOffset,
referencedElement,
false
), DeferredKotlinMoveUsage {
override fun refresh(refExpr: KtSimpleNameExpression, referencedElement: PsiElement): UsageInfo {
return CallableReferenceMoveRenameUsageInfo(
refExpr,
refExpr.mainReference,
referencedElement,
originalFile,
addImportToOriginalFile,
isInternal
)
}
override fun resolve(newElement: PsiElement): UsageInfo? {
val target = newElement.unwrapped
val element = element ?: return null
val reference = reference ?: return null
val referencedElement = referencedElement ?: return null
if (target != null && target.isTopLevelKtOrJavaMember()) {
element.getStrictParentOfType<KtCallableReferenceExpression>()?.receiverExpression?.delete()
return UnqualifiableMoveRenameUsageInfo(
element,
reference,
referencedElement,
element.containingFile!!,
addImportToOriginalFile,
isInternal
)
}
return QualifiableMoveRenameUsageInfo(element, reference, referencedElement, isInternal)
}
}
fun createMoveUsageInfoIfPossible(
reference: PsiReference,
referencedElement: PsiElement,
addImportToOriginalFile: Boolean,
isInternal: Boolean
): UsageInfo? {
val element = reference.element
return when (getReferenceKind(reference, referencedElement)) {
ReferenceKind.QUALIFIABLE -> QualifiableMoveRenameUsageInfo(
element, reference, referencedElement, isInternal
)
ReferenceKind.UNQUALIFIABLE -> UnqualifiableMoveRenameUsageInfo(
element, reference, referencedElement, element.containingFile!!, addImportToOriginalFile, isInternal
)
ReferenceKind.CALLABLE_REFERENCE -> CallableReferenceMoveRenameUsageInfo(
element, reference, referencedElement, element.containingFile!!, addImportToOriginalFile, isInternal
)
else -> null
}
}
private enum class ReferenceKind {
QUALIFIABLE,
UNQUALIFIABLE,
CALLABLE_REFERENCE,
IRRELEVANT
}
private fun KtSimpleNameExpression.isExtensionRef(bindingContext: BindingContext? = null): Boolean {
val resolvedCall = getResolvedCall(bindingContext ?: analyze(BodyResolveMode.PARTIAL)) ?: return false
if (resolvedCall is VariableAsFunctionResolvedCall) {
return resolvedCall.variableCall.candidateDescriptor.isExtension || resolvedCall.functionCall.candidateDescriptor.isExtension
}
return resolvedCall.candidateDescriptor.isExtension
}
private fun getReferenceKind(reference: PsiReference, referencedElement: PsiElement): ReferenceKind {
val target = referencedElement.unwrapped
val element = reference.element as? KtSimpleNameExpression ?: return ReferenceKind.QUALIFIABLE
if (element.getStrictParentOfType<KtSuperExpression>() != null) return ReferenceKind.IRRELEVANT
if (element.isExtensionRef() &&
reference.element.getNonStrictParentOfType<KtImportDirective>() == null
) return ReferenceKind.UNQUALIFIABLE
element.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference }?.let {
val receiverExpression = it.receiverExpression
if (receiverExpression != null) {
val lhs = it.analyze(BodyResolveMode.PARTIAL)[BindingContext.DOUBLE_COLON_LHS, receiverExpression]
return if (lhs is DoubleColonLHS.Type) ReferenceKind.CALLABLE_REFERENCE else ReferenceKind.IRRELEVANT
}
if (target is KtDeclaration && target.parent is KtFile) return ReferenceKind.UNQUALIFIABLE
if (target is PsiMember && target.containingClass == null) return ReferenceKind.UNQUALIFIABLE
}
return ReferenceKind.QUALIFIABLE
}
private fun isCallableReference(reference: PsiReference): Boolean {
return reference is KtSimpleNameReference
&& reference.element.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference } != null
}
fun guessNewFileName(declarationsToMove: Collection<KtNamedDeclaration>): String? {
if (declarationsToMove.isEmpty()) return null
val representative = declarationsToMove.singleOrNull()
?: declarationsToMove.filterIsInstance<KtClassOrObject>().singleOrNull()
val newFileName = representative?.run {
if (containingKtFile.isScript()) "$name.kts" else "$name.${KotlinFileType.EXTENSION}"
} ?: declarationsToMove.first().containingFile.name
return newFileName.capitalizeAsciiOnly()
}
// returns true if successful
private fun updateJavaReference(reference: PsiReferenceExpression, oldElement: PsiElement, newElement: PsiElement): Boolean {
if (oldElement is PsiMember && newElement is PsiMember) {
// Remove import of old package facade, if any
val oldClassName = oldElement.containingClass?.qualifiedName
if (oldClassName != null) {
val importOfOldClass = (reference.containingFile as? PsiJavaFile)?.importList?.allImportStatements?.firstOrNull {
when (it) {
is PsiImportStatement -> it.qualifiedName == oldClassName
is PsiImportStaticStatement -> it.isOnDemand && it.importReference?.canonicalText == oldClassName
else -> false
}
}
if (importOfOldClass != null && importOfOldClass.resolve() == null) {
importOfOldClass.delete()
}
}
val newClass = newElement.containingClass
if (newClass != null && reference.qualifierExpression != null) {
val refactoringOptions = object : MoveMembersOptions {
override fun getMemberVisibility(): String = PsiModifier.PUBLIC
override fun makeEnumConstant(): Boolean = true
override fun getSelectedMembers(): Array<PsiMember> = arrayOf(newElement)
override fun getTargetClassName(): String? = newClass.qualifiedName
}
val moveMembersUsageInfo = MoveMembersProcessor.MoveMembersUsageInfo(
newElement, reference.element, newClass, reference.qualifierExpression, reference
)
val moveMemberHandler = MoveMemberHandler.EP_NAME.forLanguage(reference.element.language)
if (moveMemberHandler != null) {
moveMemberHandler.changeExternalUsage(refactoringOptions, moveMembersUsageInfo)
return true
}
}
}
return false
}
internal fun mapToNewOrThis(e: PsiElement, oldToNewElementsMapping: Map<PsiElement, PsiElement>) = oldToNewElementsMapping[e] ?: e
private fun postProcessMoveUsage(
usage: UsageInfo,
oldToNewElementsMapping: Map<PsiElement, PsiElement>,
nonCodeUsages: ArrayList<NonCodeUsageInfo>,
shorteningMode: ShorteningMode
) {
if (usage is NonCodeUsageInfo) {
nonCodeUsages.add(usage)
return
}
if (usage !is MoveRenameUsageInfo) return
val oldElement = usage.referencedElement!!
val newElement = mapToNewOrThis(oldElement, oldToNewElementsMapping)
when (usage) {
is DeferredKotlinMoveUsage -> {
val newUsage = usage.resolve(newElement) ?: return
postProcessMoveUsage(newUsage, oldToNewElementsMapping, nonCodeUsages, shorteningMode)
}
is UnqualifiableMoveRenameUsageInfo -> {
val file = with(usage) {
if (addImportToOriginalFile) originalFile else mapToNewOrThis(
originalFile,
oldToNewElementsMapping
)
} as KtFile
addDelayedImportRequest(newElement, file)
}
else -> {
val reference = (usage.element as? KtSimpleNameExpression)?.mainReference ?: usage.reference
processReference(reference, newElement, shorteningMode, oldElement)
}
}
}
private fun processReference(reference: PsiReference?, newElement: PsiElement, shorteningMode: ShorteningMode, oldElement: PsiElement) {
try {
when {
reference is KtSimpleNameReference -> reference.bindToElement(newElement, shorteningMode)
reference is PsiReferenceExpression && updateJavaReference(reference, oldElement, newElement) -> return
else -> reference?.bindToElement(newElement)
}
} catch (e: IncorrectOperationException) {
// Suppress exception if bindToElement is not implemented
}
}
/**
* Perform usage postprocessing and return non-code usages
*/
fun postProcessMoveUsages(
usages: Collection<UsageInfo>,
oldToNewElementsMapping: Map<PsiElement, PsiElement> = Collections.emptyMap(),
shorteningMode: ShorteningMode = ShorteningMode.DELAYED_SHORTENING
): List<NonCodeUsageInfo> {
val sortedUsages = usages.sortedWith(
Comparator { o1, o2 ->
val file1 = o1.virtualFile
val file2 = o2.virtualFile
if (Comparing.equal(file1, file2)) {
val rangeInElement1 = o1.rangeInElement
val rangeInElement2 = o2.rangeInElement
if (rangeInElement1 != null && rangeInElement2 != null) {
return@Comparator rangeInElement2.startOffset - rangeInElement1.startOffset
}
return@Comparator 0
}
if (file1 == null) return@Comparator -1
if (file2 == null) return@Comparator 1
Comparing.compare(file1.path, file2.path)
}
)
val nonCodeUsages = ArrayList<NonCodeUsageInfo>()
val progressStep = 1.0 / sortedUsages.size
val progressIndicator = ProgressManager.getInstance().progressIndicator
progressIndicator?.isIndeterminate = false
progressIndicator?.text = KotlinBundle.message("text.updating.usages.progress")
usageLoop@ for ((i, usage) in sortedUsages.withIndex()) {
progressIndicator?.fraction = (i + 1) * progressStep
postProcessMoveUsage(usage, oldToNewElementsMapping, nonCodeUsages, shorteningMode)
}
progressIndicator?.text = ""
return nonCodeUsages
}
var KtFile.updatePackageDirective: Boolean? by UserDataProperty(Key.create("UPDATE_PACKAGE_DIRECTIVE"))
sealed class OuterInstanceReferenceUsageInfo(element: PsiElement, private val isIndirectOuter: Boolean) : UsageInfo(element) {
open fun reportConflictIfAny(conflicts: MultiMap<PsiElement, String>): Boolean {
val element = element ?: return false
if (isIndirectOuter) {
conflicts.putValue(element, KotlinBundle.message("text.indirect.outer.instances.will.not.be.extracted.0", element.text))
return true
}
return false
}
class ExplicitThis(
expression: KtThisExpression,
isIndirectOuter: Boolean
) : OuterInstanceReferenceUsageInfo(expression, isIndirectOuter) {
val expression: KtThisExpression?
get() = element as? KtThisExpression
}
class ImplicitReceiver(
callElement: KtElement,
isIndirectOuter: Boolean,
private val isDoubleReceiver: Boolean
) : OuterInstanceReferenceUsageInfo(callElement, isIndirectOuter) {
val callElement: KtElement?
get() = element as? KtElement
override fun reportConflictIfAny(conflicts: MultiMap<PsiElement, String>): Boolean {
if (super.reportConflictIfAny(conflicts)) return true
val fullCall = callElement?.let { it.getQualifiedExpressionForSelector() ?: it } ?: return false
return when {
fullCall is KtQualifiedExpression -> {
conflicts.putValue(fullCall, KotlinBundle.message("text.qualified.call.will.not.be.processed.0", fullCall.text))
true
}
isDoubleReceiver -> {
conflicts.putValue(fullCall, KotlinBundle.message("text.member.extension.call.will.not.be.processed.0", fullCall.text))
true
}
else -> false
}
}
}
}
@JvmOverloads
fun traverseOuterInstanceReferences(
member: KtNamedDeclaration,
stopAtFirst: Boolean,
body: (OuterInstanceReferenceUsageInfo) -> Unit = {}
): Boolean {
if (member is KtObjectDeclaration || member is KtClass && !member.isInner()) return false
val context = member.analyzeWithContent()
val containingClassOrObject = member.containingClassOrObject ?: return false
val outerClassDescriptor = containingClassOrObject.unsafeResolveToDescriptor() as ClassDescriptor
var found = false
member.accept(
object : PsiRecursiveElementWalkingVisitor() {
private fun getOuterInstanceReference(element: PsiElement): OuterInstanceReferenceUsageInfo? {
return when (element) {
is KtThisExpression -> {
val descriptor = context[BindingContext.REFERENCE_TARGET, element.instanceReference]
val isIndirect = when {
descriptor == outerClassDescriptor -> false
descriptor?.isAncestorOf(outerClassDescriptor, true) ?: false -> true
else -> return null
}
OuterInstanceReferenceUsageInfo.ExplicitThis(element, isIndirect)
}
is KtSimpleNameExpression -> {
val resolvedCall = element.getResolvedCall(context) ?: return null
val dispatchReceiver = resolvedCall.dispatchReceiver as? ImplicitReceiver
val extensionReceiver = resolvedCall.extensionReceiver as? ImplicitReceiver
var isIndirect = false
val isDoubleReceiver = when (outerClassDescriptor) {
dispatchReceiver?.declarationDescriptor -> extensionReceiver != null
extensionReceiver?.declarationDescriptor -> dispatchReceiver != null
else -> {
isIndirect = true
when {
dispatchReceiver?.declarationDescriptor?.isAncestorOf(outerClassDescriptor, true) ?: false ->
extensionReceiver != null
extensionReceiver?.declarationDescriptor?.isAncestorOf(outerClassDescriptor, true) ?: false ->
dispatchReceiver != null
else -> return null
}
}
}
OuterInstanceReferenceUsageInfo.ImplicitReceiver(resolvedCall.call.callElement, isIndirect, isDoubleReceiver)
}
else -> null
}
}
override fun visitElement(element: PsiElement) {
getOuterInstanceReference(element)?.let {
body(it)
found = true
if (stopAtFirst) stopWalking()
return
}
super.visitElement(element)
}
}
)
return found
}
fun collectOuterInstanceReferences(member: KtNamedDeclaration): List<OuterInstanceReferenceUsageInfo> {
val result = SmartList<OuterInstanceReferenceUsageInfo>()
traverseOuterInstanceReferences(member, false) { result += it }
return result
}
@Throws(IncorrectOperationException::class)
internal fun getOrCreateDirectory(path: String, project: Project): PsiDirectory {
File(path).toPsiDirectory(project)?.let { return it }
return project.executeCommand(RefactoringBundle.message("move.title"), null) {
runWriteAction {
val fixUpSeparators = path.replace(File.separatorChar, '/')
DirectoryUtil.mkdirs(PsiManager.getInstance(project), fixUpSeparators)
}
}
}
internal fun getTargetPackageFqName(targetContainer: PsiElement): FqName? {
if (targetContainer is PsiDirectory) {
val targetPackage = targetContainer.getPackage()
return if (targetPackage != null) FqName(targetPackage.qualifiedName) else null
}
return if (targetContainer is KtFile) targetContainer.packageFqName else null
}
internal fun logFusForMoveRefactoring(
numberOfEntities: Int,
entity: KotlinMoveRefactoringFUSCollector.MovedEntity,
destination: KotlinMoveRefactoringFUSCollector.MoveRefactoringDestination,
isDefault: Boolean,
body: Runnable
) {
val timeStarted = currentTimeMillis()
var succeeded = false
try {
body.run()
succeeded = true
} finally {
KotlinMoveRefactoringFUSCollector.log(
timeStarted = timeStarted,
timeFinished = currentTimeMillis(),
numberOfEntities = numberOfEntities,
destination = destination,
isDefault = isDefault,
entity = entity,
isSucceeded = succeeded,
)
}
}
internal fun <T> List<KtNamedDeclaration>.mapWithReadActionInProcess(
project: Project,
@NlsContexts.DialogTitle title: String,
body: (KtNamedDeclaration) -> T
): List<T> = let { declarations ->
val result = mutableListOf<T>()
val task: Task.Modal = object : Task.Modal(project, title, false) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = false
val fraction: Double = 1.0 / declarations.size
indicator.fraction = 0.0
runReadAction {
declarations.forEachIndexed { index, declaration ->
result.add(body(declaration))
indicator.fraction = fraction * index
}
}
}
}
ProgressManager.getInstance().run(task)
return result
}
| apache-2.0 | e89d09d1e4283a344d9a76c60b374462 | 41.097826 | 148 | 0.691809 | 5.599855 | false | false | false | false |
scenerygraphics/scenery | src/main/kotlin/graphics/scenery/proteins/Helix.kt | 1 | 4680 | package graphics.scenery.proteins
import graphics.scenery.geometry.Curve
import graphics.scenery.geometry.Spline
import graphics.scenery.Mesh
import org.joml.*
/**
* This class represents a Helix in 3D space. Currently, it needs a Spline which winds around an axis defined as a line
* in space. Each spline point is assigned a baseShape. Finally, all the shapes get connected with triangles.
* [axis] line around which the spline should wind
* [spline] spline
*
* @author Justin Buerger <[email protected]>
*/
class Helix (private val axis: MathLine, val spline: Spline, baseShape: () -> List<Vector3f>): Mesh("Helix") {
val splinePoints = spline.splinePoints()
private val shape = baseShape.invoke()
private val axisVector = axis.direction
private val axisPoint = axis.position
init {
val sectionVerticesCount = spline.verticesCountPerSection()
val transformedShapes = calculateTransformedShapes()
val subShapes = transformedShapes.windowed(sectionVerticesCount +1, sectionVerticesCount+1, true)
subShapes.forEachIndexed { index, list ->
//fill gaps
val arrayList = list as ArrayList
if(index != subShapes.size -1) {
arrayList.add(subShapes[index+1][0])
}
val i = when (index) {
0 -> {
0
}
subShapes.size - 1 -> {
2
}
else -> {
1
}
}
this.addChild(calcMesh(arrayList, i))
}
}
/**
* Transformation of the baseShapes along the spline, aligned with the helix axis.
*/
private fun calculateTransformedShapes(): ArrayList<List<Vector3f>> {
if(axisVector == Vector3f(0f, 0f, 0f)) {
throw Exception("The direction vector of the axis must no become the null vector.")
}
val transformedShapes = ArrayList<List<Vector3f>>(splinePoints.size)
splinePoints.forEach { point ->
/*
The coordinate systems which walk along the spline are calculated like so:
The x axis is the axis direction.
The y axis is the normalized vector from the spline point its neighbor on the axis with least distance
between them. The y axis vector is then perpendicular to the axis vector, therefore, perpendicular to
the x axis.*
The z axis is the normalized cross product between the x and the y axis.
*Calculate y
- axis line: l = a + tb (a is the positional vector and b the direction)
- spline point as: p
The point on the line with the least distance to the spline point is:
p' = a + t'b
with t' = (p-a)*b / |b|^2 (with * being the dot product)
Then y = (p-p') / |p-p'|
*/
val iVec = Vector3f()
val t = (point.sub(axisPoint, iVec)).dot(axisVector)/(axisVector.length()*axisVector.length())
val intermediateAxis = Vector3f()
intermediateAxis.set(axisVector)
val plumbLine = Vector3f()
axisPoint.add(intermediateAxis.mul(t), plumbLine)
val xAxisI = Vector3f()
xAxisI.set(axisVector).normalize()
val yAxisI = Vector3f()
point.sub(plumbLine, yAxisI).normalize()
val zAxisI = Vector3f()
xAxisI.cross(yAxisI, zAxisI).normalize()
//point transformation
val inversionMatrix = Matrix3f(xAxisI, yAxisI, zAxisI).invert()
val xAxis = Vector3f()
inversionMatrix.getColumn(0, xAxis).normalize()
val yAxis = Vector3f()
inversionMatrix.getColumn(1, yAxis).normalize()
val zAxis = Vector3f()
inversionMatrix.getColumn(2, zAxis).normalize()
val transformMatrix = Matrix4f(xAxis.x(), yAxis.x(), zAxis.x(), 0f,
xAxis.y(), yAxis.y(), zAxis.y(), 0f,
xAxis.z(), yAxis.z(), zAxis.z(), 0f,
point.x(), point.y(), point.z(), 1f)
transformedShapes.add(shape.map { shapePoint ->
val transformedPoint = Vector3f()
transformMatrix.transformPosition(shapePoint, transformedPoint)
})
}
return transformedShapes
}
private fun calcMesh(section: List<List<Vector3f>>, i: Int): Mesh {
//algorithms from the curve class, see Curve (line 219-322)
val helixSectionVertices = Curve.calculateTriangles(section, i)
return Curve.PartialCurve(helixSectionVertices)
}
}
| lgpl-3.0 | e18cf3d3ef4ce3e25d700cd4711f51dc | 41.545455 | 119 | 0.594231 | 4.341373 | false | false | false | false |
DmytroTroynikov/aemtools | lang/src/main/kotlin/com/aemtools/lang/htl/HtlParserDefinition.kt | 1 | 1681 | package com.aemtools.lang.htl
import com.aemtools.lang.htl.core.HtlFileElementType
import com.aemtools.lang.htl.lexer.HtlLexer
import com.aemtools.lang.htl.parser.HtlParser
import com.aemtools.lang.htl.psi.HtlPsiFile
import com.aemtools.lang.htl.psi.HtlTypes
import com.intellij.lang.ASTNode
import com.intellij.lang.ParserDefinition
import com.intellij.lang.PsiParser
import com.intellij.lexer.Lexer
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
/**
* @author Dmytro_Troynikov
*/
class HtlParserDefinition : ParserDefinition {
override fun createLexer(project: Project?): Lexer
= HtlLexer()
override fun createParser(project: Project?): PsiParser?
= HtlParser()
override fun createFile(viewProvider: FileViewProvider): PsiFile?
= HtlPsiFile(viewProvider)
override fun spaceExistanceTypeBetweenTokens(left: ASTNode?, right: ASTNode?): ParserDefinition.SpaceRequirements?
= ParserDefinition.SpaceRequirements.MUST
override fun getStringLiteralElements(): TokenSet
= TokenSet.create(
HtlTypes.SINGLE_QUOTED_STRING,
HtlTypes.DOUBLE_QUOTED_STRING
)
override fun getWhitespaceTokens(): TokenSet
= TokenSet.create(TokenType.WHITE_SPACE)
override fun getFileNodeType(): IFileElementType?
= HtlFileElementType
override fun createElement(node: ASTNode?): PsiElement
= HtlTypes.Factory.createElement(node)
override fun getCommentTokens(): TokenSet
= TokenSet.EMPTY
}
| gpl-3.0 | 72d3b474397e96487872948f45f391fa | 29.563636 | 116 | 0.782867 | 4.44709 | false | false | false | false |
Kotlin/kotlinx.coroutines | reactive/kotlinx-coroutines-reactive/src/Await.kt | 1 | 15637 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.reactive
import kotlinx.coroutines.*
import org.reactivestreams.Publisher
import org.reactivestreams.Subscriber
import org.reactivestreams.Subscription
import java.lang.IllegalStateException
import kotlin.coroutines.*
/**
* Awaits the first value from the given publisher without blocking the thread and returns the resulting value, or, if
* the publisher has produced an error, throws the corresponding exception.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this
* function immediately cancels its [Subscription] and resumes with [CancellationException].
*
* @throws NoSuchElementException if the publisher does not emit any value
*/
public suspend fun <T> Publisher<T>.awaitFirst(): T = awaitOne(Mode.FIRST)
/**
* Awaits the first value from the given publisher, or returns the [default] value if none is emitted, without blocking
* the thread, and returns the resulting value, or, if this publisher has produced an error, throws the corresponding
* exception.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this
* function immediately cancels its [Subscription] and resumes with [CancellationException].
*/
public suspend fun <T> Publisher<T>.awaitFirstOrDefault(default: T): T = awaitOne(Mode.FIRST_OR_DEFAULT, default)
/**
* Awaits the first value from the given publisher, or returns `null` if none is emitted, without blocking the thread,
* and returns the resulting value, or, if this publisher has produced an error, throws the corresponding exception.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this
* function immediately cancels its [Subscription] and resumes with [CancellationException].
*/
public suspend fun <T> Publisher<T>.awaitFirstOrNull(): T? = awaitOne(Mode.FIRST_OR_DEFAULT)
/**
* Awaits the first value from the given publisher, or calls [defaultValue] to get a value if none is emitted, without
* blocking the thread, and returns the resulting value, or, if this publisher has produced an error, throws the
* corresponding exception.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this
* function immediately cancels its [Subscription] and resumes with [CancellationException].
*/
public suspend fun <T> Publisher<T>.awaitFirstOrElse(defaultValue: () -> T): T = awaitOne(Mode.FIRST_OR_DEFAULT) ?: defaultValue()
/**
* Awaits the last value from the given publisher without blocking the thread and
* returns the resulting value, or, if this publisher has produced an error, throws the corresponding exception.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this
* function immediately cancels its [Subscription] and resumes with [CancellationException].
*
* @throws NoSuchElementException if the publisher does not emit any value
*/
public suspend fun <T> Publisher<T>.awaitLast(): T = awaitOne(Mode.LAST)
/**
* Awaits the single value from the given publisher without blocking the thread and returns the resulting value, or,
* if this publisher has produced an error, throws the corresponding exception.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this
* function immediately cancels its [Subscription] and resumes with [CancellationException].
*
* @throws NoSuchElementException if the publisher does not emit any value
* @throws IllegalArgumentException if the publisher emits more than one value
*/
public suspend fun <T> Publisher<T>.awaitSingle(): T = awaitOne(Mode.SINGLE)
/**
* Awaits the single value from the given publisher, or returns the [default] value if none is emitted, without
* blocking the thread, and returns the resulting value, or, if this publisher has produced an error, throws the
* corresponding exception.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this
* function immediately cancels its [Subscription] and resumes with [CancellationException].
*
* ### Deprecation
*
* This method is deprecated because the conventions established in Kotlin mandate that an operation with the name
* `awaitSingleOrDefault` returns the default value instead of throwing in case there is an error; however, this would
* also mean that this method would return the default value if there are *too many* values. This could be confusing to
* those who expect this function to validate that there is a single element or none at all emitted, and cases where
* there are no elements are indistinguishable from those where there are too many, though these cases have different
* meaning.
*
* @throws NoSuchElementException if the publisher does not emit any value
* @throws IllegalArgumentException if the publisher emits more than one value
*
* @suppress
*/
@Deprecated(
message = "Deprecated without a replacement due to its name incorrectly conveying the behavior. " +
"Please consider using awaitFirstOrDefault().",
level = DeprecationLevel.ERROR
) // Warning since 1.5, error in 1.6, hidden in 1.7
public suspend fun <T> Publisher<T>.awaitSingleOrDefault(default: T): T = awaitOne(Mode.SINGLE_OR_DEFAULT, default)
/**
* Awaits the single value from the given publisher without blocking the thread and returns the resulting value, or, if
* this publisher has produced an error, throws the corresponding exception. If more than one value or none were
* produced by the publisher, `null` is returned.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this
* function immediately cancels its [Subscription] and resumes with [CancellationException].
*
* ### Deprecation
*
* This method is deprecated because the conventions established in Kotlin mandate that an operation with the name
* `awaitSingleOrNull` returns `null` instead of throwing in case there is an error; however, this would
* also mean that this method would return `null` if there are *too many* values. This could be confusing to
* those who expect this function to validate that there is a single element or none at all emitted, and cases where
* there are no elements are indistinguishable from those where there are too many, though these cases have different
* meaning.
*
* @throws IllegalArgumentException if the publisher emits more than one value
* @suppress
*/
@Deprecated(
message = "Deprecated without a replacement due to its name incorrectly conveying the behavior. " +
"There is a specialized version for Reactor's Mono, please use that where applicable. " +
"Alternatively, please consider using awaitFirstOrNull().",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith("this.awaitSingleOrNull()", "kotlinx.coroutines.reactor")
) // Warning since 1.5, error in 1.6, hidden in 1.7
public suspend fun <T> Publisher<T>.awaitSingleOrNull(): T? = awaitOne(Mode.SINGLE_OR_DEFAULT)
/**
* Awaits the single value from the given publisher, or calls [defaultValue] to get a value if none is emitted, without
* blocking the thread, and returns the resulting value, or, if this publisher has produced an error, throws the
* corresponding exception.
*
* This suspending function is cancellable.
* If the [Job] of the current coroutine is cancelled or completed while the suspending function is waiting, this
* function immediately cancels its [Subscription] and resumes with [CancellationException].
*
* ### Deprecation
*
* This method is deprecated because the conventions established in Kotlin mandate that an operation with the name
* `awaitSingleOrElse` returns the calculated value instead of throwing in case there is an error; however, this would
* also mean that this method would return the calculated value if there are *too many* values. This could be confusing
* to those who expect this function to validate that there is a single element or none at all emitted, and cases where
* there are no elements are indistinguishable from those where there are too many, though these cases have different
* meaning.
*
* @throws IllegalArgumentException if the publisher emits more than one value
* @suppress
*/
@Deprecated(
message = "Deprecated without a replacement due to its name incorrectly conveying the behavior. " +
"Please consider using awaitFirstOrElse().",
level = DeprecationLevel.ERROR
) // Warning since 1.5, error in 1.6, hidden in 1.7
public suspend fun <T> Publisher<T>.awaitSingleOrElse(defaultValue: () -> T): T =
awaitOne(Mode.SINGLE_OR_DEFAULT) ?: defaultValue()
// ------------------------ private ------------------------
private enum class Mode(val s: String) {
FIRST("awaitFirst"),
FIRST_OR_DEFAULT("awaitFirstOrDefault"),
LAST("awaitLast"),
SINGLE("awaitSingle"),
SINGLE_OR_DEFAULT("awaitSingleOrDefault");
override fun toString(): String = s
}
private suspend fun <T> Publisher<T>.awaitOne(
mode: Mode,
default: T? = null
): T = suspendCancellableCoroutine { cont ->
/* This implementation must obey
https://github.com/reactive-streams/reactive-streams-jvm/blob/v1.0.3/README.md#2-subscriber-code
The numbers of rules are taken from there. */
injectCoroutineContext(cont.context).subscribe(object : Subscriber<T> {
// It is unclear whether 2.13 implies (T: Any), but if so, it seems that we don't break anything by not adhering
private var subscription: Subscription? = null
private var value: T? = null
private var seenValue = false
private var inTerminalState = false
override fun onSubscribe(sub: Subscription) {
/** cancelling the new subscription due to rule 2.5, though the publisher would either have to
* subscribe more than once, which would break 2.12, or leak this [Subscriber]. */
if (subscription != null) {
withSubscriptionLock {
sub.cancel()
}
return
}
subscription = sub
cont.invokeOnCancellation {
withSubscriptionLock {
sub.cancel()
}
}
withSubscriptionLock {
sub.request(if (mode == Mode.FIRST || mode == Mode.FIRST_OR_DEFAULT) 1 else Long.MAX_VALUE)
}
}
override fun onNext(t: T) {
val sub = subscription.let {
if (it == null) {
/** Enforce rule 1.9: expect [Subscriber.onSubscribe] before any other signals. */
handleCoroutineException(cont.context,
IllegalStateException("'onNext' was called before 'onSubscribe'"))
return
} else {
it
}
}
if (inTerminalState) {
gotSignalInTerminalStateException(cont.context, "onNext")
return
}
when (mode) {
Mode.FIRST, Mode.FIRST_OR_DEFAULT -> {
if (seenValue) {
moreThanOneValueProvidedException(cont.context, mode)
return
}
seenValue = true
withSubscriptionLock {
sub.cancel()
}
cont.resume(t)
}
Mode.LAST, Mode.SINGLE, Mode.SINGLE_OR_DEFAULT -> {
if ((mode == Mode.SINGLE || mode == Mode.SINGLE_OR_DEFAULT) && seenValue) {
withSubscriptionLock {
sub.cancel()
}
/* the check for `cont.isActive` is needed in case `sub.cancel() above calls `onComplete` or
`onError` on its own. */
if (cont.isActive) {
cont.resumeWithException(IllegalArgumentException("More than one onNext value for $mode"))
}
} else {
value = t
seenValue = true
}
}
}
}
@Suppress("UNCHECKED_CAST")
override fun onComplete() {
if (!tryEnterTerminalState("onComplete")) {
return
}
if (seenValue) {
/* the check for `cont.isActive` is needed because, otherwise, if the publisher doesn't acknowledge the
call to `cancel` for modes `SINGLE*` when more than one value was seen, it may call `onComplete`, and
here `cont.resume` would fail. */
if (mode != Mode.FIRST_OR_DEFAULT && mode != Mode.FIRST && cont.isActive) {
cont.resume(value as T)
}
return
}
when {
(mode == Mode.FIRST_OR_DEFAULT || mode == Mode.SINGLE_OR_DEFAULT) -> {
cont.resume(default as T)
}
cont.isActive -> {
// the check for `cont.isActive` is just a slight optimization and doesn't affect correctness
cont.resumeWithException(NoSuchElementException("No value received via onNext for $mode"))
}
}
}
override fun onError(e: Throwable) {
if (tryEnterTerminalState("onError")) {
cont.resumeWithException(e)
}
}
/**
* Enforce rule 2.4: assume that the [Publisher] is in a terminal state after [onError] or [onComplete].
*/
private fun tryEnterTerminalState(signalName: String): Boolean {
if (inTerminalState) {
gotSignalInTerminalStateException(cont.context, signalName)
return false
}
inTerminalState = true
return true
}
/**
* Enforce rule 2.7: [Subscription.request] and [Subscription.cancel] must be executed serially
*/
@Synchronized
private fun withSubscriptionLock(block: () -> Unit) {
block()
}
})
}
/**
* Enforce rule 2.4 (detect publishers that don't respect rule 1.7): don't process anything after a terminal
* state was reached.
*/
private fun gotSignalInTerminalStateException(context: CoroutineContext, signalName: String) =
handleCoroutineException(context,
IllegalStateException("'$signalName' was called after the publisher already signalled being in a terminal state"))
/**
* Enforce rule 1.1: it is invalid for a publisher to provide more values than requested.
*/
private fun moreThanOneValueProvidedException(context: CoroutineContext, mode: Mode) =
handleCoroutineException(context,
IllegalStateException("Only a single value was requested in '$mode', but the publisher provided more"))
| apache-2.0 | bf5e417488c5bb45c020db8cdbb5ad61 | 46.67378 | 130 | 0.671101 | 4.88351 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-tests/src/test/kotlin/test/apis/Api_Naming_Tests.kt | 1 | 2888 | package test.apis
import kotlinx.coroutines.runBlocking
import org.junit.Assert
import org.junit.Test
import slatekit.apis.routes.Api
import slatekit.apis.ApiServer
import slatekit.apis.Settings
import slatekit.apis.Verb
import slatekit.utils.naming.LowerHyphenNamer
import slatekit.utils.naming.LowerUnderscoreNamer
import slatekit.results.getOrElse
import test.setup.SampleExtendedApi
import test.setup.SamplePOKOApi
class Api_Naming_Tests : ApiTestsBase() {
@Test fun can_use_naming_convention_lowerHyphen() {
val apis = ApiServer(ctx, apis = listOf(Api(SamplePOKOApi::class,
"app", "SamplePOKO")), settings = Settings(naming = LowerHyphenNamer())
)
Assert.assertTrue( apis.get("app" , "sample-poko", "get-time" ).success)
Assert.assertTrue(!apis.get("app" , "SamplePOKO" , "getTime" ).success)
Assert.assertTrue( apis.get("app" , "sample-poko", "get-counter" ).success)
Assert.assertTrue( apis.get("app" , "sample-poko", "hello" ).success)
Assert.assertTrue( apis.get("app" , "sample-poko", "request" ).success)
Assert.assertTrue( apis.get("app" , "sample-poko", "response" ).success)
Assert.assertTrue(!apis.get("app" , "sample-poko", "get-email" ).success)
Assert.assertTrue(!apis.get("app" , "sample-poko", "get-ssn" ).success)
val result = runBlocking {
apis.executeAttempt("app", "sample-poko", "get-counter", Verb.Get, mapOf(), mapOf())
}
Assert.assertTrue(result.success)
Assert.assertTrue(result.getOrElse { 0 } == 1)
}
@Test fun can_use_naming_convention_lowerUnderscore() {
val apis = ApiServer(ctx, apis = listOf(Api(SampleExtendedApi::class,
"app", "SampleExtended", declaredOnly = false)),
settings = Settings(naming = LowerUnderscoreNamer())
)
Assert.assertTrue( apis.get("app" , "sample_extended", "get_seconds" ).success)
Assert.assertTrue( apis.get("app" , "sample_extended", "get_time" ).success)
Assert.assertTrue( apis.get("app" , "sample_extended", "get_counter" ).success)
Assert.assertTrue( apis.get("app" , "sample_extended", "hello" ).success)
Assert.assertTrue( apis.get("app" , "sample_extended", "request" ).success)
Assert.assertTrue( apis.get("app" , "sample_extended", "response" ).success)
Assert.assertTrue(!apis.get("app" , "sample_extended", "get_email" ).success)
Assert.assertTrue(!apis.get("app" , "sample_extended", "get_ssn" ).success)
val result = runBlocking {
apis.executeAttempt("app", "sample_extended", "get_seconds", Verb.Get, mapOf(), mapOf())
}
Assert.assertTrue(result.success)
Assert.assertTrue(result.getOrElse { 0 } in 0..59)
}
}
| apache-2.0 | 5614e4c42e455cfed137a92388572a1f | 46.344262 | 100 | 0.636427 | 3.574257 | false | true | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/AppearanceConfigurable.kt | 1 | 18020 | // 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.ide.ui
import com.intellij.application.options.editor.CheckboxDescriptor
import com.intellij.application.options.editor.checkBox
import com.intellij.ide.GeneralSettings
import com.intellij.ide.IdeBundle.message
import com.intellij.ide.actions.QuickChangeLookAndFeel
import com.intellij.ide.ui.search.OptionDescription
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager
import com.intellij.openapi.editor.colors.impl.EditorColorsManagerImpl
import com.intellij.openapi.help.HelpManager
import com.intellij.openapi.keymap.KeyMapBundle
import com.intellij.openapi.options.BoundSearchableConfigurable
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.ui.ContextHelpLabel
import com.intellij.ui.FontComboBox
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.UIBundle
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.Label
import com.intellij.ui.components.Link
import com.intellij.ui.layout.*
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.Font
import java.awt.RenderingHints
import java.awt.Window
import java.util.*
import javax.swing.*
// @formatter:off
private val settings get() = UISettings.instance
private val generalSettings get() = GeneralSettings.getInstance()
private val lafManager get() = LafManager.getInstance()
private val cdAnimateWindows get() = CheckboxDescriptor(message("checkbox.animate.windows"), settings::animateWindows, groupName = windowOptionGroupName)
private val cdShowToolWindowBars get() = CheckboxDescriptor(message("checkbox.show.tool.window.bars"), PropertyBinding({ !settings.hideToolStripes }, { settings.hideToolStripes = !it }), groupName = windowOptionGroupName)
private val cdShowToolWindowNumbers get() = CheckboxDescriptor(message("checkbox.show.tool.window.numbers"), settings::showToolWindowsNumbers, groupName = windowOptionGroupName)
private val cdShowMemoryIndicator get() = CheckboxDescriptor(message("checkbox.show.memory.indicator"), settings::showMemoryIndicator, groupName = windowOptionGroupName)
private val cdDisableMenuMnemonics get() = CheckboxDescriptor(KeyMapBundle.message("disable.mnemonic.in.menu.check.box"), settings::disableMnemonics, groupName = windowOptionGroupName)
private val cdDisableControlsMnemonics get() = CheckboxDescriptor(KeyMapBundle.message("disable.mnemonic.in.controls.check.box"), settings::disableMnemonicsInControls, groupName = windowOptionGroupName)
private val cdAllowMergingButtons get() = CheckboxDescriptor(message("allow.merging.dialog.buttons"), settings::allowMergeButtons, groupName = windowOptionGroupName)
private val cdSmoothScrolling get() = CheckboxDescriptor(message("checkbox.smooth.scrolling"), settings::smoothScrolling, groupName = uiOptionGroupName)
private val cdShowMenuIcons get() = CheckboxDescriptor(message("checkbox.show.icons.in.menu.items"), settings::showIconsInMenus, groupName = windowOptionGroupName)
private val cdWidescreenToolWindowLayout get() = CheckboxDescriptor(message("checkbox.widescreen.tool.window.layout"), settings::wideScreenSupport, groupName = windowOptionGroupName)
private val cdLeftToolWindowLayout get() = CheckboxDescriptor(message("checkbox.left.toolwindow.layout"), settings::leftHorizontalSplit, groupName = windowOptionGroupName)
private val cdRightToolWindowLayout get() = CheckboxDescriptor(message("checkbox.right.toolwindow.layout"), settings::rightHorizontalSplit, groupName = windowOptionGroupName)
private val cdCyclicListScrolling get() = CheckboxDescriptor(message("checkboox.cyclic.scrolling.in.lists"), settings::cycleScrolling, groupName = uiOptionGroupName)
private val cdShowQuickNavigationIcons get() = CheckboxDescriptor(message("checkbox.show.icons.in.quick.navigation"), settings::showIconInQuickNavigation, groupName = uiOptionGroupName)
private val cdUseCompactTreeIndents get() = CheckboxDescriptor(message("checkbox.compact.tree.indents"), settings::compactTreeIndents, groupName = uiOptionGroupName)
private val cdShowTreeIndents get() = CheckboxDescriptor(message("checkbox.show.tree.indent.guides"), settings::showTreeIndentGuides, groupName = uiOptionGroupName)
private val cdMoveCursorOnButton get() = CheckboxDescriptor(message("checkbox.position.cursor.on.default.button"), settings::moveMouseOnDefaultButton, groupName = uiOptionGroupName)
private val cdHideNavigationPopups get() = CheckboxDescriptor(message("hide.navigation.popups.on.focus.loss"), settings::hideNavigationOnFocusLoss, groupName = uiOptionGroupName)
private val cdDnDWithAlt get() = CheckboxDescriptor(message("dnd.with.alt.pressed.only"), settings::dndWithPressedAltOnly, groupName = uiOptionGroupName)
private val cdUseTransparentMode get() = CheckboxDescriptor(message("checkbox.use.transparent.mode.for.floating.windows"), PropertyBinding({ settings.state.enableAlphaMode }, { settings.state.enableAlphaMode = it }))
private val cdOverrideLaFFont get() = CheckboxDescriptor(message("checkbox.override.default.laf.fonts"), settings::overrideLafFonts)
private val cdUseContrastToolbars get() = CheckboxDescriptor(message("checkbox.acessibility.contrast.scrollbars"), settings::useContrastScrollbars)
// @formatter:on
internal val appearanceOptionDescriptors: List<OptionDescription> = listOf(
cdAnimateWindows,
cdShowToolWindowBars,
cdShowToolWindowNumbers,
cdShowMemoryIndicator,
cdDisableMenuMnemonics,
cdDisableControlsMnemonics,
cdAllowMergingButtons,
cdSmoothScrolling,
cdShowMenuIcons,
cdWidescreenToolWindowLayout,
cdLeftToolWindowLayout,
cdRightToolWindowLayout,
cdCyclicListScrolling,
cdShowQuickNavigationIcons,
cdUseCompactTreeIndents,
cdShowTreeIndents,
cdMoveCursorOnButton,
cdHideNavigationPopups,
cdDnDWithAlt
).map(CheckboxDescriptor::asOptionDescriptor)
class AppearanceConfigurable : BoundSearchableConfigurable(message("title.appearance"), "preferences.lookFeel") {
private var shouldUpdateLaF = false
override fun createPanel(): DialogPanel {
return panel {
blockRow {
fullRow {
label(message("combobox.look.and.feel"))
comboBox(lafManager.lafComboBoxModel,
{ lafManager.currentLookAndFeelReference },
{ QuickChangeLookAndFeel.switchLafAndUpdateUI(lafManager, lafManager.findLaf(it), true) })
.shouldUpdateLaF()
}.largeGapAfter()
fullRow {
val overrideLaF = checkBox(cdOverrideLaFFont)
.shouldUpdateLaF()
component(FontComboBox())
.withBinding(
{ it.fontName },
{ it, value -> it.fontName = value },
PropertyBinding({ if (settings.overrideLafFonts) settings.fontFace else JBFont.label().family },
{ settings.fontFace = it })
)
.shouldUpdateLaF()
.enableIf(overrideLaF.selected)
component(Label(message("label.font.size")))
.withLargeLeftGap()
.enableIf(overrideLaF.selected)
fontSizeComboBox({ if (settings.overrideLafFonts) settings.fontSize else JBFont.label().size },
{ settings.fontSize = it },
settings.fontSize)
.shouldUpdateLaF()
.enableIf(overrideLaF.selected)
}
}
titledRow(message("title.accessibility")) {
fullRow {
val isOverridden = GeneralSettings.isSupportScreenReadersOverridden()
checkBox(message("checkbox.support.screen.readers"),
generalSettings::isSupportScreenReaders, generalSettings::setSupportScreenReaders,
comment = if (isOverridden) message("option.is.overridden.by.jvm.property", GeneralSettings.SUPPORT_SCREEN_READERS)
else null)
.enabled(!isOverridden)
}
fullRow { checkBox(cdUseContrastToolbars) }
val supportedValues = ColorBlindness.values().filter { ColorBlindnessSupport.get(it) != null }
if (supportedValues.isNotEmpty()) {
val modelBinding = PropertyBinding({ settings.colorBlindness }, { settings.colorBlindness = it })
val onApply = {
DefaultColorSchemesManager.getInstance().reload()
(EditorColorsManager.getInstance() as EditorColorsManagerImpl).schemeChangedOrSwitched(null)
}
fullRow {
if (supportedValues.size == 1) {
component(JBCheckBox(UIBundle.message("color.blindness.checkbox.text")))
.withBinding({ if (it.isSelected) supportedValues.first() else null },
{ it, value -> it.isSelected = value != null },
modelBinding)
.onApply(onApply)
}
else {
val enableColorBlindness = component(JBCheckBox(UIBundle.message("color.blindness.combobox.text")))
.applyToComponent { isSelected = modelBinding.get() != null }
component(ComboBox(supportedValues.toTypedArray()))
.enableIf(enableColorBlindness.selected)
.applyToComponent { renderer = SimpleListCellRenderer.create<ColorBlindness>("") { UIBundle.message(it.key) } }
.withBinding({ if (enableColorBlindness.component.isSelected) it.selectedItem as? ColorBlindness else null },
{ it, value -> it.selectedItem = value ?: supportedValues.first() },
modelBinding)
.onApply(onApply)
}
component(Link(UIBundle.message("color.blindness.link.to.help"))
{ HelpManager.getInstance().invokeHelp("Colorblind_Settings") })
.withLargeLeftGap()
}
}
}
titledRow(message("group.ui.options")) {
fullRow { checkBox(cdCyclicListScrolling) }
fullRow { checkBox(cdShowQuickNavigationIcons) }
fullRow { checkBox(cdUseCompactTreeIndents) }
fullRow { checkBox(cdShowTreeIndents) }
fullRow { checkBox(cdMoveCursorOnButton) }
fullRow { checkBox(cdHideNavigationPopups) }
fullRow { checkBox(cdDnDWithAlt) }
val backgroundImageAction = ActionManager.getInstance().getAction("Images.SetBackgroundImage")
if (backgroundImageAction != null) {
fullRow {
buttonFromAction(message("background.image.button"), ActionPlaces.UNKNOWN, backgroundImageAction)
.applyToComponent { isEnabled = ProjectManager.getInstance().openProjects.isNotEmpty() }
}
}
}
if (Registry.`is`("ide.transparency.mode.for.windows") &&
WindowManagerEx.getInstanceEx().isAlphaModeSupported) {
val settingsState = settings.state
titledRow(message("group.transparency")) {
lateinit var checkbox: CellBuilder<JBCheckBox>
fullRow { checkbox = checkBox(cdUseTransparentMode) }
fullRow {
label(message("label.transparency.delay.ms"))
intTextField(settingsState::alphaModeDelay, columns = 4)
}.enableIf(checkbox.selected)
fullRow {
label(message("label.transparency.ratio"))
slider(0, 100, 10, 50)
.labelTable {
put(0, JLabel("0%"))
put(50, JLabel("50%"))
put(100, JLabel("100%"))
}
.withBinding({ it.value },
{ it, value -> it.value = value },
PropertyBinding({ (settingsState.alphaModeRatio * 100f).toInt() },
{ settingsState.alphaModeRatio = it / 100f })
)
.applyToComponent {
addChangeListener { toolTipText = "${value}%" }
}
}.enableIf(checkbox.selected)
}
}
titledRow(message("group.antialiasing.mode")) {
twoColumnRow(
{
label(message("label.text.antialiasing.scope.ide"))
comboBox(DefaultComboBoxModel(AntialiasingType.values()), settings::ideAAType, renderer = AAListCellRenderer(false))
.shouldUpdateLaF()
.onApply {
for (w in Window.getWindows()) {
for (c in UIUtil.uiTraverser(w).filter(JComponent::class.java)) {
GraphicsUtil.setAntialiasingType(c, AntialiasingType.getAAHintForSwingComponent())
}
}
}
},
{
label(message("label.text.antialiasing.scope.editor"))
comboBox(DefaultComboBoxModel(AntialiasingType.values()), settings::editorAAType, renderer = AAListCellRenderer(true))
.shouldUpdateLaF()
}
)
}
titledRow(message("group.window.options")) {
twoColumnRow(
{ checkBox(cdAnimateWindows) },
{ checkBox(cdShowToolWindowBars) }
)
twoColumnRow(
{ checkBox(cdShowMemoryIndicator) },
{ checkBox(cdShowToolWindowNumbers) }
)
twoColumnRow(
{ checkBox(cdDisableMenuMnemonics) },
{ checkBox(cdAllowMergingButtons) }
)
twoColumnRow(
{ checkBox(cdDisableControlsMnemonics) },
{
checkBox(cdSmoothScrolling)
ContextHelpLabel.create(message("checkbox.smooth.scrolling.description"))()
}
)
twoColumnRow(
{ checkBox(cdShowMenuIcons) },
{ checkBox(cdWidescreenToolWindowLayout) }
)
twoColumnRow(
{ checkBox(cdLeftToolWindowLayout) },
{ checkBox(cdRightToolWindowLayout) }
)
}
titledRow(message("group.presentation.mode")) {
fullRow {
label(message("presentation.mode.fon.size"))
fontSizeComboBox({ settings.presentationModeFontSize },
{ settings.presentationModeFontSize = it },
settings.presentationModeFontSize)
.shouldUpdateLaF()
}
}
}
}
override fun apply() {
val uiSettingsChanged = isModified
shouldUpdateLaF = false
super.apply()
if (shouldUpdateLaF) {
LafManager.getInstance().updateUI()
}
if (uiSettingsChanged) {
UISettings.instance.fireUISettingsChanged()
EditorFactory.getInstance().refreshAllEditors()
}
}
private fun <T : JComponent> CellBuilder<T>.shouldUpdateLaF(): CellBuilder<T> = onApply { shouldUpdateLaF = true }
}
private fun Cell.fontSizeComboBox(getter: () -> Int, setter: (Int) -> Unit, defaultValue: Int): CellBuilder<ComboBox<String>> {
val model = DefaultComboBoxModel(UIUtil.getStandardFontSizes())
return comboBox(model, { getter().toString() }, { setter(getIntValue(it, defaultValue)) })
.applyToComponent { isEditable = true }
}
private fun Cell.slider(min: Int, max: Int, minorTick: Int, majorTick: Int): CellBuilder<JSlider> {
val slider = JSlider()
UIUtil.setSliderIsFilled(slider, true)
slider.paintLabels = true
slider.paintTicks = true
slider.paintTrack = true
slider.minimum = min
slider.maximum = max
slider.minorTickSpacing = minorTick
slider.majorTickSpacing = majorTick
return slider()
}
private fun CellBuilder<JSlider>.labelTable(table: Hashtable<Int, JComponent>.() -> Unit): CellBuilder<JSlider> {
component.labelTable = Hashtable<Int, JComponent>().apply(table)
return this
}
private fun RowBuilder.fullRow(init: InnerCell.() -> Unit): Row = row { cell(isFullWidth = true, init = init) }
private fun RowBuilder.twoColumnRow(column1: InnerCell.() -> Unit, column2: InnerCell.() -> Unit): Row = row {
cell {
column1()
}
placeholder().withLeftGap(JBUI.scale(60))
cell {
column2()
}
placeholder().constraints(growX, pushX)
}
private fun getIntValue(text: String?, defaultValue: Int): Int {
if (text != null && text.isNotBlank()) {
val value = text.toIntOrNull()
if (value != null && value > 0) return value
}
return defaultValue
}
private class AAListCellRenderer(private val myUseEditorFont: Boolean) : SimpleListCellRenderer<AntialiasingType>() {
private val SUBPIXEL_HINT = GraphicsUtil.createAATextInfo(RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB)
private val GREYSCALE_HINT = GraphicsUtil.createAATextInfo(RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
override fun customize(list: JList<out AntialiasingType>, value: AntialiasingType, index: Int, selected: Boolean, hasFocus: Boolean) {
val aaType = when (value) {
AntialiasingType.SUBPIXEL -> SUBPIXEL_HINT
AntialiasingType.GREYSCALE -> GREYSCALE_HINT
AntialiasingType.OFF -> null
}
GraphicsUtil.setAntialiasingType(this, aaType)
if (myUseEditorFont) {
val scheme = EditorColorsManager.getInstance().globalScheme
font = Font(scheme.editorFontName, Font.PLAIN, scheme.editorFontSize)
}
text = value.toString()
}
}
| apache-2.0 | d5cf9f79699930adcb706d43912bbe21 | 48.779006 | 242 | 0.67808 | 4.886117 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/vararg/kt796_797.kt | 5 | 264 | operator fun <T> Array<T>?.get(i : Int?) = this!!.get(i!!)
fun <T> array(vararg t : T) : Array<T> = t as Array<T>
fun box() : String {
val a : Array<String>? = array<String>("Str", "Str2")
val i : Int? = 1
return if(a[i] == "Str2") "OK" else "fail"
}
| apache-2.0 | 423647931bd516c9306e131e7d944346 | 32 | 58 | 0.537879 | 2.538462 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/builtinStubMethods/ListIterator.kt | 2 | 736 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
class MyListIterator<T> : ListIterator<T> {
override fun next(): T = null!!
override fun hasNext(): Boolean = null!!
override fun hasPrevious(): Boolean = null!!
override fun previous(): T = null!!
override fun nextIndex(): Int = null!!
override fun previousIndex(): Int = null!!
}
fun expectUoe(block: () -> Any) {
try {
block()
throw AssertionError()
} catch (e: UnsupportedOperationException) {
}
}
fun box(): String {
val list = MyListIterator<String>() as java.util.ListIterator<String>
expectUoe { list.set("") }
expectUoe { list.add("") }
return "OK"
}
| apache-2.0 | 2c3375f951772975e7f8273f2cec3e7d | 25.285714 | 73 | 0.629076 | 4 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ConvertIllegalEscapeToUnicodeEscapeFix.kt | 4 | 1970 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.psi.*
class ConvertIllegalEscapeToUnicodeEscapeFix(
element: KtElement,
private val unicodeEscape: String
) : KotlinQuickFixAction<KtElement>(element) {
override fun getText(): String = KotlinBundle.message("convert.to.unicode.escape")
override fun getFamilyName(): String = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = this.element ?: return
val psiFactory = KtPsiFactory(element)
when (element) {
is KtConstantExpression -> element.replace(psiFactory.createExpression("'$unicodeEscape'"))
is KtEscapeStringTemplateEntry -> element.replace(psiFactory.createStringTemplate(unicodeEscape).entries.first())
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val element = diagnostic.psiElement as? KtElement ?: return null
val illegalEscape = when (element) {
is KtConstantExpression -> element.text.takeIf { it.length >= 2 }?.drop(1)?.dropLast(1)
is KtEscapeStringTemplateEntry -> element.text
else -> null
} ?: return null
val unicodeEscape = illegalEscapeToUnicodeEscape[illegalEscape] ?: return null
return ConvertIllegalEscapeToUnicodeEscapeFix(element, unicodeEscape)
}
private val illegalEscapeToUnicodeEscape = mapOf("\\f" to "\\u000c")
}
}
| apache-2.0 | c20a6ab2f1b16d8e82d8512e3912a09c | 45.904762 | 158 | 0.71269 | 4.987342 | false | false | false | false |
smmribeiro/intellij-community | platform/rd-platform-community/src/com/intellij/openapi/rd/SwingReactiveEx.kt | 12 | 1514 | // 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.openapi.rd
import com.intellij.openapi.wm.IdeGlassPane
import com.jetbrains.rd.swing.awtMousePoint
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.reactive.IPropertyView
import com.jetbrains.rd.util.reactive.ISource
import com.jetbrains.rd.util.reactive.map
import java.awt.Component
import java.awt.Container
import java.awt.event.MouseEvent
import java.awt.event.MouseMotionAdapter
import javax.swing.JComponent
import javax.swing.SwingUtilities
fun IdeGlassPane.mouseMoved(): ISource<MouseEvent> {
return object : ISource<MouseEvent> {
override fun advise(lifetime: Lifetime, handler: (MouseEvent) -> Unit) {
val listener = object : MouseMotionAdapter() {
override fun mouseMoved(e: MouseEvent?) {
if (e != null) {
handler(e)
}
}
}
[email protected](listener, lifetime.createNestedDisposable())
}
}
}
fun IdeGlassPane.childAtMouse(container: Container): ISource<Component?> = [email protected]()
.map { SwingUtilities.convertPoint(it.component, it.x, it.y, container) }
.map { container.getComponentAt(it) }
fun JComponent.childAtMouse(): IPropertyView<Component?> = [email protected]()
.map {
if (it == null) null
else {
[email protected](it)
}
} | apache-2.0 | 83c1815d282a4c5ab8fe7c844e91a90e | 34.232558 | 140 | 0.73712 | 3.912145 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/reflect/KotlinLanguageSettingsReflection.kt | 4 | 2646 | // 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.
@file:Suppress("RemoveExplicitTypeArguments")
package org.jetbrains.kotlin.idea.gradleTooling.reflect
import java.io.File
import kotlin.reflect.full.memberProperties
fun KotlinLanguageSettingsReflection(languageSettings: Any): KotlinLanguageSettingsReflection =
KotlinLanguageSettingsReflectionImpl(languageSettings)
interface KotlinLanguageSettingsReflection {
val languageVersion: String?
val apiVersion: String?
val progressiveMode: Boolean?
val enabledLanguageFeatures: Set<String>?
val optInAnnotationsInUse: Set<String>?
val compilerPluginArguments: List<String>?
val compilerPluginClasspath: Set<File>?
val freeCompilerArgs: List<String>?
}
private class KotlinLanguageSettingsReflectionImpl(private val instance: Any) : KotlinLanguageSettingsReflection {
override val languageVersion: String? by lazy {
instance.callReflective("getLanguageVersion", parameters(), returnType<String?>(), logger)
}
override val apiVersion: String? by lazy {
instance.callReflective("getApiVersion", parameters(), returnType<String?>(), logger)
}
override val progressiveMode: Boolean? by lazy {
instance.callReflectiveGetter("getProgressiveMode", logger)
}
override val enabledLanguageFeatures: Set<String>? by lazy {
instance.callReflective("getEnabledLanguageFeatures", parameters(), returnType<Iterable<String>>(), logger)?.toSet()
}
override val optInAnnotationsInUse: Set<String>? by lazy {
val getterName = if (instance::class.memberProperties.any { it.name == "optInAnnotationsInUse" }) "getOptInAnnotationsInUse"
else "getExperimentalAnnotationsInUse"
instance.callReflective(getterName, parameters(), returnType<Iterable<String>>(), logger)?.toSet()
}
override val compilerPluginArguments: List<String>? by lazy {
instance.callReflective("getCompilerPluginArguments", parameters(), returnType<Iterable<String>?>(), logger)?.toList()
}
override val compilerPluginClasspath: Set<File>? by lazy {
instance.callReflective("getCompilerPluginClasspath", parameters(), returnType<Iterable<File>?>(), logger)?.toSet()
}
override val freeCompilerArgs: List<String>? by lazy {
instance.callReflective("getFreeCompilerArgs", parameters(), returnType<Iterable<String>>(), logger)?.toList()
}
companion object {
val logger = ReflectionLogger(KotlinLanguageSettingsReflection::class.java)
}
}
| apache-2.0 | 30289c42b1fc4fdec5810eee979e9c9b | 41.677419 | 158 | 0.745654 | 5.098266 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/buildSystem/gradle/GradlePlugin.kt | 1 | 9196 | // 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.tools.projectWizard.plugins.buildSystem.gradle
import kotlinx.collections.immutable.toPersistentList
import org.jetbrains.kotlin.tools.projectWizard.Versions
import org.jetbrains.kotlin.tools.projectWizard.core.*
import org.jetbrains.kotlin.tools.projectWizard.core.entity.PipelineTask
import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.Property
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting
import org.jetbrains.kotlin.tools.projectWizard.core.service.FileSystemWizardService
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.*
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.SettingsGradleFileIR
import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase
import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.*
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.GradlePrinter
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.printBuildFile
import org.jetbrains.kotlin.tools.projectWizard.plugins.projectPath
import org.jetbrains.kotlin.tools.projectWizard.plugins.templates.TemplatesPlugin
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.updateBuildFiles
import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version
import org.jetbrains.kotlin.tools.projectWizard.templates.FileTemplate
import org.jetbrains.kotlin.tools.projectWizard.templates.FileTemplateDescriptor
abstract class GradlePlugin(context: Context) : BuildSystemPlugin(context) {
override val path = pluginPath
companion object : PluginSettingsOwner() {
override val pluginPath = "buildSystem.gradle"
val gradleProperties by listProperty(
"kotlin.code.style" to "official"
)
val settingsGradleFileIRs by listProperty<BuildSystemIR>()
val createGradlePropertiesFile by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runAfter(KotlinPlugin.createModules)
runBefore(TemplatesPlugin.renderFileTemplates)
isAvailable = isGradle
withAction {
TemplatesPlugin.addFileTemplate.execute(
FileTemplate(
FileTemplateDescriptor(
"gradle/gradle.properties.vm",
"gradle.properties".asPath()
),
StructurePlugin.projectPath.settingValue,
mapOf(
"properties" to gradleProperties
.propertyValue
.distinctBy { it.first }
)
)
)
}
}
val localProperties by listProperty<Pair<String, String>>()
val createLocalPropertiesFile by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runAfter(KotlinPlugin.createModules)
runBefore(TemplatesPlugin.renderFileTemplates)
isAvailable = isGradle
withAction {
val properties = localProperties.propertyValue
if (properties.isEmpty()) return@withAction UNIT_SUCCESS
TemplatesPlugin.addFileTemplate.execute(
FileTemplate(
FileTemplateDescriptor(
"gradle/local.properties.vm",
"local.properties".asPath()
),
StructurePlugin.projectPath.settingValue,
mapOf(
"properties" to localProperties.propertyValue
)
)
)
}
}
private val isGradle = checker { buildSystemType.isGradle }
val gradleVersion by valueSetting(
"<GRADLE_VERSION>",
GenerationPhase.PROJECT_GENERATION,
parser = Version.parser
) {
defaultValue = value(Versions.GRADLE)
}
val initGradleWrapperTask by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runBefore(TemplatesPlugin.renderFileTemplates)
isAvailable = isGradle
withAction {
TemplatesPlugin.addFileTemplate.execute(
FileTemplate(
FileTemplateDescriptor(
"gradle/gradle-wrapper.properties.vm",
"gradle" / "wrapper" / "gradle-wrapper.properties"
),
StructurePlugin.projectPath.settingValue,
mapOf(
"version" to gradleVersion.settingValue
)
)
)
}
}
val mergeCommonRepositories by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runBefore(createModules)
runAfter(takeRepositoriesFromDependencies)
runAfter(KotlinPlugin.createPluginRepositories)
isAvailable = isGradle
withAction {
val buildFiles = buildFiles.propertyValue
if (buildFiles.size == 1) return@withAction UNIT_SUCCESS
val moduleRepositories = buildFiles.mapNotNull { buildFileIR ->
if (buildFileIR.isRoot) null
else buildFileIR.irs.mapNotNull { it.safeAs<RepositoryIR>()?.repository }
}
val allRepositories = moduleRepositories.flatMapTo(hashSetOf()) { it }
val commonRepositories = allRepositories.filterTo(
hashSetOf(KotlinPlugin.version.propertyValue.repository)
) { repo ->
moduleRepositories.all { repo in it }
}
updateBuildFiles { buildFile ->
buildFile.withReplacedIrs(
buildFile.irs
.filterNot { it.safeAs<RepositoryIR>()?.repository in commonRepositories }
.toPersistentList()
).let {
if (it.isRoot && commonRepositories.isNotEmpty()) {
val repositories = commonRepositories.map(::RepositoryIR).distinctAndSorted()
it.withIrs(AllProjectsRepositoriesIR(repositories))
} else it
}.asSuccess()
}
}
}
val createSettingsFileTask by pipelineTask(GenerationPhase.PROJECT_GENERATION) {
runAfter(KotlinPlugin.createModules)
runAfter(KotlinPlugin.createPluginRepositories)
isAvailable = isGradle
withAction {
val (createBuildFile, buildFileName) = settingsGradleBuildFileData ?: return@withAction UNIT_SUCCESS
val repositories = getPluginRepositoriesWithDefaultOnes().map { PluginManagementRepositoryIR(RepositoryIR(it)) }
val settingsGradleIR = SettingsGradleFileIR(
StructurePlugin.name.settingValue,
allModulesPaths.map { path -> path.joinToString(separator = "") { ":$it" } },
buildPersistenceList {
+repositories
+settingsGradleFileIRs.propertyValue
}
)
val buildFileText = createBuildFile().printBuildFile { settingsGradleIR.render(this) }
service<FileSystemWizardService>().createFile(
projectPath / buildFileName,
buildFileText
)
}
}
}
override val settings: List<PluginSetting<*, *>> = super.settings +
listOf(
gradleVersion,
)
override val pipelineTasks: List<PipelineTask> = super.pipelineTasks +
listOf(
createGradlePropertiesFile,
createLocalPropertiesFile,
initGradleWrapperTask,
createSettingsFileTask,
mergeCommonRepositories,
)
override val properties: List<Property<*>> = super.properties +
listOf(
gradleProperties,
settingsGradleFileIRs,
localProperties
)
}
val Reader.settingsGradleBuildFileData
get() = when (buildSystemType) {
BuildSystemType.GradleKotlinDsl ->
BuildFileData(
{ GradlePrinter(GradlePrinter.GradleDsl.KOTLIN) },
"settings.gradle.kts"
)
BuildSystemType.GradleGroovyDsl ->
BuildFileData(
{ GradlePrinter(GradlePrinter.GradleDsl.GROOVY) },
"settings.gradle"
)
else -> null
} | apache-2.0 | ce036ce08bb737f787a56b20623c2ffd | 41.776744 | 158 | 0.596346 | 6.196765 | false | false | false | false |
siosio/intellij-community | platform/platform-impl/src/com/intellij/openapi/progress/util/ProgressDialog.kt | 1 | 17623 | // 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.progress.util
import com.intellij.CommonBundle
import com.intellij.ide.ui.laf.darcula.ui.DarculaProgressBarUI
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.DialogWrapperDialog
import com.intellij.openapi.ui.DialogWrapperPeer
import com.intellij.openapi.ui.impl.DialogWrapperPeerImpl
import com.intellij.openapi.ui.impl.GlassPaneDialogWrapperPeer
import com.intellij.openapi.ui.impl.GlassPaneDialogWrapperPeer.GlasspanePeerUnavailableException
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.WindowManager
import com.intellij.ui.PopupBorder
import com.intellij.ui.TitlePanel
import com.intellij.ui.WindowMoveListener
import com.intellij.ui.components.JBLabel
import com.intellij.ui.scale.JBUIScale
import com.intellij.uiDesigner.core.GridConstraints
import com.intellij.uiDesigner.core.GridLayoutManager
import com.intellij.util.Alarm
import com.intellij.util.SingleAlarm
import com.intellij.util.ui.DialogUtil
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Contract
import org.jetbrains.annotations.Nls
import java.awt.Component
import java.awt.Dimension
import java.awt.Window
import java.awt.event.KeyEvent
import java.io.File
import javax.swing.*
import javax.swing.border.Border
class ProgressDialog(private val myProgressWindow: ProgressWindow,
private val myShouldShowBackground: Boolean,
cancelText: @Nls String?,
private val myParentWindow: Window?) : Disposable {
companion object {
const val UPDATE_INTERVAL = 50 //msec. 20 frames per second.
}
private var myLastTimeDrawn: Long = -1
private val myUpdateAlarm = SingleAlarm(this::update, 500, this)
private var myWasShown = false
private val myStartMillis = System.currentTimeMillis()
private val myRepaintRunnable = Runnable {
val text = myProgressWindow.text
val fraction = myProgressWindow.fraction
val text2 = myProgressWindow.text2
if (myProgressBar.isShowing) {
myProgressBar.isIndeterminate = myProgressWindow.isIndeterminate
myProgressBar.value = (fraction * 100).toInt()
if (myProgressBar.isIndeterminate && isWriteActionProgress() && myProgressBar.ui is DarculaProgressBarUI) {
(myProgressBar.ui as DarculaProgressBarUI).updateIndeterminateAnimationIndex(myStartMillis)
}
}
myTextLabel.text = fitTextToLabel(text, myTextLabel)
myText2Label.text = fitTextToLabel(text2, myText2Label)
myTitlePanel.setText(StringUtil.defaultIfEmpty(myProgressWindow.title, " "))
myLastTimeDrawn = System.currentTimeMillis()
synchronized(this@ProgressDialog) {
myRepaintedFlag = true
}
}
private val myPanel = JPanel()
private val myTextLabel = JLabel(" ")
private val myText2Label = JBLabel("")
private val myCancelButton = JButton()
private val myBackgroundButton = JButton()
private val myProgressBar = JProgressBar()
private var myRepaintedFlag = true // guarded by this
private val myTitlePanel = TitlePanel()
private var myPopup: DialogWrapper? = null
private val myDisableCancelAlarm = SingleAlarm(this::setCancelButtonDisabledInEDT, 500, null, Alarm.ThreadToUse.SWING_THREAD,
ModalityState.any())
private val myEnableCancelAlarm = SingleAlarm(this::setCancelButtonEnabledInEDT, 500, null, Alarm.ThreadToUse.SWING_THREAD,
ModalityState.any())
init {
setupUI()
initDialog(cancelText)
}
private fun setupUI() {
myPanel.layout = GridLayoutManager(2, 1, JBUI.emptyInsets(), -1, -1, false, false)
val panel = JPanel()
panel.layout = GridLayoutManager(1, 2, JBUI.insets(6, 10, 10, 10), -1, -1, false, false)
panel.isOpaque = false
myPanel.add(panel, GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_GROW or GridConstraints.SIZEPOLICY_CAN_SHRINK,
GridConstraints.SIZEPOLICY_CAN_GROW or GridConstraints.SIZEPOLICY_CAN_SHRINK, null, null, null))
val innerPanel = JPanel()
innerPanel.layout = GridLayoutManager(3, 2, JBUI.emptyInsets(), -1, -1, false, false)
innerPanel.preferredSize = Dimension(if (SystemInfo.isMac) 350 else JBUIScale.scale(450), -1)
panel.add(innerPanel, GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW or
GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null))
innerPanel.add(myTextLabel, GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
(GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW or
GridConstraints.SIZEPOLICY_WANT_GROW), GridConstraints.SIZEPOLICY_FIXED,
Dimension(0, -1), null, null))
myText2Label.componentStyle = UIUtil.ComponentStyle.REGULAR
innerPanel.add(myText2Label, GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_NORTHWEST, GridConstraints.FILL_HORIZONTAL,
(GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW or
GridConstraints.SIZEPOLICY_WANT_GROW), GridConstraints.SIZEPOLICY_FIXED,
Dimension(0, -1), null, null))
myProgressBar.putClientProperty("html.disable", java.lang.Boolean.FALSE)
innerPanel.add(myProgressBar, GridConstraints(1, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
(GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW or
GridConstraints.SIZEPOLICY_WANT_GROW), GridConstraints.SIZEPOLICY_FIXED, null, null,
null))
innerPanel.add(JLabel(" "),
GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED,
GridConstraints.SIZEPOLICY_FIXED, null, null, null))
innerPanel.add(JLabel(" "),
GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED,
GridConstraints.SIZEPOLICY_FIXED, null, null, null))
val buttonPanel = JPanel()
buttonPanel.layout = GridLayoutManager(2, 1, JBUI.emptyInsets(), -1, -1, false, false)
panel.add(buttonPanel, GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK, GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
null))
myCancelButton.text = CommonBundle.getCancelButtonText()
DialogUtil.registerMnemonic(myCancelButton, '&')
buttonPanel.add(myCancelButton, GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_GROW or GridConstraints.SIZEPOLICY_CAN_SHRINK,
GridConstraints.SIZEPOLICY_FIXED, null, null, null))
myBackgroundButton.text = CommonBundle.message("button.background")
DialogUtil.registerMnemonic(myBackgroundButton, '&')
buttonPanel.add(myBackgroundButton, GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_GROW or GridConstraints.SIZEPOLICY_CAN_SHRINK,
GridConstraints.SIZEPOLICY_FIXED, null, null, null))
myPanel.add(myTitlePanel, GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
(GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW or
GridConstraints.SIZEPOLICY_WANT_GROW), GridConstraints.SIZEPOLICY_FIXED, null, null, null))
}
@Contract(pure = true)
private fun fitTextToLabel(fullText: String?, label: JLabel): String {
if (fullText == null || fullText.isEmpty()) return " "
var newFullText = StringUtil.last(fullText, 500, true).toString() // avoid super long strings
while (label.getFontMetrics(label.font).stringWidth(newFullText) > label.width) {
val sep = newFullText.indexOf(File.separatorChar, 4)
if (sep < 0) return newFullText
newFullText = "..." + newFullText.substring(sep)
}
return newFullText
}
private fun initDialog(cancelText: @Nls String?) {
if (SystemInfo.isMac) {
UIUtil.applyStyle(UIUtil.ComponentStyle.SMALL, myText2Label)
}
myText2Label.foreground = UIUtil.getContextHelpForeground()
myCancelButton.addActionListener { doCancelAction() }
myCancelButton.registerKeyboardAction(
{
if (myCancelButton.isEnabled) {
doCancelAction()
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
if (cancelText != null) {
myProgressWindow.setCancelButtonText(cancelText)
}
myProgressBar.isIndeterminate = myProgressWindow.isIndeterminate
myProgressBar.maximum = 100
createCenterPanel()
myTitlePanel.setActive(true)
val moveListener = object : WindowMoveListener(myTitlePanel) {
override fun getView(component: Component): Component {
return SwingUtilities.getAncestorOfClass(DialogWrapperDialog::class.java, component)
}
}
myTitlePanel.addMouseListener(moveListener)
myTitlePanel.addMouseMotionListener(moveListener)
}
override fun dispose() {
UIUtil.disposeProgress(myProgressBar)
UIUtil.dispose(myTitlePanel)
UIUtil.dispose(myBackgroundButton)
UIUtil.dispose(myCancelButton)
myEnableCancelAlarm.cancelAllRequests()
myDisableCancelAlarm.cancelAllRequests()
}
fun getPanel(): JPanel = myPanel
fun getRepaintRunnable(): Runnable = myRepaintRunnable
fun getPopup(): DialogWrapper? = myPopup
fun changeCancelButtonText(text: @Nls String) {
myCancelButton.text = text
}
private fun doCancelAction() {
if (myProgressWindow.myShouldShowCancel) {
myProgressWindow.cancel()
}
}
fun cancel() {
enableCancelButtonIfNeeded(false)
}
private fun setCancelButtonEnabledInEDT() {
myCancelButton.isEnabled = true
}
private fun setCancelButtonDisabledInEDT() {
myCancelButton.isEnabled = false
}
fun enableCancelButtonIfNeeded(enable: Boolean) {
if (myProgressWindow.myShouldShowCancel && !myUpdateAlarm.isDisposed) {
(if (enable) myEnableCancelAlarm else myDisableCancelAlarm).request()
}
}
private fun createCenterPanel() {
// Cancel button (if any)
if (myProgressWindow.myCancelText != null) {
myCancelButton.text = myProgressWindow.myCancelText
}
myCancelButton.isVisible = myProgressWindow.myShouldShowCancel
myBackgroundButton.isVisible = myShouldShowBackground
myBackgroundButton.addActionListener {
if (myShouldShowBackground) {
myProgressWindow.background()
}
}
}
@Synchronized
fun update() {
if (myRepaintedFlag) {
if (System.currentTimeMillis() > myLastTimeDrawn + UPDATE_INTERVAL) {
myRepaintedFlag = false
UIUtil.invokeLaterIfNeeded(myRepaintRunnable)
}
else {
// later to avoid concurrent dispose/addRequest
if (!myUpdateAlarm.isDisposed && myUpdateAlarm.isEmpty) {
UIUtil.invokeLaterIfNeeded {
if (!myUpdateAlarm.isDisposed) {
myUpdateAlarm.request(myProgressWindow.modalityState)
}
}
}
}
}
}
@Synchronized
fun background() {
if (myShouldShowBackground) {
myBackgroundButton.isEnabled = false
}
hide()
}
fun hide() {
ApplicationManager.getApplication().invokeLater(this::hideImmediately, ModalityState.any())
}
fun hideImmediately() {
if (myPopup != null) {
myPopup!!.close(DialogWrapper.CANCEL_EXIT_CODE)
myPopup = null
}
}
fun show() {
if (myWasShown) {
return
}
myWasShown = true
if (ApplicationManager.getApplication().isHeadlessEnvironment || myParentWindow == null) {
return
}
if (myPopup != null) {
myPopup!!.close(DialogWrapper.CANCEL_EXIT_CODE)
}
val popup = if (myParentWindow.isShowing) MyDialogWrapper(myParentWindow, myProgressWindow.myShouldShowCancel)
else MyDialogWrapper(myProgressWindow.myProject, myProgressWindow.myShouldShowCancel)
myPopup = popup
popup.setUndecorated(true)
if (popup.peer is DialogWrapperPeerImpl) {
(popup.peer as DialogWrapperPeerImpl).setAutoRequestFocus(false)
if (isWriteActionProgress()) {
popup.isModal = false // display the dialog and continue with EDT execution, don't block it forever
}
}
popup.pack()
Disposer.register(popup.disposable) { myProgressWindow.exitModality() }
popup.show()
// 'Light' popup is shown in glass pane, glass pane is 'activating' (becomes visible) in 'invokeLater' call
// (see IdeGlassPaneImp.addImpl), requesting focus to cancel button until that time has no effect, as it's not showing.
SwingUtilities.invokeLater {
if (myPopup != null && !myPopup!!.isDisposed) {
val window = SwingUtilities.getWindowAncestor(myCancelButton)
if (window != null) {
val originalFocusOwner = window.mostRecentFocusOwner
if (originalFocusOwner != null) {
Disposer.register(myPopup!!.disposable) { originalFocusOwner.requestFocusInWindow() }
}
}
myCancelButton.requestFocusInWindow()
myRepaintRunnable.run()
}
}
}
private fun isWriteActionProgress(): Boolean {
return myProgressWindow is PotemkinProgress
}
private inner class MyDialogWrapper : DialogWrapper {
private val myIsCancellable: Boolean
constructor(project: Project?, cancellable: Boolean) : super(project, false) {
init()
myIsCancellable = cancellable
}
constructor(parent: Component, cancellable: Boolean) : super(parent, false) {
init()
myIsCancellable = cancellable
}
override fun doCancelAction() {
if (myIsCancellable) {
[email protected]()
}
}
override fun createPeer(parent: Component, canBeParent: Boolean): DialogWrapperPeer {
return if (useLightPopup()) {
try {
GlassPaneDialogWrapperPeer(this, parent)
}
catch (e: GlasspanePeerUnavailableException) {
super.createPeer(parent, canBeParent)
}
}
else {
super.createPeer(parent, canBeParent)
}
}
override fun createPeer(owner: Window, canBeParent: Boolean, applicationModalIfPossible: Boolean): DialogWrapperPeer {
return if (useLightPopup()) {
try {
GlassPaneDialogWrapperPeer(this)
}
catch (e: GlasspanePeerUnavailableException) {
super.createPeer(WindowManager.getInstance().suggestParentWindow(myProgressWindow.myProject), canBeParent,
applicationModalIfPossible)
}
}
else {
super.createPeer(WindowManager.getInstance().suggestParentWindow(myProgressWindow.myProject), canBeParent,
applicationModalIfPossible)
}
}
private fun useLightPopup(): Boolean {
return System.getProperty("vintage.progress") == null/* && !isWriteActionProgress()*/ // TODO: KT-46874
}
override fun createPeer(project: Project?, canBeParent: Boolean): DialogWrapperPeer {
return if (System.getProperty("vintage.progress") == null) {
try {
GlassPaneDialogWrapperPeer(project, this)
}
catch (e: GlasspanePeerUnavailableException) {
super.createPeer(project, canBeParent)
}
}
else {
super.createPeer(project, canBeParent)
}
}
override fun init() {
super.init()
setUndecorated(true)
rootPane.windowDecorationStyle = JRootPane.NONE
myPanel.border = PopupBorder.Factory.create(true, true)
}
override fun isProgressDialog(): Boolean {
return true
}
override fun createCenterPanel(): JComponent {
return myPanel
}
override fun createSouthPanel(): JComponent? {
return null
}
override fun createContentPaneBorder(): Border? {
return null
}
}
} | apache-2.0 | 1fa74225b1b0e8cd643d46514b7a12fd | 38.25167 | 158 | 0.678375 | 4.844145 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-idea/tests/test/org/jetbrains/kotlin/gradle/projectStructureDSL.kt | 1 | 17209 | // 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.gradle
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.*
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.systemIndependentPath
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.jps.util.JpsPathUtil
import org.jetbrains.kotlin.config.ExternalSystemTestRunTask
import org.jetbrains.kotlin.idea.facet.KotlinFacet
import org.jetbrains.kotlin.idea.facet.externalSystemTestRunTasks
import org.jetbrains.kotlin.idea.project.isHMPPEnabled
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.project.platform
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.utils.addToStdlib.filterIsInstanceWithChecker
import java.io.File
import kotlin.test.fail
class MessageCollector {
private val builder = StringBuilder()
fun report(message: String) {
builder.append(message).append("\n\n")
}
fun check() {
val message = builder.toString()
if (message.isNotEmpty()) {
fail("\n\n" + message)
}
}
}
class ProjectInfo(
project: Project,
internal val projectPath: String,
internal val exhaustiveModuleList: Boolean,
internal val exhaustiveSourceSourceRootList: Boolean,
internal val exhaustiveDependencyList: Boolean,
internal val exhaustiveTestsList: Boolean
) {
internal val messageCollector = MessageCollector()
private val moduleManager = ModuleManager.getInstance(project)
private val expectedModuleNames = HashSet<String>()
private var allModulesAsserter: (ModuleInfo.() -> Unit)? = null
fun allModules(body: ModuleInfo.() -> Unit) {
assert(allModulesAsserter == null)
allModulesAsserter = body
}
fun module(name: String, isOptional: Boolean = false, body: ModuleInfo.() -> Unit = {}) {
val module = moduleManager.findModuleByName(name)
if (module == null) {
if (!isOptional) {
messageCollector.report("No module found: '$name' in ${moduleManager.modules.map { it.name }}")
}
return
}
val moduleInfo = ModuleInfo(module, this)
allModulesAsserter?.let { moduleInfo.it() }
moduleInfo.run(body)
expectedModuleNames += name
}
fun run(body: ProjectInfo.() -> Unit = {}) {
body()
if (exhaustiveModuleList) {
val actualNames = moduleManager.modules.map { it.name }.sorted()
val expectedNames = expectedModuleNames.sorted()
if (actualNames != expectedNames) {
messageCollector.report("Expected module list $expectedNames doesn't match the actual one: $actualNames")
}
}
messageCollector.check()
}
}
class ModuleInfo(val module: Module, private val projectInfo: ProjectInfo) {
private val rootModel = module.rootManager
private val expectedDependencyNames = HashSet<String>()
private val expectedDependencies = HashSet<OrderEntry>()
private val expectedSourceRoots = HashSet<String>()
private val expectedExternalSystemTestTasks = ArrayList<ExternalSystemTestRunTask>()
private val assertions = mutableListOf<(ModuleInfo) -> Unit>()
private var mustHaveSdk: Boolean = true
private val sourceFolderByPath by lazy {
rootModel.contentEntries.asSequence()
.flatMap { it.sourceFolders.asSequence() }
.mapNotNull {
val path = it.file?.path ?: return@mapNotNull null
FileUtil.getRelativePath(projectInfo.projectPath, path, '/')!! to it
}
.toMap()
}
fun report(text: String) {
projectInfo.messageCollector.report("Module '${module.name}': $text")
}
private fun checkReport(subject: String, expected: Any?, actual: Any?) {
if (expected != actual) {
report(
"$subject differs:\n" +
"expected $expected\n" +
"actual: $actual"
)
}
}
fun externalSystemTestTask(taskName: String, projectId: String, targetName: String) {
expectedExternalSystemTestTasks.add(ExternalSystemTestRunTask(taskName, projectId, targetName))
}
fun languageVersion(expectedVersion: String) {
val actualVersion = module.languageVersionSettings.languageVersion.versionString
checkReport("Language version", expectedVersion, actualVersion)
}
fun isHMPP(expectedValue: Boolean) {
checkReport("isHMPP", expectedValue, module.isHMPPEnabled)
}
fun targetPlatform(vararg platforms: TargetPlatform) {
val expected = platforms.flatMap { it.componentPlatforms }.toSet()
val actual = module.platform?.componentPlatforms
if (actual == null) {
report("Actual target platform is null")
return
}
val notFound = expected.subtract(actual)
if (notFound.isNotEmpty()) {
report("These target platforms were not found: " + notFound.joinToString())
}
val unexpected = actual.subtract(expected)
if (unexpected.isNotEmpty()) {
report("Unexpected target platforms found: " + unexpected.joinToString())
}
}
fun apiVersion(expectedVersion: String) {
val actualVersion = module.languageVersionSettings.apiVersion.versionString
checkReport("API version", expectedVersion, actualVersion)
}
fun platform(expectedPlatform: TargetPlatform) {
val actualPlatform = module.platform
checkReport("Platform", expectedPlatform, actualPlatform)
}
fun additionalArguments(arguments: String?) {
val actualArguments = KotlinFacet.get(module)?.configuration?.settings?.compilerSettings?.additionalArguments
checkReport("Additional arguments", arguments, actualArguments)
}
fun libraryDependency(libraryName: String, scope: DependencyScope, isOptional: Boolean = false) {
libraryDependency(Regex.fromLiteral(libraryName), scope, isOptional)
}
fun libraryDependency(libraryName: Regex, scope: DependencyScope, isOptional: Boolean = false) {
val libraryEntries = rootModel.orderEntries.filterIsInstance<LibraryOrderEntry>()
.filter { it.libraryName?.matches(libraryName) == true }
if (libraryEntries.size > 1) {
report("Multiple root entries for library $libraryName")
}
if (!isOptional && libraryEntries.isEmpty()) {
val candidate = rootModel.orderEntries
.filterIsInstance<LibraryOrderEntry>()
.sortedWith(Comparator { o1, o2 ->
val o1len = o1?.libraryName?.commonPrefixWith(libraryName.toString())?.length ?: 0
val o2len = o2?.libraryName?.commonPrefixWith(libraryName.toString())?.length ?: 0
o2len - o1len
}).firstOrNull()
val candidateName = candidate?.libraryName
report("Expected library dependency $libraryName, found nothing. Most probably candidate: $candidateName")
}
checkLibrary(libraryEntries.firstOrNull() ?: return, scope)
}
fun libraryDependencyByUrl(classesUrl: String, scope: DependencyScope) {
libraryDependencyByUrl(Regex.fromLiteral(classesUrl), scope)
}
fun libraryDependencyByUrl(classesUrl: Regex, scope: DependencyScope) {
val libraryEntries = rootModel.orderEntries.filterIsInstance<LibraryOrderEntry>().filter { entry ->
entry.library?.getUrls(OrderRootType.CLASSES)?.any { it.matches(classesUrl) } ?: false
}
if (libraryEntries.size > 1) {
report("Multiple entries for library $classesUrl")
}
if (libraryEntries.isEmpty()) {
report("No library dependency found for $classesUrl")
}
checkLibrary(libraryEntries.firstOrNull() ?: return, scope)
}
private fun checkLibrary(libraryEntry: LibraryOrderEntry, scope: DependencyScope) {
checkDependencyScope(libraryEntry, scope)
expectedDependencies += libraryEntry
expectedDependencyNames += libraryEntry.debugText
}
fun moduleDependency(
moduleName: String, scope: DependencyScope,
productionOnTest: Boolean? = null, allowMultiple: Boolean = false, isOptional: Boolean = false
) {
val moduleEntries = rootModel.orderEntries.asList()
.filterIsInstanceWithChecker<ModuleOrderEntry> { it.moduleName == moduleName && it.scope == scope }
// In normal conditions, 'allowMultiple' should always be 'false'. In reality, however, a lot of tests fails because of it.
if (!allowMultiple && moduleEntries.size > 1) {
val allEntries = rootModel.orderEntries.filterIsInstance<ModuleOrderEntry>().joinToString { it.debugText }
report("Multiple order entries found for module $moduleName: $allEntries")
return
}
val moduleEntry = moduleEntries.firstOrNull()
if (moduleEntry == null) {
if (!isOptional) {
val allModules = rootModel.orderEntries.filterIsInstance<ModuleOrderEntry>().joinToString { it.debugText }
report("Module dependency ${moduleName} (${scope.displayName}) not found. All module dependencies: $allModules")
}
return
}
checkDependencyScope(moduleEntry, scope)
checkProductionOnTest(moduleEntry, productionOnTest)
expectedDependencies += moduleEntry
expectedDependencyNames += moduleEntry.debugText
}
private val ANY_PACKAGE_PREFIX = "any_package_prefix"
fun sourceFolder(pathInProject: String, rootType: JpsModuleSourceRootType<*>, packagePrefix: String? = ANY_PACKAGE_PREFIX) {
val sourceFolder = sourceFolderByPath[pathInProject]
if (sourceFolder == null) {
report("No source root found: '$pathInProject' among $sourceFolderByPath")
return
}
if (packagePrefix != ANY_PACKAGE_PREFIX && sourceFolder.packagePrefix != packagePrefix) {
report("Source root '$pathInProject': Expected package prefix $packagePrefix, got: ${sourceFolder.packagePrefix}")
}
expectedSourceRoots += pathInProject
val actualRootType = sourceFolder.rootType
if (actualRootType != rootType) {
report("Source root '$pathInProject': Expected root type $rootType, got: $actualRootType")
return
}
}
fun inheritProjectOutput() {
val isInherited = CompilerModuleExtension.getInstance(module)?.isCompilerOutputPathInherited ?: true
if (!isInherited) {
report("Project output is not inherited")
}
}
fun outputPath(pathInProject: String, isProduction: Boolean) {
val compilerModuleExtension = CompilerModuleExtension.getInstance(module)
val url = if (isProduction) compilerModuleExtension?.compilerOutputUrl else compilerModuleExtension?.compilerOutputUrlForTests
val actualPathInProject = url?.let {
FileUtil.getRelativePath(
projectInfo.projectPath,
JpsPathUtil.urlToPath(
it
),
'/'
)
}
checkReport("Output path", pathInProject, actualPathInProject)
}
fun noSdk() {
mustHaveSdk = false
}
fun assertExhaustiveModuleDependencyList() {
assertions += {
val expectedModuleDependencies = expectedDependencies.filterIsInstance<ModuleOrderEntry>()
.map { it.debugText }.sorted().distinct()
val actualModuleDependencies = rootModel.orderEntries.filterIsInstance<ModuleOrderEntry>()
.map { it.debugText }.sorted().distinct()
// increasing readability of log outputs
.sortedBy { if (it in expectedModuleDependencies) 0 else 1 }
if (actualModuleDependencies != expectedModuleDependencies) {
report(
"Bad Module dependency list for ${module.name}\n" +
"Expected: $expectedModuleDependencies\n" +
"Actual: $actualModuleDependencies"
)
}
}
}
fun assertExhaustiveDependencyList() {
assertions += {
val expectedDependencyNames = expectedDependencyNames.sorted()
val actualDependencyNames = rootModel
.orderEntries.asList()
.filterIsInstanceWithChecker<ExportableOrderEntry> { it is ModuleOrderEntry || it is LibraryOrderEntry }
.map { it.debugText }
.sorted()
.distinct()
// increasing readability of log outputs
.sortedBy { if (it in expectedDependencyNames) 0 else 1 }
checkReport("Dependency list", expectedDependencyNames, actualDependencyNames)
}
}
fun assertExhaustiveTestsList() {
assertions += {
val actualTasks = module.externalSystemTestRunTasks()
val containsAllTasks = actualTasks.containsAll(expectedExternalSystemTestTasks)
val containsSameTasks = actualTasks == expectedExternalSystemTestTasks
if (!containsAllTasks || !containsSameTasks) {
report("Expected tests list $expectedExternalSystemTestTasks, got: $actualTasks")
}
}
}
fun assertExhaustiveSourceRootList() {
assertions += {
val actualSourceRoots = sourceFolderByPath.keys.sorted()
val expectedSourceRoots = expectedSourceRoots.sorted()
if (actualSourceRoots != expectedSourceRoots) {
report("Expected source root list $expectedSourceRoots, got: $actualSourceRoots")
}
}
}
fun assertNoDependencyInBuildClasses() {
val dependenciesInBuildDirectory = module.rootManager.orderEntries
.flatMap { orderEntry ->
orderEntry.getFiles(OrderRootType.SOURCES).toList().map { it.toIoFile() } +
orderEntry.getFiles(OrderRootType.CLASSES).toList().map { it.toIoFile() } +
orderEntry.getUrls(OrderRootType.CLASSES).toList().map { File(it) } +
orderEntry.getUrls(OrderRootType.SOURCES).toList().map { File(it) }
}
.map { file -> file.systemIndependentPath }
.filter { path -> "/build/classes/" in path }
if (dependenciesInBuildDirectory.isNotEmpty()) {
report("References dependency in build directory:\n${dependenciesInBuildDirectory.joinToString("\n")}")
}
}
fun run(body: ModuleInfo.() -> Unit = {}) {
body()
assertions.forEach { it.invoke(this) }
if (mustHaveSdk && rootModel.sdk == null) {
report("No SDK defined")
}
}
private fun checkDependencyScope(library: ExportableOrderEntry, expectedScope: DependencyScope) {
checkReport("Dependency scope", expectedScope, library.scope)
}
private fun checkProductionOnTest(library: ExportableOrderEntry, productionOnTest: Boolean?) {
if (productionOnTest == null) return
val actualFlag = (library as? ModuleOrderEntry)?.isProductionOnTestDependency
if (actualFlag == null) {
report("Dependency '${library.presentableName}' has no 'productionOnTest' property")
} else {
if (actualFlag != productionOnTest) {
report("Dependency '${library.presentableName}': expected productionOnTest '$productionOnTest', got '$actualFlag'")
}
}
}
init {
if (projectInfo.exhaustiveDependencyList) {
assertExhaustiveDependencyList()
}
if (projectInfo.exhaustiveTestsList) {
assertExhaustiveTestsList()
}
if (projectInfo.exhaustiveSourceSourceRootList) {
assertExhaustiveSourceRootList()
}
}
}
fun checkProjectStructure(
project: Project,
projectPath: String,
exhaustiveModuleList: Boolean = false,
exhaustiveSourceSourceRootList: Boolean = false,
exhaustiveDependencyList: Boolean = false,
exhaustiveTestsList: Boolean = false,
body: ProjectInfo.() -> Unit = {}
) {
ProjectInfo(
project,
projectPath,
exhaustiveModuleList,
exhaustiveSourceSourceRootList,
exhaustiveDependencyList,
exhaustiveTestsList
).run(body)
}
private val ExportableOrderEntry.debugText: String
get() = "$presentableName (${scope.displayName})"
private fun VirtualFile.toIoFile(): File = VfsUtil.virtualToIoFile(this)
| apache-2.0 | 9458abdc1f068c48b838934835f126c8 | 38.470183 | 158 | 0.653844 | 5.482319 | false | true | false | false |
JetBrains/xodus | query/src/main/kotlin/jetbrains/exodus/query/LinksEqualDecorator.kt | 1 | 3774 | /**
* Copyright 2010 - 2022 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
*
* 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 jetbrains.exodus.query
import jetbrains.exodus.entitystore.Entity
import jetbrains.exodus.entitystore.iterate.EntityIterableBase
import jetbrains.exodus.query.Utils.safe_equals
import jetbrains.exodus.query.metadata.ModelMetaData
@Suppress("EqualsOrHashCode")
class LinksEqualDecorator(val linkName: String, var decorated: NodeBase, val linkEntityType: String) : NodeBase() {
override fun instantiate(
entityType: String,
queryEngine: QueryEngine,
metaData: ModelMetaData,
context: InstantiateContext
): Iterable<Entity> {
queryEngine.assertOperational()
return (queryEngine.instantiateGetAll(entityType) as EntityIterableBase)
.findLinks(instantiateDecorated(linkEntityType, queryEngine, metaData, context), linkName)
}
override fun getClone(): NodeBase = LinksEqualDecorator(linkName, decorated.clone, linkEntityType)
protected fun instantiateDecorated(
entityType: String,
queryEngine: QueryEngine,
metaData: ModelMetaData?,
context: InstantiateContext
): Iterable<Entity> {
val emd = metaData?.getEntityMetaData(entityType)
var result =
if (emd?.isAbstract == true) EntityIterableBase.EMPTY
else decorated.instantiate(entityType, queryEngine, metaData, context)
for (subType in emd?.subTypes ?: emptyList()) {
result = queryEngine.unionAdjusted(result, instantiateDecorated(subType, queryEngine, metaData, context))
}
return result
}
override fun optimize(sorts: Sorts, rules: OptimizationPlan) {
if (decorated is LinkEqual) {
val linkEqual = decorated as LinkEqual
if (linkEqual.toId == null) {
decorated = Minus(NodeFactory.all(), LinkNotNull(linkEqual.name))
}
} else if (decorated is PropertyEqual) {
val propEqual = decorated as PropertyEqual
if (propEqual.value == null) {
decorated = Minus(NodeFactory.all(), PropertyNotNull(propEqual.name))
}
}
}
override fun equals(other: Any?): Boolean {
if (other === this) {
return true
}
if (other == null) {
return false
}
checkWildcard(other)
if (other !is LinksEqualDecorator) {
return false
}
val decorator = other
return if (!safe_equals(linkName, decorator.linkName) || !safe_equals(
linkEntityType,
decorator.linkEntityType
)
) {
false
} else safe_equals(decorated, decorator.decorated)
}
override fun toString(prefix: String): String {
return """
${super.toString(prefix)}
${decorated.toString(TREE_LEVEL_INDENT + prefix)}
""".trimIndent()
}
override fun getHandle(sb: StringBuilder): StringBuilder {
super.getHandle(sb).append('(').append(linkName).append(',').append(linkEntityType).append(')').append('{')
return decorated.getHandle(sb).append('}')
}
override fun getSimpleName() = "led"
} | apache-2.0 | 845ea4a271f9442e7620891d83fb84f5 | 35.650485 | 117 | 0.649444 | 4.741206 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/joinLines/JoinInitializerAndIfToElvisHandler.kt | 6 | 1454 | // 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.joinLines
import com.intellij.codeInsight.editorActions.JoinRawLinesHandlerDelegate
import com.intellij.openapi.editor.Document
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.inspections.FoldInitializerAndIfToElvisInspection
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtIfExpression
import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.psi.psiUtil.siblings
class JoinInitializerAndIfToElvisHandler : JoinRawLinesHandlerDelegate {
override fun tryJoinRawLines(document: Document, file: PsiFile, start: Int, end: Int): Int {
if (file !is KtFile) return -1
val lineBreak = file.findElementAt(start)
?.siblings(forward = true, withItself = true)
?.firstOrNull { it.textContains('\n') }
?: return -1
val ifExpression = lineBreak.getNextSiblingIgnoringWhitespaceAndComments() as? KtIfExpression ?: return -1
if (!FoldInitializerAndIfToElvisInspection.isApplicable(ifExpression)) return -1
return FoldInitializerAndIfToElvisInspection.applyTo(ifExpression).textRange.startOffset
}
override fun tryJoinLines(document: Document, file: PsiFile, start: Int, end: Int) = -1
} | apache-2.0 | 950f0d1576c27d76d99482d275565ad0 | 50.964286 | 158 | 0.775103 | 4.782895 | false | false | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/ui/dsl/builder/Row.kt | 3 | 14119 | // 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.ui.dsl.builder
import com.intellij.icons.AllIcons
import com.intellij.ide.TooltipTitle
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.JBIntSpinner
import com.intellij.ui.components.*
import com.intellij.ui.components.fields.ExpandableTextField
import com.intellij.ui.dsl.builder.components.SegmentedButtonToolbar
import com.intellij.ui.dsl.gridLayout.Grid
import com.intellij.ui.dsl.gridLayout.VerticalGaps
import com.intellij.ui.layout.*
import com.intellij.util.Function
import com.intellij.util.execution.ParametersListUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.NonNls
import java.awt.event.ActionEvent
import javax.swing.*
/**
* Determines relation between row grid and parent's grid
*/
enum class RowLayout {
/**
* All cells of the row (including label if present) independent of parent grid.
* That means this row has its own grid
*/
INDEPENDENT,
/**
* Label is aligned, other components independent of parent grid. If label is not provided
* then first cell (sometimes can be [JCheckBox] for example) is considered as a label.
* That means label is in parent grid, other components have own grid
*/
LABEL_ALIGNED,
/**
* All components including label are in parent grid
* That means label and other components are in parent grid
*/
PARENT_GRID
}
enum class TopGap {
/**
* No gap
*/
NONE,
/**
* See [SpacingConfiguration.verticalSmallGap]
*/
SMALL,
/**
* See [SpacingConfiguration.verticalMediumGap]
*/
MEDIUM
}
enum class BottomGap {
/**
* No gap
*/
NONE,
/**
* See [SpacingConfiguration.verticalSmallGap]
*/
SMALL,
/**
* See [SpacingConfiguration.verticalMediumGap]
*/
MEDIUM
}
@ApiStatus.NonExtendable
@LayoutDslMarker
interface Row {
/**
* Layout of the row.
* Default value is [RowLayout.LABEL_ALIGNED] when label is provided for the row, [RowLayout.INDEPENDENT] otherwise
*/
fun layout(rowLayout: RowLayout): Row
/**
* Marks the row as resizable: the row occupies all extra vertical space in parent (for example in [Panel.group] or [Panel.panel])
* and changes size together with parent. When resizable is needed in whole [DialogPanel] all row parents should be marked
* as [resizableRow] as well. It's possible to have several resizable rows, which means extra space is shared between them.
* Note that vertical size and placement of components in the row are managed by [Cell.verticalAlign]
*
* @see [Grid.resizableRows]
*/
fun resizableRow(): Row
@Deprecated("Use overloaded rowComment(...) instead", level = DeprecationLevel.HIDDEN)
@ApiStatus.ScheduledForRemoval
fun rowComment(@NlsContexts.DetailedDescription comment: String,
maxLineLength: Int = DEFAULT_COMMENT_WIDTH): Row
/**
* Adds comment after the row with appropriate color and font size (macOS and Linux use smaller font).
* [comment] can contain HTML tags except <html>, which is added automatically.
* \n does not work as new line in html, use <br> instead.
* Links with href to http/https are automatically marked with additional arrow icon.
* Visibility and enabled state of the row affects row comment as well.
*
* @see MAX_LINE_LENGTH_WORD_WRAP
* @see MAX_LINE_LENGTH_NO_WRAP
*/
fun rowComment(@NlsContexts.DetailedDescription comment: String,
maxLineLength: Int = DEFAULT_COMMENT_WIDTH,
action: HyperlinkEventAction = HyperlinkEventAction.HTML_HYPERLINK_INSTANCE): Row
@Deprecated("Use cell(component: T) and scrollCell(component: T) instead")
@ApiStatus.ScheduledForRemoval
fun <T : JComponent> cell(component: T, viewComponent: JComponent = component): Cell<T>
/**
* Adds [component]. Use this method only for custom specific components, all standard components like label, button,
* checkbox etc are covered by dedicated [Row] factory methods
*/
fun <T : JComponent> cell(component: T): Cell<T>
/**
* Adds an empty cell in the grid
*/
fun cell()
/**
* Adds [component] wrapped by [JBScrollPane]
*/
fun <T : JComponent> scrollCell(component: T): Cell<T>
/**
* Adds a reserved cell in layout which can be populated by content later
*/
fun placeholder(): Placeholder
/**
* Sets visibility of the row including comment [Row.rowComment] and all children recursively.
* The row is invisible if there is an invisible parent
*/
fun visible(isVisible: Boolean): Row
/**
* Binds row visibility to provided [predicate]
*/
fun visibleIf(predicate: ComponentPredicate): Row
/**
* Sets enabled state of the row including comment [Row.rowComment] and all children recursively.
* The row is disabled if there is a disabled parent
*/
fun enabled(isEnabled: Boolean): Row
/**
* Binds row enabled state to provided [predicate]
*/
fun enabledIf(predicate: ComponentPredicate): Row
/**
* Adds additional gap above current row. It is visible together with the row.
* Only greatest gap of top and bottom gaps is used between two rows (or top gap if equal)
*/
fun topGap(topGap: TopGap): Row
/**
* Adds additional gap below current row. It is visible together with the row.
* Only greatest gap of top and bottom gaps is used between two rows (or top gap if equal)
*/
fun bottomGap(bottomGap: BottomGap): Row
/**
* Creates sub-panel inside the cell of the row. The panel contains its own rows and cells
*/
fun panel(init: Panel.() -> Unit): Panel
fun checkBox(@NlsContexts.Checkbox text: String): Cell<JBCheckBox>
@Deprecated("Use overloaded radioButton(...) instead", level = DeprecationLevel.HIDDEN)
@ApiStatus.ScheduledForRemoval
fun radioButton(@NlsContexts.RadioButton text: String): Cell<JBRadioButton>
/**
* Adds radio button. [Panel.buttonsGroup] must be defined above hierarchy before adding radio buttons.
* If there is a binding [ButtonsGroup.bind] for the buttons group then [value] must be provided with correspondent to binding type,
* or null otherwise
*/
fun radioButton(@NlsContexts.RadioButton text: String, value: Any? = null): Cell<JBRadioButton>
fun button(@NlsContexts.Button text: String, actionListener: (event: ActionEvent) -> Unit): Cell<JButton>
fun button(@NlsContexts.Button text: String, action: AnAction, @NonNls actionPlace: String = ActionPlaces.UNKNOWN): Cell<JButton>
fun actionButton(action: AnAction, @NonNls actionPlace: String = ActionPlaces.UNKNOWN): Cell<ActionButton>
/**
* Creates an [ActionButton] with [icon] and menu with provided [actions]
*/
fun actionsButton(vararg actions: AnAction,
@NonNls actionPlace: String = ActionPlaces.UNKNOWN,
icon: Icon = AllIcons.General.GearPlain): Cell<ActionButton>
@Deprecated("Use overloaded method")
@ApiStatus.ScheduledForRemoval
fun <T> segmentedButton(options: Collection<T>, property: GraphProperty<T>, renderer: (T) -> String): Cell<SegmentedButtonToolbar>
/**
* @see [SegmentedButton]
*/
@ApiStatus.Experimental
fun <T> segmentedButton(items: Collection<T>, renderer: (T) -> String): SegmentedButton<T>
/**
* Creates JBTabbedPane which shows only tabs without tab content. To add a new tab call something like
* ```
* JBTabbedPane.addTab(tab.name, JPanel())
* ```
*/
@ApiStatus.Experimental
fun tabbedPaneHeader(items: Collection<String> = emptyList()): Cell<JBTabbedPane>
fun slider(min: Int, max: Int, minorTickSpacing: Int, majorTickSpacing: Int): Cell<JSlider>
/**
* Adds a label. For label that relates to joined control [Panel.row] and [Cell.label] must be used,
* because they set correct gap between label and component and set [JLabel.labelFor] property
*/
fun label(@NlsContexts.Label text: String): Cell<JLabel>
@Deprecated("Use text(...) instead")
@ApiStatus.ScheduledForRemoval
fun labelHtml(@NlsContexts.Label text: String,
action: HyperlinkEventAction = HyperlinkEventAction.HTML_HYPERLINK_INSTANCE): Cell<JEditorPane>
/**
* Adds text. [text] can contain HTML tags except <html>, which is added automatically.
* \n does not work as new line in html, use <br> instead.
* Links with href to http/https are automatically marked with additional arrow icon.
* It is preferable to use [label] method for short plain single-lined strings because labels use less resources and simpler
*
* @see DEFAULT_COMMENT_WIDTH
* @see MAX_LINE_LENGTH_WORD_WRAP
* @see MAX_LINE_LENGTH_NO_WRAP
*/
fun text(@NlsContexts.Label text: String, maxLineLength: Int = MAX_LINE_LENGTH_WORD_WRAP,
action: HyperlinkEventAction = HyperlinkEventAction.HTML_HYPERLINK_INSTANCE): Cell<JEditorPane>
@Deprecated("Use overloaded comment(...) instead", level = DeprecationLevel.HIDDEN)
@ApiStatus.ScheduledForRemoval
fun comment(@NlsContexts.DetailedDescription text: String, maxLineLength: Int = MAX_LINE_LENGTH_WORD_WRAP): Cell<JLabel>
/**
* Adds comment with appropriate color and font size (macOS and Linux use smaller font).
* [comment] can contain HTML tags except <html>, which is added automatically.
* \n does not work as new line in html, use <br> instead.
* Links with href to http/https are automatically marked with additional arrow icon.
*
* @see DEFAULT_COMMENT_WIDTH
* @see MAX_LINE_LENGTH_WORD_WRAP
* @see MAX_LINE_LENGTH_NO_WRAP
*/
fun comment(@NlsContexts.DetailedDescription comment: String, maxLineLength: Int = MAX_LINE_LENGTH_WORD_WRAP,
action: HyperlinkEventAction = HyperlinkEventAction.HTML_HYPERLINK_INSTANCE): Cell<JEditorPane>
@Deprecated("Use comment(...) instead")
@ApiStatus.ScheduledForRemoval
fun commentNoWrap(@NlsContexts.DetailedDescription text: String): Cell<JLabel>
@Deprecated("Use comment(...) instead")
@ApiStatus.ScheduledForRemoval
fun commentHtml(@NlsContexts.DetailedDescription text: String,
action: HyperlinkEventAction = HyperlinkEventAction.HTML_HYPERLINK_INSTANCE): Cell<JEditorPane>
/**
* Creates focusable link with text inside. Should not be used with html in [text]
*/
fun link(@NlsContexts.LinkLabel text: String, action: (ActionEvent) -> Unit): Cell<ActionLink>
/**
* Creates focusable browser link with text inside. Should not be used with html in [text]
*/
fun browserLink(@NlsContexts.LinkLabel text: String, url: String): Cell<BrowserLink>
/**
* @param item current item
* @param items list of all available items in popup
* @param onSelected invoked when item is selected
* @param updateText true if after selection link text is updated, false otherwise
*/
fun <T> dropDownLink(item: T, items: List<T>, onSelected: ((T) -> Unit)? = null, updateText: Boolean = true): Cell<DropDownLink<T>>
fun icon(icon: Icon): Cell<JLabel>
fun contextHelp(@NlsContexts.Tooltip description: String, @TooltipTitle title: String? = null): Cell<JLabel>
/**
* Creates text field with [columns] set to [COLUMNS_SHORT]
*/
fun textField(): Cell<JBTextField>
/**
* Creates text field with browse button and [columns] set to [COLUMNS_SHORT]
*/
fun textFieldWithBrowseButton(@NlsContexts.DialogTitle browseDialogTitle: String? = null,
project: Project? = null,
fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(),
fileChosen: ((chosenFile: VirtualFile) -> String)? = null): Cell<TextFieldWithBrowseButton>
/**
* Creates expandable text field with [columns] set to [COLUMNS_SHORT]
*/
fun expandableTextField(parser: Function<in String, out MutableList<String>> = ParametersListUtil.DEFAULT_LINE_PARSER,
joiner: Function<in MutableList<String>, String> = ParametersListUtil.DEFAULT_LINE_JOINER): Cell<ExpandableTextField>
/**
* Creates integer text field with [columns] set to [COLUMNS_TINY]
*
* @param range allowed values range inclusive
* @param keyboardStep increase/decrease step for keyboard keys up/down. The keys are not used if [keyboardStep] is null
*/
fun intTextField(range: IntRange? = null, keyboardStep: Int? = null): Cell<JBTextField>
/**
* Creates spinner for int values
*
* @param range allowed values range inclusive
*/
fun spinner(range: IntRange, step: Int = 1): Cell<JBIntSpinner>
/**
* Creates spinner for double values
*
* @param range allowed values range inclusive
*/
fun spinner(range: ClosedRange<Double>, step: Double = 1.0): Cell<JSpinner>
/**
* Creates text area with [columns] set to [COLUMNS_SHORT]
*/
fun textArea(): Cell<JBTextArea>
fun <T> comboBox(model: ComboBoxModel<T>, renderer: ListCellRenderer<in T?>? = null): Cell<ComboBox<T>>
fun <T> comboBox(items: Collection<T>, renderer: ListCellRenderer<in T?>? = null): Cell<ComboBox<T>>
@Deprecated("Use overloaded comboBox(...) with Collection")
@ApiStatus.ScheduledForRemoval
fun <T> comboBox(items: Array<T>, renderer: ListCellRenderer<T?>? = null): Cell<ComboBox<T>>
/**
* Overrides all gaps around row by [customRowGaps]. Should be used for very specific cases
*/
fun customize(customRowGaps: VerticalGaps): Row
}
| apache-2.0 | bb2fc5b56a8d7c7b4a4d2b133ab4e905 | 37.262873 | 158 | 0.71896 | 4.402557 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/introduceVariableUtils.kt | 1 | 4630 | // 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.refactoring.introduce.introduceVariable
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.psi.PsiNamedElement
import org.jetbrains.kotlin.builtins.PrimitiveType
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.supertypes
import org.jetbrains.kotlin.util.isValidOperator
private fun getApplicableComponentFunctions(
contextExpression: KtExpression,
receiverType: KotlinType?,
receiverExpression: KtExpression?
): List<FunctionDescriptor> {
val facade = contextExpression.getResolutionFacade()
val context = facade.analyze(contextExpression)
val builtIns = facade.moduleDescriptor.builtIns
val forbiddenClasses = arrayListOf(builtIns.collection, builtIns.array)
PrimitiveType.values().mapTo(forbiddenClasses) { builtIns.getPrimitiveArrayClassDescriptor(it) }
(receiverType ?: context.getType(contextExpression))?.let {
if ((listOf(it) + it.supertypes()).any { type ->
val fqName = type.constructor.declarationDescriptor?.importableFqName
forbiddenClasses.any { descriptor -> descriptor.fqNameSafe == fqName }
}
) return emptyList()
}
val scope = contextExpression.getResolutionScope(context, facade)
val psiFactory = KtPsiFactory(contextExpression)
@Suppress("UNCHECKED_CAST")
return generateSequence(1) { it + 1 }.map {
val componentCallExpr = psiFactory.createExpressionByPattern("$0.$1", receiverExpression ?: contextExpression, "component$it()")
val newContext = componentCallExpr.analyzeInContext(scope, contextExpression)
componentCallExpr.getResolvedCall(newContext)?.resultingDescriptor as? FunctionDescriptor
}
.takeWhile { it != null && it.isValidOperator() }
.toList() as List<FunctionDescriptor>
}
internal fun chooseApplicableComponentFunctions(
contextExpression: KtExpression,
editor: Editor?,
type: KotlinType? = null,
receiverExpression: KtExpression? = null,
callback: (List<FunctionDescriptor>) -> Unit
) {
val functions = getApplicableComponentFunctions(contextExpression, type, receiverExpression)
if (functions.size <= 1) return callback(emptyList())
if (isUnitTestMode()) return callback(functions)
if (editor == null) return callback(emptyList())
val singleVariable = KotlinBundle.message("text.create.single.variable")
val listOfVariants = listOf(
singleVariable,
KotlinBundle.message("text.create.destructuring.declaration"),
)
JBPopupFactory.getInstance()
.createPopupChooserBuilder(listOfVariants)
.setMovable(true)
.setResizable(false)
.setRequestFocus(true)
.setItemChosenCallback { callback(if (it == singleVariable) emptyList() else functions) }
.createPopup()
.showInBestPositionFor(editor)
}
internal fun suggestNamesForComponent(descriptor: FunctionDescriptor, project: Project, validator: (String) -> Boolean): Set<String> {
return LinkedHashSet<String>().apply {
val descriptorName = descriptor.name.asString()
val componentName = (DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) as? PsiNamedElement)?.name
?: descriptorName
if (componentName == descriptorName) {
descriptor.returnType?.let { addAll(KotlinNameSuggester.suggestNamesByType(it, validator)) }
}
add(KotlinNameSuggester.suggestNameByName(componentName, validator))
}
} | apache-2.0 | ea835c42132bec5700ed7cd61dd5707d | 44.851485 | 158 | 0.759179 | 5.087912 | false | false | false | false |
spotify/heroic | heroic-core/src/main/java/com/spotify/heroic/shell/task/parameters/MetadataCountParameters.kt | 1 | 1444 | /*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.shell.task.parameters
import com.spotify.heroic.common.OptionalLimit
import org.kohsuke.args4j.Argument
import org.kohsuke.args4j.Option
import java.util.*
internal class MetadataCountParameters : QueryParamsBase() {
@Option(name = "-g", aliases = ["--group"], usage = "Backend group to use", metaVar = "<group>")
val group = Optional.empty<String>()
@Option(name = "--limit", usage = "Limit the number of deletes (default: alot)")
override val limit: OptionalLimit = OptionalLimit.empty()
@Argument
override val query = ArrayList<String>()
}
| apache-2.0 | a2fffbf78fd44b7d482b9d5a1c8109a9 | 37 | 100 | 0.734072 | 4.137536 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/resources/src/org/jetbrains/kotlin/idea/KotlinIconProvider.kt | 3 | 7988 | // 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
import com.intellij.icons.AllIcons
import com.intellij.ide.IconProvider
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.util.Iconable
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parentOfType
import com.intellij.ui.IconManager
import com.intellij.ui.RowIcon
import com.intellij.util.PlatformIcons
import org.jetbrains.kotlin.analysis.decompiled.light.classes.KtLightClassForDecompiledDeclarationBase
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.idea.KotlinIcons.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.utils.addToStdlib.ifTrue
import javax.swing.Icon
abstract class KotlinIconProvider : IconProvider(), DumbAware {
protected abstract fun isMatchingExpected(declaration: KtDeclaration): Boolean
private fun Icon.addExpectActualMarker(element: PsiElement): Icon {
val declaration = (element as? KtNamedDeclaration) ?: return this
val additionalIcon = when {
isExpectDeclaration(declaration) -> EXPECT
isMatchingExpected(declaration) -> ACTUAL
else -> return this
}
return RowIcon(2).apply {
setIcon(this@addExpectActualMarker, 0)
setIcon(additionalIcon, 1)
}
}
private tailrec fun isExpectDeclaration(declaration: KtDeclaration): Boolean {
if (declaration.hasExpectModifier()) {
return true
}
val containingDeclaration = declaration.containingClassOrObject ?: return false
return isExpectDeclaration(containingDeclaration)
}
override fun getIcon(psiElement: PsiElement, flags: Int): Icon? {
if (psiElement is KtFile) {
if (psiElement.isScript()) {
return when {
psiElement.name.endsWith(".gradle.kts") -> GRADLE_SCRIPT
else -> SCRIPT
}
}
val mainClass = getSingleClass(psiElement)
return if (mainClass != null) getIcon(mainClass, flags) else FILE
}
val result = psiElement.getBaseIcon()
if (flags and Iconable.ICON_FLAG_VISIBILITY > 0 && result != null && (psiElement is KtModifierListOwner && psiElement !is KtClassInitializer)) {
val list = psiElement.modifierList
val visibilityIcon = getVisibilityIcon(list)
val withExpectedActual: Icon = try {
result.addExpectActualMarker(psiElement)
} catch (indexNotReady: IndexNotReadyException) {
result
}
return createRowIcon(withExpectedActual, visibilityIcon)
}
return result
}
companion object {
fun isSingleClassFile(file: KtFile) = getSingleClass(file) != null
fun getSingleClass(file: KtFile): KtClassOrObject? =
getMainClass(file)?.takeIf {
file.declarations
.filterNot { it.isPrivate() || it is KtTypeAlias }
.size == 1
}
fun getMainClass(file: KtFile): KtClassOrObject? {
val classes = file.declarations.filterNot { it.isPrivate() }.filterIsInstance<KtClassOrObject>()
if (classes.size == 1 && StringUtil.getPackageName(file.name) == classes[0].name) {
return classes[0]
}
return null
}
private fun createRowIcon(baseIcon: Icon, visibilityIcon: Icon): RowIcon {
val rowIcon = RowIcon(2)
rowIcon.setIcon(baseIcon, 0)
rowIcon.setIcon(visibilityIcon, 1)
return rowIcon
}
fun getVisibilityIcon(list: KtModifierList?): Icon {
if (list != null) {
if (list.hasModifier(KtTokens.PRIVATE_KEYWORD)) {
return IconManager.getInstance().getPlatformIcon(com.intellij.ui.PlatformIcons.Private)
}
if (list.hasModifier(KtTokens.PROTECTED_KEYWORD)) {
return IconManager.getInstance().getPlatformIcon(com.intellij.ui.PlatformIcons.Protected)
}
if (list.hasModifier(KtTokens.INTERNAL_KEYWORD)) {
return IconManager.getInstance().getPlatformIcon(com.intellij.ui.PlatformIcons.Local)
}
}
return PlatformIcons.PUBLIC_ICON
}
fun PsiElement.getBaseIcon(): Icon? = when (this) {
is KtPackageDirective -> AllIcons.Nodes.Package
is KtFile, is KtLightClassForFacade -> FILE
is KtLightClassForSourceDeclaration -> navigationElement.getBaseIcon()
is KtNamedFunction -> when {
receiverTypeReference != null ->
if (KtPsiUtil.isAbstract(this)) ABSTRACT_EXTENSION_FUNCTION else EXTENSION_FUNCTION
getStrictParentOfType<KtNamedDeclaration>() is KtClass ->
if (KtPsiUtil.isAbstract(this)) PlatformIcons.ABSTRACT_METHOD_ICON else IconManager.getInstance().getPlatformIcon(
com.intellij.ui.PlatformIcons.Method)
else ->
FUNCTION
}
is KtConstructor<*> -> IconManager.getInstance().getPlatformIcon(com.intellij.ui.PlatformIcons.Method)
is KtLightMethod -> when(val u = unwrapped) {
is KtProperty -> if (!u.hasBody()) PlatformIcons.ABSTRACT_METHOD_ICON else IconManager.getInstance().getPlatformIcon(
com.intellij.ui.PlatformIcons.Method)
else -> IconManager.getInstance().getPlatformIcon(com.intellij.ui.PlatformIcons.Method)
}
is KtFunctionLiteral -> LAMBDA
is KtClass -> when {
isInterface() -> INTERFACE
isEnum() -> ENUM
isAnnotation() -> ANNOTATION
this is KtEnumEntry && getPrimaryConstructorParameterList() == null -> ENUM
else -> if (isAbstract()) ABSTRACT_CLASS else CLASS
}
is KtObjectDeclaration -> OBJECT
is KtParameter -> {
if (KtPsiUtil.getClassIfParameterIsProperty(this) != null) {
if (isMutable) FIELD_VAR else FIELD_VAL
} else
PARAMETER
}
is KtProperty -> if (isVar) FIELD_VAR else FIELD_VAL
is KtClassInitializer -> CLASS_INITIALIZER
is KtTypeAlias -> TYPE_ALIAS
is KtAnnotationEntry -> {
(shortName?.asString() == JvmFileClassUtil.JVM_NAME_SHORT).ifTrue {
val grandParent = parent.parent
if (grandParent is KtPropertyAccessor) {
grandParent.parentOfType<KtProperty>()?.getBaseIcon()
} else {
grandParent.getBaseIcon()
}
}
}
is PsiClass -> (this is KtLightClassForDecompiledDeclarationBase).ifTrue {
val origin = (this as? KtLightClass)?.kotlinOrigin
//TODO (light classes for decompiled files): correct presentation
if (origin != null) origin.getBaseIcon() else CLASS
}
else -> unwrapped?.takeIf { it != this }?.getBaseIcon()
}
}
}
| apache-2.0 | bbe537c24c91aa8cb63840d07e3f4290 | 43.377778 | 152 | 0.625438 | 5.415593 | false | false | false | false |
jwren/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/sorting/MLSorter.kt | 1 | 14867 | // Copyright 2000-2022 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.completion.ml.sorting
import com.intellij.codeInsight.completion.CompletionFinalSorter
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupManager
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.completion.ml.util.prefix
import com.intellij.completion.ml.util.queryLength
import com.intellij.completion.ml.util.RelevanceUtil
import com.intellij.textMatching.PrefixMatchingUtil
import com.intellij.completion.ml.features.RankingFeaturesOverrides
import com.intellij.completion.ml.performance.CompletionPerformanceTracker
import com.intellij.completion.ml.settings.CompletionMLRankingSettings
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.diagnostic.logger
import com.intellij.completion.ml.personalization.session.SessionFactorsUtils
import com.intellij.completion.ml.storage.MutableLookupStorage
import com.intellij.internal.ml.completion.DecoratingItemsPolicy
import com.intellij.lang.Language
import java.util.*
import java.util.concurrent.TimeUnit
@Suppress("DEPRECATION")
class MLSorterFactory : CompletionFinalSorter.Factory {
override fun newSorter() = MLSorter()
}
class MLSorter : CompletionFinalSorter() {
private companion object {
private val LOG = logger<MLSorter>()
private const val REORDER_ONLY_TOP_K = 5
}
private val cachedScore: MutableMap<LookupElement, ItemRankInfo> = IdentityHashMap()
private val reorderOnlyTopItems: Boolean = Registry.`is`("completion.ml.reorder.only.top.items", true)
override fun getRelevanceObjects(items: MutableIterable<LookupElement>): Map<LookupElement, List<Pair<String, Any>>> {
if (cachedScore.isEmpty()) {
return items.associate { it to listOf(Pair.create(FeatureUtils.ML_RANK, FeatureUtils.NONE as Any)) }
}
if (hasUnknownFeatures(items)) {
return items.associate { it to listOf(Pair.create(FeatureUtils.ML_RANK, FeatureUtils.UNDEFINED as Any)) }
}
if (!isCacheValid(items)) {
return items.associate { it to listOf(Pair.create(FeatureUtils.ML_RANK, FeatureUtils.INVALID_CACHE as Any)) }
}
return items.associate {
val result = mutableListOf<Pair<String, Any>>()
val cached = cachedScore[it]
if (cached != null) {
result.add(Pair.create(FeatureUtils.ML_RANK, cached.mlRank))
result.add(Pair.create(FeatureUtils.BEFORE_ORDER, cached.positionBefore))
}
it to result
}
}
private fun isCacheValid(items: Iterable<LookupElement>): Boolean {
return items.map { cachedScore[it]?.prefixLength }.toSet().size == 1
}
private fun hasUnknownFeatures(items: Iterable<LookupElement>) = items.any {
val score = cachedScore[it]
score?.mlRank == null
}
override fun sort(items: MutableIterable<LookupElement>, parameters: CompletionParameters): Iterable<LookupElement?> {
val lookup = LookupManager.getActiveLookup(parameters.editor) as? LookupImpl ?: return items
val lookupStorage = MutableLookupStorage.get(lookup) ?: return items
// Do nothing if unable to reorder items or to log the weights
if (!lookupStorage.shouldComputeFeatures()) return items
val startedTimestamp = System.currentTimeMillis()
val queryLength = lookup.queryLength()
val prefix = lookup.prefix()
val element2score = mutableMapOf<LookupElement, Double?>()
val elements = items.toList()
val positionsBefore = elements.withIndex().associate { it.value to it.index }
tryFillFromCache(element2score, elements, queryLength)
val itemsForScoring = if (element2score.size == elements.size) emptyList() else elements
calculateScores(element2score, itemsForScoring, positionsBefore,
queryLength, prefix, lookup, lookupStorage, parameters)
val finalRanking = sortByMlScores(elements, element2score, positionsBefore, lookupStorage, lookup)
lookupStorage.performanceTracker.sortingPerformed(itemsForScoring.size, System.currentTimeMillis() - startedTimestamp)
return finalRanking
}
private fun tryFillFromCache(element2score: MutableMap<LookupElement, Double?>,
items: List<LookupElement>,
queryLength: Int) {
for ((position, element) in items.withIndex()) {
val cachedInfo = getCachedRankInfo(element, queryLength, position)
if (cachedInfo == null) return
element2score[element] = cachedInfo.mlRank
}
}
private fun calculateScores(element2score: MutableMap<LookupElement, Double?>,
items: List<LookupElement>,
positionsBefore: Map<LookupElement, Int>,
queryLength: Int,
prefix: String,
lookup: LookupImpl,
lookupStorage: MutableLookupStorage,
parameters: CompletionParameters) {
if (items.isEmpty()) return
val rankingModel = lookupStorage.model
lookupStorage.initUserFactors(lookup.project)
val meaningfulRelevanceExtractor = MeaningfulFeaturesExtractor()
val relevanceObjects = lookup.getRelevanceObjects(items, false)
val calculatedElementFeatures = mutableListOf<ElementFeatures>()
for (element in items) {
val position = positionsBefore.getValue(element)
val (relevance, additional) = RelevanceUtil.asRelevanceMaps(relevanceObjects.getOrDefault(element, emptyList()))
SessionFactorsUtils.saveElementFactorsTo(additional, lookupStorage, element)
calculateAdditionalFeaturesTo(additional, element, queryLength, prefix.length, position, items.size, parameters)
lookupStorage.performanceTracker.trackElementFeaturesCalculation(PrefixMatchingUtil.baseName) {
PrefixMatchingUtil.calculateFeatures(element.lookupString, prefix, additional)
}
meaningfulRelevanceExtractor.processFeatures(relevance)
calculatedElementFeatures.add(ElementFeatures(relevance, additional))
}
val lookupFeatures = mutableMapOf<String, Any>()
for (elementFeatureProvider in LookupFeatureProvider.forLanguage(lookupStorage.language)) {
val features = elementFeatureProvider.calculateFeatures(calculatedElementFeatures)
lookupFeatures.putAll(features)
}
val additionalContextFeatures = mutableMapOf<String, String>()
for (contextFeatureProvider in AdditionalContextFeatureProvider.forLanguage(lookupStorage.language)) {
val features = contextFeatureProvider.calculateFeatures(lookupStorage.contextFactors)
additionalContextFeatures.putAll(features)
}
val contextFactors = lookupStorage.contextFactors + additionalContextFeatures
val commonSessionFactors = SessionFactorsUtils.updateSessionFactors(lookupStorage, items)
val meaningfulRelevance = meaningfulRelevanceExtractor.meaningfulFeatures()
val features = RankingFeatures(lookupStorage.userFactors, contextFactors, commonSessionFactors, lookupFeatures, meaningfulRelevance)
val tracker = ModelTimeTracker()
for ((i, element) in items.withIndex()) {
val (relevance, additional) = overrideElementFeaturesIfNeeded(calculatedElementFeatures[i], lookupStorage.language)
val score = tracker.measure {
val position = positionsBefore.getValue(element)
val elementFeatures = features.withElementFeatures(relevance, additional)
return@measure calculateElementScore(rankingModel, element, position, elementFeatures, queryLength)
}
element2score[element] = score
additional.putAll(relevance)
lookupStorage.fireElementScored(element, additional, score)
}
tracker.finished(lookupStorage.performanceTracker)
}
private fun overrideElementFeaturesIfNeeded(elementFeatures: ElementFeatures, language: Language): ElementFeatures {
for (it in RankingFeaturesOverrides.forLanguage(language)) {
val overrides = it.getMlElementFeaturesOverrides(elementFeatures.additional)
elementFeatures.additional.putAll(overrides)
if (overrides.isNotEmpty())
LOG.debug("The next ML features was overridden: [${overrides.map { it.key }.joinToString()}]")
val relevanceOverrides = it.getDefaultWeigherFeaturesOverrides(elementFeatures.relevance)
elementFeatures.relevance.putAll(relevanceOverrides)
if (relevanceOverrides.isNotEmpty())
LOG.debug("The next default weigher features was overridden: [${relevanceOverrides.map { it.key }.joinToString()}]")
}
return elementFeatures
}
private fun sortByMlScores(items: List<LookupElement>,
element2score: Map<LookupElement, Double?>,
positionsBefore: Map<LookupElement, Int>,
lookupStorage: MutableLookupStorage,
lookup: LookupImpl): Iterable<LookupElement> {
val shouldSort = element2score.values.none { it == null } && lookupStorage.shouldReRank()
if (LOG.isDebugEnabled) {
LOG.debug("ML sorting in completion used=$shouldSort for language=${lookupStorage.language.id}")
}
if (shouldSort) {
lookupStorage.fireReorderedUsingMLScores()
val decoratingItemsPolicy = lookupStorage.model?.decoratingPolicy() ?: DecoratingItemsPolicy.DISABLED
val topItemsCount = if (reorderOnlyTopItems) REORDER_ONLY_TOP_K else Int.MAX_VALUE
return items
.reorderByMLScores(element2score, topItemsCount)
.markRelevantItemsIfNeeded(element2score, lookup, decoratingItemsPolicy)
.addDiagnosticsIfNeeded(positionsBefore, topItemsCount, lookup)
}
return items
}
private fun calculateAdditionalFeaturesTo(
additionalMap: MutableMap<String, Any>,
lookupElement: LookupElement,
oldQueryLength: Int,
prefixLength: Int,
position: Int,
itemsCount: Int,
parameters: CompletionParameters) {
additionalMap["position"] = position
additionalMap["relative_position"] = position.toDouble() / itemsCount
additionalMap["query_length"] = oldQueryLength // old version of prefix_length feature
additionalMap["prefix_length"] = prefixLength
additionalMap["result_length"] = lookupElement.lookupString.length
additionalMap["auto_popup"] = parameters.isAutoPopup
additionalMap["completion_type"] = parameters.completionType.toString()
additionalMap["invocation_count"] = parameters.invocationCount
}
private fun Iterable<LookupElement>.reorderByMLScores(element2score: Map<LookupElement, Double?>, toReorder: Int): Iterable<LookupElement> {
val result = this
.sortedByDescending { element2score.getValue(it) }
.removeDuplicatesIfNeeded()
.take(toReorder)
.toCollection(linkedSetOf())
result.addAll(this)
return result
}
private fun Iterable<LookupElement>.removeDuplicatesIfNeeded(): Iterable<LookupElement> =
if (Registry.`is`("completion.ml.reorder.without.duplicates", false)) this.distinctBy { it.lookupString } else this
private fun Iterable<LookupElement>.addDiagnosticsIfNeeded(positionsBefore: Map<LookupElement, Int>, reordered: Int, lookup: LookupImpl): Iterable<LookupElement> {
if (CompletionMLRankingSettings.getInstance().isShowDiffEnabled) {
var positionChanged = false
this.forEachIndexed { position, element ->
val before = positionsBefore.getValue(element)
if (before < reordered || position < reordered) {
val diff = position - before
positionChanged = positionChanged || diff != 0
ItemsDecoratorInitializer.itemPositionChanged(element, diff)
}
}
ItemsDecoratorInitializer.markAsReordered(lookup, positionChanged)
}
return this
}
private fun Iterable<LookupElement>.markRelevantItemsIfNeeded(element2score: Map<LookupElement, Double?>,
lookup: LookupImpl,
decoratingItemsPolicy: DecoratingItemsPolicy): Iterable<LookupElement> {
if (CompletionMLRankingSettings.getInstance().isDecorateRelevantEnabled) {
val relevantItems = decoratingItemsPolicy.itemsToDecorate(this.map { element2score[it] ?: 0.0 })
for (index in relevantItems) {
ItemsDecoratorInitializer.markAsRelevant(lookup, this.elementAt(index))
}
}
return this
}
private fun getCachedRankInfo(element: LookupElement, prefixLength: Int, position: Int): ItemRankInfo? {
val cached = cachedScore[element]
if (cached != null && prefixLength == cached.prefixLength && cached.positionBefore == position) {
return cached
}
return null
}
/**
* Null means we encountered unknown features and are unable to score
*/
private fun calculateElementScore(ranker: RankingModelWrapper?,
element: LookupElement,
position: Int,
features: RankingFeatures,
prefixLength: Int): Double? {
val mlRank: Double? = if (ranker != null && ranker.canScore(features)) ranker.score(features) else null
val info = ItemRankInfo(position, mlRank, prefixLength)
cachedScore[element] = info
return info.mlRank
}
/**
* Extracts features that have different values
*/
private class MeaningfulFeaturesExtractor {
private val meaningful = mutableSetOf<String>()
private val values = mutableMapOf<String, Any>()
fun processFeatures(features: Map<String, Any>) {
for (feature in features) {
when (values[feature.key]) {
null -> values[feature.key] = feature.value
feature.value -> Unit
else -> meaningful.add(feature.key)
}
}
}
fun meaningfulFeatures(): Set<String> = meaningful
}
/*
* Measures time on getting predictions from the ML model
*/
private class ModelTimeTracker {
private var itemsScored: Int = 0
private var timeSpent: Long = 0L
fun measure(scoringFun: () -> Double?): Double? {
val start = System.nanoTime()
val result = scoringFun.invoke()
if (result != null) {
itemsScored += 1
timeSpent += System.nanoTime() - start
}
return result
}
fun finished(performanceTracker: CompletionPerformanceTracker) {
if (itemsScored != 0) {
performanceTracker.itemsScored(itemsScored, TimeUnit.NANOSECONDS.toMillis(timeSpent))
}
}
}
}
private data class ItemRankInfo(val positionBefore: Int, val mlRank: Double?, val prefixLength: Int)
| apache-2.0 | 47cceed0f8ed4c74254c64766660aa3c | 42.855457 | 165 | 0.715208 | 4.80666 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/groovy/src/org/jetbrains/kotlin/idea/groovy/inspections/DeprecatedGradleDependencyInspection.kt | 3 | 5464 | // 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.groovy.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.util.text.VersionComparatorUtil
import org.jetbrains.kotlin.idea.configuration.allModules
import org.jetbrains.kotlin.idea.configuration.getWholeModuleGroup
import org.jetbrains.kotlin.idea.configuration.parseExternalLibraryName
import org.jetbrains.kotlin.idea.extensions.gradle.SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS
import org.jetbrains.kotlin.idea.inspections.ReplaceStringInDocumentFix
import org.jetbrains.kotlin.idea.versions.DEPRECATED_LIBRARIES_INFORMATION
import org.jetbrains.kotlin.idea.versions.DeprecatedLibInfo
import org.jetbrains.kotlin.idea.versions.LibInfo
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.plugins.groovy.codeInspection.BaseInspection
import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression
private val LibInfo.gradleMarker get() = "$groupId:$name"
class DeprecatedGradleDependencyInspection : BaseInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(): BaseInspectionVisitor = DependencyFinder()
private open class DependencyFinder : KotlinGradleInspectionVisitor() {
override fun visitClosure(closure: GrClosableBlock) {
super.visitClosure(closure)
val dependenciesCall = closure.getStrictParentOfType<GrMethodCall>() ?: return
if (dependenciesCall.invokedExpression.text != "dependencies") return
val dependencyEntries = GradleHeuristicHelper.findStatementWithPrefixes(
closure, SCRIPT_PRODUCTION_DEPENDENCY_STATEMENTS
)
for (dependencyStatement in dependencyEntries) {
visitDependencyEntry(dependencyStatement)
}
}
open fun visitDependencyEntry(dependencyStatement: GrCallExpression) {
for (outdatedInfo in DEPRECATED_LIBRARIES_INFORMATION) {
val dependencyText = dependencyStatement.text
val libMarker = outdatedInfo.old.gradleMarker
if (dependencyText.contains(libMarker)) {
val afterMarkerChar = dependencyText.substringAfter(libMarker).getOrNull(0)
if (!(afterMarkerChar == '\'' || afterMarkerChar == '"' || afterMarkerChar == ':')) {
continue
}
val libVersion =
DifferentStdlibGradleVersionInspection.getRawResolvedLibVersion(
dependencyStatement.containingFile, outdatedInfo.old.groupId, listOf(outdatedInfo.old.name)
) ?: libraryVersionFromOrderEntry(dependencyStatement.containingFile, outdatedInfo.old.name)
if (libVersion != null && VersionComparatorUtil.COMPARATOR.compare(
libVersion,
outdatedInfo.outdatedAfterVersion
) >= 0
) {
val reportOnElement = reportOnElement(dependencyStatement, outdatedInfo)
registerError(
reportOnElement, outdatedInfo.message,
arrayOf(ReplaceStringInDocumentFix(reportOnElement, outdatedInfo.old.name, outdatedInfo.new.name)),
ProblemHighlightType.LIKE_DEPRECATED
)
break
}
}
}
}
private fun reportOnElement(classpathEntry: GrCallExpression, deprecatedInfo: DeprecatedLibInfo): PsiElement {
val indexOf = classpathEntry.text.indexOf(deprecatedInfo.old.name)
if (indexOf < 0) return classpathEntry
return classpathEntry.findElementAt(indexOf) ?: classpathEntry
}
}
companion object {
fun libraryVersionFromOrderEntry(file: PsiFile, libraryId: String): String? {
val module = ProjectRootManager.getInstance(file.project).fileIndex.getModuleForFile(file.virtualFile) ?: return null
val libMarker = ":$libraryId:"
for (moduleInGroup in module.getWholeModuleGroup().allModules()) {
var libVersion: String? = null
ModuleRootManager.getInstance(moduleInGroup).orderEntries().forEachLibrary { library ->
if (library.name?.contains(libMarker) == true) {
libVersion = parseExternalLibraryName(library)?.version
}
// Continue if nothing is found
libVersion == null
}
if (libVersion != null) {
return libVersion
}
}
return null
}
}
} | apache-2.0 | 59e46f791ab612db9c022468c4f8901d | 46.112069 | 158 | 0.666911 | 5.806589 | false | false | false | false |
kpi-ua/ecampus-client-android | app/src/main/java/com/goldenpiedevs/schedule/app/core/utils/util/Utils.kt | 1 | 935 | package com.goldenpiedevs.schedule.app.core.utils.util
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import com.goldenpiedevs.schedule.app.ui.main.MainActivity
/**
* Created by Anton. A on 23.03.2019.
* Version 1.0
*/
const val NO_INTERNET = -1
const val RESULT_OK = 200
const val RESULT_FAILED = 500
fun Context.restartApp() {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
this.startActivity(intent)
if (this is Activity) {
this.finish()
}
Runtime.getRuntime().exit(0)
}
fun Context.isNetworkAvailable(): Boolean {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
val activeNetworkInfo = connectivityManager!!.activeNetworkInfo
return activeNetworkInfo != null && activeNetworkInfo.isConnected
} | apache-2.0 | 3a1f7cd848f0093543552eaa47d0d45f | 25 | 100 | 0.75508 | 4.211712 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplacePutWithAssignmentInspection.kt | 1 | 5177 | // 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.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.analysis.analyzeAsReplacement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.util.calleeTextRangeInThis
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.resolvedCallUtil.getExplicitReceiverValue
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf
import org.jetbrains.kotlin.resolve.descriptorUtil.overriddenTreeAsSequence
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class ReplacePutWithAssignmentInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java
) {
override fun isApplicable(element: KtDotQualifiedExpression): Boolean {
if (element.receiverExpression is KtSuperExpression) return false
val callExpression = element.callExpression
if (callExpression?.valueArguments?.size != 2) return false
val calleeExpression = callExpression.calleeExpression as? KtNameReferenceExpression ?: return false
if (calleeExpression.getReferencedName() !in compatibleNames) return false
val context = element.analyze()
if (element.isUsedAsExpression(context)) return false
// This fragment had to be added because of incorrect behaviour of isUsesAsExpression
// TODO: remove it after fix of KT-25682
val binaryExpression = element.getStrictParentOfType<KtBinaryExpression>()
val right = binaryExpression?.right
if (binaryExpression?.operationToken == KtTokens.ELVIS &&
right != null && (right == element || KtPsiUtil.deparenthesize(right) == element)
) return false
val resolvedCall = element.getResolvedCall(context)
val receiverType = resolvedCall?.getExplicitReceiverValue()?.type ?: return false
val receiverClass = receiverType.constructor.declarationDescriptor as? ClassDescriptor ?: return false
if (!receiverClass.isSubclassOf(DefaultBuiltIns.Instance.mutableMap)) return false
val overriddenTree =
resolvedCall.resultingDescriptor.safeAs<CallableMemberDescriptor>()?.overriddenTreeAsSequence(true) ?: return false
if (overriddenTree.none { it.fqNameOrNull() == mutableMapPutFqName }) return false
val assignment = createAssignmentExpression(element) ?: return false
val newContext = assignment.analyzeAsReplacement(element, context)
return assignment.left.getResolvedCall(newContext)?.resultingDescriptor?.fqNameOrNull() == collectionsSetFqName
}
override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) {
val assignment = createAssignmentExpression(element) ?: return
element.replace(assignment)
}
private fun createAssignmentExpression(element: KtDotQualifiedExpression): KtBinaryExpression? {
val valueArguments = element.callExpression?.valueArguments ?: return null
val firstArg = valueArguments[0]?.getArgumentExpression() ?: return null
val secondArg = valueArguments[1]?.getArgumentExpression() ?: return null
val label = if (secondArg is KtLambdaExpression) {
val returnLabel = secondArg.findDescendantOfType<KtReturnExpression>()?.getLabelName()
compatibleNames.firstOrNull { it == returnLabel }?.plus("@") ?: ""
} else ""
return KtPsiFactory(element).createExpressionByPattern(
"$0[$1] = $label$2",
element.receiverExpression, firstArg, secondArg,
reformat = false
) as? KtBinaryExpression
}
override fun inspectionHighlightRangeInElement(element: KtDotQualifiedExpression) = element.calleeTextRangeInThis()
override fun inspectionText(element: KtDotQualifiedExpression): String =
KotlinBundle.message("map.put.should.be.converted.to.assignment")
override val defaultFixText get() = KotlinBundle.message("convert.put.to.assignment")
companion object {
private val compatibleNames = setOf("put")
private val collectionsSetFqName = FqName("kotlin.collections.set")
private val mutableMapPutFqName = FqName("kotlin.collections.MutableMap.put")
}
} | apache-2.0 | b66ab8d34705e2c79da948a258f06abf | 51.836735 | 158 | 0.765115 | 5.51919 | false | false | false | false |
zielu/GitToolBox | src/test/kotlin/zielu/gittoolbox/config/MergedProjectConfigTest.kt | 1 | 1896 | package zielu.gittoolbox.config
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertAll
internal class MergedProjectConfigTest {
private val appConfig = GitToolBoxConfig2()
private val prjConfig = GitToolBoxConfigPrj()
@Test
fun `should change legacy value if legacy mode`() {
// given
val merged = createMerged(true)
// when
merged.setCommitMessageValidation(true)
// then
assertAll(
{ assertThat(prjConfig.commitMessageValidation).isTrue },
{ assertThat(appConfig.commitMessageValidationEnabled).isFalse() },
{ assertThat(prjConfig.commitMessageValidationOverride.enabled).isFalse() },
{ assertThat(prjConfig.commitMessageValidationOverride.value).isFalse() }
)
}
@Test
fun `should not change project if value same as app level`() {
// given
appConfig.commitMessageValidationEnabled = true
val merged = createMerged(false)
// when
merged.setCommitMessageValidation(true)
// then
assertAll(
{ assertThat(merged.commitMessageValidation()).isTrue },
{ assertThat(prjConfig.commitMessageValidationOverride.enabled).isFalse },
{ assertThat(prjConfig.commitMessageValidationOverride.value).isFalse }
)
}
@Test
fun `should create project override if value different than app level`() {
// given
val merged = createMerged(false)
// when
merged.setCommitMessageValidation(true)
// then
assertAll(
{ assertThat(appConfig.commitMessageValidationEnabled).isFalse },
{ assertThat(prjConfig.commitMessageValidationOverride.enabled).isTrue },
{ assertThat(prjConfig.commitMessageValidationOverride.value).isTrue() }
)
}
private fun createMerged(useLegacy: Boolean): MergedProjectConfig {
return MergedProjectConfig(appConfig, prjConfig, useLegacy)
}
}
| apache-2.0 | 5c1b8c482a2358be5e796cd05e4a1884 | 28.625 | 82 | 0.727848 | 4.62439 | false | true | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/viewer/GHPRSimpleOnesideDiffViewerReviewThreadsHandler.kt | 10 | 2929 | // 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.viewer
import com.intellij.diff.tools.simple.SimpleOnesideDiffViewer
import com.intellij.diff.util.LineRange
import com.intellij.diff.util.Range
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.collaboration.ui.codereview.diff.EditorComponentInlaysManager
import org.jetbrains.plugins.github.pullrequest.comment.GHPRCommentsUtil
import org.jetbrains.plugins.github.pullrequest.comment.GHPRDiffReviewThreadMapping
import org.jetbrains.plugins.github.pullrequest.comment.ui.*
import com.intellij.collaboration.ui.SingleValueModel
class GHPRSimpleOnesideDiffViewerReviewThreadsHandler(reviewProcessModel: GHPRReviewProcessModel,
commentableRangesModel: SingleValueModel<List<Range>?>,
reviewThreadsModel: SingleValueModel<List<GHPRDiffReviewThreadMapping>?>,
viewer: SimpleOnesideDiffViewer,
componentsFactory: GHPRDiffEditorReviewComponentsFactory,
cumulative: Boolean)
: GHPRDiffViewerBaseReviewThreadsHandler<SimpleOnesideDiffViewer>(commentableRangesModel, reviewThreadsModel, viewer) {
private val commentableRanges = SingleValueModel<List<LineRange>>(emptyList())
private val editorThreads = GHPREditorReviewThreadsModel()
override val viewerReady: Boolean = true
init {
val inlaysManager = EditorComponentInlaysManager(viewer.editor as EditorImpl)
val gutterIconRendererFactory = GHPRDiffEditorGutterIconRendererFactoryImpl(reviewProcessModel,
inlaysManager,
componentsFactory,
cumulative) { line ->
val (startLine, endLine) = getCommentLinesRange(viewer.editor, line)
GHPRCommentLocation(viewer.side, endLine, startLine)
}
GHPREditorCommentableRangesController(commentableRanges, gutterIconRendererFactory, viewer.editor)
GHPREditorReviewThreadsController(editorThreads, componentsFactory, inlaysManager)
}
override fun markCommentableRanges(ranges: List<Range>?) {
commentableRanges.value = ranges?.let { GHPRCommentsUtil.getLineRanges(it, viewer.side) }.orEmpty()
}
override fun showThreads(threads: List<GHPRDiffReviewThreadMapping>?) {
editorThreads.update(threads
?.filter { it.diffSide == viewer.side }
?.groupBy({ it.fileLineIndex }, { it.thread }).orEmpty())
}
}
| apache-2.0 | c385a074e3f2a4dafd800ba61deb635e | 56.431373 | 140 | 0.665073 | 5.965377 | false | false | false | false |
erdo/asaf-project | example-kt-08ktor/src/main/java/foo/bar/example/forektorkt/api/fruits/FruitService.kt | 1 | 2318 | package foo.bar.example.forektorkt.api.fruits
import io.ktor.client.*
import io.ktor.client.request.*
/**
* These stubs are hosted at https://www.mocky.io/
*
* success example response:
* http://www.mocky.io/v2/59efa0132e0000ef331c5f9b
*
* fail example response:
* http://www.mocky.io/v2/59ef2a6c2e00002a1a1c5dea
*/
data class FruitService(
val getFruitsSimulateOk: suspend () -> List<FruitPojo>,
val getFruitsSimulateNotAuthorised: suspend () -> List<FruitPojo>,
// call chain to demonstrate carryOn
val createUser: suspend () -> UserPojo,
val createUserTicket: suspend (Int) -> TicketPojo,
val getEstimatedWaitingTime: suspend (String) -> TimePojo,
val cancelTicket: suspend (String) -> TicketResultPojo,
val confirmTicket: suspend (String) -> TicketResultPojo,
val claimFreeFruit: suspend (String) -> List<FruitPojo>
) {
companion object {
fun create(httpClient: HttpClient): FruitService {
val baseUrl = "http://www.mocky.io/v2/"
val mediumDelay = 3
val smallDelay = 1
return FruitService(
getFruitsSimulateOk = { httpClient.get("${baseUrl}59efa0132e0000ef331c5f9b/?mocky-delay=${mediumDelay}s") },
getFruitsSimulateNotAuthorised = { httpClient.get("${baseUrl}59ef2a6c2e00002a1a1c5dea/?mocky-delay=${mediumDelay}s") },
createUser = { httpClient.get("${baseUrl}5de410e83000002b009f78f8/?mocky-delay=${smallDelay}s") },
createUserTicket = { userId -> httpClient.get("${baseUrl}5de4112e3000002b009f78f9/?userId=${userId}&mocky-delay=${smallDelay}s") },
getEstimatedWaitingTime = { ticketRef -> httpClient.get("${baseUrl}5de4114830000062009f78fa/?ticketRef=${ticketRef}&mocky-delay=${smallDelay}s") },
cancelTicket = { ticketRef -> httpClient.get("${baseUrl}5de411c63000002b009f78fc/?ticketRef=${ticketRef}&mocky-delay=${smallDelay}s") },
confirmTicket = { ticketRef -> httpClient.get("${baseUrl}5de411af3000000e009f78fb/?ticketRef=${ticketRef}&mocky-delay=${smallDelay}s") },
claimFreeFruit = { ticketRef -> httpClient.get("${baseUrl}59efa0132e0000ef331c5f9b/?ticketRef=${ticketRef}&mocky-delay=${smallDelay}s") }
)
}
}
}
| apache-2.0 | 088e9f4f4aef3781ab2390bd206cd11b | 47.291667 | 167 | 0.666091 | 3.538931 | false | false | false | false |
douzifly/clear-todolist | app/src/main/java/douzifly/list/model/ThingsManager.kt | 1 | 8023 | package douzifly.list.model
import com.activeandroid.query.Delete
import com.activeandroid.query.Select
import douzifly.list.ListApplication
import douzifly.list.R
import douzifly.list.alarm.Alarm
import douzifly.list.settings.Settings
import douzifly.list.utils.bg
import douzifly.list.utils.logd
import java.util.*
/**
* Created by liuxiaoyuan on 2015/10/2.
*/
object ThingsManager {
val TAG = "ThingsManager"
// current things
var groups: MutableList<ThingGroup> = arrayListOf()
fun loadFromDb() {
"load from db".logd(TAG)
groups = Select().from(ThingGroup::class.java).execute()
if (groups.size == 0) {
// add default group and save to database
val homeGroup = ThingGroup(ListApplication.appContext!!.resources.getString(R.string.default_list))
homeGroup.isDefault = true
homeGroup.creationTime = Date().time
homeGroup.save()
Settings.selectedGroupId = homeGroup.id
groups.add(homeGroup)
}
groups.forEach {
group ->
loadThingsCount(group)
}
}
private fun loadThings(group: ThingGroup) {
if (group.thingsLoaded) return
group.things.addAll(
Select().from(Thing::class.java).where("pid=${group.id}").execute()
)
group.things.forEach {
thing ->
thing.group = group
}
group.thingsLoaded = true
sort(group.things)
}
private fun loadThingsCount(group: ThingGroup) {
group.inCompleteThingsCount =
Select().from(Thing::class.java).where("pid=${group.id} and isComplete=0").count()
}
fun getThingsByGroupId(groupId: Long): List<Thing> {
"getThingsByGroupId: $groupId".logd("xxxx")
if (groupId == ThingGroup.SHOW_ALL_GROUP_ID) {
return allThings;
}
val group = getGroupByGroupId(groupId)
return group?.things ?: arrayListOf()
}
fun getGroupByGroupId(groupId: Long): ThingGroup? {
groups.forEach {
group ->
if (group.id == groupId) {
if (!group.thingsLoaded) {
loadThings(group)
}
return group
}
}
return null
}
fun getThingByIdAtCurrentGroup(thingId: Long): Thing? {
if (Settings.selectedGroupId == ThingGroup.SHOW_ALL_GROUP_ID) {
allThings.forEach { thing ->
if (thing.id == thingId)
return thing
}
} else {
return getGroupByGroupId(Settings.selectedGroupId)?.findThing(thingId)
}
return null
}
fun getThingById(id: Long): Thing? {
return allThings.find { thing->
thing.id == id
}
}
private var allThings: MutableList<Thing> = arrayListOf()
get() {
if (field.size > 0) {
return field
}
groups.forEach {
group ->
if (!group.thingsLoaded) {
loadThings(group)
}
"add things to all things, count: ${group.things.size} group: ${group.title}".logd("xxxx")
field.addAll(group.things)
}
sort(field)
return field
}
private set
val allThingsInComplete: Int
get() {
return groups.map {
group ->
group.inCompleteThingsCount
}.reduce { a, b -> a + b }
}
fun addGroup(title: String) {
val group = ThingGroup(title)
group.creationTime = Date().time
group.save()
groups.add(group)
}
fun release() {
groups.clear()
}
fun swapThings(group: ThingGroup, fromPosition: Int, toPosition: Int): Boolean {
val thingA = group.things[fromPosition]
val thingB = group.things[toPosition]
if (thingA.isComplete || thingB.isComplete) {
return false
}
thingA.position = toPosition
thingB.position = fromPosition
group.things[fromPosition] = thingB
group.things[toPosition] = thingA
bg {
thingA.save()
thingB.save()
}
return true
}
fun addThing(group: ThingGroup, text: String, content: String, reminder: Long, color: Int, isComplete: Boolean = false, creationTime: Long? = null) {
val t = Thing(text, group.id, color)
t.creationTime = creationTime ?: Date().time
t.reminderTime = reminder
t.content = content
t.position = group.things.size
t.group = group
t.isComplete = isComplete
t.save()
allThings.add(t)
sort(allThings)
group.things.add(t)
group.save()
if (!isComplete) {
group.inCompleteThingsCount++
}
sort(group.things)
if (reminder > System.currentTimeMillis()) {
val subLen = if (t.content.length > 10) 10 else t.content.length
val content = if (t.title.isNotBlank()) t.title else t.content.substring(0, subLen)
Alarm.setAlarm(t.id, reminder, content, color)
}
}
fun saveThing(thing: Thing, newGroup: ThingGroup?) {
if (newGroup != null && newGroup.id != thing.group!!.id) {
remove(thing)
addThing(newGroup, thing.title, thing.content, thing.reminderTime, thing.color, thing.isComplete, thing.creationTime)
} else {
thing.save()
}
if (thing.reminderTime > System.currentTimeMillis()) {
val subLen = if (thing.content.length > 10) 10 else thing.content.length
val content = if (thing.title.isNotBlank()) thing.title else thing.content.substring(0, subLen)
Alarm.setAlarm(thing.id, thing.reminderTime, content, thing.color)
}
}
fun remove(thing: Thing) {
val group = thing.group ?: return
val ok = group.things.remove(thing)
if (!ok) return
if (!thing.isComplete) {
group.inCompleteThingsCount--
}
thing.delete()
allThings.remove(thing)
sort(allThings)
}
fun removeGroup(id: Long): Boolean {
if (id == ThingGroup.SHOW_ALL_GROUP_ID) {
return false
}
groups.forEach {
group ->
if (group.id == id) {
if (group.isDefault) {
// cant delete default
return false
}
group.things.forEach {
thing ->
allThings.remove(thing)
}
groups.remove(group)
group.delete()
Delete().from(Thing::class.java).where("pid=${group.id}").execute<Thing>()
return true
}
}
return false
}
fun makeComplete(thing: Thing, complete: Boolean) {
val group = thing.group ?: return
thing.isComplete = complete
if (complete) {
group.inCompleteThingsCount--
} else {
group.inCompleteThingsCount++
}
thing.save()
sort(group.things)
sort(allThings)
}
fun isShowAllGroup() = Settings.selectedGroupId == ThingGroup.SHOW_ALL_GROUP_ID
private fun sort(things: MutableList<Thing>) {
if (things.size < 2) {
return
}
"beforeSort:".logd("MainActivity")
things.forEach { t ->
"${t.title} ${t.hashCode()}".logd("douzifly.list.ui.home.MainActivity")
}
Collections.sort(things, Comparator { t: Thing, t1: Thing ->
return@Comparator t.compareTo(t1)
})
"afterSort:".logd("MainActivity")
things.forEach { t ->
"${t.title} iscompelte: ${t.isComplete} ${t.hashCode()}".logd("MainActivity")
}
}
}
| gpl-3.0 | e37ceca91cfa59623f03931095b4e4e2 | 27.859712 | 153 | 0.545806 | 4.369826 | false | false | false | false |
TachiWeb/TachiWeb-Server | TachiServer/src/main/java/xyz/nulldev/ts/api/v2/java/model/library/LibraryFlags.kt | 1 | 1376 | package xyz.nulldev.ts.api.v2.java.model.library
import xyz.nulldev.ts.api.v2.java.model.FilterStatus
import xyz.nulldev.ts.api.v2.java.model.SortDirection
data class LibraryFlags(
val filters: List<LibraryFilter>,
val sort: LibrarySort,
var display: DisplayType,
var showDownloadBadges: Boolean
) {
companion object {
private val DEFAULT =
LibraryFlags(
filters = mutableListOf(
LibraryFilter(FilterType.DOWNLOADED, FilterStatus.ANY),
LibraryFilter(FilterType.UNREAD, FilterStatus.ANY),
LibraryFilter(FilterType.COMPLETED, FilterStatus.ANY)
),
sort = LibrarySort(LibrarySortType.ALPHA, SortDirection.ASCENDING),
display = DisplayType.GRID,
showDownloadBadges = false
)
}
}
data class LibraryFilter(var type: FilterType, var status: FilterStatus)
data class LibrarySort(var type: LibrarySortType,
var direction: SortDirection)
enum class LibrarySortType {
ALPHA,
LAST_READ,
LAST_UPDATED,
UNREAD,
TOTAL,
SOURCE
}
enum class FilterType {
DOWNLOADED,
UNREAD,
COMPLETED
}
enum class DisplayType {
GRID,
LIST
}
| apache-2.0 | 12f6ea92260692051ab8b36de0c58032 | 26.52 | 91 | 0.590843 | 4.794425 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/categories/editor/CategoryEditorViewState.kt | 1 | 2157 | package ch.rmy.android.http_shortcuts.activities.categories.editor
import android.graphics.Color
import ch.rmy.android.framework.utils.localization.Localizable
import ch.rmy.android.framework.viewmodel.viewstate.DialogState
import ch.rmy.android.http_shortcuts.activities.categories.editor.models.CategoryBackground
import ch.rmy.android.http_shortcuts.data.enums.CategoryBackgroundType
import ch.rmy.android.http_shortcuts.data.enums.CategoryLayoutType
import ch.rmy.android.http_shortcuts.data.enums.ShortcutClickBehavior
data class CategoryEditorViewState(
val dialogState: DialogState? = null,
val toolbarTitle: Localizable,
val categoryName: String,
val categoryLayoutType: CategoryLayoutType,
val categoryBackgroundType: CategoryBackgroundType,
val categoryClickBehavior: ShortcutClickBehavior?,
private val originalCategoryName: String,
private val originalCategoryLayoutType: CategoryLayoutType,
private val originalCategoryBackgroundType: CategoryBackgroundType,
private val originalCategoryClickBehavior: ShortcutClickBehavior?,
) {
val hasChanges: Boolean =
categoryName != originalCategoryName ||
categoryLayoutType != originalCategoryLayoutType ||
categoryBackgroundType != originalCategoryBackgroundType ||
categoryClickBehavior != originalCategoryClickBehavior
val saveButtonVisible: Boolean =
hasChanges && categoryName.isNotBlank()
val colorButtonVisible: Boolean
get() = categoryBackgroundType is CategoryBackgroundType.Color
val backgroundColor: Int
get() = (categoryBackgroundType as? CategoryBackgroundType.Color)?.color ?: Color.WHITE
val backgroundColorAsText: String
get() = (categoryBackgroundType as? CategoryBackgroundType.Color)?.getHexString() ?: ""
val categoryBackground: CategoryBackground
get() = when (categoryBackgroundType) {
is CategoryBackgroundType.Default -> CategoryBackground.DEFAULT
is CategoryBackgroundType.Color -> CategoryBackground.COLOR
is CategoryBackgroundType.Wallpaper -> CategoryBackground.WALLPAPER
}
}
| mit | 0a6412f0c46d2dbb98e8f3c35b31fc4b | 44.893617 | 95 | 0.77376 | 5.160287 | false | false | false | false |
kirimin/mitsumine | app/src/main/java/me/kirimin/mitsumine/feed/FeedPagerAdapter.kt | 1 | 3168 | package me.kirimin.mitsumine.feed
import me.kirimin.mitsumine.R
import android.content.Context
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v4.widget.SwipeRefreshLayout
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
class FeedPagerAdapter(context: Context, private val mLayout: View, private val mOnSlideListener: OnSlideListener, private val mUseLeft: Boolean, useRight: Boolean) : PagerAdapter(), ViewPager.OnPageChangeListener {
interface OnSlideListener {
fun onLeftSlide(view: View)
fun onRightSlide(view: View)
}
private val mInflater: LayoutInflater
private var mSwipeRefreshLayout: SwipeRefreshLayout? = null
private var mPageNum = 3
init {
mInflater = LayoutInflater.from(context)
if (!mUseLeft)
mPageNum--
if (!useRight)
mPageNum--
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val view: View
if (position == 0) {
if (mUseLeft) {
view = mInflater.inflate(R.layout.row_feed_read_later, null)
} else {
view = mLayout
}
} else if (position == 1) {
if (mUseLeft) {
view = mLayout
} else {
view = mInflater.inflate(R.layout.row_feed_read, null)
}
} else {
view = mInflater.inflate(R.layout.row_feed_read, null)
}
container.addView(view)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
(container as ViewPager).removeView(`object` as View)
}
override fun getCount(): Int {
return mPageNum
}
override fun isViewFromObject(view: View, obj: Any): Boolean {
return view == obj
}
override fun onPageSelected(position: Int) {
if (mSwipeRefreshLayout != null) {
mSwipeRefreshLayout!!.isEnabled = true
}
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
if (mSwipeRefreshLayout == null) {
mSwipeRefreshLayout = searchSwipeRefreshLayout(mLayout)
}
// スクロール干渉防止
if (mSwipeRefreshLayout != null) {
mSwipeRefreshLayout!!.isEnabled = positionOffset == 0f
}
if (positionOffset != 0f) {
return
}
if (position == 0 && mUseLeft) {
mOnSlideListener.onRightSlide(mLayout)
} else if (position == 2 || (position == 1 && !mUseLeft)) {
mOnSlideListener.onLeftSlide(mLayout)
}
}
override fun onPageScrollStateChanged(position: Int) {
}
private fun searchSwipeRefreshLayout(view: View): SwipeRefreshLayout? {
if (view.parent == null) {
return null
}
if (view.parent is SwipeRefreshLayout) {
return view.parent as SwipeRefreshLayout
} else {
return searchSwipeRefreshLayout(view.parent as View)
}
}
} | apache-2.0 | 8b06406a324088ff3430fef02c14fd32 | 29.009524 | 215 | 0.612381 | 4.565217 | false | false | false | false |
syrop/Wiktor-Navigator | navigator/src/main/kotlin/pl/org/seva/navigator/main/data/db/NavigatorDb.kt | 1 | 1866 | /*
* Copyright (C) 2017 Wiktor Nizio
*
* 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/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.navigator.main.data.db
import androidx.room.Room
import pl.org.seva.navigator.main.data.appContext
import pl.org.seva.navigator.main.data.db.migration.AddedColorMigration
import pl.org.seva.navigator.main.data.db.migration.AddedDebugMigration
import pl.org.seva.navigator.main.data.db.migration.LiteToRoomMigration
import pl.org.seva.navigator.main.init.instance
val db by instance<ContactsDatabase>()
class ContactsDatabase {
private val db = Room.databaseBuilder(appContext, NavigatorDbAbstract::class.java, DATABASE_NAME)
.addMigrations(LiteToRoomMigration(), AddedColorMigration(), AddedDebugMigration())
.allowMainThreadQueries()
.build()
val contactDao = db.contactDao()
companion object {
const val SQL_LITE_DATABASE_VERSION = 1
const val ROOM_DATABASE_VERSION = 2
const val ADDED_COLOR_DATABASE_VERSION = 3
const val ADDED_DEBUG_DATABASE_VERSION = 5
const val DATABASE_NAME = "Friends.db"
const val TABLE_NAME = "friends"
}
}
| gpl-3.0 | ed1bdf274efb974a26638dd9e1126ec6 | 37.875 | 101 | 0.734727 | 3.987179 | false | false | false | false |
google/intellij-gn-plugin | src/main/java/com/google/idea/gn/GnFoldingBuilder.kt | 1 | 1877 | package com.google.idea.gn
import com.google.idea.gn.psi.impl.GnBlockImpl
import com.google.idea.gn.psi.impl.GnCollectionImpl
import com.intellij.lang.ASTNode
import com.intellij.lang.folding.FoldingBuilderEx
import com.intellij.lang.folding.FoldingDescriptor
import com.intellij.openapi.editor.Document
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import java.util.*
class GnFoldingBuilder : FoldingBuilderEx(), DumbAware {
override fun buildFoldRegions(root: PsiElement, document: Document, quick: Boolean): Array<FoldingDescriptor> {
val descriptors: MutableList<FoldingDescriptor> = ArrayList()
//Block
val blocks = PsiTreeUtil.findChildrenOfType(root, GnBlockImpl::class.java)
for (block in blocks) {
val first = block.firstChild
val last = block.lastChild
val newRange = TextRange(first.textRange.endOffset, last.textRange.startOffset)
if (newRange.length > 0) {
descriptors.add(FoldingDescriptor(block, newRange))
}
}
// Collections
val collections = PsiTreeUtil.findChildrenOfType(root, GnCollectionImpl::class.java)
for (collection in collections) {
val first = collection.firstChild
val last = collection.lastChild
val newRange = TextRange(first.textRange.endOffset, last.textRange.startOffset)
if (newRange.length > 0) {
descriptors.add(FoldingDescriptor(collection, newRange))
}
}
return descriptors.toTypedArray()
}
override fun getPlaceholderText(node: ASTNode): String? {
return "..."
}
override fun isCollapsedByDefault(node: ASTNode): Boolean {
return false
}
}
| bsd-3-clause | 5a7737e015b0ac0a57fcefff339f2578 | 36.54 | 115 | 0.690464 | 4.71608 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/gene/utils/GeneUtils.kt | 1 | 24579 | package org.evomaster.core.search.gene.utils
import org.apache.commons.text.StringEscapeUtils
import org.evomaster.core.output.OutputFormat
import org.evomaster.core.search.gene.*
import org.evomaster.core.search.gene.collection.ArrayGene
import org.evomaster.core.search.gene.collection.TupleGene
import org.evomaster.core.search.gene.optional.OptionalGene
import org.evomaster.core.search.gene.placeholder.CycleObjectGene
import org.evomaster.core.search.gene.placeholder.LimitObjectGene
import org.evomaster.core.search.service.AdaptiveParameterControl
import org.evomaster.core.search.service.Randomness
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.math.pow
object GeneUtils {
private val log: Logger = LoggerFactory.getLogger(GeneUtils::class.java)
/**
* List where each element at position "i" has value "2^i"
*/
val intpow2 = (0..30).map { 2.0.pow(it).toInt() }
/**
* The [EscapeMode] enum is here to clarify the supported types of Escape modes.
*
* Different purposes require different modes of escape (e.g. URI may require percent encoding). This is to
* keep track of what modes are supported and how they map to the respective implementations.
*
* Any mode that is not supported will go under NONE, and will result in no escapes being applied at all. The
* purpose is to ensure that, even if the mode being used is unsupported, the system will not throw an exception.
* It may not behave as desired, but it should not crash.
*
*/
enum class EscapeMode {
URI,
SQL,
ASSERTION,
EXPECTATION,
JSON,
TEXT,
XML,
BODY,
NONE,
X_WWW_FORM_URLENCODED,
BOOLEAN_SELECTION_MODE,
BOOLEAN_SELECTION_NESTED_MODE,
GQL_INPUT_MODE,
GQL_INPUT_ARRAY_MODE,
BOOLEAN_SELECTION_UNION_INTERFACE_OBJECT_MODE,
BOOLEAN_SELECTION_UNION_INTERFACE_OBJECT_FIELDS_MODE,
GQL_STR_VALUE,
GQL_NONE_MODE
}
fun getDelta(
randomness: Randomness,
apc: AdaptiveParameterControl,
range: Long = Long.MAX_VALUE,
start: Int = intpow2.size,
end: Int = 10
): Int {
if (range < 1){
throw IllegalArgumentException("cannot generate delta with the range ($range) which is less than 1")
}
val maxIndex = apc.getExploratoryValue(start, end)
var n = 0
for (i in 0 until (maxIndex -1)) {
n = i + 1
// check with Andrea regarding n instead of i
if (intpow2[n] > range) {
break
}
}
//choose an i for 2^i modification
val delta = randomness.chooseUpTo(intpow2, n)
return delta
}
/**
* Given a number [x], return its string representation, with padded 0s
* to have a defined [length]
*/
fun padded(x: Int, length: Int): String {
require(length >= 0) { "Negative length" }
val s = x.toString()
require(length >= s.length) { "Value is too large for chosen length" }
return if (x >= 0) {
s.padStart(length, '0')
} else {
"-${(-x).toString().padStart(length - 1, '0')}"
}
}
/**
* When we generate data, we might want to generate invalid inputs
* on purpose to stress out the SUT, ie for Robustness Testing.
* But there are cases in which such kind of data makes no sense.
* For example, when we initialize SQL data directly bypassing the SUT,
* there is no point in having invalid data which will just make the SQL
* commands fail with no effect.
*
* So, we simply "repair" such genes with only valid inputs.
*/
fun repairGenes(genes: Collection<Gene>) {
if (log.isTraceEnabled) {
log.trace("repair genes {}", genes.joinToString(",") {
//note that check whether the gene is printable is not enough here
try {
it.getValueAsRawString()
} catch (e: Exception) {
"null"
}
})
}
genes.forEach { it.repair() }
// repair() will need to be refactored
// for (g in genes) {
// when (g) {
// /*
// TODO, check with Andrea, why only DateGene and TimeGene?
// there also exist a repair for StringGene
// */
// is DateGene, is TimeGene -> g.repair()
// }
// }
}
/**
* [applyEscapes] - applies various escapes needed for assertion generation.
* Moved here to allow extension to other purposes (SQL escapes, for example) and to
* allow a more consistent way of making changes.
*
* This includes escaping special chars for java and kotlin.
* Escapes may have to be applied differently between:
* Java and Kotlin
* calls and assertions
*/
fun applyEscapes(string: String, mode: EscapeMode = EscapeMode.NONE, format: OutputFormat): String {
val ret = when (mode) {
EscapeMode.URI -> applyUriEscapes(string, format)
EscapeMode.SQL -> applySqlEscapes(string, format)
EscapeMode.ASSERTION -> applyAssertionEscapes(string, format)
EscapeMode.EXPECTATION -> applyExpectationEscapes(string, format)
EscapeMode.JSON -> applyJsonEscapes(string, format)
EscapeMode.TEXT -> applyTextEscapes(string, format)
EscapeMode.NONE,
EscapeMode.X_WWW_FORM_URLENCODED,
EscapeMode.BOOLEAN_SELECTION_MODE,
EscapeMode.BOOLEAN_SELECTION_UNION_INTERFACE_OBJECT_MODE,
EscapeMode.BOOLEAN_SELECTION_UNION_INTERFACE_OBJECT_FIELDS_MODE,
EscapeMode.BOOLEAN_SELECTION_NESTED_MODE,
EscapeMode.GQL_NONE_MODE,
EscapeMode.GQL_INPUT_ARRAY_MODE,
EscapeMode.GQL_INPUT_MODE -> string
EscapeMode.GQL_STR_VALUE -> applyGQLStr(string, format)
EscapeMode.BODY -> applyBodyEscapes(string, format)
EscapeMode.XML -> StringEscapeUtils.escapeXml10(string)
}
//if(forQueries) return applyQueryEscapes(string, format)
//else return applyAssertionEscapes(string, format)
return ret
}
fun applyJsonEscapes(string: String, format: OutputFormat): String {
val ret = string
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\b", "\\b")
.replace("\t", "\\t")
return ret
}
/**
* TODO might need a further handling based on [format]
* Note that there is kind of post handling for graphQL, see [GraphQLUtils.getPrintableInputGenes]
*/
private fun applyGQLStr(string: String, format: OutputFormat): String {
val replace = string
.replace("\"", "\\\\\"")
return replace
}
private fun applyExpectationEscapes(string: String, format: OutputFormat = OutputFormat.JAVA_JUNIT_4): String {
val ret = string.replace("\\", """\\\\""")
.replace("\"", "\\\"")
.replace("\n", "\\n")
when {
format.isKotlin() -> return ret.replace("\$", "\\\$")
else -> return ret
}
}
private fun applyUriEscapes(string: String, format: OutputFormat): String {
//val ret = URLEncoder.encode(string, "utf-8")
val ret = string.replace("\\", "%5C")
.replace("\"", "%22")
.replace("\n", "%0A")
if (format.isKotlin()) return ret.replace("\$", "%24")
else return ret
}
private fun applyTextEscapes(string: String, format: OutputFormat): String {
val ret = string.replace("\\", """\\""")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\b", "\\b")
.replace("\t", "\\t")
when {
format.isKotlin() -> return ret.replace("\$", "\\\$")
else -> return ret
}
}
private fun applyAssertionEscapes(string: String, format: OutputFormat): String {
/*
FIXME
This was completely broken, as modifying the string for flakiness handling has
nothing to do with applying escapes... which broke assertion generation for when
we do full matches (and checking substrings).
Flakiness handling has to be handled somewhere else. plus this is misleading, as
eg messing up assertions on email addresses.
*/
// var ret = ""
// val timeRegEx = "[0-2]?[0-9]:[0-5][0-9]".toRegex()
// ret = string.split("@")[0] //first split off any reference that might differ between runs
// .split(timeRegEx)[0] //split off anything after specific timestamps that might differ
val ret = string.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\b", "\\b")
.replace("\t", "\\t")
if (format.isKotlin()) return ret.replace("\$", "\\\$")
else return ret
}
private fun applyBodyEscapes(string: String, format: OutputFormat): String {
val ret = string.replace("\\", """\\""")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\b", "\\b")
.replace("\t", "\\t")
if (format.isKotlin()) return ret.replace("\$", "\\\$")
.replace("\\\\u", "\\u")
//.replace("\$", "\${\'\$\'}")
//ret.replace("\$", "\\\$")
else return ret.replace("\\\\u", "\\u")
/*
The \u denote unicode characters. For some reason, escaping the \\ leads to these being invalid.
Since they are valid in the back end (and they should, arguably, be possible), this leads to inconsistent behaviour.
This fix is a hack. It may be that some \u chars are not valid. E.g. \uAndSomeRubbish.
As far as I understand, the addition of an \ in the \unicode should not really happen.
They should be their own chars, and the .replace("\\", """\\""" should be fine, but for some reason
they are not.
*/
}
private fun applySqlEscapes(string: String, format: OutputFormat): String {
val ret = string.replace("\\", """\\""")
.replace("\"", "\\\\\"")
if (format.isKotlin()) return ret.replace("\$", "\\\$")
//.replace("\$", "\${\'\$\'}")
//ret.replace("\$", "\\\$")
else return ret
}
/**
* Given an input gene, prevent any [CycleObjectGene] from affecting the phenotype.
* For example, if [CycleObjectGene] is inside an [OptionalGene], then such gene
* should never be selectable.
* An array of [CycleObjectGene] would always be empty.
* Etc.
* However, it is not necessarily trivial. An [CycleObjectGene] might be required,
* and so we would need to scan to its first ancestor in the tree which is an optional
* or an array.
*
* [force] if true, throw exception if cannot prevent the cyclces
*/
fun preventCycles(gene: Gene, force: Boolean = false) {
preventSelectionOfGeneType(gene, CycleObjectGene::class.java, force)
}
fun tryToPreventSelection(gene: Gene): Boolean {
var p = gene.parent
loop@ while (p != null) {
when (p) {
is OptionalGene -> {
p.forbidSelection()
break@loop
}
is ArrayGene<*> -> {
p.forceToOnlyEmpty()
break@loop
}
else -> p = p.parent
}
}
return p != null
}
/**
* When building a graph/tree of objects with fields, we might want to put a limit on the depth
* of such tree.
* In these cases, then LimitObjectGene will be created as place-holder to stop the recursion when
* building the tree.
*
* Here, we make sure to LimitObjectGene are not reachable, in the same way as when dealing with
* cycles.
*/
fun preventLimit(gene: Gene, force: Boolean = false) {
preventSelectionOfGeneType(gene, LimitObjectGene::class.java, force)
}
private fun preventSelectionOfGeneType(root: Gene, type: Class<out Gene>, force: Boolean = false) {
val toExclude = root.flatView().filterIsInstance(type)
if (toExclude.isEmpty()) {
//nothing to do
return
}
for (c in toExclude) {
val prevented = tryToPreventSelection(c)
if (!prevented) {
val msg = "Could not prevent skipping gene in ${root.name} gene of type $type"
if (force) {
throw RuntimeException(msg)
}
log.warn(msg)
}
}
}
fun hasNonHandledCycles(gene: Gene): Boolean {
val cycles = gene.flatView().filterIsInstance<CycleObjectGene>()
if (cycles.isEmpty()) {
return false
}
for (c in cycles) {
var p = c.parent
loop@ while (p != null) {
when {
(p is OptionalGene && !p.selectable) ||
(p is ArrayGene<*> && p.maxSize == 0)
-> {
break@loop
}
else -> p = p.parent
}
}
if (p == null) {
return true
}
}
return false
}
/**
* If the input gene is a root of a tree of genes (ie, it contains inside other genes),
* then verify that the top ancestor of each child and their children is indeed this root.
* Note: this is just testing for an invariant
*/
fun verifyRootInvariant(gene: Gene): Boolean {
if (gene.parent != null) {
//not a root
return true
}
val all = gene.flatView()
if (all.size == 1) {
//no child
return true
}
for (g in all) {
val root = g.getRoot()
if (root != gene) {
return false
}
}
return true
}
/**
* In some cases, in particular GraphQL, given an object we might want to specify
* just which fields we want to have, which is a boolean selection (ie, either a filed should
* be present, or not). But we need to handle this recursively, because an object could have
* objects inside, and so on recursively.
*
* However, to be able to print such selection for GraphQL, we need then to have a special mode
* for its string representation.
*
* Also, we need to deal for when elements are non-nullable vs. nullable.
*/
fun getBooleanSelection(gene: Gene): ObjectGene {
if (shouldApplyBooleanSelection(gene)) {
val selectedGene = handleBooleanSelection(gene)
return if (selectedGene is OptionalGene) {
selectedGene.gene as ObjectGene
} else {
selectedGene as ObjectGene
}
}
throw IllegalArgumentException("Invalid input type: ${gene.javaClass}")
}
/**
* force at least one boolean to be selected
*/
fun repairBooleanSelection(obj: ObjectGene) {
if (obj.fields.isEmpty()
|| obj.fields.count { it !is OptionalGene && it !is BooleanGene && it !is TupleGene } > 0
) {
throw IllegalArgumentException("There should be at least 1 field, and they must be all optional or boolean or tuple")
}
val selected = obj.fields.filter {
((it is OptionalGene && it.isActive) ||
(it is BooleanGene && it.value) ||
(it is OptionalGene && it.gene is TupleGene && it.gene.lastElementTreatedSpecially && isLastSelected(it.gene)) ||
(it is TupleGene && it.lastElementTreatedSpecially && isLastSelected(it))
)
}
if (selected.isNotEmpty()) {
//it is fine, but we still need to make sure selected objects are fine
selected.forEach {
if ((it is OptionalGene && it.gene is ObjectGene && (it.gene !is CycleObjectGene || it.gene !is LimitObjectGene))
) {
repairBooleanSelection(it.gene)
} else if ( //looking into objects inside a tuple
isTupleOptionalObjetNotCycleNotLimit(it)) {
repairBooleanSelection(((it as TupleGene).elements.last() as OptionalGene).gene as ObjectGene)
}
}
} else {
//must select at least one
val candidates = obj.fields.filter {
(it is OptionalGene && it.selectable) || it is BooleanGene ||
(it is TupleGene && it.lastElementTreatedSpecially && isLastCandidate(it))
}
assert(candidates.isNotEmpty())
// maybe do at random?
val selectedGene = candidates[0]
if (selectedGene is OptionalGene) {
selectedGene.isActive = true
if (selectedGene.gene is ObjectGene) {
assert(selectedGene.gene !is CycleObjectGene)
repairBooleanSelection(selectedGene.gene)
}
} else
if (selectedGene is TupleGene) {
val lastElement = selectedGene.elements.last()
repairTupleLastElement(lastElement)
} else
(selectedGene as BooleanGene).value = true
}
}
private fun repairTupleLastElement(lastElement: Gene) {
if (lastElement is OptionalGene) {
lastElement.isActive = true
if (lastElement.gene is ObjectGene) {
assert(lastElement.gene !is CycleObjectGene)
repairBooleanSelection(lastElement.gene)
}
} else
if (lastElement is BooleanGene)
lastElement.value = true
}
private fun shouldApplyBooleanSelection(gene: Gene) =
(gene is OptionalGene && gene.gene is ObjectGene)
|| gene is ObjectGene
|| (gene is ArrayGene<*> && gene.template is ObjectGene)
|| (gene is ArrayGene<*> && gene.template is OptionalGene && gene.template.gene is ObjectGene)
|| (gene is OptionalGene && gene.gene is ArrayGene<*> && gene.gene.template is OptionalGene && gene.gene.template.gene is ObjectGene)
|| (gene is OptionalGene && gene.gene is ArrayGene<*> && gene.gene.template is ObjectGene)
private fun handleBooleanSelection(gene: Gene): Gene {
return when (gene) {
is OptionalGene -> {
/*
this is nullable.
Any basic field will be represented with a BooleanGene (selected/unselected).
But for objects we need to use an Optional
*/
if (gene.gene is ObjectGene)
OptionalGene(gene.name, handleBooleanSelection(gene.gene))
else
if (gene.gene is ArrayGene<*>)
handleBooleanSelection(gene.gene.template)
else
if (gene.gene is TupleGene && gene.gene.lastElementTreatedSpecially)//opt tuple
TupleGene(
gene.name,
gene.gene.elements.dropLast(1).plus(handleBooleanSelection(gene.gene.elements.last())),
lastElementTreatedSpecially = true
) else if (gene.gene is TupleGene)
gene.gene else if (gene.gene is LimitObjectGene) gene else if (gene.gene is CycleObjectGene) gene
else
// on by default, but can be deselected during the search
BooleanGene(gene.name, true)
}
is CycleObjectGene -> {
gene
}
is LimitObjectGene -> {
gene
}
is ObjectGene -> {
//need to look at each field
ObjectGene(gene.name, gene.fields.map { handleBooleanSelection(it) })
}
is ArrayGene<*> -> handleBooleanSelection(gene.template)
is TupleGene -> {//not opt tuple
if (gene.lastElementTreatedSpecially)
TupleGene(
gene.name,
gene.elements.dropLast(1).plus(handleBooleanSelection(gene.elements.last())),
lastElementTreatedSpecially = true
) else gene
}
else -> {
BooleanGene(gene.name, true)
}
}
}
fun isGraphQLModes(mode: EscapeMode?) = mode == EscapeMode.BOOLEAN_SELECTION_MODE ||
mode == EscapeMode.BOOLEAN_SELECTION_NESTED_MODE ||
mode == EscapeMode.GQL_INPUT_MODE ||
mode == EscapeMode.GQL_INPUT_ARRAY_MODE ||
mode == EscapeMode.BOOLEAN_SELECTION_UNION_INTERFACE_OBJECT_MODE ||
mode == EscapeMode.BOOLEAN_SELECTION_UNION_INTERFACE_OBJECT_FIELDS_MODE ||
mode == EscapeMode.GQL_STR_VALUE
private fun isLastSelected(gene: TupleGene): Boolean {
val lastElement = gene.elements[gene.elements.size - 1]
return (lastElement is OptionalGene && lastElement.isActive) ||
(lastElement is BooleanGene && lastElement.value)
}
private fun isLastCandidate(gene: TupleGene): Boolean {
val lastElement = gene.elements[gene.elements.size - 1]
return (lastElement is OptionalGene && lastElement.selectable) || (lastElement is BooleanGene)
}
private fun isTupleOptionalObjetNotCycleNotLimit(gene: Gene):Boolean {
return (gene is TupleGene && gene.elements.last() is OptionalGene
&& (gene.elements.last() as OptionalGene).gene is ObjectGene && (
((gene.elements.last() as OptionalGene).gene !is CycleObjectGene) || ((gene.elements.last() as OptionalGene).gene !is LimitObjectGene)))
}
/**
* A special string used for representing a place in the string
* where we should add a SINGLE APOSTROPHE (').
* This is used mainly for SQL value handling.
*/
const val SINGLE_APOSTROPHE_PLACEHOLDER = "SINGLE_APOSTROPHE_PLACEHOLDER"
private val QUOTATION_MARK = "\""
/**
* Returns a new string by removing the enclosing quotation marks of a string.
* For example,
* ""Hello World"" -> "Hello World"
* """" -> ""
* If the input string does not start and end with a
* quotation mark, the output string is equal to the input string.
* For example:
* "Hello World"" -> "Hello World""
* ""Hello World" -> ""Hello World"
*/
fun removeEnclosedQuotationMarks(str: String): String {
return if (str.startsWith(QUOTATION_MARK) && str.endsWith(QUOTATION_MARK)) {
str.substring(1,str.length-1)
} else {
str
}
}
private fun encloseWithSingleApostrophePlaceHolder(str: String) = SINGLE_APOSTROPHE_PLACEHOLDER + str + SINGLE_APOSTROPHE_PLACEHOLDER
/**
* If the input string is enclosed in Quotation Marks, these symbols are replaced
* by the special string in SINGLE_APOSTROPHE_PLACEHOLDER in the output string.
* For example:
* ""Hello"" -> "SINGLE_APOSTROPHE_PLACEHOLDERHelloSINGLE_APOSTROPHE_PLACEHOLDER".
*
* If the input string is not enclosed in quotation marks, the output string is equal
* to the input string (i.e. no changes).
*/
fun replaceEnclosedQuotationMarksWithSingleApostrophePlaceHolder(str: String): String {
return if (str.startsWith(QUOTATION_MARK) && str.endsWith(QUOTATION_MARK)) {
encloseWithSingleApostrophePlaceHolder(removeEnclosedQuotationMarks(str))
} else {
str
}
}
} | lgpl-3.0 | e758d1a477c5ea912838deafbecc97d1 | 36.242424 | 153 | 0.562065 | 4.679041 | false | false | false | false |
VoIPGRID/vialer-android | app/src/main/java/com/voipgrid/vialer/util/InternetConnectivity.kt | 1 | 1299 | package com.voipgrid.vialer.util
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Socket
class InternetConnectivity {
/**
* Attempts to open a socket to guarantee we have an internet connection.
*
*/
suspend fun canGuaranteeAnInternetConnection(): Boolean = withContext(Dispatchers.IO) { attemptToOpenSocket() }
/**
* Perform the actual opening of a socket.
*
*/
private fun attemptToOpenSocket() = try {
Socket().apply {
connect(InetSocketAddress(IP, PORT), TIMEOUT)
close()
}
true
} catch (e: IOException) { false }
companion object {
/**
* A sensible IP to open a socket to, this must be something we expect
* to have incredibly high availability.
*
*/
private const val IP = "8.8.8.8"
/**
* The port to connect to at the given IP, for now this will be Google's DNS
* server.
*
*/
private const val PORT = 53
/**
* The time to wait before we determine we don't have an internet connection.
*
*/
private const val TIMEOUT = 1500
}
} | gpl-3.0 | dabbce6d606489da986a1c09e2fb8954 | 24.490196 | 115 | 0.597383 | 4.689531 | false | false | false | false |
eurofurence/ef-app_android | app/src/main/kotlin/org/eurofurence/connavigator/services/AnalyticsService.kt | 1 | 2675 | package org.eurofurence.connavigator.services
import android.app.Activity
import android.content.Context
import com.crashlytics.android.Crashlytics
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.perf.FirebasePerformance
import org.eurofurence.connavigator.preferences.AnalyticsPreferences
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.bundleOf
import org.jetbrains.anko.debug
/**o
* Created by David on 20-4-2016.
*/
class AnalyticsService {
/**
* Collects all categories for analytics
*/
object Category {
const val EVENT = "event"
const val DEALER = "dealer"
const val INFO = "info"
const val SETTINGS = "settings"
}
/**
* Collects all actions for analytics
*/
object Action {
const val SHARED = "shared"
const val OPENED = "opened"
const val EXPORT_CALENDAR = "Exported to calendar"
const val LINK_CLICKED = "Clicked external link"
const val INCOMING = "Incoming from websites"
const val CHANGED = "changed"
}
companion object : AnkoLogger {
lateinit var analytics: FirebaseAnalytics
val performance: FirebasePerformance by lazy { FirebasePerformance.getInstance() }
fun init(context: Context) {
analytics = FirebaseAnalytics.getInstance(context).apply {
setAnalyticsCollectionEnabled(AnalyticsPreferences.enabled)
}
performance.isPerformanceCollectionEnabled = AnalyticsPreferences.performanceTracking
}
/**
* Send new screen to analytics
*/
fun screen(activity: Activity, fragmentName: String) = analytics.setCurrentScreen(activity, fragmentName, null)
/**
* Send event to analytics
*/
fun event(category: String, action: String, label: String) = analytics.logEvent(
FirebaseAnalytics.Event.SELECT_CONTENT,
bundleOf(
FirebaseAnalytics.Param.CONTENT_TYPE to category,
FirebaseAnalytics.Param.ITEM_CATEGORY to action,
FirebaseAnalytics.Param.ITEM_NAME to label
)
)
fun updateSettings() {
debug { "AnalyticsService: ${AnalyticsPreferences.enabled}; Performance: ${AnalyticsPreferences.performanceTracking}" }
analytics.setAnalyticsCollectionEnabled(AnalyticsPreferences.enabled)
performance.isPerformanceCollectionEnabled = AnalyticsPreferences.performanceTracking
}
fun ex(exception: Exception) = Crashlytics.logException(exception)
}
} | mit | 913864be4bca02ca4b62f4f95b8e5dba | 34.210526 | 131 | 0.665421 | 5.318091 | false | false | false | false |
duftler/orca | orca-core/src/main/java/com/netflix/spinnaker/orca/pipeline/model/DefaultTrigger.kt | 2 | 1423 | /*
* Copyright 2018 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.pipeline.model
import com.netflix.spinnaker.kork.artifacts.model.Artifact
import com.netflix.spinnaker.kork.artifacts.model.ExpectedArtifact
data class DefaultTrigger
@JvmOverloads constructor(
override val type: String,
override val correlationId: String? = null,
override val user: String? = "[anonymous]",
override val parameters: Map<String, Any> = mutableMapOf(),
override val artifacts: List<Artifact> = mutableListOf(),
override val notifications: List<Map<String, Any>> = mutableListOf(),
override var isRebake: Boolean = false,
override var isDryRun: Boolean = false,
override var isStrategy: Boolean = false
) : Trigger {
override var other: Map<String, Any> = mutableMapOf()
override var resolvedExpectedArtifacts: List<ExpectedArtifact> = mutableListOf()
}
| apache-2.0 | 359d2be201c3fde89e8e59e4e358dd07 | 38.527778 | 82 | 0.756852 | 4.260479 | false | false | false | false |
khanhpq29/My-Task | app/src/main/java/ht/pq/khanh/util/Common.kt | 1 | 4018 | package ht.pq.khanh.util
import android.content.Context
import android.text.format.Time
import com.amulyakhare.textdrawable.util.ColorGenerator
import ht.pq.khanh.multitask.R
import java.text.SimpleDateFormat
/**
* Created by khanhpq on 9/9/17.
*/
object Common {
//URL
val URL_WEATHER_BASE = "http://openweathermap.org/"
val URl_ICON = "http://openweathermap.org/img/w/"
//string format
val DATE_FORMAT = "yyyyMMdd"
//theme keyname
val NIGHT_PREFERENCE_KEY = "NightModePreference"
val THEME_PREFERENCES = "theme_preferences"
val RECREATE_ACTIVITY = "recreateact"
val THEME_SAVED = "themesaved"
val DARKTHEME = "darktheme"
val LIGHTTHEME = "lighttheme"
//theme
val TEMP_PREFERENCE_KEY = "temperaturePreferece"
val TEMP_PREFERENCE = "tem_pref"
val TEMP_TYPE = "temperatureType"
val CELSIUS_TYPE = "celsiusType"
val FAHRENHEIT_TYPE = "fahrenheitType"
//location
val LOCATION_PREFERENCE = "location_pref"
//notification
val TODOTEXT = "notification.content"
val TODOUUID = "notification.id"
fun randomColor(): Int {
return ColorGenerator.MATERIAL.randomColor
}
fun getToolbarHeight(context: Context): Int {
val styledAttributes = context.theme.obtainStyledAttributes(
intArrayOf(R.attr.actionBarSize))
val toolbarHeight = styledAttributes.getDimension(0, 0f).toInt()
styledAttributes.recycle()
return toolbarHeight
}
fun getFriendlyDayString(context: Context, dateInMillis: Long, displayLongToday: Boolean): String {
// The day string for forecast uses the following logic:
// For today: "Today, June 8"
// For tomorrow: "Tomorrow"
// For the next 5 days: "Wednesday" (just the day name)
// For all days after that: "Mon Jun 8"
val time = Time()
time.setToNow()
val currentTime = System.currentTimeMillis()
val julianDay = Time.getJulianDay(dateInMillis, time.gmtoff)
val currentJulianDay = Time.getJulianDay(currentTime, time.gmtoff)
// If the date we're building the String for is today's date, the format
// is "Today, June 24"
if (displayLongToday && julianDay == currentJulianDay) {
val today = "Today"
val formatId = R.string.format_full_friendly_date
return String.format(context.getString(
formatId,
today,
getFormattedMonthDay(dateInMillis)))
} else if (julianDay < currentJulianDay + 7) {
// If the input date is less than a week in the future, just return the day name.
return getDayName(dateInMillis)
} else {
// Otherwise, use the form "Mon Jun 3"
val shortenedDateFormat = SimpleDateFormat("EEE MMM dd")
return shortenedDateFormat.format(dateInMillis)
}
}
fun getDayName(dateInMillis: Long): String {
// If the date is today, return the localized version of "Today" instead of the actual
// day name.
val t = Time()
t.setToNow()
val julianDay = Time.getJulianDay(dateInMillis, t.gmtoff)
val currentJulianDay = Time.getJulianDay(System.currentTimeMillis(), t.gmtoff)
if (julianDay == currentJulianDay) {
return "Today"
} else if (julianDay == currentJulianDay + 1) {
return "Tomorrow"
} else {
val time = Time()
time.setToNow()
// Otherwise, the format is just the day of the week (e.g "Wednesday".
val dayFormat = SimpleDateFormat("EEEE")
return dayFormat.format(dateInMillis)
}
}
fun getFormattedMonthDay(dateInMillis: Long): String {
val time = Time()
time.setToNow()
val dbDateFormat = SimpleDateFormat(DATE_FORMAT)
val monthDayFormat = SimpleDateFormat("MMMM dd")
return monthDayFormat.format(dateInMillis)
}
}
| apache-2.0 | ed8488328a870423dd6792165313b91a | 34.875 | 103 | 0.635889 | 4.225026 | false | false | false | false |
googlecodelabs/android-compose-codelabs | ThemingCodelab/app/src/main/java/com/codelab/theming/ui/start/Home.kt | 1 | 6532 | /*
* 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.codelab.theming.ui.start
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Card
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.ListItem
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Palette
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.codelab.theming.R
import com.codelab.theming.data.Post
import com.codelab.theming.data.PostRepo
import java.util.Locale
@Composable
fun Home() {
val featured = remember { PostRepo.getFeaturedPost() }
val posts = remember { PostRepo.getPosts() }
MaterialTheme {
Scaffold(
topBar = { AppBar() }
) { innerPadding ->
LazyColumn(contentPadding = innerPadding) {
item {
Header(stringResource(R.string.top))
}
item {
FeaturedPost(
post = featured,
modifier = Modifier.padding(16.dp)
)
}
item {
Header(stringResource(R.string.popular))
}
items(posts) { post ->
PostItem(post = post)
Divider(startIndent = 72.dp)
}
}
}
}
}
@Composable
private fun AppBar() {
TopAppBar(
navigationIcon = {
Icon(
imageVector = Icons.Rounded.Palette,
contentDescription = null,
modifier = Modifier.padding(horizontal = 12.dp)
)
},
title = {
Text(text = stringResource(R.string.app_title))
},
backgroundColor = MaterialTheme.colors.primary
)
}
@Composable
fun Header(
text: String,
modifier: Modifier = Modifier
) {
Text(
text = text,
modifier = modifier
.fillMaxWidth()
.background(Color.LightGray)
.semantics { heading() }
.padding(horizontal = 16.dp, vertical = 8.dp)
)
}
@Composable
fun FeaturedPost(
post: Post,
modifier: Modifier = Modifier
) {
Card(modifier) {
Column(
modifier = Modifier
.fillMaxWidth()
.clickable { /* onClick */ }
) {
Image(
painter = painterResource(post.imageId),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.heightIn(min = 180.dp)
.fillMaxWidth()
)
Spacer(Modifier.height(16.dp))
val padding = Modifier.padding(horizontal = 16.dp)
Text(
text = post.title,
modifier = padding
)
Text(
text = post.metadata.author.name,
modifier = padding
)
PostMetadata(post, padding)
Spacer(Modifier.height(16.dp))
}
}
}
@Composable
private fun PostMetadata(
post: Post,
modifier: Modifier = Modifier
) {
val divider = " • "
val tagDivider = " "
val text = buildAnnotatedString {
append(post.metadata.date)
append(divider)
append(stringResource(R.string.read_time, post.metadata.readTimeMinutes))
append(divider)
post.tags.forEachIndexed { index, tag ->
if (index != 0) {
append(tagDivider)
}
append(" ${tag.uppercase(Locale.getDefault())} ")
}
}
Text(
text = text,
modifier = modifier
)
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun PostItem(
post: Post,
modifier: Modifier = Modifier
) {
ListItem(
modifier = modifier
.clickable { /* todo */ }
.padding(vertical = 8.dp),
icon = {
Image(
painter = painterResource(post.imageThumbId),
contentDescription = null
)
},
text = {
Text(text = post.title)
},
secondaryText = {
PostMetadata(post)
}
)
}
@Preview("Post Item")
@Composable
private fun PostItemPreview() {
val post = remember { PostRepo.getFeaturedPost() }
Surface {
PostItem(post = post)
}
}
@Preview("Featured Post")
@Composable
private fun FeaturedPostPreview() {
val post = remember { PostRepo.getFeaturedPost() }
FeaturedPost(post = post)
}
@Preview("Home")
@Composable
private fun HomePreview() {
Home()
}
| apache-2.0 | deb4c9829740d56be6edbbeedbfb3091 | 27.76652 | 81 | 0.619602 | 4.585674 | false | false | false | false |
j-selby/kotgb | core/src/main/kotlin/net/jselby/kotgb/cpu/interpreter/instructions/alu/General.kt | 1 | 8708 | package net.jselby.kotgb.cpu.interpreter.instructions.alu
import net.jselby.kotgb.Gameboy
import net.jselby.kotgb.cpu.CPU
import net.jselby.kotgb.cpu.Registers
import net.jselby.kotgb.cpu.interpreter.instructions.getN
import kotlin.experimental.and
import kotlin.reflect.KMutableProperty1
/**
* General math - addition, subtraction, etc.
*/
/**
* -- Addition. --
*/
/**
* **0x80 ~ 0xE8** - *ADD X,Y* - Add X to Y.
*/
val x_ADD : (CPU, Registers, Gameboy,
KMutableProperty1<Registers, Short>, KMutableProperty1<Registers, Short>) -> (Int) = {
_, registers, _, x : KMutableProperty1<Registers, Short>, y : KMutableProperty1<Registers, Short> ->
val prevValue = x.get(registers)
val value = y.get(registers)
val newValue = (prevValue + value).toShort() and 0xFF
x.set(registers, newValue)
registers.flagZ = newValue.toInt() == 0
registers.flagN = false
registers.flagH = ((value and 0x0F) + (prevValue and 0x0F)) > 0xF
registers.flagC = (prevValue + value) > 0xFF
/*Cycles: */ 4
}
/**
* **0x19 ~ 0x39** - *ADD HL,X* - Add XX to HL.
*/
val x_ADD_HL : (CPU, Registers, Gameboy,
KMutableProperty1<Registers, Int>) -> (Int) = {
_, registers, _, target ->
// TODO: Check accuracy of flags
val prevValue = registers.hl
val targetVal = target.get(registers)
registers.hl = (prevValue + targetVal)
registers.flagN = false
registers.flagH = ((targetVal and 0x0FFF) + (prevValue and 0x0FFF)) > 0xFFF
registers.flagC = (prevValue + targetVal) > 0xFFFF
//registers.flagH = (prevValue and 0b11111111111 + targetVal and 0b11111111111) ushr 11 > 0
// registers.flagC = (prevValue and 0b111111111111111 + targetVal and 0b111111111111111) ushr 15 > 0
/*Cycles: */ 8
}
/**
* **0x86** - *ADD (hl)* - Add *hl to a.
*/
val x86 : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
val prevValue = registers.a
val value = gb.ram.readByte(registers.hl.toLong() and 0xFFFF) and 0xFF
val newValue = (prevValue + value).toShort() and 0xFF
registers.a = newValue
registers.flagZ = newValue.toInt() == 0
registers.flagN = false
registers.flagH = ((value and 0x0F) + (prevValue and 0x0F)) > 0xF
registers.flagC = (prevValue + value) > 0xFF
/*Cycles: */ 8
}
/**
* **0x88 ~ 0x9F** - *ADC A,X* - Add X + carry flag to A.
*/
val x_ADC : (CPU, Registers, Gameboy, KMutableProperty1<Registers, Short>) -> (Int) = {
_, registers, _, target ->
val value = target.get(registers).toInt()
val oldValue = registers.a.toInt()
val carry = if (registers.flagC) 1 else 0
val newValue = oldValue + value + carry
registers.a = newValue.toShort()
registers.f = 0
registers.flagZ = registers.a.toInt() == 0
registers.flagH = ((value and 0x0F) + (oldValue and 0x0F) + carry) > 0xF
registers.flagC = newValue > 0xFF
/*Cycles: */ 4
}
/**
* **0x8E** - *ADC A,(HL)* - Add (HL) + carry flag to A.
*/
val x8E : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
val value = (gb.ram.readByte(registers.hl.toLong() and 0xFFFF) and 0xFF).toInt()
val oldValue = registers.a.toInt()
val carry = if (registers.flagC) 1 else 0
val newValue = oldValue + value + carry
registers.a = newValue.toShort()
registers.f = 0
registers.flagZ = registers.a.toInt() == 0
registers.flagH = ((value and 0x0F) + (oldValue and 0x0F) + carry) > 0xF
registers.flagC = newValue > 0xFF /* Overflow */
/*Cycles: */ 8
}
/**
* **0xC6** - *ADD a,#* - Add # to a.
*/
val xC6 : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
val prevValue = registers.a
val value = getN(registers, gb)
registers.a = (prevValue + value).toShort()
registers.flagZ = registers.a.toInt() == 0
registers.flagN = false
//registers.flagH = (registers.a.toInt() shr 3 and 0x1) != (prevValue.toInt() shr 3 and 0x1)
//registers.flagC = (registers.a.toInt() shr 7 and 0x1) != (prevValue.toInt() shr 7 and 0x1)
registers.flagH = ((value and 0x0F) + (prevValue and 0x0F)) > 0xF
registers.flagC = (prevValue + value) > 0xFF
/*Cycles: */ 8
}
/**
* **0xCE** - *ADC a,#* - Add # + Carry flag to a.
*/
val xCE : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
val value = getN(registers, gb)
val oldValue = registers.a.toInt()
val newValue = oldValue + value + if (registers.flagC) 1 else 0
registers.a = newValue.toShort()
registers.f = 0
registers.flagZ = registers.a.toInt() == 0
registers.flagH = (oldValue xor newValue xor (value.toInt() and 0xFFFF) and 0x10) == 0x10
registers.flagC = (oldValue xor newValue xor (value.toInt() and 0xFFFF) and 0x100) == 0x100
/*Cycles: */ 8
}
/**
* **0xE8** - *ADD sp,#S* - Add signed value # to sp.
*/
val xE8 : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
val prevValue = registers.sp
val value = gb.ram.readByte(registers.pc.toLong() and 0xFFFF).toInt()
registers.pc++
val result = prevValue + value
registers.sp = result
registers.flagZ = false
registers.flagN = false
// Credit to Gearboy for this one:
// https://github.com/drhelius/Gearboy
registers.flagH = (prevValue xor value xor (result and 0xFFFF) and 0x10) == 0x10
registers.flagC = (prevValue xor value xor (result and 0xFFFF) and 0x100) == 0x100
/*Cycles: */ 16
}
/**
* -- Subtraction. --
**/
/**
* **0x90 ~ 0x95** - *SUB A,X* - Subtract X from A.
*/
val x_SUB : (CPU, Registers, Gameboy, KMutableProperty1<Registers, Short>) -> (Int) = {
_, registers, _, target ->
val prevValue = registers.a
val value = target.get(registers)
val newValue = prevValue - value
registers.a = newValue.toShort()
registers.flagZ = registers.a.toInt() == 0
registers.flagN = true
registers.flagH = (prevValue.toInt() and 0xF) < (newValue and 0xF)
registers.flagC = newValue < 0
/*Cycles: */ 4
}
/**
* **0x96** - *SUB (hl)* - Subtract *hl from a.
*/
val x96 : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
val prevValue = registers.a
val value = gb.ram.readByte(registers.hl.toLong() and 0xFFFF) and 0xFF
val newValue = prevValue - value
registers.a = newValue.toShort()
registers.flagZ = registers.a.toInt() == 0
registers.flagN = true
registers.flagH = (prevValue.toInt() and 0xF) < (newValue and 0xF)
registers.flagC = newValue < 0
/*Cycles: */ 8
}
/**
* *SBC a,X* - Subtract X + Carry flag from A.
*/
val x_SBC : (CPU, Registers, Gameboy, KMutableProperty1<Registers, Short>) -> (Int) = {
_, registers, _, target ->
val prevValue = registers.a
val value = target.get(registers)
val flag = if (registers.flagC) 1 else 0
val newValue = prevValue - value - flag
//((value + if (registers.flagC) 1 else 0) and 0xFF)
registers.a = newValue.toShort()
registers.flagZ = registers.a.toInt() == 0
registers.flagN = true
registers.flagH = (prevValue and 0x0f) - (value and 0x0f) - flag < 0
registers.flagC = newValue < 0
/*Cycles: */ 4
}
/**
* *SBC a,(hl)* - Subtract (hl) + Carry flag from A.
*/
val x9E : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
val prevValue = registers.a
val value = gb.ram.readByte(registers.hl.toLong() and 0xFFFF) and 0xFF
val flag = if (registers.flagC) 1 else 0
val newValue = prevValue - value - flag
registers.a = newValue.toShort()
registers.flagZ = registers.a.toInt() == 0
registers.flagN = true
registers.flagH = (prevValue and 0x0f) - (value and 0x0f) - flag < 0
registers.flagC = newValue < 0
/*Cycles: */ 8
}
/**
* **0xD6** - *SUB n* - Subtract n from a.
*/
val xD6 : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
val prevValue = registers.a
val value = getN(registers, gb)
val newValue = prevValue - value
registers.a = newValue.toShort()
registers.flagZ = registers.a.toInt() == 0
registers.flagN = true
registers.flagH = (prevValue and 0x0f) - (value and 0x0f) < 0
registers.flagC = newValue < 0
/*Cycles: */ 8
}
/**
* **0xDE** - *SBC n* - Subtract n + Carry from a.
*/
val xDE : (CPU, Registers, Gameboy) -> (Int) = {
_, registers, gb ->
val prevValue = registers.a
val value = getN(registers, gb)
val flag = if (registers.flagC) 1 else 0
val newValue = prevValue - value - flag
registers.a = newValue.toShort()
registers.flagZ = registers.a.toInt() == 0
registers.flagN = true
registers.flagH = (prevValue and 0x0f) - (value and 0x0f) - flag < 0
registers.flagC = newValue < 0
/*Cycles: */ 8
} | mit | 42ee5dfa2cea6c5b9e203d35d3e0f97d | 27.933555 | 104 | 0.61989 | 3.218034 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-block-logging-bukkit/src/main/kotlin/com/rpkit/blocklog/bukkit/listener/BlockIgniteListener.kt | 1 | 2898 | /*
* Copyright 2020 Ren Binden
*
* 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.rpkit.blocklog.bukkit.listener
import com.rpkit.blocklog.bukkit.RPKBlockLoggingBukkit
import com.rpkit.blocklog.bukkit.block.RPKBlockChangeImpl
import com.rpkit.blocklog.bukkit.block.RPKBlockHistoryService
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.bukkit.location.toRPKBlockLocation
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.RPKProfile
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority.MONITOR
import org.bukkit.event.Listener
import org.bukkit.event.block.BlockIgniteEvent
import java.time.LocalDateTime
class BlockIgniteListener(private val plugin: RPKBlockLoggingBukkit) : Listener {
@EventHandler(priority = MONITOR)
fun onBlockIgnite(event: BlockIgniteEvent) {
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
val characterService = Services[RPKCharacterService::class.java]
val blockHistoryService = Services[RPKBlockHistoryService::class.java]
if (blockHistoryService == null) {
plugin.logger.severe("Failed to retrieve block history service, did the plugin load correctly?")
return
}
val player = event.player
val minecraftProfile = if (player == null) null else minecraftProfileService?.getPreloadedMinecraftProfile(player)
val profile = minecraftProfile?.profile as? RPKProfile
val character = if (minecraftProfile == null) null else characterService?.getPreloadedActiveCharacter(minecraftProfile)
blockHistoryService.getBlockHistory(event.block.toRPKBlockLocation()).thenAccept { blockHistory ->
val blockChange = RPKBlockChangeImpl(
blockHistory = blockHistory,
time = LocalDateTime.now(),
profile = profile,
minecraftProfile = minecraftProfile,
character = character,
from = event.block.type,
to = event.block.type,
reason = "IGNITE"
)
plugin.server.scheduler.runTask(plugin, Runnable {
blockHistoryService.addBlockChange(blockChange)
})
}
}
} | apache-2.0 | 59d06460de0c6b89cebf38ded3ab6ff6 | 42.924242 | 127 | 0.723602 | 4.80597 | false | false | false | false |
FWDekker/intellij-randomness | src/main/kotlin/com/fwdekker/randomness/RandomnessIcons.kt | 1 | 11637 | package com.fwdekker.randomness
import com.intellij.openapi.util.IconLoader
import com.intellij.ui.ColorUtil
import com.intellij.util.IconUtil
import java.awt.Color
import java.awt.Component
import java.awt.Graphics
import java.awt.image.RGBImageFilter
import javax.swing.Icon
import kotlin.math.atan2
/**
* Basic Randomness icons.
*/
object RandomnessIcons {
/**
* The main icon of Randomness.
*/
val RANDOMNESS = IconLoader.findIcon("/icons/randomness.svg", this.javaClass.classLoader)!!
/**
* The template icon for template icons.
*/
val TEMPLATE = IconLoader.findIcon("/icons/template.svg", this.javaClass.classLoader)!!
/**
* The template icon for scheme icons.
*/
val SCHEME = IconLoader.findIcon("/icons/scheme.svg", this.javaClass.classLoader)!!
/**
* An icon for settings.
*/
val SETTINGS = IconLoader.findIcon("/icons/settings.svg", this.javaClass.classLoader)!!
/**
* A filled-in version of [SETTINGS].
*/
val SETTINGS_FILLED = IconLoader.findIcon("/icons/settings-filled.svg", this.javaClass.classLoader)!!
/**
* An icon for arrays.
*/
val ARRAY = IconLoader.findIcon("/icons/array.svg", this.javaClass.classLoader)!!
/**
* A filled-in version of [ARRAY].
*/
val ARRAY_FILLED = IconLoader.findIcon("/icons/array-filled.svg", this.javaClass.classLoader)!!
/**
* An icon for references.
*/
val REFERENCE = IconLoader.findIcon("/icons/reference.svg", this.javaClass.classLoader)!!
/**
* A filled-in version of [REFERENCE].
*/
val REFERENCE_FILLED = IconLoader.findIcon("/icons/reference-filled.svg", this.javaClass.classLoader)!!
/**
* An icon for repeated insertions.
*/
val REPEAT = IconLoader.findIcon("/icons/repeat.svg", this.javaClass.classLoader)!!
/**
* A filled-in version of [REPEAT].
*/
val REPEAT_FILLED = IconLoader.findIcon("/icons/repeat-filled.svg", this.javaClass.classLoader)!!
}
/**
* A colored icon with some text in it.
*
* @property base The underlying icon which should be given color; must be square.
* @property text The text to display inside the [base].
* @property colors The colors to give to the [base].
*/
data class TypeIcon(val base: Icon, val text: String, val colors: List<Color>) : Icon {
init {
require(colors.isNotEmpty()) { "At least one color must be defined." }
}
/**
* Returns an icon that describes both this icon's type and [other]'s type.
*
* @param other the icon to combine this icon with
* @return an icon that describes both this icon's type and [other]'s type
*/
fun combineWith(other: TypeIcon) =
TypeIcon(
RandomnessIcons.TEMPLATE,
if (this.text == other.text) this.text else "",
this.colors + other.colors
)
/**
* Paints the colored text icon.
*
* @param c a [Component] to get properties useful for painting
* @param g the graphics context
* @param x the X coordinate of the icon's top-left corner
* @param y the Y coordinate of the icon's top-left corner
*/
override fun paintIcon(c: Component?, g: Graphics?, x: Int, y: Int) {
if (c == null || g == null) return
val filter = RadialColorReplacementFilter(colors, Pair(iconWidth / 2, iconHeight / 2))
IconUtil.filterIcon(base, { filter }, c).paintIcon(c, g, x, y)
val textIcon = IconUtil.textToIcon(text, c, FONT_SIZE * iconWidth)
textIcon.paintIcon(c, g, x + (iconWidth - textIcon.iconWidth) / 2, y + (iconHeight - textIcon.iconHeight) / 2)
}
/**
* The width of the base icon.
*/
override fun getIconWidth() = base.iconWidth
/**
* The height of the base icon.
*/
override fun getIconHeight() = base.iconHeight
/**
* Holds constants.
*/
companion object {
/**
* The scale of the text inside the icon relative to the icon's size.
*/
const val FONT_SIZE = 12f / 32f
}
}
/**
* An overlay icon, which can be displayed on top of other icons.
*
* This icon is drawn as the [base] surrounded by a small margin of background color, which creates visual distance
* between the overlay and the rest of the icon this overlay is shown in top of. The background color is determined when
* the icon is drawn.
*
* @property base The base of the icon; must be square.
* @property background The background shape to ensure that the small margin of background color is also applied inside
* the [base], or `null` if [base] is already a solid shape.
*/
data class OverlayIcon(val base: Icon, val background: Icon? = null) : Icon {
/**
* Paints the overlay icon.
*
* @param c a [Component] to get properties useful for painting
* @param g the graphics context
* @param x the X coordinate of the icon's top-left corner
* @param y the Y coordinate of the icon's top-left corner
*/
override fun paintIcon(c: Component?, g: Graphics?, x: Int, y: Int) {
if (c == null || g == null) return
IconUtil.filterIcon(background ?: base, { RadialColorReplacementFilter(listOf(c.background)) }, c)
.paintIcon(c, g, x, y)
IconUtil.scale(base, c, 1 - 2 * MARGIN)
.paintIcon(c, g, x + (MARGIN * iconWidth).toInt(), y + (MARGIN * iconHeight).toInt())
}
/**
* The width of the base icon.
*/
override fun getIconWidth() = base.iconWidth
/**
* The height of the base icon.
*/
override fun getIconHeight() = base.iconHeight
/**
* Holds constants.
*/
companion object {
/**
* The margin around the base image that is filled with background color.
*
* This number is a fraction relative to the base image's size.
*/
const val MARGIN = 4f / 32
/**
* Overlay icon for arrays.
*/
val ARRAY by lazy { OverlayIcon(RandomnessIcons.ARRAY, RandomnessIcons.ARRAY_FILLED) }
/**
* Overlay icon for template references.
*/
val REFERENCE by lazy { OverlayIcon(RandomnessIcons.REFERENCE, RandomnessIcons.REFERENCE_FILLED) }
/**
* Overlay icon for repeated insertion.
*/
val REPEAT by lazy { OverlayIcon(RandomnessIcons.REPEAT, RandomnessIcons.REPEAT_FILLED) }
/**
* Overlay icon for settings.
*/
val SETTINGS by lazy { OverlayIcon(RandomnessIcons.SETTINGS, RandomnessIcons.SETTINGS_FILLED) }
}
}
/**
* An icon with various icons displayed on top of it as overlays.
*
* @property base
* @property overlays
*/
data class OverlayedIcon(val base: Icon, val overlays: List<Icon> = emptyList()) : Icon {
init {
require(base.iconWidth == base.iconHeight) { Bundle("icons.error.base_square") }
require(overlays.all { it.iconWidth == it.iconHeight }) { Bundle("icons.error.overlay_square") }
require(overlays.map { it.iconWidth }.toSet().size <= 1) { Bundle("icons.error.overlay_same_size") }
}
/**
* Returns a copy of this icon that has [icon] as an additional overlay icon.
*
* @param icon the additional overlay icon
* @return a copy of this icon that has [icon] as an additional overlay icon
*/
fun plusOverlay(icon: Icon) = copy(overlays = overlays + icon)
/**
* Paints the scheme icon.
*
* @param c a [Component] to get properties useful for painting
* @param g the graphics context
* @param x the X coordinate of the icon's top-left corner
* @param y the Y coordinate of the icon's top-left corner
*/
override fun paintIcon(c: Component?, g: Graphics?, x: Int, y: Int) {
if (c == null || g == null) return
base.paintIcon(c, g, x, y)
overlays.forEachIndexed { i, overlay ->
val overlaySize = iconWidth.toFloat() / OVERLAYS_PER_ROW
val overlayX = (i % OVERLAYS_PER_ROW * overlaySize).toInt()
val overlayY = (i / OVERLAYS_PER_ROW * overlaySize).toInt()
IconUtil.scale(overlay, null, overlaySize / overlay.iconWidth).paintIcon(c, g, overlayX, overlayY)
}
}
/**
* The width of the base icon.
*/
override fun getIconWidth() = base.iconWidth
/**
* The height of the base icon.
*/
override fun getIconHeight() = base.iconHeight
/**
* Holds constants.
*/
companion object {
/**
* Number of overlays displayed per row.
*/
const val OVERLAYS_PER_ROW = 2
}
}
/**
* Replaces all colors with one of [colors] depending on the angle relative to [center].
*
* @property colors The colors that should be used, in clockwise order starting north-west.
* @property center The center relative to which colors should be calculated; not required if only one color is given.
*/
class RadialColorReplacementFilter(
private val colors: List<Color>,
private val center: Pair<Int, Int>? = null
) : RGBImageFilter() {
init {
require(colors.isNotEmpty()) { Bundle("icons.error.one_colour") }
require(colors.size == 1 || center != null) { Bundle("icons.error.center_undefined") }
}
/**
* Returns the color to be displayed at ([x], [y]), considering the coordinates relative to the [center] and the
* relative alpha of the encountered color.
*
* @param x the X coordinate of the pixel
* @param y the Y coordinate of the pixel
* @param rgb `0` if and only if the pixel's color should be replaced
* @return `0` if [rgb] is `0`, or one of [colors] with its alpha shifted by [rgb]'s alpha otherwise
*/
override fun filterRGB(x: Int, y: Int, rgb: Int) =
if (rgb == 0) 0
else if (center == null || colors.size == 1) shiftAlpha(colors[0], Color(rgb, true)).rgb
else shiftAlpha(positionToColor(Pair(x - center.first, y - center.second)), Color(rgb, true)).rgb
/**
* Returns [toShift] which has its alpha multiplied by that of [shiftBy].
*
* @param toShift the color of which to shift the alpha
* @param shiftBy the color which has the alpha to shift by
* @return [toShift] which has its alpha multiplied by that of [shiftBy]
*/
private fun shiftAlpha(toShift: Color, shiftBy: Color) =
ColorUtil.withAlpha(toShift, asFraction(toShift.alpha) * asFraction(shiftBy.alpha))
/**
* Represents an integer in the range `[0, 256)` to a fraction of that range.
*
* @param number the number to represent as a fraction
* @return number as a fraction
*/
private fun asFraction(number: Int) = number / COMPONENT_MAX.toDouble()
/**
* Converts an offset to the [center] to a color in [colors].
*
* @param offset the offset to get the color for
* @return the color to be displayed at [offset]
*/
private fun positionToColor(offset: Pair<Int, Int>): Color {
val angle = 2 * Math.PI - (atan2(offset.second.toDouble(), offset.first.toDouble()) + STARTING_ANGLE)
val index = angle / (2 * Math.PI / colors.size)
return colors[Math.floorMod(index.toInt(), colors.size)]
}
/**
* Holds constants.
*/
companion object {
/**
* Maximum value for an RGB component.
*/
const val COMPONENT_MAX = 255
/**
* The angle in radians at which the first color should start being displayed.
*/
const val STARTING_ANGLE = -(3 * Math.PI / 4)
}
}
| mit | 86e4d1acf5db62f0de99b93a46fee50b | 31.415042 | 120 | 0.626622 | 4.076007 | false | false | false | false |
android/user-interface-samples | PerAppLanguages/compose_app/app/src/main/java/com/example/perapplanguages/ui/theme/Theme.kt | 1 | 1750 | /*
* 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.perapplanguages.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val DarkColorPalette = darkColors(
primary = Purple200,
primaryVariant = Purple700,
secondary = Teal200
)
private val LightColorPalette = lightColors(
primary = Purple500,
primaryVariant = Purple700,
secondary = Teal200
/* Other default colors to override
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
@Composable
fun PerAppLanguagesTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
} | apache-2.0 | 8bb4708edee5d192e6f9bc87cd6e9572 | 26.793651 | 75 | 0.715429 | 4.545455 | false | false | false | false |
sav007/apollo-android | apollo-compiler/src/test/kotlin/com/apollographql/apollo/compiler/JavaTypeResolverTest.kt | 1 | 4737 | package com.apollographql.apollo.compiler
import com.apollographql.apollo.compiler.ir.CodeGenerationContext
import com.apollographql.apollo.compiler.ir.CodeGenerationIR
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.TypeName
import org.junit.Assert
import org.junit.Test
import java.util.*
class JavaTypeResolverTest {
private val defaultContext = CodeGenerationContext(
reservedTypeNames = emptyList(),
typeDeclarations = emptyList(),
fragmentsPackage = "",
typesPackage = "",
customTypeMap = emptyMap(),
nullableValueType = NullableValueType.APOLLO_OPTIONAL,
generateAccessors = true,
ir = CodeGenerationIR(emptyList(), emptyList(), emptyList()),
useSemanticNaming = false)
private val defaultResolver = JavaTypeResolver(defaultContext, packageName)
@Test
fun resolveScalarType() {
Assert.assertEquals(ClassNames.STRING.annotated(Annotations.NONNULL), defaultResolver.resolve("String!"))
Assert.assertEquals(ClassNames.parameterizedOptional(ClassNames.STRING), defaultResolver.resolve("String", true))
Assert.assertEquals(TypeName.INT, defaultResolver.resolve("Int!"))
Assert.assertEquals(ClassNames.parameterizedOptional(TypeName.INT.box()), defaultResolver.resolve("Int", true))
Assert.assertEquals(TypeName.BOOLEAN, defaultResolver.resolve("Boolean!"))
Assert.assertEquals(ClassNames.parameterizedOptional(TypeName.BOOLEAN.box()),
defaultResolver.resolve("Boolean", true))
Assert.assertEquals(TypeName.DOUBLE, defaultResolver.resolve("Float!"))
Assert.assertEquals(ClassNames.parameterizedOptional(TypeName.DOUBLE.box()), defaultResolver.resolve("Float", true))
}
@Test
fun resolveListType() {
Assert.assertEquals(ClassNames.parameterizedListOf(ClassNames.STRING).annotated(Annotations.NONNULL),
defaultResolver.resolve("[String!]!"))
Assert.assertEquals(ClassNames.parameterizedOptional(ClassNames.parameterizedListOf(ClassNames.STRING)),
defaultResolver.resolve("[String!]", true))
Assert.assertEquals(ClassNames.parameterizedListOf(TypeName.INT.box()).annotated(Annotations.NONNULL),
defaultResolver.resolve("[Int]!"))
Assert.assertEquals(ClassNames.parameterizedOptional(ClassNames.parameterizedListOf(TypeName.INT.box())),
defaultResolver.resolve("[Int]", true))
Assert.assertEquals(ClassNames.parameterizedListOf(TypeName.BOOLEAN.box()).annotated(Annotations.NONNULL),
defaultResolver.resolve("[Boolean]!"))
Assert.assertEquals(ClassNames.parameterizedOptional(ClassNames.parameterizedListOf(TypeName.BOOLEAN.box())),
defaultResolver.resolve("[Boolean]", true))
Assert.assertEquals(ClassNames.parameterizedListOf(TypeName.DOUBLE.box()).annotated(Annotations.NONNULL),
defaultResolver.resolve("[Float]!"))
Assert.assertEquals(ClassNames.parameterizedOptional(ClassNames.parameterizedListOf(TypeName.DOUBLE.box())),
defaultResolver.resolve("[Float]", true))
}
@Test
fun resolveCustomType() {
Assert.assertEquals(ClassName.get("", "CustomClass").annotated(Annotations.NONNULL),
JavaTypeResolver(defaultContext, "").resolve("CustomClass!"))
Assert.assertEquals(ClassNames.parameterizedOptional(ClassName.get("", "CustomClass")),
JavaTypeResolver(defaultContext, "").resolve("CustomClass", true))
Assert.assertEquals(ClassName.get(packageName, "CustomClass").annotated(Annotations.NONNULL),
defaultResolver.resolve("CustomClass!"))
Assert.assertEquals(ClassNames.parameterizedOptional(ClassName.get(packageName, "CustomClass")),
defaultResolver.resolve("CustomClass", true))
}
@Test
fun resolveCustomScalarType() {
val context = defaultContext.copy(customTypeMap = mapOf("Date" to "java.util.Date", "UnsupportedType" to "Object",
"ID" to "java.lang.Integer"))
Assert.assertEquals(ClassName.get(Date::class.java).annotated(Annotations.NONNULL),
JavaTypeResolver(context, packageName).resolve("Date", false))
Assert.assertEquals(ClassNames.parameterizedOptional(Date::class.java),
JavaTypeResolver(context, packageName).resolve("Date", true))
Assert.assertEquals(ClassNames.parameterizedOptional(ClassName.get("", "Object")),
JavaTypeResolver(context, packageName).resolve("UnsupportedType", true))
Assert.assertEquals(ClassName.get(Integer::class.java).annotated(Annotations.NONNULL),
JavaTypeResolver(context, packageName).resolve("ID", false))
Assert.assertEquals(ClassNames.parameterizedOptional(Integer::class.java),
JavaTypeResolver(context, packageName).resolve("ID", true))
}
companion object {
private const val packageName = "com.example"
}
} | mit | 20adc8b89d8bcb764b5292e6eebc37a1 | 48.873684 | 120 | 0.756386 | 4.960209 | false | true | false | false |
HelloHuDi/usb-with-serial-port | usbserialport/src/main/java/com/hd/serialport/method/DeviceMeasureController.kt | 1 | 5961 | package com.hd.serialport.method
import android.annotation.SuppressLint
import android.content.Context
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.serialport.SerialPortFinder
import com.hd.serialport.config.UsbPortDeviceType
import com.hd.serialport.engine.SerialPortEngine
import com.hd.serialport.engine.UsbPortEngine
import com.hd.serialport.help.RequestUsbPermission
import com.hd.serialport.help.SystemSecurity
import com.hd.serialport.listener.SerialPortMeasureListener
import com.hd.serialport.listener.UsbMeasureListener
import com.hd.serialport.param.SerialPortMeasureParameter
import com.hd.serialport.param.UsbMeasureParameter
import com.hd.serialport.usb_driver.UsbSerialDriver
import com.hd.serialport.usb_driver.UsbSerialPort
import com.hd.serialport.usb_driver.UsbSerialProber
import com.hd.serialport.utils.L
import java.util.concurrent.ConcurrentHashMap
/**
* Created by hd on 2017/8/22 .
* usb device measurement controller
*/
@SuppressLint("StaticFieldLeak")
object DeviceMeasureController {
private lateinit var usbManager: UsbManager
private lateinit var usbPortEngine: UsbPortEngine
private lateinit var serialPortEngine: SerialPortEngine
fun init(context: Context, openLog: Boolean) {
init(context, openLog, null)
}
fun init(context: Context, openLog: Boolean, callback: RequestUsbPermission.RequestPermissionCallback? = null) {
init(context, openLog, true, callback)
}
fun init(context: Context, openLog: Boolean, requestUsbPermission: Boolean, callback: RequestUsbPermission.RequestPermissionCallback? = null) {
if (!SystemSecurity.check(context)) throw RuntimeException("There are a error in the current system usb module !")
L.allowLog = openLog
this.usbManager = context.applicationContext.getSystemService(Context.USB_SERVICE) as UsbManager
serialPortEngine = SerialPortEngine(context.applicationContext)
usbPortEngine = UsbPortEngine(context.applicationContext, usbManager)
if (requestUsbPermission)
RequestUsbPermission.newInstance().requestAllUsbDevicePermission(context.applicationContext, callback)
}
fun scanUsbPort(): List<UsbSerialDriver> = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager)
fun scanSerialPort(): ConcurrentHashMap<String, String> = SerialPortFinder().allDevices
fun measure(usbDevice: UsbDevice, deviceType: UsbPortDeviceType, parameter: UsbMeasureParameter, listener: UsbMeasureListener) {
val driver = UsbSerialProber.getDefaultProber().convertDriver(usbDevice,deviceType.value)
measure(driver.ports[0], parameter, listener)
}
fun measure(usbSerialDriverList: List<UsbSerialDriver>?, parameter: UsbMeasureParameter, listener: UsbMeasureListener) {
if (!usbSerialDriverList.isNullOrEmpty()) {
usbSerialDriverList.filter { it.deviceType == parameter.usbPortDeviceType || parameter.usbPortDeviceType == UsbPortDeviceType.USB_OTHERS }
.filter { it.ports[0] != null }.forEach { measure(it.ports[0], parameter, listener) }
} else {
val portList = scanUsbPort()
if (portList.isNullOrEmpty()) {
measure(portList, parameter, listener)
} else {
listener.measureError(parameter.tag,"not find ports")
}
}
}
fun measure(usbSerialPort: UsbSerialPort?, parameter: UsbMeasureParameter, listener: UsbMeasureListener) {
if (null != usbSerialPort) {
usbPortEngine.open(usbSerialPort, parameter, listener)
} else {
measure(usbSerialDriverList = null, parameter = parameter, listener = listener)
}
}
fun measure(paths: Array<String>?, parameter: SerialPortMeasureParameter, listeners: List<SerialPortMeasureListener>) {
if (!paths.isNullOrEmpty()) {
for (index in paths.indices) {
val path = paths[index]
when {
path.isNotEmpty() -> {
parameter.devicePath = path
when {
listeners.size == paths.size -> measure(parameter, listeners[index])
listeners.isNotEmpty() -> measure(parameter, listeners[0])
else -> L.d("not find serialPortMeasureListener")
}
}
index < listeners.size -> listeners[index].measureError(parameter.tag,"path is null")
else -> L.d("current position $index path is empty :$path ")
}
}
} else {
measure(SerialPortFinder().allDevicesPath, parameter, listeners)
}
}
fun measure(parameter: SerialPortMeasureParameter, listener: SerialPortMeasureListener) {
if (!parameter.devicePath.isNullOrEmpty()) {
serialPortEngine.open(parameter, listener)
} else {
measure(paths = null, parameter = parameter, listeners = listOf(listener))
}
}
/**write data by the tag filter, write all if tag==null*/
fun write(data: List<ByteArray>?, tag: Any? = null) {
L.d("DeviceMeasureController write usbPortEngine is working ${usbPortEngine.isWorking()}," +
"serialPortEngine is working ${serialPortEngine.isWorking()}")
when {
usbPortEngine.isWorking() -> usbPortEngine.write(tag, data)
serialPortEngine.isWorking() -> serialPortEngine.write(tag, data)
}
}
/**stop engine by the tag filter, stop all if tag==null*/
fun stop(tag: Any? = null) {
L.d("DeviceMeasureController stop")
when {
usbPortEngine.isWorking() -> usbPortEngine.stop(tag)
serialPortEngine.isWorking() -> serialPortEngine.stop(tag)
}
}
} | apache-2.0 | 36953379ecf00404bdd3a6543f6c55e3 | 43.827068 | 150 | 0.671867 | 4.682639 | false | false | false | false |
christophpickl/kpotpourri | common4k/src/main/kotlin/com/github/christophpickl/kpotpourri/common/string/string.kt | 1 | 4332 | package com.github.christophpickl.kpotpourri.common.string
/**
* Returns `null` if `isEmpty()` evaluates to true.
*/
fun String.nullIfEmpty() =
if (isEmpty()) null else this
/**
* Duplicate this string a couple of times.
*/
fun String.times(count: Int): String {
val symbol = this
return StringBuilder().apply {
0.until(count).forEach { append(symbol) }
}.toString()
}
/**
* If condition is met, wrap with left/right symbol.
*/
fun String.wrapIf(condition: Boolean, wrappingLeft: String, wrappingRight: String) =
if (condition) wrappingLeft + this + wrappingRight else this
/**
* Delegates to wrapIf(Boolean, String, String).
*/
fun String.wrapParenthesisIf(condition: Boolean) =
wrapIf(condition, "(", ")")
/**
* Combination of kotlin's `removePrefix` and `removeSuffix`.
*/
fun String.removePreAndSuffix(search: String) =
this.removePrefix(search).removeSuffix(search)
/**
* Very basic HTML tag encapsulation and line break conversion.
*/
fun String.htmlize() =
"<html>" + this.replace("\n", "<br/>") + "</html>"
/**
* Synonym for concatUrlParts().
*/
fun combineUrlParts(vararg parts: String) = concatUrlParts(*parts)
/**
* Synonym for concatUrlParts().
*/
fun joinUrlParts(vararg parts: String) = concatUrlParts(*parts)
/**
* Get sure of leading/trailing slashes.
*/
// or: infix joinUrlParts => url1 joinUrlParts url2
fun concatUrlParts(vararg parts: String): String {
if (parts.all(String::isEmpty)) {
return ""
}
val parts2 = parts.filter({ it.isNotEmpty() && it != "/" })
return (if (parts2.first().startsWith("/")) "/" else "") +
parts2.toList().map { it.removePreAndSuffix("/") }.joinToString("/")
// +(if(parts2.last().endsWith("/")) "/" else "")
}
/**
* Splits by whitespace but respects the double quite (") symbol to combine big argument.
*
* Example: a b "c d" => { "a", "b", "c d" }
*/
fun String.splitAsArguments(): List<String> {
if (isBlank()) {
return emptyList()
}
val result = mutableListOf<String>()
var stringCollect = StringBuilder()
var quoteOpen = false
(0 until length).forEach { index ->
val char = this[index]
if (char == '\"') {
if (quoteOpen) {
result += stringCollect.toString()
stringCollect = StringBuilder()
quoteOpen = false
} else {
quoteOpen = true
}
} else if (char == ' ') {
if (quoteOpen) {
stringCollect += char
} else {
result += stringCollect.toString()
stringCollect = StringBuilder()
}
} else {
stringCollect += char
}
}
result += stringCollect.toString() // append last
return result.filter(String::isNotEmpty)
}
/**
* Kotlin integration for: StringBuilder() += 'k'
*/
operator fun StringBuilder.plusAssign(char: Char) {
append(char)
}
/**
* Enhance the `contains` method receiving multiple substrings instead only of a single.
*/
fun String.containsAll(vararg substrings: String, ignoreCase: Boolean = false) =
substrings.all { this.contains(it, ignoreCase) }
/**
* Ensure a maximum length but cutting of overlengthy part and append some indication symbol.
*
* E.g.: "1234567" cut off by 3 => "123 ..."
*/
fun String.cutOffAt(cutOffLength: Int, indicationSymbol: String = " ..."): String {
if (this.length <= cutOffLength || this.length <= indicationSymbol.length) {
return this
}
if (cutOffLength <= indicationSymbol.length) {
return this.substring(0, cutOffLength)
}
return this.substring(0, cutOffLength - indicationSymbol.length) + indicationSymbol
}
/**
* Split this string into parts having each a maximum length of given maxLength.
*/
fun String.splitMaxWidth(maxLength: Int): List<String> {
require(maxLength > 0) { "Max length must be > 0! (was: $maxLength)" }
val lines = mutableListOf<String>()
var currentText = this
do {
val line = currentText.take(maxLength)
currentText = currentText.drop(line.length)
lines += line
} while (currentText.length > maxLength)
if (currentText.isNotEmpty()) {
lines += currentText
}
return lines
}
| apache-2.0 | 0e61d10bedf3e21fde208eece36b0521 | 27.688742 | 93 | 0.61819 | 4.059981 | false | false | false | false |
kotlintest/kotlintest | kotest-assertions/src/commonMain/kotlin/io/kotest/assertions/throwables/AnyThrowableHandling.kt | 1 | 3506 | package io.kotest.assertions.throwables
import io.kotest.assertions.AssertionCounter
import io.kotest.assertions.Failures
/**
* Verifies that a block of code throws any [Throwable]
*
* Use function to wrap a block of code that you want to verify that throws any kind of [Throwable], where using
* [shouldThrowAny] can't be used for any reason, such as an assignment of a variable (assignments are statements,
* therefore has no return value).
*
* If you want to verify a specific [Throwable], use [shouldThrowExactlyUnit].
*
* If you want to verify a [Throwable] and any subclass, use [shouldThrowUnit].
*
* @see [shouldThrowAny]
*/
inline fun shouldThrowAnyUnit(block: () -> Unit) = shouldThrowAny(block)
/**
* Verifies that a block of code does NOT throw any [Throwable]
*
* Use function to wrap a block of code that you want to make sure doesn't throw any [Throwable],
* where using [shouldNotThrowAny] can't be used for any reason, such as an assignment of a variable (assignments are
* statements, therefore has no return value).
*
* Note that executing this code is no different to executing [block] itself, as any uncaught exception will
* be propagated up anyways.
*
* @see [shouldNotThrowAny]
* @see [shouldNotThrowExactlyUnit]
* @see [shouldNotThrowUnit]
*
*/
inline fun shouldNotThrowAnyUnit(block: () -> Unit) = shouldNotThrowAny(block)
/**
* Verifies that a block of code throws any [Throwable]
*
* Use function to wrap a block of code that you want to verify that throws any kind of [Throwable].
*
* If you want to verify a specific [Throwable], use [shouldThrowExactly].
*
* If you want to verify a [Throwable] and any subclasses, use [shouldThrow]
*
*
* **Attention to assignment operations:**
*
* When doing an assignment to a variable, the code won't compile, because an assignment is not of type [Any], as required
* by [block]. If you need to test that an assignment throws a [Throwable], use [shouldThrowAnyUnit] or it's variations.
*
* ```
* val thrownThrowable: Throwable = shouldThrowAny {
* throw FooException() // This is a random Throwable, could be anything
* }
* ```
*
* @see [shouldThrowAnyUnit]
*/
inline fun shouldThrowAny(block: () -> Any?): Throwable {
AssertionCounter.inc()
val thrownException = try {
block()
null
} catch (e: Throwable) {
e
}
return thrownException ?: throw Failures.failure("Expected a throwable, but nothing was thrown.")
}
/**
* Verifies that a block of code does NOT throw any [Throwable]
*
* Use function to wrap a block of code that you want to make sure doesn't throw any [Throwable].
*
* Note that executing this code is no different to executing [block] itself, as any uncaught exception will
* be propagated up anyways.
*
* **Attention to assignment operations:**
*
* When doing an assignment to a variable, the code won't compile, because an assignment is not of type [Any], as required
* by [block]. If you need to test that an assignment doesn't throw a [Throwable], use [shouldNotThrowAnyUnit] or it's
* variations.
*
* @see [shouldNotThrowAnyUnit]
* @see [shouldNotThrowExactly]
* @see [shouldNotThrow]
*
*/
inline fun <T> shouldNotThrowAny(block: () -> T): T {
AssertionCounter.inc()
val thrownException = try {
return block()
} catch (e: Throwable) {
e
}
throw Failures.failure("No exception expected, but a ${thrownException::class.simpleName} was thrown.",
thrownException)
}
| apache-2.0 | 4ee5f10214e034cd7d121fb386fc6a01 | 32.711538 | 122 | 0.707929 | 4.053179 | false | false | false | false |
carlphilipp/chicago-commutes | android-app/src/foss/kotlin/fr/cph/chicago/core/activity/BusBoundActivity.kt | 1 | 10538 | /**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.core.activity
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.res.ResourcesCompat
import com.mapbox.mapboxsdk.Mapbox
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory
import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.mapboxsdk.geometry.LatLngBounds
import com.mapbox.mapboxsdk.maps.MapboxMap
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback
import com.mapbox.mapboxsdk.plugins.annotation.LineManager
import com.mapbox.mapboxsdk.plugins.annotation.LineOptions
import com.mapbox.mapboxsdk.utils.ColorUtils
import fr.cph.chicago.R
import fr.cph.chicago.core.App
import fr.cph.chicago.core.activity.station.BusStopActivity
import fr.cph.chicago.core.adapter.BusBoundAdapter
import fr.cph.chicago.core.model.BusPattern
import fr.cph.chicago.core.model.BusStop
import fr.cph.chicago.core.utils.getCurrentStyle
import fr.cph.chicago.core.utils.setupMapbox
import fr.cph.chicago.databinding.ActivityBusBoundMapboxBinding
import fr.cph.chicago.exception.CtaException
import fr.cph.chicago.service.BusService
import fr.cph.chicago.util.MapUtil
import fr.cph.chicago.util.Util
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import org.apache.commons.lang3.StringUtils
import timber.log.Timber
/**
* Activity that represents the bus bound activity
*
* @author Carl-Philipp Harmant
* @version 1
*/
class BusBoundActivity : AppCompatActivity(), OnMapReadyCallback {
companion object {
private val busService = BusService
private val util = Util
private val mapUtil = MapUtil
}
private var lineManager: LineManager? = null
private lateinit var binding: ActivityBusBoundMapboxBinding
private lateinit var busRouteId: String
private lateinit var busRouteName: String
private lateinit var bound: String
private lateinit var boundTitle: String
private lateinit var busBoundAdapter: BusBoundAdapter
private var busStops: List<BusStop> = listOf()
@SuppressLint("CheckResult")
public override fun onCreate(savedInstanceState: Bundle?) {
Mapbox.getInstance(this, getString(R.string.mapbox_token))
super.onCreate(savedInstanceState)
if (!this.isFinishing) {
binding = ActivityBusBoundMapboxBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.mapView.onCreate(savedInstanceState)
busRouteId = intent.getStringExtra(getString(R.string.bundle_bus_route_id)) ?: StringUtils.EMPTY
busRouteName = intent.getStringExtra(getString(R.string.bundle_bus_route_name)) ?: StringUtils.EMPTY
bound = intent.getStringExtra(getString(R.string.bundle_bus_bound)) ?: StringUtils.EMPTY
boundTitle = intent.getStringExtra(getString(R.string.bundle_bus_bound_title)) ?: StringUtils.EMPTY
binding.mapView.getMapAsync(this)
busBoundAdapter = BusBoundAdapter()
binding.listView.setOnItemClickListener { _, _, position, _ ->
val busStop = busBoundAdapter.getItem(position) as BusStop
val intent = Intent(applicationContext, BusStopActivity::class.java)
val extras = with(Bundle()) {
putString(getString(R.string.bundle_bus_stop_id), busStop.id.toString())
putString(getString(R.string.bundle_bus_stop_name), busStop.name)
putString(getString(R.string.bundle_bus_route_id), busRouteId)
putString(getString(R.string.bundle_bus_route_name), busRouteName)
putString(getString(R.string.bundle_bus_bound), bound)
putString(getString(R.string.bundle_bus_bound_title), boundTitle)
putDouble(getString(R.string.bundle_bus_latitude), busStop.position.latitude)
putDouble(getString(R.string.bundle_bus_longitude), busStop.position.longitude)
this
}
intent.putExtras(extras)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
binding.listView.adapter = busBoundAdapter
binding.busFilter.addTextChangedListener(object : TextWatcher {
private var busStopsFiltered: MutableList<BusStop> = mutableListOf()
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
busStopsFiltered = mutableListOf()
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
busStops
.filter { busStop -> StringUtils.containsIgnoreCase(busStop.name, s) }
.forEach { busStopsFiltered.add(it) }
}
override fun afterTextChanged(s: Editable) {
busBoundAdapter.updateBusStops(busStopsFiltered)
busBoundAdapter.notifyDataSetChanged()
}
})
binding.included.toolbar.title = "$busRouteId - $boundTitle"
binding.included.toolbar.navigationIcon = ResourcesCompat.getDrawable(resources, R.drawable.ic_arrow_back_white_24dp, theme)
binding.included.toolbar.setOnClickListener { finish() }
busService.loadAllBusStopsForRouteBound(busRouteId, bound)
.doOnSuccess { busStops ->
this.busStops = busStops
busBoundAdapter.updateBusStops(busStops)
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ busBoundAdapter.notifyDataSetChanged() },
{ error ->
Timber.e(error)
util.showOopsSomethingWentWrong(binding.listView)
})
// Preventing keyboard from moving background when showing up
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
}
}
override fun onMapReady(mapBox: MapboxMap) {
setupMapbox(mapBox, resources.configuration)
mapBox.setStyle(getCurrentStyle(resources.configuration)) { style ->
lineManager = LineManager(binding.mapView, mapBox, style)
busService.loadBusPattern(busRouteId, bound)
.observeOn(Schedulers.computation())
.map { busPattern: BusPattern ->
val pair = mapUtil.getBounds(busPattern.busStopsPatterns.map { it.position })
val latLngBounds = LatLngBounds.Builder()
.include(LatLng(pair.first.latitude, pair.first.longitude))
.include(LatLng(pair.second.latitude, pair.second.longitude))
.build()
val lineOptions = LineOptions()
.withLatLngs(busPattern.busStopsPatterns.map { patternPoint -> LatLng(patternPoint.position.latitude, patternPoint.position.longitude) })
.withLineColor(ColorUtils.colorToRgbaString(Color.BLACK))
.withLineWidth((application as App).lineWidthMapBox)
Pair(latLngBounds, lineOptions)
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ pair ->
mapBox.easeCamera(CameraUpdateFactory.newLatLngBounds(pair.first, 50), 500)
lineManager!!.create(pair.second)
},
{ error ->
Timber.e(error)
when (error) {
is CtaException -> util.showSnackBar(binding.bellowLayout, R.string.message_error_could_not_load_path)
else -> util.handleConnectOrParserException(error, binding.bellowLayout)
}
})
}
}
public override fun onResume() {
super.onResume()
binding.mapView.onResume()
}
public override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
busRouteId = savedInstanceState.getString(getString(R.string.bundle_bus_route_id)) ?: StringUtils.EMPTY
busRouteName = savedInstanceState.getString(getString(R.string.bundle_bus_route_name)) ?: StringUtils.EMPTY
bound = savedInstanceState.getString(getString(R.string.bundle_bus_bound)) ?: StringUtils.EMPTY
boundTitle = savedInstanceState.getString(getString(R.string.bundle_bus_bound_title)) ?: StringUtils.EMPTY
}
public override fun onSaveInstanceState(savedInstanceState: Bundle) {
savedInstanceState.putString(getString(R.string.bundle_bus_route_id), busRouteId)
savedInstanceState.putString(getString(R.string.bundle_bus_route_name), busRouteName)
savedInstanceState.putString(getString(R.string.bundle_bus_bound), bound)
savedInstanceState.putString(getString(R.string.bundle_bus_bound_title), boundTitle)
binding.mapView.onSaveInstanceState(savedInstanceState)
super.onSaveInstanceState(savedInstanceState)
}
override fun onStart() {
super.onStart()
binding.mapView.onStart()
}
override fun onStop() {
super.onStop()
binding.mapView.onStop()
}
override fun onLowMemory() {
super.onLowMemory()
binding.mapView.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
binding.mapView.onDestroy()
lineManager?.onDestroy()
}
}
| apache-2.0 | 4162a6ea9f261032b2511d607fe5a718 | 43.277311 | 161 | 0.66208 | 4.856221 | false | false | false | false |
ruuvi/Android_RuuvitagScanner | app/src/main/java/com/ruuvi/station/network/ui/EnterCodeFragment.kt | 1 | 2059 | package com.ruuvi.station.network.ui
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.ruuvi.station.R
import org.kodein.di.Kodein
import org.kodein.di.KodeinAware
import org.kodein.di.android.support.closestKodein
import com.ruuvi.station.util.extensions.viewModel
import kotlinx.android.synthetic.main.fragment_enter_code.*
import kotlinx.android.synthetic.main.fragment_enter_code.errorTextView
import kotlinx.android.synthetic.main.fragment_enter_code.skipTextView
class EnterCodeFragment : Fragment(R.layout.fragment_enter_code), KodeinAware {
override val kodein: Kodein by closestKodein()
private val viewModel: EnterCodeViewModel by viewModel()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupViewModel()
setupUI()
}
private fun setupViewModel() {
viewModel.errorTextObserve.observe(viewLifecycleOwner, Observer {
errorTextView.text = it
submitCodeButton.isEnabled = true
})
viewModel.successfullyVerifiedObserve.observe(viewLifecycleOwner, Observer {
if (it) {
activity?.onBackPressed()
}
})
}
private fun setupUI() {
submitCodeButton.setOnClickListener {
submitCodeButton.isEnabled = false
val code = enterCodeManuallyEditText.text.toString()
viewModel.verifyCode(code.trim())
}
val token = arguments?.getString("token")
if (token.isNullOrEmpty() == false) {
if (viewModel.signedIn) {
activity?.onBackPressed()
} else {
enterCodeManuallyEditText.setText(token)
submitCodeButton.performClick()
}
}
skipTextView.setOnClickListener {
requireActivity().finish()
}
}
companion object {
fun newInstance() = EnterCodeFragment()
}
} | mit | de9a13c86f5d312f1bf6f1a2b05b9052 | 29.746269 | 84 | 0.669743 | 4.867612 | false | false | false | false |
emce/smog | app/src/main/java/mobi/cwiklinski/smog/database/AppProvider.kt | 1 | 5188 | package mobi.cwiklinski.smog.database
import android.content.ContentProvider
import android.content.ContentProviderOperation
import android.content.ContentProviderResult
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.net.Uri
import java.util.*
class AppProvider : ContentProvider() {
var mOpenHelper: AppDatabase? = null;
val mMatcher: AppUriMatcher = AppUriMatcher()
var isBulk = false
override fun onCreate(): Boolean {
mOpenHelper = AppDatabase(context)
return true;
}
override fun insert(uri: Uri?, values: ContentValues?): Uri? {
var db: SQLiteDatabase = mOpenHelper!!.writableDatabase
var match = mMatcher.matcher.match(uri)
var syncToNetwork = !AppContract.hasCallerIsSyncAdapterParameter(uri!!)
when (match) {
AppUriMatcher.READINGS -> {
var donationId = db.insertOrThrow(AppContract.Readings.TABLE_NAME, null, values);
notifyChange(uri, syncToNetwork);
return AppContract.Readings.buildReadingUri(donationId.toString());
}
else -> {
throw UnsupportedOperationException("Unknown uri: " + uri)
}
}
}
override fun query(uri: Uri?, projection: Array<String>?, selection: String?,
selectionArgs: Array<out String>?, sortOrder: String?): Cursor? {
var db: SQLiteDatabase = mOpenHelper!!.readableDatabase
var match = mMatcher.matcher.match(uri)
if (uri != null) {
if (match > 0) {
var builder = buildSimpleSelection(uri)
var cursor = builder.where(selection, selectionArgs)
.query(db, projection, sortOrder)
cursor.setNotificationUri(context.contentResolver, uri)
return cursor
}
}
return null
}
override fun update(uri: Uri?, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int {
var db: SQLiteDatabase = mOpenHelper!!.writableDatabase
var builder = buildSimpleSelection(uri!!)
var retVal = builder.where(selection, selectionArgs).update(db, values!!);
var syncToNetwork: Boolean = !AppContract.hasCallerIsSyncAdapterParameter(uri);
context.contentResolver.notifyChange(uri, null, syncToNetwork);
return retVal
}
override fun delete(uri: Uri?, selection: String?, selectionArgs: Array<out String>?): Int {
if (uri!!.equals(AppContract.BASE_CONTENT_URI)) {
deleteDatabase()
context.contentResolver.notifyChange(uri, null, false);
return 1;
}
var db: SQLiteDatabase = mOpenHelper!!.writableDatabase
var builder = buildSimpleSelection(uri)
var retVal = builder.where(selection, selectionArgs).delete(db)
context.contentResolver.notifyChange(uri, null,
!AppContract.hasCallerIsSyncAdapterParameter(uri))
return retVal
}
override fun getType(uri: Uri?): String? {
var match = mMatcher.matcher.match(uri)
when (match) {
AppUriMatcher.READINGS -> return AppContract.Readings.CONTENT_TYPE
AppUriMatcher.READINGS_ID -> return AppContract.Readings.CONTENT_ITEM_TYPE
else -> {
throw UnsupportedOperationException("Unknown uri: " + uri)
}
}
}
fun buildSimpleSelection(uri: Uri) : SelectionBuilder {
var builder = SelectionBuilder()
var match = mMatcher.matcher.match(uri)
when (match) {
AppUriMatcher.READINGS -> return builder.table(AppContract.Readings.TABLE_NAME)
AppUriMatcher.READINGS_ID -> {
var donationId = AppContract.Readings.getReadingId(uri);
return builder.table(AppContract.Readings.TABLE_NAME)
.where(AppContract.Readings._ID + "=?", arrayOf(donationId))
}
else -> {
throw UnsupportedOperationException("Unknown uri: " + uri)
}
}
}
override fun applyBatch(operations: ArrayList<ContentProviderOperation>?): Array<out ContentProviderResult>? {
var db: SQLiteDatabase = mOpenHelper!!.writableDatabase
var results : Array<ContentProviderResult>?
isBulk = true
db.beginTransaction()
try {
var numOperations: Int = operations!!.size
results = arrayOf<ContentProviderResult>()
operations.forEach {
it.apply(this, results, numOperations)
numOperations--
}
db.setTransactionSuccessful();
} finally {
db.endTransaction()
}
return results
}
fun notifyChange(uri: Uri, syncToNetwork: Boolean) {
if (!isBulk) {
context.contentResolver.notifyChange(uri, null, syncToNetwork);
}
}
fun deleteDatabase() {
mOpenHelper!!.close()
mOpenHelper!!.deleteDatabase(context);
mOpenHelper = AppDatabase(context);
}
}
| apache-2.0 | 95e580e6df109f6b2855714d1dd69644 | 37.147059 | 120 | 0.622783 | 5.007722 | false | false | false | false |
ysl3000/PathfindergoalAPI | Pathfinder_1_16/src/main/java/com/github/ysl3000/bukkit/pathfinding/craftbukkit/v1_16_R2/pathfinding/CraftPathfinderManager.kt | 1 | 1159 | package com.github.ysl3000.bukkit.pathfinding.craftbukkit.v1_16_R2.pathfinding
import com.github.ysl3000.bukkit.pathfinding.craftbukkit.v1_16_R2.entity.CraftInsentient
import com.github.ysl3000.bukkit.pathfinding.entity.Insentient
import com.github.ysl3000.bukkit.pathfinding.pathfinding.PathfinderManagerMob
import com.github.ysl3000.bukkit.pathfinding.pathfinding.PathfinderPlayer
import org.bukkit.entity.*
class CraftPathfinderManager : PathfinderManagerMob {
override fun getPathfinderGoalEntity(creature: Creature): Insentient = CraftInsentient(creature)
override fun getPathfinderGoalEntity(mob: Mob): Insentient = CraftInsentient(mob)
override fun getPathfinderGoalEntity(flying: Flying): Insentient = CraftInsentient(flying)
override fun getPathfinderGoalEntity(ambient: Ambient): Insentient = CraftInsentient(ambient)
override fun getPathfinderGoalEntity(slime: Slime): Insentient = CraftInsentient(slime)
override fun getPathfinderGoalEntity(enderDragon: EnderDragon): Insentient = CraftInsentient(enderDragon)
override fun getPathfinderPlayer(player: Player): PathfinderPlayer = CraftPathfinderPlayer(player)
} | mit | 08509e299fec62f277fb04e440bd88b2 | 47.333333 | 109 | 0.830889 | 4.406844 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl-plugins/src/integTest/kotlin/org/gradle/kotlin/dsl/plugins/precompiled/PrecompiledScriptPluginTemplatesTest.kt | 1 | 10797 | package org.gradle.kotlin.dsl.plugins.precompiled
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.inOrder
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.initialization.Settings
import org.gradle.api.invocation.Gradle
import org.gradle.api.tasks.TaskContainer
import org.gradle.api.tasks.bundling.Jar
import org.gradle.kotlin.dsl.fixtures.assertFailsWith
import org.gradle.kotlin.dsl.fixtures.assertInstanceOf
import org.gradle.kotlin.dsl.fixtures.assertStandardOutputOf
import org.gradle.kotlin.dsl.fixtures.withFolders
import org.gradle.kotlin.dsl.precompile.PrecompiledInitScript
import org.gradle.kotlin.dsl.precompile.PrecompiledProjectScript
import org.gradle.kotlin.dsl.precompile.PrecompiledSettingsScript
import org.gradle.test.fixtures.file.LeaksFileHandles
import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
@LeaksFileHandles("Kotlin Compiler Daemon working directory")
class PrecompiledScriptPluginTemplatesTest : AbstractPrecompiledScriptPluginTest() {
@Test
fun `Project scripts from regular source-sets are compiled via the PrecompiledProjectScript template`() {
givenPrecompiledKotlinScript("my-project-script.gradle.kts", """
task("my-task")
""")
val task = mock<Task>()
val project = mock<Project> {
on { task(any()) } doReturn task
}
assertInstanceOf<PrecompiledProjectScript>(
instantiatePrecompiledScriptOf(
project,
"My_project_script_gradle"
)
)
inOrder(project, task) {
verify(project).task("my-task")
verifyNoMoreInteractions()
}
}
@Test
fun `Settings scripts from regular source-sets are compiled via the PrecompiledSettingsScript template`() {
givenPrecompiledKotlinScript("my-settings-script.settings.gradle.kts", """
include("my-project")
""")
val settings = mock<Settings>()
assertInstanceOf<PrecompiledSettingsScript>(
instantiatePrecompiledScriptOf(
settings,
"My_settings_script_settings_gradle"))
verify(settings).include("my-project")
}
@Test
fun `Gradle scripts from regular source-sets are compiled via the PrecompiledInitScript template`() {
givenPrecompiledKotlinScript("my-gradle-script.init.gradle.kts", """
useLogger("my-logger")
""")
val gradle = mock<Gradle>()
assertInstanceOf<PrecompiledInitScript>(
instantiatePrecompiledScriptOf(
gradle,
"My_gradle_script_init_gradle"))
verify(gradle).useLogger("my-logger")
}
@Test
fun `plugin adapter doesn't mask exceptions thrown by precompiled script`() {
// given:
val expectedMessage = "Not on my watch!"
withKotlinDslPlugin()
withFile("src/main/kotlin/my-project-script.gradle.kts", """
throw IllegalStateException("$expectedMessage")
""")
// when:
compileKotlin()
// then:
@Suppress("unchecked_cast")
val pluginAdapter =
loadCompiledKotlinClass("MyProjectScriptPlugin")
.getConstructor()
.newInstance() as Plugin<Project>
val exception =
assertFailsWith(IllegalStateException::class) {
pluginAdapter.apply(mock())
}
assertThat(
exception.message,
equalTo(expectedMessage))
}
@Test
fun `implicit imports are available to precompiled scripts`() {
givenPrecompiledKotlinScript("my-project-script.gradle.kts", """
task<Jar>("jar")
""")
val task = mock<Jar>()
val tasks = mock<TaskContainer> {
on { create(any<String>(), any<Class<Task>>()) } doReturn task
}
val project = mock<Project> {
on { getTasks() } doReturn tasks
}
instantiatePrecompiledScriptOf(
project,
"My_project_script_gradle")
verify(tasks).create("jar", Jar::class.java)
}
@Test
fun `precompiled script plugin ids are honored by java-gradle-plugin plugin`() {
projectRoot.withFolders {
"plugin" {
"src/main/kotlin" {
// Plugin id for script with no package declaration is simply
// the file name minus the script file extension.
// Project plugins must be named `*.gradle.kts`
withFile("my-plugin.gradle.kts", """
println("my-plugin applied!")
""")
// Settings plugins must be named `*.settings.gradle.kts`
withFile("my-settings-plugin.settings.gradle.kts", """
println("my-settings-plugin applied!")
""")
// Gradle object plugins, a.k.a., precompiled init script plugins,
// must be named `*.init.gradle.kts`
withFile("my-init-plugin.init.gradle.kts", """
println("my-init-plugin applied!")
""")
// plugin id for script with package declaration is the
// package name dot the file name minus the `.gradle.kts` suffix
withFile("org/acme/my-other-plugin.gradle.kts", """
package org.acme
println("my-other-plugin applied!")
""")
}
withFile("settings.gradle.kts", defaultSettingsScript)
withFile(
"build.gradle.kts",
scriptWithKotlinDslPlugin()
)
}
}
executer.inDirectory(file("plugin")).withTasks("jar").run()
val pluginJar = file("plugin/build/libs/plugin.jar")
assertThat("pluginJar was built", pluginJar.exists())
val movedPluginJar = file("plugin.jar")
pluginJar.renameTo(movedPluginJar)
withSettings("""
buildscript {
dependencies {
classpath(files("${movedPluginJar.name}"))
}
}
gradle.apply<MyInitPluginPlugin>()
apply(plugin = "my-settings-plugin")
""")
withFile("buildSrc/build.gradle", """
dependencies {
api files("../${movedPluginJar.name}")
}
""")
withBuildScript("""
plugins {
id("my-plugin")
id("org.acme.my-other-plugin")
}
""")
assertThat(
build("help").output,
allOf(
containsString("my-init-plugin applied!"),
containsString("my-settings-plugin applied!"),
containsString("my-plugin applied!"),
containsString("my-other-plugin applied!")
)
)
}
@Test
fun `precompiled script plugins can be published by maven-publish plugin`() {
withFolders {
"plugins" {
"src/main/kotlin" {
withFile("my-plugin.gradle.kts", """
println("my-plugin applied!")
""")
withFile("org/acme/my-other-plugin.gradle.kts", """
package org.acme
println("org.acme.my-other-plugin applied!")
""")
withFile("org/acme/plugins/my-init.init.gradle.kts", """
package org.acme.plugins
println("org.acme.plugins.my-init applied!")
""")
}
withFile("settings.gradle.kts", defaultSettingsScript)
withFile("build.gradle.kts", """
plugins {
`kotlin-dsl`
`maven-publish`
}
group = "org.acme"
version = "0.1.0"
$repositoriesBlock
publishing {
repositories {
maven(url = "../repository")
}
}
""")
}
}
build(existing("plugins"), "publish")
val repositoriesBlock = """
repositories {
maven { url = uri("./repository") }
}
"""
withSettings("""
pluginManagement {
$repositoriesBlock
}
""")
withBuildScript("""
plugins {
id("my-plugin") version "0.1.0"
id("org.acme.my-other-plugin") version "0.1.0"
}
""")
val initScript =
withFile("my-init-script.init.gradle.kts", """
initscript {
$repositoriesBlock
dependencies {
classpath("org.acme:plugins:0.1.0")
}
}
apply<org.acme.plugins.MyInitPlugin>()
// TODO: can't apply plugin by id
// apply(plugin = "org.acme.plugins.my-init")
""")
assertThat(
build("help", "-I", initScript.canonicalPath).output,
allOf(
containsString("org.acme.plugins.my-init applied!"),
containsString("my-plugin applied!"),
containsString("org.acme.my-other-plugin applied!")
)
)
}
@Test
fun `precompiled script plugins can use Kotlin 1 dot 3 language features`() {
givenPrecompiledKotlinScript("my-plugin.gradle.kts", """
// Coroutines are no longer experimental
val coroutine = sequence {
// Unsigned integer types
yield(42UL)
}
when (val value = coroutine.first()) {
42UL -> print("42!")
else -> throw IllegalStateException()
}
""")
assertStandardOutputOf("42!") {
instantiatePrecompiledScriptOf(
mock<Project>(),
"My_plugin_gradle"
)
}
}
}
| apache-2.0 | b26924f9339b48090ebf4ab83f941d02 | 28.102426 | 111 | 0.53061 | 5.208394 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/ide/inspections/fixes/import/ui.kt | 1 | 6511 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.fixes.import
import com.intellij.codeInsight.navigation.NavigationUtil
import com.intellij.ide.util.DefaultPsiElementCellRenderer
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import com.intellij.psi.PsiElement
import com.intellij.ui.popup.list.ListPopupImpl
import com.intellij.ui.popup.list.PopupListElementRenderer
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.TestOnly
import org.rust.cargo.icons.CargoIcons
import org.rust.cargo.project.workspace.PackageOrigin
import org.rust.ide.icons.RsIcons
import org.rust.openapiext.isUnitTestMode
import java.awt.BorderLayout
import java.awt.Component
import javax.swing.*
private var MOCK: ImportItemUi? = null
fun showItemsToImportChooser(
project: Project,
dataContext: DataContext,
items: List<ImportCandidate>,
callback: (ImportCandidate) -> Unit
) {
val itemImportUi = if (isUnitTestMode) {
MOCK ?: error("You should set mock ui via `withMockImportItemUi`")
} else {
PopupImportItemUi(project, dataContext)
}
itemImportUi.chooseItem(items, callback)
}
@TestOnly
fun withMockImportItemUi(mockUi: ImportItemUi, action: () -> Unit) {
MOCK = mockUi
try {
action()
} finally {
MOCK = null
}
}
interface ImportItemUi {
fun chooseItem(items: List<ImportCandidate>, callback: (ImportCandidate) -> Unit)
}
private class PopupImportItemUi(private val project: Project, private val dataContext: DataContext) : ImportItemUi {
override fun chooseItem(items: List<ImportCandidate>, callback: (ImportCandidate) -> Unit) {
// TODO: sort items in popup
val step = object : BaseListPopupStep<ImportCandidate>("Item to Import", items) {
override fun isAutoSelectionEnabled(): Boolean = false
override fun isSpeedSearchEnabled(): Boolean = true
override fun hasSubstep(selectedValue: ImportCandidate?): Boolean = false
override fun onChosen(selectedValue: ImportCandidate?, finalChoice: Boolean): PopupStep<*>? {
if (selectedValue == null) return PopupStep.FINAL_CHOICE
return doFinalStep { callback(selectedValue) }
}
override fun getTextFor(value: ImportCandidate): String = value.info.usePath
override fun getIconFor(value: ImportCandidate): Icon? = value.importItem.item.getIcon(0)
}
val popup = object : ListPopupImpl(step) {
override fun getListElementRenderer(): ListCellRenderer<*> {
val baseRenderer = super.getListElementRenderer() as PopupListElementRenderer<Any>
val psiRenderer = RsElementCellRenderer()
return ListCellRenderer<Any> { list, value, index, isSelected, cellHasFocus ->
val panel = JPanel(BorderLayout())
baseRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
panel.add(baseRenderer.nextStepLabel, BorderLayout.EAST)
val importItem = (value as? ImportCandidate)?.importItem
panel.add(psiRenderer.getListCellRendererComponent(list, importItem, index, isSelected, cellHasFocus))
panel
}
}
}
NavigationUtil.hidePopupIfDumbModeStarts(popup, project)
popup.showInBestPositionFor(dataContext)
}
}
private class RsElementCellRenderer : DefaultPsiElementCellRenderer() {
private val rightRender: LibraryCellRender = LibraryCellRender()
private var importItem: ImportItem? = null
override fun getRightCellRenderer(value: Any?): DefaultListCellRenderer? = rightRender
override fun getListCellRendererComponent(list: JList<*>?, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component {
val realValue = if (value is ImportItem) {
// Generally, it's rather hacky but I don't know another way
// how to use functionality of `PsiElementListCellRenderer`
// and pass additional info with psi element at same time
importItem = value
value.item
} else {
value
}
return super.getListCellRendererComponent(list, realValue, index, isSelected, cellHasFocus)
}
override fun getElementText(element: PsiElement): String = importItem?.itemName ?: super.getElementText(element)
override fun getContainerText(element: PsiElement, name: String): String? {
val importItem = importItem
return if (importItem != null) {
val crateName = importItem.containingCargoTarget?.normName ?: return null
val parentPath = importItem.parentCrateRelativePath ?: return null
"($crateName::$parentPath)"
} else {
super.getContainerText(element, name)
}
}
private inner class LibraryCellRender : DefaultListCellRenderer() {
override fun getListCellRendererComponent(list: JList<*>, value: Any?, index: Int,
isSelected: Boolean, cellHasFocus: Boolean): Component {
val component = super.getListCellRendererComponent(list, null, index, isSelected, cellHasFocus)
val textWithIcon = textWithIcon()
if (textWithIcon != null) {
text = textWithIcon.first
icon = textWithIcon.second
}
border = BorderFactory.createEmptyBorder(0, 0, 0, 2)
horizontalTextPosition = SwingConstants.LEFT
background = if (isSelected) UIUtil.getListSelectionBackground() else UIUtil.getListBackground()
foreground = if (isSelected) UIUtil.getListSelectionForeground() else UIUtil.getInactiveTextColor()
return component
}
private fun textWithIcon(): Pair<String, Icon>? {
val pkg = importItem?.containingCargoTarget?.pkg ?: return null
return when (pkg.origin) {
PackageOrigin.STDLIB -> pkg.normName to RsIcons.RUST
PackageOrigin.DEPENDENCY, PackageOrigin.TRANSITIVE_DEPENDENCY -> pkg.normName to CargoIcons.ICON
else -> null
}
}
}
}
| mit | 369933498764f4d41952bdca2cb45d65 | 41.555556 | 144 | 0.675933 | 5.051202 | false | false | false | false |
Jonatino/Xena | src/main/java/org/xena/cs/Game.kt | 1 | 1199 | /*
* Copyright 2016 Jonathan Beaudoin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("GameKT")
package org.xena.cs
import it.unimi.dsi.fastutil.longs.Long2IntArrayMap
import org.xena.Indexer
@JvmField
val me = Me()
@JvmField
val entityMap = Long2IntArrayMap(256)
@JvmField
val entities = Indexer<GameEntity>(128)
@JvmField
val clientState = ClientState()
operator fun Indexer<GameEntity>.get(address: Long): GameEntity? {
var index = -1
if (entityMap.containsKey(address)) index = entityMap.get(address)
if (index == -1) {
return null
}
return entities.get(index)
}
fun removePlayers() {
entityMap.clear()
entities.clear()
}
| apache-2.0 | e7394635dd2537dbf9e6e67360a3ceb6 | 26.25 | 78 | 0.722269 | 3.579104 | false | false | false | false |
clarkcb/xsearch | kotlin/ktsearch/src/main/kotlin/ktsearch/SearchSettings.kt | 1 | 4493 | package ktsearch
/**
* @author cary on 7/23/16.
*/
data class SearchSettings(val archivesOnly: Boolean,
val colorize: Boolean,
val debug: Boolean,
val excludeHidden: Boolean,
val firstMatch: Boolean,
val inArchiveExtensions: Set<String>,
val inArchiveFilePatterns: Set<Regex>,
val inDirPatterns: Set<Regex>,
val inExtensions: Set<String>,
val inFilePatterns: Set<Regex>,
val inFileTypes: Set<FileType>,
val inLinesAfterPatterns: Set<Regex>,
val inLinesBeforePatterns: Set<Regex>,
val linesAfter: Int,
val linesAfterToPatterns: Set<Regex>,
val linesAfterUntilPatterns: Set<Regex>,
val linesBefore: Int,
val listDirs: Boolean,
val listFiles: Boolean,
val listLines: Boolean,
val maxLineLength: Int,
val multiLineSearch: Boolean,
val outArchiveExtensions: Set<String>,
val outArchiveFilePatterns: Set<Regex>,
val outDirPatterns: Set<Regex>,
val outExtensions: Set<String>,
val outFilePatterns: Set<Regex>,
val outFileTypes: Set<FileType>,
val outLinesAfterPatterns: Set<Regex>,
val outLinesBeforePatterns: Set<Regex>,
val printResults: Boolean,
val printUsage: Boolean,
val printVersion: Boolean,
val recursive: Boolean,
val searchArchives: Boolean,
val searchPatterns: Set<Regex>,
val startPath: String?,
val textFileEncoding: String,
val uniqueLines: Boolean,
val verbose: Boolean)
fun getDefaultSettings() : SearchSettings {
return SearchSettings(
archivesOnly = false,
colorize = true,
debug = false,
excludeHidden = true,
firstMatch = false,
inArchiveExtensions = setOf(),
inArchiveFilePatterns = setOf(),
inDirPatterns = setOf(),
inExtensions = setOf(),
inFilePatterns = setOf(),
inFileTypes = setOf(),
inLinesAfterPatterns = setOf(),
inLinesBeforePatterns = setOf(),
linesAfter = 0,
linesAfterToPatterns = setOf(),
linesAfterUntilPatterns = setOf(),
linesBefore = 0,
listDirs = false,
listFiles = false,
listLines = false,
maxLineLength = 150,
multiLineSearch = false,
outArchiveExtensions = setOf(),
outArchiveFilePatterns = setOf(),
outDirPatterns = setOf(),
outExtensions = setOf(),
outFilePatterns = setOf(),
outFileTypes = setOf(),
outLinesAfterPatterns = setOf(),
outLinesBeforePatterns = setOf(),
printResults = false,
printUsage = false,
printVersion = false,
recursive = true,
searchArchives = false,
searchPatterns = setOf(),
startPath = null,
textFileEncoding = "UTF-8",
uniqueLines = false,
verbose = false)
}
fun addExtensions(ext: String, extensions: Set<String>): Set<String> {
val exts = ext.split(',').filter { it.isNotEmpty() }
return extensions.plus(exts)
}
fun addFileTypes(ft: String, filetypes: Set<FileType>): Set<FileType> {
val fts = ft.split(',').filter { it.isNotEmpty() }.map { fromName(it) }
return filetypes.plus(fts)
}
fun setArchivesOnly(ss: SearchSettings, archivesOnly: Boolean): SearchSettings {
return ss.copy(archivesOnly = archivesOnly, searchArchives = archivesOnly || ss.searchArchives)
}
fun setDebug(ss: SearchSettings, debug: Boolean): SearchSettings {
return ss.copy(debug = debug, verbose = debug || ss.verbose)
}
| mit | 25e73051095bc32d7bff2c636b8f3699 | 40.990654 | 99 | 0.507679 | 5.581366 | false | false | false | false |
yshrsmz/monotweety | app2/src/main/java/net/yslibrary/monotweety/ui/base/Debounce.kt | 1 | 1095 | package net.yslibrary.monotweety.ui.base
import android.view.View
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/**
* https://medium.com/swlh/android-click-debounce-80b3f2e638f3
*/
fun <T> debounce(
delayMillis: Long = 800,
scope: CoroutineScope,
action: (T) -> Unit,
): (T) -> Unit {
var debounceJob: Job? = null
return { param: T ->
if (debounceJob == null) {
debounceJob = scope.launch {
action(param)
delay(delayMillis)
debounceJob = null
}
}
}
}
inline fun View.setDebounceClickListener(
timeoutMillis: Long = 800,
crossinline listener: (View) -> Unit,
) {
setOnClickListener(object : View.OnClickListener {
private var throttling = false
override fun onClick(view: View) {
if (throttling) return
throttling = true
view.postDelayed({ throttling = false }, timeoutMillis)
listener(view)
}
})
}
| apache-2.0 | 71d4278cf65ac20645d8c603ae77fb4f | 23.886364 | 67 | 0.611872 | 4.163498 | false | false | false | false |
msal/muzei-nationalgeographic | muzei-nationalgeographic/src/main/kotlin/de/msal/muzei/nationalgeographic/NationalGeographicWorker.kt | 1 | 3659 | package de.msal.muzei.nationalgeographic
import android.content.Context
import android.util.Log
import androidx.core.net.toUri
import androidx.work.*
import com.google.android.apps.muzei.api.provider.Artwork
import com.google.android.apps.muzei.api.provider.ProviderContract
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
class NationalGeographicWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
companion object {
var isRandom = false
internal fun enqueueLoad(random: Boolean) {
this.isRandom = random
WorkManager
.getInstance()
.enqueue(OneTimeWorkRequestBuilder<NationalGeographicWorker>()
.setConstraints(Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build())
.build())
}
}
override fun doWork(): Result {
// fetch photo
val photo = try {
if (isRandom) {
// get a random photo of a month between October 2017 and now
val now = Calendar.getInstance(TimeZone.getTimeZone("Europe/London"))
val randYear = getRand(2017, now.get(Calendar.YEAR))
val randMonth =
if (randYear == now.get(Calendar.YEAR))
getRand(1, now.get(Calendar.MONTH) + 1).month()
else
getRand(if (randYear == 2017) 10 else 1, 12).month()
NationalGeographicService.getPhotosOfTheDay(randYear, randMonth)?.random()
} else {
// get most recent photo
NationalGeographicService.getPhotoOfTheDay()
}
} catch (e: IOException) {
Log.w(javaClass.simpleName, "Error reading API", e)
return Result.retry()
}
// check if successful
if (photo == null) {
Log.w(javaClass.simpleName, "No photo returned from API.")
return Result.failure()
} else if (photo.image?.url == null) {
Log.w(javaClass.simpleName, "Photo url is null (photo id: ${photo.uuid}).")
return Result.failure()
}
// success -> set Artwork
val artwork = Artwork(
title = photo.image.title, // title
byline = photo.credit, // photographer
attribution = photo.date?.let { SimpleDateFormat.getDateInstance().format(it.time)}, // date
persistentUri = photo.image.url?.toUri(), // image url
token = photo.image.url, // use url as token, as it is unique
metadata = photo.caption, // image description
)
val providerClient = ProviderContract.getProviderClient<NationalGeographicArtProvider>(applicationContext)
if (isRandom) {
providerClient.addArtwork(artwork)
} else {
providerClient.setArtwork(artwork)
}
return Result.success()
}
/**
* @param min inclusive
* @param max inclusive
* @return the random number
*/
private fun getRand(min: Int, max: Int): Int {
val rand = Random()
return rand.nextInt(max - min + 1) + min
}
private fun Int?.month() : String? {
return when {
this == 1 -> "january"
this == 2 -> "february"
this == 3 -> "march"
this == 4 -> "april"
this == 5 -> "may"
this == 6 -> "june"
this == 7 -> "july"
this == 8 -> "august"
this == 9 -> "september"
this == 10 -> "october"
this == 11 -> "november"
this == 12 -> "december"
else -> null
}
}
}
| gpl-3.0 | a3f52f468cf80f745c3544224384a6db | 33.196262 | 114 | 0.577753 | 4.429782 | false | false | false | false |
google/ksp | kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/impl/symbol/kotlin/KSValueParameterImpl.kt | 1 | 3788 | /*
* Copyright 2022 Google LLC
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
package com.google.devtools.ksp.impl.symbol.kotlin
import com.google.devtools.ksp.KSObjectCache
import com.google.devtools.ksp.symbol.*
import org.jetbrains.kotlin.analysis.api.fir.symbols.KtFirValueParameterSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtValueParameterSymbol
import org.jetbrains.kotlin.fir.java.JavaTypeParameterStack
import org.jetbrains.kotlin.fir.java.declarations.FirJavaValueParameter
import org.jetbrains.kotlin.fir.java.resolveIfJavaType
import org.jetbrains.kotlin.fir.symbols.SymbolInternals
class KSValueParameterImpl private constructor(
private val ktValueParameterSymbol: KtValueParameterSymbol,
override val parent: KSAnnotated
) : KSValueParameter {
companion object : KSObjectCache<KtValueParameterSymbol, KSValueParameterImpl>() {
fun getCached(ktValueParameterSymbol: KtValueParameterSymbol, parent: KSAnnotated) =
cache.getOrPut(ktValueParameterSymbol) { KSValueParameterImpl(ktValueParameterSymbol, parent) }
}
override val name: KSName? by lazy {
KSNameImpl.getCached(ktValueParameterSymbol.name.asString())
}
@OptIn(SymbolInternals::class)
override val type: KSTypeReference by lazy {
// FIXME: temporary workaround before upstream fixes java type refs.
if (origin == Origin.JAVA || origin == Origin.JAVA_LIB) {
((ktValueParameterSymbol as KtFirValueParameterSymbol).firSymbol.fir as FirJavaValueParameter).also {
// can't get containing class for FirJavaValueParameter, using empty stack for now.
it.returnTypeRef =
it.returnTypeRef.resolveIfJavaType(it.moduleData.session, JavaTypeParameterStack.EMPTY)
}
}
KSTypeReferenceImpl.getCached(ktValueParameterSymbol.returnType, this@KSValueParameterImpl)
}
override val isVararg: Boolean by lazy {
ktValueParameterSymbol.isVararg
}
override val isNoInline: Boolean
get() = TODO("Not yet implemented")
override val isCrossInline: Boolean
get() = TODO("Not yet implemented")
override val isVal: Boolean
get() = TODO("Not yet implemented")
override val isVar: Boolean
get() = TODO("Not yet implemented")
override val hasDefault: Boolean by lazy {
ktValueParameterSymbol.hasDefaultValue
}
override val annotations: Sequence<KSAnnotation> by lazy {
(
ktValueParameterSymbol.generatedPrimaryConstructorProperty?.annotations()
?: ktValueParameterSymbol.annotations()
).plus(findAnnotationFromUseSiteTarget())
}
override val origin: Origin by lazy {
mapAAOrigin(ktValueParameterSymbol)
}
override val location: Location by lazy {
ktValueParameterSymbol.psi?.toLocation() ?: NonExistLocation
}
override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R {
return visitor.visitValueParameter(this, data)
}
override fun toString(): String {
return name?.asString() ?: "_"
}
}
| apache-2.0 | 2b0325afbfe8da2a7753fd21962cecc0 | 38.051546 | 113 | 0.722281 | 4.801014 | false | false | false | false |
stephan-james/intellij-extend | src/com/sjd/intellijextend/IntelliJExtendExecutor.kt | 1 | 6503 | /*
* Copyright (c) 2019, http://stephan-james.github.io/intellij-extend
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the project nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sjd.intellijextend
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.FileUtil.loadFile
import com.intellij.openapi.util.io.FileUtil.writeToFile
import com.sjd.intellijx.Balloons
import org.apache.commons.exec.CommandLine
import org.apache.commons.exec.DefaultExecutor
import org.apache.commons.lang.StringUtils
import org.apache.commons.lang.StringUtils.defaultString
import java.io.File
class IntelliJExtendExecutor(private val editor: Editor) {
companion object {
private val LOG = com.intellij.openapi.diagnostic.Logger.getInstance(IntelliJExtendExecutor::class.java)
}
fun execute() {
if (editor.project == null)
return
if (!IntelliJExtendComponent.openSettingsIfNotConfigured(editor.project!!))
return
try {
createFilesAndExecuteCommand()
} catch (e: Throwable) {
LOG.info("Failed", e)
balloon(MessageType.ERROR, """Failed: ${e.message}""")
}
}
private fun createFilesAndExecuteCommand() {
val buffer = writeBufferToTransferFile(editorBuffer)
val selection = writeSelectionToTransferFile(editorSelection)
val exitCode = executeCommand()
if (!replaceBufferIfChanged(buffer))
replaceSelectionIfChanged(selection)
balloon(MessageType.INFO, "Run successfully (exit code = $exitCode).")
}
private var editorSelection
get() = defaultString(editor.selectionModel.selectedText)
set(newSelection) {
editor.document.replaceString(
editor.selectionModel.selectionStart,
editor.selectionModel.selectionEnd,
rightLineEnded(newSelection))
}
private fun rightLineEnded(newSelection: String) = newSelection
.replace("\r".toRegex(), "")
private var editorBuffer
get() = defaultString(editor.document.charsSequence.toString())
set(newBuffer) = editor.document.setText(rightLineEnded(newBuffer))
private fun executeCommand() = DefaultExecutor().execute(CommandLine.parse(buildCommand()))
private fun replaceSelectionIfChanged(selection: String) {
val newSelection = readSelectionFromTransferFile()
if (newSelection != selection)
editorSelection = newSelection
}
private fun replaceBufferIfChanged(buffer: String): Boolean {
val newBuffer = readBufferFromTransferFile()
if (newBuffer == buffer)
return false
editorBuffer = newBuffer
return true
}
private fun readSelectionFromTransferFile() = defaultString(loadFile(selectionFile))
private fun readBufferFromTransferFile() = defaultString(loadFile(bufferFile))
private fun buildCommand() = IntelliJExtendComponent.command
.replace("\$ProjectFilePath$", projectPath.absolutePath)
.replace("\$FilePath$", filePath.absolutePath)
.replace("\$TransferPath$", transferPath.absolutePath)
.replace("\$TransferBuffer$", bufferFile.absolutePath)
.replace("\$TransferSelection$", selectionFile.absolutePath)
.replace("\$CaretOffset$", caretOffset.toString())
private fun writeSelectionToTransferFile(selection: String) =
writeToAndLoadFile(selectionFile, selection)
private fun writeBufferToTransferFile(buffer: String) =
writeToAndLoadFile(bufferFile, buffer)
private fun writeToAndLoadFile(file: File, buffer: String): String {
writeToFile(file, buffer)
return loadFile(file)
}
private val projectPath
get() = File(this.editor.project?.projectFilePath ?: ".")
private val filePath
get() = File(FileDocumentManager.getInstance().getFile(this.editor.document)?.canonicalFile?.canonicalPath
?: ".")
private val selectionFile
get() = File("""${transferPath.absolutePath}/.selection""")
private val bufferFile
get() = File("""${transferPath.absolutePath}/.buffer""")
private val transferPath
get() = File(nonBlankTransferPath)
private val caretOffset
get() = editor.caretModel.currentCaret.offset
private val nonBlankTransferPath
get() = if (StringUtils.isBlank(IntelliJExtendComponent.transferPath))
defaultTransferPath
else
IntelliJExtendComponent.transferPath
private val defaultTransferPath
get() = File("""${FileUtil.getTempDirectory()}/.${IntelliJExtend.ID}""").absolutePath
private fun balloon(messageType: MessageType, message: String) {
Balloons.show(editor.project!!, messageType, """<strong>${IntelliJExtend.ID}</strong>: $message""")
}
}
| bsd-3-clause | 1a914d1d2612039ca58a4e931298a931 | 37.02924 | 114 | 0.706289 | 4.933991 | false | false | false | false |
alygin/intellij-rust | src/test/kotlin/org/rust/lang/core/type/RsGenericExpressionTypeInferenceTest.kt | 1 | 18374 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.type
class RsGenericExpressionTypeInferenceTest : RsTypificationTestBase() {
fun testGenericField() = testExpr("""
struct S<T> { field: T }
fn foo(s: S<f64>) {
let x = s.field;
x
//^ f64
}
""")
fun testGenericFieldReference() = testExpr("""
struct S<'a, T> { field: &'a T }
fn foo(s: S<'static, f64>) {
let x = s.field;
x
//^ &f64
}
""")
fun testNestedGenericField() = testExpr("""
struct A<T> { field: T }
struct B<S> { field: S }
fn foo(s: A<B<f64>>) {
let x = s.field.field;
x
//^ f64
}
""")
fun testNestedGenericField2() = testExpr("""
struct S<T> { field: T }
fn foo(s: S<S<u64>>) {
let x = s.field.field;
x
//^ u64
}
""")
fun testGenericArray() = testExpr("""
struct S<T> { field: [T; 1] }
fn foo(s: S<f64>) {
let x = s.field;
x
//^ [f64; 1]
}
""")
fun testGenericSlice() = testExpr("""
struct S<T: 'static> { field: &'static [T] }
fn foo(s: S<f64>) {
let x = s.field;
x
//^ &[f64]
}
""")
fun testGenericConstPtr() = testExpr("""
struct S<T> { field: *const T }
fn foo(s: S<f64>) {
let x = s.field;
x
//^ *const f64
}
""")
fun testGenericMutPtr() = testExpr("""
struct S<T> { field: *mut T }
fn foo(s: S<f64>) {
let x = s.field;
x
//^ *mut f64
}
""")
fun testGenericMethod() = testExpr("""
struct B<T> { field: T }
impl<T> B<T> {
fn unwrap(self) -> T { self.field }
}
fn foo(s: B<i32>) {
let x = s.unwrap();
x
//^ i32
}
""")
fun testTwoParameters() = testExpr("""
enum Result<T, E> { Ok(T), Err(E)}
impl<T, E> Result<T, E> {
fn unwrap(self) -> T { unimplemented!() }
}
fn foo(r: Result<(u32, u32), ()>) {
let x = r.unwrap();
x
//^ (u32, u32)
}
""")
fun testParamSwap() = testExpr("""
struct S<A, B> { a: A, b: B}
impl<X, Y> S<Y, X> {
fn swap(self) -> (X, Y) { (self.b, self.a) }
}
fn f(s: S<i32, ()>) {
let x = s.swap();
x
//^ ((), i32)
}
""")
fun testParamRepeat() = testExpr("""
struct S<A, B> { a: A, b: B}
impl <T> S<T, T> {
fn foo(self) -> (T, T) { (self.a, self.b) }
}
fn f(s: S<i32, i32>) {
let x = s.foo();
x
//^ (i32, i32)
}
""")
fun testPartialSpec() = testExpr("""
struct S<A, B> { a: A, b: B}
impl <T> S<i32, T> {
fn foo(self) -> T { self.b }
}
fn f(s: S<i32, ()>) {
let x = s.foo();
x
//^ ()
}
""")
fun testGenericFunction() = testExpr("""
fn f<T>(t: T) -> T { t }
fn main() {
let a = f(0i32);
a
//^ i32
}
""")
fun testGenericFunction2() = testExpr("""
fn f<T2, T1>(t1: T1, t2: T2) -> (T1, T2) { (t1, t2) }
fn main() {
let a = f(0u8, 1u16);
a
//^ (u8, u16)
}
""")
fun testGenericFunction3() = testExpr("""
fn f<T>(t: T) -> T { t }
fn main() {
let a = f::<u8>(1);
a
//^ u8
}
""")
fun testGenericFunctionPointer() = testExpr("""
fn f<T>(t: T) -> T { t }
fn main() {
let f = f::<u8>;
let r = f(1);
r
//^ u8
}
""")
fun testGenericFunctionPointer2() = testExpr("""
fn f<T1, T2>(t1: T1, t2: T2) -> (T1, T2) { (t1, t2) }
fn main() {
let f = f::<u8, _>;
let r = f(1, 2);
r
//^ (u8, i32)
}
""")
fun testStaticMethod() = testExpr("""
struct S<T> { value: T }
impl<T> S<T> {
fn new(t: T) -> S<T> { S {value: t} }
}
fn main() {
let a = S::new(0i32);
a.value
//^ i32
}
""")
fun testRecursiveType() = testExpr("""
struct S<T> {
rec: S<T>,
field: T
}
fn foo(s: S<char>) {
let x = s.rec.field;
x
//^ char
}
""")
fun testSelfType() = testExpr("""
trait T {
fn foo(&self) { self; }
//^ &Self
}
""")
fun `test struct expr`() = testExpr("""
struct S<T> { a: T }
fn main() {
let x = S { a: 5u16 };
x.a
//^ u16
}
""")
fun `test struct expr with 2 fields of same type 1`() = testExpr("""
struct X;
struct S<T> { a: T, b: T }
fn main() {
let x = S { a: X, b: unimplemented!() };
x.b
//^ X
}
""")
fun `test struct expr with 2 fields of same type 2`() = testExpr("""
struct X;
struct S<T> { a: T, b: T }
fn main() {
let x = S { a: unimplemented!(), b: X };
x.a
//^ X
}
""")
fun `test struct expr with 2 fields of different types`() = testExpr("""
struct X; struct Y;
struct S<T1, T2> { a: T1, b: T2 }
fn main() {
let x = S { a: X, b: Y };
(x.a, x.b)
//^ (X, Y)
}
""")
fun `test struct expr with explicit type parameter`() = testExpr("""
struct S<T> {a: T}
fn main() {
let x = S::<u8>{a: 1};
x.a
//^ u8
}
""")
fun `test struct expr with explicit and omitted type parameter`() = testExpr("""
struct S<T1, T2> {a: T1, b: T2}
fn main() {
let x = S::<u8, _>{a: 1, b: 2};
(x.a, x.b)
//^ (u8, i32)
}
""")
fun testTupleStructExpression() = testExpr("""
struct S<T> (T);
fn main() {
let x = S(5u16);
x.0
//^ u16
}
""")
fun `test tuple struct expr with explicit type parameter`() = testExpr("""
struct S<T> (T);
fn main() {
let x = S::<u8>(1);
x.0
//^ u8
}
""")
fun `test tuple struct expr with explicit and omitted type parameter`() = testExpr("""
struct S<T1, T2> (T1, T2);
fn main() {
let x = S::<u8, _>(1, 2);
(x.0, x.1)
//^ (u8, i32)
}
""")
fun `test reference to generic tuple constructor`() = testExpr("""
struct S<T>(T);
fn main() {
let f = S::<u8>;
f(1).0
} //^ u8
""")
fun testGenericAlias() = testExpr("""
struct S1<T>(T);
struct S3<T1, T2, T3>(T1, T2, T3);
type A<T1, T2> = S3<T2, S1<T1>, S3<S1<T2>, T2, T2>>;
type B = A<u16, u8>;
fn f(b: B) {
(b.0, (b.1).0, ((b.2).0).0)
//^ (u8, u16, u8)
}
""")
fun testGenericStructArg() = testExpr("""
struct Foo<F>(F);
fn foo<T>(xs: Foo<T>) -> T { unimplemented!() }
fn main() {
let x = foo(Foo(123));
x
//^ i32
}
""")
fun testGenericEnumArg() = testExpr("""
enum Foo<F> { V(F) }
fn foo<T>(xs: Foo<T>) -> T { unimplemented!() }
fn main() {
let x = foo(Foo::V(123));
x
//^ i32
}
""")
fun testGenericTupleArg() = testExpr("""
fn foo<T, F>(xs: (T, F)) -> F { unimplemented!() }
fn main() {
let x = foo((123, "str"));
x
//^ &str
}
""")
fun testGenericReferenceArg() = testExpr("""
fn foo<T>(xs: &T) -> T { unimplemented!() }
fn main() {
let x = foo(&8u64);
x
//^ u64
}
""")
fun testGenericPointerArg() = testExpr("""
fn foo<T>(xs: *const T) -> T { unimplemented!() }
fn main() {
let x = foo(&8u16 as *const u16);
x
//^ u16
}
""")
fun testGenericArrayArg() = testExpr("""
fn foo<T>(xs: [T; 4]) -> T { unimplemented!() }
fn main() {
let x = foo([1, 2, 3, 4]);
x
//^ i32
}
""")
fun testGenericSliceArg() = testExpr("""
fn foo<T>(xs: &[T]) -> T { unimplemented!() }
fn main() {
let slice: &[&str] = &["foo", "bar"];
let x = foo(slice);
x
//^ &str
}
""")
fun testComplexGenericArg() = testExpr("""
struct Foo<T1, T2>(T1, T2);
enum Bar<T3, T4> { V(T3, T4) }
struct FooBar<T5, T6>(T5, T6);
fn foo<F1, F2, F3, F4>(x: FooBar<Foo<F1, F2>, Bar<F3, F4>>) -> (Bar<F4, F1>, Foo<F3, F2>) { unimplemented!() }
fn main() {
let x = foo(FooBar(Foo(123, "foo"), Bar::V([0.0; 3], (0, false))));
x
//^ (Bar<(i32, bool), i32>, Foo<[f64; 3], &str>)
}
""")
fun testArrayToSlice() = testExpr("""
fn foo<T>(xs: &[T]) -> T { unimplemented!() }
fn main() {
let x = foo(&[1, 2, 3]);
x
//^ i32
}
""")
fun testGenericStructMethodArg() = testExpr("""
struct Foo<F>(F);
struct Bar<B>(B);
impl<T1> Foo<T1> {
fn foo<T2>(&self, bar: Bar<T2>) -> (T1, T2) { unimplemented!() }
}
fn main() {
let x = Foo("foo").foo(Bar(123));
x
//^ (&str, i32)
}
""")
fun testGenericEnumMethodArg() = testExpr("""
struct Foo<F>(F);
enum Bar<B> { V(B) }
impl<T1> Foo<T1> {
fn foo<T2>(&self, bar: Bar<T2>) -> (T1, T2) { unimplemented!() }
}
fn main() {
let x = Foo(0.0).foo(Bar::V("bar"));
x
//^ (f64, &str)
}
""")
fun testGenericTupleMethodArg() = testExpr("""
struct Foo<F>(F);
impl<T1> Foo<T1> {
fn foo<T2, T3>(&self, xs: (T2, T3)) -> (T1, T2, T3) { unimplemented!() }
}
fn main() {
let x = Foo(123).foo((true, "str"));
x
//^ (i32, bool, &str)
}
""")
fun testGenericReferenceMethodArg() = testExpr("""
struct Foo<F>(F);
impl<T1> Foo<T1> {
fn foo<T2>(&self, xs: &T2) -> (T2, T1) { unimplemented!() }
}
fn main() {
let x = Foo((1, 2)).foo(&8u64);
x
//^ (u64, (i32, i32))
}
""")
fun testGenericPointerMethodArg() = testExpr("""
struct Foo<F>(F);
impl<T1> Foo<T1> {
fn foo<T2>(&self, xs: *const T2) -> (T2, T1) { unimplemented!() }
}
fn main() {
let x = Foo("foo").foo(&8u16 as *const u16);
x
//^ (u16, &str)
}
""")
fun testGenericArrayMethodArg() = testExpr("""
struct Foo<F>(F);
impl<T1> Foo<T1> {
fn foo<T2>(&self, xs: [T2; 4]) -> (T2, T1) { unimplemented!() }
}
fn main() {
let x = Foo(0.0).foo([1, 2, 3, 4]);
x
//^ (i32, f64)
}
""")
fun testGenericSliceMethodArg() = testExpr("""
struct Foo<F>(F);
impl<T1> Foo<T1> {
fn foo<T2>(&self, xs: &[T2]) -> (T2, T1) { unimplemented!() }
}
fn main() {
let slice: &[&str] = &["foo", "bar"];
let x = Foo(64u8).foo(slice);
x
//^ (&str, u8)
}
""")
fun testComplexGenericMethodArg() = testExpr("""
struct Foo<T1, T2>(T1, T2);
enum Bar<T3, T4> { V(T3, T4) }
struct FooBar<T5>(T5);
impl<F1, F2> Foo<F1, F2> {
fn foo<F3, F4>(&self, x: FooBar<Bar<F3, F4>>) -> (Bar<F4, F1>, Foo<F3, F2>) { unimplemented!() }
}
fn main() {
let x = Foo(123, "foo").foo(FooBar(Bar::V([0.0; 3], (0, false))));
x
//^ (Bar<(i32, bool), i32>, Foo<[f64; 3], &str>)
}
""")
fun `test infer generic argument from trait bound`() = testExpr("""
struct S<X>(X);
trait Tr<Y> { fn foo(&self) -> Y; }
impl<Z> Tr<Z> for S<Z> { fn foo(&self) -> Z { unimplemented!() } }
fn bar<A, B: Tr<A>>(b: B) -> A { b.foo() }
fn main() {
let a = bar(S(1));
a
} //^ i32
""")
fun `test infer complex generic argument from trait bound`() = testExpr("""
struct S<A>(A);
trait Tr<B> { fn foo(&self) -> B; }
impl<C, D> Tr<(C, D)> for S<(C, D)> { fn foo(&self) -> (C, D) { unimplemented!() } }
fn bar<E, F, G: Tr<(E, F)>>(b: G) -> (E, F) { b.foo() }
fn main() {
let a = bar(S((1u8, 1u16)));
a
} //^ (u8, u16)
""")
fun `test Self substitution to trait method`() = testExpr("""
trait Tr<A> { fn wrap(self) -> S<Self> where Self: Sized { unimplemented!() } }
struct X;
struct S<C>(C);
impl<D> Tr<D> for S<D> {}
fn main() {
let a = S(X).wrap().wrap().wrap();
a
} //^ S<S<S<S<X>>>>
""")
fun `test Self substitution to impl method`() = testExpr("""
trait Tr<A> { fn wrap(self) -> S<Self> where Self: Sized { unimplemented!() } }
struct X;
struct S<C>(C);
impl<D> Tr<D> for S<D> { fn wrap(self) -> S<Self> where Self: Sized { unimplemented!() } }
fn main() {
let a = S(X).wrap().wrap().wrap();
a
} //^ S<S<S<S<X>>>>
""")
fun `test recursive receiver substitution`() = testExpr("""
trait Tr<A> {
fn wrap(self) -> S<Self> where Self: Sized { unimplemented!() }
fn fold(self) -> A where Self: Sized { unimplemented!() }
}
struct X;
struct S1<B>(B);
struct S<C>(C);
impl<D> Tr<D> for S1<D> {}
impl<Src, Dst> Tr<Dst> for S<Src> where Src: Tr<Dst> {}
fn main() {
let a = S1(X).wrap().wrap().wrap().fold();
a
} //^ X
""")
fun `test bound associated type`() = testExpr("""
trait Tr { type Item; }
struct S<A>(A);
impl<B: Tr> S<B> { fn foo(self) -> B::Item { unimplemented!() } }
struct X;
impl Tr for X { type Item = u8; }
fn main() {
let a = S(X).foo();
a
} //^ u8
""")
fun `test bound associated type in explicit UFCS form`() = testExpr("""
trait Tr { type Item; }
struct S<A>(A);
impl<B: Tr> S<B> { fn foo(self) -> <B as Tr>::Item { unimplemented!() } }
struct X;
impl Tr for X { type Item = u8; }
fn main() {
let a = S(X).foo();
a
} //^ u8
""")
fun `test bound inherited associated type`() = testExpr("""
trait Tr1 { type Item; }
trait Tr2: Tr1 {}
struct S<A>(A);
impl<B: Tr2> S<B> { fn foo(self) -> B::Item { unimplemented!() } }
struct X;
impl Tr1 for X { type Item = u8; }
impl Tr2 for X {}
fn main() {
let a = S(X).foo();
a
} //^ u8
""")
fun `test bound inherited associated type in explicit UFCS form`() = testExpr("""
trait Tr1 { type Item; }
trait Tr2: Tr1 {}
struct S<A>(A);
impl<B: Tr2> S<B> { fn foo(self) -> <B as Tr1>::Item { unimplemented!() } }
struct X;
impl Tr1 for X { type Item = u8; }
impl Tr2 for X {}
fn main() {
let a = S(X).foo();
a
} //^ u8
""")
fun `test 2 bound associated types`() = testExpr("""
trait Tr { type Item; }
struct S<A, B>(A, B);
impl<C: Tr, D: Tr> S<C, D> { fn foo(self) -> (C::Item, D::Item) { unimplemented!() } }
struct X;
struct Y;
impl Tr for X { type Item = u8; }
impl Tr for Y { type Item = u16; }
fn main() {
let a = S(X, Y).foo();
a
} //^ (u8, u16)
""")
fun `test recursive receiver substitution using associated type`() = testExpr("""
trait Tr {
type Item;
fn wrap(self) -> S<Self> where Self: Sized { unimplemented!() }
fn fold(self) -> Self::Item where Self: Sized { unimplemented!() }
}
struct X;
struct S1<A>(A);
struct S<B>(B);
impl<C> Tr for S1<C> { type Item = C; }
impl<D: Tr> Tr for S<D> { type Item = D::Item; }
fn main() {
let a = S1(X).wrap().wrap().wrap().fold();
a
} //^ X
""")
fun `test recursive receiver substitution using inherited associated type`() = testExpr("""
trait Tr1 { type Item; }
trait Tr: Tr1 {
fn wrap(self) -> S<Self> where Self: Sized { unimplemented!() }
fn fold(self) -> Self::Item where Self: Sized { unimplemented!() }
}
struct X;
struct S1<A>(A);
struct S<B>(B);
impl<C> Tr1 for S1<C> { type Item = C; }
impl<D: Tr> Tr1 for S<D> { type Item = D::Item; }
impl<E> Tr for S1<E> {}
impl<F: Tr> Tr for S<F> {}
fn main() {
let a = S1(X).wrap().wrap().wrap().fold();
a
} //^ X
""")
// https://github.com/intellij-rust/intellij-rust/issues/1549
fun `test Self type in assoc function`() = testExpr("""
struct Foo<T>(T);
impl<T> Foo<T> {
fn new(a: T) -> Self { unimplemented!() }
}
fn main() {
let x = Foo::new(123);
x;
//^ Foo<i32>
}
""")
}
| mit | c177d7ff9ef5578427eb87e95431e786 | 24.20439 | 118 | 0.398226 | 3.383794 | false | true | false | false |
gojuno/composer | composer/src/main/kotlin/com/gojuno/composer/html/HtmlDevice.kt | 1 | 703 | package com.gojuno.composer.html
import com.gojuno.composer.Device
import com.google.gson.annotations.SerializedName
import java.io.File
data class HtmlDevice(
@SerializedName("id")
val id: String,
@SerializedName("model")
val model: String,
@SerializedName("logcat_path")
val logcatPath: String,
@SerializedName("instrumentation_output_path")
val instrumentationOutputPath: String
)
fun Device.toHtmlDevice(htmlReportDir: File) = HtmlDevice(
id = id,
model = model,
logcatPath = logcat.relativePathTo(htmlReportDir),
instrumentationOutputPath = instrumentationOutput.relativePathTo(htmlReportDir)
)
| apache-2.0 | 3c3a30868a1640e760dad4b23eb5b54e | 25.037037 | 87 | 0.697013 | 4.449367 | false | false | false | false |
http4k/http4k | http4k-core/src/main/kotlin/org/http4k/core/Parameters.kt | 1 | 1126 | package org.http4k.core
import java.net.URLDecoder
import java.net.URLEncoder
typealias Parameters = List<Parameter>
fun Uri.queries(): Parameters = query.toParameters()
fun Parameters.toUrlFormEncoded(): String = joinToString("&") { it.first.toFormEncoded() + it.second?.let { "=" + it.toFormEncoded() }.orEmpty() }
fun Parameters.toParametersMap(): Map<String, List<String?>> = groupBy(Parameter::first, Parameter::second)
fun <K, V> Map<K, List<V>>.getFirst(key: K) = this[key]?.firstOrNull()
fun String.toParameters() = if (isNotEmpty()) split("&").map(String::toParameter) else listOf()
fun Parameters.findSingle(name: String): String? = find { it.first == name }?.second
fun Parameters.findMultiple(name: String) = filter { it.first == name }.map { it.second }
private fun String.toParameter(): Parameter = split("=", limit = 2).map(String::fromFormEncoded).let { l -> l.elementAt(0) to l.elementAtOrNull(1) }
internal fun String.fromFormEncoded() = URLDecoder.decode(this, "UTF-8")
internal fun String.toFormEncoded() = URLEncoder.encode(this, "UTF-8")
internal typealias Parameter = Pair<String, String?>
| apache-2.0 | cd4288758676f6a2bd8b4ee31fd41dd4 | 39.214286 | 148 | 0.722025 | 3.529781 | false | false | false | false |
GlimpseFramework/glimpse-framework | api/src/test/kotlin/glimpse/lights/DirectionLightBuilderSpec.kt | 1 | 1164 | package glimpse.lights
import glimpse.Color
import glimpse.Vector
import glimpse.test.GlimpseSpec
import io.kotlintest.matchers.be
class DirectionLightBuilderSpec : GlimpseSpec() {
init {
"Direction light builder" should {
"create an instance of direction light" {
LightBuilder.DirectionLightBuilder().build() should be a Light.DirectionLight::class
}
"create a light with updatable direction" {
var direction = Vector.X_UNIT
val builder = LightBuilder.DirectionLightBuilder()
builder.direction { direction }
val light = builder.build()
light.direction() shouldBe Vector.X_UNIT
direction = Vector.Y_UNIT
light.direction() shouldBe Vector.Y_UNIT
}
"create a light with updatable color" {
var color = Color.RED
val builder = LightBuilder.DirectionLightBuilder()
builder.color { color }
val light = builder.build()
light.color() shouldBe Color.RED
color = Color.CYAN
light.color() shouldBe Color.CYAN
}
}
"Functional direction light builder" should {
"create an instance of direction light" {
directionLight {} should be a Light.DirectionLight::class
}
}
}
} | apache-2.0 | 23f4b151afc72efa9396285b91c21f8f | 23.270833 | 88 | 0.71134 | 3.791531 | false | false | false | false |
bastienvalentin/myeurocollector | app/src/main/java/fr/vbastien/mycoincollector/features/coin/list/CoinAdapter.kt | 1 | 2556 | package fr.vbastien.mycoincollector.features.coin.list
import android.support.v7.widget.RecyclerView
import android.content.Context
import android.content.res.ColorStateList
import android.net.Uri
import android.support.v4.content.ContextCompat
import android.support.v7.widget.AppCompatImageView
import android.text.TextUtils
import android.view.LayoutInflater
import android.widget.TextView
import android.view.View
import android.view.ViewGroup
import com.squareup.picasso.Picasso
import fr.vbastien.mycoincollector.R
import fr.vbastien.mycoincollector.db.Coin
import fr.vbastien.mycoincollector.util.view.ViewUtil
/**
* Created by vbastien on 03/09/2017.
*/
class CoinAdapter(var context: Context, var coinList: List<Coin>) : RecyclerView.Adapter<CoinAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent?.context).inflate(R.layout.item_coin_list, parent, false)
val viewHolder = ViewHolder(v)
return viewHolder
}
fun getItemAt(pos: Int) : Coin? {
if (pos > coinList.size) return null
return coinList.get(pos)
}
override fun getItemCount(): Int {
return coinList.size
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
val coin = getItemAt(position) ?: return
if (TextUtils.isEmpty(coin.description)) {
holder?.coinDesc?.visibility = View.GONE
} else {
holder?.coinDesc?.text = coin.description
holder?.coinDesc?.visibility = View.VISIBLE
}
holder?.coinValue?.text = coin.value.toString()
if (TextUtils.isEmpty(coin.img)) {
holder?.coinPicture?.setImageResource(R.drawable.coin_empty)
holder?.coinPicture?.supportImageTintList = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.material_grey_400))
val padding = ViewUtil.dpToPx(context, 32)
holder?.coinPicture?.setPadding(padding, padding, padding, padding)
} else {
Picasso.with(context).load(Uri.parse(coin.img)).resize(500, 500).centerInside().into(holder?.coinPicture)
holder?.coinPicture?.setPadding(0, 0, 0, 0)
}
}
class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
var coinPicture = v.findViewById<AppCompatImageView>(R.id.ui_iv_coin_picture)
var coinDesc = v.findViewById<TextView>(R.id.ui_tv_coin_desc)
var coinValue = v.findViewById<TextView>(R.id.ui_tv_coin_value)
}
} | apache-2.0 | 17a818874763e599cb2c001f68c6ab48 | 37.164179 | 138 | 0.701487 | 4.012559 | false | false | false | false |
keidrun/qstackoverflow | src/main/kotlin/com/keidrun/qstackoverflow/lib/SOParams.kt | 1 | 2045 | /**
* Copyright 2017 Keid
*/
package com.keidrun.qstackoverflow.lib
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
/**
* Stack Overflow Search API's Parameters.
*
* @author Keid
*/
class SOParams(val _inTitle: String, val _tagged: String) {
init {
require(_inTitle.isNotEmpty() || _tagged.isNotEmpty())
}
var page: Int? = null
var pageSize: Int? = null
var fromDate: Date? = null
var toDate: Date? = null
var order: SOSerector = SOSerector.Order.DESC
var minDate: Date? = null
var maxDate: Date? = null
var sort: SOSerector = SOSerector.Sort.ACTIVITY
var tagged: String = _tagged
var noTagged: String = ""
var inTitle: String = _inTitle
var site: SOSerector = SOSerector.Site.ENGLISH
fun toMap(): Map<String, String> {
var map: MutableMap<String, String> = mutableMapOf()
if (this.page != null) map.set("page", this.page.toString())
if (this.pageSize != null) map.set("pagesize", this.pageSize.toString())
if (this.fromDate != null) map.set("fromdate", this.fromDate?.time?.div(1000).toString())
if (this.toDate != null) map.set("todate", this.toDate?.time?.div(1000).toString())
map.set("order", this.order.toString())
if (this.minDate != null) map.set("min", this.minDate?.time?.div(1000).toString())
if (this.maxDate != null) map.set("max", this.maxDate?.time?.div(1000).toString())
map.set("sort", this.sort.toString())
if (this.tagged.isNotEmpty()) map.set("tagged", this.tagged)
if (this.noTagged.isNotEmpty()) map.set("notagged", this.noTagged)
if (this.inTitle.isNotEmpty()) map.set("intitle", this.inTitle)
map.set("site", (this.site as SOSerector.Site).siteName)
return map
}
fun parseDate(date: String): Date? {
try {
return SimpleDateFormat(SOSerector.Format.DATE.toString()).parse(date)
} catch (e: ParseException) {
return null
}
}
} | mit | 224312dc69527b3bacebd3139aa80493 | 31.47619 | 97 | 0.629829 | 3.581436 | false | false | false | false |
ebraminio/DroidPersianCalendar | PersianCalendar/src/main/java/com/byagowi/persiancalendar/ui/about/IndeterminateProgressBar.kt | 1 | 1115 | package com.byagowi.persiancalendar.ui.about
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Color
import android.graphics.PorterDuff
import android.os.Build
import android.util.AttributeSet
import android.view.animation.LinearInterpolator
import android.widget.ProgressBar
class IndeterminateProgressBar @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : ProgressBar(context, attrs) {
init {
isIndeterminate = true
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
ValueAnimator.ofArgb(Color.RED, Color.YELLOW, Color.GREEN, Color.BLUE).apply {
duration = 3000
interpolator = LinearInterpolator()
repeatMode = ValueAnimator.REVERSE
repeatCount = ValueAnimator.INFINITE
addUpdateListener {
indeterminateDrawable?.setColorFilter(
it.animatedValue as Int,
PorterDuff.Mode.SRC_ATOP
)
}
}.start()
}
}
| gpl-3.0 | eed8b8e58bf1f5b964699b29fe945c6c | 34.967742 | 90 | 0.64843 | 5.386473 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/viewmodel/BuddyCollectionViewModel.kt | 1 | 1528 | package com.boardgamegeek.ui.viewmodel
import android.app.Application
import androidx.lifecycle.*
import com.boardgamegeek.entities.CollectionItemEntity
import com.boardgamegeek.entities.RefreshableResource
import com.boardgamegeek.repository.UserRepository
class BuddyCollectionViewModel(application: Application) : AndroidViewModel(application) {
private val userRepository = UserRepository(getApplication())
private val usernameAndStatus = MutableLiveData<Pair<String, String>>()
fun setUsername(username: String) {
if (usernameAndStatus.value?.first != username)
usernameAndStatus.value = username to (usernameAndStatus.value?.second ?: DEFAULT_STATUS)
}
fun setStatus(status: String) {
if (usernameAndStatus.value?.second != status) usernameAndStatus.value =
(usernameAndStatus.value?.first.orEmpty()) to status
}
val status: LiveData<String> = usernameAndStatus.map {
it.second
}
val collection: LiveData<RefreshableResource<List<CollectionItemEntity>>> =
usernameAndStatus.switchMap {
liveData {
emit(RefreshableResource.refreshing(null))
try {
emit(RefreshableResource.success(userRepository.refreshCollection(it.first, it.second)))
} catch (e: Exception) {
emit(RefreshableResource.error(e, application))
}
}
}
companion object {
const val DEFAULT_STATUS = "own"
}
}
| gpl-3.0 | e243571fca2560086c44531bf88fe612 | 34.534884 | 108 | 0.679319 | 4.977199 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/catalog/LanternCatalogKey.kt | 1 | 1334 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.catalog
import net.kyori.adventure.key.Key
import org.lanternpowered.api.key.NamespacedKey
import java.util.Objects
open class LanternNamespacedKey(private val namespace: String, private val value: String) : NamespacedKey {
override fun getNamespace(): String = this.namespace
override fun getValue(): String = this.value
override fun namespace(): String = this.namespace
override fun value(): String = this.value
override fun compareTo(other: Key): Int {
val i = this.namespace.compareTo(other.namespace())
return if (i != 0) i else this.value.compareTo(other.value())
}
override fun getFormatted(): String = toString()
override fun toString(): String = this.namespace + ':' + this.value
override fun hashCode(): Int = Objects.hash(this.namespace, this.value)
override fun equals(other: Any?): Boolean =
other is LanternNamespacedKey && other.namespace == this.namespace && other.value == this.value
}
| mit | 6dfdb020e680226c32a8b88db2ac2c42 | 38.235294 | 107 | 0.709895 | 4.208202 | false | false | false | false |
Kotlin/kotlinx.serialization | formats/protobuf/commonMain/src/kotlinx/serialization/protobuf/internal/ProtobufDecoding.kt | 1 | 12922 | /*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:OptIn(ExperimentalSerializationApi::class)
@file:Suppress("UNCHECKED_CAST", "INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
package kotlinx.serialization.protobuf.internal
import kotlinx.serialization.*
import kotlinx.serialization.builtins.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.internal.*
import kotlinx.serialization.modules.*
import kotlinx.serialization.protobuf.*
import kotlin.jvm.*
internal open class ProtobufDecoder(
@JvmField protected val proto: ProtoBuf,
@JvmField protected val reader: ProtobufReader,
@JvmField protected val descriptor: SerialDescriptor
) : ProtobufTaggedDecoder() {
override val serializersModule: SerializersModule
get() = proto.serializersModule
// Proto id -> index in serial descriptor cache
private var indexCache: IntArray? = null
private var sparseIndexCache: MutableMap<Int, Int>? = null
private var nullValue: Boolean = false
private val elementMarker = ElementMarker(descriptor, ::readIfAbsent)
init {
populateCache(descriptor)
}
public fun populateCache(descriptor: SerialDescriptor) {
val elements = descriptor.elementsCount
if (elements < 32) {
/*
* If we have reasonably small count of elements, try to build sequential
* array for the fast-path. Fast-path implies that elements are not marked with @ProtoId
* explicitly or are monotonic and incremental (maybe, 1-indexed)
*/
val cache = IntArray(elements + 1)
for (i in 0 until elements) {
val protoId = extractProtoId(descriptor, i, false)
if (protoId <= elements) {
cache[protoId] = i
} else {
return populateCacheMap(descriptor, elements)
}
}
indexCache = cache
} else {
populateCacheMap(descriptor, elements)
}
}
private fun populateCacheMap(descriptor: SerialDescriptor, elements: Int) {
val map = HashMap<Int, Int>(elements)
for (i in 0 until elements) {
map[extractProtoId(descriptor, i, false)] = i
}
sparseIndexCache = map
}
private fun getIndexByTag(protoTag: Int): Int {
val array = indexCache
if (array != null) {
return array.getOrElse(protoTag) { -1 }
}
return getIndexByTagSlowPath(protoTag)
}
private fun getIndexByTagSlowPath(
protoTag: Int
): Int = sparseIndexCache!!.getOrElse(protoTag) { -1 }
private fun findIndexByTag(descriptor: SerialDescriptor, protoTag: Int): Int {
// Fast-path: tags are incremental, 1-based
if (protoTag < descriptor.elementsCount) {
val protoId = extractProtoId(descriptor, protoTag, true)
if (protoId == protoTag) return protoTag
}
return findIndexByTagSlowPath(descriptor, protoTag)
}
private fun findIndexByTagSlowPath(desc: SerialDescriptor, protoTag: Int): Int {
for (i in 0 until desc.elementsCount) {
val protoId = extractProtoId(desc, i, true)
if (protoId == protoTag) return i
}
throw ProtobufDecodingException(
"$protoTag is not among valid ${descriptor.serialName} enum proto numbers"
)
}
override fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder {
return when (descriptor.kind) {
StructureKind.LIST -> {
val tag = currentTagOrDefault
return if (this.descriptor.kind == StructureKind.LIST && tag != MISSING_TAG && this.descriptor != descriptor) {
val reader = makeDelimited(reader, tag)
// repeated decoder expects the first tag to be read already
reader.readTag()
// all elements always have id = 1
RepeatedDecoder(proto, reader, ProtoDesc(1, ProtoIntegerType.DEFAULT), descriptor)
} else if (reader.currentType == SIZE_DELIMITED && descriptor.getElementDescriptor(0).isPackable) {
val sliceReader = ProtobufReader(reader.objectInput())
PackedArrayDecoder(proto, sliceReader, descriptor)
} else {
RepeatedDecoder(proto, reader, tag, descriptor)
}
}
StructureKind.CLASS, StructureKind.OBJECT, is PolymorphicKind -> {
val tag = currentTagOrDefault
// Do not create redundant copy
if (tag == MISSING_TAG && this.descriptor == descriptor) return this
return ProtobufDecoder(proto, makeDelimited(reader, tag), descriptor)
}
StructureKind.MAP -> MapEntryReader(proto, makeDelimitedForced(reader, currentTagOrDefault), currentTagOrDefault, descriptor)
else -> throw SerializationException("Primitives are not supported at top-level")
}
}
override fun endStructure(descriptor: SerialDescriptor) {
// Nothing
}
override fun decodeTaggedBoolean(tag: ProtoDesc): Boolean = when(val value = decodeTaggedInt(tag)) {
0 -> false
1 -> true
else -> throw SerializationException("Unexpected boolean value: $value")
}
override fun decodeTaggedByte(tag: ProtoDesc): Byte = decodeTaggedInt(tag).toByte()
override fun decodeTaggedShort(tag: ProtoDesc): Short = decodeTaggedInt(tag).toShort()
override fun decodeTaggedInt(tag: ProtoDesc): Int {
return if (tag == MISSING_TAG) {
reader.readInt32NoTag()
} else {
reader.readInt(tag.integerType)
}
}
override fun decodeTaggedLong(tag: ProtoDesc): Long {
return if (tag == MISSING_TAG) {
reader.readLongNoTag()
} else {
reader.readLong(tag.integerType)
}
}
override fun decodeTaggedFloat(tag: ProtoDesc): Float {
return if (tag == MISSING_TAG) {
reader.readFloatNoTag()
} else {
reader.readFloat()
}
}
override fun decodeTaggedDouble(tag: ProtoDesc): Double {
return if (tag == MISSING_TAG) {
reader.readDoubleNoTag()
} else {
reader.readDouble()
}
}
override fun decodeTaggedChar(tag: ProtoDesc): Char = decodeTaggedInt(tag).toChar()
override fun decodeTaggedString(tag: ProtoDesc): String {
return if (tag == MISSING_TAG) {
reader.readStringNoTag()
} else {
reader.readString()
}
}
override fun decodeTaggedEnum(tag: ProtoDesc, enumDescription: SerialDescriptor): Int {
return findIndexByTag(enumDescription, decodeTaggedInt(tag))
}
override fun <T> decodeSerializableValue(deserializer: DeserializationStrategy<T>): T = decodeSerializableValue(deserializer, null)
@Suppress("UNCHECKED_CAST")
override fun <T> decodeSerializableValue(deserializer: DeserializationStrategy<T>, previousValue: T?): T = when {
deserializer is MapLikeSerializer<*, *, *, *> -> {
deserializeMap(deserializer as DeserializationStrategy<T>, previousValue)
}
deserializer.descriptor == ByteArraySerializer().descriptor -> deserializeByteArray(previousValue as ByteArray?) as T
deserializer is AbstractCollectionSerializer<*, *, *> ->
(deserializer as AbstractCollectionSerializer<*, T, *>).merge(this, previousValue)
else -> deserializer.deserialize(this)
}
private fun deserializeByteArray(previousValue: ByteArray?): ByteArray {
val tag = currentTagOrDefault
val array = if (tag == MISSING_TAG) {
reader.readByteArrayNoTag()
} else {
reader.readByteArray()
}
return if (previousValue == null) array else previousValue + array
}
@Suppress("UNCHECKED_CAST")
private fun <T> deserializeMap(deserializer: DeserializationStrategy<T>, previousValue: T?): T {
val serializer = (deserializer as MapLikeSerializer<Any?, Any?, T, *>)
// Yeah thanks different resolution algorithms
val mapEntrySerial =
kotlinx.serialization.builtins.MapEntrySerializer(serializer.keySerializer, serializer.valueSerializer)
val oldSet = (previousValue as? Map<Any?, Any?>)?.entries
val setOfEntries = LinkedHashSetSerializer(mapEntrySerial).merge(this, oldSet)
return setOfEntries.associateBy({ it.key }, { it.value }) as T
}
override fun SerialDescriptor.getTag(index: Int) = extractParameters(index)
override fun decodeElementIndex(descriptor: SerialDescriptor): Int {
while (true) {
val protoId = reader.readTag()
if (protoId == -1) { // EOF
return elementMarker.nextUnmarkedIndex()
}
val index = getIndexByTag(protoId)
if (index == -1) { // not found
reader.skipElement()
} else {
elementMarker.mark(index)
return index
}
}
}
override fun decodeNotNullMark(): Boolean {
return !nullValue
}
private fun readIfAbsent(descriptor: SerialDescriptor, index: Int): Boolean {
if (!descriptor.isElementOptional(index)) {
val elementDescriptor = descriptor.getElementDescriptor(index)
val kind = elementDescriptor.kind
if (kind == StructureKind.MAP || kind == StructureKind.LIST) {
nullValue = false
return true
} else if (elementDescriptor.isNullable) {
nullValue = true
return true
}
}
return false
}
}
private class RepeatedDecoder(
proto: ProtoBuf,
decoder: ProtobufReader,
currentTag: ProtoDesc,
descriptor: SerialDescriptor
) : ProtobufDecoder(proto, decoder, descriptor) {
// Current index
private var index = -1
/*
* For regular messages, it is always a tag.
* For out-of-spec top-level lists (and maps) the very first varint
* represents this list size. It is stored in a single variable
* as negative value and branched based on that fact.
*/
private val tagOrSize: Long
init {
tagOrSize = if (currentTag == MISSING_TAG) {
val length = reader.readInt32NoTag()
require(length >= 0) { "Expected positive length for $descriptor, but got $length" }
-length.toLong()
} else {
currentTag
}
}
override fun decodeElementIndex(descriptor: SerialDescriptor): Int {
if (tagOrSize > 0) {
return decodeTaggedListIndex()
}
return decodeListIndexNoTag()
}
private fun decodeListIndexNoTag(): Int {
val size = -tagOrSize
val idx = ++index
// Check for eof is here for the case that it is an out-of-spec packed array where size is bytesize not list length.
if (idx.toLong() == size || reader.eof) return CompositeDecoder.DECODE_DONE
return idx
}
private fun decodeTaggedListIndex(): Int {
val protoId = if (index == -1) {
// For the very first element tag is already read by the parent
reader.currentId
} else {
reader.readTag()
}
return if (protoId == tagOrSize.protoId) {
++index
} else {
// If we read tag of a different message, push it back to the reader and bail out
reader.pushBackTag()
CompositeDecoder.DECODE_DONE
}
}
override fun SerialDescriptor.getTag(index: Int): ProtoDesc {
if (tagOrSize > 0) return tagOrSize
return MISSING_TAG
}
}
private class MapEntryReader(
proto: ProtoBuf,
decoder: ProtobufReader,
@JvmField val parentTag: ProtoDesc,
descriptor: SerialDescriptor
) : ProtobufDecoder(proto, decoder, descriptor) {
override fun SerialDescriptor.getTag(index: Int): ProtoDesc =
if (index % 2 == 0) ProtoDesc(1, (parentTag.integerType))
else ProtoDesc(2, (parentTag.integerType))
}
private fun makeDelimited(decoder: ProtobufReader, parentTag: ProtoDesc): ProtobufReader {
val tagless = parentTag == MISSING_TAG
val input = if (tagless) decoder.objectTaglessInput() else decoder.objectInput()
return ProtobufReader(input)
}
private fun makeDelimitedForced(decoder: ProtobufReader, parentTag: ProtoDesc): ProtobufReader {
val tagless = parentTag == MISSING_TAG
val input = if (tagless) decoder.objectTaglessInput() else decoder.objectInput()
return ProtobufReader(input)
}
| apache-2.0 | 35b925b10bf2b2155025ba885a50a83f | 36.563953 | 137 | 0.629314 | 4.867043 | false | false | false | false |
WindSekirun/RichUtilsKt | demo/src/main/java/pyxis/uzuki/live/richutilskt/demo/set/FileSet.kt | 1 | 1773 | package pyxis.uzuki.live.richutilskt.demo.set
import android.content.Context
import pyxis.uzuki.live.richutilskt.demo.R
import pyxis.uzuki.live.richutilskt.demo.item.CategoryItem
import pyxis.uzuki.live.richutilskt.demo.item.ExecuteItem
import pyxis.uzuki.live.richutilskt.demo.item.generateExecuteItem
/**
* Created by pyxis on 07/11/2017.
*/
fun Context.getFileSet(): ArrayList<ExecuteItem> {
val list = arrayListOf<ExecuteItem>()
val downloadFile = generateExecuteItem(CategoryItem.FILE, "downloadFile",
getString(R.string.file_message_downloadfile),
"downloadFile(url, file.absolutePath, {uri -> }",
"RichUtils.downloadFile(url, file.getAbsolutePath(), (uri) -> {}")
list.add(downloadFile)
val toFile = generateExecuteItem(CategoryItem.FILE, "toFile",
getString(R.string.file_message_tofile),
"\"${this.getExternalFilesDir(null)}/\$path\".toFile()",
"RichUtils.toFile(localPath);")
list.add(toFile)
val saveFile = generateExecuteItem(CategoryItem.FILE, "saveFile",
getString(R.string.file_message_savefile),
"saveFile(path, content)",
"RichUtils.saveFile(path, content);")
list.add(saveFile)
val readFile = generateExecuteItem(CategoryItem.FILE, "readFile",
getString(R.string.file_message_readfile),
"file.readFile()",
"RichUtils.readFile(file);")
list.add(readFile)
val getRealPath = generateExecuteItem(CategoryItem.FILE, "getRealPath",
getString(R.string.file_message_getrealpath),
"Uri.parse(path) getRealPath this@PickMediaActivity",
"RichUtils.getRealPath(Uri.parse(path), this);")
list.add(getRealPath)
return list
} | apache-2.0 | 15a242562ef448f431c8128343ec56e6 | 32.471698 | 78 | 0.679639 | 4.32439 | false | false | false | false |
PKRoma/github-android | app/src/main/java/com/github/pockethub/android/ui/item/repository/RepositoryItem.kt | 5 | 3010 | package com.github.pockethub.android.ui.item.repository
import android.text.TextUtils
import android.view.View
import androidx.core.text.bold
import androidx.core.text.buildSpannedString
import androidx.core.text.color
import com.github.pockethub.android.R
import com.github.pockethub.android.ui.view.OcticonTextView.ICON_FORK
import com.github.pockethub.android.ui.view.OcticonTextView.ICON_MIRROR_PRIVATE
import com.github.pockethub.android.ui.view.OcticonTextView.ICON_MIRROR_PUBLIC
import com.github.pockethub.android.ui.view.OcticonTextView.ICON_PRIVATE
import com.github.pockethub.android.ui.view.OcticonTextView.ICON_PUBLIC
import com.meisolsson.githubsdk.model.Repository
import com.meisolsson.githubsdk.model.User
import com.xwray.groupie.kotlinandroidextensions.Item
import com.xwray.groupie.kotlinandroidextensions.ViewHolder
import kotlinx.android.synthetic.main.repo_details.*
import kotlinx.android.synthetic.main.user_repo_item.*
class RepositoryItem(val repo: Repository, private val user: User?) : Item(repo.id()!!) {
private var descriptionColor = -1
override fun getId() = repo.id()!!
override fun getLayout() = R.layout.user_repo_item
override fun bind(holder: ViewHolder, position: Int) {
if (descriptionColor == -1) {
descriptionColor = holder.root.resources.getColor(R.color.text_description)
}
holder.tv_repo_name.text = buildSpannedString {
if (user == null) {
append(repo.owner()!!.login()).append('/')
} else {
if (user.login() != repo.owner()!!.login()) {
color(descriptionColor) {
append("${repo.owner()!!.login()}/")
}
}
}
bold {
append(repo.name())
}
}
if (TextUtils.isEmpty(repo.mirrorUrl())) {
when {
repo.isPrivate!! -> holder.tv_repo_icon.text = ICON_PRIVATE
repo.isFork!! -> holder.tv_repo_icon.text = ICON_FORK
else -> holder.tv_repo_icon.text = ICON_PUBLIC
}
} else {
if (repo.isPrivate!!) {
holder.tv_repo_icon.text = ICON_MIRROR_PRIVATE
} else {
holder.tv_repo_icon.text = ICON_MIRROR_PUBLIC
}
}
if (!TextUtils.isEmpty(repo.description())) {
holder.tv_repo_description.text = repo.description()
holder.tv_repo_description.visibility = View.VISIBLE
} else {
holder.tv_repo_description.visibility = View.GONE
}
if (!TextUtils.isEmpty(repo.language())) {
holder.tv_language.text = repo.language()
holder.tv_language.visibility = View.VISIBLE
} else {
holder.tv_language.visibility = View.GONE
}
holder.tv_watchers.text = repo.watchersCount().toString()
holder.tv_forks.text = repo.forksCount().toString()
}
}
| apache-2.0 | f5943e570b99af892cfa0825ab08de8b | 36.160494 | 89 | 0.625914 | 4.198047 | false | false | false | false |
cfig/Android_boot_image_editor | bbootimg/src/main/kotlin/bootimg/v3/BootV3.kt | 1 | 18547 | // Copyright 2021 [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cfig.bootimg.v3
import avb.AVBInfo
import avb.alg.Algorithms
import avb.blob.AuxBlob
import cfig.Avb
import cfig.utils.EnvironmentVerifier
import cfig.bootimg.Common.Companion.deleleIfExists
import cfig.bootimg.Common.Companion.getPaddingSize
import cfig.bootimg.Signer
import cfig.helper.Helper
import cfig.helper.Dumpling
import cfig.packable.VBMetaParser
import com.fasterxml.jackson.databind.ObjectMapper
import de.vandermeer.asciitable.AsciiTable
import org.apache.commons.exec.CommandLine
import org.apache.commons.exec.DefaultExecutor
import org.slf4j.LoggerFactory
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
import cfig.bootimg.Common as C
data class BootV3(
var info: MiscInfo = MiscInfo(),
var kernel: CommArgs = CommArgs(),
val ramdisk: CommArgs = CommArgs(),
var bootSignature: CommArgs = CommArgs(),
) {
companion object {
private val log = LoggerFactory.getLogger(BootV3::class.java)
private val errLog = LoggerFactory.getLogger("uiderrors")
private val mapper = ObjectMapper()
private val workDir = Helper.prop("workDir")
fun parse(fileName: String): BootV3 {
val ret = BootV3()
FileInputStream(fileName).use { fis ->
val header = BootHeaderV3(fis)
//info
ret.info.output = File(fileName).name
ret.info.json = File(fileName).name.removeSuffix(".img") + ".json"
ret.info.cmdline = header.cmdline
ret.info.headerSize = header.headerSize
ret.info.headerVersion = header.headerVersion
ret.info.osVersion = header.osVersion
ret.info.osPatchLevel = header.osPatchLevel
ret.info.pageSize = BootHeaderV3.pageSize
ret.info.signatureSize = header.signatureSize
//kernel
ret.kernel.file = workDir + "kernel"
ret.kernel.size = header.kernelSize
ret.kernel.position = BootHeaderV3.pageSize
//ramdisk
ret.ramdisk.file = workDir + "ramdisk.img"
ret.ramdisk.size = header.ramdiskSize
ret.ramdisk.position = ret.kernel.position + header.kernelSize +
getPaddingSize(header.kernelSize, BootHeaderV3.pageSize)
//boot signature
if (header.signatureSize > 0) {
ret.bootSignature.file = workDir + "bootsig"
ret.bootSignature.size = header.signatureSize
ret.bootSignature.position = ret.ramdisk.position + ret.ramdisk.size +
getPaddingSize(header.ramdiskSize, BootHeaderV3.pageSize)
}
}
ret.info.imageSize = File(fileName).length()
return ret
}
}
data class MiscInfo(
var output: String = "",
var json: String = "",
var headerVersion: Int = 0,
var headerSize: Int = 0,
var pageSize: Int = 0,
var cmdline: String = "",
var osVersion: String = "",
var osPatchLevel: String = "",
var imageSize: Long = 0,
var signatureSize: Int = 0,
)
data class CommArgs(
var file: String = "",
var position: Int = 0,
var size: Int = 0,
)
fun pack(): BootV3 {
if (this.kernel.size > 0) {
this.kernel.size = File(this.kernel.file).length().toInt()
}
if (this.ramdisk.size > 0) {
if (File(this.ramdisk.file).exists() && !File(workDir + "root").exists()) {
//do nothing if we have ramdisk.img.gz but no /root
log.warn("Use prebuilt ramdisk file: ${this.ramdisk.file}")
} else {
File(this.ramdisk.file).deleleIfExists()
File(this.ramdisk.file.replaceFirst("[.][^.]+$", "")).deleleIfExists()
//TODO: remove cpio in C/C++
//C.packRootfs("$workDir/root", this.ramdisk.file, C.parseOsMajor(info.osVersion))
// enable advance JAVA cpio
C.packRootfs("$workDir/root", this.ramdisk.file)
}
this.ramdisk.size = File(this.ramdisk.file).length().toInt()
}
//header
FileOutputStream(this.info.output + ".clear", false).use { fos ->
//trim bootSig if it's not parsable
//https://github.com/cfig/Android_boot_image_editor/issues/88
File(Avb.getJsonFileName(this.bootSignature.file)).let { bootSigJson ->
if (!bootSigJson.exists()) {
errLog.info(
"erase unparsable boot signature in header. Refer to https://github.com/cfig/Android_boot_image_editor/issues/88"
)
this.info.signatureSize = 0
}
}
val encodedHeader = this.toHeader().encode()
fos.write(encodedHeader)
fos.write(
ByteArray(Helper.round_to_multiple(encodedHeader.size, this.info.pageSize) - encodedHeader.size)
)
}
//data
log.info("Writing data ...")
//BootV3 should have correct image size
val bf = ByteBuffer.allocate(maxOf(info.imageSize.toInt(), 64 * 1024 * 1024))
bf.order(ByteOrder.LITTLE_ENDIAN)
if (kernel.size > 0) {
C.writePaddedFile(bf, this.kernel.file, this.info.pageSize)
}
if (ramdisk.size > 0) {
C.writePaddedFile(bf, this.ramdisk.file, this.info.pageSize)
}
//write V3 data
FileOutputStream("${this.info.output}.clear", true).use { fos ->
fos.write(bf.array(), 0, bf.position())
}
//write V4 boot sig
if (this.info.headerVersion > 3) {
val bootSigJson = File(Avb.getJsonFileName(this.bootSignature.file))
var bootSigBytes = ByteArray(this.bootSignature.size)
if (bootSigJson.exists()) {
log.warn("V4 BootImage has GKI boot signature")
val readBackBootSig = mapper.readValue(bootSigJson, AVBInfo::class.java)
val alg = Algorithms.get(readBackBootSig.header!!.algorithm_type)!!
//replace new pub key
readBackBootSig.auxBlob!!.pubkey!!.pubkey = AuxBlob.encodePubKey(alg)
//update hash and sig
readBackBootSig.auxBlob!!.hashDescriptors.get(0).update(this.info.output + ".clear")
bootSigBytes = readBackBootSig.encodePadded()
}
if (this.info.signatureSize > 0) {
//write V4 data
FileOutputStream("${this.info.output}.clear", true).use { fos ->
fos.write(bootSigBytes)
}
} else {
errLog.info("ignore bootsig for v4 boot.img")
}
}
//google way
this.toCommandLine().addArgument(this.info.output + ".google").let {
log.info(it.toString())
DefaultExecutor().execute(it)
}
Helper.assertFileEquals(this.info.output + ".clear", this.info.output + ".google")
File(this.info.output + ".google").delete()
return this
}
fun sign(fileName: String): BootV3 {
if (File(Avb.getJsonFileName(info.output)).exists()) {
Signer.signAVB(fileName, this.info.imageSize, String.format(Helper.prop("avbtool"), "v1.2"))
} else {
log.warn("no AVB info found, assume it's clear image")
}
return this
}
private fun toHeader(): BootHeaderV3 {
return BootHeaderV3(
kernelSize = kernel.size,
ramdiskSize = ramdisk.size,
headerVersion = info.headerVersion,
osVersion = info.osVersion,
osPatchLevel = info.osPatchLevel,
headerSize = info.headerSize,
cmdline = info.cmdline,
signatureSize = info.signatureSize
).feature67()
}
fun extractImages(): BootV3 {
val workDir = Helper.prop("workDir")
//info
mapper.writerWithDefaultPrettyPrinter().writeValue(File(workDir + this.info.json), this)
//kernel
if (kernel.size > 0) {
C.dumpKernel(Helper.Slice(info.output, kernel.position, kernel.size, kernel.file))
} else {
log.warn("${this.info.output} has no kernel")
}
//ramdisk
if (ramdisk.size > 0) {
val fmt = C.dumpRamdisk(
Helper.Slice(info.output, ramdisk.position, ramdisk.size, ramdisk.file), "${workDir}root"
)
this.ramdisk.file = this.ramdisk.file + ".$fmt"
}
//bootsig
//dump info again
mapper.writerWithDefaultPrettyPrinter().writeValue(File(workDir + this.info.json), this)
return this
}
fun extractVBMeta(): BootV3 {
// vbmeta in image
try {
val ai = AVBInfo.parseFrom(Dumpling(info.output)).dumpDefault(info.output)
if (File("vbmeta.img").exists()) {
log.warn("Found vbmeta.img, parsing ...")
VBMetaParser().unpack("vbmeta.img")
}
} catch (e: IllegalArgumentException) {
log.warn(e.message)
log.warn("failed to parse vbmeta info")
}
//GKI 1.0 bootsig
if (info.signatureSize > 0) {
log.info("GKI 1.0 signature")
Dumpling(info.output).readFully(Pair(this.bootSignature.position.toLong(), this.bootSignature.size))
.let { bootsigData ->
File(this.bootSignature.file).writeBytes(bootsigData)
if (bootsigData.any { it.toInt() != 0 }) {
try {
val bootsig = AVBInfo.parseFrom(Dumpling(bootsigData)).dumpDefault(this.bootSignature.file)
Avb.verify(bootsig, Dumpling(bootsigData, "bootsig"))
} catch (e: IllegalArgumentException) {
log.warn("GKI 1.0 boot signature is invalid")
}
} else {
log.warn("GKI 1.0 boot signature has only NULL data")
}
}
return this
}
//GKI 2.0 bootsig
if (!File(Avb.getJsonFileName(info.output)).exists()) {
log.info("no AVB info found in ${info.output}")
return this
}
log.info("probing 16KB boot signature ...")
val mainBlob = ObjectMapper().readValue(
File(Avb.getJsonFileName(info.output)),
AVBInfo::class.java
)
val bootSig16kData =
Dumpling(Dumpling(info.output).readFully(Pair(mainBlob.footer!!.originalImageSize - 16 * 1024, 16 * 1024)))
try {
val blob1 = AVBInfo.parseFrom(bootSig16kData)
.also { check(it.auxBlob!!.hashDescriptors[0].partition_name == "boot") }
.also { it.dumpDefault("sig.boot") }
val blob2 =
AVBInfo.parseFrom(Dumpling(bootSig16kData.readFully(blob1.encode().size until bootSig16kData.getLength())))
.also { check(it.auxBlob!!.hashDescriptors[0].partition_name == "generic_kernel") }
.also { it.dumpDefault("sig.kernel") }
val gkiAvbData = bootSig16kData.readFully(blob1.encode().size until bootSig16kData.getLength())
File("${workDir}kernel.img").let { gki ->
File("${workDir}kernel").copyTo(gki)
System.setProperty("more", workDir)
Avb.verify(blob2, Dumpling(gkiAvbData))
gki.delete()
}
log.info(blob1.auxBlob!!.hashDescriptors[0].partition_name)
log.info(blob2.auxBlob!!.hashDescriptors[0].partition_name)
} catch (e: IllegalArgumentException) {
log.warn("can not find boot signature: " + e.message)
}
return this
}
fun printSummary(): BootV3 {
val workDir = Helper.prop("workDir")
val tableHeader = AsciiTable().apply {
addRule()
addRow("What", "Where")
addRule()
}
val tab = AsciiTable().let {
it.addRule()
it.addRow("image info", workDir + info.output.removeSuffix(".img") + ".json")
it.addRule()
if (this.kernel.size > 0) {
it.addRow("kernel", this.kernel.file)
File(Helper.prop("kernelVersionFile")).let { kernelVersionFile ->
if (kernelVersionFile.exists()) {
it.addRow("\\-- version " + kernelVersionFile.readLines().toString(), kernelVersionFile.path)
}
}
File(Helper.prop("kernelConfigFile")).let { kernelConfigFile ->
if (kernelConfigFile.exists()) {
it.addRow("\\-- config", kernelConfigFile.path)
}
}
it.addRule()
}
if (this.ramdisk.size > 0) {
it.addRow("ramdisk", this.ramdisk.file)
it.addRow("\\-- extracted ramdisk rootfs", "${workDir}root")
it.addRule()
}
if (this.info.signatureSize > 0) {
it.addRow("GKI signature 1.0", this.bootSignature.file)
File(Avb.getJsonFileName(this.bootSignature.file)).let { jsFile ->
it.addRow("\\-- decoded boot signature", if (jsFile.exists()) jsFile.path else "N/A")
if (jsFile.exists()) {
it.addRow("\\------ signing key", Avb.inspectKey(mapper.readValue(jsFile, AVBInfo::class.java)))
}
}
it.addRule()
}
//GKI signature 2.0
File(Avb.getJsonFileName("sig.boot")).let { jsonFile ->
if (jsonFile.exists()) {
it.addRow("GKI signature 2.0", this.bootSignature.file)
it.addRow("\\-- boot", jsonFile.path)
it.addRow("\\------ signing key", Avb.inspectKey(mapper.readValue(jsonFile, AVBInfo::class.java)))
}
}
File(Avb.getJsonFileName("sig.kernel")).let { jsonFile ->
if (jsonFile.exists()) {
val readBackAvb = mapper.readValue(jsonFile, AVBInfo::class.java)
it.addRow("\\-- kernel", jsonFile.path)
it.addRow("\\------ signing key", Avb.inspectKey(readBackAvb))
it.addRule()
}
}
//AVB info
Avb.getJsonFileName(info.output).let { jsonFile ->
it.addRow("AVB info", if (File(jsonFile).exists()) jsonFile else "NONE")
if (File(jsonFile).exists()) {
mapper.readValue(File(jsonFile), AVBInfo::class.java).let { ai ->
it.addRow("\\------ signing key", Avb.inspectKey(ai))
}
}
}
it.addRule()
it
}
val tabVBMeta = AsciiTable().let {
if (File("vbmeta.img").exists()) {
it.addRule()
it.addRow("vbmeta.img", Avb.getJsonFileName("vbmeta.img"))
it.addRule()
"\n" + it.render()
} else {
""
}
}
log.info(
"\n\t\t\tUnpack Summary of ${info.output}\n{}\n{}{}",
tableHeader.render(), tab.render(), tabVBMeta
)
return this
}
fun printPackSummary(): BootV3 {
VendorBoot.printPackSummary(info.output)
return this
}
fun updateVbmeta(): BootV3 {
Avb.updateVbmeta(info.output)
return this
}
private fun toCommandLine(): CommandLine {
val cmdPrefix = if (EnvironmentVerifier().isWindows) "python " else ""
return CommandLine.parse(cmdPrefix + Helper.prop("mkbootimg")).let { ret ->
ret.addArgument("--header_version")
ret.addArgument(info.headerVersion.toString())
if (kernel.size > 0) {
ret.addArgument("--kernel")
ret.addArgument(this.kernel.file)
}
if (ramdisk.size > 0) {
ret.addArgument("--ramdisk")
ret.addArgument(this.ramdisk.file)
}
if (info.cmdline.isNotBlank()) {
ret.addArgument(" --cmdline ")
ret.addArgument(info.cmdline, false)
}
if (info.osVersion.isNotBlank()) {
ret.addArgument(" --os_version")
ret.addArgument(info.osVersion)
}
if (info.osPatchLevel.isNotBlank()) {
ret.addArgument(" --os_patch_level")
ret.addArgument(info.osPatchLevel)
}
if (this.bootSignature.size > 0 && File(Avb.getJsonFileName(this.bootSignature.file)).exists()) {
val origSig = mapper.readValue(File(Avb.getJsonFileName(this.bootSignature.file)), AVBInfo::class.java)
val alg = Algorithms.get(origSig.header!!.algorithm_type)!!
ret.addArgument("--gki_signing_algorithm").addArgument(alg.name)
ret.addArgument("--gki_signing_key").addArgument(alg.defaultKey)
ret.addArgument("--gki_signing_avbtool_path").addArgument(String.format(Helper.prop("avbtool"), "v1.2"))
}
ret.addArgument(" --id ")
ret.addArgument(" --output ")
//ret.addArgument("boot.img" + ".google")
log.debug("To Commandline: $ret")
ret
}
}
}
| apache-2.0 | 002b320931ba3e62bef79c5eeab739cc | 40.399554 | 137 | 0.548714 | 4.467004 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/InboxActivity.kt | 1 | 6471 | package com.pr0gramm.app.ui
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.viewpager.widget.ViewPager
import com.pr0gramm.app.R
import com.pr0gramm.app.databinding.ActivityInboxBinding
import com.pr0gramm.app.services.InboxService
import com.pr0gramm.app.services.ThemeHelper
import com.pr0gramm.app.services.Track
import com.pr0gramm.app.services.UserService
import com.pr0gramm.app.ui.base.BaseAppCompatActivity
import com.pr0gramm.app.ui.base.bindViews
import com.pr0gramm.app.ui.base.launchWhenCreated
import com.pr0gramm.app.ui.fragments.ConversationsFragment
import com.pr0gramm.app.ui.fragments.GenericInboxFragment
import com.pr0gramm.app.ui.fragments.WrittenCommentsFragment
import com.pr0gramm.app.util.di.instance
import com.pr0gramm.app.util.startActivity
import kotlinx.coroutines.flow.collect
/**
* The activity that displays the inbox.
*/
class InboxActivity : BaseAppCompatActivity("InboxActivity") {
private val userService: UserService by instance()
private val inboxService: InboxService by instance()
private val views by bindViews(ActivityInboxBinding::inflate)
private lateinit var tabsAdapter: TabsStateAdapter
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(ThemeHelper.theme.noActionBar)
super.onCreate(savedInstanceState)
if (!userService.isAuthorized) {
startActivity<MainActivity>()
finish()
return
}
setContentView(views)
setSupportActionBar(views.toolbar)
supportActionBar?.apply {
setDisplayShowHomeEnabled(true)
setDisplayHomeAsUpEnabled(true)
}
tabsAdapter = TabsStateAdapter(this)
InboxType.values().forEach { type ->
when (type) {
InboxType.PRIVATE -> tabsAdapter.addTab(getString(R.string.inbox_type_private), id = InboxType.PRIVATE) {
ConversationsFragment()
}
InboxType.COMMENTS_OUT -> tabsAdapter.addTab(getString(R.string.inbox_type_comments_out), id = InboxType.COMMENTS_OUT) {
WrittenCommentsFragment()
}
InboxType.ALL -> tabsAdapter.addTab(getString(R.string.inbox_type_all), id = InboxType.ALL) {
GenericInboxFragment()
}
InboxType.COMMENTS_IN -> tabsAdapter.addTab(getString(R.string.inbox_type_comments_in), id = InboxType.COMMENTS_IN) {
GenericInboxFragment(GenericInboxFragment.MessageTypeComments)
}
InboxType.STALK -> tabsAdapter.addTab(getString(R.string.inbox_type_stalk), id = InboxType.STALK) {
GenericInboxFragment(GenericInboxFragment.MessageTypeStalk)
}
InboxType.NOTIFICATIONS -> tabsAdapter.addTab(getString(R.string.inbox_type_notifications), id = InboxType.NOTIFICATIONS) {
GenericInboxFragment(GenericInboxFragment.MessageTypeNotifications)
}
}
}
views.pager.adapter = tabsAdapter
views.pager.offscreenPageLimit = 1
views.pager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
override fun onPageSelected(position: Int) {
onTabChanged()
}
})
views.tabs.setupWithViewPager(views.pager, true)
// restore previously selected tab
if (savedInstanceState != null) {
views.pager.currentItem = savedInstanceState.getInt("tab")
} else {
handleNewIntent(intent)
}
// track if we've clicked the notification!
if (intent.getBooleanExtra(EXTRA_FROM_NOTIFICATION, false)) {
Track.inboxNotificationClosed("clicked")
}
intent.getStringExtra(EXTRA_CONVERSATION_NAME)?.let { name ->
ConversationActivity.start(this, name, skipInbox = true)
}
launchWhenCreated {
inboxService.unreadMessagesCount().collect { counts ->
fun titleOf(id: Int, count: Int): String {
return getString(id) + (if (count > 0) " ($count)" else "")
}
tabsAdapter.updateTabTitle(InboxType.ALL, titleOf(R.string.inbox_type_all, counts.total))
tabsAdapter.updateTabTitle(InboxType.PRIVATE, titleOf(R.string.inbox_type_private, counts.messages))
tabsAdapter.updateTabTitle(InboxType.NOTIFICATIONS, titleOf(R.string.inbox_type_notifications, counts.notifications))
tabsAdapter.updateTabTitle(InboxType.STALK, titleOf(R.string.inbox_type_stalk, counts.follows))
tabsAdapter.updateTabTitle(InboxType.COMMENTS_IN, titleOf(R.string.inbox_type_comments_in, counts.comments))
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return super.onOptionsItemSelected(item) || when (item.itemId) {
android.R.id.home -> {
finish()
true
}
else -> false
}
}
override fun onStart() {
super.onStart()
Track.inboxActivity()
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handleNewIntent(intent)
}
private fun handleNewIntent(intent: Intent?) {
val extras = intent?.extras ?: return
showInboxType(InboxType.values()[extras.getInt(EXTRA_INBOX_TYPE, 0)])
}
private fun showInboxType(type: InboxType?) {
if (type != null && type.ordinal < tabsAdapter.getItemCount()) {
views.pager.currentItem = type.ordinal
}
}
override fun onResumeFragments() {
super.onResumeFragments()
onTabChanged()
}
private fun onTabChanged() {
val index = views.pager.currentItem
if (index >= 0 && index < tabsAdapter.getItemCount()) {
title = tabsAdapter.getPageTitle(index)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("tab", views.pager.currentItem)
}
companion object {
const val EXTRA_INBOX_TYPE = "InboxActivity.inboxType"
const val EXTRA_FROM_NOTIFICATION = "InboxActivity.fromNotification"
const val EXTRA_CONVERSATION_NAME = "InboxActivity.conversationName"
}
}
| mit | 8fba6077f7bdaeaff894acd6db38c76a | 35.150838 | 139 | 0.650595 | 4.655396 | false | false | false | false |
Geobert/radis | app/src/main/kotlin/fr/geobert/radis/ui/StatisticsListFragment.kt | 1 | 4515 | package fr.geobert.radis.ui
import android.app.Activity
import android.content.Intent
import android.content.IntentFilter
import android.database.Cursor
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.support.v4.app.LoaderManager.LoaderCallbacks
import android.support.v4.content.CursorLoader
import android.support.v4.content.Loader
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import fr.geobert.radis.BaseFragment
import fr.geobert.radis.R
import fr.geobert.radis.db.DbContentProvider
import fr.geobert.radis.db.StatisticTable
import fr.geobert.radis.service.OnRefreshReceiver
import fr.geobert.radis.tools.Tools
import fr.geobert.radis.ui.adapter.StatisticAdapter
import fr.geobert.radis.ui.editor.StatisticEditor
import kotlin.properties.Delegates
class StatisticsListFragment : BaseFragment(), LoaderCallbacks<Cursor> {
val ctx: FragmentActivity by lazy(LazyThreadSafetyMode.NONE) { activity }
private val STAT_LOADER = 2020
private var mContainer: View by Delegates.notNull()
private var mList: RecyclerView by Delegates.notNull()
private val mEmptyView: View by lazy(LazyThreadSafetyMode.NONE) { mContainer.findViewById(R.id.empty_textview) }
private var mAdapter: StatisticAdapter? = null
private var mLoader: Loader<Cursor>? = null
private val mOnRefreshReceiver by lazy(LazyThreadSafetyMode.NONE) { OnRefreshReceiver(this) }
override fun setupIcon() = setIcon(R.drawable.stat_48)
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
super.onCreateView(inflater, container, savedInstanceState)
val v = inflater?.inflate(R.layout.statistics_list_fragment, container, false) as View
mContainer = v
mList = v.findViewById(R.id.operation_list) as RecyclerView
mList.layoutManager = android.support.v7.widget.LinearLayoutManager(activity)
mList.setHasFixedSize(true)
mList.itemAnimator = DefaultItemAnimator()
setupIcon()
setMenu(R.menu.operations_list_menu)
mActivity.registerReceiver(mOnRefreshReceiver, IntentFilter(Tools.INTENT_REFRESH_STAT))
return v
}
override fun onDestroyView() {
super.onDestroyView()
mActivity.unregisterReceiver(mOnRefreshReceiver)
}
override fun onMenuItemClick(item: MenuItem?): Boolean =
when (item?.itemId) {
R.id.create_operation -> {
StatisticEditor.callMeForResult(ctx)
true
}
else ->
false
}
override fun onResume(): Unit {
super.onResume()
fetchStats()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
fetchStats()
}
}
override fun onOperationEditorResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK) {
fetchStats()
}
}
private fun fetchStats() {
when (mLoader) {
null ->
ctx.supportLoaderManager?.initLoader(STAT_LOADER, Bundle(), this)
else ->
ctx.supportLoaderManager?.restartLoader(STAT_LOADER, Bundle(), this)
}
}
override fun updateDisplay(intent: Intent?) {
fetchStats()
}
override fun onCreateLoader(p1: Int, p2: Bundle?): Loader<Cursor>? {
mLoader = CursorLoader(ctx, DbContentProvider.STATS_URI, StatisticTable.STAT_COLS, null, null, null)
return mLoader
}
override fun onLoaderReset(p1: Loader<Cursor>?): Unit {
mLoader?.reset()
}
override fun onLoadFinished(loader: Loader<Cursor>?, cursor: Cursor): Unit {
val a = mAdapter
if (a == null) {
mAdapter = StatisticAdapter(cursor, this)
mList.adapter = mAdapter
} else {
a.swapCursor(cursor)
}
if (mAdapter?.itemCount == 0) {
mList.visibility = View.GONE
mEmptyView.visibility = View.VISIBLE
} else {
mList.visibility = View.VISIBLE
mEmptyView.visibility = View.GONE
}
}
}
| gpl-2.0 | aceb692f0f77f1fb11edfe23b8d9e57e | 34 | 116 | 0.677519 | 4.635524 | false | false | false | false |
i7c/cfm | server/mbservice/src/main/kotlin/org/rliz/mbs/release/data/Release.kt | 1 | 637 | package org.rliz.mbs.release.data
import org.rliz.mbs.artist.data.ArtistCredit
import java.util.Date
import java.util.UUID
class Release {
val id: Long? = null
val gid: UUID? = null
// status | integer
// packaging | integer
// language | integer
// script | integer
// barcode | character varying(255)
// edits_pending | integer
// quality | smallint
val name: String? = null
val artistCredit: ArtistCredit? = null
val comment: String? = null
val lastUpdated: Date? = null
val releaseGroup: ReleaseGroup? = null
}
| gpl-3.0 | ba32803157b926cce2c354ca7c81d1ea | 20.233333 | 48 | 0.594976 | 3.932099 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.