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
zdary/intellij-community
plugins/git4idea/src/git4idea/config/GitVcsPanel.kt
1
21844
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.config import com.intellij.application.options.editor.CheckboxDescriptor import com.intellij.application.options.editor.checkBox import com.intellij.dvcs.branch.DvcsSyncSettings import com.intellij.dvcs.ui.DvcsBundle import com.intellij.ide.ui.search.OptionDescription import com.intellij.openapi.Disposable import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.application.runInEdt import com.intellij.openapi.components.service import com.intellij.openapi.options.BoundCompositeConfigurable import com.intellij.openapi.options.SearchableConfigurable import com.intellij.openapi.options.UnnamedConfigurable import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsEnvCustomizer import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager import com.intellij.openapi.vcs.changes.onChangeListAvailabilityChanged import com.intellij.openapi.vcs.update.AbstractCommonUpdateAction import com.intellij.ui.* import com.intellij.ui.components.JBLabel import com.intellij.ui.components.TextComponentEmptyText import com.intellij.ui.components.fields.ExpandableTextField import com.intellij.ui.layout.* import com.intellij.util.Function import com.intellij.util.execution.ParametersListUtil import com.intellij.util.ui.UIUtil import com.intellij.util.ui.VcsExecutablePathSelector import com.intellij.vcs.commit.CommitModeManager import com.intellij.vcs.log.VcsLogFilterCollection.STRUCTURE_FILTER import com.intellij.vcs.log.impl.MainVcsLogUiProperties import com.intellij.vcs.log.ui.VcsLogColorManagerImpl import com.intellij.vcs.log.ui.filter.StructureFilterPopupComponent import com.intellij.vcs.log.ui.filter.VcsLogClassicFilterUi import git4idea.GitVcs import git4idea.branch.GitBranchIncomingOutgoingManager import git4idea.i18n.GitBundle.message import git4idea.index.canEnableStagingArea import git4idea.index.enableStagingArea import git4idea.repo.GitRepositoryManager import git4idea.update.GitUpdateProjectInfoLogProperties import git4idea.update.getUpdateMethods import org.jetbrains.annotations.CalledInAny import java.awt.Color import java.awt.event.FocusAdapter import java.awt.event.FocusEvent import javax.swing.JLabel import javax.swing.border.Border private fun gitSharedSettings(project: Project) = GitSharedSettings.getInstance(project) private fun projectSettings(project: Project) = GitVcsSettings.getInstance(project) private val applicationSettings get() = GitVcsApplicationSettings.getInstance() private val gitOptionGroupName get() = message("settings.git.option.group") // @formatter:off private fun cdSyncBranches(project: Project) = CheckboxDescriptor(DvcsBundle.message("sync.setting"), PropertyBinding({ projectSettings(project).syncSetting == DvcsSyncSettings.Value.SYNC }, { projectSettings(project).syncSetting = if (it) DvcsSyncSettings.Value.SYNC else DvcsSyncSettings.Value.DONT_SYNC }), groupName = gitOptionGroupName) private val cdCommitOnCherryPick get() = CheckboxDescriptor(message("settings.commit.automatically.on.cherry.pick"), PropertyBinding(applicationSettings::isAutoCommitOnCherryPick, applicationSettings::setAutoCommitOnCherryPick), groupName = gitOptionGroupName) private fun cdAddCherryPickSuffix(project: Project) = CheckboxDescriptor(message("settings.add.suffix"), PropertyBinding({ projectSettings(project).shouldAddSuffixToCherryPicksOfPublishedCommits() }, { projectSettings(project).setAddSuffixToCherryPicks(it) }), groupName = gitOptionGroupName) private fun cdWarnAboutCrlf(project: Project) = CheckboxDescriptor(message("settings.crlf"), PropertyBinding({ projectSettings(project).warnAboutCrlf() }, { projectSettings(project).setWarnAboutCrlf(it) }), groupName = gitOptionGroupName) private fun cdWarnAboutDetachedHead(project: Project) = CheckboxDescriptor(message("settings.detached.head"), PropertyBinding({ projectSettings(project).warnAboutDetachedHead() }, { projectSettings(project).setWarnAboutDetachedHead(it) }), groupName = gitOptionGroupName) private fun cdAutoUpdateOnPush(project: Project) = CheckboxDescriptor(message("settings.auto.update.on.push.rejected"), PropertyBinding({ projectSettings(project).autoUpdateIfPushRejected() }, { projectSettings(project).setAutoUpdateIfPushRejected(it) }), groupName = gitOptionGroupName) private fun cdShowCommitAndPushDialog(project: Project) = CheckboxDescriptor(message("settings.push.dialog"), PropertyBinding({ projectSettings(project).shouldPreviewPushOnCommitAndPush() }, { projectSettings(project).setPreviewPushOnCommitAndPush(it) }), groupName = gitOptionGroupName) private fun cdHidePushDialogForNonProtectedBranches(project: Project) = CheckboxDescriptor(message("settings.push.dialog.for.protected.branches"), PropertyBinding({ projectSettings(project).isPreviewPushProtectedOnly }, { projectSettings(project).isPreviewPushProtectedOnly = it }), groupName = gitOptionGroupName) private val cdOverrideCredentialHelper get() = CheckboxDescriptor(message("settings.credential.helper"), PropertyBinding({ applicationSettings.isUseCredentialHelper }, { applicationSettings.isUseCredentialHelper = it }), groupName = gitOptionGroupName) private fun synchronizeBranchProtectionRules(project: Project) = CheckboxDescriptor(message("settings.synchronize.branch.protection.rules"), PropertyBinding({gitSharedSettings(project).isSynchronizeBranchProtectionRules}, { gitSharedSettings(project).isSynchronizeBranchProtectionRules = it }), groupName = gitOptionGroupName, comment = message("settings.synchronize.branch.protection.rules.description")) private val cdEnableStagingArea get() = CheckboxDescriptor(message("settings.enable.staging.area"), PropertyBinding({ applicationSettings.isStagingAreaEnabled }, { enableStagingArea(it) }), groupName = gitOptionGroupName, comment = message("settings.enable.staging.area.comment")) // @formatter:on internal fun gitOptionDescriptors(project: Project): List<OptionDescription> { val list = mutableListOf( cdCommitOnCherryPick, cdAutoUpdateOnPush(project), cdWarnAboutCrlf(project), cdWarnAboutDetachedHead(project), cdEnableStagingArea ) val manager = GitRepositoryManager.getInstance(project) if (manager.moreThanOneRoot()) { list += cdSyncBranches(project) } return list.map(CheckboxDescriptor::asOptionDescriptor) } internal class GitVcsPanel(private val project: Project) : BoundCompositeConfigurable<UnnamedConfigurable>(message("settings.git.option.group"), "project.propVCSSupport.VCSs.Git"), SearchableConfigurable { private val projectSettings by lazy { GitVcsSettings.getInstance(project) } @Volatile private var versionCheckRequested = false private val currentUpdateInfoFilterProperties = MyLogProperties(project.service<GitUpdateProjectInfoLogProperties>()) private lateinit var branchUpdateInfoRow: Row private lateinit var branchUpdateInfoCommentRow: Row private lateinit var supportedBranchUpLabel: JLabel private val pathSelector: VcsExecutablePathSelector by lazy { VcsExecutablePathSelector(GitVcs.NAME, disposable!!, object : VcsExecutablePathSelector.ExecutableHandler { override fun patchExecutable(executable: String): String? { return GitExecutableDetector.patchExecutablePath(executable) } override fun testExecutable(executable: String) { testGitExecutable(executable) } }) } private fun testGitExecutable(pathToGit: String) { val modalityState = ModalityState.stateForComponent(pathSelector.mainPanel) val errorNotifier = InlineErrorNotifierFromSettings( GitExecutableInlineComponent(pathSelector.errorComponent, modalityState, null), modalityState, disposable!! ) object : Task.Modal(project, message("git.executable.version.progress.title"), true) { private lateinit var gitVersion: GitVersion override fun run(indicator: ProgressIndicator) { val executableManager = GitExecutableManager.getInstance() val executable = executableManager.getExecutable(pathToGit) executableManager.dropVersionCache(executable) gitVersion = executableManager.identifyVersion(executable) } override fun onThrowable(error: Throwable) { val problemHandler = findGitExecutableProblemHandler(project) problemHandler.showError(error, errorNotifier) } override fun onSuccess() { if (gitVersion.isSupported) { errorNotifier.showMessage(message("git.executable.version.is", gitVersion.presentation)) } else { showUnsupportedVersionError(project, gitVersion, errorNotifier) } } }.queue() } private inner class InlineErrorNotifierFromSettings(inlineComponent: InlineComponent, private val modalityState: ModalityState, disposable: Disposable) : InlineErrorNotifier(inlineComponent, modalityState, disposable) { @CalledInAny override fun showError(text: String, description: String?, fixOption: ErrorNotifier.FixOption?) { if (fixOption is ErrorNotifier.FixOption.Configure) { super.showError(text, description, null) } else { super.showError(text, description, fixOption) } } override fun resetGitExecutable() { super.resetGitExecutable() GitExecutableManager.getInstance().getDetectedExecutable(project) // populate cache invokeAndWaitIfNeeded(modalityState) { resetPathSelector() } } } private fun getCurrentExecutablePath(): String? = pathSelector.currentPath?.takeIf { it.isNotBlank() } private fun LayoutBuilder.gitExecutableRow() = row { pathSelector.mainPanel(growX) .onReset { resetPathSelector() } .onIsModified { val projectSettingsPathToGit = projectSettings.pathToGit val currentPath = getCurrentExecutablePath() if (pathSelector.isOverridden) { currentPath != projectSettingsPathToGit } else { currentPath != applicationSettings.savedPathToGit || projectSettingsPathToGit != null } } .onApply { val executablePathOverridden = pathSelector.isOverridden val currentPath = getCurrentExecutablePath() if (executablePathOverridden) { projectSettings.pathToGit = currentPath } else { applicationSettings.setPathToGit(currentPath) projectSettings.pathToGit = null } validateExecutableOnceAfterClose() updateBranchUpdateInfoRow() VcsDirtyScopeManager.getInstance(project).markEverythingDirty() } } private fun resetPathSelector() { val projectSettingsPathToGit = projectSettings.pathToGit val detectedExecutable = try { GitExecutableManager.getInstance().getDetectedExecutable(project) } catch (e: ProcessCanceledException) { GitExecutableDetector.getDefaultExecutable() } pathSelector.reset(applicationSettings.savedPathToGit, projectSettingsPathToGit != null, projectSettingsPathToGit, detectedExecutable) updateBranchUpdateInfoRow() } /** * Special method to check executable after it has been changed through settings */ private fun validateExecutableOnceAfterClose() { if (versionCheckRequested) return versionCheckRequested = true runInEdt(ModalityState.NON_MODAL) { versionCheckRequested = false runBackgroundableTask(message("git.executable.version.progress.title"), project, true) { GitExecutableManager.getInstance().testGitExecutableVersionValid(project) } } } private fun updateBranchUpdateInfoRow() { val branchInfoSupported = GitVersionSpecialty.INCOMING_OUTGOING_BRANCH_INFO.existsIn(project) branchUpdateInfoRow.enabled = Registry.`is`("git.update.incoming.outgoing.info") && branchInfoSupported branchUpdateInfoCommentRow.visible = !branchInfoSupported supportedBranchUpLabel.foreground = if (!branchInfoSupported && projectSettings.incomingCheckStrategy != GitIncomingCheckStrategy.Never) { DialogWrapper.ERROR_FOREGROUND_COLOR } else { UIUtil.getContextHelpForeground() } } private fun LayoutBuilder.branchUpdateInfoRow() { branchUpdateInfoRow = row { supportedBranchUpLabel = JBLabel(message("settings.supported.for.2.9")) cell { label(message("settings.explicitly.check") + " ") comboBox( EnumComboBoxModel(GitIncomingCheckStrategy::class.java), { projectSettings.incomingCheckStrategy }, { selectedStrategy -> projectSettings.incomingCheckStrategy = selectedStrategy as GitIncomingCheckStrategy updateBranchUpdateInfoRow() if (!project.isDefault) { GitBranchIncomingOutgoingManager.getInstance(project).updateIncomingScheduling() } }) } branchUpdateInfoCommentRow = row { supportedBranchUpLabel() } } } override fun getId() = "vcs.${GitVcs.NAME}" override fun createConfigurables(): List<UnnamedConfigurable> { return VcsEnvCustomizer.EP_NAME.extensions.mapNotNull { it.getConfigurable(project) } } override fun createPanel(): DialogPanel = panel { gitExecutableRow() row { checkBox(cdEnableStagingArea) .enableIf(StagingAreaAvailablePredicate(project, disposable!!)) } if (project.isDefault || GitRepositoryManager.getInstance(project).moreThanOneRoot()) { row { checkBox(cdSyncBranches(project)).applyToComponent { toolTipText = DvcsBundle.message("sync.setting.description", GitVcs.DISPLAY_NAME.get()) } } } row { checkBox(cdCommitOnCherryPick) .enableIf(ChangeListsEnabledPredicate(project, disposable!!)) } row { checkBox(cdAddCherryPickSuffix(project)) } row { checkBox(cdWarnAboutCrlf(project)) } row { checkBox(cdWarnAboutDetachedHead(project)) } branchUpdateInfoRow() row { cell { label(message("settings.update.method")) comboBox( CollectionComboBoxModel(getUpdateMethods()), { projectSettings.updateMethod }, { projectSettings.updateMethod = it!! }, renderer = SimpleListCellRenderer.create<UpdateMethod>("", UpdateMethod::getName) ) } } row { cell { label(message("settings.clean.working.tree")) buttonGroup({ projectSettings.saveChangesPolicy }, { projectSettings.saveChangesPolicy = it }) { GitSaveChangesPolicy.values().forEach { saveSetting -> radioButton(saveSetting.text, saveSetting) } } } } row { checkBox(cdAutoUpdateOnPush(project)) } row { val previewPushOnCommitAndPush = checkBox(cdShowCommitAndPushDialog(project)) row { checkBox(cdHidePushDialogForNonProtectedBranches(project)) .enableIf(previewPushOnCommitAndPush.selected) } } row { cell { label(message("settings.protected.branched")) val sharedSettings = gitSharedSettings(project) val protectedBranchesField = ExpandableTextFieldWithReadOnlyText(ParametersListUtil.COLON_LINE_PARSER, ParametersListUtil.COLON_LINE_JOINER) if (sharedSettings.isSynchronizeBranchProtectionRules) { protectedBranchesField.readOnlyText = ParametersListUtil.COLON_LINE_JOINER.`fun`(sharedSettings.additionalProhibitedPatterns) } protectedBranchesField(growX) .withBinding<List<String>>( { ParametersListUtil.COLON_LINE_PARSER.`fun`(it.text) }, { component, value -> component.text = ParametersListUtil.COLON_LINE_JOINER.`fun`(value) }, PropertyBinding( { sharedSettings.forcePushProhibitedPatterns }, { sharedSettings.forcePushProhibitedPatterns = it }) ) } row { checkBox(synchronizeBranchProtectionRules(project)) } } row { checkBox(cdOverrideCredentialHelper) } for (configurable in configurables) { appendDslConfigurableRow(configurable) } if (AbstractCommonUpdateAction.showsCustomNotification(listOf(GitVcs.getInstance(project)))) { updateProjectInfoFilter() } } private fun LayoutBuilder.updateProjectInfoFilter() { row { cell { val storedProperties = project.service<GitUpdateProjectInfoLogProperties>() val roots = ProjectLevelVcsManager.getInstance(project).getRootsUnderVcs(GitVcs.getInstance(project)).toSet() val model = VcsLogClassicFilterUi.FileFilterModel(roots, currentUpdateInfoFilterProperties, null) val component = object : StructureFilterPopupComponent(currentUpdateInfoFilterProperties, model, VcsLogColorManagerImpl(roots)) { override fun shouldDrawLabel(): Boolean = false override fun shouldIndicateHovering(): Boolean = false override fun getDefaultSelectorForeground(): Color = UIUtil.getLabelForeground() override fun createUnfocusedBorder(): Border { return FilledRoundedBorder(JBColor.namedColor("Component.borderColor", Gray.xBF), ARC_SIZE, 1) } }.initUi() label(message("settings.filter.update.info") + " ") component() .onIsModified { storedProperties.getFilterValues(STRUCTURE_FILTER.name) != currentUpdateInfoFilterProperties.structureFilter } .onApply { storedProperties.saveFilterValues(STRUCTURE_FILTER.name, currentUpdateInfoFilterProperties.structureFilter) } .onReset { currentUpdateInfoFilterProperties.structureFilter = storedProperties.getFilterValues(STRUCTURE_FILTER.name) model.updateFilterFromProperties() } } } } private class MyLogProperties(mainProperties: GitUpdateProjectInfoLogProperties) : MainVcsLogUiProperties by mainProperties { var structureFilter: List<String>? = null override fun getFilterValues(filterName: String): List<String>? = structureFilter.takeIf { filterName == STRUCTURE_FILTER.name } override fun saveFilterValues(filterName: String, values: MutableList<String>?) { if (filterName == STRUCTURE_FILTER.name) { structureFilter = values } } } } private typealias ParserFunction = Function<String, List<String>> private typealias JoinerFunction = Function<List<String>, String> internal class ExpandableTextFieldWithReadOnlyText(lineParser: ParserFunction, private val lineJoiner: JoinerFunction) : ExpandableTextField(lineParser, lineJoiner) { var readOnlyText = "" init { addFocusListener(object : FocusAdapter() { override fun focusLost(e: FocusEvent) { val myComponent = this@ExpandableTextFieldWithReadOnlyText if (e.component == myComponent) { val document = myComponent.document val documentText = document.getText(0, document.length) updateReadOnlyText(documentText) } } }) } override fun setText(t: String?) { if (!t.isNullOrBlank() && t != text) { updateReadOnlyText(t) } super.setText(t) } private fun updateReadOnlyText(@NlsSafe text: String) { if (readOnlyText.isBlank()) return val readOnlySuffix = if (text.isBlank()) readOnlyText else lineJoiner.join("", readOnlyText) // NON-NLS with(emptyText as TextComponentEmptyText) { clear() appendText(text, SimpleTextAttributes.REGULAR_ATTRIBUTES) appendText(readOnlySuffix, SimpleTextAttributes.GRAYED_ATTRIBUTES) setTextToTriggerStatus(text) //this will force status text rendering in case if the text field is not empty } } fun JoinerFunction.join(vararg items: String): String = `fun`(items.toList()) } private class StagingAreaAvailablePredicate(val project: Project, val disposable: Disposable) : ComponentPredicate() { override fun addListener(listener: (Boolean) -> Unit) { project.messageBus.connect(disposable).subscribe(CommitModeManager.SETTINGS, object : CommitModeManager.SettingsListener { override fun settingsChanged() { listener(invoke()) } }) } override fun invoke(): Boolean = canEnableStagingArea() } private class ChangeListsEnabledPredicate(val project: Project, val disposable: Disposable) : ComponentPredicate() { override fun addListener(listener: (Boolean) -> Unit) { onChangeListAvailabilityChanged(project, disposable, false) { listener(invoke()) } } override fun invoke(): Boolean = ChangeListManager.getInstance(project).areChangeListsEnabled() }
apache-2.0
4c8a22a2faa6e109087d9482b24f3820
44.225673
420
0.731688
5.176303
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/jvmStatic/annotations.kt
2
1346
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME // FILE: Test.java import java.lang.annotation.Annotation; class Test { public static String test1() throws NoSuchMethodException { Annotation[] test1s = A.class.getMethod("test1").getAnnotations(); for (Annotation test : test1s) { String name = test.toString(); if (name.contains("testAnnotation")) { return "OK"; } } return "fail"; } public static String test2() throws NoSuchMethodException { Annotation[] test2s = B.class.getMethod("test1").getAnnotations(); for (Annotation test : test2s) { String name = test.toString(); if (name.contains("testAnnotation")) { return "OK"; } } return "fail"; } } // FILE: test.kt @Retention(AnnotationRetention.RUNTIME) annotation class testAnnotation class A { companion object { val b: String = "OK" @JvmStatic @testAnnotation fun test1() = b } } object B { val b: String = "OK" @JvmStatic @testAnnotation fun test1() = b } fun box(): String { if (Test.test1() != "OK") return "fail 1" if (Test.test2() != "OK") return "fail 2" return "OK" }
apache-2.0
3c50716bcc43b4bed187839cb835eda5
21.065574
74
0.581724
4.005952
false
true
false
false
AndroidX/androidx
compose/ui/ui-graphics/src/androidMain/kotlin/androidx/compose/ui/graphics/AndroidRenderEffect.android.kt
3
5409
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.graphics import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.runtime.Immutable import androidx.compose.ui.geometry.Offset /** * Convert the [android.graphics.RenderEffect] instance into a Compose-compatible [RenderEffect] */ fun android.graphics.RenderEffect.asComposeRenderEffect(): RenderEffect = AndroidRenderEffect(this) @Immutable actual sealed class RenderEffect { private var internalRenderEffect: android.graphics.RenderEffect? = null /** * Obtain a [android.graphics.RenderEffect] from the compose [RenderEffect] */ @RequiresApi(Build.VERSION_CODES.S) fun asAndroidRenderEffect(): android.graphics.RenderEffect = internalRenderEffect ?: createRenderEffect().also { internalRenderEffect = it } @RequiresApi(Build.VERSION_CODES.S) protected abstract fun createRenderEffect(): android.graphics.RenderEffect actual open fun isSupported(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S } @Immutable internal class AndroidRenderEffect( val androidRenderEffect: android.graphics.RenderEffect ) : RenderEffect() { override fun createRenderEffect(): android.graphics.RenderEffect = androidRenderEffect } @Immutable actual class BlurEffect actual constructor( private val renderEffect: RenderEffect?, private val radiusX: Float, private val radiusY: Float, private val edgeTreatment: TileMode ) : RenderEffect() { @RequiresApi(Build.VERSION_CODES.S) override fun createRenderEffect(): android.graphics.RenderEffect = RenderEffectVerificationHelper.createBlurEffect( renderEffect, radiusX, radiusY, edgeTreatment ) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is BlurEffect) return false if (radiusX != other.radiusX) return false if (radiusY != other.radiusY) return false if (edgeTreatment != other.edgeTreatment) return false if (renderEffect != other.renderEffect) return false return true } override fun hashCode(): Int { var result = renderEffect?.hashCode() ?: 0 result = 31 * result + radiusX.hashCode() result = 31 * result + radiusY.hashCode() result = 31 * result + edgeTreatment.hashCode() return result } override fun toString(): String { return "BlurEffect(renderEffect=$renderEffect, radiusX=$radiusX, radiusY=$radiusY, " + "edgeTreatment=$edgeTreatment)" } } @Immutable actual class OffsetEffect actual constructor( private val renderEffect: RenderEffect?, private val offset: Offset ) : RenderEffect() { @RequiresApi(Build.VERSION_CODES.S) override fun createRenderEffect(): android.graphics.RenderEffect = RenderEffectVerificationHelper.createOffsetEffect(renderEffect, offset) override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is OffsetEffect) return false if (renderEffect != other.renderEffect) return false if (offset != other.offset) return false return true } override fun hashCode(): Int { var result = renderEffect?.hashCode() ?: 0 result = 31 * result + offset.hashCode() return result } override fun toString(): String { return "OffsetEffect(renderEffect=$renderEffect, offset=$offset)" } } @RequiresApi(Build.VERSION_CODES.S) private object RenderEffectVerificationHelper { @androidx.annotation.DoNotInline fun createBlurEffect( inputRenderEffect: RenderEffect?, radiusX: Float, radiusY: Float, edgeTreatment: TileMode ): android.graphics.RenderEffect = if (inputRenderEffect == null) { android.graphics.RenderEffect.createBlurEffect( radiusX, radiusY, edgeTreatment.toAndroidTileMode() ) } else { android.graphics.RenderEffect.createBlurEffect( radiusX, radiusY, inputRenderEffect.asAndroidRenderEffect(), edgeTreatment.toAndroidTileMode() ) } @androidx.annotation.DoNotInline fun createOffsetEffect( inputRenderEffect: RenderEffect?, offset: Offset ): android.graphics.RenderEffect = if (inputRenderEffect == null) { android.graphics.RenderEffect.createOffsetEffect(offset.x, offset.y) } else { android.graphics.RenderEffect.createOffsetEffect( offset.x, offset.y, inputRenderEffect.asAndroidRenderEffect() ) } }
apache-2.0
93070929727f4df5ce8aeab72464ef19
31.196429
96
0.674247
4.769841
false
false
false
false
hannesa2/owncloud-android
owncloudData/src/main/java/com/owncloud/android/data/capabilities/db/OCCapabilityDao.kt
2
2346
/** * ownCloud Android client application * * @author David González Verdugo * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.data.capabilities.db import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import com.owncloud.android.data.ProviderMeta.ProviderTableMeta @Dao abstract class OCCapabilityDao { companion object { private const val SELECT = "SELECT * " + "FROM ${ProviderTableMeta.CAPABILITIES_TABLE_NAME} " + "WHERE ${ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME} = :accountName" private const val DELETE = "DELETE FROM ${ProviderTableMeta.CAPABILITIES_TABLE_NAME} " + "WHERE ${ProviderTableMeta.CAPABILITIES_ACCOUNT_NAME} = :accountName" } @Query(SELECT) abstract fun getCapabilitiesForAccountAsLiveData( accountName: String ): LiveData<OCCapabilityEntity?> @Query(SELECT) abstract fun getCapabilitiesForAccount( accountName: String ): OCCapabilityEntity? @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun insert(ocCapability: OCCapabilityEntity): Long @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun insert(ocCapabilities: List<OCCapabilityEntity>): List<Long> @Query(DELETE) abstract fun delete(accountName: String) @Transaction open fun replace(ocCapabilities: List<OCCapabilityEntity>) { ocCapabilities.forEach { ocCapability -> ocCapability.accountName?.run { delete(this) } } insert(ocCapabilities) } }
gpl-2.0
970d612058953f5139f9f03d93018f56
32.028169
89
0.70533
4.652778
false
false
false
false
ianhanniballake/muzei
android-client-common/src/main/java/com/google/android/apps/muzei/util/ShadowDipsTextView.kt
2
1670
/* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei.util import android.content.Context import android.util.AttributeSet import android.widget.TextView import androidx.core.content.res.use import net.nurik.roman.muzei.androidclientcommon.R class ShadowDipsTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : TextView(context, attrs, defStyle) { init { context.obtainStyledAttributes(attrs, R.styleable.ShadowDipsTextView, defStyle, 0).use { val shadowDx = it.getDimensionPixelSize(R.styleable.ShadowDipsTextView_shadowDx, 0) val shadowDy = it.getDimensionPixelSize(R.styleable.ShadowDipsTextView_shadowDy, 0) val shadowRadius = it.getDimensionPixelSize(R.styleable.ShadowDipsTextView_shadowRadius, 0) val shadowColor = it.getColor(R.styleable.ShadowDipsTextView_shadowColor, 0) if (shadowColor != 0) { setShadowLayer(shadowRadius.toFloat(), shadowDx.toFloat(), shadowDy.toFloat(), shadowColor) } } } }
apache-2.0
93fded042ef405208068904e4c37eca6
40.75
116
0.720958
4.217172
false
false
false
false
smmribeiro/intellij-community
platform/core-impl/src/com/intellij/openapi/progress/ProgressIndicatorEx.kt
12
5434
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("ProgressIndicatorForCollections") package com.intellij.openapi.progress import com.intellij.concurrency.SensitiveProgressWrapper import com.intellij.openapi.progress.util.AbstractProgressIndicatorExBase import com.intellij.openapi.progress.util.RelayUiToDelegateIndicator import org.jetbrains.annotations.ApiStatus @JvmSynthetic inline fun <Y> ProgressIndicator.withPushPop(action: () -> Y): Y { val wasIndeterminate = isIndeterminate pushState() try { return action() } finally { isIndeterminate = wasIndeterminate popState() } } @JvmSynthetic inline fun <Y> Collection<Y>.forEachWithProgress(indicator: ProgressIndicator, action: (Y, ProgressIndicator) -> Unit) { indicator.withPushPop { indicator.isIndeterminate = false indicator.checkCanceled() val size = this.size.toDouble() for ((i, y) in this.withIndex()) { indicator.checkCanceled() val lowerBound = i / size val upperBound = (i + 1) / size indicator.fraction = lowerBound val prevText = indicator.text val prevText2 = indicator.text2 action(y, indicator.scaleFraction(lowerBound, upperBound)) indicator.text = prevText indicator.text2 = prevText2 } indicator.fraction = 1.0 } } @JvmSynthetic inline fun <Y, R> Collection<Y>.mapWithProgress(indicator: ProgressIndicator, action: (Y, ProgressIndicator) -> R): List<R> { indicator.checkCanceled() val result = mutableListOf<R>() forEachWithProgress(indicator) { y, it -> result += action(y, it) } indicator.checkCanceled() return result.toList() } @JvmSynthetic @PublishedApi @ApiStatus.Internal internal fun ProgressIndicator.scaleFraction( lowerBound: Double, upperBound: Double ): ProgressIndicator { val parentProgress = this return object : SensitiveProgressWrapper(parentProgress) { private var myFraction = 0.0 private val d = upperBound - lowerBound init { //necessary for push/pop state methods text = parentProgress.text text2 = parentProgress.text2 } override fun getFraction() = synchronized(lock) { myFraction } override fun setFraction(fraction: Double) { //there is no need to propagate too small parts at all if (d <= 0.001) return synchronized(lock) { myFraction = fraction } parentProgress.fraction = (lowerBound + d * fraction).coerceIn(lowerBound, upperBound) } override fun setIndeterminate(indeterminate: Boolean) { //ignore } override fun isIndeterminate() = false } } /** * Implements the best effort in translating progress events from * the parent [parentProgress] into [childProgress] while running the * [action]. It may pass either of the progresses to the action */ inline fun <Y> runUnderNestedProgressAndRelayMessages(parentProgress: ProgressIndicator, childProgress: ProgressIndicator, crossinline action: (ProgressIndicator) -> Y): Y { //avoid the action to be inlined multiple times in the code @Suppress("NAME_SHADOWING") val action : (ProgressIndicator) -> Y = { action(it) } //case 1 - parent progress is capable of delegates if (parentProgress is AbstractProgressIndicatorExBase) { return runWithStateDelegate(parentProgress, RelayUiToDelegateIndicator(childProgress)) { runUnderBoundCancellation(cancelOf = childProgress, cancels = parentProgress) { action(parentProgress) } } } //case 2 - we run it under child progress and delegate messages back if (childProgress is AbstractProgressIndicatorExBase) { return runWithStateDelegate(childProgress, RelayUiToDelegateIndicator(parentProgress)) { runUnderBoundCancellation(cancelOf = parentProgress, cancels = childProgress) { action(childProgress) } } } //case 3 - just run it under child progress, no connection is supported return action(childProgress) } /** * A best effort way to bind a cancellation of one progress with the other. */ inline fun <Y> runUnderBoundCancellation(cancelOf: ProgressIndicator, cancels: ProgressIndicator, crossinline action: () -> Y) : Y { //avoid the action to be inlined multiple times in the code @Suppress("NAME_SHADOWING") val action : () -> Y = { action() } if (cancelOf !is AbstractProgressIndicatorExBase) { return action() } val relay = object: AbstractProgressIndicatorExBase() { override fun cancel() { super.cancel() cancels.cancel() } } return runWithStateDelegate(cancelOf, relay, action) } /** * Runs an action on [parentProgress] with the state delegate attached for the * time [action] runs. */ inline fun <Y> runWithStateDelegate(parentProgress: AbstractProgressIndicatorExBase, delegate: AbstractProgressIndicatorExBase, action: () -> Y): Y { parentProgress.addStateDelegate(delegate) try { return action() } finally { parentProgress.removeStateDelegate(delegate) } }
apache-2.0
b069872f67d59ad2b952c478409abb75
30.593023
140
0.674273
4.640478
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/ui/adapters/RewardCardAdapter.kt
1
3843
package com.kickstarter.ui.adapters import android.util.Pair import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.recyclerview.widget.RecyclerView import com.kickstarter.R import com.kickstarter.databinding.EmptyViewBinding import com.kickstarter.databinding.ItemAddCardBinding import com.kickstarter.databinding.ItemRewardSelectedCardBinding import com.kickstarter.databinding.ItemRewardUnselectedCardBinding import com.kickstarter.models.Project import com.kickstarter.models.StoredCard import com.kickstarter.ui.data.CardState import com.kickstarter.ui.viewholders.EmptyViewHolder import com.kickstarter.ui.viewholders.KSViewHolder import com.kickstarter.ui.viewholders.RewardAddCardViewHolder import com.kickstarter.ui.viewholders.RewardCardSelectedViewHolder import com.kickstarter.ui.viewholders.RewardCardUnselectedViewHolder import com.kickstarter.ui.viewholders.State import rx.Observable class RewardCardAdapter(private val delegate: Delegate) : KSAdapter() { interface Delegate : RewardCardUnselectedViewHolder.Delegate, RewardAddCardViewHolder.Delegate private var selectedPosition = Pair(RecyclerView.NO_POSITION, CardState.SELECTED) init { val placeholders = arrayOfNulls<Any>(3).toList() addSection(placeholders) } override fun layout(sectionRow: SectionRow): Int { return if (sections().size == 1) { R.layout.item_reward_placeholder_card } else { if (sectionRow.section() == 0) { if (sectionRow.row() == this.selectedPosition.first) { return when { this.selectedPosition.second == CardState.SELECTED -> R.layout.item_reward_selected_card else -> R.layout.item_reward_unselected_card } } R.layout.item_reward_unselected_card } else { R.layout.item_add_card } } } override fun viewHolder(@LayoutRes layout: Int, viewGroup: ViewGroup): KSViewHolder { return when (layout) { R.layout.item_add_card -> RewardAddCardViewHolder(ItemAddCardBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false), this.delegate) R.layout.item_reward_selected_card -> RewardCardSelectedViewHolder(ItemRewardSelectedCardBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false)) R.layout.item_reward_unselected_card -> RewardCardUnselectedViewHolder(ItemRewardUnselectedCardBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false), this.delegate) else -> EmptyViewHolder(EmptyViewBinding.inflate(LayoutInflater.from(viewGroup.context), viewGroup, false)) } } fun takeCards(cards: List<StoredCard>, project: Project) { sections().clear() addSection( Observable.from(cards) .map { Pair(it, project) } .toList().toBlocking().single() ) addSection(listOf(null)) notifyDataSetChanged() } fun setSelectedPosition(position: Int) { this.selectedPosition = Pair(position, CardState.SELECTED) notifyDataSetChanged() } fun resetSelectedPosition() { this.selectedPosition = Pair(RecyclerView.NO_POSITION, CardState.SELECTED) notifyDataSetChanged() } fun insertCard(storedCardAndProject: Pair<StoredCard, Project>): Int { val storedCards = sections()[0] val position = 0 storedCards.add(position, storedCardAndProject) notifyItemInserted(position) return position } fun updateState(state: State) { sections().last().clear() sections().last().add(0, state) notifyDataSetChanged() } }
apache-2.0
a7fccfb01ced2fea8cb908a8c5adf66a
39.03125
196
0.700234
4.815789
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddThrowsAnnotationIntention.kt
1
8039
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.Module import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.refactoring.fqName.fqName import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex import org.jetbrains.kotlin.idea.util.addAnnotation import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.platform.js.isJs import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypesAndPredicate import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.annotations.JVM_THROWS_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.resolve.annotations.KOTLIN_THROWS_ANNOTATION_FQ_NAME import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.getAbbreviatedType class AddThrowsAnnotationIntention : SelfTargetingIntention<KtThrowExpression>( KtThrowExpression::class.java, KotlinBundle.lazyMessage("add.throws.annotation") ) { override fun isApplicableTo(element: KtThrowExpression, caretOffset: Int): Boolean { if (element.platform.isJs()) return false val containingDeclaration = element.getContainingDeclaration() ?: return false val type = element.thrownExpression?.resolveToCall()?.resultingDescriptor?.returnType ?: return false if ((type.constructor.declarationDescriptor as? DeclarationDescriptorWithVisibility)?.visibility == DescriptorVisibilities.LOCAL) return false val module = element.module ?: return false if (!KOTLIN_THROWS_ANNOTATION_FQ_NAME.fqNameIsExists(module) && !(element.platform.isJvm() && JVM_THROWS_ANNOTATION_FQ_NAME.fqNameIsExists(module)) ) return false val context = element.analyze(BodyResolveMode.PARTIAL) val annotationEntry = containingDeclaration.findThrowsAnnotation(context) ?: return true val valueArguments = annotationEntry.valueArguments if (valueArguments.isEmpty()) return true val argumentExpression = valueArguments.firstOrNull()?.getArgumentExpression() if (argumentExpression is KtCallExpression && argumentExpression.calleeExpression?.getCallableDescriptor()?.fqNameSafe != FqName("kotlin.arrayOf") ) return false return valueArguments.none { it.hasType(type, context) } } override fun applyTo(element: KtThrowExpression, editor: Editor?) { val containingDeclaration = element.getContainingDeclaration() ?: return val type = element.thrownExpression?.resolveToCall()?.resultingDescriptor?.returnType ?: return val annotationArgumentText = if (type.getAbbreviatedType() != null) "$type::class" else type.constructor.declarationDescriptor?.fqNameSafe?.render()?.let { "$it::class" } ?: return val context = element.analyze(BodyResolveMode.PARTIAL) val annotationEntry = containingDeclaration.findThrowsAnnotation(context) if (annotationEntry == null || annotationEntry.valueArguments.isEmpty()) { annotationEntry?.delete() val whiteSpaceText = if (containingDeclaration is KtPropertyAccessor) " " else "\n" val annotationFqName = KOTLIN_THROWS_ANNOTATION_FQ_NAME.takeIf { element.languageVersionSettings.apiVersion >= ApiVersion.KOTLIN_1_4 } ?: JVM_THROWS_ANNOTATION_FQ_NAME containingDeclaration.addAnnotation(annotationFqName, annotationArgumentText, whiteSpaceText) } else { val factory = KtPsiFactory(element) val argument = annotationEntry.valueArguments.firstOrNull() val expression = argument?.getArgumentExpression() val added = when { argument?.getArgumentName() == null -> annotationEntry.valueArgumentList?.addArgument(factory.createArgument(annotationArgumentText)) expression is KtCallExpression -> expression.valueArgumentList?.addArgument(factory.createArgument(annotationArgumentText)) expression is KtClassLiteralExpression -> { expression.replaced( factory.createCollectionLiteral(listOf(expression), annotationArgumentText) ).getInnerExpressions().lastOrNull() } expression is KtCollectionLiteralExpression -> { expression.replaced( factory.createCollectionLiteral(expression.getInnerExpressions(), annotationArgumentText) ).getInnerExpressions().lastOrNull() } else -> null } if (added != null) ShortenReferences.DEFAULT.process(added) } } } private fun KtThrowExpression.getContainingDeclaration(): KtDeclaration? { val parent = getParentOfTypesAndPredicate( true, KtNamedFunction::class.java, KtSecondaryConstructor::class.java, KtPropertyAccessor::class.java, KtClassInitializer::class.java, KtLambdaExpression::class.java ) { true } if (parent is KtClassInitializer || parent is KtLambdaExpression) return null return parent as? KtDeclaration } private fun KtDeclaration.findThrowsAnnotation(context: BindingContext): KtAnnotationEntry? { val annotationEntries = this.annotationEntries + (parent as? KtProperty)?.annotationEntries.orEmpty() return annotationEntries.find { val typeReference = it.typeReference ?: return@find false val fqName = context[BindingContext.TYPE, typeReference]?.fqName ?: return@find false fqName == KOTLIN_THROWS_ANNOTATION_FQ_NAME || fqName == JVM_THROWS_ANNOTATION_FQ_NAME } } private fun ValueArgument.hasType(type: KotlinType, context: BindingContext): Boolean = when (val argumentExpression = getArgumentExpression()) { is KtClassLiteralExpression -> listOf(argumentExpression) is KtCollectionLiteralExpression -> argumentExpression.getInnerExpressions().filterIsInstance(KtClassLiteralExpression::class.java) is KtCallExpression -> argumentExpression.valueArguments.mapNotNull { it.getArgumentExpression() as? KtClassLiteralExpression } else -> emptyList() }.any { it.getType(context)?.arguments?.firstOrNull()?.type == type } private fun KtPsiFactory.createCollectionLiteral(expressions: List<KtExpression>, lastExpression: String): KtCollectionLiteralExpression = createExpression( (expressions.map { it.text } + lastExpression).joinToString(prefix = "[", postfix = "]") ) as KtCollectionLiteralExpression private fun FqName.fqNameIsExists(module: Module): Boolean { return KotlinFullClassNameIndex.get(asString(), module.project, GlobalSearchScope.moduleWithLibrariesScope(module)).isNotEmpty() }
apache-2.0
b83e62631ee6224f4023b8797d1b4a74
53.317568
158
0.741137
5.373663
false
false
false
false
siosio/intellij-community
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/run/KotlinRunConfiguration.kt
1
22795
// 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.run import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil import com.intellij.diagnostic.logging.LogConfigurationPanel import com.intellij.execution.* import com.intellij.execution.InputRedirectAware.InputRedirectOptions import com.intellij.execution.JavaRunConfigurationExtensionManager.Companion.checkConfigurationIsValid import com.intellij.execution.application.BaseJavaApplicationCommandLineState import com.intellij.execution.application.JvmMainMethodRunConfigurationOptions import com.intellij.execution.configurations.* import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.target.LanguageRuntimeType import com.intellij.execution.target.TargetEnvironmentAwareRunProfile import com.intellij.execution.target.TargetEnvironmentConfiguration import com.intellij.execution.target.getEffectiveTargetName import com.intellij.execution.target.java.JavaLanguageRuntimeConfiguration import com.intellij.execution.target.java.JavaLanguageRuntimeType import com.intellij.execution.util.JavaParametersUtil import com.intellij.execution.util.ProgramParametersUtil import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.options.SettingsEditor import com.intellij.openapi.options.SettingsEditorGroup import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JavaSdkVersion import com.intellij.openapi.projectRoots.ex.JavaSdkUtil import com.intellij.openapi.roots.DependencyScope import com.intellij.openapi.roots.ExportableOrderEntry import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.util.WriteExternalException import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiElement import com.intellij.psi.PsiJavaModule import com.intellij.psi.PsiPackage import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.GlobalSearchScopes import com.intellij.refactoring.listeners.RefactoringElementAdapter import com.intellij.refactoring.listeners.RefactoringElementListener import com.intellij.util.PathUtil import org.jdom.Element import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName import org.jetbrains.kotlin.idea.KotlinJvmBundle.message import org.jetbrains.kotlin.idea.MainFunctionDetector import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.core.isInTestSourceContentKotlinAware import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.run.KotlinRunConfigurationProducer.Companion.getEntryPointContainer import org.jetbrains.kotlin.idea.run.KotlinRunConfigurationProducer.Companion.getStartClassFqName import org.jetbrains.kotlin.idea.stubindex.KotlinFileFacadeFqNameIndex import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex import org.jetbrains.kotlin.idea.util.application.runReadActionInSmartMode import org.jetbrains.kotlin.idea.util.jvmName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.utils.addToStdlib.safeAs open class KotlinRunConfiguration(name: String?, runConfigurationModule: JavaRunConfigurationModule, factory: ConfigurationFactory?) : JavaRunConfigurationBase(name, runConfigurationModule, factory!!), CommonJavaRunConfigurationParameters, RefactoringListenerProvider, InputRedirectAware, TargetEnvironmentAwareRunProfile { init { runConfigurationModule.setModuleToAnyFirstIfNotSpecified() } override fun getValidModules(): Collection<Module> = ModuleManager.getInstance(project).modules.toList() override fun getSearchScope(): GlobalSearchScope? = GlobalSearchScopes.executionScope(modules.toList()) override fun getConfigurationEditor(): SettingsEditor<out RunConfiguration?> { val group = SettingsEditorGroup<KotlinRunConfiguration>() group.addEditor(ExecutionBundle.message("run.configuration.configuration.tab.title"), KotlinRunConfigurationEditor(project)) JavaRunConfigurationExtensionManager.instance.appendEditors(this, group) group.addEditor(ExecutionBundle.message("logs.tab.title"), LogConfigurationPanel()) return group } override fun getOptions(): JvmMainMethodRunConfigurationOptions { return super.getOptions() as JvmMainMethodRunConfigurationOptions } override fun readExternal(element: Element) { super<JavaRunConfigurationBase>.readExternal(element) JavaRunConfigurationExtensionManager.instance.readExternal(this, element) } @Throws(WriteExternalException::class) override fun writeExternal(element: Element) { super<JavaRunConfigurationBase>.writeExternal(element) JavaRunConfigurationExtensionManager.instance.writeExternal(this, element) } override fun setWorkingDirectory(value: String?) { val normalizedValue = if (StringUtil.isEmptyOrSpaces(value)) null else value!!.trim { it <= ' ' } val independentValue = PathUtil.toSystemIndependentName(normalizedValue) options.workingDirectory = independentValue?.takeIf { it != defaultWorkingDirectory() } } override fun getWorkingDirectory(): String? = options.workingDirectory?.let { FileUtilRt.toSystemDependentName(VirtualFileManager.extractPath(it)) } ?: PathUtil.toSystemDependentName(defaultWorkingDirectory()) protected open fun defaultWorkingDirectory() = project.basePath override fun setVMParameters(value: String?) { options.vmParameters = value } override fun getVMParameters(): String? { return options.vmParameters } override fun setProgramParameters(value: String?) { options.programParameters = value } override fun getProgramParameters(): String? { return options.programParameters } override fun setPassParentEnvs(passParentEnvs: Boolean) { options.isPassParentEnv = passParentEnvs } override fun isPassParentEnvs(): Boolean { return options.isPassParentEnv } override fun getEnvs(): Map<String, String> { return options.env } override fun setEnvs(envs: Map<String, String>) { options.env = envs.toMutableMap() } override fun getRunClass(): String? { return options.mainClassName } fun setRunClass(value: String?) { options.mainClassName = value } override fun getPackage(): String? { return null } override fun isAlternativeJrePathEnabled(): Boolean { return options.isAlternativeJrePathEnabled } override fun setAlternativeJrePathEnabled(enabled: Boolean) { options.isAlternativeJrePathEnabled = enabled } override fun getAlternativeJrePath(): String? { return options.alternativeJrePath } override fun setAlternativeJrePath(path: String?) { options.alternativeJrePath = path } fun findMainClassFile(): KtFile? { val module = configurationModule?.module ?: return null val mainClassName = options.mainClassName?.takeIf { !StringUtil.isEmpty(it) } ?: return null return findMainClassFile(module, mainClassName) } @Throws(RuntimeConfigurationException::class) override fun checkConfiguration() { JavaParametersUtil.checkAlternativeJRE(this) ProgramParametersUtil.checkWorkingDirectoryExist(this, project, configurationModule!!.module) checkConfigurationIsValid(this) val module = configurationModule!!.module ?: throw RuntimeConfigurationError(message("run.configuration.error.no.module")) val mainClassName = options.mainClassName?.takeIf { !StringUtil.isEmpty(it) } ?: throw RuntimeConfigurationError(message("run.configuration.error.no.main.class")) val mainFile = findMainClassFile(module, mainClassName) ?: throw RuntimeConfigurationWarning( message("run.configuration.error.class.not.found", mainClassName, configurationModule!!.moduleName) ) if (!mainFile.hasMainFun()) { throw RuntimeConfigurationWarning(message("run.configuration.error.class.no.main.method", mainClassName)) } } @Throws(ExecutionException::class) override fun getState(executor: Executor, executionEnvironment: ExecutionEnvironment): RunProfileState? { return MyJavaCommandLineState(this, executionEnvironment) } override fun getRefactoringElementListener(element: PsiElement): RefactoringElementListener? { val fqNameBeingRenamed: String? = when (element) { is KtDeclarationContainer -> getStartClassFqName(element as KtDeclarationContainer) is PsiPackage -> element.qualifiedName else -> null } val mainClassName = options.mainClassName if (mainClassName == null || mainClassName != fqNameBeingRenamed && !mainClassName.startsWith("$fqNameBeingRenamed.") ) { return null } if (element is KtDeclarationContainer) { return object : RefactoringElementAdapter() { override fun undoElementMovedOrRenamed(newElement: PsiElement, oldQualifiedName: String) { updateMainClassName(newElement) } override fun elementRenamedOrMoved(newElement: PsiElement) { updateMainClassName(newElement) } } } val nameSuffix = mainClassName.substring(fqNameBeingRenamed!!.length) return object : RefactoringElementAdapter() { override fun elementRenamedOrMoved(newElement: PsiElement) { updateMainClassNameWithSuffix(newElement, nameSuffix) } override fun undoElementMovedOrRenamed(newElement: PsiElement, oldQualifiedName: String) { updateMainClassNameWithSuffix(newElement, nameSuffix) } } } private fun updateMainClassName(element: PsiElement) { val container = getEntryPointContainer(element) ?: return val name = getStartClassFqName(container) if (name != null) { runClass = name } } private fun updateMainClassNameWithSuffix(element: PsiElement, suffix: String) { if (element is PsiPackage) { runClass = element.qualifiedName + suffix } } override fun suggestedName(): String? { val runClass = runClass if (StringUtil.isEmpty(runClass)) { return null } val parts = StringUtil.split(runClass!!, ".") return if (parts.isEmpty()) { runClass } else parts[parts.size - 1] } override fun getInputRedirectOptions(): InputRedirectOptions { return options.redirectOptions } override fun canRunOn(target: TargetEnvironmentConfiguration): Boolean { return target.runtimes.findByType(JavaLanguageRuntimeConfiguration::class.java) != null } override fun getDefaultLanguageRuntimeType(): LanguageRuntimeType<*>? { return LanguageRuntimeType.EXTENSION_NAME.findExtension(JavaLanguageRuntimeType::class.java) } override fun getDefaultTargetName(): String? { return options.remoteTarget } override fun setDefaultTargetName(targetName: String?) { options.remoteTarget = targetName } override fun needPrepareTarget(): Boolean { return getEffectiveTargetName(project) != null || runsUnderWslJdk() } override fun getShortenCommandLine(): ShortenCommandLine? { return options.shortenClasspath } override fun setShortenCommandLine(mode: ShortenCommandLine?) { options.shortenClasspath = mode } private class MyJavaCommandLineState(configuration: KotlinRunConfiguration, environment: ExecutionEnvironment?) : BaseJavaApplicationCommandLineState<KotlinRunConfiguration?>(environment, configuration) { @Throws(ExecutionException::class) override fun createJavaParameters(): JavaParameters { val params = JavaParameters() val module = myConfiguration.configurationModule val classPathType = DumbService.getInstance(module!!.project).computeWithAlternativeResolveEnabled<Int, Exception> { getClasspathType(module) } val jreHome = if (myConfiguration.isAlternativeJrePathEnabled) myConfiguration.alternativeJrePath else null JavaParametersUtil.configureModule(module, params, classPathType, jreHome) setupJavaParameters(params) params.setShortenCommandLine(null, module.project) params.mainClass = myConfiguration.runClass setupModulePath(params, module) return params } private fun getClasspathType(configurationModule: RunConfigurationModule?): Int { val module = configurationModule!!.module ?: throw CantRunException.noModuleConfigured(configurationModule.moduleName) val runClass = myConfiguration.runClass ?: throw CantRunException(message("run.configuration.error.run.class.should.be.defined", myConfiguration.name)) val findMainClassFile = findMainClassFile(module, runClass) ?: throw CantRunException.classNotFound(runClass, module) val classModule = ModuleUtilCore.findModuleForPsiElement(findMainClassFile) ?: module val virtualFileForMainFun = findMainClassFile.virtualFile ?: throw CantRunException(noFunctionFoundMessage(findMainClassFile)) val fileIndex = ModuleRootManager.getInstance(classModule).fileIndex if (fileIndex.isInSourceContent(virtualFileForMainFun)) { return if (fileIndex.isInTestSourceContentKotlinAware(virtualFileForMainFun)) { JavaParameters.JDK_AND_CLASSES_AND_TESTS } else { JavaParameters.JDK_AND_CLASSES } } val entriesForFile = fileIndex.getOrderEntriesForFile(virtualFileForMainFun) for (entry in entriesForFile) { if (entry is ExportableOrderEntry && entry.scope == DependencyScope.TEST) { return JavaParameters.JDK_AND_CLASSES_AND_TESTS } } return JavaParameters.JDK_AND_CLASSES } @Nls private fun noFunctionFoundMessage(ktFile: KtFile): String { val packageFqName = ktFile.packageFqName return message("run.configuration.error.main.not.found.top.level", packageFqName.asString()) } companion object { private fun setupModulePath(params: JavaParameters, module: JavaRunConfigurationModule?) { if (JavaSdkUtil.isJdkAtLeast(params.jdk, JavaSdkVersion.JDK_1_9)) { DumbService.getInstance(module!!.project).computeWithAlternativeResolveEnabled<PsiJavaModule?, Exception> { JavaModuleGraphUtil.findDescriptorByElement(module.findClass(params.mainClass)) }?.let { mainModule -> params.moduleName = mainModule.name val classPath = params.classPath val modulePath = params.modulePath modulePath.addAll(classPath.pathList) classPath.clear() } } } } } companion object { private fun KtNamedFunction.isAMainCandidate(): Boolean { if (isLocal) return false val jvmName = jvmName if (!(name == "main" && jvmName == null || jvmName == "main")) return false // method annotated with @JvmName("main") could be a candidate as well val valueParameter = valueParameters.singleOrNull() val valueParameterType = valueParameter?.typeReference?.typeElement?.safeAs<KtUserType>() val argsIsStringArray = // `vararg String` has same semantic for main function as Array<String> (valueParameter?.isVarArg == true && valueParameterType?.referencedName == "String") || // Array<String> valueParameter?.typeReference?.typeElement?.run { // to handle `Array` or `Array?` safeAs<KtUserType>() ?: safeAs<KtNullableType>()?.innerType.safeAs() }?.run { referencedName == "Array" && typeArgumentList?.arguments?.singleOrNull()?.run { typeReference?.typeElement?.safeAs<KtUserType>()?.referencedName == "String" && // <String> / <out String> projectionKind.run { this == KtProjectionKind.NONE || this == KtProjectionKind.OUT } } ?: false } ?: false val topLevel = isTopLevel return topLevel && ( // top level could be parameterless name == "main" && jvmName == null && (valueParameters.isEmpty() || argsIsStringArray) || // but if it has @JvmName("main") it has to have Array<String> parameter (jvmName == "main" && argsIsStringArray) ) || !topLevel && // nested main method has to have Array<String> parameter argsIsStringArray && // has to have @JvmStatic annotation annotationEntries.any { it.shortName?.asString() == "JvmStatic" } && (getParentOfType<KtObjectDeclaration>(false) != null) } private fun KtDeclarationContainer.getMainFunCandidates(): Collection<KtNamedFunction> = declarations.filterIsInstance<KtNamedFunction>().filter { it.isAMainCandidate() } private fun KtElement.findMainFunCandidates(): Collection<KtNamedFunction> = collectDescendantsOfType<KtNamedFunction>().filter { it.isAMainCandidate() } fun findMainClassFile( module: Module, mainClassName: String, shouldUseSlowResolve: Boolean = module.project.shouldUseSlowResolve() ): KtFile? { val project = module.project.takeUnless { it.isDefault } ?: return null val scope = module.getModuleRuntimeScope(true) val shortName = StringUtil.getShortName(mainClassName) val psiFacade = JavaPsiFacade.getInstance(project) fun findPackageNameHeuristically(base: String): String { val packageName = StringUtil.getPackageName(base) if (packageName.isEmpty()) return packageName return packageName.takeIf { psiFacade.findPackage(it) != null } ?: findPackageNameHeuristically(packageName) } val packageName = findPackageNameHeuristically(mainClassName) val dotNotationFqName = if (mainClassName.contains('$')) { StringUtil.getQualifiedName(StringUtil.getPackageName(mainClassName), shortName.replace('$', '.')) } else { mainClassName } // heuristically here means that it follows some common sense: // classes of package a.b.c are located in folder `a/b/c` fun findMainClassFileHeuristically(): Collection<KtFile> { val className = if (packageName.isEmpty()) dotNotationFqName else dotNotationFqName.substring(packageName.length + 1) return psiFacade.findPackage(packageName)?.let { pkg -> pkg.getFiles(scope).filterIsInstance<KtFile>().filter { ktFile -> // for top level functions ktFile.javaFileFacadeFqName.shortName().asString() == shortName || run { // or within a nested class-or-object var parent: KtDeclarationContainer? = ktFile className.split('.').forEach { name -> parent = parent?.declarations ?.filterIsInstance<KtClassOrObject>() ?.firstOrNull { it.name == name } ?: return@run false } parent?.getMainFunCandidates()?.isNotEmpty() ?: false } } } ?: emptyList() } fun findFiles(fqName: String) = if (shouldUseSlowResolve) { findMainClassFileHeuristically() } else { project.runReadActionInSmartMode { KotlinFileFacadeFqNameIndex.INSTANCE.get(fqName, project, scope).takeIf { it.isNotEmpty() } ?: KotlinFullClassNameIndex.getInstance().get(fqName, project, scope) .flatMap { it.findMainFunCandidates() } .map { it.containingKtFile } } } return findFiles(dotNotationFqName).firstOrNull { it.hasMainFun(shouldUseSlowResolve) } } private fun Project.shouldUseSlowResolve(): Boolean = takeUnless { it.isDefault }?.let { DumbService.getInstance(this).isDumb } ?: false private fun KtFile.hasMainFun( shouldUseSlowResolve: Boolean = project.shouldUseSlowResolve() ): Boolean { val mainFunCandidates = findMainFunCandidates() if (shouldUseSlowResolve && mainFunCandidates.size == 1) { return true } val versionSettings = this.languageVersionSettings return mainFunCandidates.any { MainFunctionDetector(versionSettings) { f -> f.resolveToDescriptorIfAny() } .isMain(it) } } } }
apache-2.0
6141f1f95d32ba08b399b3ae6093cb37
45.713115
158
0.668348
5.718766
false
true
false
false
siosio/intellij-community
platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarStopAction.kt
1
1718
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.runToolbar import com.intellij.execution.KillableProcess import com.intellij.execution.impl.ExecutionManagerImpl import com.intellij.execution.ui.RunContentDescriptor import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAware class RunToolbarStopAction : AnAction(AllIcons.Actions.Suspend), DumbAware, RTBarAction { override fun getRightSideType(): RTBarAction.Type = RTBarAction.Type.RIGHT_STABLE override fun actionPerformed(e: AnActionEvent) { e.environment()?.contentToReuse?.let { if (canBeStopped(it)) ExecutionManagerImpl.stopProcess(it) } } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = e.environment()?.let { if(e.isItRunToolbarMainSlot() && !RunToolbarSlotManager.getInstance(it.project).getState().isSingleProcess() && !e.isOpened() ) return@let false e.presentation.icon = e.environment()?.getRunToolbarProcess()?.getStopIcon() ?: templatePresentation.icon it.contentToReuse?.let { canBeStopped(it) } } ?: false } private fun canBeStopped(descriptor: RunContentDescriptor?): Boolean { val processHandler = descriptor?.processHandler return (processHandler != null && !processHandler.isProcessTerminated && (!processHandler.isProcessTerminating || processHandler is KillableProcess && (processHandler as KillableProcess).canKillProcess())) } }
apache-2.0
a3e79c4dcfa6a33c8650ac5a2cc34645
40.926829
140
0.749127
4.798883
false
false
false
false
jwren/intellij-community
plugins/package-search/maven/src/com/jetbrains/packagesearch/intellij/plugin/maven/GetMavenVersionPsiElement.kt
1
940
package com.jetbrains.packagesearch.intellij.plugin.maven import com.intellij.buildsystem.model.unified.UnifiedDependency import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.xml.XmlTag import org.jetbrains.idea.maven.dom.MavenDomUtil import org.jetbrains.idea.maven.navigator.MavenNavigationUtil internal fun getMavenVersionPsiElement( dependency: UnifiedDependency, file: PsiFile ): PsiElement? { val groupId = dependency.coordinates.groupId ?: return null val artifactId = dependency.coordinates.artifactId ?: return null val projectModel = MavenDomUtil.getMavenDomProjectModel(file.project, file.virtualFile) ?: return null val mavenDependency = MavenNavigationUtil.findDependency(projectModel, groupId, artifactId) val element = mavenDependency?.version?.xmlElement ?: return null return if (element is XmlTag) element.value.textElements.firstOrNull() else null }
apache-2.0
c16e6bcb1fe8989d7ccc1269c3fb10dd
39.869565
106
0.809574
4.723618
false
false
false
false
bjansen/pebble-intellij
src/main/kotlin/com/github/bjansen/intellij/pebble/lang/PebbleParameterInfoHandler.kt
1
3727
package com.github.bjansen.intellij.pebble.lang import com.github.bjansen.intellij.pebble.psi.PebbleArgumentList import com.github.bjansen.intellij.pebble.psi.PebbleIdentifier import com.github.bjansen.intellij.pebble.psi.PebbleParserDefinition.Companion.rules import com.github.bjansen.intellij.pebble.psi.PebbleParserDefinition.Companion.tokens import com.github.bjansen.pebble.parser.PebbleLexer import com.github.bjansen.pebble.parser.PebbleParser import com.intellij.codeInsight.hint.api.impls.MethodParameterInfoHandler import com.intellij.lang.parameterInfo.CreateParameterInfoContext import com.intellij.lang.parameterInfo.ParameterInfoUIContext import com.intellij.lang.parameterInfo.ParameterInfoUtils.findParentOfType import com.intellij.lang.parameterInfo.ParameterInfoUtils.getCurrentParameterIndex import com.intellij.lang.parameterInfo.UpdateParameterInfoContext import com.intellij.psi.* import com.intellij.psi.tree.IElementType import org.antlr.intellij.adaptor.psi.ANTLRPsiNode class PebbleParameterInfoHandler : PebbleBaseParameterInfoHandler() { override fun getArgListStopSearchClasses(): MutableSet<out Class<Any>> = mutableSetOf() override fun getArgumentListClass() = PebbleArgumentList::class.java override fun getArgumentListAllowedParentClasses() = mutableSetOf(ANTLRPsiNode::class.java) override fun getActualParametersRBraceType(): IElementType { return tokens[PebbleLexer.RBRACE] } override fun getActualParameterDelimiterType(): IElementType { return tokens[PebbleLexer.COMMA] } override fun getActualParameters(o: PebbleArgumentList): Array<PsiElement> { return o.children.filter { it.node.elementType == rules[PebbleParser.RULE_expression] }.toTypedArray() } override fun updateParameterInfo(args: PebbleArgumentList, context: UpdateParameterInfoContext) { val index = getCurrentParameterIndex(args.node, context.offset, tokens[PebbleLexer.COMMA]) context.setCurrentParameter(index) // context.highlightedParameter = context.objectsToView.first { // if (it is PsiMethod) // it.parameterList.parametersCount >= index // else // false // } } override fun updateUI(p: PsiElement?, context: ParameterInfoUIContext) { updatePresentation(p, context) } fun updatePresentation(p: PsiElement?, context: ParameterInfoUIContext): String? { if (p is PsiMethod) { return MethodParameterInfoHandler.updateMethodPresentation(p, PsiSubstitutor.EMPTY, context) } return null } override fun findElementForUpdatingParameterInfo(context: UpdateParameterInfoContext): PebbleArgumentList? { return findParentOfType(context.file, context.offset, PebbleArgumentList::class.java) } override fun findElementForParameterInfo(context: CreateParameterInfoContext): PebbleArgumentList? { val argList = findParentOfType(context.file, context.offset, PebbleArgumentList::class.java) if (argList != null) { val identifier = argList.parent.firstChild if (identifier is PebbleIdentifier) { context.itemsToShow = identifier.references.flatMap { (it as PsiPolyVariantReference).multiResolve(false) .map(ResolveResult::getElement) }.toTypedArray() } return argList } return null } override fun showParameterInfo(element: PebbleArgumentList, context: CreateParameterInfoContext) { context.showHint(element, element.textRange.startOffset, this) } }
mit
d371d0d0971d93b4274da5d29b306ea5
39.51087
112
0.730614
5.02969
false
false
false
false
androidx/androidx
datastore/datastore-sampleapp/src/main/java/com/example/datastoresampleapp/SettingsFragment.kt
3
6331
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.datastoresampleapp import android.annotation.SuppressLint import android.content.Context import android.os.Bundle import android.util.Log import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.datastore.core.CorruptionException import androidx.datastore.core.DataStore import androidx.datastore.core.DataStoreFactory import androidx.datastore.core.Serializer import androidx.preference.Preference import androidx.preference.SwitchPreference import androidx.preference.PreferenceFragmentCompat import androidx.lifecycle.lifecycleScope import androidx.preference.TwoStatePreference import com.google.protobuf.InvalidProtocolBufferException import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.launch import java.io.File import java.io.IOException import java.io.InputStream import java.io.OutputStream private val TAG = "SettingsActivity" class SettingsFragmentActivity() : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportFragmentManager.beginTransaction() .replace(android.R.id.content, SettingsFragment()).commit() } } /** * Toggle States: * 1) Value not read from disk. Toggle is disabled in default position. * 2) Value read from disk and no pending updates. Toggle is enabled in latest persisted position. * 3) Value read from disk but with pending updates. Toggle is disabled in pending position. */ class SettingsFragment() : PreferenceFragmentCompat() { private val fooToggle: TwoStatePreference by lazy { createFooPreference(preferenceManager.context) } private val PROTO_STORE_FILE_NAME = "datastore_test_app.pb" private val settingsStore: DataStore<Settings> by lazy { DataStoreFactory.create( serializer = SettingsSerializer ) { File(requireActivity().applicationContext.filesDir, PROTO_STORE_FILE_NAME) } } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { val preferences = preferenceManager.createPreferenceScreen(preferenceManager.context) preferences.addPreference(fooToggle) preferenceScreen = preferences } @Suppress("OPT_IN_MARKER_ON_OVERRIDE_WARNING") @SuppressLint("SyntheticAccessor") @ExperimentalCoroutinesApi override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewLifecycleOwner.lifecycleScope.launchWhenStarted { // Read the initial value from disk val settings: Settings = try { settingsStore.data.first() } catch (ex: IOException) { Log.e(TAG, "Could not read settings.", ex) // Show error to user here, or try re-reading. return@launchWhenStarted } // Set the toggle to the value read from disk and enable the toggle. fooToggle.isChecked = settings.foo fooToggle.isEnabled = true fooToggle.changeFlow.flatMapLatest { (_: Preference?, newValue: Any?) -> val isChecked = newValue as Boolean fooToggle.isEnabled = false // Disable the toggle until the write is completed fooToggle.isChecked = isChecked // Set the disabled toggle to the pending value try { settingsStore.setFoo(isChecked) } catch (ex: IOException) { // setFoo can only throw IOExceptions Log.e(TAG, "Could not write settings", ex) // Show error to user here } settingsStore.data // Switch to data flow since it is the source of truth. }.collect { // We update the toggle to the latest persisted value - whether or not the // update succeeded. If the write failed, this will reset to original state. fooToggle.isChecked = it.foo fooToggle.isEnabled = true } } } private suspend fun DataStore<Settings>.setFoo(foo: Boolean) = updateData { it.toBuilder().setFoo(foo).build() } private fun createFooPreference(context: Context) = SwitchPreference(context).apply { isEnabled = false // Start out disabled isPersistent = false // Disable SharedPreferences title = "Foo title" summary = "Summary of Foo toggle" } } @ExperimentalCoroutinesApi private val Preference.changeFlow: Flow<Pair<Preference?, Any?>> get() = callbackFlow { [email protected] { preference: Preference?, newValue: Any? -> [email protected] { send(Pair(preference, newValue)) } false // Do not update the state of the toggle. } awaitClose { [email protected] = null } } private object SettingsSerializer : Serializer<Settings> { override val defaultValue: Settings = Settings.getDefaultInstance() override suspend fun readFrom(input: InputStream): Settings { try { return Settings.parseFrom(input) } catch (ipbe: InvalidProtocolBufferException) { throw CorruptionException("Cannot read proto.", ipbe) } } override suspend fun writeTo(t: Settings, output: OutputStream) = t.writeTo(output) }
apache-2.0
71df6597bb6e1c92d8b1c8e3cf98f1f2
38.08642
98
0.697994
5.056709
false
false
false
false
cqjjjzr/Laplacian
Laplacian.Framework/src/main/kotlin/charlie/laplacian/decoder/DecoderRegistry.kt
1
1558
package charlie.laplacian.decoder import charlie.laplacian.output.OutputSettings import charlie.laplacian.stream.TrackStream import java.util.* import kotlin.NoSuchElementException object DecoderRegistry { private val decoders: MutableList<Decoder> = LinkedList() fun registerDecoderFactory(factory: Decoder) { if (!decoders.contains(factory)) decoders += factory } fun unregisterDecoderFactory(factory: Decoder) { decoders -= factory } fun getMetadatas(): Array<DecoderMetadata> = Array(decoders.size, { decoders[it].getMetadata() }) fun moveUp(index: Int) { if (index == 0 || decoders.size <= 1) throw IllegalArgumentException() decoders[index - 1].apply { decoders[index - 1] = decoders[index] decoders[index] = this } } fun moveDown(index: Int) { if (index == decoders.size - 1 || decoders.size <= 1) throw IllegalArgumentException() decoders[index].apply { decoders[index] = decoders[index + 1] decoders[index + 1] = this } } fun tryDecode(outputSettings: OutputSettings, stream: TrackStream): DecoderSession { var e: Throwable? = null decoders.forEach { try { return it.getSession(outputSettings, stream) } catch (ex: Exception) { e = ex } } if (e == null) throw DecoderException(NoSuchElementException()) else throw DecoderException(e) } }
apache-2.0
cb4758882777a12d49a5d17020a0edbc
28.980769
101
0.607831
4.515942
false
false
false
false
GunoH/intellij-community
jvm/jvm-analysis-java-tests/testSrc/com/intellij/codeInspection/tests/java/test/JavaTestCaseWithConstructorInspectionTest.kt
4
3339
package com.intellij.codeInspection.tests.java.test import com.intellij.codeInspection.tests.ULanguage import com.intellij.codeInspection.tests.test.TestCaseWithConstructorInspectionTestBase class JavaTestCaseWithConstructorInspectionTest : TestCaseWithConstructorInspectionTestBase() { fun `test no highlighting parameterized test case`() { myFixture.testHighlighting(ULanguage.JAVA, """ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class ParameterizedTest { private final int myX; private final int myY; public ParameterizedTest(int x, int y) { myX = x; myY = y; } @Test public void testMe() { System.out.println(myX * myY); } @Parameterized.Parameters public static Object[][] parameters() { return new Object[][] {{1, 2}, {3, 4}}; } } """.trimIndent(), "ParameterizedTest") } fun `test no highlighting trivial constructor`() { myFixture.testHighlighting(ULanguage.JAVA, """ import junit.framework.TestCase; public class TestCaseWithConstructorInspection2 extends TestCase { public TestCaseWithConstructorInspection2() { super(); ; if (false) { System.out.println(); } } } """.trimIndent(), "TestCaseWithConstructorInspection2") } fun `test highlighting simple non-trivial constructor`() { myFixture.testHighlighting(ULanguage.JAVA, """ import junit.framework.TestCase; public class TestCaseWithConstructorInspection1 extends TestCase { public <warning descr="Initialization logic in constructor 'TestCaseWithConstructorInspection1()' instead of 'setup()' life cycle method">TestCaseWithConstructorInspection1</warning>() { System.out.println(""); } } """.trimIndent(), "TestCaseWithConstructorInspection1") } fun `test highlighting complex non-trivial constructor`() { myFixture.testHighlighting(ULanguage.JAVA, """ import junit.framework.TestCase; public class TestCaseWithConstructorInspection3 extends TestCase { public <warning descr="Initialization logic in constructor 'TestCaseWithConstructorInspection3()' instead of 'setup()' life cycle method">TestCaseWithConstructorInspection3</warning>() { super(); System.out.println("TestCaseWithConstructorInspection3.TestCaseWithConstructorInspection3"); } } """.trimIndent(), "TestCaseWithConstructorInspection3") } fun `test highlighting Junit 4`() { myFixture.testHighlighting(ULanguage.JAVA, """ public class JUnit4TestCaseWithConstructor { public <warning descr="Initialization logic in constructor 'JUnit4TestCaseWithConstructor()' instead of 'setup()' life cycle method">JUnit4TestCaseWithConstructor</warning>() { System.out.println(); System.out.println(); System.out.println(); } @org.junit.Test public void testMe() {} } """.trimIndent(), "JUnit4TestCaseWithConstructor") } }
apache-2.0
57cd5e0e756a9c57a30b513b50baff28
34.531915
196
0.662773
5.266562
false
true
false
false
siosio/intellij-community
platform/platform-tests/testSrc/com/intellij/ide/plugins/PluginModelTest.kt
1
1825
// 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.plugins import com.intellij.project.IntelliJProjectConfiguration import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.UsefulTestCase import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.util.JpsPathUtil.urlToPath import org.junit.Assert import org.junit.Test import java.nio.file.Path class PluginModelTest { @Test fun check() { val validator = validatePluginModel() if (!UsefulTestCase.IS_UNDER_TEAMCITY) { val out = Path.of(PlatformTestUtil.getCommunityPath(), System.getProperty("plugin.graph.out", "docs/plugin-graph/plugin-graph.local.json")) validator.writeGraph(out) println() println("Graph is written to $out") println("Drop file to https://plugingraph.ij.pages.jetbrains.team/ to visualize.") } } } fun validatePluginModel(): PluginModelValidator { val modules = IntelliJProjectConfiguration.loadIntelliJProject(homePath.toString()) .modules .map { wrap(it) } val validator = PluginModelValidator(modules) val errors = validator.errorsAsString if (!errors.isEmpty()) { System.err.println(errors) Assert.fail() } return validator } private fun wrap(module: JpsModule): PluginModelValidator.Module { return object : PluginModelValidator.Module { override val name: String get() = module.name override val sourceRoots: List<Path> get() { return module.sourceRoots .asSequence() .filter { !it.rootType.isForTests } .map { it.url } .map(::urlToPath) .map(Path::of) .toList() } } }
apache-2.0
89c9976009ddae07f2263f1c30647e81
30.482759
158
0.700822
4.284038
false
true
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/ObjCInterop.kt
1
15303
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin.backend.konan import org.jetbrains.kotlin.backend.konan.descriptors.findPackage import org.jetbrains.kotlin.backend.konan.descriptors.getArgumentValueOrNull import org.jetbrains.kotlin.backend.konan.descriptors.getAnnotationValueOrNull import org.jetbrains.kotlin.backend.konan.descriptors.getStringValue import org.jetbrains.kotlin.backend.konan.descriptors.getAnnotationStringValue import org.jetbrains.kotlin.backend.konan.descriptors.getStringValueOrNull import org.jetbrains.kotlin.backend.konan.ir.* import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.expressions.IrConstructorCall import org.jetbrains.kotlin.ir.symbols.isPublicApi import org.jetbrains.kotlin.ir.types.classOrNull import org.jetbrains.kotlin.ir.types.getPublicSignature import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.ExternalOverridabilityCondition import org.jetbrains.kotlin.resolve.constants.BooleanValue import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.getAllSuperClassifiers import org.jetbrains.kotlin.resolve.descriptorUtil.parentsWithSelf import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.typeUtil.supertypes import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult internal val interopPackageName = InteropFqNames.packageName internal val objCObjectFqName = interopPackageName.child(Name.identifier("ObjCObject")) internal val objCObjectIdSignature = getTopLevelPublicSignature(objCObjectFqName) private val objCClassFqName = interopPackageName.child(Name.identifier("ObjCClass")) private val objCClassIdSignature = getTopLevelPublicSignature(objCClassFqName) private val objCProtocolFqName = interopPackageName.child(Name.identifier("ObjCProtocol")) private val objCProtocolIdSignature = getTopLevelPublicSignature(objCProtocolFqName) internal val externalObjCClassFqName = interopPackageName.child(Name.identifier("ExternalObjCClass")) private val objCMethodFqName = interopPackageName.child(Name.identifier("ObjCMethod")) private val objCConstructorFqName = FqName("kotlinx.cinterop.ObjCConstructor") private val objCFactoryFqName = interopPackageName.child(Name.identifier("ObjCFactory")) private val objcnamesForwardDeclarationsPackageName = Name.identifier("objcnames") private fun getTopLevelPublicSignature(fqName: FqName): IdSignature.PublicSignature = getPublicSignature(fqName.parent(), fqName.shortName().asString()) fun ClassDescriptor.isObjCClass(): Boolean = this.containingDeclaration.fqNameSafe != interopPackageName && this.getAllSuperClassifiers().any { it.fqNameSafe == objCObjectFqName } // TODO: this is not cheap. Cache me! fun KotlinType.isObjCObjectType(): Boolean = (this.supertypes() + this).any { TypeUtils.getClassDescriptor(it)?.fqNameSafe == objCObjectFqName } private fun IrClass.selfOrAnySuperClass(pred: (IrClass) -> Boolean): Boolean { if (pred(this)) return true return superTypes.any { it.classOrNull!!.owner.selfOrAnySuperClass(pred) } } internal fun IrClass.isObjCClass() = this.packageFqName != interopPackageName && selfOrAnySuperClass { it.symbol.isPublicApi && objCObjectIdSignature == it.symbol.signature } fun ClassDescriptor.isExternalObjCClass(): Boolean = this.isObjCClass() && this.parentsWithSelf.filterIsInstance<ClassDescriptor>().any { it.annotations.findAnnotation(externalObjCClassFqName) != null } fun IrClass.isExternalObjCClass(): Boolean = this.isObjCClass() && (this as IrDeclaration).parentDeclarationsWithSelf.filterIsInstance<IrClass>().any { it.annotations.hasAnnotation(externalObjCClassFqName) } fun ClassDescriptor.isObjCForwardDeclaration(): Boolean = this.findPackage().fqName.startsWith(objcnamesForwardDeclarationsPackageName) fun ClassDescriptor.isObjCMetaClass(): Boolean = this.getAllSuperClassifiers().any { it.fqNameSafe == objCClassFqName } fun IrClass.isObjCMetaClass(): Boolean = selfOrAnySuperClass { it.symbol.isPublicApi && objCClassIdSignature == it.symbol.signature } fun IrClass.isObjCProtocolClass(): Boolean = symbol.isPublicApi && objCProtocolIdSignature == symbol.signature fun ClassDescriptor.isObjCProtocolClass(): Boolean = this.fqNameSafe == objCProtocolFqName fun FunctionDescriptor.isObjCClassMethod() = this.containingDeclaration.let { it is ClassDescriptor && it.isObjCClass() } fun IrFunction.isObjCClassMethod() = this.parent.let { it is IrClass && it.isObjCClass() } fun FunctionDescriptor.isExternalObjCClassMethod() = this.containingDeclaration.let { it is ClassDescriptor && it.isExternalObjCClass() } internal fun IrFunction.isExternalObjCClassMethod() = this.parent.let {it is IrClass && it.isExternalObjCClass()} // Special case: methods from Kotlin Objective-C classes can be called virtually from bridges. fun FunctionDescriptor.canObjCClassMethodBeCalledVirtually(overriddenDescriptor: FunctionDescriptor) = overriddenDescriptor.isOverridable && this.kind.isReal && !this.isExternalObjCClassMethod() internal fun IrFunction.canObjCClassMethodBeCalledVirtually(overridden: IrFunction) = overridden.isOverridable && this.origin != IrDeclarationOrigin.FAKE_OVERRIDE && !this.isExternalObjCClassMethod() fun ClassDescriptor.isKotlinObjCClass(): Boolean = this.isObjCClass() && !this.isExternalObjCClass() fun IrClass.isKotlinObjCClass(): Boolean = this.isObjCClass() && !this.isExternalObjCClass() data class ObjCMethodInfo(val selector: String, val encoding: String, val isStret: Boolean) private fun FunctionDescriptor.decodeObjCMethodAnnotation(): ObjCMethodInfo? { assert (this.kind.isReal) val methodAnnotation = this.annotations.findAnnotation(objCMethodFqName) ?: return null return objCMethodInfo(methodAnnotation) } private fun IrFunction.decodeObjCMethodAnnotation(): ObjCMethodInfo? { assert (this.isReal) val methodAnnotation = this.annotations.findAnnotation(objCMethodFqName) ?: return null return objCMethodInfo(methodAnnotation) } private fun objCMethodInfo(annotation: AnnotationDescriptor) = ObjCMethodInfo( selector = annotation.getStringValue("selector"), encoding = annotation.getStringValue("encoding"), isStret = annotation.getArgumentValueOrNull<Boolean>("isStret") ?: false ) private fun objCMethodInfo(annotation: IrConstructorCall) = ObjCMethodInfo( selector = annotation.getAnnotationStringValue("selector"), encoding = annotation.getAnnotationStringValue("encoding"), isStret = annotation.getAnnotationValueOrNull<Boolean>("isStret") ?: false ) /** * @param onlyExternal indicates whether to accept overriding methods from Kotlin classes */ private fun FunctionDescriptor.getObjCMethodInfo(onlyExternal: Boolean): ObjCMethodInfo? { if (this.kind.isReal) { this.decodeObjCMethodAnnotation()?.let { return it } if (onlyExternal) { return null } } return overriddenDescriptors.firstNotNullResult { it.getObjCMethodInfo(onlyExternal) } } /** * @param onlyExternal indicates whether to accept overriding methods from Kotlin classes */ private fun IrSimpleFunction.getObjCMethodInfo(onlyExternal: Boolean): ObjCMethodInfo? { if (this.isReal) { this.decodeObjCMethodAnnotation()?.let { return it } if (onlyExternal) { return null } } return overriddenSymbols.firstNotNullResult { it.owner.getObjCMethodInfo(onlyExternal) } } fun FunctionDescriptor.getExternalObjCMethodInfo(): ObjCMethodInfo? = this.getObjCMethodInfo(onlyExternal = true) fun IrFunction.getExternalObjCMethodInfo(): ObjCMethodInfo? = (this as? IrSimpleFunction)?.getObjCMethodInfo(onlyExternal = true) fun FunctionDescriptor.getObjCMethodInfo(): ObjCMethodInfo? = this.getObjCMethodInfo(onlyExternal = false) fun IrFunction.getObjCMethodInfo(): ObjCMethodInfo? = (this as? IrSimpleFunction)?.getObjCMethodInfo(onlyExternal = false) fun IrFunction.isObjCBridgeBased(): Boolean { assert(this.isReal) return this.annotations.hasAnnotation(objCMethodFqName) || this.annotations.hasAnnotation(objCFactoryFqName) || this.annotations.hasAnnotation(objCConstructorFqName) } /** * Describes method overriding rules for Objective-C methods. * * This class is applied at [org.jetbrains.kotlin.resolve.OverridingUtil] as configured with * `META-INF/services/org.jetbrains.kotlin.resolve.ExternalOverridabilityCondition` resource. */ class ObjCOverridabilityCondition : ExternalOverridabilityCondition { override fun getContract() = ExternalOverridabilityCondition.Contract.BOTH override fun isOverridable( superDescriptor: CallableDescriptor, subDescriptor: CallableDescriptor, subClassDescriptor: ClassDescriptor? ): ExternalOverridabilityCondition.Result { if (superDescriptor.name == subDescriptor.name) { // Slow path: if (superDescriptor is FunctionDescriptor && subDescriptor is FunctionDescriptor) { superDescriptor.getExternalObjCMethodInfo()?.let { superInfo -> val subInfo = subDescriptor.getExternalObjCMethodInfo() if (subInfo != null) { // Overriding Objective-C method by Objective-C method in interop stubs. // Don't even check method signatures: return if (superInfo.selector == subInfo.selector) { ExternalOverridabilityCondition.Result.OVERRIDABLE } else { ExternalOverridabilityCondition.Result.INCOMPATIBLE } } else { // Overriding Objective-C method by Kotlin method. if (!parameterNamesMatch(superDescriptor, subDescriptor)) { return ExternalOverridabilityCondition.Result.INCOMPATIBLE } } } } else if (superDescriptor.isExternalObjCClassProperty() && subDescriptor.isExternalObjCClassProperty()) { return ExternalOverridabilityCondition.Result.OVERRIDABLE } } return ExternalOverridabilityCondition.Result.UNKNOWN } private fun CallableDescriptor.isExternalObjCClassProperty() = this is PropertyDescriptor && (this.containingDeclaration as? ClassDescriptor)?.isExternalObjCClass() == true private fun parameterNamesMatch(first: FunctionDescriptor, second: FunctionDescriptor): Boolean { // The original Objective-C method selector is represented as // function name and parameter names (except first). if (first.valueParameters.size != second.valueParameters.size) { return false } first.valueParameters.forEachIndexed { index, parameter -> if (index > 0 && parameter.name != second.valueParameters[index].name) { return false } } return true } } fun IrConstructor.objCConstructorIsDesignated(): Boolean = this.getAnnotationArgumentValue<Boolean>(objCConstructorFqName, "designated") ?: error("Could not find 'designated' argument") fun ConstructorDescriptor.objCConstructorIsDesignated(): Boolean { val annotation = this.annotations.findAnnotation(objCConstructorFqName)!! val value = annotation.allValueArguments[Name.identifier("designated")]!! return (value as BooleanValue).value } val IrConstructor.isObjCConstructor get() = this.annotations.hasAnnotation(objCConstructorFqName) val ConstructorDescriptor.isObjCConstructor get() = this.annotations.hasAnnotation(objCConstructorFqName) // TODO-DCE-OBJC-INIT: Selector should be preserved by DCE. fun IrConstructor.getObjCInitMethod(): IrSimpleFunction? { return this.annotations.findAnnotation(objCConstructorFqName)?.let { val initSelector = it.getAnnotationStringValue("initSelector") this.constructedClass.declarations.asSequence() .filterIsInstance<IrSimpleFunction>() .single { it.getExternalObjCMethodInfo()?.selector == initSelector } } } fun ConstructorDescriptor.getObjCInitMethod(): FunctionDescriptor? { return this.annotations.findAnnotation(objCConstructorFqName)?.let { val initSelector = it.getAnnotationStringValue("initSelector") val memberScope = constructedClass.unsubstitutedMemberScope val functionNames = memberScope.getFunctionNames() for (name in functionNames) { val functions = memberScope.getContributedFunctions(name, NoLookupLocation.FROM_BACKEND) for (function in functions) { val objectInfo = function.getExternalObjCMethodInfo() ?: continue if (objectInfo.selector == initSelector) return function } } error("Cannot find ObjInitMethod for $this") } } val IrFunction.hasObjCFactoryAnnotation get() = this.annotations.hasAnnotation(objCFactoryFqName) val FunctionDescriptor.hasObjCFactoryAnnotation get() = this.annotations.hasAnnotation(objCFactoryFqName) val IrFunction.hasObjCMethodAnnotation get() = this.annotations.hasAnnotation(objCMethodFqName) val FunctionDescriptor.hasObjCMethodAnnotation get() = this.annotations.hasAnnotation(objCMethodFqName) fun FunctionDescriptor.getObjCFactoryInitMethodInfo(): ObjCMethodInfo? { val factoryAnnotation = this.annotations.findAnnotation(objCFactoryFqName) ?: return null return objCMethodInfo(factoryAnnotation) } fun IrFunction.getObjCFactoryInitMethodInfo(): ObjCMethodInfo? { val factoryAnnotation = this.annotations.findAnnotation(objCFactoryFqName) ?: return null return objCMethodInfo(factoryAnnotation) } fun inferObjCSelector(descriptor: FunctionDescriptor): String = if (descriptor.valueParameters.isEmpty()) { descriptor.name.asString() } else { buildString { append(descriptor.name) append(':') descriptor.valueParameters.drop(1).forEach { append(it.name) append(':') } } } fun ClassDescriptor.getExternalObjCClassBinaryName(): String = this.getExplicitExternalObjCClassBinaryName() ?: this.name.asString() fun ClassDescriptor.getExternalObjCMetaClassBinaryName(): String = this.getExplicitExternalObjCClassBinaryName() ?: this.name.asString().removeSuffix("Meta") private fun ClassDescriptor.getExplicitExternalObjCClassBinaryName() = this.annotations.findAnnotation(externalObjCClassFqName)!!.getStringValueOrNull("binaryName")
apache-2.0
a9baa1061e825a5bab62949277aa84c7
44.683582
129
0.747566
5.035538
false
false
false
false
jwren/intellij-community
platform/diagnostic/src/startUpPerformanceReporter/StartUpPerformanceReporter.kt
3
9992
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceGetOrSet") package com.intellij.diagnostic.startUpPerformanceReporter import com.fasterxml.jackson.core.JsonGenerator import com.intellij.diagnostic.ActivityCategory import com.intellij.diagnostic.ActivityImpl import com.intellij.diagnostic.StartUpMeasurer import com.intellij.diagnostic.StartUpMeasurer.Activities import com.intellij.diagnostic.StartUpPerformanceService import com.intellij.ide.plugins.IdeaPluginDescriptorImpl import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.cl.PluginAwareClassLoader import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.util.io.FileUtil import com.intellij.util.SystemProperties import com.intellij.util.io.jackson.IntelliJPrettyPrinter import com.intellij.util.io.write import com.intellij.util.lang.ClassPath import it.unimi.dsi.fastutil.objects.Object2IntMap import it.unimi.dsi.fastutil.objects.Object2LongMap import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap import java.io.File import java.nio.ByteBuffer import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.ForkJoinPool import java.util.function.Consumer class StartUpPerformanceReporter : StartupActivity, StartUpPerformanceService { init { val app = ApplicationManager.getApplication() if (app.isUnitTestMode || app.isHeadlessEnvironment) { throw ExtensionNotApplicableException.create() } } private var pluginCostMap: Map<String, Object2LongMap<String>>? = null private var lastReport: ByteBuffer? = null private var lastMetrics: Object2IntMap<String>? = null companion object { internal val LOG = logger<StartUpMeasurer>() internal const val VERSION = "36" internal fun sortItems(items: MutableList<ActivityImpl>) { items.sortWith(Comparator { o1, o2 -> if (o1 == o2.parent) { return@Comparator -1 } else if (o2 == o1.parent) { return@Comparator 1 } compareTime(o1, o2) }) } fun logStats(projectName: String) { doLogStats(projectName) } } override fun getMetrics() = lastMetrics override fun getPluginCostMap() = pluginCostMap!! override fun getLastReport() = lastReport override fun runActivity(project: Project) { if (ActivityImpl.listener != null) { return } val projectName = project.name ActivityImpl.listener = ActivityListener(projectName) } private inner class ActivityListener(private val projectName: String) : Consumer<ActivityImpl> { @Volatile private var projectOpenedActivitiesPassed = false // not all activities are performed always, so, we wait only activities that were started @Volatile private var editorRestoringTillPaint = true override fun accept(activity: ActivityImpl) { if (activity.category != null && activity.category != ActivityCategory.DEFAULT) { return } if (activity.end == 0L) { if (activity.name == Activities.EDITOR_RESTORING_TILL_PAINT) { editorRestoringTillPaint = false } } else { when (activity.name) { Activities.PROJECT_DUMB_POST_START_UP_ACTIVITIES -> { projectOpenedActivitiesPassed = true if (editorRestoringTillPaint) { completed() } } Activities.EDITOR_RESTORING_TILL_PAINT -> { editorRestoringTillPaint = true if (projectOpenedActivitiesPassed) { completed() } } } } } private fun completed() { ActivityImpl.listener = null StartUpMeasurer.stopPluginCostMeasurement() // don't report statistic from here if we want to measure project import duration if (!java.lang.Boolean.getBoolean("idea.collect.project.import.performance")) { keepAndLogStats(projectName) } } } override fun reportStatistics(project: Project) { ForkJoinPool.commonPool().execute { keepAndLogStats(project.name) } } @Synchronized private fun keepAndLogStats(projectName: String) { val params = doLogStats(projectName) pluginCostMap = params.pluginCostMap lastReport = params.lastReport lastMetrics = params.lastMetrics } } private fun doLogStats(projectName: String): StartUpPerformanceReporterValues { val instantEvents = mutableListOf<ActivityImpl>() // write activity category in the same order as first reported val activities = LinkedHashMap<String, MutableList<ActivityImpl>>() val serviceActivities = HashMap<String, MutableList<ActivityImpl>>() val services = mutableListOf<ActivityImpl>() val threadNameManager = IdeThreadNameManager() var end = -1L StartUpMeasurer.processAndClear(SystemProperties.getBooleanProperty("idea.collect.perf.after.first.project", false)) { item -> // process it now to ensure that thread will have a first name (because report writer can process events in any order) threadNameManager.getThreadName(item) if (item.end == -1L) { instantEvents.add(item) } else { when (val category = item.category ?: ActivityCategory.DEFAULT) { ActivityCategory.DEFAULT -> { if (item.name == Activities.PROJECT_DUMB_POST_START_UP_ACTIVITIES) { end = item.end } activities.computeIfAbsent(category.jsonName) { mutableListOf() }.add(item) } ActivityCategory.APP_COMPONENT, ActivityCategory.PROJECT_COMPONENT, ActivityCategory.MODULE_COMPONENT, ActivityCategory.APP_SERVICE, ActivityCategory.PROJECT_SERVICE, ActivityCategory.MODULE_SERVICE, ActivityCategory.SERVICE_WAITING -> { services.add(item) serviceActivities.computeIfAbsent(category.jsonName) { mutableListOf() }.add(item) } else -> { activities.computeIfAbsent(category.jsonName) { mutableListOf() }.add(item) } } } } val pluginCostMap = computePluginCostMap() val w = IdeIdeaFormatWriter(activities, pluginCostMap, threadNameManager) val defaultActivities = activities.get(ActivityCategory.DEFAULT.jsonName) val startTime = defaultActivities?.first()?.start ?: 0 if (defaultActivities != null) { for (item in defaultActivities) { val pluginId = item.pluginId ?: continue StartUpMeasurer.doAddPluginCost(pluginId, item.category?.name ?: "unknown", item.end - item.start, pluginCostMap) } } w.write(startTime, serviceActivities, instantEvents, end, projectName) val currentReport = w.toByteBuffer() if (System.getProperty("idea.log.perf.stats", "false").toBoolean()) { w.writeToLog(StartUpPerformanceReporter.LOG) } val perfFilePath = System.getProperty("idea.log.perf.stats.file") if (!perfFilePath.isNullOrBlank()) { StartUpPerformanceReporter.LOG.info("StartUp Measurement report was written to: $perfFilePath") Path.of(perfFilePath).write(currentReport) currentReport.flip() } val classReport = System.getProperty("idea.log.class.list.file") if (!classReport.isNullOrBlank()) { generateJarAccessLog(Path.of(FileUtil.expandUserHome(classReport))) } return StartUpPerformanceReporterValues(pluginCostMap, currentReport, w.publicStatMetrics) } private class StartUpPerformanceReporterValues(val pluginCostMap: MutableMap<String, Object2LongOpenHashMap<String>>, val lastReport: ByteBuffer, val lastMetrics: Object2IntMap<String>) private fun computePluginCostMap(): MutableMap<String, Object2LongOpenHashMap<String>> { val result = HashMap(StartUpMeasurer.pluginCostMap) StartUpMeasurer.pluginCostMap.clear() for (plugin in PluginManagerCore.getLoadedPlugins()) { val id = plugin.pluginId.idString val classLoader = (plugin as IdeaPluginDescriptorImpl).pluginClassLoader as? PluginAwareClassLoader ?: continue val costPerPhaseMap = result.computeIfAbsent(id) { val m = Object2LongOpenHashMap<String>() m.defaultReturnValue(-1) m } costPerPhaseMap.put("classloading (EDT)", classLoader.edtTime) costPerPhaseMap.put("classloading (background)", classLoader.backgroundTime) } return result } // to make output more compact (quite a lot of slow components) internal class MyJsonPrettyPrinter : IntelliJPrettyPrinter() { private var objectLevel = 0 override fun writeStartObject(g: JsonGenerator) { objectLevel++ if (objectLevel > 1) { _objectIndenter = FixedSpaceIndenter.instance } super.writeStartObject(g) } override fun writeEndObject(g: JsonGenerator, nrOfEntries: Int) { super.writeEndObject(g, nrOfEntries) objectLevel-- if (objectLevel <= 1) { _objectIndenter = UNIX_LINE_FEED_INSTANCE } } } internal fun compareTime(o1: ActivityImpl, o2: ActivityImpl): Int { return when { o1.start > o2.start -> 1 o1.start < o2.start -> -1 else -> { when { o1.end > o2.end -> -1 o1.end < o2.end -> 1 else -> 0 } } } } private fun generateJarAccessLog(outFile: Path) { val homeDir = Path.of(PathManager.getHomePath()) val builder = StringBuilder() for (item in ClassPath.getLoadedClasses()) { val source = item.value if (!source.startsWith(homeDir)) { continue } builder.append(item.key).append(':').append(homeDir.relativize(source).toString().replace(File.separatorChar, '/')) builder.append('\n') } Files.createDirectories(outFile.parent) Files.writeString(outFile, builder) }
apache-2.0
eb1fe9ea3e353491ae2d86490c1faf40
33.102389
128
0.71217
4.452763
false
false
false
false
jwren/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/DependenciesProperties.kt
1
1069
// 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.intellij.build.impl import org.jetbrains.intellij.build.CompilationContext import java.nio.file.Path import java.util.* import kotlin.io.path.inputStream class DependenciesProperties(private val context: CompilationContext) { private val directory = context.paths.communityHomeDir.resolve("build/dependencies") private val propertiesFile = directory.resolve("gradle.properties") val file: Path = propertiesFile val props: Properties by lazy { propertiesFile.inputStream().use { val properties = Properties() properties.load(it) properties } } fun property(name: String): String = props.getProperty(name) ?: error("`$name` is not defined in `$propertiesFile`") fun propertyOrNull(name: String): String? { val value = props.getProperty(name) if (value == null) { context.messages.warning("`$name` is not defined in `$propertiesFile`") } return value } }
apache-2.0
b00c633c8aad86b5a44cf049f2cccba0
31.393939
120
0.727783
4.310484
false
false
false
false
vovagrechka/fucking-everything
alraune/alraune/src/main/java/bolone/fa/FuckAround_UserSearch.kt
1
1205
package bolone.fa import alraune.* import alraune.entity.* import vgrechka.* object FuckAround_UserSearch { @JvmStatic fun main(args: Array<String>) { val pageSize = AlConst.pageSize val q = "" val ordering = Ordering.NewerFirst FAPile.usingConnection { val m = User.Meta val boobs = PaginationBoobs(UsualPaginationPussy( itemClass = User::class, table = m.table, pageSize = pageSize, shitIntoWhere = { it.text("and (") it.text(" ${m.email} ilike", "$q%") it.text(" or ${m.firstNameForSearch} ilike", "$q%") it.text(" or ${m.lastNameForSearch} ilike", "$q%") it.text(")") it.text("and ${m.kind} =", AlUserKind.Writer) it.text("and ${m.profileState} =", User.ProfileState.Approved) }, shitOrderBy = {it.text("order by ${m.lastNameForSearch} asc, ${m.firstNameForSearch} asc")} )) boobs.fart(_page = 1) boobs.items.forEach {clog(it.fullNameOrEmail())} } clog("OK") } }
apache-2.0
d59a21948a5b05641bde7765eaf42ff5
34.470588
107
0.506224
4.126712
false
false
false
false
LouisCAD/Splitties
modules/views-dsl-constraintlayout/src/androidMain/kotlin/splitties/views/dsl/constraintlayout/Chains.kt
1
4660
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.views.dsl.constraintlayout import android.view.View import android.view.ViewGroup import androidx.annotation.Px import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.view.updateLayoutParams import splitties.collections.forEachWithIndex import splitties.views.dsl.core.add import splitties.views.dsl.core.endMargin import splitties.views.dsl.core.startMargin import androidx.constraintlayout.widget.ConstraintLayout.LayoutParams as LP @Suppress("unused") inline val ConstraintLayout.packed get() = LP.CHAIN_PACKED @Suppress("unused") inline val ConstraintLayout.spread get() = LP.CHAIN_SPREAD @Suppress("unused") inline val ConstraintLayout.spreadInside get() = LP.CHAIN_SPREAD_INSIDE inline fun ConstraintLayout.horizontalChain( views: List<View>, style: Int = spread, defaultWidth: Int = matchConstraints, defaultHeight: Int = matchConstraints, initFirstViewParams: ConstraintLayout.LayoutParams.() -> Unit = { startOfParent() }, initLastViewParams: ConstraintLayout.LayoutParams.() -> Unit = { endOfParent() }, alignVerticallyOnFirstView: Boolean = false, initParams: ConstraintLayout.LayoutParams.(View) -> Unit = {} ) { lateinit var previousView: View val lastIndex = views.lastIndex views.forEachWithIndex { index, view -> val existingLParams = view.layoutParams as? ConstraintLayout.LayoutParams val layoutParams = existingLParams?.apply { width = defaultWidth height = defaultHeight } ?: lParams(defaultWidth, defaultHeight) layoutParams.apply { initParams(view) if (index == 0) { initFirstViewParams() horizontalChainStyle = style } else { startToEndOf(previousView) if (alignVerticallyOnFirstView) alignVerticallyOn(previousView) } if (index == lastIndex) initLastViewParams() else { val nextView = views[index + 1] endToStartOf(nextView) } } if (existingLParams == null) add(view, layoutParams) else view.layoutParams = existingLParams // Refresh to take changes into account previousView = view } } inline fun ConstraintLayout.verticalChain( views: List<View>, style: Int = spread, defaultWidth: Int = matchConstraints, defaultHeight: Int = matchConstraints, initFirstViewParams: ConstraintLayout.LayoutParams.() -> Unit = { topOfParent() }, initLastViewParams: ConstraintLayout.LayoutParams.() -> Unit = { bottomOfParent() }, alignHorizontallyOnFirstView: Boolean = false, initParams: ConstraintLayout.LayoutParams.(View) -> Unit = {} ) { lateinit var previousView: View val lastIndex = views.lastIndex views.forEachWithIndex { index, view -> val existingLParams = view.layoutParams as? ConstraintLayout.LayoutParams val layoutParams = existingLParams?.apply { width = defaultWidth height = defaultHeight } ?: lParams(defaultWidth, defaultHeight) layoutParams.apply { initParams(view) if (index == 0) { initFirstViewParams() verticalChainStyle = style } else { topToBottomOf(previousView) if (alignHorizontallyOnFirstView) alignHorizontallyOn(previousView) } if (index == lastIndex) initLastViewParams() else { val nextView = views[index + 1] bottomToTopOf(nextView) } } if (existingLParams == null) add(view, layoutParams) else view.layoutParams = layoutParams // Refresh to take changes into account previousView = view } } var List<View>.horizontalMargin: Int @Deprecated(NO_GETTER, level = DeprecationLevel.HIDDEN) get() = noGetter set(@Px value) { first().updateLayoutParams<ViewGroup.MarginLayoutParams> { startMargin = value } last().updateLayoutParams<ViewGroup.MarginLayoutParams> { endMargin = value } } var List<View>.verticalMargin: Int @Deprecated(NO_GETTER, level = DeprecationLevel.HIDDEN) get() = noGetter set(@Px value) { first().updateLayoutParams<ViewGroup.MarginLayoutParams> { topMargin = value } last().updateLayoutParams<ViewGroup.MarginLayoutParams> { bottomMargin = value } }
apache-2.0
ce3b758ef5edc1edc809cdba7a05b89c
35.692913
109
0.658584
4.859228
false
false
false
false
smmribeiro/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/settings/MarkdownSettings.kt
1
5640
// 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.intellij.plugins.markdown.settings import com.intellij.openapi.components.SimplePersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.colors.impl.AppEditorFontOptions import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.ui.jcef.JBCefApp import com.intellij.util.messages.Topic import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanelProvider import org.intellij.plugins.markdown.ui.preview.jcef.JCEFHtmlPanelProvider @State(name = "MarkdownSettings", storages = [(Storage("markdown.xml"))]) class MarkdownSettings(val project: Project): SimplePersistentStateComponent<MarkdownSettingsState>(MarkdownSettingsState()) { var areInjectionsEnabled get() = state.areInjectionsEnabled set(value) { state.areInjectionsEnabled = value } var hideErrorsInCodeBlocks get() = state.hideErrorsInCodeBlocks set(value) { state.hideErrorsInCodeBlocks = value } var isEnhancedEditingEnabled get() = state.isEnhancedEditingEnabled set(value) { state.isEnhancedEditingEnabled = value } var splitLayout get() = state.splitLayout set(value) { state.splitLayout = value } var previewPanelProviderInfo get() = state.previewPanelProviderInfo set(value) { state.previewPanelProviderInfo = value } var isVerticalSplit get() = state.isVerticalSplit set(value) { state.isVerticalSplit = value } var isAutoScrollEnabled get() = state.isAutoScrollEnabled set(value) { state.isAutoScrollEnabled = value } var isRunnerEnabled get() = state.isRunnerEnabled set(value) { state.isRunnerEnabled = value } var useCustomStylesheetPath get() = state.useCustomStylesheetPath set(value) { state.useCustomStylesheetPath = value } var customStylesheetPath get() = state.customStylesheetPath set(value) { state.customStylesheetPath = value } var useCustomStylesheetText get() = state.useCustomStylesheetText set(value) { state.useCustomStylesheetText = value } var customStylesheetText get() = state.customStylesheetText set(value) { state.customStylesheetText = value } var fontSize get() = state.fontSize set(value) { state.fontSize = value } var fontFamily get() = state.fontFamily set(value) { state.fontFamily = value } override fun loadState(state: MarkdownSettingsState) { val migrated = possiblyMigrateSettings(state) super.loadState(migrated) } override fun noStateLoaded() { super.noStateLoaded() loadState(MarkdownSettingsState()) } @Synchronized fun update(block: (MarkdownSettings) -> Unit) { val publisher = project.messageBus.syncPublisher(ChangeListener.TOPIC) publisher.beforeSettingsChanged(this) block(this) publisher.settingsChanged(this) } private fun possiblyMigrateSettings(from: MarkdownSettingsState): MarkdownSettingsState { @Suppress("DEPRECATION") val old = MarkdownApplicationSettings.getInstance().takeIf { it.state != null } val migration = MarkdownSettingsMigration.getInstance(project) if (old == null || migration.state.stateVersion == 1) { return from } logger.info("Migrating Markdown settings") val migrated = MarkdownSettingsState() with(migrated) { old.markdownPreviewSettings.let { previewPanelProviderInfo = it.htmlPanelProviderInfo splitLayout = it.splitEditorLayout isAutoScrollEnabled = it.isAutoScrollPreview isVerticalSplit = it.isVerticalSplit } old.markdownCssSettings.let { customStylesheetPath = it.customStylesheetPath.takeIf { _ -> it.isCustomStylesheetEnabled } customStylesheetText = it.customStylesheetText.takeIf { _ -> it.isTextEnabled } fontFamily = it.fontFamily fontSize = it.fontSize } enabledExtensions = old.extensionsEnabledState areInjectionsEnabled = !old.isDisableInjections hideErrorsInCodeBlocks = old.isHideErrors isEnhancedEditingEnabled = old.isEnhancedEditingEnabled resetModificationCount() } migration.state.stateVersion = 1 return migrated } interface ChangeListener { fun beforeSettingsChanged(settings: MarkdownSettings) = Unit fun settingsChanged(settings: MarkdownSettings) = Unit companion object { @Topic.ProjectLevel @JvmField val TOPIC = Topic.create("MarkdownSettingsChanged", ChangeListener::class.java) } } companion object { private val logger = logger<MarkdownSettings>() @JvmStatic val defaultFontSize get() = JBCefApp.normalizeScaledSize(checkNotNull(AppEditorFontOptions.getInstance().state).FONT_SIZE) @JvmStatic val defaultFontFamily get() = checkNotNull(AppEditorFontOptions.getInstance().state).FONT_FAMILY @JvmStatic val defaultProviderInfo get() = when { JBCefApp.isSupported() -> JCEFHtmlPanelProvider().providerInfo else -> MarkdownHtmlPanelProvider.ProviderInfo("Unavailable", "Unavailable") } @JvmStatic fun getInstance(project: Project): MarkdownSettings { return project.service() } @JvmStatic fun getInstanceForDefaultProject(): MarkdownSettings { return ProjectManager.getInstance().defaultProject.service() } } }
apache-2.0
a1384d2df99c0c80b297399028b63524
33.181818
158
0.742199
4.711779
false
false
false
false
android/sunflower
app/src/main/java/com/google/samples/apps/sunflower/compose/plantlist/PlantListItemView.kt
1
3147
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.sunflower.compose.plantlist import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi import com.bumptech.glide.integration.compose.GlideImage import com.google.samples.apps.sunflower.R import com.google.samples.apps.sunflower.data.Plant @OptIn(ExperimentalMaterialApi::class, ExperimentalGlideComposeApi::class) @Composable fun PlantListItemView(plant: Plant, onClick: () -> Unit) { Card( onClick = onClick, elevation = dimensionResource(id = R.dimen.card_elevation), shape = RoundedCornerShape( topStart = 0.dp, topEnd = dimensionResource(id = R.dimen.card_corner_radius), bottomStart = dimensionResource(id = R.dimen.card_corner_radius), bottomEnd = 0.dp ), modifier = Modifier .padding(horizontal = dimensionResource(id = R.dimen.card_side_margin)) .padding(bottom = dimensionResource(id = R.dimen.card_bottom_margin)) ) { Column(Modifier.fillMaxWidth()) { GlideImage( model = plant.imageUrl, contentDescription = stringResource(R.string.a11y_plant_item_image), Modifier .fillMaxWidth() .height(dimensionResource(id = R.dimen.plant_item_image_height)), contentScale = ContentScale.Crop ) Text( text = plant.name, textAlign = TextAlign.Center, modifier = Modifier .fillMaxWidth() .padding(vertical = dimensionResource(id = R.dimen.margin_normal)) .wrapContentWidth(Alignment.CenterHorizontally) ) } } }
apache-2.0
8e4c44300736e5a0abc5a20f0ef615d3
40.421053
86
0.703209
4.594161
false
false
false
false
shofujimoto/examples
until_201803/kotlin/todo-spark/src/main/java/todolist/TaskController.kt
1
1484
package todolist import com.fasterxml.jackson.databind.ObjectMapper import spark.Route import spark.Spark.halt import spark.Request class TaskController(private val objectMapper: ObjectMapper, private val taskRepository: TaskRepository) { fun index(): Route = Route {req, res -> taskRepository.findAll() } fun create(): Route = Route {req, res -> val request: TaskCreateRequest = objectMapper.readValue(req.bodyAsBytes()) ?: throw halt(400) val task = taskRepository.create(request.content) res.status(201) task } fun show(): Route = Route { req, res -> req.task ?: throw halt(404) } fun destroy(): Route = Route {req,res -> val task = req.task ?: throw halt(404) taskRepository.delete(task) res.status(204) } private val Request.task: Task? get() { val id = params("id").toLongOrNull() return id?.let(taskRepository::findById) } fun update(): Route = Route{ req, res -> val request: TaskUpdateRequest = objectMapper.readValue(req.bodyAsBytes()) ?: throw halt(400) print("update request is received.") val task = req.task ?: throw halt(404) val newTask = task.copy( content = request.content ?: task.content, done = request.done ?: task.done ) taskRepository.update(newTask) res.status(204) } }
mit
32e54ccecc156278a3feb1f4ddd80159
28.117647
101
0.597709
4.429851
false
false
false
false
joaomneto/TitanCompanion
src/main/java/pt/joaomneto/titancompanion/adventure/impl/STRIDERAdventure.kt
1
2866
package pt.joaomneto.titancompanion.adventure.impl import android.view.Menu import java.io.BufferedWriter import java.io.IOException import pt.joaomneto.titancompanion.R import pt.joaomneto.titancompanion.adventure.Adventure import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureCombatFragment import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureNotesFragment import pt.joaomneto.titancompanion.adventure.impl.fragments.strider.STRIDERAdventureEquipmentFragment import pt.joaomneto.titancompanion.adventure.impl.fragments.strider.STRIDERAdventureTimeOxygenFragment import pt.joaomneto.titancompanion.adventure.impl.fragments.strider.STRIDERAdventureVitalStatsFragment import pt.joaomneto.titancompanion.util.AdventureFragmentRunner import pt.joaomneto.titancompanion.util.DiceRoller import kotlin.math.max import kotlin.math.min class STRIDERAdventure : Adventure( arrayOf( AdventureFragmentRunner( R.string.vitalStats, STRIDERAdventureVitalStatsFragment::class ), AdventureFragmentRunner( R.string.timeAndOxygen, STRIDERAdventureTimeOxygenFragment::class ), AdventureFragmentRunner( R.string.fights, AdventureCombatFragment::class ), AdventureFragmentRunner( R.string.equipment2, STRIDERAdventureEquipmentFragment::class ), AdventureFragmentRunner( R.string.notes, AdventureNotesFragment::class ) ) ) { var currentFear: Int = -1 var time: Int = -1 var oxygen: Int = -1 override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.adventure, menu) return true } @Throws(IOException::class) override fun storeAdventureSpecificValuesInFile(bw: BufferedWriter) { bw.write("fear=$currentFear\n") bw.write("time=$time\n") bw.write("oxygen=$oxygen\n") } override fun loadAdventureSpecificValuesFromFile() { currentFear = Integer.valueOf(savedGame.getProperty("fear")) time = Integer.valueOf(savedGame.getProperty("time")) oxygen = Integer.valueOf(savedGame.getProperty("oxygen")) } fun testFear() { val result = DiceRoller.roll2D6().sum <= currentFear val message = if (result) R.string.success else R.string.failed Adventure.showAlert(message, this) (getFragment<STRIDERAdventureVitalStatsFragment>())?.refreshScreensFromResume() } fun increaseTime() { this.time = min(time + 1, 48) } fun decreaseTime() { this.time = max(time - 1, 0) } fun increaseOxygen() { this.oxygen = min(oxygen + 1, 20) } fun decreaseOxygen() { this.oxygen = max(oxygen - 1, 0) } companion object { } }
lgpl-3.0
a836865ded13be52a650a606bbce5930
29.817204
102
0.692603
4.368902
false
false
false
false
ThiagoGarciaAlves/intellij-community
platform/platform-api/src/com/intellij/ide/browsers/BrowserLauncherAppless.kt
6
9786
/* * 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.ide.browsers import com.intellij.CommonBundle import com.intellij.Patches import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil import com.intellij.ide.BrowserUtil import com.intellij.ide.GeneralSettings import com.intellij.ide.IdeBundle import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VfsUtil import com.intellij.util.ArrayUtil import com.intellij.util.PathUtil import com.intellij.util.io.URLUtil import org.jetbrains.annotations.Contract import java.awt.Desktop import java.io.File import java.io.IOException import java.util.* open class BrowserLauncherAppless : BrowserLauncher() { companion object { internal val LOG = Logger.getInstance(BrowserLauncherAppless::class.java) private fun isDesktopActionSupported(action: Desktop.Action): Boolean { return !Patches.SUN_BUG_ID_6486393 && Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(action) } @JvmStatic fun canUseSystemDefaultBrowserPolicy(): Boolean { return isDesktopActionSupported(Desktop.Action.BROWSE) || SystemInfo.isMac || SystemInfo.isWindows || SystemInfo.isUnix && SystemInfo.hasXdgOpen() } private val generalSettings: GeneralSettings get() { if (ApplicationManager.getApplication() != null) { GeneralSettings.getInstance()?.let { return it } } return GeneralSettings() } private val defaultBrowserCommand: List<String>? get() { if (SystemInfo.isWindows) { return listOf(ExecUtil.getWindowsShellName(), "/c", "start", GeneralCommandLine.inescapableQuote("")) } else if (SystemInfo.isMac) { return listOf(ExecUtil.getOpenCommandPath()) } else if (SystemInfo.isUnix && SystemInfo.hasXdgOpen()) { return listOf("xdg-open") } else { return null } } private fun addArgs(command: GeneralCommandLine, settings: BrowserSpecificSettings?, additional: Array<String>) { val specific = settings?.additionalParameters ?: emptyList<String>() if (specific.size + additional.size > 0) { if (isOpenCommandUsed(command)) { if (BrowserUtil.isOpenCommandSupportArgs()) { command.addParameter("--args") } else { LOG.warn("'open' command doesn't allow to pass command line arguments so they will be ignored: " + StringUtil.join(specific, ", ") + " " + Arrays.toString(additional)) return } } command.addParameters(specific) command.addParameters(*additional) } } fun isOpenCommandUsed(command: GeneralCommandLine) = SystemInfo.isMac && ExecUtil.getOpenCommandPath() == command.exePath } override fun open(url: String) = openOrBrowse(url, false) override fun browse(file: File) { var path = file.absolutePath if (SystemInfo.isWindows && path[0] != '/') { path = '/' + path } openOrBrowse("${StandardFileSystems.FILE_PROTOCOL_PREFIX}$path", true) } protected open fun browseUsingNotSystemDefaultBrowserPolicy(url: String, settings: GeneralSettings, project: Project?) { browseUsingPath(url, settings.browserPath, project = project) } private fun openOrBrowse(_url: String, browse: Boolean, project: Project? = null) { val url = signUrl(_url.trim { it <= ' ' }) if (!BrowserUtil.isAbsoluteURL(url)) { val file = File(url) if (!browse && isDesktopActionSupported(Desktop.Action.OPEN)) { if (!file.exists()) { showError(IdeBundle.message("error.file.does.not.exist", file.path), null, null, null, null) return } try { Desktop.getDesktop().open(file) return } catch (e: IOException) { LOG.debug(e) } } browse(file) return } LOG.debug("Launch browser: [$url]") val settings = generalSettings if (settings.isUseDefaultBrowser) { val uri = VfsUtil.toUri(url) if (uri == null) { showError(IdeBundle.message("error.malformed.url", url), project = project) return } var tryToUseCli = true if (isDesktopActionSupported(Desktop.Action.BROWSE)) { try { Desktop.getDesktop().browse(uri) LOG.debug("Browser launched using JDK 1.6 API") return } catch (e: Exception) { LOG.warn("Error while using Desktop API, fallback to CLI", e) // if "No application knows how to open", then we must not try to use OS open tryToUseCli = !e.message!!.contains("Error code: -10814") } } if (tryToUseCli) { defaultBrowserCommand?.let { doLaunch(url, it, null, project) return } } } browseUsingNotSystemDefaultBrowserPolicy(url, settings, project = project) } open protected fun signUrl(url: String): String = url override final fun browse(url: String, browser: WebBrowser?, project: Project?) { val effectiveBrowser = getEffectiveBrowser(browser) // if browser is not passed, UrlOpener should be not used for non-http(s) urls if (effectiveBrowser == null || (browser == null && !url.startsWith(URLUtil.HTTP_PROTOCOL))) { openOrBrowse(url, true, project) } else { UrlOpener.EP_NAME.extensions.any { it.openUrl(effectiveBrowser, signUrl(url), project) } } } override fun browseUsingPath(url: String?, browserPath: String?, browser: WebBrowser?, project: Project?, openInNewWindow: Boolean, additionalParameters: Array<String>): Boolean { var browserPathEffective = browserPath var launchTask: (() -> Unit)? = null if (browserPath == null && browser != null) { browserPathEffective = PathUtil.toSystemDependentName(browser.path) launchTask = { browseUsingPath(url, null, browser, project, openInNewWindow, additionalParameters) } } return doLaunch(url, browserPathEffective, browser, project, openInNewWindow, additionalParameters, launchTask) } private fun doLaunch(url: String?, browserPath: String?, browser: WebBrowser?, project: Project?, openInNewWindow: Boolean, additionalParameters: Array<String>, launchTask: (() -> Unit)?): Boolean { if (!checkPath(browserPath, browser, project, launchTask)) { return false } return doLaunch(url, BrowserUtil.getOpenBrowserCommand(browserPath!!, openInNewWindow), browser, project, additionalParameters, launchTask) } @Contract("null, _, _, _ -> false") fun checkPath(browserPath: String?, browser: WebBrowser?, project: Project?, launchTask: (() -> Unit)?): Boolean { if (!browserPath.isNullOrBlank()) { return true } val message = browser?.browserNotFoundMessage ?: IdeBundle.message("error.please.specify.path.to.web.browser", CommonBundle.settingsActionPath()) showError(message, browser, project, IdeBundle.message("title.browser.not.found"), launchTask) return false } private fun doLaunch(url: String?, command: List<String>, browser: WebBrowser?, project: Project?, additionalParameters: Array<String> = ArrayUtil.EMPTY_STRING_ARRAY, launchTask: (() -> Unit)? = null): Boolean { val commandLine = GeneralCommandLine(command) if (url != null) { if (url.startsWith("jar:")) { return false } commandLine.addParameter(url) } val browserSpecificSettings = browser?.specificSettings if (browserSpecificSettings != null) { commandLine.environment.putAll(browserSpecificSettings.environmentVariables) } addArgs(commandLine, browserSpecificSettings, additionalParameters) try { checkCreatedProcess(browser, project, commandLine, commandLine.createProcess(), launchTask) return true } catch (e: ExecutionException) { showError(e.message, browser, project, null, null) return false } } protected open fun checkCreatedProcess(browser: WebBrowser?, project: Project?, commandLine: GeneralCommandLine, process: Process, launchTask: (() -> Unit)?) { } protected open fun showError(error: String?, browser: WebBrowser? = null, project: Project? = null, title: String? = null, launchTask: (() -> Unit)? = null) { // Not started yet. Not able to show message up. (Could happen in License panel under Linux). LOG.warn(error) } open protected fun getEffectiveBrowser(browser: WebBrowser?): WebBrowser? = browser }
apache-2.0
605fa5a02e5270ede0f90332feeb2e49
35.518657
213
0.659105
4.682297
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/fragments/keysbackup/setup/KeysBackupSetupStep1Fragment.kt
2
2597
/* * Copyright 2019 New Vector Ltd * * 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 im.vector.fragments.keysbackup.setup import android.os.Bundle import android.view.View import android.widget.Button import android.widget.TextView import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import butterknife.BindView import butterknife.OnClick import im.vector.R import im.vector.fragments.VectorBaseFragment import im.vector.ui.arch.LiveEvent class KeysBackupSetupStep1Fragment : VectorBaseFragment() { companion object { fun newInstance() = KeysBackupSetupStep1Fragment() } override fun getLayoutResId() = R.layout.fragment_keys_backup_setup_step1 private lateinit var viewModel: KeysBackupSetupSharedViewModel @BindView(R.id.keys_backup_setup_step1_advanced) lateinit var advancedOptionText: TextView @BindView(R.id.keys_backup_setup_step1_manualExport) lateinit var manualExportButton: Button override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = activity?.run { ViewModelProviders.of(this).get(KeysBackupSetupSharedViewModel::class.java) } ?: throw Exception("Invalid Activity") viewModel.showManualExport.observe(this, Observer { val showOption = it ?: false //Can't use isVisible because the kotlin compiler will crash with Back-end (JVM) Internal error: wrong code generated advancedOptionText.visibility = if (showOption) View.VISIBLE else View.GONE manualExportButton.visibility = if (showOption) View.VISIBLE else View.GONE }) } @OnClick(R.id.keys_backup_setup_step1_button) fun onButtonClick() { viewModel.navigateEvent.value = LiveEvent(KeysBackupSetupSharedViewModel.NAVIGATE_TO_STEP_2) } @OnClick(R.id.keys_backup_setup_step1_manualExport) fun onManualExportClick() { viewModel.navigateEvent.value = LiveEvent(KeysBackupSetupSharedViewModel.NAVIGATE_MANUAL_EXPORT) } }
apache-2.0
5cdf4ec2d2d4d46eb08a45030f4fb4ec
34.094595
130
0.74432
4.379427
false
false
false
false
slisson/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/DefaultWebServerRootsProvider.kt
3
11427
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.builtInWebServer import com.intellij.openapi.application.ReadAction import com.intellij.openapi.application.runReadAction import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.JavadocOrderRootType import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.impl.DirectoryIndex import com.intellij.openapi.roots.impl.ModuleLibraryOrderEntryImpl import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.util.NotNullLazyValue import com.intellij.openapi.util.Ref import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.JarFileSystem import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PairFunction import com.intellij.util.PlatformUtils import com.intellij.util.Processor class DefaultWebServerRootsProvider : WebServerRootsProvider() { override fun resolve(path: String, project: Project): PathInfo? { var effectivePath = path val resolver: PairFunction<String, VirtualFile, VirtualFile> if (PlatformUtils.isIntelliJ()) { val index = effectivePath.indexOf('/') if (index > 0 && !effectivePath.regionMatches(0, project.getName(), 0, index, !SystemInfo.isFileSystemCaseSensitive)) { val moduleName = effectivePath.substring(0, index) val token = ReadAction.start() val module: Module? try { module = ModuleManager.getInstance(project).findModuleByName(moduleName) } finally { token.finish() } if (module != null && !module.isDisposed()) { effectivePath = effectivePath.substring(index + 1) resolver = WebServerPathToFileManager.getInstance(project).getResolver(effectivePath) val moduleRootManager = ModuleRootManager.getInstance(module) for (rootProvider in RootProvider.values()) { val result = findByRelativePath(effectivePath, rootProvider.getRoots(moduleRootManager), resolver, moduleName) if (result != null) { return result } } val result = findInModuleLibraries(effectivePath, module, resolver) if (result != null) { return result } } } } val modules = runReadAction { ModuleManager.getInstance(project).getModules() } resolver = WebServerPathToFileManager.getInstance(project).getResolver(effectivePath) for (rootProvider in RootProvider.values()) { val result = findByRelativePath(project, effectivePath, modules, rootProvider, resolver) if (result != null) { return result } } return findInLibraries(project, modules, effectivePath, resolver) } override fun getRoot(file: VirtualFile, project: Project): PathInfo? { runReadAction { val directoryIndex = DirectoryIndex.getInstance(project) val info = directoryIndex.getInfoForFile(file) // we serve excluded files if (!info.isExcluded() && !info.isInProject()) { // javadoc jars is "not under project", but actually is, so, let's check project library table return if (file.getFileSystem() === JarFileSystem.getInstance()) getInfoForDocJar(file, project) else null } var root = info.getSourceRoot() val isLibrary: Boolean if (root == null) { root = info.getContentRoot() if (root == null) { root = info.getLibraryClassRoot() isLibrary = true assert(root != null) { file.getPresentableUrl() } } else { isLibrary = false } } else { isLibrary = info.isInLibrarySource() } var module = info.getModule() if (isLibrary && module == null) { for (entry in directoryIndex.getOrderEntries(info)) { if (entry is ModuleLibraryOrderEntryImpl) { module = entry.getOwnerModule() break } } } return PathInfo(file, root!!, getModuleNameQualifier(project, module), isLibrary) } } private enum class RootProvider { SOURCE { override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> { return rootManager.getSourceRoots() } }, CONTENT { override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> { return rootManager.getContentRoots() } }, EXCLUDED { override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> { return rootManager.getExcludeRoots() } }; public abstract fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> } companion object { private val ORDER_ROOT_TYPES = object : NotNullLazyValue<Array<OrderRootType>>() { override fun compute(): Array<OrderRootType> { val javaDocRootType = getJavadocOrderRootType() return if (javaDocRootType == null) arrayOf(OrderRootType.DOCUMENTATION, OrderRootType.SOURCES, OrderRootType.CLASSES) else arrayOf(javaDocRootType, OrderRootType.DOCUMENTATION, OrderRootType.SOURCES, OrderRootType.CLASSES) } } private fun getJavadocOrderRootType(): OrderRootType? { try { return JavadocOrderRootType.getInstance() } catch (e: Throwable) { return null } } private fun findInModuleLibraries(path: String, module: Module, resolver: PairFunction<String, VirtualFile, VirtualFile>): PathInfo? { val index = path.indexOf('/') if (index <= 0) { return null } val result = Ref.create<PathInfo>() findInModuleLibraries(resolver, path.substring(0, index), path.substring(index + 1), result, module) return result.get() } private fun findInLibraries(project: Project, modules: Array<Module>, path: String, resolver: PairFunction<String, VirtualFile, VirtualFile>): PathInfo? { val index = path.indexOf('/') if (index < 0) { return null } val libraryFileName = path.substring(0, index) val relativePath = path.substring(index + 1) runReadAction { val result = Ref.create<PathInfo>() for (module in modules) { if (!module.isDisposed()) { if (findInModuleLibraries(resolver, libraryFileName, relativePath, result, module)) { return result.get() } } } for (library in LibraryTablesRegistrar.getInstance().getLibraryTable(project).getLibraries()) { val pathInfo = findInLibrary(libraryFileName, relativePath, library, resolver) if (pathInfo != null) { return pathInfo } } } return null } private fun findInModuleLibraries(resolver: PairFunction<String, VirtualFile, VirtualFile>, libraryFileName: String, relativePath: String, result: Ref<PathInfo>, module: Module): Boolean { ModuleRootManager.getInstance(module).orderEntries().forEachLibrary(object : Processor<Library> { override fun process(library: Library): Boolean { result.set(findInLibrary(libraryFileName, relativePath, library, resolver)) return result.isNull() } }) return !result.isNull() } private fun findInLibrary(libraryFileName: String, relativePath: String, library: Library, resolver: PairFunction<String, VirtualFile, VirtualFile>): PathInfo? { for (rootType in ORDER_ROOT_TYPES.getValue()) { for (root in library.getFiles(rootType)) { if (StringUtil.equalsIgnoreCase(root.getNameSequence(), libraryFileName)) { val file = resolver.`fun`(relativePath, root) if (file != null) { return PathInfo(file, root, null, true) } } } } return null } private fun getInfoForDocJar(file: VirtualFile, project: Project): PathInfo? { val javaDocRootType = getJavadocOrderRootType() ?: return null class LibraryProcessor : Processor<Library> { var result: PathInfo? = null var module: Module? = null override fun process(library: Library): Boolean { for (root in library.getFiles(javaDocRootType)) { if (VfsUtilCore.isAncestor(root, file, false)) { result = PathInfo(file, root, getModuleNameQualifier(project, module), true) return false } } return true } } val processor = LibraryProcessor() runReadAction { val moduleManager = ModuleManager.getInstance(project) for (module in moduleManager.getModules()) { if (module.isDisposed()) { continue } processor.module = module ModuleRootManager.getInstance(module).orderEntries().forEachLibrary(processor) if (processor.result != null) { return processor.result } } processor.module = null for (library in LibraryTablesRegistrar.getInstance().getLibraryTable(project).getLibraries()) { if (!processor.process(library)) { return processor.result } } } return null } private fun getModuleNameQualifier(project: Project, module: Module?): String? { if (module != null && PlatformUtils.isIntelliJ() && !(module.getName().equals(project.getName(), ignoreCase = true) || compareNameAndProjectBasePath(module.getName(), project))) { return module.getName() } return null } private fun findByRelativePath(path: String, roots: Array<VirtualFile>, resolver: PairFunction<String, VirtualFile, VirtualFile>, moduleName: String?): PathInfo? { for (root in roots) { val file = resolver.`fun`(path, root) if (file != null) { return PathInfo(file, root, moduleName, false) } } return null } private fun findByRelativePath(project: Project, path: String, modules: Array<Module>, rootProvider: RootProvider, resolver: PairFunction<String, VirtualFile, VirtualFile>): PathInfo? { for (module in modules) { if (!module.isDisposed()) { val moduleRootManager = ModuleRootManager.getInstance(module) val result = findByRelativePath(path, rootProvider.getRoots(moduleRootManager), resolver, null) if (result != null) { result.moduleName = getModuleNameQualifier(project, module) return result } } } return null } } }
apache-2.0
37b5a97c399fa6d0406f3f9ab3eb2c3f
35.864516
192
0.660191
4.979085
false
false
false
false
dscoppelletti/spaceship
lib/src/main/kotlin/it/scoppelletti/spaceship/widget/HorizontalDividerItemDecoration.kt
1
3982
/* * Copyright (C) 2019 Dario Scoppelletti, <http://www.scoppelletti.it/>. * * 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("JoinDeclarationAndAssignment", "RedundantVisibilityModifier", "unused") package it.scoppelletti.spaceship.widget import android.content.Context import android.content.res.TypedArray import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import android.view.View import androidx.recyclerview.widget.RecyclerView import it.scoppelletti.spaceship.R import kotlin.math.roundToInt /** * Inserts a divider between the items in a `LinearLayoutManager` list. It * supports only `VERTICAL` orientations. * * @since 1.0.0 * * @constructor Constructor. * @param ctx Context. * @param marginLeft Left margin for the divider (px). * @param marginRight Right margin for the divider (px). */ public class HorizontalDividerItemDecoration( ctx: Context, private val marginLeft: Int = 0, private val marginRight: Int = 0 ) : RecyclerView.ItemDecoration() { private val marginHorz: Int private val marginVert: Int private val divider: Drawable init { val attrs: TypedArray marginHorz = ctx.resources.getDimensionPixelOffset( R.dimen.it_scoppelletti_marginHorz) marginVert = ctx.resources.getDimensionPixelOffset( R.dimen.it_scoppelletti_spacingVert) attrs = ctx.obtainStyledAttributes(IntArray(1) { android.R.attr.listDivider }) try { divider = checkNotNull(attrs.getDrawable(0)) { "Divider drawable not found." } } finally { attrs.recycle() } } @Suppress("FoldInitializerAndIfToElvis") override fun onDraw( c: Canvas, parent: RecyclerView, state: RecyclerView.State ) { val left: Int val right: Int var child: View? if (parent.clipToPadding) { left = parent.paddingLeft right = parent.width - parent.paddingRight c.clipRect(left, parent.paddingTop, right, parent.height - parent.paddingBottom) } else { left = 0 right = parent.width } val bounds = Rect() for (i in 0 until state.itemCount) { child = parent.getChildAt(i) if (child == null) { continue } val pos = parent.getChildAdapterPosition(child) if (pos == state.itemCount - 1) { continue } parent.getDecoratedBoundsWithMargins(child, bounds) val bottom = bounds.bottom - child.translationY.roundToInt() val top = bottom - divider.intrinsicHeight divider.setBounds(left + marginLeft, top, right - marginRight, bottom) divider.draw(c) } } override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { val pos = parent.getChildAdapterPosition(view) outRect.left = 0 outRect.right = 0 outRect.top = if (pos == 0) marginVert else 0 outRect.bottom = if (pos == state.itemCount - 1) marginVert else divider.intrinsicHeight } }
apache-2.0
b48c755d1bd80bd32520e49b41b84276
29.868217
77
0.619538
4.712426
false
false
false
false
wuan/bo-android
app/src/main/java/org/blitzortung/android/app/WidgetProvider.kt
1
1545
/* Copyright 2015 Andreas Würl Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.blitzortung.android.app import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.Context import android.widget.RemoteViews import org.blitzortung.android.app.view.AlertView class WidgetProvider : AppWidgetProvider() { override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { for (element in appWidgetIds) { val appWidgetId = element updateAppWidget(context) } } private fun updateAppWidget(context: Context) { val alertView = AlertView(context) alertView.measure(150, 150) alertView.layout(0, 0, 150, 150) alertView.isDrawingCacheEnabled = true val bitmap = alertView.drawingCache val remoteViews = RemoteViews(context.packageName, R.layout.widget) remoteViews.setImageViewBitmap(R.layout.widget, bitmap) } }
apache-2.0
563dd519a961a72d0ae4a9f8f3b6bb3b
30.510204
105
0.722798
4.765432
false
false
false
false
Litote/kmongo
kmongo-core/src/main/kotlin/org/litote/kmongo/MongoIterables.kt
1
1907
/* * Copyright (C) 2016/2022 Litote * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.litote.kmongo import com.mongodb.client.MongoIterable private val NULL = Any() private class NullIterator<T>(val iterator: Iterator<T>) : Iterator<T?> by iterator { override fun next(): T? = iterator.next()?.takeUnless { it === NULL } } private class NullHandlerSequence<T>(val sequence: Sequence<T>) : Sequence<T?> { override fun iterator(): Iterator<T?> = NullIterator(sequence.iterator()) } /** * Evaluates the current [MongoIterable] given the [expression] of Sequences. * * The mongo cursor is closed before returning the result. * * Sample: * ``` * col.find().evaluate { * //this is a sequence evaluation * //If the first row has a name like "Fred", only one row is loaded in memory! * filter { it.name != "Joe" }.first() * } * ``` */ fun <T, R> MongoIterable<T>.evaluate(expression: Sequence<T>.() -> R): R { @Suppress("UNCHECKED_CAST") return iterator().run { use { expression( NullHandlerSequence( generateSequence { if (hasNext()) { next() ?: NULL } else { null } } ) as Sequence<T> ) } } }
apache-2.0
6cd676808c355d14e59bd89f44a63082
29.269841
85
0.596224
4.191209
false
false
false
false
GoSkyer/Java-Kotlin-MicroServer
src/main/kotlin/microserver/bio/ServerState.kt
1
1781
package microserver.bio import java.util.* import java.util.concurrent.ConcurrentHashMap /** * Created by OoO on 2017/1/21. * * * 服务器运行时状态 */ class ServerState(private val mServer: MicroServer) { var isRunning = false var connectionTotal = 0 private set private val connectionMap = ConcurrentHashMap<String, MicroConnection>() val localAddress: String get() = mServer.mConfig!!.localAddress val port: Int get() = mServer.mConfig!!.port fun cutConnection(connection: MicroConnection): Int { connectionMap.remove(connection.name) return --connectionTotal } fun addConnection(connection: MicroConnection): Int { connectionMap.put(connection.name, connection) return ++connectionTotal } /** * 获取一个连接 */ fun getConnection(name: String): MicroConnection? { return connectionMap[name] } /** * 获取全部连接 */ val allConnection: Map<String, MicroConnection> get() = connectionMap /** * 获取全部连接的名字 */ val allConnectionName: List<String> get() { val list = ArrayList<String>() val keys = connectionMap.keys() while (keys.hasMoreElements()) { val key = keys.nextElement() list.add(key) } return list } /** * 关闭一个连接 */ fun closeConnection(connection: MicroConnection) { connection.close() } /** * 关闭全部连接 */ fun closeAllConnection() { val set = connectionMap.entries for ((key, value) in set) { closeConnection(value) } } }
apache-2.0
460b08c24f76810107fd20eed6de4181
17.074468
76
0.575633
4.447644
false
false
false
false
Chimerapps/alexa-home-skill-java
project-kotlin/src/main/kotlin/com/chimerapps/alexa/home/error/Errors.kt
1
2221
/* * Copyright 2017 Chimerapps * * 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.chimerapps.alexa.home.error import com.chimerapps.alexa.home.model.CurrentModePayload import com.chimerapps.alexa.home.model.DeviceMode import com.chimerapps.alexa.home.model.ResponsePayload import com.chimerapps.alexa.home.model.SmartHomeHeader /** * @author Nicola Verbeeck * Date 09/03/2017. */ open class SmartHomeError(val header: SmartHomeHeader, val errorName: String, message: String?, cause: Throwable?, val payload: ResponsePayload? = null) : Exception(message, cause) class DriverInternalError(header: SmartHomeHeader, message: String?, cause: Throwable? = null) : SmartHomeError(header, "DriverInternalError", message, cause) class ExpiredAccessTokenError(header: SmartHomeHeader, message: String, cause: Throwable? = null) : SmartHomeError(header, "ExpiredAccessTokenError", message, cause) class InvalidAccessTokenError(header: SmartHomeHeader, message: String, cause: Throwable? = null) : SmartHomeError(header, "InvalidAccessTokenError", message, cause) class UnsupportedTargetError(header: SmartHomeHeader, message: String, cause: Throwable? = null) : SmartHomeError(header, "UnsupportedTargetError", message, cause) class UnsupportedOperationError(header: SmartHomeHeader, message: String, cause: Throwable? = null) : SmartHomeError(header, "UnsupportedOperationError", message, cause) class NotSupportedInCurrentModeError(header: SmartHomeHeader, message: String, mode: DeviceMode, cause: Throwable? = null) : SmartHomeError(header, "NotSupportedInCurrentModeError", message, cause, CurrentModePayload("NotSupportedInCurrentModeError", mode.name))
apache-2.0
8bb8ee16c7731b477c37626fb2d0ffd9
51.904762
180
0.776677
3.973166
false
false
false
false
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/endpoints/geo/Search.kt
1
6437
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ @file:Suppress("UNUSED", "PublicApiImplicitType") package jp.nephy.penicillin.endpoints.geo import jp.nephy.penicillin.core.request.action.JsonObjectApiAction import jp.nephy.penicillin.core.request.parameters import jp.nephy.penicillin.core.session.get import jp.nephy.penicillin.endpoints.Option import jp.nephy.penicillin.endpoints.Geo import jp.nephy.penicillin.models.GeoResult /** * Search for places that can be attached to a Tweet via [POST statuses/update](https://developer.twitter.com/en/docs/tweets/post-and-engage/post-statuses-update). Given a latitude and a longitude pair, an IP address, or a name, this request will return a list of all the valid places that can be used as the place_id when updating a status. * Conceptually, a query can be made from the user's location, retrieve a list of places, have the user validate the location they are at, and then send the ID of this location with a call to [POST statuses/update](https://developer.twitter.com/en/docs/tweets/post-and-engage/post-statuses-update). * This is the recommended method to use find places that can be attached to statuses/update. Unlike [GET geo/reverse_geocode](https://developer.twitter.com/en/docs/geo/places-near-location/api-reference/get-geo-reverse_geocode) which provides raw data access, this endpoint can potentially re-order places with regards to the user who is authenticated. This approach is also preferred for interactive place matching with the user. * Some parameters in this method are only required based on the existence of other parameters. For instance, "lat" is required if "long" is provided, and vice-versa. Authentication is recommended, but not required with this method. * * [Twitter API reference](https://developer.twitter.com/en/docs/geo/places-near-location/api-reference/get-geo-reverse_geocode) * * @param latitude The latitude to search around. This parameter will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding long parameter. * @param longitude The longitude to search around. The valid ranges for longitude are -180.0 to +180.0 (East is positive) inclusive. This parameter will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding lat parameter. * @param query Free-form text to match against while executing a geo-based query, best suited for finding nearby locations by name. Remember to URL encode the query. * @param ip An IP address. Used when attempting to fix geolocation based off of the user's IP address. * @param granularity This is the minimal granularity of place types to return and must be one of: neighborhood, city, admin or country . If no granularity is provided for the request neighborhood is assumed. Setting this to city, for example, will find places which have a type of city, admin or country. * @param accuracy A hint on the "region" in which to search. If a number, then this is a radius in meters, but it can also take a string that is suffixed with ft to specify feet. If this is not passed in, then it is assumed to be 0m. If coming from a device, in practice, this value is whatever accuracy the device has measuring its location (whether it be coming from a GPS, WiFi triangulation, etc.). * @param maxResults A hint as to the number of results to return. This does not guarantee that the number of results returned will equal max_results, but instead informs how many "nearby" results to return. Ideally, only pass in the number of places you intend to display to the user here. * @param containedWithin This is the place_id which you would like to restrict the search results to. Setting this value means only places within the given place_id will be found. Specify a place_id. For example, to scope all results to places within "San Francisco, CA USA", you would specify a place_id of "5a110d312052166f". * @param attributeStreetAddress This parameter searches for places which have this given street address. There are other well-known, and application specific attributes available. Custom attributes are also permitted. Learn more about [Place attributes](https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/geo-objects). * @param options Optional. Custom parameters of this request. * @receiver [Geo] endpoint instance. * @return [JsonObjectApiAction] for [GeoResult] model. */ fun Geo.search( latitude: Double? = null, longitude: Double? = null, query: String? = null, ip: String? = null, granularity: GeoGranularity? = null, accuracy: String? = null, maxResults: Int? = null, containedWithin: String? = null, attributeStreetAddress: String? = null, callback: String? = null, vararg options: Option ) = client.session.get("/1.1/geo/search.json") { parameters( "lat" to latitude, "long" to longitude, "query" to query, "ip" to ip, "granularity" to granularity, "accuracy" to accuracy, "max_results" to maxResults, "contained_within" to containedWithin, "attribute:street_address" to attributeStreetAddress, "callback" to callback, *options ) }.jsonObject<GeoResult>()
mit
d8a89c8d6cbc4c014bb9ac848d161c33
76.554217
431
0.75936
4.243243
false
false
false
false
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/endpoints/statuses/Show.kt
1
4422
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ @file:Suppress("UNUSED", "PublicApiImplicitType") package jp.nephy.penicillin.endpoints.statuses import jp.nephy.penicillin.core.request.action.JsonObjectApiAction import jp.nephy.penicillin.core.request.parameters import jp.nephy.penicillin.core.session.get import jp.nephy.penicillin.endpoints.Option import jp.nephy.penicillin.endpoints.Statuses import jp.nephy.penicillin.endpoints.common.TweetMode import jp.nephy.penicillin.models.Status /** * Returns a single [Tweet](https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/tweet-object), specified by the id parameter. The Tweet's author will also be embedded within the Tweet. * See [GET statuses/lookup](https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-lookup) for getting Tweets in bulk (up to 100 per call). See also [Embedded Timelines](https://developer.twitter.com/web/embedded-timelines), [Embedded Tweets](https://developer.twitter.com/web/embedded-tweets), and [GET statuses/oembed](https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-oembed) for tools to render Tweets according to [Display Requirements](https://about.twitter.com/company/display-requirements). * * [Twitter API reference](https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/get-statuses-show-id) * * @param id The numerical ID of the desired Tweet. * @param trimUser When set to either true , t or 1 , each Tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object. * @param includeMyRetweet When set to either true, t or 1, any Tweets returned that have been retweeted by the authenticating user will include an additional current_user_retweet node, containing the ID of the source status for the retweet. * @param includeEntities The entities node will not be included when set to false. * @param includeExtAltText If alt text has been added to any attached media entities, this parameter will return an ext_alt_text value in the top-level key for the media entity. If no value has been set, this will be returned as null. * @param includeCardUri When set to either true, t or 1, the retrieved Tweet will include a card_uri attribute when there is an ads card attached to the Tweet and when that card was attached using the card_uri value. * @param options Optional. Custom parameters of this request. * @receiver [Statuses] endpoint instance. * @return [JsonObjectApiAction] for [Status] model. */ fun Statuses.show( id: Long, trimUser: Boolean? = null, includeMyRetweet: Boolean? = null, includeEntities: Boolean? = null, includeExtAltText: Boolean? = null, includeCardUri: Boolean? = null, tweetMode: TweetMode = TweetMode.Default, vararg options: Option ) = client.session.get("/1.1/statuses/show.json") { parameters( "id" to id, "trim_user" to trimUser, "include_my_retweet" to includeMyRetweet, "include_entities" to includeEntities, "include_ext_alt_text" to includeExtAltText, "include_card_uri" to includeCardUri, "tweet_mode" to tweetMode, *options ) }.jsonObject<Status>()
mit
02af4fdfb4a18e1a5f8b5fe7c2a51583
59.575342
570
0.758933
4.075576
false
false
false
false
lena0204/Plattenspieler
app/src/main/java/com/lk/plattenspieler/observables/PlaybackViewModel.kt
1
3458
package com.lk.plattenspieler.observables import android.app.Application import android.media.session.PlaybackState import android.util.Log import androidx.lifecycle.* import com.lk.musicservicelibrary.database.* import com.lk.musicservicelibrary.database.room.PlaylistRoomRepository import com.lk.musicservicelibrary.models.MusicList import com.lk.musicservicelibrary.models.MusicMetadata import com.lk.musicservicelibrary.utils.SharedPrefsWrapper import com.lk.plattenspieler.musicbrowser.ControllerAction /** * Erstellt von Lena am 09.09.18. */ class PlaybackViewModel(application: Application): AndroidViewModel(application) { private val TAG = "PlaybackViewModel" private var metadata = MutableLiveData<MusicMetadata>() private var playbackState = MutableLiveData<PlaybackState>() private var queue = MutableLiveData<MusicList>() private var controllerAction = MutableLiveData<ControllerAction>() private var showBar = MutableLiveData<Boolean>() private var playlistRepo: PlaylistRepository init { metadata.value = MusicMetadata() playbackState.value = PlaybackState.Builder().build() queue.value = MusicList() showBar.value = false playlistRepo = PlaylistRoomRepository(application) } fun setObserverToAll(owner: LifecycleOwner, observer: Observer<Any>){ metadata.observe(owner, observer) playbackState.observe(owner, observer) queue.observe(owner, observer) } fun setObserverToShowBar(owner: LifecycleOwner, observer: Observer<Any>) { showBar.observe(owner, observer) } fun setObserverToPlaybackState(owner: LifecycleOwner, observer: Observer<Any>){ playbackState.observe(owner, observer) } fun setObserverToAction(owner: LifecycleOwner, observer: Observer<Any>){ controllerAction.observe(owner, observer) } fun callAction(action: ControllerAction) { controllerAction.value = action } // TODO über Commands lösen anstatt von direktem Zugriff fun saveQueue(){ if(!queue.value!!.isEmpty()) { // is queue resetted when stopping? Log.d(TAG, "saveQueue: currently not used cause being buggy ...") // playlistRepo.savePlayingQueue(queue.value!!, metadata.value!!) } else { Log.d(TAG, "just delete playlist") playlistRepo.deletePlaylist() } } private fun getShufflePreference(): Boolean = SharedPrefsWrapper.readShuffle(this.getApplication()) fun getMetadata(): MusicMetadata { return metadata.value ?: MusicMetadata() } fun setMetadata(data: MusicMetadata) { metadata.value = data } fun getPlaybackState(): PlaybackState { return playbackState.value ?: PlaybackState.Builder().build() } fun setPlaybackState(data: PlaybackState) { playbackState.value = data } fun setQueue(data: MusicList) { queue.value = data } fun getQueueLimitedTo30(): MusicList{ var limitedQueue = MusicList() if(queue.value!!.size() > 30) { for(i in 0..29){ limitedQueue.addItem(queue.value!!.getItemAt(i)) } } else { limitedQueue = queue.value as MusicList } return limitedQueue } fun setShowBar(show: Boolean) { showBar.value= show } fun getShowBar(): Boolean = showBar.value ?: false }
gpl-3.0
8639a305e01c4f52bd4fc4446e53ee36
31.009259
83
0.684028
4.535433
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/bowlers/BowlerDialog.kt
1
7527
package ca.josephroque.bowlingcompanion.bowlers import android.app.Dialog import android.content.Context import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v7.app.AlertDialog import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.Window import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import ca.josephroque.bowlingcompanion.App import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.Android import ca.josephroque.bowlingcompanion.common.fragments.BaseDialogFragment import ca.josephroque.bowlingcompanion.utils.Analytics import ca.josephroque.bowlingcompanion.utils.Color import ca.josephroque.bowlingcompanion.utils.safeLet import kotlinx.android.synthetic.main.dialog_bowler.input_name as nameInput import kotlinx.android.synthetic.main.dialog_bowler.btn_delete as deleteButton import kotlinx.android.synthetic.main.dialog_bowler.view.* import kotlinx.coroutines.experimental.launch /** * Copyright (C) 2018 Joseph Roque * * Dialog to create a new bowler. */ class BowlerDialog : BaseDialogFragment() { companion object { @Suppress("unused") private const val TAG = "BowlerDialog" private const val ARG_BOWLER = "${TAG}_BOWLER" fun newInstance(bowler: Bowler?): BowlerDialog { val dialog = BowlerDialog() dialog.arguments = Bundle().apply { bowler?.let { putParcelable(ARG_BOWLER, bowler) } } return dialog } } private var bowler: Bowler? = null private var delegate: BowlerDialogDelegate? = null private val deleteListener = View.OnClickListener { safeLet(context, bowler) { context, bowler -> AlertDialog.Builder(context) .setTitle(String.format(context.resources.getString(R.string.query_delete_item), bowler.name)) .setMessage(R.string.dialog_delete_item_message) .setPositiveButton(R.string.delete) { _, _ -> delegate?.onDeleteBowler(bowler) dismiss() } .setNegativeButton(R.string.cancel, null) .show() } } // MARK: Lifecycle functions override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(DialogFragment.STYLE_NORMAL, R.style.Dialog) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { bowler = arguments?.getParcelable(ARG_BOWLER) val rootView = inflater.inflate(R.layout.dialog_bowler, container, false) bowler?.let { resetInputs(it, rootView) } setupToolbar(rootView) setupInput(rootView) return rootView } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) return dialog } override fun onAttach(context: Context?) { super.onAttach(context) val parentFragment = parentFragment as? BowlerDialogDelegate ?: throw RuntimeException("${parentFragment!!} must implement BowlerDialogDelegate") delegate = parentFragment } override fun onDetach() { super.onDetach() delegate = null } override fun onStart() { super.onStart() dialog.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) // Requesting input focus and showing keyboard nameInput.requestFocus() val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput(nameInput, InputMethodManager.SHOW_IMPLICIT) bowler?.let { deleteButton.visibility = View.VISIBLE } nameInput.text?.let { nameInput.setSelection(it.length) } updateSaveButton() } override fun dismiss() { App.hideSoftKeyBoard(activity!!) activity?.supportFragmentManager?.popBackStack() super.dismiss() } // MARK: Private functions private fun setupToolbar(rootView: View) { if (bowler == null) { rootView.toolbar_bowler.setTitle(R.string.new_bowler) } else { rootView.toolbar_bowler.setTitle(R.string.edit_bowler) } rootView.toolbar_bowler.apply { inflateMenu(R.menu.dialog_bowler) menu.findItem(R.id.action_save).isEnabled = bowler?.name?.isNotEmpty() == true setNavigationIcon(R.drawable.ic_dismiss) setNavigationOnClickListener { dismiss() } setOnMenuItemClickListener { when (it.itemId) { R.id.action_save -> { saveBowler() true } else -> super.onOptionsItemSelected(it) } } } } private fun setupInput(rootView: View) { rootView.btn_delete.setOnClickListener(deleteListener) rootView.input_name.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) {} override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { updateSaveButton() } }) } private fun canSave() = nameInput.text?.isNotEmpty() ?: false private fun updateSaveButton() { val saveButton = view?.toolbar_bowler?.menu?.findItem(R.id.action_save) if (canSave()) { saveButton?.isEnabled = true saveButton?.icon?.alpha = Color.ALPHA_ENABLED } else { saveButton?.isEnabled = false saveButton?.icon?.alpha = Color.ALPHA_DISABLED } } private fun saveBowler() { launch(Android) { [email protected]?.let { context -> val name = nameInput.text.toString() if (canSave()) { val oldBowler = bowler val (newBowler, error) = if (oldBowler != null) { Bowler.save(context, oldBowler.id, name, oldBowler.average).await() } else { Bowler.save(context, -1, name).await() } if (error != null) { error.show(context) bowler?.let { resetInputs(it) } } else if (newBowler != null) { dismiss() delegate?.onFinishBowler(newBowler) if (oldBowler == null) { Analytics.trackCreateBowler() } else { Analytics.trackEditBowler() } } } } } } private fun resetInputs(bowler: Bowler, rootView: View? = null) { val nameInput = rootView?.input_name ?: this.nameInput nameInput.setText(bowler.name) } // MARK: BowlerDialogDelegate interface BowlerDialogDelegate { fun onFinishBowler(bowler: Bowler) fun onDeleteBowler(bowler: Bowler) } }
mit
ad8f32c1229ba955f18ddb018bcdb2a5
34.504717
153
0.612595
4.90998
false
false
false
false
duftler/orca
orca-kayenta/src/test/kotlin/com/netflix/spinnaker/orca/kayenta/pipeline/KayentaCanaryStageTest.kt
1
2846
/* * 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.kayenta.pipeline import com.netflix.spinnaker.orca.fixture.stage import com.netflix.spinnaker.orca.pipeline.graph.StageGraphBuilder import com.netflix.spinnaker.time.fixedClock import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it object KayentaCanaryStageTest : Spek({ val clock = fixedClock() val builder = KayentaCanaryStage(clock) describe("planning a canary stage") { given("canary deployments are requested") { val kayentaCanaryStage = stage { type = "kayentaCanary" name = "Run Kayenta Canary" context["canaryConfig"] = mapOf( "metricsAccountName" to "atlas-acct-1", "canaryConfigId" to "MySampleAtlasCanaryConfig", "scopes" to listOf(mapOf( "controlScope" to "some.host.node", "experimentScope" to "some.other.host.node", "step" to 60 )), "scoreThresholds" to mapOf("marginal" to 75, "pass" to 90), "canaryAnalysisIntervalMins" to 6.hoursInMinutes, "lifetimeHours" to "12" ) context["deployments"] = mapOf( "clusters" to listOf( mapOf("control" to mapOf<String, Any>()), mapOf("experiment" to mapOf<String, Any>()) ) ) } val aroundStages = StageGraphBuilder.beforeStages(kayentaCanaryStage) .let { graph -> builder.beforeStages(kayentaCanaryStage, graph) graph.build() } it("injects a deploy canary stage") { aroundStages.first().apply { assertThat(type).isEqualTo(DeployCanaryServerGroupsStage.STAGE_TYPE) } } it("the canary analysis will only start once the deployment is complete") { aroundStages.toList()[0..1].let { (first, second) -> assertThat(second.requisiteStageRefIds).isEqualTo(setOf(first.refId)) } } } } }) private operator fun <E> List<E>.get(range: IntRange): List<E> { return subList(range.start, range.endExclusive) } private val IntRange.endExclusive: Int get() = endInclusive + 1
apache-2.0
97fb7c7c9972554c8962311253620303
32.880952
81
0.668658
4.124638
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-banks-bukkit/src/main/kotlin/com/rpkit/banks/bukkit/listener/SignChangeListener.kt
1
2934
/* * Copyright 2021 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.banks.bukkit.listener import com.rpkit.banks.bukkit.RPKBanksBukkit import com.rpkit.core.service.Services import com.rpkit.economy.bukkit.currency.RPKCurrencyName import com.rpkit.economy.bukkit.currency.RPKCurrencyService import org.bukkit.ChatColor.GREEN import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.block.SignChangeEvent /** * Sign change listener for bank signs. */ class SignChangeListener(private val plugin: RPKBanksBukkit) : Listener { @EventHandler fun onSignChange(event: SignChangeEvent) { if (event.getLine(0).equals("[bank]", ignoreCase = true)) { event.setLine(0, "$GREEN[bank]") if (!event.player.hasPermission("rpkit.banks.sign.bank")) { event.block.breakNaturally() event.player.sendMessage(plugin.messages["no-permission-bank-create"]) return } if (!(event.getLine(1).equals("withdraw", ignoreCase = true) || event.getLine(1).equals("deposit", ignoreCase = true) || event.getLine(1).equals("balance", ignoreCase = true))) { event.block.breakNaturally() event.player.sendMessage(plugin.messages["bank-sign-invalid-operation"]) return } if (event.getLine(1).equals("balance", ignoreCase = true)) { event.setLine(2, "") } else { event.setLine(2, "1") } val currencyService = Services[RPKCurrencyService::class.java] if (currencyService == null) { event.block.breakNaturally() event.player.sendMessage(plugin.messages["no-currency-service"]) return } val currencyName = event.getLine(3) if (currencyName == null || currencyService.getCurrency(RPKCurrencyName(currencyName)) == null) { val defaultCurrency = currencyService.defaultCurrency if (defaultCurrency == null) { event.block.breakNaturally() event.player.sendMessage(plugin.messages["bank-sign-invalid-currency"]) return } else { event.setLine(3, defaultCurrency.name.value) } } } } }
apache-2.0
9e040d342cada480fece13144d03eaec
41.536232
190
0.63122
4.577223
false
false
false
false
cketti/k-9
app/ui/legacy/src/main/java/com/fsck/k9/activity/MessageList.kt
1
57510
package com.fsck.k9.activity import android.annotation.SuppressLint import android.app.SearchManager import android.content.Context import android.content.Intent import android.content.IntentSender import android.content.res.Configuration import android.graphics.Color import android.os.Bundle import android.os.Parcelable import android.view.KeyEvent import android.view.Menu import android.view.MenuItem import android.view.View import android.view.animation.AnimationUtils import android.widget.ProgressBar import androidx.appcompat.app.ActionBar import androidx.appcompat.view.ActionMode import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.Toolbar import androidx.drawerlayout.widget.DrawerLayout import androidx.drawerlayout.widget.DrawerLayout.DrawerListener import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentTransaction import androidx.fragment.app.commit import androidx.fragment.app.commitNow import androidx.lifecycle.Observer import com.fsck.k9.Account import com.fsck.k9.K9 import com.fsck.k9.K9.SplitViewMode import com.fsck.k9.Preferences import com.fsck.k9.account.BackgroundAccountRemover import com.fsck.k9.activity.compose.MessageActions import com.fsck.k9.controller.MessageReference import com.fsck.k9.controller.MessagingController import com.fsck.k9.helper.Contacts import com.fsck.k9.helper.ParcelableUtil import com.fsck.k9.mailstore.SearchStatusManager import com.fsck.k9.preferences.GeneralSettingsManager import com.fsck.k9.search.LocalSearch import com.fsck.k9.search.SearchAccount import com.fsck.k9.search.SearchSpecification import com.fsck.k9.search.SearchSpecification.SearchCondition import com.fsck.k9.search.SearchSpecification.SearchField import com.fsck.k9.search.isUnifiedInbox import com.fsck.k9.ui.BuildConfig import com.fsck.k9.ui.K9Drawer import com.fsck.k9.ui.R import com.fsck.k9.ui.base.K9Activity import com.fsck.k9.ui.changelog.RecentChangesActivity import com.fsck.k9.ui.changelog.RecentChangesViewModel import com.fsck.k9.ui.managefolders.ManageFoldersActivity import com.fsck.k9.ui.messagelist.DefaultFolderProvider import com.fsck.k9.ui.messagelist.MessageListFragment import com.fsck.k9.ui.messagelist.MessageListFragment.MessageListFragmentListener import com.fsck.k9.ui.messageview.Direction import com.fsck.k9.ui.messageview.MessageViewContainerFragment import com.fsck.k9.ui.messageview.MessageViewContainerFragment.MessageViewContainerListener import com.fsck.k9.ui.messageview.MessageViewFragment.MessageViewFragmentListener import com.fsck.k9.ui.messageview.PlaceholderFragment import com.fsck.k9.ui.onboarding.OnboardingActivity import com.fsck.k9.ui.permissions.K9PermissionUiHelper import com.fsck.k9.ui.permissions.Permission import com.fsck.k9.ui.permissions.PermissionUiHelper import com.fsck.k9.view.ViewSwitcher import com.fsck.k9.view.ViewSwitcher.OnSwitchCompleteListener import com.google.android.material.snackbar.Snackbar import com.mikepenz.materialdrawer.util.getOptimalDrawerWidth import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.component.KoinComponent import org.koin.core.component.inject import timber.log.Timber /** * MessageList is the primary user interface for the program. This Activity shows a list of messages. * * From this Activity the user can perform all standard message operations. */ open class MessageList : K9Activity(), MessageListFragmentListener, MessageViewFragmentListener, MessageViewContainerListener, FragmentManager.OnBackStackChangedListener, OnSwitchCompleteListener, PermissionUiHelper { private val recentChangesViewModel: RecentChangesViewModel by viewModel() protected val searchStatusManager: SearchStatusManager by inject() private val preferences: Preferences by inject() private val defaultFolderProvider: DefaultFolderProvider by inject() private val accountRemover: BackgroundAccountRemover by inject() private val generalSettingsManager: GeneralSettingsManager by inject() private val messagingController: MessagingController by inject() private val permissionUiHelper: PermissionUiHelper = K9PermissionUiHelper(this) private lateinit var actionBar: ActionBar private var searchView: SearchView? = null private var initialSearchViewQuery: String? = null private var initialSearchViewIconified: Boolean = true private var drawer: K9Drawer? = null private var openFolderTransaction: FragmentTransaction? = null private var progressBar: ProgressBar? = null private var messageViewPlaceHolder: PlaceholderFragment? = null private var messageListFragment: MessageListFragment? = null private var messageViewContainerFragment: MessageViewContainerFragment? = null private var account: Account? = null private var search: LocalSearch? = null private var singleFolderMode = false private val lastDirection: Direction get() { return messageViewContainerFragment?.lastDirection ?: if (K9.isMessageViewShowNext) Direction.NEXT else Direction.PREVIOUS } private var messageListActivityConfig: MessageListActivityConfig? = null /** * `true` if the message list should be displayed as flat list (i.e. no threading) * regardless whether or not message threading was enabled in the settings. This is used for * filtered views, e.g. when only displaying the unread messages in a folder. */ private var noThreading = false private var displayMode: DisplayMode = DisplayMode.MESSAGE_LIST private var messageReference: MessageReference? = null /** * If this is `true`, only the message view will be displayed and pressing the back button will finish the Activity. */ private var messageViewOnly = false private var messageListWasDisplayed = false private var viewSwitcher: ViewSwitcher? = null private lateinit var recentChangesSnackbar: Snackbar public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // If the app's main task was not created using the default launch intent (e.g. from a notification, a widget, // or a shortcut), using the app icon to "launch" the app will create a new MessageList instance instead of only // bringing the app's task to the foreground. We catch this situation here and simply finish the activity. This // will bring the task to the foreground, showing the last active screen. if (intent.action == Intent.ACTION_MAIN && intent.hasCategory(Intent.CATEGORY_LAUNCHER) && !isTaskRoot) { Timber.v("Not displaying MessageList. Only bringing the app task to the foreground.") finish() return } val accounts = preferences.accounts deleteIncompleteAccounts(accounts) val hasAccountSetup = accounts.any { it.isFinishedSetup } if (!hasAccountSetup) { OnboardingActivity.launch(this) finish() return } if (UpgradeDatabases.actionUpgradeDatabases(this, intent)) { finish() return } if (useSplitView()) { setLayout(R.layout.split_message_list) } else { setLayout(R.layout.message_list) viewSwitcher = findViewById<ViewSwitcher>(R.id.container).apply { firstInAnimation = AnimationUtils.loadAnimation(this@MessageList, R.anim.slide_in_left) firstOutAnimation = AnimationUtils.loadAnimation(this@MessageList, R.anim.slide_out_right) secondInAnimation = AnimationUtils.loadAnimation(this@MessageList, R.anim.slide_in_right) secondOutAnimation = AnimationUtils.loadAnimation(this@MessageList, R.anim.slide_out_left) setOnSwitchCompleteListener(this@MessageList) } } window.statusBarColor = Color.TRANSPARENT val rootLayout = findViewById<View>(R.id.drawerLayout) rootLayout.systemUiVisibility = rootLayout.systemUiVisibility or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN val toolbar = findViewById<Toolbar>(R.id.toolbar) toolbar.setOnApplyWindowInsetsListener { view, insets -> view.setPadding(view.paddingLeft, insets.systemWindowInsetTop, view.paddingRight, view.paddingBottom) insets } val swipeRefreshLayout = findViewById<View>(R.id.material_drawer_swipe_refresh) swipeRefreshLayout.layoutParams.width = getOptimalDrawerWidth(this) initializeActionBar() initializeDrawer(savedInstanceState) if (!decodeExtras(intent)) { return } if (isDrawerEnabled) { configureDrawer() drawer!!.updateUserAccountsAndFolders(account) } findFragments() initializeDisplayMode(savedInstanceState) initializeLayout() initializeFragments() displayViews() initializeRecentChangesSnackbar() if (savedInstanceState == null) { checkAndRequestPermissions() } } public override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) if (isFinishing) { return } if (intent.action == Intent.ACTION_MAIN && intent.hasCategory(Intent.CATEGORY_LAUNCHER)) { // There's nothing to do if the default launcher Intent was used. // This only brings the existing screen to the foreground. return } setIntent(intent) // Start with a fresh fragment back stack supportFragmentManager.popBackStackImmediate(FIRST_FRAGMENT_TRANSACTION, FragmentManager.POP_BACK_STACK_INCLUSIVE) removeMessageListFragment() removeMessageViewContainerFragment() messageReference = null search = null if (!decodeExtras(intent)) { return } if (isDrawerEnabled) { configureDrawer() drawer!!.updateUserAccountsAndFolders(account) } initializeDisplayMode(null) initializeFragments() displayViews() } private fun deleteIncompleteAccounts(accounts: List<Account>) { accounts.filter { !it.isFinishedSetup }.forEach { accountRemover.removeAccountAsync(it.uuid) } } private fun findFragments() { val fragmentManager = supportFragmentManager messageListFragment = fragmentManager.findFragmentById(R.id.message_list_container) as MessageListFragment? messageViewContainerFragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG_MESSAGE_VIEW_CONTAINER) as MessageViewContainerFragment? messageListFragment?.let { messageListFragment -> messageViewContainerFragment?.setViewModel(messageListFragment.viewModel) initializeFromLocalSearch(messageListFragment.localSearch) } } private fun initializeFragments() { val fragmentManager = supportFragmentManager fragmentManager.addOnBackStackChangedListener(this) val hasMessageListFragment = messageListFragment != null if (!hasMessageListFragment) { val fragmentTransaction = fragmentManager.beginTransaction() val messageListFragment = MessageListFragment.newInstance( search!!, false, K9.isThreadedViewEnabled && !noThreading ) fragmentTransaction.add(R.id.message_list_container, messageListFragment) fragmentTransaction.commitNow() this.messageListFragment = messageListFragment } // Check if the fragment wasn't restarted and has a MessageReference in the arguments. // If so, open the referenced message. if (!hasMessageListFragment && messageViewContainerFragment == null && messageReference != null) { openMessage(messageReference!!) } } /** * Set the initial display mode (message list, message view, or split view). * * **Note:** * This method has to be called after [.findFragments] because the result depends on * the availability of a [MessageViewFragment] instance. */ private fun initializeDisplayMode(savedInstanceState: Bundle?) { if (useSplitView()) { displayMode = DisplayMode.SPLIT_VIEW return } if (savedInstanceState != null) { val savedDisplayMode = savedInstanceState.getSerializable(STATE_DISPLAY_MODE) as DisplayMode if (savedDisplayMode != DisplayMode.SPLIT_VIEW) { displayMode = savedDisplayMode return } } displayMode = if (messageViewContainerFragment != null || messageReference != null) { DisplayMode.MESSAGE_VIEW } else { DisplayMode.MESSAGE_LIST } } private fun useSplitView(): Boolean { val splitViewMode = K9.splitViewMode val orientation = resources.configuration.orientation return splitViewMode === SplitViewMode.ALWAYS || splitViewMode === SplitViewMode.WHEN_IN_LANDSCAPE && orientation == Configuration.ORIENTATION_LANDSCAPE } private fun initializeLayout() { progressBar = findViewById(R.id.message_list_progress) messageViewPlaceHolder = PlaceholderFragment() } private fun displayViews() { when (displayMode) { DisplayMode.MESSAGE_LIST -> { showMessageList() } DisplayMode.MESSAGE_VIEW -> { showMessageView() } DisplayMode.SPLIT_VIEW -> { val messageListFragment = checkNotNull(this.messageListFragment) messageListWasDisplayed = true messageListFragment.isActive = true messageViewContainerFragment.let { messageViewContainerFragment -> if (messageViewContainerFragment == null) { showMessageViewPlaceHolder() } else { messageViewContainerFragment.isActive = true } } setDrawerLockState() onMessageListDisplayed() } } } private val shouldShowRecentChangesHintObserver = Observer<Boolean> { showRecentChangesHint -> val recentChangesSnackbarVisible = recentChangesSnackbar.isShown if (showRecentChangesHint && !recentChangesSnackbarVisible) { recentChangesSnackbar.show() } else if (!showRecentChangesHint && recentChangesSnackbarVisible) { recentChangesSnackbar.dismiss() } } @SuppressLint("ShowToast") private fun initializeRecentChangesSnackbar() { recentChangesSnackbar = Snackbar .make(findViewById(R.id.container), R.string.changelog_snackbar_text, Snackbar.LENGTH_INDEFINITE) .setAction(R.string.okay_action) { launchRecentChangesActivity() } recentChangesViewModel.shouldShowRecentChangesHint.observe(this, shouldShowRecentChangesHintObserver) } private fun launchRecentChangesActivity() { recentChangesViewModel.shouldShowRecentChangesHint.removeObserver(shouldShowRecentChangesHintObserver) val intent = Intent(this, RecentChangesActivity::class.java) startActivity(intent) } private fun decodeExtras(intent: Intent): Boolean { val launchData = decodeExtrasToLaunchData(intent) // If Unified Inbox was disabled show default account instead val search = if (launchData.search.isUnifiedInbox && !K9.isShowUnifiedInbox) { createDefaultLocalSearch() } else { launchData.search } // If no account has been specified, keep the currently active account when opening the Unified Inbox val account = launchData.account ?: account?.takeIf { launchData.search.isUnifiedInbox } ?: search.firstAccount() if (account == null) { finish() return false } this.account = account this.search = search singleFolderMode = search.folderIds.size == 1 noThreading = launchData.noThreading messageReference = launchData.messageReference messageViewOnly = launchData.messageViewOnly return true } private fun decodeExtrasToLaunchData(intent: Intent): LaunchData { val action = intent.action val queryString = intent.getStringExtra(SearchManager.QUERY) if (action == ACTION_SHORTCUT) { // Handle shortcut intents val specialFolder = intent.getStringExtra(EXTRA_SPECIAL_FOLDER) if (SearchAccount.UNIFIED_INBOX == specialFolder) { return LaunchData(search = SearchAccount.createUnifiedInboxAccount().relatedSearch) } } else if (action == Intent.ACTION_SEARCH && queryString != null) { // Query was received from Search Dialog val query = queryString.trim() val search = LocalSearch().apply { isManualSearch = true or(SearchCondition(SearchField.SENDER, SearchSpecification.Attribute.CONTAINS, query)) or(SearchCondition(SearchField.SUBJECT, SearchSpecification.Attribute.CONTAINS, query)) or(SearchCondition(SearchField.MESSAGE_CONTENTS, SearchSpecification.Attribute.CONTAINS, query)) } val appData = intent.getBundleExtra(SearchManager.APP_DATA) if (appData != null) { val searchAccountUuid = appData.getString(EXTRA_SEARCH_ACCOUNT) if (searchAccountUuid != null) { search.addAccountUuid(searchAccountUuid) // searches started from a folder list activity will provide an account, but no folder if (appData.containsKey(EXTRA_SEARCH_FOLDER)) { val folderId = appData.getLong(EXTRA_SEARCH_FOLDER) search.addAllowedFolder(folderId) } } else if (BuildConfig.DEBUG) { throw AssertionError("Invalid app data in search intent") } } return LaunchData( search = search, noThreading = true ) } else if (intent.hasExtra(EXTRA_MESSAGE_REFERENCE)) { val messageReferenceString = intent.getStringExtra(EXTRA_MESSAGE_REFERENCE) val messageReference = MessageReference.parse(messageReferenceString) if (messageReference != null) { val search = if (intent.hasExtra(EXTRA_SEARCH)) { ParcelableUtil.unmarshall(intent.getByteArrayExtra(EXTRA_SEARCH), LocalSearch.CREATOR) } else { messageReference.toLocalSearch() } return LaunchData( search = search, messageReference = messageReference, messageViewOnly = intent.getBooleanExtra(EXTRA_MESSAGE_VIEW_ONLY, false) ) } } else if (intent.hasExtra(EXTRA_SEARCH)) { // regular LocalSearch object was passed val search = ParcelableUtil.unmarshall(intent.getByteArrayExtra(EXTRA_SEARCH), LocalSearch.CREATOR) val noThreading = intent.getBooleanExtra(EXTRA_NO_THREADING, false) val account = intent.getStringExtra(EXTRA_ACCOUNT)?.let { accountUuid -> preferences.getAccount(accountUuid) } return LaunchData(search = search, account = account, noThreading = noThreading) } else if (intent.hasExtra("account")) { val accountUuid = intent.getStringExtra("account") if (accountUuid != null) { // We've most likely been started by an old unread widget or accounts shortcut val account = preferences.getAccount(accountUuid) if (account == null) { Timber.d("Account %s not found.", accountUuid) return LaunchData(createDefaultLocalSearch()) } val folderId = defaultFolderProvider.getDefaultFolder(account) val search = LocalSearch().apply { addAccountUuid(accountUuid) addAllowedFolder(folderId) } return LaunchData(search = search) } } // Default action val search = if (K9.isShowUnifiedInbox) { SearchAccount.createUnifiedInboxAccount().relatedSearch } else { createDefaultLocalSearch() } return LaunchData(search) } private fun createDefaultLocalSearch(): LocalSearch { val account = preferences.defaultAccount ?: error("No default account available") return LocalSearch().apply { addAccountUuid(account.uuid) addAllowedFolder(defaultFolderProvider.getDefaultFolder(account)) } } private fun checkAndRequestPermissions() { if (!hasPermission(Permission.READ_CONTACTS)) { requestPermissionOrShowRationale(Permission.READ_CONTACTS) } } public override fun onResume() { super.onResume() if (messageListActivityConfig == null) { messageListActivityConfig = MessageListActivityConfig.create(generalSettingsManager) } else if (messageListActivityConfig != MessageListActivityConfig.create(generalSettingsManager)) { recreateCompat() } if (displayMode != DisplayMode.MESSAGE_VIEW) { onMessageListDisplayed() } if (this !is Search) { // necessary b/c no guarantee Search.onStop will be called before MessageList.onResume // when returning from search results searchStatusManager.isActive = false } } override fun onStart() { super.onStart() Contacts.clearCache() } public override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putSerializable(STATE_DISPLAY_MODE, displayMode) outState.putBoolean(STATE_MESSAGE_VIEW_ONLY, messageViewOnly) outState.putBoolean(STATE_MESSAGE_LIST_WAS_DISPLAYED, messageListWasDisplayed) searchView?.let { searchView -> outState.putBoolean(STATE_SEARCH_VIEW_ICONIFIED, searchView.isIconified) outState.putString(STATE_SEARCH_VIEW_QUERY, searchView.query?.toString()) } } public override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) messageViewOnly = savedInstanceState.getBoolean(STATE_MESSAGE_VIEW_ONLY) messageListWasDisplayed = savedInstanceState.getBoolean(STATE_MESSAGE_LIST_WAS_DISPLAYED) initialSearchViewIconified = savedInstanceState.getBoolean(STATE_SEARCH_VIEW_ICONIFIED, true) initialSearchViewQuery = savedInstanceState.getString(STATE_SEARCH_VIEW_QUERY) } private fun initializeActionBar() { actionBar = supportActionBar!! actionBar.setDisplayHomeAsUpEnabled(true) } private fun initializeDrawer(savedInstanceState: Bundle?) { if (!isDrawerEnabled) { val drawerLayout = findViewById<DrawerLayout>(R.id.drawerLayout) drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED) return } drawer = K9Drawer(this, savedInstanceState) } fun createDrawerListener(): DrawerListener { return object : DrawerListener { override fun onDrawerClosed(drawerView: View) { if (openFolderTransaction != null) { commitOpenFolderTransaction() } } override fun onDrawerStateChanged(newState: Int) = Unit override fun onDrawerOpened(drawerView: View) { collapseSearchView() messageListFragment?.finishActionMode() } override fun onDrawerSlide(drawerView: View, slideOffset: Float) = Unit } } fun openFolder(folderId: Long) { if (displayMode == DisplayMode.SPLIT_VIEW) { removeMessageViewContainerFragment() showMessageViewPlaceHolder() } val search = LocalSearch() search.addAccountUuid(account!!.uuid) search.addAllowedFolder(folderId) performSearch(search) } private fun openFolderImmediately(folderId: Long) { openFolder(folderId) commitOpenFolderTransaction() } private fun commitOpenFolderTransaction() { openFolderTransaction!!.commit() openFolderTransaction = null messageListFragment!!.isActive = true onMessageListDisplayed() } fun openUnifiedInbox() { actionDisplaySearch(this, SearchAccount.createUnifiedInboxAccount().relatedSearch, false, false) } fun launchManageFoldersScreen() { if (account == null) { Timber.e("Tried to open \"Manage folders\", but no account selected!") return } ManageFoldersActivity.launch(this, account!!) } fun openRealAccount(account: Account): Boolean { val shouldCloseDrawer = account.autoExpandFolderId != null val folderId = defaultFolderProvider.getDefaultFolder(account) val search = LocalSearch() search.addAllowedFolder(folderId) search.addAccountUuid(account.uuid) actionDisplaySearch(this, search, noThreading = false, newTask = false) return shouldCloseDrawer } private fun performSearch(search: LocalSearch) { initializeFromLocalSearch(search) val fragmentManager = supportFragmentManager check(!(BuildConfig.DEBUG && fragmentManager.backStackEntryCount > 0)) { "Don't call performSearch() while there are fragments on the back stack" } val openFolderTransaction = fragmentManager.beginTransaction() val messageListFragment = MessageListFragment.newInstance(search, false, K9.isThreadedViewEnabled) openFolderTransaction.replace(R.id.message_list_container, messageListFragment) this.messageListFragment = messageListFragment this.openFolderTransaction = openFolderTransaction } protected open val isDrawerEnabled: Boolean = true override fun dispatchKeyEvent(event: KeyEvent): Boolean { var eventHandled = false if (event.action == KeyEvent.ACTION_DOWN && isSearchViewCollapsed()) { eventHandled = onCustomKeyDown(event) } if (!eventHandled) { eventHandled = super.dispatchKeyEvent(event) } return eventHandled } override fun onBackPressed() { if (isDrawerEnabled && drawer!!.isOpen) { drawer!!.close() } else if (displayMode == DisplayMode.MESSAGE_VIEW) { if (messageViewOnly) { finish() } else { showMessageList() } } else if (!isSearchViewCollapsed()) { collapseSearchView() } else { if (isDrawerEnabled && account != null && supportFragmentManager.backStackEntryCount == 0) { if (K9.isShowUnifiedInbox) { if (search!!.id != SearchAccount.UNIFIED_INBOX) { openUnifiedInbox() } else { super.onBackPressed() } } else { val defaultFolderId = defaultFolderProvider.getDefaultFolder(account!!) val currentFolder = if (singleFolderMode) search!!.folderIds[0] else null if (currentFolder == null || defaultFolderId != currentFolder) { openFolderImmediately(defaultFolderId) } else { super.onBackPressed() } } } else { super.onBackPressed() } } } /** * Handle hotkeys * * This method is called by [.dispatchKeyEvent] before any view had the chance to consume this key event. * * @return `true` if this event was consumed. */ private fun onCustomKeyDown(event: KeyEvent): Boolean { if (!event.hasNoModifiers()) return false when (event.keyCode) { KeyEvent.KEYCODE_VOLUME_UP -> { if (messageViewContainerFragment != null && displayMode != DisplayMode.MESSAGE_LIST && K9.isUseVolumeKeysForNavigation ) { showPreviousMessage() return true } } KeyEvent.KEYCODE_VOLUME_DOWN -> { if (messageViewContainerFragment != null && displayMode != DisplayMode.MESSAGE_LIST && K9.isUseVolumeKeysForNavigation ) { showNextMessage() return true } } KeyEvent.KEYCODE_DEL -> { onDeleteHotKey() return true } KeyEvent.KEYCODE_DPAD_LEFT -> { return if (messageViewContainerFragment != null && displayMode == DisplayMode.MESSAGE_VIEW) { showPreviousMessage() } else { false } } KeyEvent.KEYCODE_DPAD_RIGHT -> { return if (messageViewContainerFragment != null && displayMode == DisplayMode.MESSAGE_VIEW) { showNextMessage() } else { false } } } when (if (event.unicodeChar != 0) event.unicodeChar.toChar() else null) { 'c' -> { messageListFragment!!.onCompose() return true } 'o' -> { messageListFragment!!.onCycleSort() return true } 'i' -> { messageListFragment!!.onReverseSort() return true } 'd' -> { onDeleteHotKey() return true } 's' -> { messageListFragment!!.toggleMessageSelect() return true } 'g' -> { if (displayMode == DisplayMode.MESSAGE_LIST) { messageListFragment!!.onToggleFlagged() } else if (messageViewContainerFragment != null) { messageViewContainerFragment!!.onToggleFlagged() } return true } 'm' -> { if (displayMode == DisplayMode.MESSAGE_LIST) { messageListFragment!!.onMove() } else if (messageViewContainerFragment != null) { messageViewContainerFragment!!.onMove() } return true } 'v' -> { if (displayMode == DisplayMode.MESSAGE_LIST) { messageListFragment!!.onArchive() } else if (messageViewContainerFragment != null) { messageViewContainerFragment!!.onArchive() } return true } 'y' -> { if (displayMode == DisplayMode.MESSAGE_LIST) { messageListFragment!!.onCopy() } else if (messageViewContainerFragment != null) { messageViewContainerFragment!!.onCopy() } return true } 'z' -> { if (displayMode == DisplayMode.MESSAGE_LIST) { messageListFragment!!.onToggleRead() } else if (messageViewContainerFragment != null) { messageViewContainerFragment!!.onToggleRead() } return true } 'f' -> { if (messageViewContainerFragment != null) { messageViewContainerFragment!!.onForward() } return true } 'a' -> { if (messageViewContainerFragment != null) { messageViewContainerFragment!!.onReplyAll() } return true } 'r' -> { if (messageViewContainerFragment != null) { messageViewContainerFragment!!.onReply() } return true } 'j', 'p' -> { if (messageViewContainerFragment != null) { showPreviousMessage() } return true } 'n', 'k' -> { if (messageViewContainerFragment != null) { showNextMessage() } return true } } return false } private fun onDeleteHotKey() { if (displayMode == DisplayMode.MESSAGE_LIST) { messageListFragment!!.onDelete() } else if (messageViewContainerFragment != null) { messageViewContainerFragment!!.onDelete() } } override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean { // Swallow these events too to avoid the audible notification of a volume change if (K9.isUseVolumeKeysForNavigation) { if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { Timber.v("Swallowed key up.") return true } } return super.onKeyUp(keyCode, event) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { if (displayMode != DisplayMode.MESSAGE_VIEW && !isAdditionalMessageListDisplayed) { if (isDrawerEnabled) { if (drawer!!.isOpen) { drawer!!.close() } else { drawer!!.open() } } else { finish() } } else { goBack() } return true } return super.onOptionsItemSelected(item) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.message_list_option, menu) val searchItem = menu.findItem(R.id.search) initializeSearchMenuItem(searchItem) return true } private fun initializeSearchMenuItem(searchItem: MenuItem) { // Reuse existing SearchView if available searchView?.let { searchView -> searchItem.actionView = searchView return } val searchView = searchItem.actionView as SearchView searchView.maxWidth = Int.MAX_VALUE searchView.queryHint = resources.getString(R.string.search_action) val searchManager = getSystemService(SEARCH_SERVICE) as SearchManager searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName)) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { messageListFragment?.onSearchRequested(query) collapseSearchView() return true } override fun onQueryTextChange(s: String): Boolean { return false } }) searchView.setQuery(initialSearchViewQuery, false) searchView.isIconified = initialSearchViewIconified this.searchView = searchView } private fun isSearchViewCollapsed(): Boolean = searchView?.isIconified == true private fun collapseSearchView() { searchView?.let { searchView -> searchView.setQuery(null, false) searchView.isIconified = true } } fun setActionBarTitle(title: String, subtitle: String? = null) { actionBar.title = title actionBar.subtitle = subtitle } override fun setMessageListTitle(title: String, subtitle: String?) { if (displayMode != DisplayMode.MESSAGE_VIEW) { setActionBarTitle(title, subtitle) } } override fun setMessageListProgressEnabled(enable: Boolean) { progressBar!!.visibility = if (enable) View.VISIBLE else View.INVISIBLE } override fun setMessageListProgress(level: Int) { progressBar!!.progress = level } override fun openMessage(messageReference: MessageReference) { val account = preferences.getAccount(messageReference.accountUuid) ?: error("Account not found") val folderId = messageReference.folderId val draftsFolderId = account.draftsFolderId if (draftsFolderId != null && folderId == draftsFolderId) { MessageActions.actionEditDraft(this, messageReference) } else { val fragment = MessageViewContainerFragment.newInstance(messageReference) supportFragmentManager.commitNow { replace(R.id.message_view_container, fragment, FRAGMENT_TAG_MESSAGE_VIEW_CONTAINER) } messageViewContainerFragment = fragment messageListFragment?.let { messageListFragment -> fragment.setViewModel(messageListFragment.viewModel) } if (displayMode == DisplayMode.SPLIT_VIEW) { fragment.isActive = true } else { showMessageView() } } collapseSearchView() } override fun onForward(messageReference: MessageReference, decryptionResultForReply: Parcelable?) { MessageActions.actionForward(this, messageReference, decryptionResultForReply) } override fun onForwardAsAttachment(messageReference: MessageReference, decryptionResultForReply: Parcelable?) { MessageActions.actionForwardAsAttachment(this, messageReference, decryptionResultForReply) } override fun onEditAsNewMessage(messageReference: MessageReference) { MessageActions.actionEditDraft(this, messageReference) } override fun onReply(messageReference: MessageReference, decryptionResultForReply: Parcelable?) { MessageActions.actionReply(this, messageReference, false, decryptionResultForReply) } override fun onReplyAll(messageReference: MessageReference, decryptionResultForReply: Parcelable?) { MessageActions.actionReply(this, messageReference, true, decryptionResultForReply) } override fun onCompose(account: Account?) { MessageActions.actionCompose(this, account) } override fun onBackStackChanged() { findFragments() messageListFragment?.isActive = true if (isDrawerEnabled && !isAdditionalMessageListDisplayed) { unlockDrawer() } if (displayMode == DisplayMode.SPLIT_VIEW) { showMessageViewPlaceHolder() } } private fun addMessageListFragment(fragment: MessageListFragment) { messageListFragment?.isActive = false supportFragmentManager.commit { replace(R.id.message_list_container, fragment) setReorderingAllowed(true) if (supportFragmentManager.backStackEntryCount == 0) { addToBackStack(FIRST_FRAGMENT_TRANSACTION) } else { addToBackStack(null) } } messageListFragment = fragment fragment.isActive = true if (isDrawerEnabled) { lockDrawer() } } override fun startSearch(query: String, account: Account?, folderId: Long?): Boolean { // If this search was started from a MessageList of a single folder, pass along that folder info // so that we can enable remote search. val appData = if (account != null && folderId != null) { Bundle().apply { putString(EXTRA_SEARCH_ACCOUNT, account.uuid) putLong(EXTRA_SEARCH_FOLDER, folderId) } } else { // TODO Handle the case where we're searching from within a search result. null } val searchIntent = Intent(this, Search::class.java).apply { action = Intent.ACTION_SEARCH putExtra(SearchManager.QUERY, query) putExtra(SearchManager.APP_DATA, appData) } startActivity(searchIntent) return true } override fun startSupportActionMode(callback: ActionMode.Callback): ActionMode? { collapseSearchView() return super.startSupportActionMode(callback) } override fun showThread(account: Account, threadRootId: Long) { showMessageViewPlaceHolder() val tmpSearch = LocalSearch().apply { addAccountUuid(account.uuid) and(SearchField.THREAD_ID, threadRootId.toString(), SearchSpecification.Attribute.EQUALS) } initializeFromLocalSearch(tmpSearch) val fragment = MessageListFragment.newInstance(tmpSearch, true, false) addMessageListFragment(fragment) } private fun showMessageViewPlaceHolder() { removeMessageViewContainerFragment() // Add placeholder fragment if necessary val fragmentManager = supportFragmentManager if (fragmentManager.findFragmentByTag(FRAGMENT_TAG_PLACEHOLDER) == null) { val fragmentTransaction = fragmentManager.beginTransaction() fragmentTransaction.replace(R.id.message_view_container, messageViewPlaceHolder!!, FRAGMENT_TAG_PLACEHOLDER) fragmentTransaction.commit() } messageListFragment!!.setActiveMessage(null) } private fun removeMessageViewContainerFragment() { if (messageViewContainerFragment != null) { val fragmentTransaction = supportFragmentManager.beginTransaction() fragmentTransaction.remove(messageViewContainerFragment!!) messageViewContainerFragment = null fragmentTransaction.commit() showDefaultTitleView() } } private fun removeMessageListFragment() { val fragmentTransaction = supportFragmentManager.beginTransaction() fragmentTransaction.remove(messageListFragment!!) messageListFragment = null fragmentTransaction.commit() } override fun goBack() { val fragmentManager = supportFragmentManager when { displayMode == DisplayMode.MESSAGE_VIEW -> showMessageList() fragmentManager.backStackEntryCount > 0 -> fragmentManager.popBackStack() else -> finish() } } override fun closeMessageView() { returnToMessageList() } override fun setActiveMessage(messageReference: MessageReference) { val messageListFragment = checkNotNull(messageListFragment) messageListFragment.setActiveMessage(messageReference) } override fun showNextMessageOrReturn() { if (K9.isMessageViewReturnToList || !showLogicalNextMessage()) { returnToMessageList() } } private fun returnToMessageList() { if (displayMode == DisplayMode.SPLIT_VIEW) { showMessageViewPlaceHolder() } else { showMessageList() } } private fun showLogicalNextMessage(): Boolean { val couldMoveInLastDirection = when (lastDirection) { Direction.NEXT -> showNextMessage() Direction.PREVIOUS -> showPreviousMessage() } return if (couldMoveInLastDirection) { true } else { showNextMessage() || showPreviousMessage() } } override fun setProgress(enable: Boolean) { setProgressBarIndeterminateVisibility(enable) } private fun showNextMessage(): Boolean { val messageViewContainerFragment = checkNotNull(messageViewContainerFragment) return messageViewContainerFragment.showNextMessage() } private fun showPreviousMessage(): Boolean { val messageViewContainerFragment = checkNotNull(messageViewContainerFragment) return messageViewContainerFragment.showPreviousMessage() } private fun showMessageList() { messageViewOnly = false messageListWasDisplayed = true displayMode = DisplayMode.MESSAGE_LIST viewSwitcher!!.showFirstView() messageViewContainerFragment?.isActive = false messageListFragment!!.isActive = true messageListFragment!!.setActiveMessage(null) setDrawerLockState() showDefaultTitleView() onMessageListDisplayed() } private fun setDrawerLockState() { if (!isDrawerEnabled) return if (isAdditionalMessageListDisplayed) { lockDrawer() } else { unlockDrawer() } } private fun showMessageView() { val messageViewContainerFragment = checkNotNull(this.messageViewContainerFragment) displayMode = DisplayMode.MESSAGE_VIEW messageListFragment?.isActive = false messageViewContainerFragment.isActive = true if (!messageListWasDisplayed) { viewSwitcher!!.animateFirstView = false } viewSwitcher!!.showSecondView() if (isDrawerEnabled) { lockDrawer() } showMessageTitleView() } private fun showDefaultTitleView() { if (messageListFragment != null) { messageListFragment!!.updateTitle() } } private fun showMessageTitleView() { setActionBarTitle("") } override fun onSwitchComplete(displayedChild: Int) { if (displayedChild == 0) { removeMessageViewContainerFragment() } } private fun onMessageListDisplayed() { clearNotifications() } private fun clearNotifications() { messagingController.clearNotifications(search) } override fun startIntentSenderForResult( intent: IntentSender, requestCode: Int, fillInIntent: Intent?, flagsMask: Int, flagsValues: Int, extraFlags: Int ) { // If any of the high 16 bits are set it is not one of our request codes if (requestCode and REQUEST_CODE_MASK != 0) { super.startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags) return } val modifiedRequestCode = requestCode or REQUEST_FLAG_PENDING_INTENT super.startIntentSenderForResult(intent, modifiedRequestCode, fillInIntent, flagsMask, flagsValues, extraFlags) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // If any of the high 16 bits are set it is not one of our request codes if (requestCode and REQUEST_CODE_MASK != 0) return if (requestCode and REQUEST_FLAG_PENDING_INTENT != 0) { val originalRequestCode = requestCode xor REQUEST_FLAG_PENDING_INTENT if (messageViewContainerFragment != null) { messageViewContainerFragment!!.onPendingIntentResult(originalRequestCode, resultCode, data) } } } private val isAdditionalMessageListDisplayed: Boolean get() = supportFragmentManager.backStackEntryCount > 0 private fun lockDrawer() { drawer!!.lock() actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back) } private fun unlockDrawer() { drawer!!.unlock() actionBar.setHomeAsUpIndicator(R.drawable.ic_menu) } private fun initializeFromLocalSearch(search: LocalSearch?) { this.search = search singleFolderMode = false if (!search!!.searchAllAccounts()) { val accountUuids = search.accountUuids if (accountUuids.size == 1) { account = preferences.getAccount(accountUuids[0]) val folderIds = search.folderIds singleFolderMode = folderIds.size == 1 } else { account = null } } configureDrawer() } private fun LocalSearch.firstAccount(): Account? { return if (searchAllAccounts()) { preferences.defaultAccount } else { val accountUuid = accountUuids.first() preferences.getAccount(accountUuid) } } private fun MessageReference.toLocalSearch(): LocalSearch { return LocalSearch().apply { addAccountUuid(accountUuid) addAllowedFolder(folderId) } } private fun configureDrawer() { val drawer = drawer ?: return drawer.selectAccount(account!!.uuid) when { singleFolderMode -> drawer.selectFolder(search!!.folderIds[0]) // Don't select any item in the drawer because the Unified Inbox is displayed, but not listed in the drawer search!!.id == SearchAccount.UNIFIED_INBOX && !K9.isShowUnifiedInbox -> drawer.deselect() search!!.id == SearchAccount.UNIFIED_INBOX -> drawer.selectUnifiedInbox() else -> drawer.deselect() } } override fun hasPermission(permission: Permission): Boolean { return permissionUiHelper.hasPermission(permission) } override fun requestPermissionOrShowRationale(permission: Permission) { permissionUiHelper.requestPermissionOrShowRationale(permission) } override fun requestPermission(permission: Permission) { permissionUiHelper.requestPermission(permission) } override fun onFolderNotFoundError() { val defaultFolderId = defaultFolderProvider.getDefaultFolder(account!!) openFolderImmediately(defaultFolderId) } private enum class DisplayMode { MESSAGE_LIST, MESSAGE_VIEW, SPLIT_VIEW } private class LaunchData( val search: LocalSearch, val account: Account? = null, val messageReference: MessageReference? = null, val noThreading: Boolean = false, val messageViewOnly: Boolean = false ) companion object : KoinComponent { private const val EXTRA_SEARCH = "search_bytes" private const val EXTRA_NO_THREADING = "no_threading" private const val ACTION_SHORTCUT = "shortcut" private const val EXTRA_SPECIAL_FOLDER = "special_folder" private const val EXTRA_ACCOUNT = "account_uuid" private const val EXTRA_MESSAGE_REFERENCE = "message_reference" private const val EXTRA_MESSAGE_VIEW_ONLY = "message_view_only" // used for remote search const val EXTRA_SEARCH_ACCOUNT = "com.fsck.k9.search_account" private const val EXTRA_SEARCH_FOLDER = "com.fsck.k9.search_folder" private const val STATE_DISPLAY_MODE = "displayMode" private const val STATE_MESSAGE_VIEW_ONLY = "messageViewOnly" private const val STATE_MESSAGE_LIST_WAS_DISPLAYED = "messageListWasDisplayed" private const val STATE_SEARCH_VIEW_ICONIFIED = "searchViewIconified" private const val STATE_SEARCH_VIEW_QUERY = "searchViewQuery" private const val FIRST_FRAGMENT_TRANSACTION = "first" private const val FRAGMENT_TAG_MESSAGE_VIEW_CONTAINER = "MessageViewContainerFragment" private const val FRAGMENT_TAG_PLACEHOLDER = "MessageViewPlaceholder" private const val REQUEST_CODE_MASK = 0xFFFF0000.toInt() private const val REQUEST_FLAG_PENDING_INTENT = 1 shl 15 private val defaultFolderProvider: DefaultFolderProvider by inject() @JvmStatic @JvmOverloads fun actionDisplaySearch( context: Context, search: SearchSpecification?, noThreading: Boolean, newTask: Boolean, clearTop: Boolean = true ) { context.startActivity(intentDisplaySearch(context, search, noThreading, newTask, clearTop)) } @JvmStatic fun intentDisplaySearch( context: Context?, search: SearchSpecification?, noThreading: Boolean, newTask: Boolean, clearTop: Boolean ): Intent { return Intent(context, MessageList::class.java).apply { putExtra(EXTRA_SEARCH, ParcelableUtil.marshall(search)) putExtra(EXTRA_NO_THREADING, noThreading) addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) if (clearTop) addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) if (newTask) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } } fun createUnifiedInboxIntent(context: Context, account: Account): Intent { return Intent(context, MessageList::class.java).apply { val search = SearchAccount.createUnifiedInboxAccount().relatedSearch putExtra(EXTRA_ACCOUNT, account.uuid) putExtra(EXTRA_SEARCH, ParcelableUtil.marshall(search)) putExtra(EXTRA_NO_THREADING, false) addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } } fun createNewMessagesIntent(context: Context, account: Account): Intent { val search = LocalSearch().apply { id = SearchAccount.NEW_MESSAGES addAccountUuid(account.uuid) and(SearchField.NEW_MESSAGE, "1", SearchSpecification.Attribute.EQUALS) } return intentDisplaySearch(context, search, noThreading = false, newTask = true, clearTop = true) } @JvmStatic fun shortcutIntent(context: Context?, specialFolder: String?): Intent { return Intent(context, MessageList::class.java).apply { action = ACTION_SHORTCUT putExtra(EXTRA_SPECIAL_FOLDER, specialFolder) addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } } @JvmStatic fun shortcutIntentForAccount(context: Context?, account: Account): Intent { val folderId = defaultFolderProvider.getDefaultFolder(account) val search = LocalSearch().apply { addAccountUuid(account.uuid) addAllowedFolder(folderId) } return intentDisplaySearch(context, search, noThreading = false, newTask = true, clearTop = true) } fun actionDisplayMessageIntent( context: Context, messageReference: MessageReference, openInUnifiedInbox: Boolean = false, messageViewOnly: Boolean = false ): Intent { return actionDisplayMessageTemplateIntent(context, openInUnifiedInbox, messageViewOnly).apply { putExtra(EXTRA_MESSAGE_REFERENCE, messageReference.toIdentityString()) } } fun actionDisplayMessageTemplateIntent( context: Context, openInUnifiedInbox: Boolean, messageViewOnly: Boolean ): Intent { return Intent(context, MessageList::class.java).apply { if (openInUnifiedInbox) { val search = SearchAccount.createUnifiedInboxAccount().relatedSearch putExtra(EXTRA_SEARCH, ParcelableUtil.marshall(search)) } putExtra(EXTRA_MESSAGE_VIEW_ONLY, messageViewOnly) addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) } } fun actionDisplayMessageTemplateFillIntent(messageReference: MessageReference): Intent { return Intent().apply { putExtra(EXTRA_MESSAGE_REFERENCE, messageReference.toIdentityString()) } } @JvmStatic fun launch(context: Context) { val intent = Intent(context, MessageList::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) } context.startActivity(intent) } @JvmStatic fun launch(context: Context, account: Account) { val folderId = defaultFolderProvider.getDefaultFolder(account) val search = LocalSearch().apply { addAllowedFolder(folderId) addAccountUuid(account.uuid) } actionDisplaySearch(context, search, noThreading = false, newTask = false) } } }
apache-2.0
8a5b8695dcea7472b59524506d6c99f5
35.747604
122
0.633316
5.33785
false
false
false
false
rethumb/rethumb-examples
examples-resize-by-width-and-height/example-kotlin.kt
1
830
import java.io.FileOutputStream import java.net.URL import java.nio.channels.Channels object KotlinRethumbWidthHeightExample { @Throws(Exception::class) @JvmStatic fun main(args: Array<String>) { val paramOperation1 = "height" val paramValue1 = 100 // New height in pixels. val paramOperation2 = "width" val paramValue2 = 100 // New width in pixels. val imageURL = "http://images.rethumb.com/image_coimbra_600x300.jpg" val imageFilename = "resized-image.jpg" val url = URL(String.format("http://api.rethumb.com/v1/%s/%s/%s/%s/%s", paramOperation1, paramValue1, paramOperation2, paramValue2, imageURL)) val fos = FileOutputStream(imageFilename) fos.channel.transferFrom(Channels.newChannel(url.openStream()), 0, java.lang.Long.MAX_VALUE) } }
unlicense
caf7a65f8c14b435a1521c34b3417879
35.130435
150
0.690361
3.577586
false
false
false
false
newbieandroid/AppBase
app/src/main/java/com/fuyoul/sanwenseller/base/BaseAdapter.kt
1
5015
package com.fuyoul.sanwenseller.base import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.csl.refresh.SmartRefreshLayout import com.fuyoul.sanwenseller.bean.AdapterMultiItem import com.fuyoul.sanwenseller.bean.MultBaseBean import com.fuyoul.sanwenseller.configs.Code import com.fuyoul.sanwenseller.configs.Code.VIEWTYPE_EMPTY import com.zhy.autolayout.utils.AutoUtils /** * @author: chen * @CreatDate: 2017\10\26 0026 * @Desc: */ abstract class BaseAdapter(context: Context) : RecyclerView.Adapter<BaseViewHolder>() { private var context: Context? = null var datas = arrayListOf<MultBaseBean>()//数据 private var multiItems = ArrayList<AdapterMultiItem>()//多布局 init { this.datas = datas this.context = context addMultiType(multiItems) } override fun getItemCount(): Int = datas.size override fun getItemViewType(position: Int): Int = datas.get(position).itemType() override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): BaseViewHolder { var view: View? = null for (index in 0 until multiItems.size) { when (viewType) { multiItems[index].typeId -> { view = LayoutInflater.from(context).inflate(multiItems[index].typeLayoutRes, parent, false) AutoUtils.auto(view) if (viewType != Code.VIEWTYPE_EMPTY) { view.setOnClickListener { onItemClicked(view!!, view?.tag as Int) } } else { onEmpryLayou(view, multiItems[index].typeLayoutRes) } } } } return BaseViewHolder(view!!) } override fun onBindViewHolder(holder: BaseViewHolder, position: Int) { if (holder.itemViewType != Code.VIEWTYPE_EMPTY) { holder.itemView.tag = position convert(holder, position, datas) } } private fun <D : MultBaseBean> setNewData(newDatas: List<D>) { this.datas.clear() this.datas.addAll(newDatas) notifyDataSetChanged() } private fun <D : MultBaseBean> addData(addDatas: List<D>) { if (datas.isEmpty()) { setNewData(addDatas) } else { this.datas.addAll(addDatas) notifyItemRangeInserted(this.datas.size - addDatas.size, addDatas.size) } } /**更改某一条数据**/ fun changeData(item: MultBaseBean) { notifyItemChanged(datas.indexOf(item)) } fun changeData(position: Int) { notifyItemChanged(position) } /**移除某一条数据**/ fun remove(position: Int) { this.datas.removeAt(position) notifyItemRemoved(position) notifyItemRangeChanged(position, 1) } /**移除某一条数据**/ fun remove(item: MultBaseBean) { this.datas.remove(item) val index = this.datas.indexOf(item) notifyItemRemoved(index) notifyItemRangeChanged(index, 1) } /**这里用于显示空页面**/ fun setEmptyView(emptyLayourRes: Int) { this.datas.clear() datas.add(object : MultBaseBean { override fun itemType(): Int = VIEWTYPE_EMPTY }) val item = AdapterMultiItem(VIEWTYPE_EMPTY, emptyLayourRes) (0 until multiItems.size) .filter { multiItems[it].typeId == VIEWTYPE_EMPTY } .forEach { multiItems.removeAt(it) } multiItems.add(item) notifyDataSetChanged() } /**数据的操作**/ abstract fun convert(holder: BaseViewHolder, position: Int, allDatas: List<MultBaseBean>) /**添加布局**/ abstract fun addMultiType(multiItems: ArrayList<AdapterMultiItem>) /**item点击事件**/ abstract fun onItemClicked(view: View, position: Int) /**空数据页的点击事件**/ abstract fun onEmpryLayou(view: View, layoutResId: Int) abstract fun getSmartRefreshLayout(): SmartRefreshLayout abstract fun getRecyclerView(): RecyclerView /**控制刷新和加载更多是否可用**/ fun setRefreshAndLoadMoreEnable(isEnableLoadMore: Boolean) { getSmartRefreshLayout().isEnableLoadmore = isEnableLoadMore } /**增加或者刷新数据**/ fun <D : MultBaseBean> setData(isRefresh: Boolean, datas: List<D>) { if (isRefresh) { setNewData(datas) } else { addData(datas) } setRefreshAndLoadMoreEnable(true) } /**通过网络请求获取数据的状态来设置刷新控件的状态**/ fun setReqLayoutInfo(isRefresh: Boolean, isSuccess: Boolean) { if (isRefresh) { getSmartRefreshLayout().finishRefresh(isSuccess) } else { getSmartRefreshLayout().finishLoadmore(isSuccess) } } }
apache-2.0
a1b336e0427fe9ed6fb4e85ce0d56d8c
27.485207
111
0.62352
4.452359
false
false
false
false
Juuxel/ChatTime
server/src/main/kotlin/chattime/server/plugins/CommandPlugin.kt
1
9401
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package chattime.server.plugins import chattime.api.event.* import chattime.api.features.Commands import chattime.api.features.Commands.Command import chattime.api.net.Packet import chattime.common.Info import chattime.server.L10n class CommandPlugin : Commands { override val id = "Commands" private val mutCommands: ArrayList<Command> = arrayListOf( construct("help", Desc.help, CommandPlugin::help), construct("id", Desc.id, CommandPlugin::id), construct("rename", Desc.rename, CommandPlugin::rename), construct("plugins", Desc.plugins, CommandPlugin::plugins), construct("silent", Desc.silent, CommandPlugin::runSilently), construct("users", Desc.users, CommandPlugin::users), construct("pm", Desc.pm, CommandPlugin::pm), construct("who-is", Desc.whoIs, CommandPlugin::whoIs), construct("about", Desc.ctInfo, CommandPlugin::ctInfo), construct("kick", Desc.kick, CommandPlugin::kick) ) override val commands: List<Command> get() = mutCommands override fun load(event: PluginLoadEvent) { event.eventBus.subscribe(EventType.userJoin) { onUserJoin(it) } event.eventBus.subscribe(EventType.chatMessage) { onMessageReceived(it) } } private fun onUserJoin(event: UserJoinEvent) { val userList = listOf(event.user) event.server.sendMessage("%s%n%s".format(L10n["commands.start1"], L10n["commands.start2"]), whitelist = userList) } private fun onMessageReceived(event: MessageEvent) { if (event.msg.message.startsWith("!") && event.msg.message != "!") processCommand(event) } private fun processCommand(event: MessageEvent) { val commandName = Commands.getCommandParams(event.msg.message)[0] var commandFound = false val commandEvent = CommandEvent(event.server, commandName, event.msg, event.sender) // Fire the command event event.eventBus.post(commandEvent) // Check if canceled if (commandEvent.isCanceled) return // Handle the command mutCommands.forEach { if (it.name == commandName) { it.handleMessage(event) commandFound = true } } if (!commandFound) event.server.sendMessage(L10n["commands.commandNotFound", commandName], whitelist = listOf(event.sender)) } override fun addCommand(command: Commands.Command) { mutCommands += command } // UTILS // private fun pluginMessage(event: MessageEvent, cmd: String, msg: String) { event.sendMessageToSender("[Commands] $cmd: $msg") } private fun construct(name: String, desc: String, function: (CommandPlugin, MessageEvent) -> Unit) = Commands.construct(name, desc) { function(this, it) } // COMMANDS // private fun help(event: MessageEvent) { pluginMessage(event, "help", L10n["commands.help.all"]) commands.sortedBy { it.name } .joinToString(separator = "\n") { "- ${it.name}: ${it.description}" } .let(event::sendMessageToSender) } private fun id(event: MessageEvent) { val params = Commands.getCommandParams(event.msg.message, joinLastParam = true, lastParamIndex = 1) if (params.size > 1) { val userName = params[1] val users = event.server.users if (users.none { it.name.contains(userName, ignoreCase = true) }) pluginMessage(event, "id", L10n["commands.id.noUsersFound", userName]) else { pluginMessage(event, "id", L10n["commands.id.usersFound", userName]) users.filter { it.name.contains(userName, ignoreCase = true) }.forEach { event.sendMessageToSender("- ${it.name}: ${it.id}") } } } else pluginMessage(event, "id", event.sender.id) } private fun rename(event: MessageEvent) { val params = Commands.getCommandParams(event.msg.message, joinLastParam = true, lastParamIndex = 1) if (params.size == 1) pluginMessage(event, "rename", L10n["commands.rename.noNameGiven"]) else { val oldName = event.sender.name val newName = params[1] event.sender.name = newName event.server.sendMessage(L10n["commands.rename.renamed", oldName, newName]) } } private fun plugins(event: MessageEvent) { pluginMessage(event, "plugins", L10n["commands.plugins.all"]) event.server.plugins.sortedBy { it.id }.forEach { event.sendMessageToSender("- ${it.id}") } } private fun runSilently(event: MessageEvent) { val params = Commands.getCommandParams(event.msg.message, joinLastParam = true, lastParamIndex = 1) if (params.size == 1) { pluginMessage(event, "silent", "Usage: !silent <command>") return } processCommand(MessageEvent(event.server, Packet.Message(event.sender.id, "!${params[1]}"), event.sender)) event.cancel() } private fun users(event: MessageEvent) { pluginMessage(event, "users", L10n["commands.users.all"]) event.server.users.sortedBy { it.name }.forEach { event.sendMessageToSender("- ${it.name}") } } private fun pm(event: MessageEvent) { val params = Commands.getCommandParams(event.msg.message, joinLastParam = true, lastParamIndex = 2) if (params.size < 3) { pluginMessage(event, "pm", "Usage: !pm <user id> <msg>") return } val list = event.server.users.filter { it.id == params[1] } event.server.sendMessage("${event.sender.name} (PM): ${params[2]}", whitelist = list) event.cancel() } private fun whoIs(event: MessageEvent) { val params = Commands.getCommandParams(event.msg.message) if (params.size < 2) { pluginMessage(event, "who-is", "Usage: !who-is <user id>") return } try { val user = event.server.getUserById(params[1]).name event.sendMessageToSender(L10n["commands.who-is.message", params[1], user]) } catch (iae: IllegalArgumentException) { event.sendMessageToSender(iae.message ?: L10n["error.generic"]) } } private fun ctInfo(event: MessageEvent) { event.sendMessageToSender(""" ${Info.fullVersion} Made by Juuxel Licensed under MPL v2.0 See more info at ${Info.url} -=-=-=-=- Open Source Libraries: - picocli (https://github.com/remkop/picocli) - RxJava (https://github.com/ReactiveX/RxJava) - Klaxon (https://github.com/cbeust/klaxon) """.trimIndent()) } private fun kick(event: MessageEvent) { val params = Commands.getCommandParams(event.msg.message, joinLastParam = true, lastParamIndex = 2) if (params.size < 3) { pluginMessage(event, "kick", "Usage: !kick <user id> <msg>") return } try { event.server.getUserById(params[1]).kick() event.server.sendMessage(L10n["commands.kick.message", event.sender.name, params[2]], whitelist = listOf(event.server.getUserById(params[1]))) pluginMessage(event, "kick", L10n["commands.kick.kickerMessage", params[1]]) } catch (iae: IllegalArgumentException) { event.sendMessageToSender(iae.message ?: L10n["error.generic"]) } } object Desc // TODO Translate command desc { val attributes = "Manage user attributes" val ctInfo = L10n["commands.about.desc"] val help = "Shows information about commands" val id = "Shows user ids" val plugins = "Lists all plugins" val pm = L10n["commands.pm.desc"] val rename = "Rename yourself" val silent = "Debugs commands silently" val users = "Lists all users" val whoIs = "Shows the name of a user from an id" val kick = "Kick users from the chat" } }
mpl-2.0
962bd2744fec49863f6055f577dc14f0
32.695341
121
0.548027
4.537162
false
false
false
false
Quireg/AnotherMovieApp
app/src/main/java/com/anothermovieapp/repository/RepositoryFavoritesListImpl.kt
1
1393
/* * Created by Arcturus Mengsk * 2021. */ package com.anothermovieapp.repository import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.* import javax.inject.Inject class RepositoryFavoritesListImpl @Inject constructor( var db: Database, ) : RepositoryFavoritesList { override suspend fun getFavoriteMovies(): Flow<List<EntityDBMovie>> { return flow { db.movieFavoriteDao().get().collect { emit(it.map { fav -> db.movieDao().get().findLast { it.id == fav.id.toLong() }!! }) } } } override suspend fun remove(id: Long) { db.movieFavoriteDao().remove(EntityDBFavoriteMovie(id.toString())) } override suspend fun add(id: Long) { db.movieFavoriteDao().insert(EntityDBFavoriteMovie(id.toString())) } override suspend fun addOrRemove(id: Long) { val favMovie = db.movieFavoriteDao().get().first().find { it.id.toLong() == id } if (favMovie == null) { db.movieFavoriteDao().insert(EntityDBFavoriteMovie(id.toString())) } else { db.movieFavoriteDao().remove(favMovie) } } override suspend fun isFavourite(id: Long): Flow<Boolean> { return flow { db.movieFavoriteDao().get().collect { emit(it.find { it.id.toLong() == id } != null) } } } }
mit
f050614e6e8beeb5cdcf490a20899896
26.88
99
0.60804
4.085044
false
false
false
false
MichaelRocks/lightsaber
processor/src/main/java/io/michaelrocks/lightsaber/processor/analysis/FactoriesAnalyzer.kt
1
6912
/* * Copyright 2020 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.lightsaber.processor.analysis import io.michaelrocks.grip.Grip import io.michaelrocks.grip.and import io.michaelrocks.grip.annotatedWith import io.michaelrocks.grip.classes import io.michaelrocks.grip.from import io.michaelrocks.grip.isConstructor import io.michaelrocks.grip.methods import io.michaelrocks.grip.mirrors.ClassMirror import io.michaelrocks.grip.mirrors.MethodMirror import io.michaelrocks.grip.mirrors.Type import io.michaelrocks.grip.mirrors.getObjectTypeByInternalName import io.michaelrocks.grip.mirrors.signature.GenericType import io.michaelrocks.lightsaber.Factory.Return import io.michaelrocks.lightsaber.processor.ErrorReporter import io.michaelrocks.lightsaber.processor.commons.Types import io.michaelrocks.lightsaber.processor.commons.associateByIndexedTo import io.michaelrocks.lightsaber.processor.commons.boxed import io.michaelrocks.lightsaber.processor.model.Dependency import io.michaelrocks.lightsaber.processor.model.Factory import io.michaelrocks.lightsaber.processor.model.FactoryInjectee import io.michaelrocks.lightsaber.processor.model.FactoryInjectionPoint import io.michaelrocks.lightsaber.processor.model.FactoryProvisionPoint import io.michaelrocks.lightsaber.processor.model.Injectee import io.michaelrocks.lightsaber.processor.model.InjectionPoint import java.io.File interface FactoriesAnalyzer { fun analyze(files: Collection<File>): Collection<Factory> } class FactoriesAnalyzerImpl( private val grip: Grip, private val analyzerHelper: AnalyzerHelper, private val errorReporter: ErrorReporter, private val projectName: String ) : FactoriesAnalyzer { override fun analyze(files: Collection<File>): Collection<Factory> { val factoriesQuery = grip select classes from files where annotatedWith(Types.FACTORY_TYPE) return factoriesQuery.execute().classes.mapNotNull { maybeCreateFactory(it) } } private fun maybeCreateFactory(mirror: ClassMirror): Factory? { val provisionPoints = mirror.methods.mapNotNull { maybeCreateFactoryProvisionPoint(mirror, it) } if (provisionPoints.isEmpty()) { return null } val implementationType = getObjectTypeByInternalName(mirror.type.internalName + "\$Lightsaber\$Factory\$$projectName") val qualifier = analyzerHelper.findQualifier(mirror) val dependency = Dependency(GenericType.Raw(mirror.type), qualifier) return Factory(mirror.type, implementationType, dependency, provisionPoints) } private fun maybeCreateFactoryProvisionPoint(mirror: ClassMirror, method: MethodMirror): FactoryProvisionPoint? { val returnType = tryExtractReturnTypeFromFactoryMethod(mirror, method) ?: return null val dependencyMirror = grip.classRegistry.getClassMirror(returnType) val dependencyConstructorsQuery = grip select methods from dependencyMirror where (isConstructor() and annotatedWith(Types.FACTORY_INJECT_TYPE)) val dependencyConstructors = dependencyConstructorsQuery.execute().values.singleOrNull().orEmpty() if (dependencyConstructors.isEmpty()) { error("Class ${dependencyMirror.type.className} must have a constructor annotated with @Factory.Inject") return null } if (dependencyConstructors.size != 1) { error("Class ${dependencyMirror.type.className} must have a single constructor annotated with @Factory.Inject") return null } val methodInjectionPoint = analyzerHelper.convertToInjectionPoint(method, mirror.type) validateNoDuplicateInjectees(methodInjectionPoint) val argumentIndexToInjecteeMap = methodInjectionPoint.injectees.associateByIndexedTo( HashMap(), keySelector = { _, injectee -> injectee }, valueSelector = { index, _ -> index } ) val constructor = dependencyConstructors.single() val constructorInjectionPoint = analyzerHelper.convertToInjectionPoint(constructor, mirror.type) val factoryInjectees = constructorInjectionPoint.injectees.mapNotNull { injectee -> if (Types.FACTORY_PARAMETER_TYPE in injectee.annotations) { val argumentIndex = argumentIndexToInjecteeMap[injectee] if (argumentIndex == null) { val dependencyClassName = dependencyMirror.type.className val factoryClassName = mirror.type.className error("Class $dependencyClassName contains a @Factory.Parameter not provided by factory $factoryClassName: ${injectee.dependency}") null } else { FactoryInjectee.FromMethod(injectee, argumentIndex) } } else { FactoryInjectee.FromInjector(injectee) } } val factoryInjectionPoint = FactoryInjectionPoint(returnType, constructor, factoryInjectees) return FactoryProvisionPoint(mirror.type, method, factoryInjectionPoint) } private fun tryExtractReturnTypeFromFactoryMethod(mirror: ClassMirror, method: MethodMirror): Type.Object? { val returnAnnotation = method.annotations[Types.FACTORY_RETURN_TYPE] if (returnAnnotation != null) { val returnType = returnAnnotation.values[Return::value.name] if (returnType !is Type) { error("Method ${mirror.type.className}.${method.name} is annotated with @Factory.Return that has a wrong parameter $returnType") return null } if (returnType !is Type.Object) { error("Method ${mirror.type.className}.${method.name} is annotated with @Factory.Return with ${returnType.className} value, but its value must be a class") return null } return returnType } val returnType = method.type.returnType if (returnType !is Type.Object) { error("Method ${mirror.type.className}.${method.name} returns ${returnType.className}, but must return a class") return null } return returnType } private fun validateNoDuplicateInjectees(injectionPoint: InjectionPoint.Method) { val visitedInjectees = hashSetOf<Injectee>() injectionPoint.injectees.forEach { injectee -> if (!visitedInjectees.add(injectee.boxed())) { val className = injectionPoint.containerType.className val methodName = injectionPoint.method.name error("Method $className.$methodName accepts $injectee multiple times") } } } private fun error(message: String) { errorReporter.reportError(message) } }
apache-2.0
ac3f09d452157395aeca347c1854e4bb
41.146341
163
0.76114
4.692464
false
false
false
false
christophpickl/gadsu
src/test/kotlin/at/cpickl/gadsu/appointment/gcal/sync/SyncServiceIT.kt
1
3118
package at.cpickl.gadsu.appointment.gcal.sync import at.cpickl.gadsu.appointment.AppointmentService import at.cpickl.gadsu.appointment.gcal.testInstance import at.cpickl.gadsu.client.Client import at.cpickl.gadsu.client.ClientService import at.cpickl.gadsu.client.Contact import at.cpickl.gadsu.mail.Mail import at.cpickl.gadsu.mail.MailSender import at.cpickl.gadsu.preferences.Prefs import at.cpickl.gadsu.service.Clock import at.cpickl.gadsu.testinfra.TestBusListener import at.cpickl.gadsu.testinfra.initTestGuice import at.cpickl.gadsu.testinfra.unsavedValidInstance import com.google.common.eventbus.EventBus import com.google.inject.testing.fieldbinder.Bind import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.hasSize import org.joda.time.DateTime import org.mockito.Mockito.* import org.testng.annotations.BeforeMethod import org.testng.annotations.Test import javax.inject.Inject @Test(groups = arrayOf("integration", "guice")) class SyncServiceIT { private lateinit var busListener: TestBusListener @Inject private lateinit var bus: EventBus @Inject private lateinit var clientService: ClientService @Inject private lateinit var appointmentService: AppointmentService @Inject private lateinit var syncService: SyncService @Inject private lateinit var prefs: Prefs @Inject private lateinit var clock: Clock @Bind private lateinit var mockMailSender: MailSender private val templateSubject = "test subject" private val templateBody = "test body" private lateinit var appointmentDate: DateTime private lateinit var client: Client @BeforeMethod fun init() { busListener = TestBusListener() mockMailSender = mock(MailSender::class.java) initTestGuice(this) bus.register(busListener) appointmentDate = clock.now().plusDays(1) client = clientService.insertOrUpdate(Client.unsavedValidInstance().copy( contact = Contact.EMPTY.copy(mail = "[email protected]") )) prefs.preferencesData = prefs.preferencesData.copy( templateConfirmSubject = templateSubject, templateConfirmBody = templateBody ) } fun `import single new appointment with sending confirmation`() { syncService.import(listOf( ImportAppointment.testInstance(client, appointmentDate, sendConfirmation = true) )) assertThat(appointmentService.findAllFutureFor(client), hasSize(1)) verify(mockMailSender).send(Mail( recipient = client.contact.mail, subject = templateSubject, body = templateBody, recipientsAsBcc = false)) verifyNoMoreInteractions(mockMailSender) } fun `import single new appointment without sending confirmation`() { syncService.import(listOf( ImportAppointment.testInstance(client, appointmentDate, sendConfirmation = false) )) assertThat(appointmentService.findAllFutureFor(client), hasSize(1)) verifyNoMoreInteractions(mockMailSender) } }
apache-2.0
c0d0d5a33e6aa4b4d3531a4ac1411d90
35.255814
97
0.732842
4.70997
false
true
false
false
luoyuan800/NeverEnd
dataModel/src/cn/luo/yuan/maze/model/goods/types/Grill.kt
1
2230
package cn.luo.yuan.maze.model.goods.types import cn.luo.yuan.maze.model.Parameter import cn.luo.yuan.maze.model.goods.BatchUseGoods import cn.luo.yuan.maze.model.goods.GoodsProperties import cn.luo.yuan.maze.model.goods.UsableGoods import cn.luo.yuan.maze.service.InfoControlInterface import cn.luo.yuan.maze.service.RangePropertiesHelper import cn.luo.yuan.maze.utils.Field /** * * Created by luoyuan on 2017/7/16. */ class Grill() : UsableGoods(), BatchUseGoods { companion object { private const val serialVersionUID: Long = Field.SERVER_VERSION } override fun perform(properties: GoodsProperties): Boolean { var count = properties[Parameter.COUNT] as Int var msg = "" val context = properties["context"] as InfoControlInterface while (getCount() >= count && count > 0) { count -= 1 var desc = "没有任何作用!" val random = context.random val hero = properties.hero val index = random.nextInt(10) var value: Long when (index) { 0 -> { value = random.nextLong(hero.str / 50000) + 1 if (value > 100) { value = random.nextLong(100) } desc = "吃到了带血丝的烤肉,力量增加了$value。但是要小心寄生虫感染哦!" RangePropertiesHelper.addStr(value,context) } 1 -> { value = random.nextLong(hero.agi / 20000) + 1 desc = "吃到了烤焦的烤肉,黑暗属性的烤肉导致你的体内发生了变异,敏捷增加了$value。记得多备纸巾随时准备上厕所!" if (value > 100) { value = random.nextLong(100) } RangePropertiesHelper.addAgi(value, context) } } msg += desc + "<br>" } context.showPopup(msg) return true } override var desc: String = "一团黑乎乎的烤肉,不知道是什么味道。" override var name: String = "烤肉" override var price = 10000L }
bsd-3-clause
068608a5743e45ac6443aeac4ac890bd
33.913793
83
0.5583
3.620751
false
false
false
false
skydoves/WaterDrink
app/src/main/java/com/skydoves/waterdays/persistence/preference/PreferenceKeys.kt
1
1114
/* * Copyright (C) 2016 skydoves * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.skydoves.waterdays.persistence.preference import android.util.Pair /** * Developed by skydoves on 2017-08-19. * Copyright (c) 2017 skydoves rights reserved. */ object PreferenceKeys { val NEWBE = Pair("NEWBE", true) val INIT_CAPACITY = Pair("INIT_CAPACITY", false) val WATER_GOAL = Pair("WaterGoal", "2000") val LOCALINDEX = Pair("localIndex", 0) val CUP_CAPICITY = Pair("MyCup", "0") val ALARM_WEAHTER = Pair("setWeatherAlarm", false) val BUBBLE_COLOR = Pair("BUBBLE_COLOR", "#1c9ade") }
apache-2.0
eb460ee8ca35946fefb004c3ca92955c
31.764706
75
0.721724
3.664474
false
false
false
false
marvec/engine
lumeer-core/src/test/kotlin/io/lumeer/core/util/CronTaskCheckerTest.kt
2
9422
package io.lumeer.core.util import io.lumeer.api.model.Rule import io.lumeer.api.model.rule.CronRule import io.lumeer.engine.api.data.DataDocument import org.assertj.core.api.Assertions import org.junit.Test import java.time.DayOfWeek import java.time.ZonedDateTime import java.time.temporal.ChronoField import java.time.temporal.ChronoUnit import kotlin.math.pow class CronTaskCheckerTest { private val checker = CronTaskChecker() @Test fun checkRunningRule() { val (rule, now) = createRunningRuleData() Assertions.assertThat(checker.shouldExecute(rule, now)).isTrue } @Test fun checkInvalidCronUnit() { val (rule, now) = createRunningRuleData() rule.unit = ChronoUnit.DECADES Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse } @Test fun checkCronBeforeStartsOn() { val (rule, now) = createRunningRuleData() rule.startsOn = now.plusDays(2) Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse } @Test fun checkCronAfterEndsOn() { val (rule, now) = createRunningRuleData() rule.endsOn = now.minusDays(2) Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse } @Test fun checkCronExecutionsLeft() { val (rule, now) = createRunningRuleData() rule.executionsLeft = 2 Assertions.assertThat(checker.shouldExecute(rule, now)).isTrue rule.executionsLeft = 0 Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse } @Test fun checkDailyCronCreatedAfterAndBeforeHour() { val createdAt = CronTaskChecker.now().withHour(15) val rule = createRule(createdAt) rule.unit = ChronoUnit.DAYS rule.hour = 14 rule.interval = 2 rule.startsOn = CronTaskChecker.now().minusDays(10) // created at after execution val now = CronTaskChecker.now().withHour(14).truncatedTo(ChronoUnit.HOURS) Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse // created at before execution rule.rule.createdAt = createdAt.withHour(13) Assertions.assertThat(checker.shouldExecute(rule, now)).isTrue } @Test fun checkDailyCronAfterSomeExecution() { val now = CronTaskChecker.now().withHour(18).withMinute(20) val rule = createRule() rule.unit = ChronoUnit.DAYS rule.hour = 18 rule.interval = 2 rule.startsOn = now.minusDays(10) rule.lastRun = now.minusDays(1) Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse rule.lastRun = now.minusDays(2) Assertions.assertThat(checker.shouldExecute(rule, now)).isTrue // check with delay rule.lastRun = now.minusDays(2).plusSeconds(23) Assertions.assertThat(checker.shouldExecute(rule, now)).isTrue rule.lastRun = now.minusDays(2).plusMinutes(30) Assertions.assertThat(checker.shouldExecute(rule, now)).isTrue rule.lastRun = now.minusDays(2).plusHours(1) Assertions.assertThat(checker.shouldExecute(rule, now)).isTrue } @Test fun checkMonthlyCronCreatedAfterAndBeforeHour() { val createdAt = CronTaskChecker.now().withDayOfMonth(12).withHour(10) val rule = createRule(createdAt) rule.unit = ChronoUnit.MONTHS rule.hour = 9 rule.occurrence = 12 rule.interval = 3 rule.startsOn = CronTaskChecker.now().withDayOfMonth(12).minusDays(10) // created at after execution val now = CronTaskChecker.now().withDayOfMonth(12).withHour(9).truncatedTo(ChronoUnit.HOURS) Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse // created at before execution rule.rule.createdAt = createdAt.withHour(8) Assertions.assertThat(checker.shouldExecute(rule, now)).isTrue } @Test fun checkMonthlyCronOtherDay() { val createdAt = CronTaskChecker.now().withDayOfMonth(1).withHour(5) val rule = createRule(createdAt) rule.unit = ChronoUnit.MONTHS rule.hour = 9 rule.occurrence = 1 rule.interval = 3 rule.startsOn = CronTaskChecker.now().withDayOfMonth(1).minusDays(10) // created at after execution val now = CronTaskChecker.now().withDayOfMonth(3).withHour(9).truncatedTo(ChronoUnit.HOURS) Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse } @Test fun checkMonthlyCronAfterExecution() { val now = CronTaskChecker.now().withDayOfMonth(1).withHour(11).withMinute(44) val rule = createRule(now.minusMonths(10)) rule.unit = ChronoUnit.MONTHS rule.hour = 11 rule.occurrence = 1 rule.interval = 3 rule.startsOn = now.minusMonths(10) rule.lastRun = now.minusMonths(1) Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse rule.lastRun = now.minusMonths(2) Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse rule.lastRun = now.minusMonths(3) Assertions.assertThat(checker.shouldExecute(rule, now)).isTrue rule.occurrence = 3 Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse } @Test fun checkWeeklyCronCreatedAfterAndBeforeHour() { val createdAt = CronTaskChecker.now().withHour(10) val rule = createRule(createdAt) rule.unit = ChronoUnit.WEEKS rule.hour = 9 rule.daysOfWeek = 127 // every day in week rule.interval = 3 rule.startsOn = createdAt.minusDays(1) // created at after execution val now = createdAt.withHour(9).truncatedTo(ChronoUnit.HOURS) Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse // created at before execution rule.rule.createdAt = createdAt.withHour(8) Assertions.assertThat(checker.shouldExecute(rule, now)).isTrue } @Test fun checkWeeklyCronOtherDay() { val createdAt = CronTaskChecker.now().minusDays(10) val daysOfWeek = 2f.pow(CronTaskChecker.now().dayOfWeek.value - 1).toInt() val rule = createRule(createdAt) rule.unit = ChronoUnit.WEEKS rule.hour = 9 rule.daysOfWeek = daysOfWeek - 1 rule.interval = 3 rule.startsOn = createdAt // check execution other day val now = CronTaskChecker.now().withHour(9).truncatedTo(ChronoUnit.HOURS) Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse // check execution this day rule.daysOfWeek = daysOfWeek Assertions.assertThat(checker.shouldExecute(rule, now)).isTrue } @Test fun checkWeeklyAfterExecutedThisWeek() { val createdAt = CronTaskChecker.now().minusYears(1) val monday = DayOfWeek.MONDAY.value.toLong() val wednesday = DayOfWeek.WEDNESDAY.value.toLong() val saturday = DayOfWeek.SATURDAY.value.toLong() val rule = createRule(createdAt) rule.unit = ChronoUnit.WEEKS rule.hour = 6 rule.daysOfWeek = 1 + 4 + 32 // MON, WED, SAT rule.interval = 3 rule.startsOn = createdAt rule.lastRun = CronTaskChecker.now() .with(ChronoField.DAY_OF_WEEK, monday) // ran in monday and check if it should run in wednesday var now = CronTaskChecker.now() .with(ChronoField.DAY_OF_WEEK, wednesday) .withHour(6) .truncatedTo(ChronoUnit.HOURS) Assertions.assertThat(checker.shouldExecute(rule, now)).isTrue // ran in monday and check if it should run in saturday now = now.with(ChronoField.DAY_OF_WEEK, saturday) Assertions.assertThat(checker.shouldExecute(rule, now)).isTrue // ran in monday and check if it should run in monday now = now.with(ChronoField.DAY_OF_WEEK, monday) Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse } @Test fun checkWeeklyAfterExecutedOtherWeek() { val createdAt = CronTaskChecker.now().minusYears(1) val rule = createRule(createdAt) rule.unit = ChronoUnit.WEEKS rule.hour = 4 rule.daysOfWeek = 2f.pow(CronTaskChecker.now().dayOfWeek.value - 1).toInt() rule.interval = 5 rule.startsOn = createdAt rule.lastRun = CronTaskChecker.now().minusWeeks(1) val now = CronTaskChecker.now().withHour(4).truncatedTo(ChronoUnit.HOURS) Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse rule.lastRun = CronTaskChecker.now().minusWeeks(2) Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse rule.lastRun = CronTaskChecker.now().minusWeeks(3) Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse rule.lastRun = CronTaskChecker.now().minusWeeks(4) Assertions.assertThat(checker.shouldExecute(rule, now)).isFalse rule.lastRun = CronTaskChecker.now().minusWeeks(5) Assertions.assertThat(checker.shouldExecute(rule, now)).isTrue } private fun createRule(createdAt: ZonedDateTime? = null): CronRule { val rule = Rule("r1", Rule.RuleType.CRON, null, DataDocument()) rule.createdAt = createdAt return CronRule(rule) } private fun createRunningRuleData(): Pair<CronRule, ZonedDateTime> { val createdAt = CronTaskChecker.now().withHour(13) val rule = createRule(createdAt).apply { unit = ChronoUnit.DAYS hour = 14 interval = 2 startsOn = CronTaskChecker.now().minusDays(10) } val now = CronTaskChecker.now().withHour(14).truncatedTo(ChronoUnit.HOURS) return Pair(rule, now) } }
gpl-3.0
b8fca0e235d9fc8d44b9193ebb99601d
32.176056
98
0.68945
4.128834
false
true
false
false
lanhuaguizha/Christian
common/src/main/java/com/christian/common/data/Comment.kt
1
357
package com.christian.common.data data class Comment ( var commentId: String = "", var avatarUrl: String = "", var nickName: String = "", var childComment: List<String> = arrayListOf(), var comment: String = "", var createTime: String = "", var flag: String = "", var gospelId: String = "", var timestamp: String = "", )
gpl-3.0
268cc23a4ed22c4b5d1b4881c085a87d
26.538462
51
0.607843
4.2
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/mining_robot/RequestStatus.kt
2
533
package com.cout970.magneticraft.systems.tilemodules.mining_robot /** * Created by cout970 on 2017/08/23. */ enum class RequestStatus { RUNNING, FAILED, SUCCESSFUL } object FailReason { val NO_FAIL = 0 val NO_ENERGY = 1 val BLOCKED = 2 val UNBREAKABLE = 3 val LIMIT_REACHED = 4 val INVENTORY_FULL = 5 val AIR = 6 } val RequestStatus?.isFinished: Boolean get() = this == RequestStatus.FAILED || this == RequestStatus.SUCCESSFUL val RequestStatus?.isNotFinished: Boolean get() = !isFinished
gpl-2.0
2551051fc16e066708f5ec22dd49c931
22.217391
111
0.690432
3.727273
false
false
false
false
EyeSeeTea/QAApp
app/src/main/java/org/eyeseetea/malariacare/presentation/presenters/LoginPresenter.kt
1
1894
package org.eyeseetea.malariacare.presentation.presenters import org.eyeseetea.malariacare.domain.entity.Server import org.eyeseetea.malariacare.domain.usecase.GetServersUseCase import org.eyeseetea.malariacare.presentation.boundary.Executor class LoginPresenter( private val executor: Executor, private val getServersUseCase: GetServersUseCase ) { private var view: View? = null private lateinit var otherText: String private lateinit var server: Server fun attachView(view: View, otherText: String) { this.view = view this.otherText = otherText loadServers() } fun detachView() { this.view = null } fun selectServer(server: Server) { this.server = server if (server.url == otherText) { showManualServerUrlView() } else { hideManualServerUrlView(server.url) } } private fun loadServers() = executor.asyncExecute { showLoading() val servers = getServersUseCase.execute() hideLoading() showServers(servers + Server(otherText)) } private fun showServers(servers: List<Server>) = executor.uiExecute { view?.showServers(servers) } private fun showLoading() = executor.uiExecute { view?.showLoading() } private fun hideLoading() = executor.uiExecute { view?.hideLoading() } private fun showManualServerUrlView() = executor.uiExecute { view?.showManualServerUrlView() } private fun hideManualServerUrlView(serverUrl: String) = executor.uiExecute { view?.hideManualServerUrlView(serverUrl) } interface View { fun showLoading() fun hideLoading() fun showManualServerUrlView() fun hideManualServerUrlView(serverUrl: String) fun showServers(servers: List<@JvmSuppressWildcards Server>) } }
gpl-3.0
55130e28d47c1984d629d89e6c1ff418
25.690141
81
0.668955
4.699752
false
false
false
false
tom-kita/kktAPK
app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/presenter/TimelinePresenter.kt
2
5465
package com.bl_lia.kirakiratter.presentation.presenter import android.support.v4.app.Fragment import com.bl_lia.kirakiratter.domain.entity.Status import com.bl_lia.kirakiratter.domain.extension.containsJapanese import com.bl_lia.kirakiratter.domain.interactor.SingleUseCase import com.bl_lia.kirakiratter.domain.value_object.Translation import com.bl_lia.kirakiratter.presentation.fragment.TimelineFragment import com.bl_lia.kirakiratter.presentation.internal.di.PerFragment import com.google.firebase.remoteconfig.FirebaseRemoteConfig import io.reactivex.Single import org.jsoup.Jsoup import javax.inject.Inject import javax.inject.Named @PerFragment class TimelinePresenter @Inject constructor( private val fragment: Fragment, @Named("getHomeTimeline") private val getHomeTimeline: SingleUseCase<List<Status>>, @Named("getMoreHomeTimeline") private val getMoreHomeTimeline: SingleUseCase<List<Status>>, @Named("getNewHomeTimeline") private val getNewHomeTimeline: SingleUseCase<List<Status>>, @Named("getPublicTimeline") private val getPublicTimeline: SingleUseCase<List<Status>>, @Named("getMorePublicTimeline") private val getMorePublicTimeline: SingleUseCase<List<Status>>, @Named("getNewPublicTimeline") private val getNewPublicTimeline: SingleUseCase<List<Status>>, @Named("favouriteStatus") private val favouriteStatus: SingleUseCase<Status>, @Named("unfavouriteStatus") private val unfavouriteStatus: SingleUseCase<Status>, @Named("reblogStatus") private val reblogStatus: SingleUseCase<Status>, @Named("unreblogStatus") private val unreblogStatus: SingleUseCase<Status>, @Named("translateContent") private val translateContent: SingleUseCase<List<Translation>> ): Presenter { override fun resume() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun pause() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun destroy() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun start() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } fun fetchTimeline(scope: TimelineFragment.Scope, newTimeline: Boolean = false): Single<List<Status>> = when (scope) { TimelineFragment.Scope.Home -> { if (newTimeline) { getNewHomeTimeline.execute() } else { getHomeTimeline.execute() } } TimelineFragment.Scope.Local -> { if (newTimeline) { getNewPublicTimeline.execute() } else { getPublicTimeline.execute() } } } fun fetchMoreTimeline(scope: TimelineFragment.Scope, maxId: String): Single<List<Status>>? { if (getMoreHomeTimeline.processing) return null when (scope) { TimelineFragment.Scope.Home -> { return getMoreHomeTimeline.execute(maxId) } TimelineFragment.Scope.Local -> { return getMorePublicTimeline.execute(maxId) } } } fun favourite(status: Status): Single<Status> { val target = status.reblog ?: status if (target.favourited) { return unfavouriteStatus.execute(status.id.toString()) } else { return favouriteStatus.execute(status.id.toString()) } } fun reblog(status: Status): Single<Status> { val target = status.reblog ?: status if (target.reblogged) { return unreblogStatus.execute(status.id) } else { return reblogStatus.execute(status.id) } } fun translation(status: Status) { val target = status.reblog ?: status val content = Jsoup.parse(target.content?.body).text() if (content.isNotEmpty()) { val remoteConfig = FirebaseRemoteConfig.getInstance() remoteConfig.fetch() .addOnCompleteListener { task -> if (task.isSuccessful) { remoteConfig.activateFetched() val key = remoteConfig.getString("translation_api_key") val sourceLang = if (content.containsJapanese()) "ja" else "en" val targetLang = if (sourceLang == "ja") "en" else "ja" translateContent.execute(key, sourceLang, targetLang, content) .subscribe { list, error -> (fragment as TimelineFragment).tranlateText(status, list, error) } } else { (fragment as TimelineFragment).tranlateText(status, listOf(), Exception("Error")) } } } else { (fragment as TimelineFragment).tranlateText(status, listOf(), Exception("Error")) } } }
mit
4507bbd41d871857e8d9cd1cdf505a99
39.791045
109
0.597072
5.088454
false
true
false
false
Ph1b/MaterialAudiobookPlayer
playback/src/main/kotlin/de/ph1b/audiobook/playback/session/MediaSessionCallback.kt
1
5454
package de.ph1b.audiobook.playback.session import android.os.Bundle import android.support.v4.media.session.MediaControllerCompat.TransportControls import android.support.v4.media.session.MediaSessionCompat import androidx.datastore.core.DataStore import de.ph1b.audiobook.common.pref.CurrentBook import de.ph1b.audiobook.data.Book2 import de.ph1b.audiobook.data.Chapter2 import de.ph1b.audiobook.playback.BuildConfig import de.ph1b.audiobook.playback.androidauto.AndroidAutoConnectedReceiver import de.ph1b.audiobook.playback.di.PlaybackScope import de.ph1b.audiobook.playback.player.MediaPlayer import de.ph1b.audiobook.playback.session.search.BookSearchHandler import de.ph1b.audiobook.playback.session.search.BookSearchParser import kotlinx.coroutines.runBlocking import timber.log.Timber import javax.inject.Inject /** * Media session callback that handles playback controls. */ @PlaybackScope class MediaSessionCallback @Inject constructor( private val bookUriConverter: BookUriConverter, @CurrentBook private val currentBook: DataStore<Book2.Id?>, private val bookSearchHandler: BookSearchHandler, private val autoConnection: AndroidAutoConnectedReceiver, private val bookSearchParser: BookSearchParser, private val player: MediaPlayer, ) : MediaSessionCompat.Callback() { override fun onSkipToQueueItem(id: Long) { Timber.i("onSkipToQueueItem $id") val chapter = player.book ?.chapters?.getOrNull(id.toInt()) ?: return player.changePosition(0, chapter.id) player.play() } override fun onPlayFromMediaId(mediaId: String?, extras: Bundle?) { Timber.i("onPlayFromMediaId $mediaId") mediaId ?: return val parsed = bookUriConverter.parse(mediaId) if (parsed is BookUriConverter.Parsed.Book) { runBlocking { currentBook.updateData { parsed.id } } onPlay() } else { Timber.e("Didn't handle $parsed") } } override fun onPlayFromSearch(query: String?, extras: Bundle?) { Timber.i("onPlayFromSearch $query") val bookSearch = bookSearchParser.parse(query, extras) runBlocking { bookSearchHandler.handle(bookSearch) } } override fun onSkipToNext() { Timber.i("onSkipToNext") if (autoConnection.connected) { player.next() } else { onFastForward() } } override fun onRewind() { Timber.i("onRewind") player.skip(forward = false) } override fun onSkipToPrevious() { Timber.i("onSkipToPrevious") if (autoConnection.connected) { player.previous(toNullOfNewTrack = true) } else { onRewind() } } override fun onFastForward() { Timber.i("onFastForward") player.skip(forward = true) } override fun onStop() { Timber.i("onStop") player.stop() } override fun onPause() { Timber.i("onPause") player.pause(rewind = true) } override fun onPlay() { Timber.i("onPlay") player.play() } override fun onSeekTo(pos: Long) { player.changePosition(pos) } override fun onSetPlaybackSpeed(speed: Float) { player.setPlaybackSpeed(speed) } override fun onCustomAction(action: String?, extras: Bundle?) { Timber.i("onCustomAction $action") when (action) { ANDROID_AUTO_ACTION_NEXT -> onSkipToNext() ANDROID_AUTO_ACTION_PREVIOUS -> onSkipToPrevious() ANDROID_AUTO_ACTION_FAST_FORWARD -> onFastForward() ANDROID_AUTO_ACTION_REWIND -> onRewind() PLAY_PAUSE_ACTION -> player.playPause() SKIP_SILENCE_ACTION -> { val skip = extras!!.getBoolean(SKIP_SILENCE_EXTRA) player.setSkipSilences(skip) } SET_POSITION_ACTION -> { val id = Chapter2.Id(extras!!.getString(SET_POSITION_EXTRA_CHAPTER)!!) val time = extras.getLong(SET_POSITION_EXTRA_TIME) player.changePosition(time, id) } FORCED_PREVIOUS -> { player.previous(toNullOfNewTrack = true) } FORCED_NEXT -> { player.next() } else -> if (BuildConfig.DEBUG) { error("Didn't handle $action") } } } } private inline fun TransportControls.sendCustomAction(action: String, fillBundle: Bundle.() -> Unit = {}) { sendCustomAction(action, Bundle().apply(fillBundle)) } private const val PLAY_PAUSE_ACTION = "playPause" fun TransportControls.playPause() = sendCustomAction(PLAY_PAUSE_ACTION) private const val SKIP_SILENCE_ACTION = "skipSilence" private const val SKIP_SILENCE_EXTRA = "$SKIP_SILENCE_ACTION#value" fun TransportControls.skipSilence(skip: Boolean) = sendCustomAction(SKIP_SILENCE_ACTION) { putBoolean(SKIP_SILENCE_EXTRA, skip) } private const val SET_POSITION_ACTION = "setPosition" private const val SET_POSITION_EXTRA_TIME = "$SET_POSITION_ACTION#time" private const val SET_POSITION_EXTRA_CHAPTER = "$SET_POSITION_ACTION#uri" fun TransportControls.setPosition(time: Long, id: Chapter2.Id) = sendCustomAction(SET_POSITION_ACTION) { putString(SET_POSITION_EXTRA_CHAPTER, id.value) putLong(SET_POSITION_EXTRA_TIME, time) } const val ANDROID_AUTO_ACTION_FAST_FORWARD = "fast_forward" const val ANDROID_AUTO_ACTION_REWIND = "rewind" const val ANDROID_AUTO_ACTION_NEXT = "next" const val ANDROID_AUTO_ACTION_PREVIOUS = "previous" private const val FORCED_PREVIOUS = "forcedPrevious" fun TransportControls.forcedPrevious() = sendCustomAction(FORCED_PREVIOUS) private const val FORCED_NEXT = "forcedNext" fun TransportControls.forcedNext() = sendCustomAction(FORCED_NEXT)
lgpl-3.0
5befa0aea365ca3360ede9b854ac59b2
29.469274
107
0.719839
3.876333
false
false
false
false
fnouama/intellij-community
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/LineBreakpointManager.kt
12
8190
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.icons.AllIcons import com.intellij.util.SmartList import com.intellij.util.containers.MultiMap import com.intellij.xdebugger.XSourcePosition import com.intellij.xdebugger.breakpoints.XLineBreakpoint import gnu.trove.THashMap import gnu.trove.THashSet import org.jetbrains.util.concurrency import org.jetbrains.util.concurrency.Promise import org.jetbrains.util.concurrency.ResolvedPromise public abstract class LineBreakpointManager(private val vm: Vm, private val debugProcess: DebugProcessImpl<*>) { private val ideToVmBreakpoints = THashMap<XLineBreakpoint<*>, MutableList<Breakpoint>>() protected val vmToIdeBreakpoint: MultiMap<Breakpoint, XLineBreakpoint<*>> = MultiMap.createSmart() private val runToLocationBreakpoints = THashSet<Breakpoint>() private val lock = Object() init { vm.getBreakpointManager().addBreakpointListener(object : BreakpointManager.BreakpointListener { override fun resolved(breakpoint: Breakpoint) { var breakpoints = synchronized (lock) { vmToIdeBreakpoint.get(breakpoint) } for (ideBreakpoint in breakpoints) { debugProcess.getSession().updateBreakpointPresentation(ideBreakpoint, AllIcons.Debugger.Db_verified_breakpoint, null) } } override fun errorOccurred(breakpoint: Breakpoint, errorMessage: String?) { if (isAnyFirstLineBreakpoint(breakpoint)) { return } if (synchronized (lock) { runToLocationBreakpoints.remove(breakpoint) }) { debugProcess.getSession().reportError("Cannot run to cursor: ${errorMessage!!}") return } var breakpoints = synchronized (lock) { vmToIdeBreakpoint.get(breakpoint) } for (ideBreakpoint in breakpoints) { debugProcess.getSession().updateBreakpointPresentation(ideBreakpoint, AllIcons.Debugger.Db_invalid_breakpoint, errorMessage) } } }) } public open fun isAnyFirstLineBreakpoint(breakpoint: Breakpoint): Boolean = false public fun setBreakpoint(breakpoint: XLineBreakpoint<*>, onlySourceMappedBreakpoints: Boolean) { var target = synchronized (lock) { ideToVmBreakpoints.get(breakpoint) } if (target == null) { setBreakpoint(breakpoint, debugProcess.getLocationsForBreakpoint(breakpoint, onlySourceMappedBreakpoints)) } else { val breakpointManager = vm.getBreakpointManager() for (vmBreakpoint in target) { if (!vmBreakpoint.enabled) { vmBreakpoint.enabled = true breakpointManager.flush(vmBreakpoint).rejected { debugProcess.getSession().updateBreakpointPresentation(breakpoint, AllIcons.Debugger.Db_invalid_breakpoint, it.getMessage()) } } } } } public fun removeBreakpoint(breakpoint: XLineBreakpoint<*>, temporary: Boolean): concurrency.Promise<*> { val disable = temporary && vm.getBreakpointManager().getMuteMode() !== BreakpointManager.MUTE_MODE.NONE beforeBreakpointRemoved(breakpoint, disable) return doRemoveBreakpoint(breakpoint, disable) } protected open fun beforeBreakpointRemoved(breakpoint: XLineBreakpoint<*>, disable: Boolean) { } public fun doRemoveBreakpoint(breakpoint: XLineBreakpoint<*>, disable: Boolean): concurrency.Promise<*> { var vmBreakpoints: Collection<Breakpoint> = emptySet() synchronized (lock) { if (disable) { val list = ideToVmBreakpoints.get(breakpoint) ?: return ResolvedPromise() val iterator = list.iterator() vmBreakpoints = list while (iterator.hasNext()) { val vmBreakpoint = iterator.next() if (vmToIdeBreakpoint.get(vmBreakpoint).size() > 1) { // we must not disable vm breakpoint - it is used for another ide breakpoints iterator.remove() } } } else { vmBreakpoints = ideToVmBreakpoints.remove(breakpoint) ?: return ResolvedPromise() if (!vmBreakpoints.isEmpty()) { for (vmBreakpoint in vmBreakpoints) { vmToIdeBreakpoint.remove(vmBreakpoint, breakpoint) if (vmToIdeBreakpoint.containsKey(vmBreakpoint)) { // we must not remove vm breakpoint - it is used for another ide breakpoints return ResolvedPromise() } } } } } if (vmBreakpoints.isEmpty()) { return ResolvedPromise() } val breakpointManager = vm.getBreakpointManager() val promises = SmartList<concurrency.Promise<*>>() if (disable) { for (vmBreakpoint in vmBreakpoints) { vmBreakpoint.enabled = false promises.add(breakpointManager.flush(vmBreakpoint)) } } else { for (vmBreakpoint in vmBreakpoints) { promises.add(breakpointManager.remove(vmBreakpoint)) } } return concurrency.Promise.all(promises) } public fun setBreakpoint(breakpoint: XLineBreakpoint<*>, locations: List<Location>) { if (locations.isEmpty()) { return } val vmBreakpoints = SmartList<Breakpoint>() for (location in locations) { vmBreakpoints.add(doSetBreakpoint(breakpoint, location, false)) } synchronized (lock) { ideToVmBreakpoints.put(breakpoint, vmBreakpoints) for (vmBreakpoint in vmBreakpoints) { vmToIdeBreakpoint.putValue(vmBreakpoint, breakpoint) } } } protected fun doSetBreakpoint(breakpoint: XLineBreakpoint<*>?, location: Location, isTemporary: Boolean): Breakpoint { val breakpointManager = vm.getBreakpointManager() val target = createTarget(breakpoint, breakpointManager, location, isTemporary) val condition = breakpoint?.getConditionExpression() return breakpointManager.setBreakpoint(target, location.getLine(), location.getColumn(), condition?.getExpression(), Breakpoint.EMPTY_VALUE, true) } protected abstract fun createTarget(breakpoint: XLineBreakpoint<*>?, breakpointManager: BreakpointManager, location: Location, isTemporary: Boolean): BreakpointTarget public fun runToLocation(position: XSourcePosition) { val addedBreakpoints = doRunToLocation(position) if (addedBreakpoints.isEmpty()) { return } synchronized (lock) { runToLocationBreakpoints.addAll(addedBreakpoints) } debugProcess.resume() } protected abstract fun doRunToLocation(position: XSourcePosition): List<Breakpoint> public fun isRunToCursorBreakpoints(breakpoints: List<Breakpoint>): Boolean { synchronized (runToLocationBreakpoints) { return runToLocationBreakpoints.containsAll(breakpoints) } } public fun updateAllBreakpoints() { var array = synchronized (lock) { ideToVmBreakpoints.keySet().toTypedArray() } for (breakpoint in array) { removeBreakpoint(breakpoint, false) setBreakpoint(breakpoint, false) } } public fun removeAllBreakpoints(): Promise<*> { synchronized (lock) { ideToVmBreakpoints.clear() vmToIdeBreakpoint.clear() runToLocationBreakpoints.clear() } return vm.getBreakpointManager().removeAll() } public fun clearRunToLocationBreakpoints() { var breakpoints = synchronized (lock) { if (runToLocationBreakpoints.isEmpty()) { return@clearRunToLocationBreakpoints } var breakpoints = runToLocationBreakpoints.toArray<Breakpoint>(arrayOfNulls<Breakpoint>(runToLocationBreakpoints.size())) runToLocationBreakpoints.clear() breakpoints } val breakpointManager = vm.getBreakpointManager() for (breakpoint in breakpoints) { breakpointManager.remove(breakpoint) } } }
apache-2.0
7e2f5c7d18bb18a932fa41626deef17f
36.746544
185
0.711844
5.071207
false
false
false
false
corenting/EDCompanion
app/src/main/java/fr/corenting/edcompanion/activities/DetailsActivity.kt
1
2885
package fr.corenting.edcompanion.activities import android.os.Bundle import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.recyclerview.widget.LinearLayoutManager import fr.corenting.edcompanion.adapters.CommunityGoalsAdapter import fr.corenting.edcompanion.adapters.NewsAdapter import fr.corenting.edcompanion.databinding.ActivityDetailsBinding import fr.corenting.edcompanion.models.CommunityGoal import fr.corenting.edcompanion.models.NewsArticle import fr.corenting.edcompanion.utils.ThemeUtils class DetailsActivity : AppCompatActivity() { private lateinit var binding: ActivityDetailsBinding override fun onCreate(savedInstanceState: Bundle?) { AppCompatDelegate.setDefaultNightMode(ThemeUtils.getThemeToUse(this)) super.onCreate(savedInstanceState) binding = ActivityDetailsBinding.inflate(layoutInflater) val view = binding.root setContentView(view) // Set toolbar setSupportActionBar(binding.includeAppBar.toolbar) supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) // Common recycler view setup val linearLayoutManager = LinearLayoutManager(this) binding.recyclerView.layoutManager = linearLayoutManager // Get the goal or the article if (intent.extras != null) { val communityGoal = intent.extras?.getParcelable<CommunityGoal>("goal") val article = intent.extras?.getParcelable<NewsArticle>("article") if (communityGoal == null && article != null) { val isGalnet = intent.extras?.getBoolean("isGalnet") ?: false newsArticleSetup(article, isGalnet) } else if (communityGoal != null) { communityGoalSetup(communityGoal) } } binding.recyclerView.smoothScrollToPosition(-10) // because recycler view may not start on top } private fun communityGoalSetup(communityGoal: CommunityGoal) { supportActionBar?.title = communityGoal.title // Adapter setup val adapter = CommunityGoalsAdapter(this, binding.recyclerView, true) binding.recyclerView.adapter = adapter adapter.submitList(listOf(communityGoal)) } private fun newsArticleSetup(article: NewsArticle, isGalnet: Boolean) { supportActionBar?.title = article.title // Adapter view setup val adapter = NewsAdapter(this, binding.recyclerView, true, isGalnet) binding.recyclerView.adapter = adapter adapter.submitList(listOf(article)) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finish() } return super.onOptionsItemSelected(item) } }
mit
61ea306a8d999ec6e7016df26f4825e9
37.986486
102
0.714731
5.255009
false
false
false
false
chrisbanes/tivi
data-android/src/main/java/app/tivi/data/repositories/trendingshows/TrendingShowsModule.kt
1
3318
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.data.repositories.trendingshows import app.tivi.data.daos.TiviShowDao import app.tivi.data.daos.TrendingDao import app.tivi.data.entities.TrendingShowEntry import com.dropbox.android.external.store4.Fetcher import com.dropbox.android.external.store4.SourceOfTruth import com.dropbox.android.external.store4.Store import com.dropbox.android.external.store4.StoreBuilder import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.flow.map import org.threeten.bp.Duration import javax.inject.Singleton typealias TrendingShowsStore = Store<Int, List<TrendingShowEntry>> @InstallIn(SingletonComponent::class) @Module object TrendingShowsModule { @Provides @Singleton fun provideTrendingShowsStore( traktTrendingShows: TraktTrendingShowsDataSource, trendingShowsDao: TrendingDao, showDao: TiviShowDao, lastRequestStore: TrendingShowsLastRequestStore ): TrendingShowsStore = StoreBuilder.from( fetcher = Fetcher.of { page: Int -> traktTrendingShows(page, 20) .also { if (page == 0) { lastRequestStore.updateLastRequest() } } }, sourceOfTruth = SourceOfTruth.of( reader = { page -> trendingShowsDao.entriesObservable(page).map { entries -> when { // Store only treats null as 'no value', so convert to null entries.isEmpty() -> null // If the request is expired, our data is stale lastRequestStore.isRequestExpired(Duration.ofHours(3)) -> null // Otherwise, our data is fresh and valid else -> entries } } }, writer = { page, response -> trendingShowsDao.withTransaction { val entries = response.map { (show, entry) -> entry.copy(showId = showDao.getIdOrSavePlaceholder(show), page = page) } if (page == 0) { // If we've requested page 0, remove any existing entries first trendingShowsDao.deleteAll() trendingShowsDao.insertAll(entries) } else { trendingShowsDao.updatePage(page, entries) } } }, delete = trendingShowsDao::deletePage, deleteAll = trendingShowsDao::deleteAll ) ).build() }
apache-2.0
550318142f93375b52d70ff5b55a8d71
37.581395
94
0.610609
4.952239
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/util/InspectionResult.kt
1
2421
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.util import com.vladsch.plugin.util.suffixWith enum class Severity constructor(val value: Int) : DataPrinterAware { INFO(0), WEAK_WARNING(1), WARNING(2), ERROR(3); override fun testData(): String = super.testData() + "." + toString() } class InspectionResult( val location: String?, val id: String, val severity: Severity, val fixedLink: String? = null, val fixedFilePath: String? = null ) { var referenceId: Any? = location var handled: Boolean = false fun compareTo(other: InspectionResult): Int { return if (severity == other.severity && fixedLink == other.fixedLink && fixedFilePath == other.fixedFilePath) id.compareTo(other.id) else -1 } private fun dataPrint(value: Any?): String { return if (value == null) "null" else when (value) { is Unit -> "" is Int, is Long, is Boolean, is Float, is Double, is Byte -> "$value" is Char -> "'$value'" else -> "\"$value\"" } } override fun toString(): String { return "InspectionResults(${dataPrint(referenceId)}, \"$id\", Severity.$severity, ${if (fixedLink == null) "null" else "\"$fixedLink\""}, ${if (fixedFilePath == null) "null" else "\"$fixedFilePath\""})" } fun isA(id: String) = this.id == id // /* 0 */arrayOf<Any?>(18, GitHubLinkInspector.ID_WIKI_LINK_HAS_DASHES , Severity.WEAK_WARNING, "Normal File", null) /* 0 */ fun toArrayOfTestString(rowId: Int = 0, removePrefix: String = ""): String { val rowPad = " ".repeat(3 - rowId.toString().length) + rowId return "arrayOf($rowPad, \"$id\", Severity.$severity, ${if (fixedLink == null) "null" else "\"$fixedLink\""}, ${if (fixedFilePath == null) "null" else "\"${if (!removePrefix.isEmpty()) PathInfo.relativePath(removePrefix.suffixWith('/'), fixedFilePath, blobRawEqual = false) else fixedFilePath}\""})" } companion object { @JvmStatic fun handled(results: List<InspectionResult>, vararg ids: String) { for (result in results) { if (!result.handled && ids.contains(result.id)) { result.handled = true } } } } }
apache-2.0
25963eee34740e171b9e705e283dd1eb
40.033898
307
0.614622
4.014925
false
true
false
false
canou/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/views/MyAppCompatSpinner.kt
2
1828
package com.simplemobiletools.commons.views import android.content.Context import android.graphics.PorterDuff import android.support.v7.widget.AppCompatSpinner import android.util.AttributeSet import android.view.View import android.widget.AdapterView import android.widget.TextView import com.simplemobiletools.commons.R import com.simplemobiletools.commons.adapters.MyArrayAdapter class MyAppCompatSpinner : AppCompatSpinner { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) fun setColors(textColor: Int, accentColor: Int, backgroundColor: Int) { if (adapter == null) return val cnt = adapter.count val items = kotlin.arrayOfNulls<Any>(cnt) for (i in 0..cnt - 1) items[i] = adapter.getItem(i) val position = selectedItemPosition val padding = resources.getDimension(R.dimen.activity_margin).toInt() adapter = MyArrayAdapter(context, android.R.layout.simple_spinner_item, items, textColor, backgroundColor, padding) setSelection(position) val superListener = onItemSelectedListener onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { if (view != null) { (view as TextView).setTextColor(textColor) } superListener?.onItemSelected(parent, view, position, id) } override fun onNothingSelected(parent: AdapterView<*>?) { } } background.setColorFilter(textColor, PorterDuff.Mode.SRC_ATOP) } }
apache-2.0
79716b9cfdffec330dfc61d59e040667
37.083333
123
0.686543
4.823219
false
false
false
false
TangHao1987/intellij-community
platform/platform-impl/src/com/intellij/openapi/application/actions.kt
2
1336
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.application import javax.swing.SwingUtilities public inline fun <T> runWriteAction(runnable: () -> T): T { val token = WriteAction.start() try { return runnable() } finally { token.finish() } } public inline fun runReadAction(runnable: () -> Unit) { val token = ReadAction.start() try { runnable() } finally { token.finish() } } /** * @exclude Internal use only */ public fun invokeAndWaitIfNeed(runnable: () -> Unit) { val app = ApplicationManager.getApplication() if (app == null) { if (SwingUtilities.isEventDispatchThread()) runnable() else SwingUtilities.invokeAndWait(runnable) } else { app.invokeAndWait(runnable, ModalityState.any()) } }
apache-2.0
b926096bd5b1ad49af9f22edcd816c9b
25.196078
102
0.702844
4.048485
false
false
false
false
SerCeMan/intellij-community
plugins/settings-repository/src/keychain/CredentialsStore.kt
23
677
package org.jetbrains.keychain import com.intellij.openapi.diagnostic.Logger val LOG: Logger = Logger.getInstance(javaClass<CredentialsStore>()) public data class Credentials(id: String?, token: String?) { public val id: String? = if (id.isNullOrEmpty()) null else id public val token: String? = if (token.isNullOrEmpty()) null else token } public fun Credentials?.isFulfilled(): Boolean = this != null && id != null && token != null public interface CredentialsStore { public fun get(host: String?, sshKeyFile: String? = null): Credentials? public fun save(host: String?, credentials: Credentials, sshKeyFile: String? = null) public fun reset(host: String) }
apache-2.0
18e0383064e6f47c99fa3fa414a46bd1
32.85
92
0.734121
4.153374
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/themes/Themes.kt
1
4553
/* Copyright (c) 2011 Norbert Nagold <[email protected]> Copyright (c) 2015 Timothy Rae <[email protected]> Copyright (c) 2021 Akshay Jadhav <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.themes import android.content.Context import androidx.annotation.AttrRes import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import com.ichi2.anki.AnkiDroidApp import com.ichi2.anki.R /** * Helper methods to configure things related to AnkiDroid's themes */ object Themes { const val ALPHA_ICON_ENABLED_LIGHT = 255 // 100% const val ALPHA_ICON_DISABLED_LIGHT = 76 // 31% const val FOLLOW_SYSTEM_MODE = "0" private const val APP_THEME_KEY = "appTheme" private const val DAY_THEME_KEY = "dayTheme" private const val NIGHT_THEME_KEY = "nightTheme" var currentTheme: Theme = Theme.fallback var systemIsInNightMode: Boolean = false /** * Sets theme to [currentTheme] */ fun setTheme(context: Context) { context.setTheme(currentTheme.resId) } /** * Sets theme to the legacy version of [currentTheme] */ fun setThemeLegacy(context: Context) { context.setTheme(currentTheme.legacyResId) } /** * Updates [currentTheme] value based on preferences. * If `Follow system` is selected, it's updated to the theme set * on `Day` or `Night` theme according to system's current mode * Otherwise, updates to the selected theme. */ fun updateCurrentTheme() { val prefs = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.instance.applicationContext) currentTheme = if (themeFollowsSystem()) { if (systemIsInNightMode) { Theme.ofId(prefs.getString(NIGHT_THEME_KEY, Theme.BLACK.id)!!) } else { Theme.ofId(prefs.getString(DAY_THEME_KEY, Theme.LIGHT.id)!!) } } else { Theme.ofId(prefs.getString(APP_THEME_KEY, Theme.fallback.id)!!) } } /** * #8150: Fix icons not appearing in Note Editor due to MIUI 12's "force dark" mode */ fun disableXiaomiForceDarkMode(context: Context) { // Setting a theme is an additive operation, so this adds a single property. context.setTheme(R.style.ThemeOverlay_Xiaomi) } fun getResFromAttr(context: Context, resAttr: Int): Int { val attrs = intArrayOf(resAttr) return getResFromAttr(context, attrs)[0] } fun getResFromAttr(context: Context, attrs: IntArray): IntArray { val ta = context.obtainStyledAttributes(attrs) for (i in attrs.indices) { attrs[i] = ta.getResourceId(i, 0) } ta.recycle() return attrs } @JvmStatic // tests failed when removing, maybe try later @ColorInt fun getColorFromAttr(context: Context?, colorAttr: Int): Int { val attrs = intArrayOf(colorAttr) return getColorFromAttr(context!!, attrs)[0] } @JvmStatic // tests failed when removing, maybe try later @ColorInt fun getColorFromAttr(context: Context, attrs: IntArray): IntArray { val ta = context.obtainStyledAttributes(attrs) for (i in attrs.indices) { attrs[i] = ta.getColor(i, ContextCompat.getColor(context, R.color.white)) } ta.recycle() return attrs } /** * @return required color depending on the theme from the given attribute */ @ColorInt fun Fragment.getColorFromAttr(@AttrRes attribute: Int): Int { return getColorFromAttr(requireContext(), attribute) } /** * @return if current selected theme is `Follow system` */ fun themeFollowsSystem(): Boolean { val prefs = AnkiDroidApp.getSharedPrefs(AnkiDroidApp.instance.applicationContext) return prefs.getString(APP_THEME_KEY, FOLLOW_SYSTEM_MODE) == FOLLOW_SYSTEM_MODE } }
gpl-3.0
06ed538bf263927b5e5d56cd165244d0
33.233083
89
0.676038
4.239292
false
false
false
false
pdvrieze/ProcessManager
ProcessEngine/core/src/commonMain/kotlin/nl/adaptivity/process/engine/processModel/CompositeInstance.kt
1
6334
/* * Copyright (c) 2019. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.engine.processModel import net.devrieze.util.* import net.devrieze.util.collection.replaceBy import net.devrieze.util.security.SecureObject import nl.adaptivity.process.engine.* import nl.adaptivity.process.engine.impl.generateXmlString import nl.adaptivity.process.processModel.engine.ExecutableCompositeActivity import nl.adaptivity.util.multiplatform.assert import nl.adaptivity.util.security.Principal import nl.adaptivity.xmlutil.QName import nl.adaptivity.xmlutil.serialize import nl.adaptivity.xmlutil.smartStartTag import nl.adaptivity.xmlutil.util.CompactFragment import nl.adaptivity.xmlutil.util.ICompactFragment /** * Class representing a node instance that wraps a composite activity. */ class CompositeInstance(builder: Builder) : ProcessNodeInstance<CompositeInstance>(builder) { interface Builder : ProcessNodeInstance.Builder<ExecutableCompositeActivity, CompositeInstance> { var hChildInstance: Handle<SecureObject<ProcessInstance>> override fun doProvideTask(engineData: MutableProcessEngineDataAccess): Boolean { val shouldProgress = node.provideTask(engineData, this) val childHandle = engineData.instances.put(ProcessInstance(engineData, node.childModel, handle) {}) hChildInstance = childHandle store(engineData) engineData.commit() return shouldProgress } @OptIn(ProcessInstanceStorage::class) override fun doStartTask(engineData: MutableProcessEngineDataAccess): Boolean { val shouldProgress = tryCreateTask { node.startTask(this) } assert(hChildInstance.isValid) { "The task can only be started if the child instance already exists" } tryCreateTask { engineData.updateInstance(hChildInstance) { start(engineData, build().getPayload(processInstanceBuilder)) } } engineData.queueTickle(hChildInstance) return shouldProgress } override fun doFinishTask(engineData: MutableProcessEngineDataAccess, resultPayload: ICompactFragment?) { val childInstance = engineData.instance(hChildInstance).withPermission() if (childInstance.state != ProcessInstance.State.FINISHED) { throw ProcessException("A Composite task cannot be finished until its child process is. The child state is: ${childInstance.state}") } return super.doFinishTask(engineData, childInstance.getOutputPayload()) } override fun doTakeTask(engineData: MutableProcessEngineDataAccess): Boolean { return true } } class BaseBuilder( node: ExecutableCompositeActivity, predecessor: Handle<SecureObject<ProcessNodeInstance<*>>>?, processInstanceBuilder: ProcessInstance.Builder, override var hChildInstance: Handle<SecureObject<ProcessInstance>>, owner: Principal, entryNo: Int, handle: Handle<SecureObject<ProcessNodeInstance<*>>> = Handle.invalid(), state: NodeInstanceState = NodeInstanceState.Pending ) : ProcessNodeInstance.BaseBuilder<ExecutableCompositeActivity, CompositeInstance>( node, listOfNotNull(predecessor), processInstanceBuilder, owner, entryNo, handle, state ), Builder { override fun invalidateBuilder(engineData: ProcessEngineDataAccess) { engineData.nodeInstances[handle]?.withPermission()?.let { n -> val newBase = n as CompositeInstance node = newBase.node predecessors.replaceBy(newBase.predecessors) owner = newBase.owner state = newBase.state hChildInstance = newBase.hChildInstance } } override fun build(): CompositeInstance { return CompositeInstance(this) } } class ExtBuilder(base: CompositeInstance, processInstanceBuilder: ProcessInstance.Builder) : ProcessNodeInstance.ExtBuilder<ExecutableCompositeActivity, CompositeInstance>(base, processInstanceBuilder), Builder { override var node: ExecutableCompositeActivity by overlay { base.node } override var hChildInstance: Handle<SecureObject<ProcessInstance>> by overlay( observer() ) { base.hChildInstance } override fun build(): CompositeInstance { return if (changed) CompositeInstance(this).also { invalidateBuilder(it) } else base } } val hChildInstance: Handle<SecureObject<ProcessInstance>> = builder.hChildInstance.apply { if (! (builder.state==NodeInstanceState.Pending || isValid)) throw ProcessException("Child process instance handles must be valid if the state isn't pending") } override val node: ExecutableCompositeActivity get() = super.node as ExecutableCompositeActivity override fun builder(processInstanceBuilder: ProcessInstance.Builder) = ExtBuilder(this, processInstanceBuilder) fun getPayload(nodeInstanceSource: IProcessInstance): CompactFragment? { val defines = getDefines(nodeInstanceSource) if (defines.isEmpty()) return null val content = buildString { for (data in defines) { append(generateXmlString(true) { writer -> writer.smartStartTag(QName(data.name!!)) { writer.serialize(data.contentStream) } }) append("\n") } } return CompactFragment(content) } }
lgpl-3.0
afb976cd8e86610eabf4a3f22ff451b6
40.94702
148
0.691033
5.340641
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/adapter/AutoUpdatableAdapter.kt
1
875
package com.boardgamegeek.ui.adapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView interface AutoUpdatableAdapter { fun <T> RecyclerView.Adapter<*>.autoNotify(old: List<T>, new: List<T>, compare: (T, T) -> Boolean) { val diff = DiffUtil.calculateDiff(object : DiffUtil.Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return compare(old[oldItemPosition], new[newItemPosition]) } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return old[oldItemPosition] == new[newItemPosition] } override fun getOldListSize() = old.size override fun getNewListSize() = new.size }) diff.dispatchUpdatesTo(this) } }
gpl-3.0
323ef149945908599a41a79d21262388
37.043478
104
0.664
5.057803
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/model/shippinglabels/WCShippingLabelModel.kt
2
6286
package org.wordpress.android.fluxc.model.shippinglabels import com.google.gson.Gson import com.google.gson.annotations.SerializedName import com.google.gson.reflect.TypeToken import com.yarolegovich.wellsql.core.Identifiable import com.yarolegovich.wellsql.core.annotation.Column import com.yarolegovich.wellsql.core.annotation.PrimaryKey import com.yarolegovich.wellsql.core.annotation.Table import org.wordpress.android.fluxc.persistence.WellSqlConfig import java.math.BigDecimal @Table(addOn = WellSqlConfig.ADDON_WOOCOMMERCE) class WCShippingLabelModel(@PrimaryKey @Column private var id: Int = 0) : Identifiable { @Column var localSiteId = 0 @Column var remoteOrderId = 0L // The remote identifier for the parent order object @Column var remoteShippingLabelId = 0L // The unique identifier for this note on the server @Column var trackingNumber = "" @Column var carrierId = "" @Column var dateCreated: Long? = null @Column var expiryDate: Long? = null @Column var serviceName = "" @Column var status = "" @Column var packageName = "" @Column var rate = 0F @Column var refundableAmount = 0F @Column var currency = "" @Column var productNames = "" // list of product names the shipping label was purchased for @Column var productIds = "" // list of product ids the shipping label was purchased for @Column var formData = "" // map containing package and product details related to that shipping label @Column var refund = "" // map containing refund information for a shipping label @Column var commercialInvoiceUrl: String? = null // URL pointing to the international commercial URL override fun getId() = id override fun setId(id: Int) { this.id = id } companion object { private val gson by lazy { Gson() } } /** * Returns the destination details wrapped in a [ShippingLabelAddress]. */ fun getDestinationAddress() = getFormData()?.destination /** * Returns the shipping details wrapped in a [ShippingLabelAddress]. */ fun getOriginAddress() = getFormData()?.origin /** * Returns the product details for the order wrapped in a list of [ProductItem] */ fun getProductItems() = getFormData()?.selectedPackage?.defaultBox?.productItems ?: emptyList() /** * Returns default data related to the order such as the origin address, * destination address and product items associated with the order. */ private fun getFormData(): FormData? { val responseType = object : TypeToken<FormData>() {}.type return gson.fromJson(formData, responseType) as? FormData } /** * Returns the list of products the shipping labels were purchased for * * For instance: "[Belt, Cap, Herman Miller Chair Embody]" would be split into a list * ["Belt", "Cap", "Herman Miller Chair Embody"] */ fun getProductNameList(): List<String> { return productNames .trim() // remove extra spaces between commas .removePrefix("[") // remove the String prefix .removeSuffix("]") // remove the String suffix .split(",") // split the string into list using comma spearators } /** * Returns the list of products the shipping labels were purchased for * * For instance: "[60, 61, 62]" would be split into a list * [60, 61, 62] */ fun getProductIdsList(): List<Long> { return productIds .trim() // remove extra spaces between the brackets .removePrefix("[") // remove the String prefix .removeSuffix("]") // remove the String suffix .split(",") // split the string into list using comma separators .filter { it.isNotEmpty() } .map { it.trim().toLong() } } /** * Returns data related to the refund of a shipping label. * Will only be available in the API if a refund has been initiated */ fun getRefundModel(): WCShippingLabelRefundModel? { val responseType = object : TypeToken<WCShippingLabelRefundModel>() {}.type return gson.fromJson(refund, responseType) as? WCShippingLabelRefundModel } /** * Model class corresponding to the [formData] map from the API response. * The [formData] contains the [origin] and [destination] address and the * product details associated with the order. * (nested under [selectedPackage] -> [DefaultBox] -> List of [ProductItem]). */ class FormData( val origin: ShippingLabelAddress? = null, val destination: ShippingLabelAddress? = null, @SerializedName("selected_packages") val selectedPackage: SelectedPackage? = null ) data class ShippingLabelAddress( val company: String? = null, val name: String? = null, val phone: String? = null, val country: String? = null, val state: String? = null, val address: String? = null, @SerializedName("address_2") val address2: String? = null, val city: String? = null, val postcode: String? = null ) { enum class Type { ORIGIN, DESTINATION } } data class ShippingLabelPackage( val id: String, @SerializedName("box_id") val boxId: String, val height: Float, val length: Float, val width: Float, val weight: Float, @SerializedName("is_letter") val isLetter: Boolean = false ) class SelectedPackage { @SerializedName("default_box") val defaultBox: DefaultBox? = null } class DefaultBox { @SerializedName("items") val productItems: List<ProductItem>? = null } class ProductItem { val height: BigDecimal? = null val length: BigDecimal? = null val quantity: Int? = null val width: BigDecimal? = null val name: String? = null val url: String? = null val value: BigDecimal? = null @SerializedName("product_id") val productId: Long? = null } class WCShippingLabelRefundModel { val status: String? = null @SerializedName("request_date") val requestDate: Long? = null } }
gpl-2.0
cf456b87a7b2c6e97e04b6aef2e1b3f3
36.195266
106
0.64588
4.622059
false
false
false
false
Kotlin/kotlinx.serialization
formats/json-okio/commonMain/src/kotlinx/serialization/json/okio/OkioStreams.kt
1
5790
/* * Copyright 2017-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER") package kotlinx.serialization.json.okio import kotlinx.serialization.* import kotlinx.serialization.json.DecodeSequenceMode import kotlinx.serialization.json.Json import kotlinx.serialization.json.internal.* import kotlinx.serialization.json.okio.internal.JsonToOkioStreamWriter import kotlinx.serialization.json.internal.decodeToSequenceByReader import kotlinx.serialization.json.okio.internal.OkioSerialReader import okio.* /** * Serializes the [value] with [serializer] into a [target] using JSON format and UTF-8 encoding. * * @throws [SerializationException] if the given value cannot be serialized to JSON. * @throws [okio.IOException] If an I/O error occurs and sink can't be written to. */ @ExperimentalSerializationApi public fun <T> Json.encodeToBufferedSink( serializer: SerializationStrategy<T>, value: T, target: BufferedSink ) { val writer = JsonToOkioStreamWriter(target) try { encodeByWriter(writer, serializer, value) } finally { writer.release() } } /** * Serializes given [value] to a [target] using UTF-8 encoding and serializer retrieved from the reified type parameter. * * @throws [SerializationException] if the given value cannot be serialized to JSON. * @throws [okio.IOException] If an I/O error occurs and sink can't be written to. */ @ExperimentalSerializationApi public inline fun <reified T> Json.encodeToBufferedSink( value: T, target: BufferedSink ): Unit = encodeToBufferedSink(serializersModule.serializer(), value, target) /** * Deserializes JSON from [source] using UTF-8 encoding to a value of type [T] using [deserializer]. * * Note that this functions expects that exactly one object would be present in the source * and throws an exception if there are any dangling bytes after an object. * * @throws [SerializationException] if the given JSON input cannot be deserialized to the value of type [T]. * @throws [okio.IOException] If an I/O error occurs and source can't be read from. */ @ExperimentalSerializationApi public fun <T> Json.decodeFromBufferedSource( deserializer: DeserializationStrategy<T>, source: BufferedSource ): T { return decodeByReader(deserializer, OkioSerialReader(source)) } /** * Deserializes the contents of given [source] to the value of type [T] using UTF-8 encoding and * deserializer retrieved from the reified type parameter. * * Note that this functions expects that exactly one object would be present in the stream * and throws an exception if there are any dangling bytes after an object. * * @throws [SerializationException] if the given JSON input cannot be deserialized to the value of type [T]. * @throws [okio.IOException] If an I/O error occurs and source can't be read from. */ @ExperimentalSerializationApi public inline fun <reified T> Json.decodeFromBufferedSource(source: BufferedSource): T = decodeFromBufferedSource(serializersModule.serializer(), source) /** * Transforms the given [source] into lazily deserialized sequence of elements of type [T] using UTF-8 encoding and [deserializer]. * Unlike [decodeFromBufferedSource], [source] is allowed to have more than one element, separated as [format] declares. * * Elements must all be of type [T]. * Elements are parsed lazily when resulting [Sequence] is evaluated. * Resulting sequence is tied to the stream and can be evaluated only once. * * **Resource caution:** this method neither closes the [source] when the parsing is finished nor provides a method to close it manually. * It is a caller responsibility to hold a reference to a source and close it. Moreover, because source is parsed lazily, * closing it before returned sequence is evaluated completely will result in [Exception] from decoder. * * @throws [SerializationException] if the given JSON input cannot be deserialized to the value of type [T]. * @throws [okio.IOException] If an I/O error occurs and source can't be read from. */ @ExperimentalSerializationApi public fun <T> Json.decodeBufferedSourceToSequence( source: BufferedSource, deserializer: DeserializationStrategy<T>, format: DecodeSequenceMode = DecodeSequenceMode.AUTO_DETECT ): Sequence<T> { return decodeToSequenceByReader(OkioSerialReader(source), deserializer, format) } /** * Transforms the given [source] into lazily deserialized sequence of elements of type [T] using UTF-8 encoding and deserializer retrieved from the reified type parameter. * Unlike [decodeFromBufferedSource], [source] is allowed to have more than one element, separated as [format] declares. * * Elements must all be of type [T]. * Elements are parsed lazily when resulting [Sequence] is evaluated. * Resulting sequence is tied to the stream and constrained to be evaluated only once. * * **Resource caution:** this method does not close [source] when the parsing is finished neither provides method to close it manually. * It is a caller responsibility to hold a reference to a source and close it. Moreover, because source is parsed lazily, * closing it before returned sequence is evaluated fully would result in [Exception] from decoder. * * @throws [SerializationException] if the given JSON input cannot be deserialized to the value of type [T]. * @throws [okio.IOException] If an I/O error occurs and source can't be read from. */ @ExperimentalSerializationApi public inline fun <reified T> Json.decodeBufferedSourceToSequence( source: BufferedSource, format: DecodeSequenceMode = DecodeSequenceMode.AUTO_DETECT ): Sequence<T> = decodeBufferedSourceToSequence(source, serializersModule.serializer(), format)
apache-2.0
fb80ef455f13e8fb9dfc1a76a8f567c2
44.952381
171
0.767358
4.484895
false
false
false
false
mediathekview/MediathekView
src/main/java/mediathek/tool/affinity/WindowsAffinity.kt
1
1333
package mediathek.tool.affinity import com.sun.jna.Native import com.sun.jna.Pointer import com.sun.jna.platform.win32.Kernel32 import com.sun.jna.platform.win32.WinNT.HANDLE import org.apache.logging.log4j.LogManager import java.util.* class WindowsAffinity : IAffinity { override fun setDesiredCpuAffinity(numCpus: Int) { val pid = -1 // current process val bitSet = BitSet() bitSet[0] = numCpus val affinity = bitSet.stream() .takeWhile { i: Int -> i < java.lang.Long.SIZE } .mapToLong { i: Int -> 1L shl i } .reduce(0) { a: Long, b: Long -> a or b } val affinityMask = affinity.toInt() val instance = Native.load("Kernel32", AffinityKernel::class.java) val result = instance.SetProcessAffinityMask(HANDLE(Pointer(pid.toLong())), affinityMask) if (result) { logger.info("CPU affinity was set successfully.") logger.trace("Available processors: {}", Runtime.getRuntime().availableProcessors()) } else logger.warn("Failed to set CPU affinity.") } private interface AffinityKernel : Kernel32 { fun SetProcessAffinityMask(hProcess: HANDLE?, dwProcessAffinityMask: Int): Boolean } companion object { private val logger = LogManager.getLogger() } }
gpl-3.0
7a43a43cd1f3cbd3236c29972a1b8790
37.114286
97
0.653413
4.076453
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/action/NewLatexFileAction.kt
1
5235
package nl.hannahsten.texifyidea.action import com.intellij.ide.actions.CreateElementActionBase import com.intellij.ide.actions.CreateFileFromTemplateDialog import com.intellij.ide.actions.CreateFileFromTemplateDialog.FileCreator import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import nl.hannahsten.texifyidea.TexifyIcons import nl.hannahsten.texifyidea.file.* import nl.hannahsten.texifyidea.templates.LatexTemplatesFactory import nl.hannahsten.texifyidea.templates.LatexTemplatesFactory.Companion.createFromTemplate import nl.hannahsten.texifyidea.util.appendExtension import nl.hannahsten.texifyidea.util.files.FileUtil.fileTypeByExtension import java.util.* /** * @author Hannah Schellekens */ class NewLatexFileAction : CreateElementActionBase("LaTeX File", "Create a new LaTeX file", TexifyIcons.LATEX_FILE) { override fun invokeDialog(project: Project, psiDirectory: PsiDirectory, elementsConsumer: java.util.function.Consumer<Array<PsiElement>>) { val fileCreator = LatexFileCreator(project, psiDirectory) val builder = CreateFileFromTemplateDialog.createDialog(project) builder.setTitle("Create a New LaTeX File") builder.addKind("Sources (.tex)", TexifyIcons.LATEX_FILE, OPTION_TEX_FILE) builder.addKind("Bibliography (.bib)", TexifyIcons.BIBLIOGRAPHY_FILE, OPTION_BIB_FILE) builder.addKind("Package (.sty)", TexifyIcons.STYLE_FILE, OPTION_STY_FILE) builder.addKind("Document class (.cls)", TexifyIcons.CLASS_FILE, OPTION_CLS_FILE) builder.addKind("TikZ (.tikz)", TexifyIcons.TIKZ_FILE, OPTION_TIKZ_FILE) val consumer = com.intellij.util.Consumer<PsiElement> { } builder.show<PsiElement>("", null, fileCreator, consumer) } override fun create(s: String, psiDirectory: PsiDirectory): Array<PsiElement> { return arrayOf() } override fun getErrorTitle(): String { return "Error" } override fun getActionName(psiDirectory: PsiDirectory, s: String): String { return "" } private inner class LatexFileCreator(private val project: Project, private val directory: PsiDirectory) : FileCreator<PsiElement?> { private fun openFile(virtualFile: VirtualFile) { val fileEditorManager = FileEditorManager.getInstance(project) fileEditorManager.openFile(virtualFile, true) } private fun getTemplateNameFromExtension(extensionWithoutDot: String): String { return when (extensionWithoutDot) { OPTION_STY_FILE -> LatexTemplatesFactory.fileTemplateSty OPTION_CLS_FILE -> LatexTemplatesFactory.fileTemplateCls OPTION_BIB_FILE -> LatexTemplatesFactory.fileTemplateBib OPTION_TIKZ_FILE -> LatexTemplatesFactory.fileTemplateTikz else -> LatexTemplatesFactory.fileTemplateTex } } private fun getFileType(fileName: String, option: String): FileType { val smallFileName = fileName.lowercase(Locale.getDefault()) if (smallFileName.endsWith(".$OPTION_TEX_FILE")) { return LatexFileType } if (smallFileName.endsWith(".$OPTION_CLS_FILE")) { return ClassFileType } if (smallFileName.endsWith(".$OPTION_STY_FILE")) { return StyleFileType } if (smallFileName.endsWith(".$OPTION_BIB_FILE")) { return BibtexFileType } return if (smallFileName.endsWith(".$OPTION_TIKZ_FILE")) { TikzFileType } else fileTypeByExtension(option) } private fun getNewFileName(fileName: String, fileType: FileType): String { val smallFileName = fileName.lowercase(Locale.getDefault()) return if (smallFileName.endsWith("." + fileType.defaultExtension)) { smallFileName } else fileName.appendExtension(fileType.defaultExtension) } override fun createFile(fileName: String, option: String): PsiElement? { val fileType = getFileType(fileName, option) val newFileName = getNewFileName(fileName, fileType) val templateName = getTemplateNameFromExtension(fileType.defaultExtension) val file = createFromTemplate( directory, newFileName, templateName, fileType ) openFile(file.virtualFile) return file } override fun getActionName(fileName: String, option: String): String { return "New LaTeX File" } override fun startInWriteAction(): Boolean { return false } } companion object { private const val OPTION_TEX_FILE = "tex" private const val OPTION_STY_FILE = "sty" private const val OPTION_CLS_FILE = "cls" private const val OPTION_BIB_FILE = "bib" private const val OPTION_TIKZ_FILE = "tikz" } }
mit
4a5f0b572270acd5bd432e02f2d7e196
41.225806
143
0.674499
4.915493
false
false
false
false
FHannes/intellij-community
plugins/stats-collector/src/com/intellij/stats/completion/experiment/StatusInfoProvider.kt
11
3626
/* * 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.experiment import com.google.gson.Gson import com.google.gson.internal.LinkedTreeMap import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.application.PermanentInstallationID import com.intellij.stats.completion.RequestService import com.intellij.stats.completion.assertNotEDT interface WebServiceStatusProvider { fun updateStatus() fun getDataServerUrl(): String fun getExperimentVersion(): Int fun isServerOk(): Boolean fun getSalt(): String } fun WebServiceStatusProvider.isPerformExperiment(): Boolean { val uid = PermanentInstallationID.get() val hash = (uid + getSalt()).hashCode() return hash % 2 == 0 } class StatusInfoProvider(private val requestSender: RequestService): WebServiceStatusProvider { companion object { private val gson = Gson() private val statusUrl = "https://www.jetbrains.com/config/features-service-status.json" private val salt = "completion.stats.experiment.salt" private val experimentVersionString = "completion.stats.experiment.version" } @Volatile private var statusInfo = loadInfo() @Volatile private var serverStatus = "" @Volatile private var dataServerUrl = "" override fun getExperimentVersion() = statusInfo.experimentVersion override fun getDataServerUrl(): String = dataServerUrl override fun isServerOk(): Boolean = serverStatus.equals("ok", ignoreCase = true) override fun getSalt() = statusInfo.salt override fun updateStatus() { serverStatus = "" dataServerUrl = "" assertNotEDT() val response = requestSender.get(statusUrl) if (response != null && response.isOK()) { val map = gson.fromJson(response.text, LinkedTreeMap::class.java) val salt = map["salt"]?.toString() val experimentVersion = map["experimentVersion"]?.toString() if (salt != null && experimentVersion != null) { //should be Int always val floatVersion = experimentVersion.toFloat() statusInfo = ExperimentInfo(floatVersion.toInt(), salt) saveInfo(statusInfo) } serverStatus = map["status"]?.toString() ?: "" dataServerUrl = map["urlForZipBase64Content"]?.toString() ?: "" } } private fun loadInfo(): ExperimentInfo { val component = PropertiesComponent.getInstance() val salt = component.getValue(salt) ?: "" val experimentVersion = component.getInt(experimentVersionString, 0) return ExperimentInfo(experimentVersion, salt) } private fun saveInfo(info: ExperimentInfo) { val component = PropertiesComponent.getInstance() component.setValue(salt, info.salt) component.setValue(experimentVersionString, info.experimentVersion.toString()) } } data class ExperimentInfo(var experimentVersion: Int, var salt: String)
apache-2.0
81876aec1d190e914c79d4f49b9381ae
34.213592
95
0.688086
4.777339
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/viewmodels/mobile/AudioBrowserViewModel.kt
1
4112
/***************************************************************************** * AudioBrowserViewModel.kt ***************************************************************************** * Copyright © 2019 VLC authors and VideoLAN * * 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 2 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ package org.videolan.vlc.viewmodels.mobile import android.content.Context import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import androidx.lifecycle.viewModelScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import kotlinx.coroutines.launch import org.videolan.vlc.gui.audio.AudioBrowserFragment import org.videolan.vlc.providers.medialibrary.AlbumsProvider import org.videolan.vlc.providers.medialibrary.ArtistsProvider import org.videolan.vlc.providers.medialibrary.GenresProvider import org.videolan.vlc.providers.medialibrary.TracksProvider import org.videolan.resources.KEY_AUDIO_CURRENT_TAB import org.videolan.tools.KEY_ARTISTS_SHOW_ALL import org.videolan.tools.Settings import org.videolan.vlc.viewmodels.MedialibraryViewModel @ExperimentalCoroutinesApi class AudioBrowserViewModel(context: Context) : MedialibraryViewModel(context) { var currentTab = Settings.getInstance(context).getInt(KEY_AUDIO_CURRENT_TAB, 0) val artistsProvider = ArtistsProvider(context, this, Settings.getInstance(context).getBoolean(KEY_ARTISTS_SHOW_ALL, false)) val albumsProvider = AlbumsProvider(null, context, this) val tracksProvider = TracksProvider(null, context, this) val genresProvider = GenresProvider(context, this) override val providers = arrayOf(artistsProvider, albumsProvider, tracksProvider, genresProvider) private val settings = Settings.getInstance(context) val providersInCard = arrayOf(true, true, false, false) var showResumeCard = settings.getBoolean("audio_resume_card", true) val displayModeKeys = arrayOf("display_mode_audio_browser_artists", "display_mode_audio_browser_albums", "display_mode_audio_browser_track") init { watchAlbums() watchArtists() watchGenres() watchMedia() //Initial state coming from preferences and falling back to [providersInCard] hardcoded values for (i in displayModeKeys.indices) { providersInCard[i] = settings.getBoolean(displayModeKeys[i], providersInCard[i]) } } override fun refresh() { artistsProvider.showAll = settings.getBoolean(KEY_ARTISTS_SHOW_ALL, false) viewModelScope.launch { providers[currentTab].awaitRefresh() for ((index, provider) in providers.withIndex()) { if (index != currentTab && provider.loading.hasObservers()) provider.awaitRefresh() } } } class Factory(val context: Context): ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel> create(modelClass: Class<T>): T { @Suppress("UNCHECKED_CAST") return AudioBrowserViewModel(context.applicationContext) as T } } } @ExperimentalCoroutinesApi @ObsoleteCoroutinesApi internal fun AudioBrowserFragment.getViewModel() = ViewModelProviders.of(requireActivity(), AudioBrowserViewModel.Factory(requireContext())).get(AudioBrowserViewModel::class.java)
gpl-2.0
bc3ffed3ee9eaa233bcdf766634af29a
44.688889
179
0.713452
4.894048
false
false
false
false
ademar111190/Studies
Projects/Reddit/app/src/main/java/ademar/study/reddit/mapper/comment/CommentMapper.kt
1
840
package ademar.study.reddit.mapper.comment import ademar.study.reddit.R import ademar.study.reddit.core.model.Comment import ademar.study.reddit.model.comment.CommentViewModel import ademar.study.reddit.view.base.BaseActivity import javax.inject.Inject class CommentMapper @Inject constructor( private val context: BaseActivity ) { fun transform(comment: Comment): CommentViewModel { val author = comment.author val text = comment.text val level = comment.level val resources = context.resources val downs = resources.getString(R.string.post_downs, comment.downs) val ups = resources.getString(R.string.post_ups, comment.ups) val comments = comment.comments.map { transform(it) } return CommentViewModel(author, text, downs, ups, level, comments) } }
mit
8f369f64bc152e1af69123511f5ab6f1
27.965517
75
0.721429
4.097561
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/compose/AddReminderDialog.kt
1
21630
package org.tasks.compose import android.content.res.Configuration import androidx.annotation.StringRes import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Autorenew import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment.Companion.CenterVertically import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.core.content.res.ResourcesCompat import com.google.android.material.composethemeadapter.MdcTheme import com.todoroo.astrid.ui.ReminderControlSetViewModel.ViewState import kotlinx.coroutines.android.awaitFrame import org.tasks.R import org.tasks.data.Alarm import org.tasks.data.Alarm.Companion.TYPE_DATE_TIME import org.tasks.data.Alarm.Companion.TYPE_RANDOM import org.tasks.data.Alarm.Companion.TYPE_REL_END import org.tasks.data.Alarm.Companion.TYPE_REL_START import org.tasks.data.Alarm.Companion.whenStarted import org.tasks.reminders.AlarmToString.Companion.getRepeatString import java.util.concurrent.TimeUnit @ExperimentalComposeUiApi object AddReminderDialog { @Composable fun AddRandomReminderDialog( viewState: ViewState, addAlarm: (Alarm) -> Unit, closeDialog: () -> Unit, ) { val time = rememberSaveable { mutableStateOf(15) } val units = rememberSaveable { mutableStateOf(0) } if (viewState.showRandomDialog) { AlertDialog( onDismissRequest = closeDialog, text = { AddRandomReminder(time, units) }, confirmButton = { Constants.TextButton(text = R.string.ok, onClick = { time.value.takeIf { it > 0 }?.let { i -> addAlarm(Alarm(0, i * units.millis, TYPE_RANDOM)) closeDialog() } }) }, dismissButton = { Constants.TextButton( text = R.string.cancel, onClick = closeDialog ) }, ) } else { time.value = 15 units.value = 0 } } @Composable fun AddCustomReminderDialog( viewState: ViewState, addAlarm: (Alarm) -> Unit, closeDialog: () -> Unit, ) { val openDialog = viewState.showCustomDialog val time = rememberSaveable { mutableStateOf(15) } val units = rememberSaveable { mutableStateOf(0) } val openRecurringDialog = rememberSaveable { mutableStateOf(false) } val interval = rememberSaveable { mutableStateOf(0) } val recurringUnits = rememberSaveable { mutableStateOf(0) } val repeat = rememberSaveable { mutableStateOf(0) } if (openDialog) { if (!openRecurringDialog.value) { AlertDialog( onDismissRequest = closeDialog, text = { AddCustomReminder( time, units, interval, recurringUnits, repeat, showRecurring = { openRecurringDialog.value = true } ) }, confirmButton = { Constants.TextButton(text = R.string.ok, onClick = { time.value.takeIf { it >= 0 }?.let { i -> addAlarm( Alarm( task = 0, time = -1 * i * units.millis, type = TYPE_REL_END, repeat = repeat.value, interval = interval.value * recurringUnits.millis ) ) closeDialog() } }) }, dismissButton = { Constants.TextButton( text = R.string.cancel, onClick = closeDialog ) }, ) } AddRepeatReminderDialog( openDialog = openRecurringDialog, initialInterval = interval.value, initialUnits = recurringUnits.value, initialRepeat = repeat.value, selected = { i, u, r -> interval.value = i recurringUnits.value = u repeat.value = r } ) } else { time.value = 15 units.value = 0 interval.value = 0 recurringUnits.value = 0 repeat.value = 0 } } @Composable fun AddRepeatReminderDialog( openDialog: MutableState<Boolean>, initialInterval: Int, initialUnits: Int, initialRepeat: Int, selected: (Int, Int, Int) -> Unit, ) { val interval = rememberSaveable { mutableStateOf(initialInterval) } val units = rememberSaveable { mutableStateOf(initialUnits) } val repeat = rememberSaveable { mutableStateOf(initialRepeat) } val closeDialog = { openDialog.value = false } if (openDialog.value) { AlertDialog( onDismissRequest = closeDialog, text = { AddRecurringReminder( openDialog.value, interval, units, repeat, ) }, confirmButton = { Constants.TextButton(text = R.string.ok, onClick = { if (interval.value > 0 && repeat.value > 0) { selected(interval.value, units.value, repeat.value) openDialog.value = false } }) }, dismissButton = { Constants.TextButton( text = R.string.cancel, onClick = closeDialog ) }, ) } else { interval.value = initialInterval.takeIf { it > 0 } ?: 15 units.value = initialUnits repeat.value = initialRepeat.takeIf { it > 0 } ?: 4 } } @Composable fun AddRandomReminder( time: MutableState<Int>, units: MutableState<Int>, ) { val scrollState = rememberScrollState() Column( modifier = Modifier .fillMaxWidth() .verticalScroll(scrollState) ) { CenteredH6(text = stringResource(id = R.string.randomly_every, "").trim()) val focusRequester = remember { FocusRequester() } OutlinedIntInput( time, modifier = Modifier .fillMaxWidth() .focusRequester(focusRequester) ) Spacer(modifier = Modifier.height(16.dp)) options.forEachIndexed { index, option -> RadioRow(index, option, time, units) } ShowKeyboard(true, focusRequester) } } @Composable fun AddCustomReminder( time: MutableState<Int>, units: MutableState<Int>, interval: MutableState<Int>, recurringUnits: MutableState<Int>, repeat: MutableState<Int>, showRecurring: () -> Unit, ) { val scrollState = rememberScrollState() Column( modifier = Modifier .fillMaxWidth() .verticalScroll(scrollState) ) { CenteredH6(resId = R.string.custom_notification) val focusRequester = remember { FocusRequester() } OutlinedIntInput( time, minValue = 0, modifier = Modifier .fillMaxWidth() .focusRequester(focusRequester) ) Spacer(modifier = Modifier.height(16.dp)) options.forEachIndexed { index, option -> RadioRow(index, option, time, units, R.string.alarm_before_due) } Divider(modifier = Modifier.padding(vertical = 4.dp), thickness = 1.dp) Row(modifier = Modifier .fillMaxWidth() .clickable { showRecurring() }) { IconButton(onClick = showRecurring) { Icon( imageVector = Icons.Outlined.Autorenew, contentDescription = null, modifier = Modifier .align(CenterVertically) .alpha( ResourcesCompat.getFloat( LocalContext.current.resources, R.dimen.alpha_secondary ) ), ) } val repeating = repeat.value > 0 && interval.value > 0 val text = if (repeating) { LocalContext.current.resources.getRepeatString( repeat.value, interval.value * recurringUnits.millis ) } else { stringResource(id = R.string.repeat_option_does_not_repeat) } BodyText( text = text, modifier = Modifier .fillMaxWidth() .weight(1f) .align(CenterVertically) ) if (repeating) { ClearButton { repeat.value = 0 interval.value = 0 recurringUnits.value = 0 } } } ShowKeyboard(true, focusRequester) } } @Composable fun AddRecurringReminder( openDialog: Boolean, interval: MutableState<Int>, units: MutableState<Int>, repeat: MutableState<Int> ) { val scrollState = rememberScrollState() Column( modifier = Modifier .fillMaxWidth() .verticalScroll(scrollState) ) { CenteredH6(text = stringResource(id = R.string.repeats_plural, "").trim()) val focusRequester = remember { FocusRequester() } OutlinedIntInput( time = interval, modifier = Modifier.focusRequester(focusRequester), ) Spacer(modifier = Modifier.height(16.dp)) options.forEachIndexed { index, option -> RadioRow(index, option, interval, units) } Divider(modifier = Modifier.padding(vertical = 4.dp), thickness = 1.dp) Row(modifier = Modifier.fillMaxWidth()) { OutlinedIntInput( time = repeat, modifier = Modifier.weight(0.5f), autoSelect = false, ) BodyText( text = LocalContext.current.resources.getQuantityString( R.plurals.repeat_times, repeat.value ), modifier = Modifier .weight(0.5f) .align(CenterVertically) ) } ShowKeyboard(openDialog, focusRequester) } } private val options = listOf( R.plurals.reminder_minutes, R.plurals.reminder_hours, R.plurals.reminder_days, R.plurals.reminder_week, ) private val MutableState<Int>.millis: Long get() = when (value) { 1 -> TimeUnit.HOURS.toMillis(1) 2 -> TimeUnit.DAYS.toMillis(1) 3 -> TimeUnit.DAYS.toMillis(7) else -> TimeUnit.MINUTES.toMillis(1) } } @ExperimentalComposeUiApi @Composable fun ShowKeyboard(visible: Boolean, focusRequester: FocusRequester) { val keyboardController = LocalSoftwareKeyboardController.current LaunchedEffect(visible) { focusRequester.freeFocus() awaitFrame() focusRequester.requestFocus() keyboardController?.show() } } @Composable fun OutlinedIntInput( time: MutableState<Int>, modifier: Modifier = Modifier, minValue: Int = 1, autoSelect: Boolean = true, ) { val value = rememberSaveable(stateSaver = TextFieldValue.Saver) { val text = time.value.toString() mutableStateOf( TextFieldValue( text = text, selection = TextRange(0, if (autoSelect) text.length else 0) ) ) } OutlinedTextField( value = value.value, onValueChange = { value.value = it.copy(text = it.text.filter { t -> t.isDigit() }) time.value = value.value.text.toIntOrNull() ?: 0 }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), modifier = modifier.padding(horizontal = 16.dp), colors = TextFieldDefaults.outlinedTextFieldColors( textColor = MaterialTheme.colors.onSurface, focusedBorderColor = MaterialTheme.colors.onSurface ), isError = value.value.text.toIntOrNull()?.let { it < minValue } ?: true, ) } @Composable fun CenteredH6(@StringRes resId: Int) { CenteredH6(text = stringResource(id = resId)) } @Composable fun CenteredH6(text: String) { Text( text = text, textAlign = TextAlign.Center, modifier = Modifier .fillMaxWidth() .padding(vertical = 16.dp), color = MaterialTheme.colors.onSurface, style = MaterialTheme.typography.h6 ) } @Composable fun RadioRow( index: Int, option: Int, time: MutableState<Int>, units: MutableState<Int>, formatString: Int? = null, ) { val optionString = LocalContext.current.resources.getQuantityString(option, time.value) Row( modifier = Modifier .fillMaxWidth() .clickable { units.value = index } ) { RadioButton( selected = index == units.value, onClick = { units.value = index }, modifier = Modifier.align(CenterVertically) ) BodyText( text = if (index == units.value) { formatString ?.let { stringResource(id = formatString, optionString) } ?: optionString } else { optionString }, modifier = Modifier.align(CenterVertically), ) } } @Composable fun BodyText(modifier: Modifier = Modifier, text: String) { Text( text = text, modifier = modifier, color = MaterialTheme.colors.onSurface, style = MaterialTheme.typography.body1, ) } @Composable fun AddAlarmDialog( viewState: ViewState, existingAlarms: List<Alarm>, addAlarm: (Alarm) -> Unit, addRandom: () -> Unit, addCustom: () -> Unit, pickDateAndTime: () -> Unit, dismiss: () -> Unit, ) { if (viewState.showAddAlarm) { when (viewState.replace?.type) { TYPE_RANDOM -> { addRandom() dismiss() return } TYPE_DATE_TIME -> { pickDateAndTime() dismiss() return } // TODO: if replacing custom alarm show custom picker // TODO: prepopulate pickers with existing values } } CustomDialog(visible = viewState.showAddAlarm, onDismiss = dismiss) { Column(modifier = Modifier.padding(vertical = 4.dp)) { if (existingAlarms.none { it.type == TYPE_REL_START && it.time == 0L }) { DialogRow(text = R.string.when_started) { addAlarm(whenStarted(0)) dismiss() } } if (existingAlarms.none { it.type == TYPE_REL_END && it.time == 0L }) { DialogRow(text = R.string.when_due) { addAlarm(Alarm.whenDue(0)) dismiss() } } if (existingAlarms.none { it.type == TYPE_REL_END && it.time == TimeUnit.HOURS.toMillis(24) }) { DialogRow(text = R.string.when_overdue) { addAlarm(Alarm.whenOverdue(0)) dismiss() } } DialogRow(text = R.string.randomly) { addRandom() dismiss() } DialogRow(text = R.string.pick_a_date_and_time) { pickDateAndTime() dismiss() } DialogRow(text = R.string.repeat_option_custom) { addCustom() dismiss() } } } } @ExperimentalComposeUiApi @Preview(showBackground = true) @Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable fun AddCustomReminderOne() = MdcTheme { AddReminderDialog.AddCustomReminder( time = remember { mutableStateOf(1) }, units = remember { mutableStateOf(0) }, interval = remember { mutableStateOf(0) }, recurringUnits = remember { mutableStateOf(0) }, repeat = remember { mutableStateOf(0) }, showRecurring = {}, ) } @ExperimentalComposeUiApi @Preview(showBackground = true) @Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable fun AddCustomReminder() = MdcTheme { AddReminderDialog.AddCustomReminder( time = remember { mutableStateOf(15) }, units = remember { mutableStateOf(1) }, interval = remember { mutableStateOf(0) }, recurringUnits = remember { mutableStateOf(0) }, repeat = remember { mutableStateOf(0) }, showRecurring = {}, ) } @ExperimentalComposeUiApi @Preview(showBackground = true) @Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable fun AddRepeatingReminderOne() = MdcTheme { AddReminderDialog.AddRecurringReminder( openDialog = true, interval = remember { mutableStateOf(1) }, units = remember { mutableStateOf(0) }, repeat = remember { mutableStateOf(1) }, ) } @ExperimentalComposeUiApi @Preview(showBackground = true) @Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable fun AddRepeatingReminder() = MdcTheme { AddReminderDialog.AddRecurringReminder( openDialog = true, interval = remember { mutableStateOf(15) }, units = remember { mutableStateOf(1) }, repeat = remember { mutableStateOf(4) }, ) } @ExperimentalComposeUiApi @Preview(showBackground = true) @Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable fun AddRandomReminderOne() = MdcTheme { AddReminderDialog.AddRandomReminder( time = remember { mutableStateOf(1) }, units = remember { mutableStateOf(0) } ) } @ExperimentalComposeUiApi @Preview(showBackground = true) @Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable fun AddRandomReminder() = MdcTheme { AddReminderDialog.AddRandomReminder( time = remember { mutableStateOf(15) }, units = remember { mutableStateOf(1) } ) } @Preview(showBackground = true) @Preview(showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable fun AddReminderDialog() = MdcTheme { AddAlarmDialog( viewState = ViewState(showAddAlarm = true), existingAlarms = emptyList(), addAlarm = {}, addRandom = {}, addCustom = {}, pickDateAndTime = {}, dismiss = {}, ) }
gpl-3.0
7895ac12549a01f79fe4f9b61de849bd
33.389507
91
0.528294
5.230955
false
false
false
false
adrcotfas/Goodtime
app/src/main/java/com/apps/adrcotfas/goodtime/main/FullscreenHelper.kt
1
3512
/* * Copyright 2016-2019 Adrian Cotfas * * 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.apps.adrcotfas.goodtime.main import android.annotation.SuppressLint import android.os.Handler import android.os.Looper import android.view.MotionEvent import android.view.View import androidx.appcompat.app.ActionBar @SuppressLint("ClickableViewAccessibility") internal class FullscreenHelper( private val mContentView: View, private val mActionBar: ActionBar? ) { private var mVisible = true private val mHideHandler = Handler(Looper.getMainLooper()) private val mHidePart2Runnable = Runnable { mContentView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LOW_PROFILE or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) } private val mShowPart2Runnable = Runnable { // Delayed display of UI elements mActionBar!!.show() } private val mHideRunnable = Runnable { hide() } private fun toggle() { if (mVisible) { hide() } else { show() } } fun hide() { // Hide UI first mActionBar?.hide() mVisible = false // Schedule a runnable to remove the status and navigation bar after a delay mHideHandler.removeCallbacks(mShowPart2Runnable) mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY.toLong()) } private fun show() { // Show the system bar mContentView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) mVisible = true // Schedule a runnable to display UI elements after a delay mHideHandler.removeCallbacks(mHidePart2Runnable) mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY.toLong()) } /** * Schedules a call to hide() in [delay] milliseconds, canceling any * previously scheduled calls. */ private fun delayedHide() { mHideHandler.removeCallbacks(mHideRunnable) mHideHandler.postDelayed(mHideRunnable, AUTO_HIDE_DELAY_MILLIS.toLong()) } fun disable() { mContentView.setOnClickListener(null) mContentView.setOnTouchListener(null) mHideHandler.removeCallbacks(mHideRunnable) mHideHandler.removeCallbacks(mHidePart2Runnable) show() } companion object { private const val AUTO_HIDE = true private const val AUTO_HIDE_DELAY_MILLIS = 3000 private const val UI_ANIMATION_DELAY = 300 } init { mContentView.setOnClickListener { toggle() } mContentView.setOnTouchListener { _: View?, _: MotionEvent? -> if (AUTO_HIDE) { delayedHide() } false } hide() } }
apache-2.0
b1ad5dadb62e994e48f40060870c6cdf
33.106796
128
0.666287
4.56697
false
false
false
false
olonho/carkot
server/src/main/java/net/car/server/handlers/CarConnection.kt
1
840
package net.car.server.handlers import CodedInputStream import CodedOutputStream import ConnectionRequest import ConnectionResponse import net.Handler import objects.Environment class CarConnection : Handler { override fun execute(bytesFromClient: ByteArray): ByteArray { val data = ConnectionRequest.BuilderConnectionRequest(IntArray(0), 0).build() data.mergeFrom(CodedInputStream(bytesFromClient)) val ipString = data.ipValues.map { elem -> elem.toString() }.reduce { elem1, elem2 -> elem1 + "." + elem2 } val uid = Environment.connectCar(ipString, data.port) val responseObject = ConnectionResponse.BuilderConnectionResponse(uid, 0).build() val result = ByteArray(responseObject.getSizeNoTag()) responseObject.writeTo(CodedOutputStream(result)) return result } }
mit
dea09d9ff0e0bfe021645a21bec0b655
37.227273
115
0.740476
4.640884
false
false
false
false
BOINC/boinc
android/BOINC/app/src/main/java/edu/berkeley/boinc/BOINCActivity.kt
2
18124
/* * This file is part of BOINC. * http://boinc.berkeley.edu * Copyright (C) 2021 University of California * * BOINC is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * BOINC 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with BOINC. If not, see <http://www.gnu.org/licenses/>. */ package edu.berkeley.boinc import android.app.Dialog import android.app.Service import android.content.BroadcastReceiver import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.ServiceConnection import android.content.pm.PackageManager import android.content.pm.PackageManager.PackageInfoFlags import android.content.res.Configuration import android.os.Build.VERSION import android.os.Build.VERSION_CODES import android.os.Bundle import android.os.IBinder import android.os.RemoteException import android.view.KeyEvent import android.view.Menu import android.view.MenuItem import android.view.View import android.view.Window import android.widget.AdapterView import android.widget.AdapterView.OnItemClickListener import android.widget.Button import android.widget.TextView import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatActivity import androidx.core.net.toUri import androidx.core.os.bundleOf import androidx.fragment.app.replace import androidx.lifecycle.lifecycleScope import edu.berkeley.boinc.adapter.NavDrawerListAdapter import edu.berkeley.boinc.adapter.NavDrawerListAdapter.NavDrawerItem import edu.berkeley.boinc.attach.AboutActivity import edu.berkeley.boinc.attach.AttachAccountManagerActivity import edu.berkeley.boinc.attach.SelectionListActivity import edu.berkeley.boinc.client.ClientStatus import edu.berkeley.boinc.client.IMonitor import edu.berkeley.boinc.client.Monitor import edu.berkeley.boinc.client.MonitorAsync import edu.berkeley.boinc.databinding.MainBinding import edu.berkeley.boinc.ui.eventlog.EventLogActivity import edu.berkeley.boinc.utils.Logging import edu.berkeley.boinc.utils.RUN_MODE_AUTO import edu.berkeley.boinc.utils.RUN_MODE_NEVER import edu.berkeley.boinc.utils.getColorCompat import edu.berkeley.boinc.utils.writeClientModeAsync import kotlinx.coroutines.launch class BOINCActivity : AppCompatActivity() { private var clientComputingStatus = -1 private var numberProjectsInNavList = 0 // app title (changes with nav bar selection) private var mTitle: CharSequence? = null private lateinit var binding: MainBinding // nav drawer title private var mDrawerTitle: CharSequence? = null private lateinit var mDrawerToggle: ActionBarDrawerToggle private lateinit var mDrawerListAdapter: NavDrawerListAdapter private val mConnection: ServiceConnection = object : ServiceConnection { override fun onServiceConnected(className: ComponentName, service: IBinder) { // This is called when the connection with the service has been established, getService returns // the Monitor object that is needed to call functions. monitor = MonitorAsync(IMonitor.Stub.asInterface(service)) mIsBound = true determineStatus() } override fun onServiceDisconnected(className: ComponentName) { // This should not happen monitor = null mIsBound = false Logging.logError(Logging.Category.GUI_ACTIVITY, "BOINCActivity onServiceDisconnected") } } private val mClientStatusChangeRec: BroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { Logging.logVerbose(Logging.Category.CLIENT, "BOINCActivity ClientStatusChange - onReceive()") determineStatus() } } private val ifcsc = IntentFilter("edu.berkeley.boinc.clientstatuschange") public override fun onCreate(savedInstanceState: Bundle?) { Logging.logVerbose(Logging.Category.GUI_ACTIVITY, "BOINCActivity onCreate()") super.onCreate(savedInstanceState) binding = MainBinding.inflate(layoutInflater) setContentView(binding.root) // setup navigation bar mDrawerTitle = title mTitle = mDrawerTitle binding.drawerList.onItemClickListener = OnItemClickListener { _: AdapterView<*>?, _: View?, position: Int, _: Long -> // display view for selected nav drawer item dispatchNavBarOnClick(mDrawerListAdapter.getItem(position), false) } mDrawerListAdapter = NavDrawerListAdapter(this) binding.drawerList.adapter = mDrawerListAdapter // enabling action bar app icon and behaving it as toggle button supportActionBar!!.setDisplayHomeAsUpEnabled(true) supportActionBar!!.setHomeButtonEnabled(true) mDrawerToggle = object : ActionBarDrawerToggle(this, binding.drawerLayout, R.string.app_name, // nav drawer openapplicationContext - description for accessibility R.string.app_name // nav drawer close - description for accessibility ) { override fun onDrawerClosed(view: View) { supportActionBar!!.title = mTitle // calling onPrepareOptionsMenu() to show action bar icons invalidateOptionsMenu() } override fun onDrawerOpened(drawerView: View) { supportActionBar!!.title = mDrawerTitle // force redraw of all items (adapter.getView()) in order to adapt changing icons or number of tasks/notices mDrawerListAdapter.notifyDataSetChanged() // calling onPrepareOptionsMenu() to hide action bar icons invalidateOptionsMenu() } } mDrawerToggle.drawerArrowDrawable.color = getColorCompat(R.color.white) binding.drawerLayout.addDrawerListener(mDrawerToggle) // pre-select fragment // 1. check if explicitly requested fragment present // e.g. after initial project attach. var targetFragId = intent.getIntExtra("targetFragment", -1) // 2. if no explicit request, try to restore previous selection if (targetFragId < 0 && savedInstanceState != null) { targetFragId = savedInstanceState.getInt("navBarSelectionId") } val item: NavDrawerItem? = if (targetFragId < 0) { // if none of the above, go to default mDrawerListAdapter.getItem(0) } else { mDrawerListAdapter.getItemForId(targetFragId) } if (item != null) { dispatchNavBarOnClick(item, true) } else { Logging.logWarning(Logging.Category.GUI_ACTIVITY, "onCreate: fragment selection returned null") } //bind monitor service doBindService() } override fun onSaveInstanceState(outState: Bundle) { outState.putInt("navBarSelectionId", mDrawerListAdapter.selectedMenuId) super.onSaveInstanceState(outState) } override fun onDestroy() { Logging.logVerbose(Logging.Category.GUI_ACTIVITY, "BOINCActivity onDestroy()") doUnbindService() super.onDestroy() } override fun onNewIntent(intent: Intent) { Logging.logVerbose(Logging.Category.GUI_ACTIVITY, "BOINCActivity onNewIntent()") // onNewIntent gets called if activity is brought to front via intent, but was still alive, so onCreate is not called again // getIntent always returns the intent activity was created of, so this method is the only hook to receive an updated intent // e.g. after (not initial) project attach super.onNewIntent(intent) // navigate to explicitly requested fragment (e.g. after project attach) val id = intent.getIntExtra("targetFragment", -1) Logging.logDebug(Logging.Category.GUI_ACTIVITY, "BOINCActivity onNewIntent() for target fragment: $id") val item: NavDrawerItem? = if (id < 0) { // if ID is -1, go to default mDrawerListAdapter.getItem(0) } else { mDrawerListAdapter.getItemForId(id) } dispatchNavBarOnClick(item, false) } override fun onResume() { // gets called by system every time activity comes to front. after onCreate upon first creation super.onResume() registerReceiver(mClientStatusChangeRec, ifcsc) determineStatus() } override fun onPause() { // gets called by system every time activity loses focus. Logging.logDebug(Logging.Category.GUI_ACTIVITY, "BOINCActivity onPause()") super.onPause() unregisterReceiver(mClientStatusChangeRec) } private fun doBindService() { // start service to allow setForeground later on... startService(Intent(this, Monitor::class.java)) // Establish a connection with the service, onServiceConnected gets called when bindService(Intent(this, Monitor::class.java), mConnection, Service.BIND_AUTO_CREATE) } private fun doUnbindService() { if (mIsBound) { // Detach existing connection. unbindService(mConnection) mIsBound = false } } /** * React to selection of nav bar item * * @param item Nav bar item * @param init Initialize */ private fun dispatchNavBarOnClick(item: NavDrawerItem?, init: Boolean) { // update the main content by replacing fragments if (item == null) { Logging.logWarning(Logging.Category.USER_ACTION, "dispatchNavBarOnClick returns, item null.") return } Logging.logVerbose(Logging.Category.USER_ACTION, "dispatchNavBarOnClick for item with id: ${item.id} title: ${item.title}" + " is project? ${item.isProjectItem}") val ft = supportFragmentManager.beginTransaction() var fragmentChanges = false if (init) { // if init, setup status fragment ft.replace<StatusFragment>(R.id.status_container) } if (!item.isProjectItem) { when (item.id) { R.string.tab_tasks -> { ft.replace<TasksFragment>(R.id.frame_container) fragmentChanges = true } R.string.tab_notices -> { ft.replace<NoticesFragment>(R.id.frame_container) fragmentChanges = true } R.string.tab_projects -> { ft.replace<ProjectsFragment>(R.id.frame_container) fragmentChanges = true } R.string.menu_help -> startActivity(Intent(Intent.ACTION_VIEW, "https://boinc.berkeley.edu/wiki/BOINC_Help".toUri())) R.string.menu_report_issue -> startActivity(Intent(Intent.ACTION_VIEW, "https://boinc.berkeley.edu/trac/wiki/ReportBugs".toUri())) R.string.menu_about -> startActivity(Intent(this, AboutActivity::class.java)) R.string.menu_eventlog -> startActivity(Intent(this, EventLogActivity::class.java)) R.string.projects_add -> startActivity(Intent(this, SelectionListActivity::class.java)) R.string.attachproject_acctmgr_header -> startActivity(Intent(this, AttachAccountManagerActivity::class.java)) R.string.tab_preferences -> { ft.replace<SettingsFragment>(R.id.frame_container) fragmentChanges = true } else -> Logging.logError(Logging.Category.USER_ACTION, "dispatchNavBarOnClick() could not find corresponding fragment for" + " ${item.title}") } } else { // ProjectDetailsFragment. Data shown based on given master URL ft.replace<ProjectDetailsFragment>(R.id.frame_container, args = bundleOf("url" to item.projectMasterUrl)) fragmentChanges = true } binding.drawerLayout.closeDrawer(binding.drawerList) if (fragmentChanges) { ft.commit() title = item.title mDrawerListAdapter.selectedMenuId = item.id //highlight item persistently mDrawerListAdapter.notifyDataSetChanged() // force redraw } Logging.logDebug(Logging.Category.USER_ACTION, "displayFragmentForNavDrawer() " + item.title) } // tests whether status is available and whether it changed since the last event. private fun determineStatus() { try { if (mIsBound) { val newComputingStatus = monitor!!.computingStatus if (newComputingStatus != clientComputingStatus) { // computing status has changed, update and invalidate to force adaption of action items clientComputingStatus = newComputingStatus invalidateOptionsMenu() } if (numberProjectsInNavList != monitor!!.projects.size) { numberProjectsInNavList = mDrawerListAdapter.compareAndAddProjects(monitor!!.projects) } mDrawerListAdapter.updateUseAccountManagerItem() } } catch (e: Exception) { Logging.logException(Logging.Category.GUI_ACTIVITY, "BOINCActivity.determineStatus error: ", e) } } override fun onKeyDown(keyCode: Int, keyEvent: KeyEvent): Boolean { if (keyCode == KeyEvent.KEYCODE_MENU) { if (binding.drawerLayout.isDrawerOpen(binding.drawerList)) { binding.drawerLayout.closeDrawer(binding.drawerList) } else { binding.drawerLayout.openDrawer(binding.drawerList) } return true } return super.onKeyDown(keyCode, keyEvent) } override fun onCreateOptionsMenu(menu: Menu): Boolean { Logging.logVerbose(Logging.Category.GUI_ACTIVITY, "BOINCActivity onCreateOptionsMenu()") val inflater = menuInflater inflater.inflate(R.menu.main_menu, menu) return true } override fun onPrepareOptionsMenu(menu: Menu): Boolean { Logging.logVerbose(Logging.Category.GUI_ACTIVITY, "BOINCActivity onPrepareOptionsMenu()") // run mode, set title and icon based on status val runMode = menu.findItem(R.id.run_mode) if (clientComputingStatus == ClientStatus.COMPUTING_STATUS_NEVER) { // display play button runMode.setTitle(R.string.menu_run_mode_enable) runMode.setIcon(R.drawable.ic_baseline_play_arrow_white) } else { // display stop button runMode.setTitle(R.string.menu_run_mode_disable) runMode.setIcon(R.drawable.ic_baseline_pause_white) } return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { Logging.logVerbose(Logging.Category.USER_ACTION, "BOINCActivity onOptionsItemSelected()") // toggle drawer return if (mDrawerToggle.onOptionsItemSelected(item)) { true } else when (item.itemId) { R.id.run_mode -> { when { item.title == application.getString(R.string.menu_run_mode_disable) -> { Logging.logDebug(Logging.Category.USER_ACTION, "run mode: disable") lifecycleScope.launch { writeClientMode(RUN_MODE_NEVER) } } item.title == application.getString(R.string.menu_run_mode_enable) -> { Logging.logDebug(Logging.Category.USER_ACTION, "run mode: enable") lifecycleScope.launch { writeClientMode(RUN_MODE_AUTO) } } else -> { Logging.logDebug(Logging.Category.USER_ACTION, "run mode: unrecognized command") } } true } R.id.projects_add -> { startActivity(Intent(this, SelectionListActivity::class.java)) true } else -> super.onOptionsItemSelected(item) } } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState() } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) // Pass any configuration change to the drawer toggls mDrawerToggle.onConfigurationChanged(newConfig) } override fun setTitle(title: CharSequence) { mTitle = title supportActionBar!!.title = mTitle } private fun writeClientMode(mode: Int) { val success = writeClientModeAsync(mode) if (success) { try { monitor!!.forceRefresh() } catch (e: RemoteException) { Logging.logException(Logging.Category.GUI_ACTIVITY, "BOINCActivity.writeClientMode() error: ", e) } } else { Logging.logWarning(Logging.Category.GUI_ACTIVITY, "BOINCActivity setting run and network mode failed") } } companion object { @JvmField var monitor: MonitorAsync? = null var mIsBound = false } }
lgpl-3.0
874e0102d675de83128342dfb12853d2
40.856813
146
0.649801
5.024674
false
false
false
false
BOINC/boinc
android/BOINC/app/src/main/java/edu/berkeley/boinc/BOINCApplication.kt
3
2717
/* * This file is part of BOINC. * http://boinc.berkeley.edu * Copyright (C) 2020 University of California * * BOINC is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * BOINC 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with BOINC. If not, see <http://www.gnu.org/licenses/>. */ package edu.berkeley.boinc import android.app.NotificationChannel import android.app.NotificationManager import android.os.Build import androidx.multidex.MultiDexApplication import androidx.preference.PreferenceManager import edu.berkeley.boinc.di.AppComponent import edu.berkeley.boinc.di.DaggerAppComponent import edu.berkeley.boinc.utils.setAppTheme open class BOINCApplication : MultiDexApplication() { override fun onCreate() { super.onCreate() val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this) setAppTheme(sharedPreferences.getString("theme", "light")!!) // Create notification channels for use on API 26 and higher. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val notificationManager = getSystemService(NotificationManager::class.java) // Create main notification channel. val mainChannelName = getString(R.string.main_notification_channel_name) val mainChannel = NotificationChannel("main-channel", mainChannelName, NotificationManager.IMPORTANCE_HIGH) mainChannel.description = getString(R.string.main_notification_channel_description) notificationManager.createNotificationChannel(mainChannel) // Create notice notification channel. val noticeChannelName = getString(R.string.notice_notification_channel_name) val noticeChannel = NotificationChannel("notice-channel", noticeChannelName, NotificationManager.IMPORTANCE_HIGH) noticeChannel.description = getString(R.string.notice_notification_channel_description) notificationManager.createNotificationChannel(noticeChannel) } } val appComponent: AppComponent by lazy { DaggerAppComponent.factory().create(applicationContext) } // Override in tests. open fun initializeComponent() = DaggerAppComponent.factory().create(applicationContext) }
lgpl-3.0
95252d9ebb4b1e71b390d92e26d78051
43.540984
125
0.745307
4.994485
false
false
false
false
apixandru/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/GrReferenceResolveRunner.kt
1
10251
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.lang.resolve import com.intellij.psi.* import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.psi.util.InheritanceUtil import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.parents import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult import org.jetbrains.plugins.groovy.lang.psi.api.SpreadState import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationArrayInitializer import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.impl.GrTraitType import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyResolveResultImpl import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.ClosureParameterEnhancer import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil import org.jetbrains.plugins.groovy.lang.psi.util.treeWalkUp import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil.canResolveToMethod import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil.isDefinitelyKeyOfMap import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolverProcessorBuilder private class GrReferenceResolveRunner(val place: GrReferenceExpression, val processor: PsiScopeProcessor) { fun resolveReferenceExpression(): Boolean { val processNonCode = PsiTreeUtil.skipParentsOfType( place, GrReferenceExpression::class.java, GrAnnotationArrayInitializer::class.java ) !is GrAnnotationNameValuePair val initialState = initialState(processNonCode) val qualifier = place.qualifier if (qualifier == null) { if (!treeWalkUp(place, processor, initialState)) return false if (!processNonCode) return true if (place.context is GrMethodCall && !ClosureMissingMethodContributor.processMethodsFromClosures(place, processor)) return false } else { val state = initialState.put(ClassHint.RESOLVE_CONTEXT, qualifier) if (place.dotTokenType === GroovyTokenTypes.mSPREAD_DOT) { return processSpread(qualifier.type, state) } else { if (ResolveUtil.isClassReference(place)) return false if (!processJavaLangClass(qualifier, initialState)) return false if (!processQualifier(qualifier, initialState)) return false } } return true } private fun processJavaLangClass(qualifier: GrExpression, initialState: ResolveState): Boolean { if (qualifier !is GrReferenceExpression) return true //optimization: only 'class' or 'this' in static context can be an alias of java.lang.Class if ("class" != qualifier.referenceName && !PsiUtil.isThisReference(qualifier) && qualifier.resolve() !is PsiClass) return true val classType = ResolveUtil.unwrapClassType(qualifier.getType()) return classType?.let { processQualifierType(classType, initialState) } ?: true } private fun processQualifier(qualifier: GrExpression, state: ResolveState): Boolean { val qualifierType = qualifier.type if (qualifierType == null || PsiType.VOID == qualifierType) { if (qualifier is GrReferenceExpression) { val resolved = qualifier.resolve() if (resolved is PsiClass) { if (!ResolveUtil.processClassDeclarations((resolved as PsiClass?)!!, processor, state, null, place)) return false } else if (resolved != null && !resolved.processDeclarations(processor, state, null, place)) return false if (resolved !is PsiPackage) { val objectQualifier = TypesUtil.getJavaLangObject(place) if (!processQualifierType(objectQualifier, state)) return false } } } else { if (!processQualifierType(qualifierType, state)) return false } return true } private fun processQualifierType(qualifierType: PsiType, state: ResolveState): Boolean { val type = (qualifierType as? PsiDisjunctionType)?.leastUpperBound ?: qualifierType return doProcessQualifierType(type, state) } private fun doProcessQualifierType(qualifierType: PsiType, state: ResolveState): Boolean { if (qualifierType is PsiIntersectionType) { return qualifierType.conjuncts.find { !processQualifierType(it, state) } == null } if (qualifierType is PsiCapturedWildcardType) { val wildcard = qualifierType.wildcard if (wildcard.isExtends) { return processQualifierType(wildcard.extendsBound, state) } } if (qualifierType is PsiWildcardType) { if (qualifierType.isExtends) { return processQualifierType(qualifierType.extendsBound, state) } } // Process trait type conjuncts in reversed order because last applied trait matters. if (qualifierType is GrTraitType) return qualifierType.conjuncts.findLast { !processQualifierType(it, state) } == null if (qualifierType is PsiClassType) { val qualifierResult = qualifierType.resolveGenerics() qualifierResult.element?.let { val resolveState = state.put(PsiSubstitutor.KEY, qualifierResult.substitutor) if (!ResolveUtil.processClassDeclarations(it, processor, resolveState, null, place)) return false } } else if (qualifierType is PsiPrimitiveType) { val boxedType = qualifierType.getBoxedType(place) ?: return true return processQualifierType(boxedType, state) } else if (qualifierType is PsiArrayType) { GroovyPsiManager.getInstance(place.project).getArrayClass(qualifierType.componentType)?.let { if (!ResolveUtil.processClassDeclarations(it, processor, state, null, place)) return false } } if (place.parent !is GrMethodCall && InheritanceUtil.isInheritor(qualifierType, CommonClassNames.JAVA_UTIL_COLLECTION)) { if (!processSpread(qualifierType, state)) return false } if (state.processNonCodeMembers()) { if (!ResolveUtil.processCategoryMembers(place, processor, state)) return false if (!ResolveUtil.processNonCodeMembers(qualifierType, processor, place, state)) return false } return true } private fun processSpread(qualifierType: PsiType?, state: ResolveState): Boolean { val componentType = ClosureParameterEnhancer.findTypeForIteration(qualifierType, place) ?: return true val spreadState = SpreadState.create(qualifierType, state.get(SpreadState.SPREAD_STATE)) return processQualifierType(componentType, state.put(SpreadState.SPREAD_STATE, spreadState)) } } fun GrReferenceExpression.getCallVariants(upToArgument: GrExpression?): Array<out GroovyResolveResult> { val processor = GroovyResolverProcessorBuilder.builder() .setAllVariants(true) .setUpToArgument(upToArgument) .build(this) GrReferenceResolveRunner(this, processor).resolveReferenceExpression() return processor.candidatesArray } fun GrReferenceExpression.resolveReferenceExpression(forceRValue: Boolean, incomplete: Boolean): Array<out GroovyResolveResult> { resolvePackageOrClass()?.let { return arrayOf(it) } resolveLocalVariable()?.let { return arrayOf(it) } if (!canResolveToMethod(this) && isDefinitelyKeyOfMap(this)) return GroovyResolveResult.EMPTY_ARRAY val processor = GroovyResolverProcessorBuilder.builder() .setForceRValue(forceRValue) .setIncomplete(incomplete) .build(this) GrReferenceResolveRunner(this, processor).resolveReferenceExpression() return processor.candidatesArray } private fun GrReferenceExpression.resolvePackageOrClass(): GroovyResolveResult? { return doResolvePackageOrClass()?.let { GroovyResolveResultImpl(it, true) } } private fun GrReferenceExpression.doResolvePackageOrClass(): PsiElement? { val facade = JavaPsiFacade.getInstance(project) val scope = resolveScope fun GrReferenceExpression.resolveClass(): PsiClass? { if (parent is GrMethodCall) return null val name = referenceName ?: return null if (name.isEmpty() || !name.first().isUpperCase()) return null val qname = getQualifiedReferenceName() ?: return null return facade.findClass(qname, scope) } if (isQualified) { resolveClass()?.let { return it } } for (parent in parents().drop(1)) { if (parent !is GrReferenceExpression) return null if (parent.resolveClass() == null) continue val qname = getQualifiedReferenceName()!! return facade.findPackage(qname) } return null } private fun GrReferenceExpression.resolveLocalVariable(): GroovyResolveResult? { if (isQualified) return null val name = referenceName ?: return null val state = ResolveState.initial() val processor = VariableProcessor(name) treeWalkUp(processor, state) return processor.result } private fun GrReferenceElement<*>.getQualifiedReferenceName(): String? { val parts = mutableListOf<String>() var current = this while (true) { val name = current.referenceName ?: return null parts.add(name) val qualifier = current.qualifier ?: break qualifier as? GrReferenceExpression ?: return null current = qualifier } return parts.reversed().joinToString(separator = ".") }
apache-2.0
5622f842ddd79bbf59eeac1e9a68c0ee
42.621277
134
0.757975
4.670159
false
false
false
false
karollewandowski/aem-intellij-plugin
src/main/kotlin/co/nums/intellij/aem/htl/completion/provider/HtlPredefinedPropertyCompletionProvider.kt
1
1566
package co.nums.intellij.aem.htl.completion.provider import co.nums.intellij.aem.htl.definitions.* import co.nums.intellij.aem.htl.extensions.* import co.nums.intellij.aem.icons.HtlIcons import com.intellij.codeInsight.completion.* import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.util.ProcessingContext object HtlPredefinedPropertyCompletionProvider : CompletionProvider<CompletionParameters>() { private val listPropertiesElements = getPredefinedPropertiesElementsByContext(HtlPredefinedPropertyContext.LIST) private val globalObjectsPropertiesElements = getPredefinedPropertiesElementsByContext(HtlPredefinedPropertyContext.GLOBAL_PROPERTIES_OBJECT) private fun getPredefinedPropertiesElementsByContext(context: HtlPredefinedPropertyContext) = HtlPredefinedProperty.values() .filter { it.context == context } .map { it.toLookupElement() } private fun HtlPredefinedProperty.toLookupElement() = LookupElementBuilder.create(identifier) .bold() .withIcon(HtlIcons.HTL_PREDEFINED_PROPERTY) .withTypeText(type) override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { when { parameters.position.isListPropertyAccess() -> result.addAllElements(listPropertiesElements) parameters.position.isGlobalObjectPropertyAccess() -> result.addAllElements(globalObjectsPropertiesElements) } } }
gpl-3.0
2eda522529de773df0e039ac65738d80
43.742857
128
0.753512
5.22
false
false
false
false
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/health/service/community/HomeVisitActivity.kt
1
5822
/* * Copyright (c) 2018 NECTEC * National Electronics and Computer Technology Center, Thailand * * 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 ffc.app.health.service.community import android.app.Activity import android.net.Uri import android.os.Bundle import ffc.android.disable import ffc.android.enable import ffc.android.find import ffc.android.getExtra import ffc.android.loadDrawableBottom import ffc.android.observe import ffc.android.onClick import ffc.app.FamilyFolderActivity import ffc.app.R import ffc.app.auth.auth import ffc.app.dev import ffc.app.health.BodyFormFragment import ffc.app.health.VitalSignFormFragment import ffc.app.health.diagnosis.DiagnosisFormFragment import ffc.app.health.service.healthCareServicesOf import ffc.app.person.mockPerson import ffc.app.person.personId import ffc.app.person.persons import ffc.app.photo.TakePhotoFragment import ffc.app.util.Analytics import ffc.app.util.SimpleViewModel import ffc.app.util.TaskCallback import ffc.app.util.alert.handle import ffc.app.util.alert.toast import ffc.entity.Person import ffc.entity.User import ffc.entity.gson.toJson import ffc.entity.healthcare.HealthCareService import ffc.entity.update import ffc.entity.util.generateTempId import kotlinx.android.synthetic.main.activity_visit.done import kotlinx.android.synthetic.main.activity_visit.personName import timber.log.Timber class HomeVisitActivity : FamilyFolderActivity() { private val homeVisit by lazy { supportFragmentManager.find<HomeVisitFormFragment>(R.id.homeVisit) } private val vitalSign by lazy { supportFragmentManager.find<VitalSignFormFragment>(R.id.vitalSign) } private val diagnosis by lazy { supportFragmentManager.find<DiagnosisFormFragment>(R.id.diagnosis) } private val body by lazy { supportFragmentManager.find<BodyFormFragment>(R.id.body) } private val photo by lazy { supportFragmentManager.find<TakePhotoFragment>(R.id.photos) } private val providerId by lazy { auth(this).user!!.id } private val personId get() = intent.personId private val service get() = intent.getExtra<HealthCareService>("service") private val viewModel by lazy { SimpleViewModel<Person>() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_visit) dev { if (auth(this).user == null) { auth(this).user = User( generateTempId(), "hello", "world", User.Role.PROVIDER, User.Role.SURVEYOR) } if (personId == null) intent.personId = mockPerson.id } setupPersonInfo() service?.let { Timber.d("Edit visit=${it.toJson()}") homeVisit.bind(it) vitalSign.bind(it) diagnosis.bind(it) body.bind(it) photo.bind(it) } if (service == null) { diagnosis.addDefaultPrincipleDx() } done.onClick { done -> try { val visit = service ?: HealthCareService(providerId, personId!!) visit.update { homeVisit.dataInto(visit) vitalSign.dataInto(visit) diagnosis.dataInto(visit) body.dataInto(visit) photo.dataInto(visit) } Timber.d("visit=%s", visit.toJson()) done.disable() val healthCareServices = healthCareServicesOf(personId!!, org!!.id) if (visit.isTempId) { healthCareServices.add(visit, callback) Analytics.instance?.service(visit, viewModel.content.value) } else { healthCareServices.update(visit, callback) } } catch (invalid: IllegalStateException) { handle(invalid) done.enable() } catch (throwable: Throwable) { handle(throwable) done.enable() } } } val callback: TaskCallback<HealthCareService>.() -> Unit = { onComplete { Timber.d("post/put service = %s", it.toJson()) toast("บันทึกข้อมูลเรียบร้อย") setResult(Activity.RESULT_OK) finish() } onFail { done.enable() toast(it.message ?: "Something went wrong") } } private fun setupPersonInfo() { observe(viewModel.content) { if (it != null) { personName.text = it.name it.avatarUrl?.let { personName.loadDrawableBottom(Uri.parse(it)) } } else { toast("ไม่พบข้อมูลบุคคล") finish() } } observe(viewModel.exception) { it?.let { handle(it) finish() } } persons(org!!.id).person(personId!!) { onFound { viewModel.content.value = it } onNotFound { viewModel.content.value = null } onFail { viewModel.exception.value = it } } } }
apache-2.0
55575d2a0b2cd14d3ff1bed7f290057d
33.214286
104
0.621608
4.248337
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/loadingview/style/Wave.kt
1
1617
package com.tamsiree.rxui.view.loadingview.style import android.animation.ValueAnimator import android.graphics.Rect import com.tamsiree.rxui.view.loadingview.animation.SpriteAnimatorBuilder import com.tamsiree.rxui.view.loadingview.sprite.RectSprite import com.tamsiree.rxui.view.loadingview.sprite.Sprite import com.tamsiree.rxui.view.loadingview.sprite.SpriteContainer /** * @author tamsiree */ class Wave : SpriteContainer() { override fun onCreateChild(): Array<Sprite?>? { val waveItems = arrayOfNulls<Sprite>(5) for (i in waveItems.indices) { waveItems[i] = WaveItem() waveItems[i]!!.setAnimationDelay(-1200 + i * 100) } return waveItems } override fun onBoundsChange(bounds: Rect) { var bounds = bounds super.onBoundsChange(bounds) bounds = clipSquare(bounds) val rw = bounds.width() / childCount val width = bounds.width() / 5 * 3 / 5 for (i in 0 until childCount) { val sprite = getChildAt(i) val l = bounds.left + i * rw + rw / 5 val r = l + width sprite!!.setDrawBounds0(l, bounds.top, r, bounds.bottom) } } private inner class WaveItem internal constructor() : RectSprite() { override fun onCreateAnimation(): ValueAnimator? { val fractions = floatArrayOf(0f, 0.2f, 0.4f, 1f) return SpriteAnimatorBuilder(this).scaleY(fractions, 0.4f, 1f, 0.4f, 0.4f).duration(1200).easeInOut(*fractions) .build() } init { scaleY = 0.4f } } }
apache-2.0
f1be5675ad0fd55464caa196a2119005
32.708333
123
0.626469
4.032419
false
false
false
false
Popalay/Cardme
presentation/src/main/kotlin/com/popalay/cardme/presentation/screens/Screens.kt
1
548
package com.popalay.cardme.presentation.screens const val SCREEN_HOME = "SCREEN_HOME" const val SCREEN_HOLDER_DETAILS = "SCREEN_HOLDER_DETAILS" const val SCREEN_SETTINGS = "SCREEN_SETTINGS" const val SCREEN_ADD_CARD = "SCREEN_ADD_CARD" const val SCREEN_CARDS = "SCREEN_CARDS" const val SCREEN_DEBTS = "SCREEN_DEBTS" const val SCREEN_HOLDERS = "SCREEN_HOLDERS" const val SCREEN_SCAN_CARD = "SCREEN_SCAN_CARD" const val SCREEN_ADD_DEBT = "SCREEN_ADD_DEBT" const val SCREEN_TRASH = "SCREEN_TRASH" const val SCREEN_CARD_DETAILS = "SCREEN_CARD_DETAILS"
apache-2.0
e098a6bd504dd56c9d2e0e7941511fb5
41.230769
57
0.770073
3.204678
false
false
false
false
stripe/stripe-android
payments-core/src/main/java/com/stripe/android/model/SetupIntent.kt
1
8562
package com.stripe.android.model import androidx.annotation.RestrictTo import com.stripe.android.core.model.StripeModel import com.stripe.android.model.parsers.SetupIntentJsonParser import kotlinx.parcelize.Parcelize import org.json.JSONObject import java.util.regex.Pattern /** * A [SetupIntent] guides you through the process of setting up a customer's payment credentials for * future payments. * * - [Setup Intents Overview](https://stripe.com/docs/payments/setup-intents) * - [SetupIntents API Reference](https://stripe.com/docs/api/setup_intents) */ @Parcelize data class SetupIntent internal constructor( /** * Unique identifier for the object. */ override val id: String?, /** * Reason for cancellation of this [SetupIntent]. */ val cancellationReason: CancellationReason?, /** * Time at which the object was created. Measured in seconds since the Unix epoch. */ override val created: Long, /** * Country code of the user. */ @get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) val countryCode: String?, /** * The client secret of this SetupIntent. Used for client-side retrieval using a * publishable key. * * The client secret can be used to complete payment setup from your frontend. It should not * be stored, logged, embedded in URLs, or exposed to anyone other than the customer. Make * sure that you have TLS enabled on any page that includes the client secret. */ override val clientSecret: String?, /** * An arbitrary string attached to the object. Often useful for displaying to users. */ override val description: String?, /** * Has the value `true` if the object exists in live mode or the value * `false` if the object exists in test mode. */ override val isLiveMode: Boolean, /** * The expanded [PaymentMethod] represented by [paymentMethodId]. */ override val paymentMethod: PaymentMethod? = null, /** * ID of the payment method used with this [SetupIntent]. */ override val paymentMethodId: String?, /** * The list of payment method types (e.g. card) that this [SetupIntent] is allowed to set up. */ override val paymentMethodTypes: List<String>, /** * [Status](https://stripe.com/docs/payments/intents#intent-statuses) of this [SetupIntent]. */ override val status: StripeIntent.Status?, /** * Indicates how the payment method is intended to be used in the future. * * Use [StripeIntent.Usage.OnSession] if you intend to only reuse the payment method when the * customer is in your checkout flow. Use [StripeIntent.Usage.OffSession] if your customer may * or may not be in your checkout flow. If not provided, this value defaults to * [StripeIntent.Usage.OffSession]. */ val usage: StripeIntent.Usage?, /** * The error encountered in the previous [SetupIntent] confirmation. */ val lastSetupError: Error? = null, /** * Payment types that have not been activated in livemode, but have been activated in testmode. */ override val unactivatedPaymentMethods: List<String>, /** * Payment types that are accepted when paying with Link. */ override val linkFundingSources: List<String>, override val nextActionData: StripeIntent.NextActionData? ) : StripeIntent { override val nextActionType: StripeIntent.NextActionType? get() = when (nextActionData) { is StripeIntent.NextActionData.SdkData -> { StripeIntent.NextActionType.UseStripeSdk } is StripeIntent.NextActionData.RedirectToUrl -> { StripeIntent.NextActionType.RedirectToUrl } is StripeIntent.NextActionData.DisplayOxxoDetails -> { StripeIntent.NextActionType.DisplayOxxoDetails } is StripeIntent.NextActionData.VerifyWithMicrodeposits -> { StripeIntent.NextActionType.VerifyWithMicrodeposits } is StripeIntent.NextActionData.AlipayRedirect, is StripeIntent.NextActionData.BlikAuthorize, is StripeIntent.NextActionData.WeChatPayRedirect, is StripeIntent.NextActionData.UpiAwaitNotification, null -> { null } } override val isConfirmed: Boolean get() = setOf( StripeIntent.Status.Processing, StripeIntent.Status.Succeeded ).contains(status) override val lastErrorMessage: String? get() = lastSetupError?.message override fun requiresAction(): Boolean { return status === StripeIntent.Status.RequiresAction } override fun requiresConfirmation(): Boolean { return status === StripeIntent.Status.RequiresConfirmation } /** * The error encountered in the previous [SetupIntent] confirmation. * * See [last_setup_error](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-last_setup_error). */ @Parcelize data class Error internal constructor( /** * For some errors that could be handled programmatically, a short string indicating the * [error code](https://stripe.com/docs/error-codes) reported. */ val code: String?, /** * For card errors resulting from a card issuer decline, a short string indicating the * [card issuer’s reason for the decline](https://stripe.com/docs/declines#issuer-declines) * if they provide one. */ val declineCode: String?, /** * A URL to more information about the * [error code](https://stripe.com/docs/error-codes) reported. */ val docUrl: String?, /** * A human-readable message providing more details about the error. For card errors, * these messages can be shown to your users. */ val message: String?, /** * If the error is parameter-specific, the parameter related to the error. * For example, you can use this to display a message near the correct form field. */ val param: String?, /** * The PaymentMethod object for errors returned on a request involving a PaymentMethod. */ val paymentMethod: PaymentMethod?, /** * The type of error returned. */ val type: Type? ) : StripeModel { enum class Type(val code: String) { ApiConnectionError("api_connection_error"), ApiError("api_error"), AuthenticationError("authentication_error"), CardError("card_error"), IdempotencyError("idempotency_error"), InvalidRequestError("invalid_request_error"), RateLimitError("rate_limit_error"); internal companion object { internal fun fromCode(typeCode: String?): Type? { return values().firstOrNull { it.code == typeCode } } } } internal companion object { internal const val CODE_AUTHENTICATION_ERROR = "setup_intent_authentication_failure" } } internal data class ClientSecret(internal val value: String) { internal val setupIntentId: String = value.split("_secret".toRegex()) .dropLastWhile { it.isEmpty() }.toTypedArray()[0] init { require(isMatch(value)) { "Invalid Setup Intent client secret: $value" } } internal companion object { private val PATTERN = Pattern.compile("^seti_[^_]+_secret_[^_]+$") fun isMatch(value: String) = PATTERN.matcher(value).matches() } } /** * Reason for cancellation of a [SetupIntent]. */ enum class CancellationReason(private val code: String) { Duplicate("duplicate"), RequestedByCustomer("requested_by_customer"), Abandoned("abandoned"); internal companion object { internal fun fromCode(code: String?): CancellationReason? { return values().firstOrNull { it.code == code } } } } companion object { @JvmStatic fun fromJson(jsonObject: JSONObject?): SetupIntent? { return jsonObject?.let { SetupIntentJsonParser().parse(it) } } } }
mit
def0d7487bbbbe40dc32acc81a6bcc87
31.923077
117
0.625584
4.913892
false
false
false
false
AromaTech/banana-data-operations
src/main/java/tech/aroma/data/sql/serializers/ImageSerializer.kt
3
2098
/* * Copyright 2017 RedRoma, 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 tech.aroma.data.sql.serializers import org.springframework.jdbc.core.JdbcOperations import tech.aroma.data.assertions.RequestAssertions.validImage import tech.aroma.data.sql.DatabaseSerializer import tech.aroma.data.sql.serializers.Columns.Media import tech.aroma.thrift.Dimension import tech.aroma.thrift.Image import tech.aroma.thrift.ImageType import tech.sirwellington.alchemy.arguments.Arguments.checkThat import tech.sirwellington.alchemy.arguments.assertions.* import java.sql.ResultSet /** * * @author SirWellington */ internal class ImageSerializer : DatabaseSerializer<Image> { override fun save(image: Image, statement: String, database: JdbcOperations) { checkThat(statement).isA(nonEmptyString()) checkThat(image).isA(validImage()) } override fun deserialize(row: ResultSet): Image { val image = Image() val mediaType = row.getString(Media.MEDIA_TYPE) val width = row.getInt(Media.WIDTH) val height = row.getInt(Media.HEIGHT) val data = row.getBytes(Media.DATA) if (width > 0 && height > 0) { image.dimension = Dimension(width, height) } image.imageType = mediaType.toImageType() image.setData(data) return image } private fun String.toImageType(): ImageType? { return try { ImageType.valueOf(this) } catch(ex: Exception) { return null } } }
apache-2.0
011527f717dcac834c54bb3455175c04
26.986667
80
0.687321
4.264228
false
false
false
false
bl-lia/kktAPK
app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/activity/TimelineActivity.kt
1
5271
package com.bl_lia.kirakiratter.presentation.activity import android.content.Intent import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v4.content.res.ResourcesCompat import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.AdapterView import com.bl_lia.kirakiratter.App import com.bl_lia.kirakiratter.KKTIntent import com.bl_lia.kirakiratter.R import com.bl_lia.kirakiratter.presentation.adapter.timeline.TimelineFragmentPagerAdapter import com.bl_lia.kirakiratter.presentation.adapter.timeline.TimelineSpinnerAdapter import com.bl_lia.kirakiratter.presentation.fragment.NavigationDrawerFragment import com.bl_lia.kirakiratter.presentation.fragment.ScrollableFragment import com.bl_lia.kirakiratter.presentation.internal.di.component.DaggerTimelineActivityComponent import com.bl_lia.kirakiratter.presentation.internal.di.component.TimelineActivityComponent import com.bl_lia.kirakiratter.presentation.presenter.TimelineActivityPresenter import kotlinx.android.synthetic.main.activity_timeline.* import javax.inject.Inject class TimelineActivity : AppCompatActivity() { val timelines: List<String> = listOf("home", "local") val spinnerAdapter: TimelineSpinnerAdapter by lazy { TimelineSpinnerAdapter(this, android.R.layout.simple_spinner_dropdown_item, timelines) } val timelineFragmentAdapter by lazy { TimelineFragmentPagerAdapter(supportFragmentManager) } @Inject lateinit var presenter: TimelineActivityPresenter private var isSpinnerInitialized: Boolean = false private val component: TimelineActivityComponent by lazy { DaggerTimelineActivityComponent.builder() .applicationComponent((application as App).component) .build() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_timeline) component.inject(this) view_pager.adapter = timelineFragmentAdapter if (savedInstanceState == null) { supportFragmentManager.beginTransaction().also { transaction -> val fragment = NavigationDrawerFragment.newInstance() transaction.add(R.id.left_drawer, fragment) }.commit() } initView() } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) if (intent?.hasExtra(KKTIntent.EXTRA_SWITCH_SIMPLE_MODE) ?: false) { timelineFragmentAdapter.switchSimpleMode(intent?.getBooleanExtra(KKTIntent.EXTRA_SWITCH_SIMPLE_MODE, false) ?: false) } } private fun initView() { button_katsu.setOnClickListener { val intent = Intent(this, KatsuActivity::class.java) startActivity(intent) } button_menu.setOnClickListener { if (!layout_drawer.isDrawerOpen(left_drawer)) { layout_drawer.openDrawer(left_drawer) } } spinner_timeline.adapter = spinnerAdapter spinner_timeline.onItemSelectedListener = object: AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { if (!isSpinnerInitialized) { isSpinnerInitialized = true return } showTimeline(position) presenter.setSelectedTimeline(timelines[position]) } override fun onNothingSelected(p0: AdapterView<*>?) { val position = spinner_timeline.selectedItemPosition view_pager.currentItem = position } } button_account.setOnClickListener { val intent = Intent(this, AccountActivity::class.java) startActivity(intent) } button_notification.setOnClickListener { view_pager.setCurrentItem(2, false) } button_search.setOnClickListener { showNothing() } view_pager.post { presenter.getSelectedTimeline() .subscribe { timeline, error -> val index = timelines.indexOf(timeline) if (index > -1) { showTimeline(index) } } } toolbar_space_left.setOnClickListener { val innerFragment = timelineFragmentAdapter.getItem(view_pager.currentItem) if(innerFragment is ScrollableFragment) { innerFragment.scrollToTop() } } } private fun showTimeline(position: Int) { when (position) { 0 -> { spinner_timeline.background = ResourcesCompat.getDrawable(resources, R.drawable.ic_home_kira_18px, null) view_pager.setCurrentItem(0, false) } 1 -> { spinner_timeline.background = ResourcesCompat.getDrawable(resources, R.drawable.ic_group_kira_18px, null) view_pager.setCurrentItem(1, false) } } } private fun showNothing() { Snackbar.make(layout_drawer, "まだないよ!", Snackbar.LENGTH_SHORT).show() } }
mit
fae795124d339f25a59747cfd1679340
36.841727
129
0.659631
5.01813
false
false
false
false
exponent/exponent
android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/components/reactnativestripesdk/StripeSdkCardView.kt
2
9961
package versioned.host.exp.exponent.modules.api.components.reactnativestripesdk import android.content.res.ColorStateList import android.graphics.Color import android.graphics.Typeface import android.text.Editable import android.text.TextWatcher import android.widget.FrameLayout import com.facebook.react.bridge.ReadableMap import com.facebook.react.uimanager.ThemedReactContext import com.facebook.react.uimanager.UIManagerModule import com.facebook.react.uimanager.events.EventDispatcher import com.google.android.material.shape.CornerFamily import com.google.android.material.shape.MaterialShapeDrawable import com.google.android.material.shape.ShapeAppearanceModel import com.stripe.android.databinding.CardInputWidgetBinding import com.stripe.android.model.Address import com.stripe.android.model.PaymentMethodCreateParams import com.stripe.android.view.CardInputListener import com.stripe.android.view.CardInputWidget class StripeSdkCardView(private val context: ThemedReactContext) : FrameLayout(context) { private var mCardWidget: CardInputWidget val cardDetails: MutableMap<String, Any?> = mutableMapOf("brand" to "", "last4" to "", "expiryMonth" to null, "expiryYear" to null, "postalCode" to "") var cardParams: PaymentMethodCreateParams.Card? = null var cardAddress: Address? = null private var mEventDispatcher: EventDispatcher? private var dangerouslyGetFullCardDetails: Boolean = false init { mCardWidget = CardInputWidget(context) mEventDispatcher = context.getNativeModule(UIManagerModule::class.java)?.eventDispatcher val binding = CardInputWidgetBinding.bind(mCardWidget) binding.container.isFocusable = true binding.container.isFocusableInTouchMode = true binding.container.requestFocus() addView(mCardWidget) setListeners() viewTreeObserver.addOnGlobalLayoutListener { requestLayout() } } fun setAutofocus(value: Boolean) { if (value) { val binding = CardInputWidgetBinding.bind(mCardWidget) binding.cardNumberEditText.requestFocus() binding.cardNumberEditText.showSoftKeyboard() } } fun requestFocusFromJS() { val binding = CardInputWidgetBinding.bind(mCardWidget) binding.cardNumberEditText.requestFocus() binding.cardNumberEditText.showSoftKeyboard() } fun requestBlurFromJS() { val binding = CardInputWidgetBinding.bind(mCardWidget) binding.cardNumberEditText.hideSoftKeyboard() binding.cardNumberEditText.clearFocus() binding.container.requestFocus() } fun requestClearFromJS() { val binding = CardInputWidgetBinding.bind(mCardWidget) binding.cardNumberEditText.setText("") binding.cvcEditText.setText("") binding.expiryDateEditText.setText("") if (mCardWidget.postalCodeEnabled) { binding.postalCodeEditText.setText("") } } fun setCardStyle(value: ReadableMap) { val binding = CardInputWidgetBinding.bind(mCardWidget) val borderWidth = getIntOrNull(value, "borderWidth") val backgroundColor = getValOr(value, "backgroundColor", null) val borderColor = getValOr(value, "borderColor", null) val borderRadius = getIntOrNull(value, "borderRadius") ?: 0 val textColor = getValOr(value, "textColor", null) val fontSize = getIntOrNull(value, "fontSize") val fontFamily = getValOr(value, "fontFamily") val placeholderColor = getValOr(value, "placeholderColor", null) val textErrorColor = getValOr(value, "textErrorColor", null) textColor?.let { binding.cardNumberEditText.setTextColor(Color.parseColor(it)) binding.cvcEditText.setTextColor(Color.parseColor(it)) binding.expiryDateEditText.setTextColor(Color.parseColor(it)) binding.postalCodeEditText.setTextColor(Color.parseColor(it)) } textErrorColor?.let { binding.cardNumberEditText.setErrorColor(Color.parseColor(it)) binding.cvcEditText.setErrorColor(Color.parseColor(it)) binding.expiryDateEditText.setErrorColor(Color.parseColor(it)) binding.postalCodeEditText.setErrorColor(Color.parseColor(it)) } placeholderColor?.let { binding.cardNumberEditText.setHintTextColor(Color.parseColor(it)) binding.cvcEditText.setHintTextColor(Color.parseColor(it)) binding.expiryDateEditText.setHintTextColor(Color.parseColor(it)) binding.postalCodeEditText.setHintTextColor(Color.parseColor(it)) } fontSize?.let { binding.cardNumberEditText.textSize = it.toFloat() binding.cvcEditText.textSize = it.toFloat() binding.expiryDateEditText.textSize = it.toFloat() binding.postalCodeEditText.textSize = it.toFloat() } fontFamily?.let { binding.cardNumberEditText.typeface = Typeface.create(it, Typeface.NORMAL) binding.cvcEditText.typeface = Typeface.create(it, Typeface.NORMAL) binding.expiryDateEditText.typeface = Typeface.create(it, Typeface.NORMAL) binding.postalCodeEditText.typeface = Typeface.create(it, Typeface.NORMAL) } mCardWidget.setPadding(40, 0, 40, 0) mCardWidget.background = MaterialShapeDrawable( ShapeAppearanceModel() .toBuilder() .setAllCorners(CornerFamily.ROUNDED, (borderRadius * 2).toFloat()) .build() ).also { shape -> shape.strokeWidth = 0.0f shape.strokeColor = ColorStateList.valueOf(Color.parseColor("#000000")) shape.fillColor = ColorStateList.valueOf(Color.parseColor("#FFFFFF")) borderWidth?.let { shape.strokeWidth = (it * 2).toFloat() } borderColor?.let { shape.strokeColor = ColorStateList.valueOf(Color.parseColor(it)) } backgroundColor?.let { shape.fillColor = ColorStateList.valueOf(Color.parseColor(it)) } } } fun setPlaceHolders(value: ReadableMap) { val binding = CardInputWidgetBinding.bind(mCardWidget) val numberPlaceholder = getValOr(value, "number", null) val expirationPlaceholder = getValOr(value, "expiration", null) val cvcPlaceholder = getValOr(value, "cvc", null) val postalCodePlaceholder = getValOr(value, "postalCode", null) numberPlaceholder?.let { binding.cardNumberEditText.hint = it } expirationPlaceholder?.let { binding.expiryDateEditText.hint = it } cvcPlaceholder?.let { mCardWidget.setCvcLabel(it) } postalCodePlaceholder?.let { binding.postalCodeEditText.hint = it } } fun setDangerouslyGetFullCardDetails(isEnabled: Boolean) { dangerouslyGetFullCardDetails = isEnabled } fun setPostalCodeEnabled(isEnabled: Boolean) { mCardWidget.postalCodeEnabled = isEnabled } fun getValue(): MutableMap<String, Any?> { return cardDetails } fun onCardChanged() { mCardWidget.paymentMethodCard?.let { cardParams = it cardAddress = Address.Builder() .setPostalCode(cardDetails["postalCode"] as String?) .build() } ?: run { cardParams = null cardAddress = null } mCardWidget.cardParams?.let { cardDetails["brand"] = mapCardBrand(it.brand) cardDetails["last4"] = it.last4 } ?: run { cardDetails["brand"] = null cardDetails["last4"] = null } mEventDispatcher?.dispatchEvent( CardChangedEvent(id, cardDetails, mCardWidget.postalCodeEnabled, cardParams != null, dangerouslyGetFullCardDetails) ) } private fun setListeners() { mCardWidget.setCardValidCallback { isValid, _ -> if (isValid) { onCardChanged() } } mCardWidget.setCardInputListener(object : CardInputListener { override fun onCardComplete() {} override fun onExpirationComplete() {} override fun onCvcComplete() {} override fun onFocusChange(focusField: CardInputListener.FocusField) { if (mEventDispatcher != null) { mEventDispatcher?.dispatchEvent( CardFocusEvent(id, focusField.name) ) } } }) mCardWidget.setExpiryDateTextWatcher(object : TextWatcher { override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun afterTextChanged(p0: Editable?) {} override fun onTextChanged(var1: CharSequence?, var2: Int, var3: Int, var4: Int) { val splitted = var1.toString().split("/") cardDetails["expiryMonth"] = splitted[0].toIntOrNull() if (splitted.size == 2) { cardDetails["expiryYear"] = var1.toString().split("/")[1].toIntOrNull() } onCardChanged() } }) mCardWidget.setPostalCodeTextWatcher(object : TextWatcher { override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun afterTextChanged(p0: Editable?) {} override fun onTextChanged(var1: CharSequence?, var2: Int, var3: Int, var4: Int) { cardDetails["postalCode"] = var1.toString() onCardChanged() } }) mCardWidget.setCardNumberTextWatcher(object : TextWatcher { override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun afterTextChanged(p0: Editable?) {} override fun onTextChanged(var1: CharSequence?, var2: Int, var3: Int, var4: Int) { if (dangerouslyGetFullCardDetails) { cardDetails["number"] = var1.toString().replace(" ", "") } onCardChanged() } }) mCardWidget.setCvcNumberTextWatcher(object : TextWatcher { override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun afterTextChanged(p0: Editable?) {} override fun onTextChanged(var1: CharSequence?, var2: Int, var3: Int, var4: Int) { onCardChanged() } }) } override fun requestLayout() { super.requestLayout() post(mLayoutRunnable) } private val mLayoutRunnable = Runnable { measure( MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY) ) layout(left, top, right, bottom) } }
bsd-3-clause
d7110d3c7497e8e5598453b6967e2b9e
35.354015
153
0.711876
4.433022
false
false
false
false
ex/godot
platform/android/java/lib/src/org/godotengine/godot/io/file/DataAccess.kt
2
6173
/*************************************************************************/ /* DataAccess.kt */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ package org.godotengine.godot.io.file import android.content.Context import android.os.Build import android.util.Log import org.godotengine.godot.io.StorageScope import java.io.IOException import java.nio.ByteBuffer import java.nio.channels.FileChannel import kotlin.math.max /** * Base class for file IO operations. * * Its derived instances provide concrete implementations to handle regular file access, as well * as file access through the media store API on versions of Android were scoped storage is enabled. */ internal abstract class DataAccess(private val filePath: String) { companion object { private val TAG = DataAccess::class.java.simpleName fun generateDataAccess( storageScope: StorageScope, context: Context, filePath: String, accessFlag: FileAccessFlags ): DataAccess? { return when (storageScope) { StorageScope.APP -> FileData(filePath, accessFlag) StorageScope.SHARED -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { MediaStoreData(context, filePath, accessFlag) } else { null } StorageScope.UNKNOWN -> null } } fun fileExists(storageScope: StorageScope, context: Context, path: String): Boolean { return when(storageScope) { StorageScope.APP -> FileData.fileExists(path) StorageScope.SHARED -> MediaStoreData.fileExists(context, path) StorageScope.UNKNOWN -> false } } fun fileLastModified(storageScope: StorageScope, context: Context, path: String): Long { return when(storageScope) { StorageScope.APP -> FileData.fileLastModified(path) StorageScope.SHARED -> MediaStoreData.fileLastModified(context, path) StorageScope.UNKNOWN -> 0L } } fun removeFile(storageScope: StorageScope, context: Context, path: String): Boolean { return when(storageScope) { StorageScope.APP -> FileData.delete(path) StorageScope.SHARED -> MediaStoreData.delete(context, path) StorageScope.UNKNOWN -> false } } fun renameFile(storageScope: StorageScope, context: Context, from: String, to: String): Boolean { return when(storageScope) { StorageScope.APP -> FileData.rename(from, to) StorageScope.SHARED -> MediaStoreData.rename(context, from, to) StorageScope.UNKNOWN -> false } } } protected abstract val fileChannel: FileChannel internal var endOfFile = false private set fun close() { try { fileChannel.close() } catch (e: IOException) { Log.w(TAG, "Exception when closing file $filePath.", e) } } fun flush() { try { fileChannel.force(false) } catch (e: IOException) { Log.w(TAG, "Exception when flushing file $filePath.", e) } } fun seek(position: Long) { try { fileChannel.position(position) if (position <= size()) { endOfFile = false } } catch (e: Exception) { Log.w(TAG, "Exception when seeking file $filePath.", e) } } fun seekFromEnd(positionFromEnd: Long) { val positionFromBeginning = max(0, size() - positionFromEnd) seek(positionFromBeginning) } fun position(): Long { return try { fileChannel.position() } catch (e: IOException) { Log.w( TAG, "Exception when retrieving position for file $filePath.", e ) 0L } } fun size() = try { fileChannel.size() } catch (e: IOException) { Log.w(TAG, "Exception when retrieving size for file $filePath.", e) 0L } fun read(buffer: ByteBuffer): Int { return try { val readBytes = fileChannel.read(buffer) endOfFile = readBytes == -1 || (fileChannel.position() >= fileChannel.size() && fileChannel.size() > 0) if (readBytes == -1) { 0 } else { readBytes } } catch (e: IOException) { Log.w(TAG, "Exception while reading from file $filePath.", e) 0 } } fun write(buffer: ByteBuffer) { try { val writtenBytes = fileChannel.write(buffer) if (writtenBytes > 0) { endOfFile = false } } catch (e: IOException) { Log.w(TAG, "Exception while writing to file $filePath.", e) } } }
mit
185e85060b6be610351ac3e18917b61d
32.010695
100
0.601166
4.0719
false
false
false
false
openmhealth/schemas
kotlin-schema-sdk/src/test/kotlin/org/openmhealth/schema/domain/omh/AreaUnitValueTests.kt
1
883
package org.openmhealth.schema.domain.omh import com.fasterxml.jackson.databind.JsonNode import org.junit.jupiter.params.ParameterizedTest import org.openmhealth.schema.domain.omh.AreaUnit.SQUARE_INCH import org.openmhealth.schema.domain.omh.AreaUnit.SQUARE_METER import org.openmhealth.schema.support.DataFileSource class AreaUnitValueTests : MappingTests() { @ParameterizedTest @DataFileSource(schemaId = "omh:area-unit-value:1.0", filename = "positive-value.json") fun `positive-value`(json: JsonNode) { val value = AreaUnitValue(SQUARE_METER, 7.6) assertThatMappingWorks(value, json) } @ParameterizedTest @DataFileSource(schemaId = "omh:area-unit-value:1.0", filename = "zero-value.json") fun `zero-value`(json: JsonNode) { val value = AreaUnitValue(SQUARE_INCH, 0.0) assertThatMappingWorks(value, json) } }
apache-2.0
0dd7b24b1690f361c23bcc635313f1a3
31.703704
91
0.737259
3.64876
false
true
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/rule/tensor/NDArrayMappingRule.kt
1
2923
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.onnx.rule.tensor import onnx.Onnx import org.nd4j.ir.OpNamespace import org.nd4j.ir.TensorNamespace import org.nd4j.samediff.frameworkimport.findOp import org.nd4j.samediff.frameworkimport.onnx.ir.OnnxIRTensor import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder import org.nd4j.samediff.frameworkimport.rule.MappingRule import org.nd4j.samediff.frameworkimport.rule.tensor.BaseNDArrayMappingRule import java.lang.IllegalArgumentException @MappingRule("onnx","ndarraymapping","tensor") class NDArrayMappingRule(mappingNamesToPerform: MutableMap<String,String>, transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>> = emptyMap()): BaseNDArrayMappingRule<Onnx.GraphProto, Onnx.NodeProto, Onnx.NodeProto, Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto, Onnx.TensorProto.DataType>(mappingNamesToPerform = mappingNamesToPerform, transformerArgs = transformerArgs) { override fun createTensorProto(input: Onnx.TensorProto): TensorNamespace.TensorProto { return OnnxIRTensor(input).toArgTensor() } override fun isInputTensorName(inputName: String): Boolean { val onnxOp = OpDescriptorLoaderHolder.listForFramework<Onnx.NodeProto>("onnx") if(!onnxOp.containsKey(mappingProcess!!.inputFrameworkOpName())) { throw IllegalArgumentException("No op definition found for ${mappingProcess!!.inputFrameworkOpName()}") } val ret = onnxOp[mappingProcess!!.inputFrameworkOpName()]!! return ret.inputList.contains(inputName) } override fun isOutputTensorName(outputName: String): Boolean { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess!!.opName()) return nd4jOpDescriptor.argDescriptorList.filter { inputDescriptor -> inputDescriptor.argType == OpNamespace.ArgDescriptor.ArgType.INPUT_TENSOR } .map {inputDescriptor -> inputDescriptor.name }.contains(outputName) } }
apache-2.0
1e641c0dbe0391fe7e1dd9e45e1df7f1
48.559322
153
0.713308
4.863561
false
false
false
false
exponent/exponent
packages/expo-battery/android/src/main/java/expo/modules/battery/BatteryLevelReceiver.kt
2
1309
package expo.modules.battery import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.BatteryManager import android.os.Bundle import android.util.Log import expo.modules.core.interfaces.services.EventEmitter class BatteryLevelReceiver(private val eventEmitter: EventEmitter?) : BroadcastReceiver() { private val BATTERY_LEVEL_EVENT_NAME = "Expo.batteryLevelDidChange" private fun onBatteryLevelChange(BatteryLevel: Float) { eventEmitter?.emit( BATTERY_LEVEL_EVENT_NAME, Bundle().apply { putFloat("batteryLevel", BatteryLevel) } ) } override fun onReceive(context: Context, intent: Intent) { val batteryIntent = context.applicationContext.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) if (batteryIntent == null) { Log.e("Battery", "ACTION_BATTERY_CHANGED unavailable. Events wont be received") return } val level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) val scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1) val batteryLevel: Float = if (level != -1 && scale != -1) { level / scale.toFloat() } else { -1f } onBatteryLevelChange(batteryLevel) } }
bsd-3-clause
57ce90c17f72f8c6a92858f3d9ff7624
32.564103
118
0.734912
4.277778
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/hints/RsDeclarationRangeHandler.kt
3
2675
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.hints import com.intellij.codeInsight.hint.DeclarationRangeHandler import com.intellij.openapi.util.TextRange import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* class RsStructItemDeclarationRangeHandler : DeclarationRangeHandler<RsStructItem> { override fun getDeclarationRange(container: RsStructItem): TextRange { val startOffset = (container.struct ?: container.union ?: container).startOffset val endOffset = (container.blockFields?.getPrevNonCommentSibling() ?: container).endOffset return TextRange(startOffset, endOffset) } } class RsTraitItemDeclarationRangeHandler : DeclarationRangeHandler<RsTraitItem> { override fun getDeclarationRange(container: RsTraitItem): TextRange { val startOffset = container.trait.startOffset val endOffset = (container.members?.getPrevNonCommentSibling() ?: container).endOffset return TextRange(startOffset, endOffset) } } class RsImplItemDeclarationRangeHandler : DeclarationRangeHandler<RsImplItem> { override fun getDeclarationRange(container: RsImplItem): TextRange { val startOffset = container.impl.startOffset val endOffset = (container.members?.getPrevNonCommentSibling() ?: container).endOffset return TextRange(startOffset, endOffset) } } class RsEnumItemDeclarationRangeHandler : DeclarationRangeHandler<RsEnumItem> { override fun getDeclarationRange(container: RsEnumItem): TextRange { val startOffset = container.enum.startOffset val endOffset = (container.enumBody?.getPrevNonCommentSibling() ?: container).endOffset return TextRange(startOffset, endOffset) } } class RsModItemDeclarationRangeHandler : DeclarationRangeHandler<RsModItem> { override fun getDeclarationRange(container: RsModItem): TextRange { val startOffset = container.mod.startOffset val endOffset = container.identifier.endOffset return TextRange(startOffset, endOffset) } } class RsFunctionDeclarationRangeHandler : DeclarationRangeHandler<RsFunction> { override fun getDeclarationRange(container: RsFunction): TextRange { val startOffset = container.fn.startOffset val endOffset = (container.block?.getPrevNonCommentSibling() ?: container).endOffset return TextRange(startOffset, endOffset) } } class RsMacroDeclarationRangeHandler : DeclarationRangeHandler<RsMacro> { override fun getDeclarationRange(container: RsMacro): TextRange = container.identifier?.textRange ?: container.textRange }
mit
e77a3a5830fe4c664088a44e35824bd3
40.796875
98
0.762243
5.224609
false
false
false
false
jk1/youtrack-idea-plugin
src/main/kotlin/com/github/jk1/ytplugin/rest/IssuesRestClient.kt
1
5198
package com.github.jk1.ytplugin.rest import com.github.jk1.ytplugin.issues.model.Issue import com.github.jk1.ytplugin.issues.model.IssueWorkItem import com.github.jk1.ytplugin.logger import com.github.jk1.ytplugin.tasks.YouTrackServer import com.github.jk1.ytplugin.timeTracker.TrackerNotification import com.google.gson.* import com.intellij.notification.NotificationType import org.apache.http.client.methods.HttpGet import org.apache.http.client.methods.HttpPost import org.apache.http.client.utils.URIBuilder import java.net.URL /** * Fetches YouTrack issues with issue description formatted from wiki into html on server side. */ class IssuesRestClient(override val repository: YouTrackServer) : IssuesRestClientBase, RestClientTrait { companion object { const val ISSUE_FIELDS = "id,idReadable,updated,created," + "tags(color(foreground,background),name),project(shortName),links(value,direction,issues(idReadable)," + "linkType(name,sourceToTarget,targetToSource),id),comments(id,textPreview,created,updated," + "author(name,login),deleted),summary,wikifiedDescription,customFields(name,color," + "value(name,minutes,presentation,markdownText,color(background,foreground))," + "id,projectCustomField(emptyFieldText)),resolved,attachments(name,url),reporter(login)" } override fun createDraft(summary: String): String? { val method = HttpPost("${repository.url}/api/admin/users/me/drafts") val res: URL? = this::class.java.classLoader.getResource("create_draft_body.json") val summaryFormatted = summary.replace("\n", "\\n").replace("\"", "\\\"") method.entity = res?.readText()?.replace("{description}", summaryFormatted)?.jsonEntity try { return method.execute { element -> val id = element.asJsonObject.get("id").asString logger.debug("Successfully created issue draft: $id") id } } catch (e: Exception){ val trackerNote = TrackerNotification() trackerNote.notify("YouTrack server integration is not configured yet " + "or the connection might be lost", NotificationType.WARNING) return "" } } override fun getIssue(id: String): Issue { val builder = URIBuilder("${repository.url}/api/issues/$id") builder.addParameter("fields", ISSUE_FIELDS) val method = HttpGet(builder.build()) return method.execute { element -> val issuesWithWorkItems: List<JsonElement> = mapWorkItemsWithIssues(listOf(element)) val fullIssues = parseIssues(issuesWithWorkItems) logger.debug("Successfully fetched issue: $id") fullIssues[0] } } private fun mapWorkItemsWithIssues(issues: Iterable<JsonElement>): List<JsonElement> { val newIssues = mutableListOf<JsonElement>() for (issue in issues) { val id = issue.asJsonObject.get("idReadable").asString val workItems = getWorkItems(id) var workItemsJson: String if (workItems.isEmpty()) { workItemsJson = "\"workItems\": []" } else { workItemsJson = "\"workItems\": [" for (x in 0..workItems.size - 2) { workItemsJson += "${workItems[x].json}," } workItemsJson += "${workItems.last().json}]" } // add workItems to issue val issueString = issue.toString().substring(0, issue.toString().length - 1) + ",\n$workItemsJson\n}" newIssues.add(JsonParser.parseString(issueString) as JsonElement) } return newIssues } private fun parseIssues(json: List<JsonElement>): List<Issue> { return json.map { IssueParser().parseIssue(it.asJsonObject, repository.url) } } override fun getIssues(query: String): List<Issue> { // todo: customizable "max" limit val builder = URIBuilder("${repository.url}/api/issues") builder.addParameter("query", query) .addParameter("\$top", "100") .addParameter("fields", ISSUE_FIELDS) val method = HttpGet(builder.build()) return method.execute { element -> val issues: JsonArray = element.asJsonArray val issuesWithWorkItems: List<JsonElement> = mapWorkItemsWithIssues(issues) parseIssues(issuesWithWorkItems) } } private fun getWorkItems(query: String): List<IssueWorkItem> { val builder = URIBuilder("${repository.url}/api/workItems") builder.addParameter("\$top", "100") .addParameter("query", query) .addParameter("fields", "text,type(name),created,issue(idReadable)," + "duration(presentation,minutes),author(name),creator(name),date,id,attributes(name,id,value(name))") .addParameter("sort", "descending") return HttpGet(builder.build()).execute { element -> element.asJsonArray.mapNotNull { IssueJsonParser.parseWorkItem(it) } } } }
apache-2.0
6c628864e3af88d202dd12b58e68b313
45.837838
124
0.637361
4.547682
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/cargo/project/model/CargoStdlibPackagesTest.kt
2
4688
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.project.model import com.intellij.util.io.delete import org.rust.cargo.RsWithToolchainTestBase import org.rust.cargo.project.model.impl.testCargoProjects import org.rust.cargo.project.workspace.* import org.rust.singleProject import org.rust.workspaceOrFail class CargoStdlibPackagesTest : RsWithToolchainTestBase() { override val fetchActualStdlibMetadata: Boolean get() = true fun `test stdlib dependency`() { buildProject { toml("Cargo.toml", """ [package] name = "sandbox" version = "0.1.0" authors = [] """) dir("src") { rust("lib.rs", "") } } val cargoProject = project.cargoProjects.singleProject() val workspace = cargoProject.workspaceOrFail() val hashbrownPkg = workspace.packages.first { it.name == HASHBROWN } assertEquals(PackageOrigin.STDLIB_DEPENDENCY, hashbrownPkg.origin) hashbrownPkg.checkFeature("rustc-dep-of-std", FeatureState.Enabled) hashbrownPkg.checkFeature("default", FeatureState.Disabled) for (pkgName in TARGET_SPECIFIC_DEPENDENCIES) { val pkg = workspace.packages.find { it.name == pkgName } assertNull("$pkgName shouldn't be in stdlib dependencies because it's target-specific", pkg) } } fun `test target specific dependencies with custom build target`() { buildProject { dir(".cargo") { toml("config", """ [build] target = "custom-target.json" """) } file("custom-target.json", """ { "llvm-target": "aarch64-unknown-none", "data-layout": "e-m:e-i64:64-f80:128-n8:16:32:64-S128", "arch": "aarch64", "target-endian": "little", "target-pointer-width": "64", "target-c-int-width": "32", "os": "none", "executables": true, "linker-flavor": "ld.lld", "linker": "rust-lld", "panic-strategy": "abort", "disable-redzone": true, "features": "-mmx,-sse,+soft-float" } """) toml("Cargo.toml", """ [package] name = "sandbox" version = "0.1.0" authors = [] """) dir("src") { rust("lib.rs", "") } } val workspace = project.cargoProjects.singleProject().workspaceOrFail() val hashbrownPkg = workspace.packages.first { it.name == HASHBROWN } assertEquals(PackageOrigin.STDLIB_DEPENDENCY, hashbrownPkg.origin) } fun `test recover corrupted stdlib dependency directory`() { buildProject { toml("Cargo.toml", """ [package] name = "sandbox" version = "0.1.0" authors = [] """) dir("src") { rust("lib.rs", "") } } val cargoProjectService = project.testCargoProjects val cargoProject = cargoProjectService.singleProject() val version = cargoProject.rustcInfo?.version ?: error("") val srcDir = rustupFixture.stdlib?.let { StandardLibrary.findSrcDir(it) } ?: error("") val path = StdlibDataFetcher.stdlibVendorDir(srcDir, version) // Corrupt vendor directory path.resolve(HASHBROWN).delete(true) cargoProjectService.refreshAllProjectsSync() val hashbrownPkg = cargoProjectService .singleProject() .workspaceOrFail() .packages .firstOrNull { it.name == HASHBROWN } assertNotNull("Stdlib must contain `$HASHBROWN` package", hashbrownPkg) } private fun CargoWorkspace.Package.checkFeature(featureName: String, expectedState: FeatureState) { val featureState = featureState.getValue(featureName) assertEquals("Feature `$featureName` in package `$name` should be in $expectedState", expectedState, featureState) } companion object { private const val HASHBROWN = "hashbrown" // Some stdlib dependencies for non default (from IDE point of view) build targets private val TARGET_SPECIFIC_DEPENDENCIES = listOf("wasi", "hermit-abi", "dlmalloc", "fortanix-sgx-abi") } }
mit
8741002c33191b0f32ef82feb6dd71c9
34.24812
122
0.556314
4.692693
false
true
false
false
Undin/intellij-rust
toml/src/main/kotlin/org/rust/toml/resolve/CargoTomlFileReferenceProvider.kt
3
4145
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.toml.resolve import com.intellij.openapi.util.Condition import com.intellij.openapi.util.TextRange import com.intellij.patterns.PsiElementPattern import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileSystemItem import com.intellij.psi.PsiReferenceProvider import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet import com.intellij.psi.util.parentOfType import com.intellij.util.ProcessingContext import org.rust.lang.core.or import org.rust.lang.core.psi.RsFile import org.rust.lang.core.psi.ext.ancestorStrict import org.rust.toml.CargoTomlPsiPattern import org.rust.toml.resolve.PathPatternType.* import org.toml.lang.psi.TomlHeaderOwner import org.toml.lang.psi.TomlKeyValue import org.toml.lang.psi.TomlLiteral import org.toml.lang.psi.ext.TomlLiteralKind import org.toml.lang.psi.ext.kind import org.toml.lang.psi.ext.name class CargoTomlFileReferenceProvider(private val patternType: PathPatternType) : PsiReferenceProvider() { override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<FileReference> { val kind = (element as? TomlLiteral)?.kind ?: return emptyArray() if (kind !is TomlLiteralKind.String) return emptyArray() val (completeDirs, completeRustFiles) = when (patternType) { WORKSPACE -> true to false GENERAL -> { val table = element.ancestorStrict<TomlHeaderOwner>() val completeRustFiles = table != null && table.header.key?.name in TARGET_TABLE_NAMES true to completeRustFiles } BUILD -> false to true } val ignoreGlobs = patternType == WORKSPACE && element.parentOfType<TomlKeyValue>()?.key?.segments?.firstOrNull()?.name in KEYS_SUPPORTING_GLOB val referenceSet: FileReferenceSet = if (ignoreGlobs) { GlobIgnoringFileReferenceSet(element, completeDirs, completeRustFiles) } else { CargoTomlFileReferenceSet(element, completeDirs, completeRustFiles) } return referenceSet.allReferences } companion object { private val TARGET_TABLE_NAMES = listOf("lib", "bin", "test", "bench", "example") private val KEYS_SUPPORTING_GLOB = listOf("members", "default-members") } } enum class PathPatternType(val pattern: PsiElementPattern.Capture<out PsiElement>) { GENERAL(CargoTomlPsiPattern.path), WORKSPACE(CargoTomlPsiPattern.workspacePath or CargoTomlPsiPattern.packageWorkspacePath), BUILD(CargoTomlPsiPattern.buildPath) } private open class CargoTomlFileReferenceSet( element: TomlLiteral, private val completeDirs: Boolean, private val completeRustFiles: Boolean ) : FileReferenceSet(element) { override fun getReferenceCompletionFilter(): Condition<PsiFileSystemItem> { return Condition { when (it) { is PsiDirectory -> completeDirs is RsFile -> completeRustFiles else -> false } } } } private class GlobIgnoringFileReferenceSet( element: TomlLiteral, completeDirs: Boolean, completeRustFiles: Boolean ) : CargoTomlFileReferenceSet(element, completeDirs, completeRustFiles) { private var globPatternFound: Boolean = false override fun reparse() { globPatternFound = false super.reparse() } override fun createFileReference(range: TextRange, index: Int, text: String): FileReference? { if (!globPatternFound && isGlobPathFragment(text)) { globPatternFound = true } if (globPatternFound) return null return super.createFileReference(range, index, text) } } private fun isGlobPathFragment(text: String?): Boolean { if (text == null) return false return text.contains("?") || text.contains("*") || text.contains("[") || text.contains("]") }
mit
267ea11f167324d41ebeac5f7f5e47eb
36.681818
112
0.712907
4.404888
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/refactoring/move/common/RsMoveConflictsDetector.kt
3
12779
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.refactoring.move.common import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts.DialogMessage import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.refactoring.util.RefactoringUIUtil import com.intellij.util.containers.MultiMap import org.rust.ide.refactoring.move.common.RsMoveUtil.addInner import org.rust.ide.refactoring.move.common.RsMoveUtil.isInsideMovedElements import org.rust.ide.refactoring.move.common.RsMoveUtil.isSimplePath import org.rust.ide.refactoring.move.common.RsMoveUtil.isTargetOfEachSubpathAccessible import org.rust.ide.refactoring.move.common.RsMoveUtil.startsWithSelf import org.rust.ide.utils.getTopmostParentInside import org.rust.lang.core.macros.setContext import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* class RsMoveConflictsDetector( @Suppress("UnstableApiUsage") private val conflicts: MultiMap<PsiElement, @DialogMessage String>, private val elementsToMove: List<ElementToMove>, private val sourceMod: RsMod, private val targetMod: RsMod ) { val itemsToMakePublic: MutableSet<RsElement> = hashSetOf() fun detectInsideReferencesVisibilityProblems(insideReferences: List<RsMoveReferenceInfo>) { updateItemsToMakePublic(insideReferences) detectReferencesVisibilityProblems(insideReferences) detectPrivateFieldOrMethodInsideReferences() } private fun updateItemsToMakePublic(insideReferences: List<RsMoveReferenceInfo>) { for (reference in insideReferences) { val pathOld = reference.pathOldOriginal val target = reference.target val usageMod = pathOld.containingMod val isSelfReference = pathOld.isInsideMovedElements(elementsToMove) if (!isSelfReference && !usageMod.superMods.contains(targetMod)) { val itemToMakePublic = (target as? RsFile)?.declaration ?: target itemsToMakePublic.add(itemToMakePublic) } } } fun detectOutsideReferencesVisibilityProblems(outsideReferences: List<RsMoveReferenceInfo>) { detectReferencesVisibilityProblems(outsideReferences) detectPrivateFieldOrMethodOutsideReferences() } private fun detectReferencesVisibilityProblems(references: List<RsMoveReferenceInfo>) { for (reference in references) { val pathNew = reference.pathNewAccessible if (pathNew == null || !pathNew.isTargetOfEachSubpathAccessible()) { addVisibilityConflict(conflicts, reference.pathOldOriginal, reference.target) } } } /** * For now we check only references from [sourceMod], * because to check all references we should find them, * and it would be very slow when moving e.g. many files. */ private fun detectPrivateFieldOrMethodInsideReferences() { val movedElementsShallowDescendants = movedElementsShallowDescendantsOfType<RsElement>(elementsToMove) val sourceFile = sourceMod.containingFile val elementsToCheck = sourceFile.descendantsOfType<RsElement>() - movedElementsShallowDescendants detectPrivateFieldOrMethodReferences(elementsToCheck.asSequence(), ::checkVisibilityForInsideReference) } /** We create temp child mod of [targetMod] and copy [target] to this temp mod */ private fun checkVisibilityForInsideReference(referenceElement: RsElement, target: RsVisible) { if (target.visibility == RsVisibility.Public) return /** * Can't use `target.containingMod` directly, * because if [target] is expanded by macros, * then `containingMod` will return element from other file, * and [getTopmostParentInside] will throw exception. * We expect [target] to be one of [elementsToMove], so [target] should not be expanded by macros. */ val targetContainingMod = target.ancestorStrict<RsMod>() ?: return if (targetContainingMod != sourceMod) return // all moved items belong to `sourceMod` val item = target.getTopmostParentInside(targetContainingMod) // It is enough to check only references to descendants of moved items (not mods), // because if something in inner mod is private, then it was not accessible before move. if (elementsToMove.none { (it as? ItemToMove)?.item == item }) return val tempMod = RsPsiFactory(sourceMod.project).createModItem(TMP_MOD_NAME, "") tempMod.setContext(targetMod) target.putCopyableUserData(RS_ELEMENT_FOR_CHECK_INSIDE_REFERENCES_VISIBILITY, target) val itemInTempMod = tempMod.addInner(item) val targetInTempMod = itemInTempMod.descendantsOfType<RsVisible>() .singleOrNull { it.getCopyableUserData(RS_ELEMENT_FOR_CHECK_INSIDE_REFERENCES_VISIBILITY) == target } ?: return if (!targetInTempMod.isVisibleFrom(referenceElement.containingMod)) { addVisibilityConflict(conflicts, referenceElement, target) } target.putCopyableUserData(RS_ELEMENT_FOR_CHECK_INSIDE_REFERENCES_VISIBILITY, null) } private fun detectPrivateFieldOrMethodOutsideReferences() { fun checkVisibility(referenceElement: RsElement, target: RsVisible) { if (!target.isInsideMovedElements(elementsToMove) && !target.isVisibleFrom(targetMod)) { addVisibilityConflict(conflicts, referenceElement, target) } } // TODO: Consider using [PsiRecursiveElementVisitor] val elementsToCheck = movedElementsDeepDescendantsOfType<RsElement>(elementsToMove) detectPrivateFieldOrMethodReferences(elementsToCheck, ::checkVisibility) } private fun detectPrivateFieldOrMethodReferences( elementsToCheck: Sequence<RsElement>, checkVisibility: (RsElement, RsVisible) -> Unit ) { fun checkVisibility(reference: RsReferenceElement) { val target = reference.reference?.resolve() as? RsVisible ?: return checkVisibility(reference, target) } loop@ for (element in elementsToCheck) { when (element) { is RsDotExpr -> { val fieldReference = element.fieldLookup ?: element.methodCall ?: continue@loop checkVisibility(fieldReference) } is RsStructLiteralField -> { val field = element.resolveToDeclaration() ?: continue@loop checkVisibility(element, field) } is RsPatField -> { val patBinding = element.patBinding ?: continue@loop checkVisibility(patBinding) } is RsPatTupleStruct -> { // It is ok to use `resolve` and not `deepResolve` here // because type aliases can't be used in destructuring tuple struct: val struct = element.path.reference?.resolve() as? RsStructItem ?: continue@loop val fields = struct.tupleFields?.tupleFieldDeclList ?: continue@loop for (field in fields) { checkVisibility(element, field) } } is RsPath -> { // Conflicts for simple paths are handled using `pathNewAccessible`/`pathNewFallback` machinery val isInsideSimplePath = element.ancestors .takeWhile { it is RsPath } .any { isSimplePath(it as RsPath) } if (!isInsideSimplePath && !element.startsWithSelf()) { // Here we handle e.g. UFCS paths: `Struct1::method1` checkVisibility(element) } } } } } /** * Rules for inherent impls: * - An implementing type must be defined within the same crate as the original type definition * - https://doc.rust-lang.org/reference/items/implementations.html#inherent-implementations * - https://doc.rust-lang.org/error-index.html#E0116 * We should check: * - When moving inherent impl: check that implementing type is also moved * - When moving struct/enum: check that all inherent impls are also moved * TODO: Check impls for trait objects: `impl dyn Trait { ... }` * * Rules for trait impls: * - Orphan rules: https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules * - https://doc.rust-lang.org/error-index.html#E0117 * We should check (denote impls as `impl<P1..=Pn> Trait<T1..=Tn> for T0`): * - When moving trait impl: * - either implemented trait is in target crate * - or at least one of the types `T0..=Tn` is a local type * - When moving trait: for each impl of this trait which remains in source crate: * - at least one of the types `T0..=Tn` is a local type * - Uncovering is not checking, because it is complicated */ fun checkImpls() { if (sourceMod.crateRoot == targetMod.crateRoot) return val structsToMove = movedElementsDeepDescendantsOfType<RsStructOrEnumItemElement>(elementsToMove).toSet() val implsToMove = movedElementsDeepDescendantsOfType<RsImplItem>(elementsToMove) val (inherentImplsToMove, traitImplsToMove) = implsToMove .partition { it.traitRef == null } .run { first.toSet() to second.toSet() } checkStructIsMovedTogetherWithInherentImpl(structsToMove, inherentImplsToMove) checkInherentImplIsMovedTogetherWithStruct(structsToMove, inherentImplsToMove) traitImplsToMove.forEach(::checkTraitImplIsCoherentAfterMove) } // https://doc.rust-lang.org/reference/items/implementations.html#trait-implementation-coherence private fun checkTraitImplIsCoherentAfterMove(impl: RsImplItem) { fun RsElement.isLocalAfterMove(): Boolean = crateRoot == targetMod.crateRoot || isInsideMovedElements(elementsToMove) if (!checkOrphanRules(impl, RsElement::isLocalAfterMove)) { conflicts.putValue(impl, "Orphan rules check failed for trait implementation after move") } } private fun checkStructIsMovedTogetherWithInherentImpl( structsToMove: Set<RsStructOrEnumItemElement>, inherentImplsToMove: Set<RsImplItem> ) { for (impl in inherentImplsToMove) { val struct = impl.implementingType?.item ?: continue if (struct !in structsToMove) { val structDescription = RefactoringUIUtil.getDescription(struct, true) val message = "Inherent implementation should be moved together with $structDescription" conflicts.putValue(impl, message) } } } private fun checkInherentImplIsMovedTogetherWithStruct( structsToMove: Set<RsStructOrEnumItemElement>, inherentImplsToMove: Set<RsImplItem> ) { for ((file, structsToMoveInFile) in structsToMove.groupBy { it.containingFile }) { // not working if there is inherent impl in other file // but usually struct and its inherent impls belong to same file val structInherentImpls = file.descendantsOfType<RsImplItem>() .filter { it.traitRef == null } .groupBy { it.implementingType?.item } for (struct in structsToMoveInFile) { val impls = structInherentImpls[struct] ?: continue for (impl in impls.filter { it !in inherentImplsToMove }) { val structDescription = RefactoringUIUtil.getDescription(struct, true) val message = "Inherent implementation should be moved together with $structDescription" conflicts.putValue(impl, message) } } } } companion object { val RS_ELEMENT_FOR_CHECK_INSIDE_REFERENCES_VISIBILITY: Key<RsElement> = Key("RS_ELEMENT_FOR_CHECK_INSIDE_REFERENCES_VISIBILITY") } } fun addVisibilityConflict( @Suppress("UnstableApiUsage") conflicts: MultiMap<PsiElement, @DialogMessage String>, reference: RsElement, target: RsElement ) { val referenceDescription = RefactoringUIUtil.getDescription(reference.containingMod, true) val targetDescription = RefactoringUIUtil.getDescription(target, true) val message = "$referenceDescription uses $targetDescription which will be inaccessible after move" conflicts.putValue(reference, StringUtil.capitalize(message)) }
mit
bb893128447fbc31f31b1a81dceb3c09
47.405303
115
0.674466
4.836866
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/console/RsConsoleRunner.kt
2
11368
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.console import com.intellij.execution.actions.EOFAction import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.console.ConsoleHistoryController import com.intellij.execution.console.ProcessBackedConsoleExecuteActionHandler import com.intellij.execution.process.OSProcessHandler import com.intellij.execution.runners.AbstractConsoleRunnerWithHistory import com.intellij.execution.ui.RunContentDescriptor import com.intellij.execution.ui.actions.CloseAction import com.intellij.ide.errorTreeView.NewErrorTreeViewPanel import com.intellij.openapi.actionSystem.* import com.intellij.openapi.application.* import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.editor.actions.ScrollToTheEndToolbarAction import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.keymap.KeymapUtil 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.Disposer import com.intellij.ui.JBColor import com.intellij.util.ui.JBEmptyBorder import com.intellij.util.ui.MessageCategory import org.rust.cargo.project.model.cargoProjects import org.rust.cargo.project.settings.toolchain import org.rust.cargo.runconfig.command.workingDirectory import org.rust.cargo.toolchain.tools.Cargo import org.rust.cargo.toolchain.tools.evcxr import org.rust.ide.icons.RsIcons import org.rust.openapiext.saveAllDocuments import java.awt.BorderLayout import java.nio.charset.StandardCharsets import javax.swing.BorderFactory import javax.swing.Icon import javax.swing.JPanel class RsConsoleRunner(project: Project) : AbstractConsoleRunnerWithHistory<RsConsoleView>(project, TOOL_WINDOW_TITLE, null) { private lateinit var commandLine: GeneralCommandLine private lateinit var consoleCommunication: RsConsoleCommunication override fun getConsoleExecuteActionHandler(): RsConsoleExecuteActionHandler { return super.getConsoleExecuteActionHandler() as RsConsoleExecuteActionHandler } override fun getProcessHandler(): RsConsoleProcessHandler? { return super.getProcessHandler() as RsConsoleProcessHandler? } override fun createConsoleView(): RsConsoleView { val consoleView = RsConsoleView(project) consoleCommunication = RsConsoleCommunication(consoleView) return consoleView } override fun createContentDescriptorAndActions() { val actionManager = ActionManager.getInstance() val runActionGroup = DefaultActionGroup() val runToolbar = actionManager.createActionToolbar("RustConsoleRunner", runActionGroup, false) val outputActionGroup = DefaultActionGroup() val outputToolbar = actionManager.createActionToolbar("RustConsoleRunner", outputActionGroup, false).apply { val emptyBorderSize = component.border.getBorderInsets(component).left val outsideBorder = BorderFactory.createMatteBorder(0, 1, 0, 0, JBColor.border()) val insideBorder = JBEmptyBorder(emptyBorderSize) component.border = BorderFactory.createCompoundBorder(outsideBorder, insideBorder) } val actionsPanel = JPanel(BorderLayout()).apply { add(runToolbar.component, BorderLayout.WEST) add(outputToolbar.component, BorderLayout.CENTER) } val mainPanel = JPanel(BorderLayout()).apply { add(actionsPanel, BorderLayout.WEST) add(consoleView.component, BorderLayout.CENTER) runToolbar.targetComponent = this outputToolbar.targetComponent = this } val title = constructConsoleTitle(consoleTitle) val contentDescriptor = RunContentDescriptor(consoleView, processHandler, mainPanel, title, consoleIcon).apply { setFocusComputable { consoleView.consoleEditor.contentComponent } isAutoFocusContent = isAutoFocusContent Disposer.register(project, this) } val runActions = listOf( RestartAction(this), createConsoleExecAction(consoleExecuteActionHandler), StopAction(processHandler!!), CloseAction(executor, contentDescriptor, project) ) runActionGroup.addAll(runActions) val outputActions = listOf<AnAction>( SoftWrapAction(consoleView), ScrollToTheEndToolbarAction(consoleView.editor), PrintAction(consoleView), ConsoleHistoryController.getController(consoleView)!!.browseHistory, ShowVariablesAction(consoleView) ) outputActionGroup.addAll(outputActions) val actions = outputActions + runActions + EOFAction() registerActionShortcuts(actions, consoleView.consoleEditor.component) registerActionShortcuts(actions, mainPanel) showConsole(executor, contentDescriptor) } override fun createConsoleExecAction(consoleExecuteActionHandler: ProcessBackedConsoleExecuteActionHandler): AnAction { val consoleEditor = consoleView.consoleEditor val executeAction = super.createConsoleExecAction(consoleExecuteActionHandler) executeAction.registerCustomShortcutSet(getExecuteActionShortcut(), consoleEditor.component) val actionShortcutText = KeymapUtil.getFirstKeyboardShortcutText(executeAction) consoleEditor.setPlaceholder("<$actionShortcutText> to execute") consoleEditor.setShowPlaceholderWhenFocused(true) return executeAction } private fun getExecuteActionShortcut(): ShortcutSet { val keymap = KeymapManager.getInstance().activeKeymap val shortcuts = keymap.getShortcuts("Console.Execute.Multiline") return if (shortcuts.isNotEmpty()) { CustomShortcutSet(*shortcuts) } else { CommonShortcuts.CTRL_ENTER } } fun runSync(requestEditorFocus: Boolean) { if (Cargo.checkNeedInstallEvcxr(project)) return try { initAndRun() ProgressManager.getInstance().run(object : Task.Backgroundable(project, "Connecting to Console", false) { override fun run(indicator: ProgressIndicator) { indicator.text = "Connecting to console..." connect() if (requestEditorFocus) { consoleView?.requestFocus() } } }) } catch (e: Exception) { LOG.warn("Error running console", e) showErrorsInConsole(e) } } fun run(requestEditorFocus: Boolean) { if (Cargo.checkNeedInstallEvcxr(project)) return // BACKCOMPAT: 2019.3 @Suppress("DEPRECATION") TransactionGuard.submitTransaction(project) { saveAllDocuments() } ApplicationManager.getApplication().executeOnPooledThread { ProgressManager.getInstance().run(object : Task.Backgroundable(project, "Connecting to Console", false) { override fun run(indicator: ProgressIndicator) { indicator.text = "Connecting to console..." try { initAndRun() connect() if (requestEditorFocus) { consoleView?.requestFocus() } } catch (e: Exception) { LOG.warn("Error running console", e) invokeAndWaitIfNeeded { showErrorsInConsole(e) } } } }) } } override fun initAndRun() { invokeAndWaitIfNeeded { super.initAndRun() } } override fun createProcessHandler(process: Process): OSProcessHandler = RsConsoleProcessHandler( process, consoleView, consoleCommunication, commandLine.commandLineString, StandardCharsets.UTF_8 ) private fun createCommandLine(): GeneralCommandLine { val cargoProject = project.cargoProjects.allProjects.firstOrNull() ?: throw RuntimeException("No cargo project") val toolchain = project.toolchain ?: throw RuntimeException("Rust toolchain is not defined") val evcxr = toolchain.evcxr() ?: throw RuntimeException("Evcxr executable not found") val workingDir = cargoProject.workingDirectory return evcxr.createCommandLine(workingDir.toFile()) } override fun createProcess(): Process { commandLine = createCommandLine() return commandLine.createProcess() } private fun connect() { invokeLater { consoleView.removeBorders() consoleView.initVariablesWindow() consoleView.executeActionHandler = consoleExecuteActionHandler consoleExecuteActionHandler.isEnabled = true consoleView.initialized() } } override fun createExecuteActionHandler(): RsConsoleExecuteActionHandler { val consoleExecuteActionHandler = RsConsoleExecuteActionHandler(processHandler!!, consoleCommunication) consoleExecuteActionHandler.isEnabled = false ConsoleHistoryController(RsConsoleRootType.instance, "", consoleView).install() return consoleExecuteActionHandler } fun rerun() { object : Task.Backgroundable(project, "Restarting console", true) { override fun run(indicator: ProgressIndicator) { val processHandler = processHandler if (processHandler != null) { processHandler.destroyProcess() processHandler.waitFor() } runInEdt { RsConsoleRunner(project).run(true) } } }.queue() } private fun showErrorsInConsole(e: Exception) { val actionGroup = DefaultActionGroup(RestartAction(this)) val actionToolbar = ActionManager.getInstance() .createActionToolbar("RsConsoleRunnerErrors", actionGroup, false) // Runner creating val panel = JPanel(BorderLayout()) panel.add(actionToolbar.component, BorderLayout.WEST) val errorViewPanel = NewErrorTreeViewPanel(project, null, false, false, null) val messages = mutableListOf("Can't start evcxr.") val message = e.message if (message != null && message.isNotBlank()) { messages += message.lines() } errorViewPanel.addMessage(MessageCategory.ERROR, messages.toTypedArray(), null, -1, -1, null) panel.add(errorViewPanel, BorderLayout.CENTER) val contentDescriptor = RunContentDescriptor(null, processHandler, panel, "Error Running Console") showConsole(executor, contentDescriptor) } override fun getConsoleIcon(): Icon { return RsIcons.REPL } companion object { val LOG: Logger = logger<RsConsoleRunner>() const val TOOL_WINDOW_TITLE: String = "Rust REPL" } }
mit
d3d4891164e34ad86ad154e075ec4991
37.798635
123
0.681474
5.608288
false
false
false
false
arcuri82/testing_security_development_enterprise_systems
advanced/exercise-solutions/card-game/part-09/auth/src/main/kotlin/org/tsdes/advanced/exercises/cardgame/auth/RestApi.kt
1
3088
package org.tsdes.advanced.exercises.cardgame.auth import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.Authentication import org.springframework.security.core.authority.AuthorityUtils import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.web.bind.annotation.* import org.tsdes.advanced.exercises.cardgame.auth.db.UserService import java.security.Principal /** * Created by arcuri82 on 08-Nov-17. */ @RestController @RequestMapping("/api/auth") class RestApi( private val service: UserService, private val authenticationManager: AuthenticationManager, private val userDetailsService: UserDetailsService ) { @RequestMapping("/user") fun user(user: Principal): ResponseEntity<Map<String, Any>> { val map = mutableMapOf<String,Any>() map["name"] = user.name map["roles"] = AuthorityUtils.authorityListToSet((user as Authentication).authorities) return ResponseEntity.ok(map) } @PostMapping(path = ["/signUp"], consumes = [(MediaType.APPLICATION_JSON_UTF8_VALUE)]) fun signUp(@RequestBody dto: AuthDto) : ResponseEntity<Void> { val userId : String = dto.userId!! val password : String = dto.password!! val registered = service.createUser(userId, password, setOf("USER")) if (!registered) { return ResponseEntity.status(400).build() } val userDetails = userDetailsService.loadUserByUsername(userId) val token = UsernamePasswordAuthenticationToken(userDetails, password, userDetails.authorities) authenticationManager.authenticate(token) if (token.isAuthenticated) { SecurityContextHolder.getContext().authentication = token } return ResponseEntity.status(201).build() } @PostMapping(path = ["/login"], consumes = [(MediaType.APPLICATION_JSON_UTF8_VALUE)]) fun login(@RequestBody dto: AuthDto) : ResponseEntity<Void> { val userId : String = dto.userId!! val password : String = dto.password!! val userDetails = try{ userDetailsService.loadUserByUsername(userId) } catch (e: UsernameNotFoundException){ return ResponseEntity.status(400).build() } val token = UsernamePasswordAuthenticationToken(userDetails, password, userDetails.authorities) authenticationManager.authenticate(token) if (token.isAuthenticated) { SecurityContextHolder.getContext().authentication = token return ResponseEntity.status(204).build() } return ResponseEntity.status(400).build() } }
lgpl-3.0
98715682e0e781a4f26c7a5fdaa606c9
34.102273
103
0.711464
5.172529
false
false
false
false
charleskorn/batect
app/src/unitTest/kotlin/batect/cli/options/ValueConvertersSpec.kt
1
14640
/* Copyright 2017-2020 Charles Korn. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.cli.options import batect.os.PathResolutionResult import batect.os.PathResolver import batect.os.PathResolverFactory import batect.os.PathType import batect.testutils.equalTo import batect.testutils.given import batect.ui.OutputStyle import com.google.common.jimfs.Configuration import com.google.common.jimfs.Jimfs import com.natpryce.hamkrest.assertion.assertThat import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object ValueConvertersSpec : Spek({ describe("value converters") { describe("string value converter") { it("returns the value passed to it") { assertThat(ValueConverters.string("some-value"), equalTo(ValueConversionResult.ConversionSucceeded("some-value"))) } } describe("boolean value converter") { listOf( "1", "yes", "YES", "true", "TRUE" ).forEach { value -> given("the value '$value'") { it("returns the value 'true'") { assertThat(ValueConverters.boolean(value), equalTo(ValueConversionResult.ConversionSucceeded(true))) } } } listOf( "0", "no", "NO", "false", "FALSE" ).forEach { value -> given("the value '$value'") { it("returns the value 'false'") { assertThat(ValueConverters.boolean(value), equalTo(ValueConversionResult.ConversionSucceeded(false))) } } } given("an invalid value") { it("returns an appropriate error") { assertThat(ValueConverters.boolean("blah"), equalTo(ValueConversionResult.ConversionFailed("Value is not a recognised boolean value."))) } } } describe("positive integer value converter") { given("a positive integer") { it("returns the parsed representation of that integer") { assertThat(ValueConverters.positiveInteger("1"), equalTo(ValueConversionResult.ConversionSucceeded(1))) } } given("zero") { it("returns an error") { assertThat(ValueConverters.positiveInteger("0"), equalTo(ValueConversionResult.ConversionFailed("Value must be positive."))) } } given("a negative integer") { it("returns an error") { assertThat(ValueConverters.positiveInteger("-1"), equalTo(ValueConversionResult.ConversionFailed("Value must be positive."))) } } given("an empty string") { it("returns an error") { assertThat(ValueConverters.positiveInteger(""), equalTo(ValueConversionResult.ConversionFailed("Value is not a valid integer."))) } } given("a hexadecimal number") { it("returns an error") { assertThat(ValueConverters.positiveInteger("123AAA"), equalTo(ValueConversionResult.ConversionFailed("Value is not a valid integer."))) } } given("something that is not a number") { it("returns an error") { assertThat(ValueConverters.positiveInteger("x"), equalTo(ValueConversionResult.ConversionFailed("Value is not a valid integer."))) } } } describe("optional enum value converter") { val converter = ValueConverters.optionalEnum<OutputStyle>() given("a valid value") { it("returns the equivalent enum constant") { assertThat(converter("simple"), equalTo(ValueConversionResult.ConversionSucceeded(OutputStyle.Simple))) } } given("an empty string") { it("returns an error") { assertThat(converter(""), equalTo(ValueConversionResult.ConversionFailed("Value must be one of 'all', 'fancy', 'quiet' or 'simple'."))) } } given("an invalid value") { it("returns an error") { assertThat(converter("nonsense"), equalTo(ValueConversionResult.ConversionFailed("Value must be one of 'all', 'fancy', 'quiet' or 'simple'."))) } } } describe("path to file converter") { val fileSystem = Jimfs.newFileSystem(Configuration.unix()) val pathResolver = mock<PathResolver> { on { resolve("file") } doReturn PathResolutionResult.Resolved("file", fileSystem.getPath("/resolved/file"), PathType.File) on { resolve("directory") } doReturn PathResolutionResult.Resolved("directory", fileSystem.getPath("/resolved/directory"), PathType.Directory) on { resolve("other") } doReturn PathResolutionResult.Resolved("other", fileSystem.getPath("/resolved/other"), PathType.Other) on { resolve("does-not-exist") } doReturn PathResolutionResult.Resolved("does-not-exist", fileSystem.getPath("/resolved/does-not-exist"), PathType.DoesNotExist) on { resolve("invalid") } doReturn PathResolutionResult.InvalidPath("invalid") } val pathResolverFactory = mock<PathResolverFactory> { on { createResolverForCurrentDirectory() } doReturn pathResolver } given("the file is not required to exist") { val converter = ValueConverters.pathToFile(pathResolverFactory, mustExist = false) given("a path to a file that exists") { it("returns the resolved path") { assertThat(converter("file"), equalTo(ValueConversionResult.ConversionSucceeded(fileSystem.getPath("/resolved/file")))) } } given("a path to a directory") { it("returns an error") { assertThat(converter("directory"), equalTo(ValueConversionResult.ConversionFailed("The path 'directory' (resolved to '/resolved/directory') refers to a directory."))) } } given("a path to something other than a file or directory") { it("returns an error") { assertThat(converter("other"), equalTo(ValueConversionResult.ConversionFailed("The path 'other' (resolved to '/resolved/other') refers to something other than a file."))) } } given("a path to a file that does not exist") { it("returns the resolved path") { assertThat(converter("does-not-exist"), equalTo(ValueConversionResult.ConversionSucceeded(fileSystem.getPath("/resolved/does-not-exist")))) } } given("an invalid path") { it("returns an error") { assertThat(converter("invalid"), equalTo(ValueConversionResult.ConversionFailed("'invalid' is not a valid path."))) } } } given("the file is required to exist") { val converter = ValueConverters.pathToFile(pathResolverFactory, mustExist = true) given("a path to a file that exists") { it("returns the resolved path") { assertThat(converter("file"), equalTo(ValueConversionResult.ConversionSucceeded(fileSystem.getPath("/resolved/file")))) } } given("a path to a directory") { it("returns an error") { assertThat(converter("directory"), equalTo(ValueConversionResult.ConversionFailed("The path 'directory' (resolved to '/resolved/directory') refers to a directory."))) } } given("a path to something other than a file or directory") { it("returns an error") { assertThat(converter("other"), equalTo(ValueConversionResult.ConversionFailed("The path 'other' (resolved to '/resolved/other') refers to something other than a file."))) } } given("a path to a file that does not exist") { it("returns an error") { assertThat(converter("does-not-exist"), equalTo(ValueConversionResult.ConversionFailed("The file 'does-not-exist' (resolved to '/resolved/does-not-exist') does not exist."))) } } given("an invalid path") { it("returns an error") { assertThat(converter("invalid"), equalTo(ValueConversionResult.ConversionFailed("'invalid' is not a valid path."))) } } } } describe("path to directory converter") { val fileSystem = Jimfs.newFileSystem(Configuration.unix()) val pathResolver = mock<PathResolver> { on { resolve("file") } doReturn PathResolutionResult.Resolved("file", fileSystem.getPath("/resolved/file"), PathType.File) on { resolve("directory") } doReturn PathResolutionResult.Resolved("directory", fileSystem.getPath("/resolved/directory"), PathType.Directory) on { resolve("other") } doReturn PathResolutionResult.Resolved("other", fileSystem.getPath("/resolved/other"), PathType.Other) on { resolve("does-not-exist") } doReturn PathResolutionResult.Resolved("does-not-exist", fileSystem.getPath("/resolved/does-not-exist"), PathType.DoesNotExist) on { resolve("invalid") } doReturn PathResolutionResult.InvalidPath("invalid") } val pathResolverFactory = mock<PathResolverFactory> { on { createResolverForCurrentDirectory() } doReturn pathResolver } given("the directory is not required to exist") { val converter = ValueConverters.pathToDirectory(pathResolverFactory, mustExist = false) given("a path to a file") { it("returns an error") { assertThat(converter("file"), equalTo(ValueConversionResult.ConversionFailed("The path 'file' (resolved to '/resolved/file') refers to a file."))) } } given("a path to a directory") { it("returns the resolved path") { assertThat(converter("directory"), equalTo(ValueConversionResult.ConversionSucceeded(fileSystem.getPath("/resolved/directory")))) } } given("a path to something other than a file or directory") { it("returns an error") { assertThat(converter("other"), equalTo(ValueConversionResult.ConversionFailed("The path 'other' (resolved to '/resolved/other') refers to something other than a directory."))) } } given("a path to a directory that does not exist") { it("returns the resolved path") { assertThat(converter("does-not-exist"), equalTo(ValueConversionResult.ConversionSucceeded(fileSystem.getPath("/resolved/does-not-exist")))) } } given("an invalid path") { it("returns an error") { assertThat(converter("invalid"), equalTo(ValueConversionResult.ConversionFailed("'invalid' is not a valid path."))) } } } given("the file is required to exist") { val converter = ValueConverters.pathToDirectory(pathResolverFactory, mustExist = true) given("a path to a file") { it("returns an error") { assertThat(converter("file"), equalTo(ValueConversionResult.ConversionFailed("The path 'file' (resolved to '/resolved/file') refers to a file."))) } } given("a path to a directory") { it("returns the resolved path") { assertThat(converter("directory"), equalTo(ValueConversionResult.ConversionSucceeded(fileSystem.getPath("/resolved/directory")))) } } given("a path to something other than a file or directory") { it("returns an error") { assertThat(converter("other"), equalTo(ValueConversionResult.ConversionFailed("The path 'other' (resolved to '/resolved/other') refers to something other than a directory."))) } } given("a path to a directory that does not exist") { it("returns an error") { assertThat(converter("does-not-exist"), equalTo(ValueConversionResult.ConversionFailed("The directory 'does-not-exist' (resolved to '/resolved/does-not-exist') does not exist."))) } } given("an invalid path") { it("returns an error") { assertThat(converter("invalid"), equalTo(ValueConversionResult.ConversionFailed("'invalid' is not a valid path."))) } } } } } })
apache-2.0
76eb5510f364b921b3a41fc432a96364
45.773163
203
0.556421
5.630769
false
false
false
false
oleksiyp/mockk
agent/android/src/main/kotlin/io/mockk/proxy/android/advice/Advice.kt
1
5500
/* * Copyright (c) 2018 Mockito contributors * This program is made available under the terms of the MIT License. */ package io.mockk.proxy.android.advice import io.mockk.proxy.MockKAgentException import io.mockk.proxy.android.AndroidMockKMap import io.mockk.proxy.android.MethodDescriptor import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.lang.reflect.Modifier import java.lang.reflect.Modifier.isFinal import java.lang.reflect.Modifier.isPublic import java.util.concurrent.Callable internal class Advice( private val handlers: AndroidMockKMap, private val staticHandlers: AndroidMockKMap, private val constructorHandlers: AndroidMockKMap ) { private val selfCallInfo = SelfCallInfo() @Suppress("unused") // called from dispatcher fun getOrigin(instance: Any?, methodWithTypeAndSignature: String): Method? { val methodDesc = MethodDescriptor(methodWithTypeAndSignature) val obj = instance ?: MethodDescriptor.classForTypeName(methodDesc.className) if (!obj.checkSelfCall()) { return null } if (instance != null && instance::class.java.isOverridden(methodDesc.method)) { return null } return methodDesc.method } @Suppress("unused") // called from dispatcher fun handle( instance: Any, origin: Method, arguments: Array<Any?> ): Callable<*>? { if (isInternalHashMap(instance)) { return null; } val instanceOrClass = if (Modifier.isStatic(origin.modifiers)) { val methodDesc = MethodDescriptor(instance as String) MethodDescriptor.classForTypeName(methodDesc.className) } else { instance } val handler = handlers[instanceOrClass] ?: staticHandlers[instanceOrClass] ?: constructorHandlers[instanceOrClass] ?: return null val superMethodCall = SuperMethodCall( selfCallInfo, origin, instanceOrClass, arguments ) return Callable { handler.invocation( instanceOrClass, origin, superMethodCall, arguments ) } } private fun isInternalHashMap(instance: Any) = handlers.isInternalHashMap(instance) || staticHandlers.isInternalHashMap(instance) || constructorHandlers.isInternalHashMap(instance) @Suppress("unused") // called from dispatcher fun handleConstructor( instance: Any, methodDescriptor: String, arguments: Array<Any?> ): Callable<*>? { val methodDesc = MethodDescriptor(methodDescriptor) val cls = MethodDescriptor.classForTypeName(methodDesc.className) val handler = constructorHandlers[cls] ?: return null return Callable { handler.invocation( instance, null, null, arguments ) } } @Suppress("unused") // called from dispatcher fun isMock(instance: Any): Boolean { if (isInternalHashMap(instance)) { return false; } return handlers.containsKey(instance) || staticHandlers.containsKey(instance) || constructorHandlers.containsKey(instance) } private fun Any.checkSelfCall() = selfCallInfo.checkSelfCall(this) private class SuperMethodCall( private val selfCallInfo: SelfCallInfo, private val origin: Method, private val instance: Any, private val arguments: Array<Any?> ) : Callable<Any?> { override fun call(): Any? = try { origin.makeAccessible() selfCallInfo.set(instance) origin.invoke(instance, *arguments) } catch (exception: InvocationTargetException) { throw exception.cause ?: MockKAgentException("no cause for InvocationTargetException", exception) } } private class SelfCallInfo : ThreadLocal<Any>() { fun checkSelfCall(value: Any) = if (get() === value) { set(null) false } else { true } } companion object { private tailrec fun Class<*>.isOverridden(origin: Method): Boolean { val method = findMethod(origin.name, origin.parameterTypes) ?: return superclass.isOverridden(origin) return origin.declaringClass !== method.declaringClass } private fun Class<*>.findMethod(name: String, parameters: Array<Class<*>>) = declaredMethods.firstOrNull { it.name == name && it.parameterTypes refEquals parameters } private infix fun <T> Array<T>.refEquals(other: Array<T>) = size == other.size && zip(other).none { (a, b) -> a !== b } private val Class<*>.final get() = isFinal(modifiers) private val Method.final get() = isFinal(modifiers) private fun Method.makeAccessible() { if (!isPublic(declaringClass.modifiers and this.modifiers)) { isAccessible = true } } } }
apache-2.0
a93a49752255763b7b8240f753114a2a
29.38674
95
0.587455
5.27325
false
false
false
false
darkpaw/boss_roobot
src/org/darkpaw/ld33/mobs/ActionTimer.kt
1
659
package org.darkpaw.ld33.mobs import org.darkpaw.ld33.Vector class ActionTimer(){ var timer_frames : Double = 0.0 var expired : Boolean = false fun tick(){ if(timer_frames < 0.0) expired = true timer_frames -= 1 } fun set(duration : Double){ timer_frames = duration expired = false } // // // fun move(){ // if(reload_timer > 0.0){ // reloading = true // reload_timer -= 1.0 // }else{ // reloading = false // } // // // } // // fun fire() { // reload_timer = game_world.target_fps * 1.5 // reloading = true // } }
agpl-3.0
594d0d2de3e83766cb829e0e487147c1
15.475
52
0.491654
3.328283
false
false
false
false
EventFahrplan/EventFahrplan
network/src/main/java/info/metadude/android/eventfahrplan/network/models/Session.kt
1
1943
package info.metadude.android.eventfahrplan.network.models import info.metadude.android.eventfahrplan.network.serialization.FahrplanParser /** * Network model representing a lecture, a workshop or any similar time-framed happening. * Values in this class are parsed from a schedule XML file via [FahrplanParser]. */ data class Session( var sessionId: String = "", var abstractt: String = "", var dayIndex: Int = 0, // XML values start with 1 var date: String = "", var dateUTC: Long = 0, var description: String = "", var duration: Int = 0, // minutes var hasAlarm: Boolean = false, var isHighlight: Boolean = false, var language: String = "", var links: String = "", var relativeStartTime: Int = 0, var recordingLicense: String = "", var recordingOptOut: Boolean = RECORDING_OPT_OUT_OFF, var room: String = "", var roomIndex: Int = 0, var speakers: String = "", var startTime: Int = 0, // minutes since day start var slug: String = "", var subtitle: String = "", var timeZoneOffset: Int? = null, // seconds var title: String = "", var track: String = "", var type: String = "", var url: String = "", var changedDayIndex: Boolean = false, var changedDuration: Boolean = false, var changedIsCanceled: Boolean = false, var changedIsNew: Boolean = false, var changedLanguage: Boolean = false, var changedRecordingOptOut: Boolean = false, var changedRoom: Boolean = false, var changedSpeakers: Boolean = false, var changedStartTime: Boolean = false, var changedSubtitle: Boolean = false, var changedTitle: Boolean = false, var changedTrack: Boolean = false ) { companion object { const val RECORDING_OPT_OUT_OFF = false } }
apache-2.0
cc32f9fdf79fda45a89519f7cf24cca7
33.087719
89
0.610396
4.615202
false
false
false
false