repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
siosio/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/completion/TextCompletionInfo.kt
2
458
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.service.ui.completion import com.intellij.openapi.util.NlsSafe import org.jetbrains.annotations.Nls import javax.swing.Icon data class TextCompletionInfo( val text: @NlsSafe String, val description: @Nls String? = null, val icon: Icon? = null) { }
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/numberConversion/convertExpression.kt
4
119
// "Convert expression to 'Int'" "true" // WITH_RUNTIME fun foo() { bar("1".toLong()<caret>) } fun bar(l: Int) { }
apache-2.0
siosio/intellij-community
plugins/git4idea/tests/git4idea/index/GitStageTrackerTest.kt
1
6053
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.index import com.google.common.util.concurrent.MoreExecutors import com.google.common.util.concurrent.SettableFuture import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.application.runReadAction import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.Executor import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.testFramework.UsefulTestCase import com.intellij.vcsUtil.VcsUtil import git4idea.index.vfs.GitIndexFileSystemRefresher import git4idea.test.GitSingleRepoTest import junit.framework.TestCase import org.apache.commons.lang.RandomStringUtils import java.util.concurrent.Future import java.util.concurrent.TimeUnit class GitStageTrackerTest : GitSingleRepoTest() { private var _tracker: GitStageTracker? = null private val tracker get() = _tracker!! override fun setUp() { super.setUp() VcsConfiguration.StandardConfirmation.ADD.doNothing() repo.untrackedFilesHolder.createWaiter().waitFor() _tracker = GitStageTracker(project) } override fun tearDown() { val t = _tracker _tracker = null t?.let { Disposer.dispose(it) } repo.untrackedFilesHolder.createWaiter().waitFor() super.tearDown() } fun `test unstaged`() { val fileName = "file.txt" Executor.touch(fileName, RandomStringUtils.randomAlphanumeric(200)) git("add .") git("commit -m file") runWithTrackerUpdate("refresh") { refresh() } assertTrue(trackerState().isEmpty()) val file = projectRoot.findChild(fileName)!! val document = runReadAction { FileDocumentManager.getInstance().getDocument(file)!! } runWithTrackerUpdate("setText") { invokeAndWaitIfNeeded { runWriteAction { document.setText(RandomStringUtils.randomAlphanumeric(100)) } } } trackerState().let { state -> TestCase.assertEquals(GitFileStatus(' ', 'M', VcsUtil.getFilePath(file)), state.statuses.getValue(VcsUtil.getFilePath(file))) } runWithTrackerUpdate("saveDocument") { invokeAndWaitIfNeeded { FileDocumentManager.getInstance().saveDocument(document) } } trackerState().let { state -> TestCase.assertEquals(GitFileStatus(' ', 'M', VcsUtil.getFilePath(file)), state.statuses.getValue(VcsUtil.getFilePath(file))) } } fun `test staged`() { val fileName = "file.txt" Executor.touch(fileName, RandomStringUtils.randomAlphanumeric(200)) git("add .") git("commit -m file") runWithTrackerUpdate("refresh") { refresh() } assertTrue(trackerState().isEmpty()) val file = projectRoot.findChild(fileName)!! val indexFile = project.service<GitIndexFileSystemRefresher>().getFile(projectRoot, VcsUtil.getFilePath(file))!! val document = runReadAction { FileDocumentManager.getInstance().getDocument(indexFile)!!} runWithTrackerUpdate("setText") { invokeAndWaitIfNeeded { runWriteAction { document.setText(RandomStringUtils.randomAlphanumeric(100)) } } } trackerState().let { state -> TestCase.assertEquals(GitFileStatus('M', ' ', VcsUtil.getFilePath(file)), state.statuses.getValue(VcsUtil.getFilePath(file))) } runWithTrackerUpdate("saveDocument") { invokeAndWaitIfNeeded { FileDocumentManager.getInstance().saveDocument(document) } } trackerState().let { state -> TestCase.assertEquals(GitFileStatus('M', 'M', VcsUtil.getFilePath(file)), state.statuses.getValue(VcsUtil.getFilePath(file))) } } fun `test untracked`() { val fileName = "file.txt" val file = runWithTrackerUpdate("createChildData") { invokeAndWaitIfNeeded { runWriteAction { projectRoot.createChildData(this, fileName) }} } TestCase.assertEquals(GitFileStatus('?', '?', VcsUtil.getFilePath(file)), trackerState().statuses.getValue(VcsUtil.getFilePath(projectRoot, fileName))) val document = runReadAction { FileDocumentManager.getInstance().getDocument(file)!!} runWithTrackerUpdate("setText") { invokeAndWaitIfNeeded { runWriteAction { document.setText(RandomStringUtils.randomAlphanumeric(100)) } } } trackerState().let { state -> TestCase.assertEquals(GitFileStatus('?', '?', VcsUtil.getFilePath(file)), state.statuses.getValue(VcsUtil.getFilePath(file))) } runWithTrackerUpdate("saveDocument") { invokeAndWaitIfNeeded { FileDocumentManager.getInstance().saveDocument(document) } } trackerState().let { state -> TestCase.assertEquals(GitFileStatus('?', '?', VcsUtil.getFilePath(file)), state.statuses.getValue(VcsUtil.getFilePath(file))) } } private fun trackerState() = tracker.state.rootStates.getValue(projectRoot) private fun <T> runWithTrackerUpdate(name: String, function: () -> T): T { return tracker.futureUpdate(name).let { futureUpdate -> val result = function() futureUpdate.waitOrCancel() return@let result } } private fun Future<Unit>.waitOrCancel() { try { get(2, TimeUnit.SECONDS) } finally { cancel(false) } } private fun GitStageTracker.futureUpdate(name: String): Future<Unit> { val removeListener = Disposer.newDisposable("Listener disposable") val future = SettableFuture.create<Unit>() addListener(object : GitStageTrackerListener { override fun update() { UsefulTestCase.LOG.debug("Refreshed tracker after \"$name\"") future.set(Unit) } }, removeListener) future.addListener(Runnable { Disposer.dispose(removeListener) }, MoreExecutors.directExecutor()) return future } }
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/intentions/joinParameterList/hasLineBreakBeforeFirstParam.kt
4
47
fun test(<caret> a: Int, b: Int, c: Int) {}
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/j2k/J2KPostProcessingRegistrarImpl.kt
2
18568
// 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.j2k import com.intellij.codeInspection.ProblemHighlightType import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.core.setVisibility import org.jetbrains.kotlin.idea.inspections.* import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToElvisInspection import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToSafeAccessInspection import org.jetbrains.kotlin.idea.inspections.conventionNameCalls.ReplaceGetOrSetInspection import org.jetbrains.kotlin.idea.intentions.* import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnAsymmetricallyIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isTrivialStatementBody import org.jetbrains.kotlin.idea.quickfix.RemoveModifierFix import org.jetbrains.kotlin.idea.quickfix.RemoveUselessCastFix import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getChildOfType import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getType import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.mapToIndex object J2KPostProcessingRegistrarImpl : J2KPostProcessingRegistrar { private val myProcessings = ArrayList<J2kPostProcessing>() override val processings: Collection<J2kPostProcessing> get() = myProcessings private val processingsToPriorityMap = HashMap<J2kPostProcessing, Int>() override fun priority(processing: J2kPostProcessing): Int = processingsToPriorityMap[processing]!! init { myProcessings.add(RemoveExplicitTypeArgumentsProcessing()) myProcessings.add(RemoveRedundantOverrideVisibilityProcessing()) registerInspectionBasedProcessing(MoveLambdaOutsideParenthesesInspection()) myProcessings.add(FixObjectStringConcatenationProcessing()) myProcessings.add(ConvertToStringTemplateProcessing()) myProcessings.add(UsePropertyAccessSyntaxProcessing()) myProcessings.add(UninitializedVariableReferenceFromInitializerToThisReferenceProcessing()) myProcessings.add(UnresolvedVariableReferenceFromInitializerToThisReferenceProcessing()) myProcessings.add(RemoveRedundantSamAdaptersProcessing()) myProcessings.add(RemoveRedundantCastToNullableProcessing()) registerInspectionBasedProcessing(ReplacePutWithAssignmentInspection()) myProcessings.add(UseExpressionBodyProcessing()) registerInspectionBasedProcessing(UnnecessaryVariableInspection()) registerInspectionBasedProcessing(FoldInitializerAndIfToElvisInspection()) registerIntentionBasedProcessing(FoldIfToReturnIntention()) { it.then.isTrivialStatementBody() && it.`else`.isTrivialStatementBody() } registerIntentionBasedProcessing(FoldIfToReturnAsymmetricallyIntention()) { it.then.isTrivialStatementBody() && (KtPsiUtil.skipTrailingWhitespacesAndComments( it ) as KtReturnExpression).returnedExpression.isTrivialStatementBody() } registerInspectionBasedProcessing(IfThenToSafeAccessInspection()) registerInspectionBasedProcessing(IfThenToElvisInspection(true)) registerInspectionBasedProcessing(SimplifyNegatedBinaryExpressionInspection()) registerInspectionBasedProcessing(ReplaceGetOrSetInspection()) registerInspectionBasedProcessing(AddOperatorModifierInspection()) registerIntentionBasedProcessing(ObjectLiteralToLambdaIntention()) registerIntentionBasedProcessing(AnonymousFunctionToLambdaIntention()) registerIntentionBasedProcessing(RemoveUnnecessaryParenthesesIntention()) registerIntentionBasedProcessing(DestructureIntention()) registerInspectionBasedProcessing(SimplifyAssertNotNullInspection()) registerIntentionBasedProcessing(RemoveRedundantCallsOfConversionMethodsIntention()) registerInspectionBasedProcessing(JavaMapForEachInspection()) registerInspectionBasedProcessing(ReplaceGuardClauseWithFunctionCallInspection()) registerDiagnosticBasedProcessing<KtBinaryExpressionWithTypeRHS>(Errors.USELESS_CAST) { element, _ -> val expression = RemoveUselessCastFix.invoke(element) val variable = expression.parent as? KtProperty if (variable != null && expression == variable.initializer && variable.isLocal) { val ref = ReferencesSearch.search(variable, LocalSearchScope(variable.containingFile)).findAll().singleOrNull() if (ref != null && ref.element is KtSimpleNameExpression) { ref.element.replace(expression) variable.delete() } } } registerDiagnosticBasedProcessing<KtTypeProjection>(Errors.REDUNDANT_PROJECTION) { _, diagnostic -> val fix = RemoveModifierFix.createRemoveProjectionFactory(true).createActions(diagnostic).single() as RemoveModifierFix fix.invoke() } registerDiagnosticBasedProcessingFactory( Errors.VAL_REASSIGNMENT, Errors.CAPTURED_VAL_INITIALIZATION, Errors.CAPTURED_MEMBER_VAL_INITIALIZATION ) { element: KtSimpleNameExpression, _: Diagnostic -> val property = element.mainReference.resolve() as? KtProperty if (property == null) { null } else { { if (!property.isVar) { property.valOrVarKeyword.replace(KtPsiFactory(element.project).createVarKeyword()) } } } } registerDiagnosticBasedProcessing<KtSimpleNameExpression>(Errors.UNNECESSARY_NOT_NULL_ASSERTION) { element, _ -> val exclExclExpr = element.parent as KtUnaryExpression val baseExpression = exclExclExpr.baseExpression!! val context = baseExpression.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) if (context.diagnostics.forElement(element).any { it.factory == Errors.UNNECESSARY_NOT_NULL_ASSERTION }) { exclExclExpr.replace(baseExpression) } } processingsToPriorityMap.putAll(myProcessings.mapToIndex()) } private inline fun <reified TElement : KtElement, TIntention : SelfTargetingRangeIntention<TElement>> registerIntentionBasedProcessing( intention: TIntention, noinline additionalChecker: (TElement) -> Boolean = { true } ) { myProcessings.add(object : J2kPostProcessing { // Intention can either need or not need write action override val writeActionNeeded = intention.startInWriteAction() override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (!TElement::class.java.isInstance(element)) return null val tElement = element as TElement if (intention.applicabilityRange(tElement) == null) return null if (!additionalChecker(tElement)) return null return { if (intention.applicabilityRange(tElement) != null) { // check availability of the intention again because something could change intention.applyTo(element, null) } } } }) } private inline fun <reified TElement : KtElement, TInspection : AbstractApplicabilityBasedInspection<TElement>> registerInspectionBasedProcessing( inspection: TInspection, acceptInformationLevel: Boolean = false ) { myProcessings.add(object : J2kPostProcessing { // Inspection can either need or not need write action override val writeActionNeeded = inspection.startFixInWriteAction private fun isApplicable(element: TElement): Boolean { if (!inspection.isApplicable(element)) return false return acceptInformationLevel || inspection.inspectionHighlightType(element) != ProblemHighlightType.INFORMATION } override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (!TElement::class.java.isInstance(element)) return null val tElement = element as TElement if (!isApplicable(tElement)) return null return { if (isApplicable(tElement)) { // check availability of the inspection again because something could change inspection.applyTo(tElement) } } } }) } private inline fun <reified TElement : KtElement> registerDiagnosticBasedProcessing( vararg diagnosticFactory: DiagnosticFactory<*>, crossinline fix: (TElement, Diagnostic) -> Unit ) { registerDiagnosticBasedProcessingFactory(*diagnosticFactory) { element: TElement, diagnostic: Diagnostic -> { fix( element, diagnostic ) } } } private inline fun <reified TElement : KtElement> registerDiagnosticBasedProcessingFactory( vararg diagnosticFactory: DiagnosticFactory<*>, crossinline fixFactory: (TElement, Diagnostic) -> (() -> Unit)? ) { myProcessings.add(object : J2kPostProcessing { // ??? override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (!TElement::class.java.isInstance(element)) return null val diagnostic = diagnostics.forElement(element).firstOrNull { it.factory in diagnosticFactory } ?: return null return fixFactory(element as TElement, diagnostic) } }) } private class RemoveExplicitTypeArgumentsProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtTypeArgumentList || !RemoveExplicitTypeArgumentsIntention.isApplicableTo( element, approximateFlexible = true ) ) return null return { if (RemoveExplicitTypeArgumentsIntention.isApplicableTo(element, approximateFlexible = true)) { element.delete() } } } } private class RemoveRedundantOverrideVisibilityProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtCallableDeclaration || !element.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return null val modifier = element.visibilityModifierType() ?: return null return { element.setVisibility(modifier) } } } private class ConvertToStringTemplateProcessing : J2kPostProcessing { override val writeActionNeeded = true private val intention = ConvertToStringTemplateIntention() override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element is KtBinaryExpression && intention.isApplicableTo(element) && ConvertToStringTemplateIntention.shouldSuggestToConvert( element ) ) { return { intention.applyTo(element, null) } } else { return null } } } private class UsePropertyAccessSyntaxProcessing : J2kPostProcessing { override val writeActionNeeded = true private val intention = UsePropertyAccessSyntaxIntention() override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtCallExpression) return null val propertyName = intention.detectPropertyNameToUse(element) ?: return null return { intention.applyTo(element, propertyName, reformat = true) } } } private class RemoveRedundantSamAdaptersProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtCallExpression) return null val expressions = RedundantSamConstructorInspection.samConstructorCallsToBeConverted(element) if (expressions.isEmpty()) return null return { RedundantSamConstructorInspection.samConstructorCallsToBeConverted(element) .forEach { RedundantSamConstructorInspection.replaceSamConstructorCall(it) } } } } private class UseExpressionBodyProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtPropertyAccessor) return null val inspection = UseExpressionBodyInspection(convertEmptyToUnit = false) if (!inspection.isActiveFor(element)) return null return { if (inspection.isActiveFor(element)) { inspection.simplify(element, false) } } } } private class RemoveRedundantCastToNullableProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtBinaryExpressionWithTypeRHS) return null val context = element.analyze() val leftType = context.getType(element.left) ?: return null val rightType = context.get(BindingContext.TYPE, element.right) ?: return null if (!leftType.isMarkedNullable && rightType.isMarkedNullable) { return { val type = element.right?.typeElement as? KtNullableType type?.replace(type.innerType!!) } } return null } } private class FixObjectStringConcatenationProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtBinaryExpression || element.operationToken != KtTokens.PLUS || diagnostics.forElement(element.operationReference).none { it.factory == Errors.UNRESOLVED_REFERENCE_WRONG_RECEIVER || it.factory == Errors.NONE_APPLICABLE } ) return null val bindingContext = element.analyze() val rightType = element.right?.getType(bindingContext) ?: return null if (KotlinBuiltIns.isString(rightType)) { return { val factory = KtPsiFactory(element) element.left!!.replace(factory.buildExpression { appendFixedText("(") appendExpression(element.left) appendFixedText(").toString()") }) } } return null } } private class UninitializedVariableReferenceFromInitializerToThisReferenceProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtSimpleNameExpression || diagnostics.forElement(element) .none { it.factory == Errors.UNINITIALIZED_VARIABLE } ) return null val resolved = element.mainReference.resolve() ?: return null if (resolved.isAncestor(element, strict = true)) { if (resolved is KtVariableDeclaration && resolved.hasInitializer()) { val anonymousObject = element.getParentOfType<KtClassOrObject>(true) ?: return null if (resolved.initializer!!.getChildOfType<KtClassOrObject>() == anonymousObject) { return { element.replaced(KtPsiFactory(element).createThisExpression()) } } } } return null } } private class UnresolvedVariableReferenceFromInitializerToThisReferenceProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtSimpleNameExpression || diagnostics.forElement(element) .none { it.factory == Errors.UNRESOLVED_REFERENCE } ) return null val anonymousObject = element.getParentOfType<KtClassOrObject>(true) ?: return null val variable = anonymousObject.getParentOfType<KtVariableDeclaration>(true) ?: return null if (variable.nameAsName == element.getReferencedNameAsName() && variable.initializer?.getChildOfType<KtClassOrObject>() == anonymousObject ) { return { element.replaced(KtPsiFactory(element).createThisExpression()) } } return null } } }
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/implement/inner.kt
4
193
// "Implement abstract class" "true" // WITH_RUNTIME // SHOULD_BE_AVAILABLE_AFTER_EXECUTION class Container { inner abstract class <caret>Base { abstract fun foo(): String } }
apache-2.0
rei-m/HBFav_material
app/src/main/kotlin/me/rei_m/hbfavmaterial/viewmodel/widget/fragment/di/HotEntryFragmentViewModelModule.kt
1
1124
/* * Copyright (c) 2017. Rei Matsushita * * 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 me.rei_m.hbfavmaterial.viewmodel.widget.fragment.di import dagger.Module import dagger.Provides import me.rei_m.hbfavmaterial.di.ForFragment import me.rei_m.hbfavmaterial.model.HotEntryModel import me.rei_m.hbfavmaterial.viewmodel.widget.fragment.HotEntryFragmentViewModel @Module class HotEntryFragmentViewModelModule { @Provides @ForFragment internal fun provideViewModelFactory(hotEntryModel: HotEntryModel): HotEntryFragmentViewModel.Factory = HotEntryFragmentViewModel.Factory(hotEntryModel) }
apache-2.0
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/model/alerts/StorageFailureAlert.kt
2
469
package com.github.kerubistan.kerub.model.alerts import com.fasterxml.jackson.annotation.JsonTypeName import java.util.UUID @JsonTypeName("storage-failure-alert") data class StorageFailureAlert( override val id: UUID, override val created: Long, override val resolved: Long?, override val open: Boolean, val hostId: UUID, val storageDevice: String, val deviceId: String?, val hotSwap: Boolean? ) : VirtualResourceAlert { init { this.validate() } }
apache-2.0
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/config/MaterialNoteConfig.kt
1
2350
package com.maubis.scarlet.base.config import android.content.Context import androidx.appcompat.app.AppCompatActivity import com.maubis.scarlet.base.config.auth.IAuthenticator import com.maubis.scarlet.base.config.auth.NullAuthenticator import com.maubis.scarlet.base.config.remote.IRemoteConfigFetcher import com.maubis.scarlet.base.config.remote.NullRemoteConfigFetcher import com.maubis.scarlet.base.core.folder.IFolderActor import com.maubis.scarlet.base.core.folder.MaterialFolderActor import com.maubis.scarlet.base.core.note.INoteActor import com.maubis.scarlet.base.core.note.MaterialNoteActor import com.maubis.scarlet.base.core.tag.ITagActor import com.maubis.scarlet.base.core.tag.MaterialTagActor import com.maubis.scarlet.base.database.FoldersProvider import com.maubis.scarlet.base.database.NotesProvider import com.maubis.scarlet.base.database.TagsProvider import com.maubis.scarlet.base.database.remote.IRemoteDatabaseState import com.maubis.scarlet.base.database.room.AppDatabase import com.maubis.scarlet.base.database.room.folder.Folder import com.maubis.scarlet.base.database.room.note.Note import com.maubis.scarlet.base.database.room.tag.Tag open class MaterialNoteConfig(context: Context) : CoreConfig() { val db = AppDatabase.createDatabase(context) val notesProvider = NotesProvider() val tagsProvider = TagsProvider() val foldersProvider = FoldersProvider() override fun database(): AppDatabase = db override fun authenticator(): IAuthenticator = NullAuthenticator() override fun notesDatabase(): NotesProvider = notesProvider override fun tagsDatabase(): TagsProvider = tagsProvider override fun noteActions(note: Note): INoteActor = MaterialNoteActor(note) override fun tagActions(tag: Tag): ITagActor = MaterialTagActor(tag) override fun foldersDatabase(): FoldersProvider = foldersProvider override fun folderActions(folder: Folder): IFolderActor = MaterialFolderActor(folder) override fun remoteConfigFetcher(): IRemoteConfigFetcher = NullRemoteConfigFetcher() override fun remoteDatabaseState(): IRemoteDatabaseState { return object : IRemoteDatabaseState { override fun notifyInsert(data: Any, onExecution: () -> Unit) {} override fun notifyRemove(data: Any, onExecution: () -> Unit) {} } } override fun startListener(activity: AppCompatActivity) {} }
gpl-3.0
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddJvmNameAnnotationFix.kt
1
3474
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.core.NewDeclarationNameValidator import org.jetbrains.kotlin.idea.util.addAnnotation import org.jetbrains.kotlin.idea.util.findAnnotation import org.jetbrains.kotlin.psi.* class AddJvmNameAnnotationFix(element: KtElement, private val jvmName: String) : KotlinQuickFixAction<KtElement>(element) { override fun getText(): String = if (element is KtAnnotationEntry) { KotlinBundle.message("fix.change.jvm.name") } else { KotlinBundle.message("fix.add.annotation.text.self", JvmFileClassUtil.JVM_NAME.shortName()) } override fun getFamilyName(): String = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return when (element) { is KtAnnotationEntry -> { val argList = element.valueArgumentList val newArgList = KtPsiFactory(element).createCallArguments("(\"$jvmName\")") if (argList != null) { argList.replace(newArgList) } else { element.addAfter(newArgList, element.lastChild) } } is KtFunction -> element.addAnnotation(JvmFileClassUtil.JVM_NAME, annotationInnerText = "\"$jvmName\"") } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val function = diagnostic.psiElement as? KtNamedFunction ?: return null val functionName = function.name ?: return null val containingDeclaration = function.parent ?: return null val nameValidator = NewDeclarationNameValidator( containingDeclaration, function, NewDeclarationNameValidator.Target.FUNCTIONS_AND_CLASSES ) val receiverTypeElements = function.receiverTypeReference?.typeElements()?.joinToString("") { it.text } ?: "" val jvmName = KotlinNameSuggester.suggestNameByName(functionName + receiverTypeElements, nameValidator) return AddJvmNameAnnotationFix(function.findAnnotation(JvmFileClassUtil.JVM_NAME) ?: function, jvmName) } private fun KtTypeReference.typeElements(): List<KtTypeElement> { val typeElements = mutableListOf<KtTypeElement>() fun collect(typeReference: KtTypeReference?) { val typeElement = typeReference?.typeElement ?: return val typeArguments = typeElement.typeArgumentsAsTypes if (typeArguments.isEmpty()) { typeElements.add(typeElement) } else { typeArguments.forEach { collect(it) } } } typeElement?.typeArgumentsAsTypes?.forEach { collect(it) } return typeElements } } }
apache-2.0
androidx/androidx
graphics/graphics-core/src/main/java/androidx/graphics/opengl/GLRenderer.kt
3
32918
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.graphics.opengl import android.graphics.SurfaceTexture import android.opengl.EGL14 import android.opengl.EGLConfig import android.opengl.EGLSurface import android.view.Surface import android.view.SurfaceHolder import android.view.SurfaceView import android.view.TextureView import androidx.annotation.WorkerThread import androidx.graphics.opengl.egl.EGLConfigAttributes import androidx.graphics.opengl.egl.EGLManager import androidx.graphics.opengl.egl.EGLSpec import java.util.concurrent.CountDownLatch import java.util.concurrent.atomic.AtomicInteger /** * Class responsible for coordination of requests to render into surfaces using OpenGL. * This creates a backing thread to handle EGL dependencies and draw leveraging OpenGL across * multiple [android.view.Surface] instances that can be attached and detached throughout * the lifecycle of an application. Usage of this class is recommended to be done on the UI thread. * * @param eglSpecFactory Callback invoked to determine the EGL spec version to use * for EGL management. This is invoked on the GL Thread * @param eglConfigFactory Callback invoked to determine the appropriate EGLConfig used * to create the EGL context. This is invoked on the GL Thread */ // GL is the industry standard for referencing OpenGL vs Gl (lowercase l) @Suppress("AcronymName") class GLRenderer( eglSpecFactory: () -> EGLSpec = { EGLSpec.V14 }, eglConfigFactory: EGLManager.() -> EGLConfig = { // 8 bit channels should always be supported loadConfig(EGLConfigAttributes.RGBA_8888) ?: throw IllegalStateException("Unable to obtain config for 8 bit EGL " + "configuration") } ) { /** * Factory method to determine which [EGLSpec] the underlying [EGLManager] implementation uses */ private val mEglSpecFactory: () -> EGLSpec = eglSpecFactory /** * Factory method used to create the corresponding EGLConfig used to create the EGLRenderer used * by [EGLManager] */ private val mEglConfigFactory: EGLManager.() -> EGLConfig = eglConfigFactory /** * GLThread used to manage EGL dependencies, create EGLSurfaces and draw content */ private var mGLThread: GLThread? = null /** * Collection of [RenderTarget] instances that are managed by the GLRenderer */ private val mRenderTargets = ArrayList<RenderTarget>() /** * Collection of callbacks to be invoked when the EGL dependencies are initialized * or torn down */ private val mEglContextCallback = HashSet<EGLContextCallback>() /** * Removes the corresponding [RenderTarget] from management of the GLThread. * This destroys the EGLSurface associated with this surface and subsequent requests * to render into the surface with the provided token are ignored. * * If the [cancelPending] flag is set to true, any queued request * to render that has not started yet is cancelled. However, if this is invoked in the * middle of the frame being rendered, it will continue to process the current frame. * * Additionally if this flag is false, all pending requests to render will be processed * before the [RenderTarget] is detached. * * Note the detach operation will only occur if the GLRenderer is started, that is if * [isRunning] returns true. Otherwise this is a no-op. GLRenderer will automatically detach all * [RenderTarget] instances as part of its teardown process. */ @JvmOverloads fun detach( target: RenderTarget, cancelPending: Boolean, @WorkerThread onDetachComplete: ((RenderTarget) -> Unit)? = null ) { if (mRenderTargets.contains(target)) { mGLThread?.detachSurface(target.token, cancelPending) { // WorkerThread target.release() target.onDetach.invoke() onDetachComplete?.invoke(target) } mRenderTargets.remove(target) } } /** * Determines if the GLThread has been started. That is [start] has been invoked * on this GLRenderer instance without a corresponding call to [stop]. */ fun isRunning(): Boolean = mGLThread != null /** * Starts the GLThread. After this method is called, consumers can attempt * to attach [android.view.Surface] instances through [attach] as well as * schedule content to be drawn through [requestRender] * * @param name Optional name to provide to the GLThread * * @throws IllegalStateException if EGLConfig with desired attributes cannot be created */ @JvmOverloads fun start( name: String = "GLThread", ) { if (mGLThread == null) { GLThread.log("starting thread...") mGLThread = GLThread( name, mEglSpecFactory, mEglConfigFactory ).apply { start() if (!mEglContextCallback.isEmpty()) { // Add a copy of the current collection as new entries to mEglContextCallback // could be mistakenly added multiple times. this.addEGLCallbacks(ArrayList<EGLContextCallback>(mEglContextCallback)) } } } } /** * Mark the corresponding surface session with the given token as dirty * to schedule a call to [RenderCallback#onDrawFrame]. * If there is already a queued request to render into the provided surface with * the specified token, this request is ignored. * * Note the render operation will only occur if the GLRenderer is started, that is if * [isRunning] returns true. Otherwise this is a no-op. * * @param target RenderTarget to be re-rendered * @param onRenderComplete Optional callback invoked on the backing thread after the frame has * been rendered. */ @JvmOverloads fun requestRender(target: RenderTarget, onRenderComplete: ((RenderTarget) -> Unit)? = null) { val token = target.token val callbackRunnable = if (onRenderComplete != null) { Runnable { onRenderComplete.invoke(target) } } else { null } mGLThread?.requestRender(token, callbackRunnable) } /** * Resize the corresponding surface associated with the RenderTarget to the specified * width and height and re-render. This will destroy the EGLSurface created by * [RenderCallback.onSurfaceCreated] and invoke it again with the updated dimensions. * An optional callback is invoked on the backing thread after the resize operation * is complete. * * Note the resize operation will only occur if the GLRenderer is started, that is if * [isRunning] returns true. Otherwise this is a no-op. * * @param target RenderTarget to be resized * @param width Updated width of the corresponding surface * @param height Updated height of the corresponding surface * @param onResizeComplete Optional callback invoked on the backing thread when the resize * operation is complete */ @JvmOverloads fun resize( target: RenderTarget, width: Int, height: Int, onResizeComplete: ((RenderTarget) -> Unit)? = null ) { val token = target.token val callbackRunnable = if (onResizeComplete != null) { Runnable { onResizeComplete.invoke(target) } } else { null } mGLThread?.resizeSurface(token, width, height, callbackRunnable) } /** * Stop the corresponding GL thread. This destroys all EGLSurfaces as well * as any other EGL dependencies. All queued requests that have not been processed * yet are cancelled. * * Note the stop operation will only occur if the GLRenderer was previously started, that is * [isRunning] returns true. Otherwise this is a no-op. * * @param cancelPending If true all pending requests and cancelled and the backing thread is * torn down immediately. If false, all pending requests are processed first before tearing * down the backing thread. Subsequent requests made after this call are ignored. * @param onStop Optional callback invoked on the backing thread after it is torn down. */ @JvmOverloads fun stop(cancelPending: Boolean, onStop: ((GLRenderer) -> Unit)? = null) { GLThread.log("stopping thread...") // Make a copy of the render targets to call cleanup operations on to avoid potential // concurrency issues. // This method will clear the existing collection and we do not want to potentially tear // down a target that was attached after a subsequent call to start if the tear down // callback execution is delayed if previously pending requests have not been cancelled // (i.e. cancelPending is false) val renderTargets = ArrayList(mRenderTargets) mGLThread?.tearDown(cancelPending) { // No need to call target.detach as this callback is invoked after // the dependencies are cleaned up for (target in renderTargets) { target.release() target.onDetach.invoke() } onStop?.invoke(this@GLRenderer) } mGLThread = null mRenderTargets.clear() } /** * Add an [EGLContextCallback] to receive callbacks for construction and * destruction of EGL dependencies. * * These callbacks are invoked on the backing thread. */ @Suppress("AcronymName") fun registerEGLContextCallback(callback: EGLContextCallback) { mEglContextCallback.add(callback) mGLThread?.addEGLCallback(callback) } /** * Remove [EGLContextCallback] to no longer receive callbacks for construction and * destruction of EGL dependencies. * * These callbacks are invoked on the backing thread */ @Suppress("AcronymName") fun unregisterEGLContextCallback(callback: EGLContextCallback) { mEglContextCallback.remove(callback) mGLThread?.removeEGLCallback(callback) } /** * Callbacks invoked when the GL dependencies are created and destroyed. * These are logical places to setup and tear down any dependencies that are used * for drawing content within a frame (ex. compiling shaders) */ @Suppress("AcronymName") interface EGLContextCallback { /** * Callback invoked on the backing thread after EGL dependencies are initialized. * This is guaranteed to be invoked before any instance of * [RenderCallback.onSurfaceCreated] is called. * This will be invoked lazily before the first request to [GLRenderer.requestRender] */ // Suppressing CallbackMethodName due to b/238939160 @Suppress("AcronymName", "CallbackMethodName") @WorkerThread fun onEGLContextCreated(eglManager: EGLManager) /** * Callback invoked on the backing thread before EGL dependencies are about to be torn down. * This is invoked after [GLRenderer.stop] is processed. */ // Suppressing CallbackMethodName due to b/238939160 @Suppress("AcronymName", "CallbackMethodName") @WorkerThread fun onEGLContextDestroyed(eglManager: EGLManager) } @JvmDefaultWithCompatibility /** * Interface used for creating an [EGLSurface] with a user defined configuration * from the provided surface as well as a callback used to render content into the surface * for a given frame */ interface RenderCallback { /** * Used to create a corresponding [EGLSurface] from the provided * [android.view.Surface] instance. This enables consumers to configure * the corresponding [EGLSurface] they wish to render into. * The [EGLSurface] created here is guaranteed to be the current surface * before [onDrawFrame] is called. That is, implementations of onDrawFrame * do not need to call eglMakeCurrent on this [EGLSurface]. * * This method is invoked on the GL thread. * * The default implementation will create a window surface with EGL_WIDTH and EGL_HEIGHT * set to [width] and [height] respectively. * Implementations can override this method to provide additional [EGLConfigAttributes] * for this surface (ex. [EGL14.EGL_SINGLE_BUFFER]. * * Implementations can return null to indicate the default surface should be used. * This is helpful in situations where content is to be rendered within a frame buffer * object instead of to an [EGLSurface] * * @param spec EGLSpec used to create the corresponding EGLSurface * @param config EGLConfig used to create the corresponding EGLSurface * @param surface [android.view.Surface] used to create an EGLSurface from * @param width Desired width of the surface to create * @param height Desired height of the surface to create */ @WorkerThread fun onSurfaceCreated( spec: EGLSpec, config: EGLConfig, surface: Surface, width: Int, height: Int ): EGLSurface? = // Always default to creating an EGL window surface // Despite having access to the width and height here, do not explicitly // pass in EGLConfigAttributes specifying the EGL_WIDTH and EGL_HEIGHT parameters // as those are not accepted parameters for eglCreateWindowSurface but they are // for other EGL Surface factory methods such as eglCreatePBufferSurface // See accepted parameters here: // https://www.khronos.org/registry/EGL/sdk/docs/man/html/eglCreateWindowSurface.xhtml // and here // https://www.khronos.org/registry/EGL/sdk/docs/man/html/eglCreatePbufferSurface.xhtml spec.eglCreateWindowSurface(config, surface, null) /** * Callback used to issue OpenGL drawing commands into the [EGLSurface] * created in [onSurfaceCreated]. This [EGLSurface] is guaranteed to * be current before this callback is invoked and [EGLManager.swapAndFlushBuffers] * will be invoked afterwards. If additional scratch [EGLSurface]s are used * here it is up to the implementation of this method to ensure that the proper * surfaces are made current and the appropriate swap buffers call is made * * This method is invoked on the backing thread * * @param eglManager Handle to EGL dependencies */ @WorkerThread fun onDrawFrame(eglManager: EGLManager) } /** * Adds the [android.view.Surface] to be managed by the GLThread. * A corresponding [EGLSurface] is created on the GLThread as well as a callback * for rendering into the surface through [RenderCallback]. * Unlike the other [attach] methods that consume a [SurfaceView] or [TextureView], * this method does not handle any lifecycle callbacks associated with the target surface. * Therefore it is up to the consumer to properly setup/teardown resources associated with * this surface. * * @param surface Target surface to be managed by the backing thread * @param width Desired width of the [surface] * @param height Desired height of the [surface] * @param renderer Callbacks used to create a corresponding [EGLSurface] from the * given surface as well as render content into the created [EGLSurface] * @return [RenderTarget] used for subsequent requests to communicate * with the provided Surface (ex. [requestRender] or [detach]). * * @throws IllegalStateException If this method was called when the GLThread has not started * (i.e. start has not been called) */ fun attach(surface: Surface, width: Int, height: Int, renderer: RenderCallback): RenderTarget { val thread = mGLThread if (thread != null) { val token = sToken.getAndIncrement() thread.attachSurface(token, surface, width, height, renderer) return RenderTarget(token, this).also { mRenderTargets.add(it) } } else { throw IllegalStateException("GLThread not started, did you forget to call start?") } } /** * Creates a new [RenderTarget] without a corresponding [android.view.Surface]. * This avoids creation of an [EGLSurface] which is useful in scenarios where only * rendering to a frame buffer object is required. * * @param width Desired width of the [RenderTarget] * @param height Desired height of the [RenderTarget] * @param renderer Callbacks used to issue OpenGL commands to the [RenderTarget] * @return [RenderTarget] used for subsequent requests to render through * [RenderTarget.requestRender] or to remove itself from the [GLRenderer] through * [RenderTarget.detach] * * @throws IllegalStateException If this method was called when the GLThread has not started * (i.e. start has not been called) */ fun createRenderTarget(width: Int, height: Int, renderer: RenderCallback): RenderTarget { val thread = mGLThread if (thread != null) { val token = sToken.getAndIncrement() thread.attachSurface( token, null, width, height, renderer ) return RenderTarget(token, this).also { mRenderTargets.add(it) } } else { throw IllegalStateException("GLThread not started, did you forget to call start?") } } /** * Adds the [android.view.Surface] provided by the given [SurfaceView] to be managed by the * backing thread. * * A corresponding [EGLSurface] is created on the GLThread as well as a callback * for rendering into the surface through [RenderCallback]. * * This method automatically configures a [SurfaceHolder.Callback] used to attach the * [android.view.Surface] when the underlying [SurfaceHolder] that contains the surface is * available. Similarly this surface will be detached from [GLRenderer] when the surface provided * by the [SurfaceView] is destroyed (i.e. [SurfaceHolder.Callback.surfaceDestroyed] is called. * * If the [android.view.Surface] is already available by the time this method is invoked, * it is attached synchronously. * * @param surfaceView SurfaceView that provides the surface to be rendered by the backing thread * @param renderer callbacks used to create a corresponding [EGLSurface] from the * given surface as well as render content into the created [EGLSurface] * @return [RenderTarget] used for subsequent requests to communicate * with the provided Surface (ex. [requestRender] or [detach]). * * @throws IllegalStateException If this method was called when the GLThread has not started * (i.e. start has not been called) */ fun attach(surfaceView: SurfaceView, renderer: RenderCallback): RenderTarget { val thread = mGLThread if (thread != null) { val token = sToken.getAndIncrement() val holder = surfaceView.holder val callback = object : SurfaceHolder.Callback2 { var isAttached = false /** * Optional condition that maybe used if we are issuing a blocking call to render * in [SurfaceHolder.Callback2.surfaceRedrawNeeded] * In this case we need to signal the condition of either the request to render * has completed, or if the RenderTarget has been detached and the pending * render request is cancelled. */ @Volatile var renderLatch: CountDownLatch? = null /** * [CountDownLatch] used when issuing a blocking call to * [SurfaceHolder.Callback.surfaceDestroyed] * In this case we need to signal the condition of either the request to detach * has completed in case the GLRenderer has been forcefully stopped via * [GLRenderer.stop] with the cancel pending flag set to true. */ val detachLatch: CountDownLatch = CountDownLatch(1) val renderTarget = RenderTarget(token, this@GLRenderer) @WorkerThread { isAttached = false // SurfaceHolder.add/remove callback is thread safe holder.removeCallback(this) // Countdown in case we have been detached while waiting for a render // to be completed renderLatch?.countDown() detachLatch.countDown() } override fun surfaceRedrawNeeded(p0: SurfaceHolder) { // If the [RenderTarget] has already been detached then skip rendering if (detachLatch.count > 0) { val latch = CountDownLatch(1).also { renderLatch = it } // Request a render and block until the rendering is complete // surfaceRedrawNeeded is invoked on older API levels and is replaced with // surfaceRedrawNeededAsync for newer API levels which is non-blocking renderTarget.requestRender @WorkerThread { latch.countDown() } latch.await() renderLatch = null } } override fun surfaceRedrawNeededAsync( holder: SurfaceHolder, drawingFinished: Runnable ) { renderTarget.requestRender { drawingFinished.run() } } override fun surfaceCreated(holder: SurfaceHolder) { // NO-OP wait until surfaceChanged which is guaranteed to be called and also // provides the appropriate width height of the surface } override fun surfaceChanged( holder: SurfaceHolder, format: Int, width: Int, height: Int ) { if (!isAttached) { thread.attachSurface(token, holder.surface, width, height, renderer) isAttached = true } else { renderTarget.resize(width, height) } renderTarget.requestRender() } override fun surfaceDestroyed(holder: SurfaceHolder) { // Issue a request to detech the [RenderTarget]. Even if it was // previously detached this request is a no-op and the corresponding // [CountDownLatch] will signal when the [RenderTarget] detachment is complete // or instantaneously if it was already detached renderTarget.detach(true) detachLatch.await() } } holder.addCallback(callback) if (holder.surface != null && holder.surface.isValid) { thread.attachSurface( token, holder.surface, surfaceView.width, surfaceView.height, renderer ) } mRenderTargets.add(callback.renderTarget) return callback.renderTarget } else { throw IllegalStateException("GLThread not started, did you forget to call start?") } } /** * Adds the [android.view.Surface] provided by the given [TextureView] to be managed by the * backing thread. * * A corresponding [EGLSurface] is created on the GLThread as well as a callback * for rendering into the surface through [RenderCallback]. * * This method automatically configures a [TextureView.SurfaceTextureListener] used to create a * [android.view.Surface] when the underlying [SurfaceTexture] is available. * Similarly this surface will be detached from [GLRenderer] if the underlying [SurfaceTexture] * is destroyed (i.e. [TextureView.SurfaceTextureListener.onSurfaceTextureDestroyed] is called. * * If the [SurfaceTexture] is already available by the time this method is called, then it is * attached synchronously. * * @param textureView TextureView that provides the surface to be rendered into on the GLThread * @param renderer callbacks used to create a corresponding [EGLSurface] from the * given surface as well as render content into the created [EGLSurface] * @return [RenderTarget] used for subsequent requests to communicate * with the provided Surface (ex. [requestRender] or [detach]). * * @throws IllegalStateException If this method was called when the GLThread has not started * (i.e. start has not been called) */ fun attach(textureView: TextureView, renderer: RenderCallback): RenderTarget { val thread = mGLThread if (thread != null) { val token = sToken.getAndIncrement() val detachLatch = CountDownLatch(1) val renderTarget = RenderTarget(token, this) @WorkerThread { textureView.handler?.post { textureView.surfaceTextureListener = null } detachLatch.countDown() } textureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener { override fun onSurfaceTextureAvailable( surfaceTexture: SurfaceTexture, width: Int, height: Int ) { thread.attachSurface(token, Surface(surfaceTexture), width, height, renderer) } override fun onSurfaceTextureSizeChanged( texture: SurfaceTexture, width: Int, height: Int ) { renderTarget.resize(width, height) renderTarget.requestRender() } override fun onSurfaceTextureDestroyed(p0: SurfaceTexture): Boolean { // Issue a request to detech the [RenderTarget]. Even if it was // previously detached this request is a no-op and the corresponding // [CountDownLatch] will signal when the [RenderTarget] detachment is complete // or instantaneously if it was already detached renderTarget.detach(true) detachLatch.await() return true } override fun onSurfaceTextureUpdated(p0: SurfaceTexture) { // NO-OP } } if (textureView.isAvailable) { thread.attachSurface( token, Surface(textureView.surfaceTexture), textureView.width, textureView.height, renderer ) } mRenderTargets.add(renderTarget) return renderTarget } else { throw IllegalStateException("GLThread not started, did you forget to call start?") } } /** * Handle to a [android.view.Surface] that is given to [GLRenderer] to handle * rendering. */ class RenderTarget internal constructor( internal val token: Int, glManager: GLRenderer, @WorkerThread internal val onDetach: () -> Unit = {} ) { @Volatile private var mManager: GLRenderer? = glManager internal fun release() { mManager = null } /** * Request that this [RenderTarget] should have its contents redrawn. * This consumes an optional callback that is invoked on the backing thread when * the rendering is completed. * * Note the render operation will only occur if the RenderTarget is attached, that is * [isAttached] returns true. If the [RenderTarget] is detached or the [GLRenderer] that * created this RenderTarget is stopped, this is a no-op. * * @param onRenderComplete Optional callback called on the backing thread when * rendering is finished */ @JvmOverloads fun requestRender(@WorkerThread onRenderComplete: ((RenderTarget) -> Unit)? = null) { mManager?.requestRender(this@RenderTarget, onRenderComplete) } /** * Determines if the current RenderTarget is attached to GLRenderer. * This is true until [detach] has been called. If the RenderTarget is no longer * in an attached state (i.e. this returns false). Subsequent calls to [requestRender] * will be ignored. */ fun isAttached(): Boolean = mManager != null /** * Resize the RenderTarget to the specified width and height. * This will destroy the EGLSurface created by [RenderCallback.onSurfaceCreated] * and invoke it again with the updated dimensions. * An optional callback is invoked on the backing thread after the resize operation * is complete * * Note the resize operation will only occur if the RenderTarget is attached, that is * [isAttached] returns true. If the [RenderTarget] is detached or the [GLRenderer] that * created this RenderTarget is stopped, this is a no-op. * * @param width New target width to resize the RenderTarget * @param height New target height to resize the RenderTarget * @param onResizeComplete Optional callback invoked after the resize is complete */ @JvmOverloads fun resize( width: Int, height: Int, @WorkerThread onResizeComplete: ((RenderTarget) -> Unit)? = null ) { mManager?.resize(this, width, height, onResizeComplete) } /** * Removes the corresponding [RenderTarget] from management of the GLThread. * This destroys the EGLSurface associated with this surface and subsequent requests * to render into the surface with the provided token are ignored. * * If the [cancelPending] flag is set to true, any queued request * to render that has not started yet is cancelled. However, if this is invoked in the * middle of the frame being rendered, it will continue to process the current frame. * * Additionally if this flag is false, all pending requests to render will be processed * before the [RenderTarget] is detached. * * This is a convenience method around [GLRenderer.detach] * * Note the detach operation will only occur if the RenderTarget is attached, that is * [isAttached] returns true. If the [RenderTarget] is detached or the [GLRenderer] that * created this RenderTarget is stopped, this is a no-op. */ @JvmOverloads fun detach(cancelPending: Boolean, onDetachComplete: ((RenderTarget) -> Unit)? = null) { mManager?.detach(this, cancelPending, onDetachComplete) } } companion object { /** * Counter used to issue unique identifiers for surfaces that are managed by GLRenderer */ private val sToken = AtomicInteger() } }
apache-2.0
androidx/androidx
navigation/navigation-dynamic-features-runtime/src/main/java/androidx/navigation/dynamicfeatures/DynamicInstallManager.kt
3
7696
/* * Copyright 2019 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.navigation.dynamicfeatures import android.content.Context import android.os.Bundle import android.util.Log import androidx.annotation.RestrictTo import androidx.lifecycle.MutableLiveData import androidx.navigation.NavBackStackEntry import androidx.navigation.NavDestination import androidx.navigation.Navigator import androidx.navigation.dynamicfeatures.DynamicGraphNavigator.DynamicNavGraph import androidx.navigation.get import com.google.android.play.core.splitcompat.SplitCompat import com.google.android.play.core.splitinstall.SplitInstallException import com.google.android.play.core.splitinstall.SplitInstallHelper import com.google.android.play.core.splitinstall.SplitInstallManager import com.google.android.play.core.splitinstall.SplitInstallRequest import com.google.android.play.core.splitinstall.SplitInstallSessionState import com.google.android.play.core.splitinstall.SplitInstallStateUpdatedListener import com.google.android.play.core.splitinstall.model.SplitInstallErrorCode import com.google.android.play.core.splitinstall.model.SplitInstallSessionStatus /** * Install manager for dynamic features. * * Enables installation of dynamic features for both installed and instant apps. */ public open class DynamicInstallManager( private val context: Context, private val splitInstallManager: SplitInstallManager ) { internal companion object { internal fun terminateLiveData( status: MutableLiveData<SplitInstallSessionState> ) { // Best effort leak prevention, will only work for active observers check(!status.hasActiveObservers()) { "This DynamicInstallMonitor will not " + "emit any more status updates. You should remove all " + "Observers after null has been emitted." } } } /** * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public fun performInstall( backStackEntry: NavBackStackEntry, extras: DynamicExtras?, moduleName: String ): NavDestination? { if (extras?.installMonitor != null) { requestInstall(moduleName, extras.installMonitor) return null } else { val progressArgs = Bundle().apply { putInt(Constants.DESTINATION_ID, backStackEntry.destination.id) putBundle(Constants.DESTINATION_ARGS, backStackEntry.arguments) } val dynamicNavGraph = DynamicNavGraph.getOrThrow(backStackEntry.destination) val navigator: Navigator<*> = dynamicNavGraph.navigatorProvider[dynamicNavGraph.navigatorName] if (navigator is DynamicGraphNavigator) { navigator.navigateToProgressDestination(dynamicNavGraph, progressArgs) return null } else { throw IllegalStateException( "You must use a DynamicNavGraph to perform a module installation." ) } } } /** * @param module The module to install. * @return Whether the requested module needs installation. * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public fun needsInstall(module: String): Boolean { return !splitInstallManager.installedModules.contains(module) } private fun requestInstall( module: String, installMonitor: DynamicInstallMonitor ) { check(!installMonitor.isUsed) { // We don't want an installMonitor in an undefined state or used by another install "You must pass in a fresh DynamicInstallMonitor " + "in DynamicExtras every time you call navigate()." } val status = installMonitor.status as MutableLiveData<SplitInstallSessionState> installMonitor.isInstallRequired = true val request = SplitInstallRequest .newBuilder() .addModule(module) .build() splitInstallManager .startInstall(request) .addOnSuccessListener { sessionId -> installMonitor.sessionId = sessionId installMonitor.splitInstallManager = splitInstallManager if (sessionId == 0) { // The feature is already installed, emit synthetic INSTALLED state. status.value = SplitInstallSessionState.create( sessionId, SplitInstallSessionStatus.INSTALLED, SplitInstallErrorCode.NO_ERROR, /* bytesDownloaded */ 0, /* totalBytesToDownload */ 0, listOf(module), emptyList() ) terminateLiveData(status) } else { val listener = SplitInstallListenerWrapper( context, status, installMonitor ) splitInstallManager.registerListener(listener) } } .addOnFailureListener { exception -> Log.i( "DynamicInstallManager", "Error requesting install of $module: ${exception.message}" ) installMonitor.exception = exception status.value = SplitInstallSessionState.create( /* sessionId */ 0, SplitInstallSessionStatus.FAILED, if (exception is SplitInstallException) exception.errorCode else SplitInstallErrorCode.INTERNAL_ERROR, /* bytesDownloaded */ 0, /* totalBytesToDownload */ 0, listOf(module), emptyList() ) terminateLiveData(status) } } private class SplitInstallListenerWrapper( private val context: Context, private val status: MutableLiveData<SplitInstallSessionState>, private val installMonitor: DynamicInstallMonitor ) : SplitInstallStateUpdatedListener { override fun onStateUpdate( splitInstallSessionState: SplitInstallSessionState ) { if (splitInstallSessionState.sessionId() == installMonitor.sessionId) { if (splitInstallSessionState.status() == SplitInstallSessionStatus.INSTALLED) { SplitCompat.install(context) // Enable immediate usage of dynamic feature modules in an instant app context. SplitInstallHelper.updateAppInfo(context) } status.value = splitInstallSessionState if (splitInstallSessionState.hasTerminalStatus()) { installMonitor.splitInstallManager!!.unregisterListener(this) terminateLiveData(status) } } } } }
apache-2.0
stoyicker/dinger
domain/src/main/kotlin/domain/dislike/DislikeRecommendationUseCase.kt
1
610
package domain.dislike import domain.interactor.SingleDisposableUseCase import domain.recommendation.DomainRecommendationUser import io.reactivex.Scheduler import io.reactivex.Single class DislikeRecommendationUseCase( private val recommendation: DomainRecommendationUser, postExecutionScheduler: Scheduler) : SingleDisposableUseCase<DomainDislikedRecommendationAnswer>( postExecutionScheduler = postExecutionScheduler) { override fun buildUseCase(): Single<DomainDislikedRecommendationAnswer> = DislikeRecommendationHolder.dislikeRecommendation.dislikeRecommendation(recommendation) }
mit
SimpleMobileTools/Simple-Notes
app/src/main/kotlin/com/simplemobiletools/notes/pro/interfaces/ChecklistItemsListener.kt
1
137
package com.simplemobiletools.notes.pro.interfaces interface ChecklistItemsListener { fun refreshItems() fun saveChecklist() }
gpl-3.0
androidx/androidx
compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/platform/PlatformParagraph.kt
3
2639
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.platform import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.Paragraph import androidx.compose.ui.text.ParagraphIntrinsics import androidx.compose.ui.text.Placeholder import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density @Suppress("DEPRECATION") @Deprecated( "Font.ResourceLoader is deprecated, instead pass FontFamily.Resolver", replaceWith = ReplaceWith("ActualParagraph(text, style, spanStyles, placeholders, " + "maxLines, ellipsis, width, density, fontFamilyResolver)"), ) // TODO(b/157854677): remove after fixing. internal expect fun ActualParagraph( text: String, style: TextStyle, spanStyles: List<AnnotatedString.Range<SpanStyle>>, placeholders: List<AnnotatedString.Range<Placeholder>>, maxLines: Int, ellipsis: Boolean, width: Float, density: Density, resourceLoader: Font.ResourceLoader ): Paragraph internal expect fun ActualParagraph( text: String, style: TextStyle, spanStyles: List<AnnotatedString.Range<SpanStyle>>, placeholders: List<AnnotatedString.Range<Placeholder>>, maxLines: Int, ellipsis: Boolean, constraints: Constraints, density: Density, fontFamilyResolver: FontFamily.Resolver ): Paragraph // TODO(b/157854677): remove after fixing. internal expect fun ActualParagraph( paragraphIntrinsics: ParagraphIntrinsics, maxLines: Int, ellipsis: Boolean, constraints: Constraints ): Paragraph // TODO(b/157854677): remove after fixing. internal expect fun ActualParagraphIntrinsics( text: String, style: TextStyle, spanStyles: List<AnnotatedString.Range<SpanStyle>>, placeholders: List<AnnotatedString.Range<Placeholder>>, density: Density, fontFamilyResolver: FontFamily.Resolver ): ParagraphIntrinsics
apache-2.0
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/staggeredgrid/LazyStaggeredGridState.kt
3
17677
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.lazy.staggeredgrid import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.gestures.ScrollScope import androidx.compose.foundation.gestures.ScrollableState import androidx.compose.foundation.interaction.InteractionSource import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.lazy.layout.LazyAnimateScrollScope import androidx.compose.foundation.lazy.layout.LazyLayoutItemProvider import androidx.compose.foundation.lazy.layout.LazyLayoutPrefetchState import androidx.compose.foundation.lazy.layout.LazyLayoutPrefetchState.PrefetchHandle import androidx.compose.foundation.lazy.layout.animateScrollToItem import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.layout.Remeasurement import androidx.compose.ui.layout.RemeasurementModifier import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import kotlin.math.abs /** * Creates a [LazyStaggeredGridState] that is remembered across composition. * * Calling this function with different parameters on recomposition WILL NOT recreate or change * the state. * Use [LazyStaggeredGridState.scrollToItem] or [LazyStaggeredGridState.animateScrollToItem] to * adjust position instead. * * @param initialFirstVisibleItemIndex initial position for * [LazyStaggeredGridState.firstVisibleItemIndex] * @param initialFirstVisibleItemScrollOffset initial value for * [LazyStaggeredGridState.firstVisibleItemScrollOffset] * @return created and memoized [LazyStaggeredGridState] with given parameters. */ @ExperimentalFoundationApi @Composable fun rememberLazyStaggeredGridState( initialFirstVisibleItemIndex: Int = 0, initialFirstVisibleItemScrollOffset: Int = 0 ): LazyStaggeredGridState = rememberSaveable(saver = LazyStaggeredGridState.Saver) { LazyStaggeredGridState( initialFirstVisibleItemIndex, initialFirstVisibleItemScrollOffset ) } /** * Hoisted state object controlling [LazyVerticalStaggeredGrid] or [LazyHorizontalStaggeredGrid]. * In most cases, it should be created via [rememberLazyStaggeredGridState]. */ @ExperimentalFoundationApi class LazyStaggeredGridState private constructor( initialFirstVisibleItems: IntArray, initialFirstVisibleOffsets: IntArray, ) : ScrollableState { /** * @param initialFirstVisibleItemIndex initial value for [firstVisibleItemIndex] * @param initialFirstVisibleItemOffset initial value for [firstVisibleItemScrollOffset] */ constructor( initialFirstVisibleItemIndex: Int = 0, initialFirstVisibleItemOffset: Int = 0 ) : this( intArrayOf(initialFirstVisibleItemIndex), intArrayOf(initialFirstVisibleItemOffset) ) /** * Index of the first visible item across all staggered grid lanes. * * This property is observable and when use it in composable function it will be recomposed on * each scroll, potentially causing performance issues. */ val firstVisibleItemIndex: Int get() = scrollPosition.indices.minOfOrNull { // index array can contain -1, indicating lane being empty (cell number > itemCount) // if any of the lanes are empty, we always on 0th item index if (it == -1) 0 else it } ?: 0 /** * Current offset of the item with [firstVisibleItemIndex] relative to the container start. * * This property is observable and when use it in composable function it will be recomposed on * each scroll, potentially causing performance issues. */ val firstVisibleItemScrollOffset: Int get() = scrollPosition.offsets.run { if (isEmpty()) 0 else this[scrollPosition.indices.indexOfMinValue()] } /** holder for current scroll position **/ internal val scrollPosition = LazyStaggeredGridScrollPosition( initialFirstVisibleItems, initialFirstVisibleOffsets, ::fillNearestIndices ) /** * Layout information calculated during last layout pass, with information about currently * visible items and container parameters. * * This property is observable and when use it in composable function it will be recomposed on * each scroll, potentially causing performance issues. */ val layoutInfo: LazyStaggeredGridLayoutInfo get() = layoutInfoState.value /** backing state for [layoutInfo] **/ private val layoutInfoState: MutableState<LazyStaggeredGridLayoutInfo> = mutableStateOf(EmptyLazyStaggeredGridLayoutInfo) /** storage for lane assignments for each item for consistent scrolling in both directions **/ internal val spans = LazyStaggeredGridSpans() override var canScrollForward: Boolean by mutableStateOf(false) private set override var canScrollBackward: Boolean by mutableStateOf(false) private set /** implementation of [LazyAnimateScrollScope] scope required for [animateScrollToItem] **/ private val animateScrollScope = LazyStaggeredGridAnimateScrollScope(this) private var remeasurement: Remeasurement? = null internal val remeasurementModifier = object : RemeasurementModifier { override fun onRemeasurementAvailable(remeasurement: Remeasurement) { [email protected] = remeasurement } } /** * Only used for testing to disable prefetching when needed to test the main logic. */ /*@VisibleForTesting*/ internal var prefetchingEnabled: Boolean = true /** prefetch state used for precomputing items in the direction of scroll **/ internal val prefetchState: LazyLayoutPrefetchState = LazyLayoutPrefetchState() /** state controlling the scroll **/ private val scrollableState = ScrollableState { -onScroll(-it) } /** scroll to be consumed during next/current layout pass **/ internal var scrollToBeConsumed = 0f private set /* @VisibleForTesting */ internal var measurePassCount = 0 /** states required for prefetching **/ internal var isVertical = false internal var laneWidthsPrefixSum: IntArray = IntArray(0) private var prefetchBaseIndex: Int = -1 private val currentItemPrefetchHandles = mutableMapOf<Int, PrefetchHandle>() /** state required for implementing [animateScrollScope] **/ internal var density: Density = Density(1f, 1f) internal val laneCount get() = laneWidthsPrefixSum.size /** * [InteractionSource] that will be used to dispatch drag events when this * list is being dragged. If you want to know whether the fling (or animated scroll) is in * progress, use [isScrollInProgress]. */ val interactionSource get(): InteractionSource = mutableInteractionSource /** backing field mutable field for [interactionSource] **/ internal val mutableInteractionSource = MutableInteractionSource() /** * Call this function to take control of scrolling and gain the ability to send scroll events * via [ScrollScope.scrollBy]. All actions that change the logical scroll position must be * performed within a [scroll] block (even if they don't call any other methods on this * object) in order to guarantee that mutual exclusion is enforced. * * If [scroll] is called from elsewhere, this will be canceled. */ override suspend fun scroll( scrollPriority: MutatePriority, block: suspend ScrollScope.() -> Unit ) { scrollableState.scroll(scrollPriority, block) } /** * Whether this [scrollableState] is currently scrolling by gesture, fling or programmatically or * not. */ override val isScrollInProgress: Boolean get() = scrollableState.isScrollInProgress /** Main scroll callback which adjusts scroll delta and remeasures layout **/ private fun onScroll(distance: Float): Float { if (distance < 0 && !canScrollForward || distance > 0 && !canScrollBackward) { return 0f } check(abs(scrollToBeConsumed) <= 0.5f) { "entered drag with non-zero pending scroll: $scrollToBeConsumed" } scrollToBeConsumed += distance // scrollToBeConsumed will be consumed synchronously during the forceRemeasure invocation // inside measuring we do scrollToBeConsumed.roundToInt() so there will be no scroll if // we have less than 0.5 pixels if (abs(scrollToBeConsumed) > 0.5f) { val preScrollToBeConsumed = scrollToBeConsumed remeasurement?.forceRemeasure() if (prefetchingEnabled) { notifyPrefetch(preScrollToBeConsumed - scrollToBeConsumed) } } // here scrollToBeConsumed is already consumed during the forceRemeasure invocation if (abs(scrollToBeConsumed) <= 0.5f) { // We consumed all of it - we'll hold onto the fractional scroll for later, so report // that we consumed the whole thing return distance } else { val scrollConsumed = distance - scrollToBeConsumed // We did not consume all of it - return the rest to be consumed elsewhere (e.g., // nested scrolling) scrollToBeConsumed = 0f // We're not consuming the rest, give it back return scrollConsumed } } /** * Instantly brings the item at [index] to the top of layout viewport, offset by [scrollOffset] * pixels. * * @param index the index to which to scroll. MUST NOT be negative. * @param scrollOffset the offset where the item should end up after the scroll. Note that * positive offset refers to forward scroll, so in a reversed list, positive offset will * scroll the item further upward (taking it partly offscreen). */ suspend fun scrollToItem( /* @IntRange(from = 0) */ index: Int, scrollOffset: Int = 0 ) { scroll { snapToItemInternal(index, scrollOffset) } } /** * Animate (smooth scroll) to the given item. * * @param index the index to which to scroll. MUST NOT be negative. * @param scrollOffset the offset that the item should end up after the scroll. Note that * positive offset refers to forward scroll, so in a top-to-bottom list, positive offset will * scroll the item further upward (taking it partly offscreen). */ suspend fun animateScrollToItem( /* @IntRange(from = 0) */ index: Int, scrollOffset: Int = 0 ) { animateScrollScope.animateScrollToItem(index, scrollOffset) } internal fun ScrollScope.snapToItemInternal(index: Int, scrollOffset: Int) { val visibleItem = layoutInfo.findVisibleItem(index) if (visibleItem != null) { val currentOffset = if (isVertical) visibleItem.offset.y else visibleItem.offset.x val delta = currentOffset + scrollOffset scrollBy(delta.toFloat()) } else { scrollPosition.requestPosition(index, scrollOffset) remeasurement?.forceRemeasure() } } /** * Maintain scroll position for item based on custom key if its index has changed. */ internal fun updateScrollPositionIfTheFirstItemWasMoved(itemProvider: LazyLayoutItemProvider) { scrollPosition.updateScrollPositionIfTheFirstItemWasMoved(itemProvider) } override fun dispatchRawDelta(delta: Float): Float = scrollableState.dispatchRawDelta(delta) /** Start prefetch of the items based on provided delta **/ private fun notifyPrefetch(delta: Float) { val info = layoutInfoState.value if (info.visibleItemsInfo.isNotEmpty()) { val scrollingForward = delta < 0 val prefetchIndex = if (scrollingForward) { info.visibleItemsInfo.last().index } else { info.visibleItemsInfo.first().index } if (prefetchIndex == prefetchBaseIndex) { // Already prefetched based on this index return } prefetchBaseIndex = prefetchIndex val prefetchHandlesUsed = mutableSetOf<Int>() var targetIndex = prefetchIndex for (lane in laneWidthsPrefixSum.indices) { val previousIndex = targetIndex // find the next item for each line and prefetch if it is valid targetIndex = if (scrollingForward) { spans.findNextItemIndex(previousIndex, lane) } else { spans.findPreviousItemIndex(previousIndex, lane) } if ( targetIndex !in (0 until info.totalItemsCount) || previousIndex == targetIndex ) { return } prefetchHandlesUsed += targetIndex if (targetIndex in currentItemPrefetchHandles) { continue } val crossAxisSize = laneWidthsPrefixSum[lane] - if (lane == 0) 0 else laneWidthsPrefixSum[lane - 1] val constraints = if (isVertical) { Constraints.fixedWidth(crossAxisSize) } else { Constraints.fixedHeight(crossAxisSize) } currentItemPrefetchHandles[targetIndex] = prefetchState.schedulePrefetch( index = targetIndex, constraints = constraints ) } clearLeftoverPrefetchHandles(prefetchHandlesUsed) } } private fun clearLeftoverPrefetchHandles(prefetchHandlesUsed: Set<Int>) { val iterator = currentItemPrefetchHandles.iterator() while (iterator.hasNext()) { val entry = iterator.next() if (entry.key !in prefetchHandlesUsed) { entry.value.cancel() iterator.remove() } } } private fun cancelPrefetchIfVisibleItemsChanged(info: LazyStaggeredGridLayoutInfo) { val items = info.visibleItemsInfo if (prefetchBaseIndex != -1 && items.isNotEmpty()) { if (prefetchBaseIndex !in items.first().index..items.last().index) { prefetchBaseIndex = -1 currentItemPrefetchHandles.values.forEach { it.cancel() } currentItemPrefetchHandles.clear() } } } /** updates state after measure pass **/ internal fun applyMeasureResult(result: LazyStaggeredGridMeasureResult) { scrollToBeConsumed -= result.consumedScroll canScrollBackward = result.canScrollBackward canScrollForward = result.canScrollForward layoutInfoState.value = result cancelPrefetchIfVisibleItemsChanged(result) scrollPosition.updateFromMeasureResult(result) measurePassCount++ } private fun fillNearestIndices(itemIndex: Int, laneCount: Int): IntArray { // reposition spans if needed to ensure valid indices spans.ensureValidIndex(itemIndex + laneCount) val span = spans.getSpan(itemIndex) val targetLaneIndex = if (span == LazyStaggeredGridSpans.Unset) 0 else minOf(span, laneCount) val indices = IntArray(laneCount) // fill lanes before starting index var currentItemIndex = itemIndex for (lane in (targetLaneIndex - 1) downTo 0) { indices[lane] = spans.findPreviousItemIndex(currentItemIndex, lane) if (indices[lane] == -1) { indices.fill(-1, toIndex = lane) break } currentItemIndex = indices[lane] } indices[targetLaneIndex] = itemIndex // fill lanes after starting index currentItemIndex = itemIndex for (lane in (targetLaneIndex + 1) until laneCount) { indices[lane] = spans.findNextItemIndex(currentItemIndex, lane) currentItemIndex = indices[lane] } return indices } companion object { /** * The default implementation of [Saver] for [LazyStaggeredGridState] */ val Saver = listSaver<LazyStaggeredGridState, IntArray>( save = { state -> listOf( state.scrollPosition.indices, state.scrollPosition.offsets ) }, restore = { LazyStaggeredGridState(it[0], it[1]) } ) } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/autoImports/libraryTopLevelFunctionImportJsRuntime.kt
2
90
// "Import function 'cos'" "true" // JS package some fun testFun() { <caret>cos(0.0) }
apache-2.0
GunoH/intellij-community
platform/testFramework/junit5/src/impl/ThreadLeakTrackerExtension.kt
5
1200
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.testFramework.junit5.impl import com.intellij.testFramework.common.ThreadLeakTracker import com.intellij.util.ui.EDT import org.jetbrains.annotations.TestOnly import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.extension.AfterEachCallback import org.junit.jupiter.api.extension.BeforeEachCallback import org.junit.jupiter.api.extension.ExtensionContext @TestOnly internal class ThreadLeakTrackerExtension : BeforeEachCallback, AfterEachCallback { companion object { private const val threadsBeforeKey = "threads before test started" } override fun beforeEach(context: ExtensionContext) { context.getStore(ExtensionContext.Namespace.GLOBAL).put(threadsBeforeKey, ThreadLeakTracker.getThreads()) } override fun afterEach(context: ExtensionContext) { val threadsBefore = context.getStore(ExtensionContext.Namespace.GLOBAL).typedGet<Map<String, Thread>>(threadsBeforeKey) Assertions.assertFalse(EDT.isCurrentThreadEdt()) ThreadLeakTracker.awaitQuiescence() ThreadLeakTracker.checkLeak(threadsBefore) } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantInnerClassModifier/innerClassConstructorCall2.kt
9
101
package test class Test { <caret>inner class Inner fun foo() { this.Inner() } }
apache-2.0
GunoH/intellij-community
plugins/full-line/src/org/jetbrains/completion/full/line/platform/FullLineCompletionQuery.kt
2
444
package org.jetbrains.completion.full.line.platform import com.intellij.lang.Language import com.intellij.openapi.project.Project import org.jetbrains.completion.full.line.FullLineCompletionMode data class FullLineCompletionQuery( val mode: FullLineCompletionMode, val context: String, val filename: String, val prefix: String, val offset: Int, val language: Language, val project: Project, val rollbackPrefix: List<String> )
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/j2k/J2KPostProcessingRegistrarImpl.kt
1
19124
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.j2k import com.intellij.codeInspection.ProblemHighlightType import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeInsight.intentions.shared.RemoveUnnecessaryParenthesesIntention import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.codeinsights.impl.base.KotlinInspectionFacade import org.jetbrains.kotlin.idea.core.setVisibility import org.jetbrains.kotlin.idea.inspections.* import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToElvisInspection import org.jetbrains.kotlin.idea.inspections.branchedTransformations.IfThenToSafeAccessInspection import org.jetbrains.kotlin.idea.inspections.conventionNameCalls.ReplaceGetOrSetInspection import org.jetbrains.kotlin.idea.intentions.* import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnAsymmetricallyIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.FoldIfToReturnIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isTrivialStatementBody import org.jetbrains.kotlin.idea.quickfix.RemoveModifierFixBase import org.jetbrains.kotlin.idea.quickfix.RemoveUselessCastFix import org.jetbrains.kotlin.idea.quickfix.asKotlinIntentionActionsFactory import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getChildOfType import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.mapToIndex object J2KPostProcessingRegistrarImpl : J2KPostProcessingRegistrar { private val myProcessings = ArrayList<J2kPostProcessing>() override val processings: Collection<J2kPostProcessing> get() = myProcessings private val processingsToPriorityMap = HashMap<J2kPostProcessing, Int>() override fun priority(processing: J2kPostProcessing): Int = processingsToPriorityMap[processing]!! init { myProcessings.add(RemoveExplicitTypeArgumentsProcessing()) myProcessings.add(RemoveRedundantOverrideVisibilityProcessing()) registerInspectionBasedProcessing(MoveLambdaOutsideParenthesesInspection()) myProcessings.add(FixObjectStringConcatenationProcessing()) myProcessings.add(ConvertToStringTemplateProcessing()) myProcessings.add(UsePropertyAccessSyntaxProcessing()) myProcessings.add(UninitializedVariableReferenceFromInitializerToThisReferenceProcessing()) myProcessings.add(UnresolvedVariableReferenceFromInitializerToThisReferenceProcessing()) myProcessings.add(RemoveRedundantSamAdaptersProcessing()) myProcessings.add(RemoveRedundantCastToNullableProcessing()) registerInspectionBasedProcessing(ReplacePutWithAssignmentInspection()) myProcessings.add(UseExpressionBodyProcessing()) registerInspectionBasedProcessing(UnnecessaryVariableInspection()) registerInspectionBasedProcessing(FoldInitializerAndIfToElvisInspection()) registerIntentionBasedProcessing(FoldIfToReturnIntention()) { it.then.isTrivialStatementBody() && it.`else`.isTrivialStatementBody() } registerIntentionBasedProcessing(FoldIfToReturnAsymmetricallyIntention()) { it.then.isTrivialStatementBody() && (KtPsiUtil.skipTrailingWhitespacesAndComments( it ) as KtReturnExpression).returnedExpression.isTrivialStatementBody() } registerInspectionBasedProcessing(IfThenToSafeAccessInspection()) registerInspectionBasedProcessing(IfThenToElvisInspection(true)) registerInspectionBasedProcessing(KotlinInspectionFacade.instance.simplifyNegatedBinaryExpression) registerInspectionBasedProcessing(ReplaceGetOrSetInspection()) registerInspectionBasedProcessing(AddOperatorModifierInspection()) registerIntentionBasedProcessing(ObjectLiteralToLambdaIntention()) registerIntentionBasedProcessing(AnonymousFunctionToLambdaIntention()) registerIntentionBasedProcessing(RemoveUnnecessaryParenthesesIntention()) registerIntentionBasedProcessing(DestructureIntention()) registerInspectionBasedProcessing(SimplifyAssertNotNullInspection()) registerIntentionBasedProcessing(RemoveRedundantCallsOfConversionMethodsIntention()) registerInspectionBasedProcessing(JavaMapForEachInspection()) registerInspectionBasedProcessing(ReplaceGuardClauseWithFunctionCallInspection()) registerDiagnosticBasedProcessing<KtBinaryExpressionWithTypeRHS>(Errors.USELESS_CAST) { element, _ -> val expression = RemoveUselessCastFix.invoke(element) val variable = expression.parent as? KtProperty if (variable != null && expression == variable.initializer && variable.isLocal) { val ref = ReferencesSearch.search(variable, LocalSearchScope(variable.containingFile)).findAll().singleOrNull() if (ref != null && ref.element is KtSimpleNameExpression) { ref.element.replace(expression) variable.delete() } } } registerDiagnosticBasedProcessing<KtTypeProjection>(Errors.REDUNDANT_PROJECTION) { _, diagnostic -> val fix = RemoveModifierFixBase.createRemoveProjectionFactory(true) .asKotlinIntentionActionsFactory() .createActions(diagnostic).single() as RemoveModifierFixBase fix.invoke() } registerDiagnosticBasedProcessingFactory( Errors.VAL_REASSIGNMENT, Errors.CAPTURED_VAL_INITIALIZATION, Errors.CAPTURED_MEMBER_VAL_INITIALIZATION ) { element: KtSimpleNameExpression, _: Diagnostic -> val property = element.mainReference.resolve() as? KtProperty if (property == null) { null } else { { if (!property.isVar) { property.valOrVarKeyword.replace(KtPsiFactory(element.project).createVarKeyword()) } } } } registerDiagnosticBasedProcessing<KtSimpleNameExpression>(Errors.UNNECESSARY_NOT_NULL_ASSERTION) { element, _ -> val exclExclExpr = element.parent as KtUnaryExpression val baseExpression = exclExclExpr.baseExpression!! val context = baseExpression.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) if (context.diagnostics.forElement(element).any { it.factory == Errors.UNNECESSARY_NOT_NULL_ASSERTION }) { exclExclExpr.replace(baseExpression) } } processingsToPriorityMap.putAll(myProcessings.mapToIndex()) } private inline fun <reified TElement : KtElement, TIntention : SelfTargetingRangeIntention<TElement>> registerIntentionBasedProcessing( intention: TIntention, noinline additionalChecker: (TElement) -> Boolean = { true } ) { myProcessings.add(object : J2kPostProcessing { // Intention can either need or not need write action override val writeActionNeeded = intention.startInWriteAction() override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (!TElement::class.java.isInstance(element)) return null val tElement = element as TElement if (intention.applicabilityRange(tElement) == null) return null if (!additionalChecker(tElement)) return null return { if (intention.applicabilityRange(tElement) != null) { // check availability of the intention again because something could change intention.applyTo(element, null) } } } }) } private inline fun <reified TElement : KtElement, TInspection : AbstractApplicabilityBasedInspection<TElement>> registerInspectionBasedProcessing( inspection: TInspection, acceptInformationLevel: Boolean = false ) { myProcessings.add(object : J2kPostProcessing { // Inspection can either need or not need write action override val writeActionNeeded = inspection.startFixInWriteAction private fun isApplicable(element: TElement): Boolean { if (!inspection.isApplicable(element)) return false return acceptInformationLevel || inspection.inspectionHighlightType(element) != ProblemHighlightType.INFORMATION } override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (!TElement::class.java.isInstance(element)) return null val tElement = element as TElement if (!isApplicable(tElement)) return null return { if (isApplicable(tElement)) { // check availability of the inspection again because something could change inspection.applyTo(tElement) } } } }) } private inline fun <reified TElement : KtElement> registerDiagnosticBasedProcessing( vararg diagnosticFactory: DiagnosticFactory<*>, crossinline fix: (TElement, Diagnostic) -> Unit ) { registerDiagnosticBasedProcessingFactory(*diagnosticFactory) { element: TElement, diagnostic: Diagnostic -> { fix( element, diagnostic ) } } } private inline fun <reified TElement : KtElement> registerDiagnosticBasedProcessingFactory( vararg diagnosticFactory: DiagnosticFactory<*>, crossinline fixFactory: (TElement, Diagnostic) -> (() -> Unit)? ) { myProcessings.add(object : J2kPostProcessing { // ??? override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (!TElement::class.java.isInstance(element)) return null val diagnostic = diagnostics.forElement(element).firstOrNull { it.factory in diagnosticFactory } ?: return null return fixFactory(element as TElement, diagnostic) } }) } private class RemoveExplicitTypeArgumentsProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtTypeArgumentList || !RemoveExplicitTypeArgumentsIntention.isApplicableTo( element, approximateFlexible = true ) ) return null return { if (RemoveExplicitTypeArgumentsIntention.isApplicableTo(element, approximateFlexible = true)) { element.delete() } } } } private class RemoveRedundantOverrideVisibilityProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtCallableDeclaration || !element.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return null val modifier = element.visibilityModifierType() ?: return null return { element.setVisibility(modifier) } } } private class ConvertToStringTemplateProcessing : J2kPostProcessing { override val writeActionNeeded = true private val intention = ConvertToStringTemplateIntention() override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element is KtBinaryExpression && intention.isApplicableTo(element) && ConvertToStringTemplateIntention.shouldSuggestToConvert( element ) ) { return { intention.applyTo(element, null) } } else { return null } } } private class UsePropertyAccessSyntaxProcessing : J2kPostProcessing { override val writeActionNeeded = true private val intention = UsePropertyAccessSyntaxIntention() override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtCallExpression) return null val propertyName = intention.detectPropertyNameToUse(element) ?: return null return { intention.applyTo(element, propertyName, reformat = true) } } } private class RemoveRedundantSamAdaptersProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtCallExpression) return null val expressions = RedundantSamConstructorInspection.samConstructorCallsToBeConverted(element) if (expressions.isEmpty()) return null return { RedundantSamConstructorInspection.samConstructorCallsToBeConverted(element) .forEach { RedundantSamConstructorInspection.replaceSamConstructorCall(it) } } } } private class UseExpressionBodyProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtPropertyAccessor) return null val inspection = UseExpressionBodyInspection(convertEmptyToUnit = false) if (!inspection.isActiveFor(element)) return null return { if (inspection.isActiveFor(element)) { inspection.simplify(element, false) } } } } private class RemoveRedundantCastToNullableProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtBinaryExpressionWithTypeRHS) return null val context = element.analyze() val leftType = context.getType(element.left) ?: return null val rightType = context.get(BindingContext.TYPE, element.right) ?: return null if (!leftType.isMarkedNullable && rightType.isMarkedNullable) { return { val type = element.right?.typeElement as? KtNullableType type?.replace(type.innerType!!) } } return null } } private class FixObjectStringConcatenationProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtBinaryExpression || element.operationToken != KtTokens.PLUS || diagnostics.forElement(element.operationReference).none { it.factory == Errors.UNRESOLVED_REFERENCE_WRONG_RECEIVER || it.factory == Errors.NONE_APPLICABLE } ) return null val bindingContext = element.analyze() val rightType = element.right?.getType(bindingContext) ?: return null if (KotlinBuiltIns.isString(rightType)) { return { val factory = KtPsiFactory(element) element.left!!.replace(factory.buildExpression { appendFixedText("(") appendExpression(element.left) appendFixedText(").toString()") }) } } return null } } private class UninitializedVariableReferenceFromInitializerToThisReferenceProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtSimpleNameExpression || diagnostics.forElement(element) .none { it.factory == Errors.UNINITIALIZED_VARIABLE } ) return null val resolved = element.mainReference.resolve() ?: return null if (resolved.isAncestor(element, strict = true)) { if (resolved is KtVariableDeclaration && resolved.hasInitializer()) { val anonymousObject = element.getParentOfType<KtClassOrObject>(true) ?: return null if (resolved.initializer!!.getChildOfType<KtClassOrObject>() == anonymousObject) { return { element.replaced(KtPsiFactory(element).createThisExpression()) } } } } return null } } private class UnresolvedVariableReferenceFromInitializerToThisReferenceProcessing : J2kPostProcessing { override val writeActionNeeded = true override fun createAction(element: KtElement, diagnostics: Diagnostics): (() -> Unit)? { if (element !is KtSimpleNameExpression || diagnostics.forElement(element) .none { it.factory == Errors.UNRESOLVED_REFERENCE } ) return null val anonymousObject = element.getParentOfType<KtClassOrObject>(true) ?: return null val variable = anonymousObject.getParentOfType<KtVariableDeclaration>(true) ?: return null if (variable.nameAsName == element.getReferencedNameAsName() && variable.initializer?.getChildOfType<KtClassOrObject>() == anonymousObject ) { return { element.replaced(KtPsiFactory(element).createThisExpression()) } } return null } } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/j2k/new/tests/testData/newJ2k/protected/superInSamePackage.kt
13
279
package test internal open class BaseSuperSamePackage { fun usage1() { val derived = DerivedSuperSamePackage() derived.foo() val i = derived.i } } internal class DerivedSuperSamePackage : BaseSuperSamePackage() { fun foo() {} var i = 1 }
apache-2.0
GunoH/intellij-community
plugins/full-line/core/src/org/jetbrains/completion/full/line/language/formatters/SkippedElementsFormatter.kt
2
533
package org.jetbrains.completion.full.line.language.formatters import com.intellij.psi.PsiElement import org.jetbrains.completion.full.line.language.ElementFormatter class SkippedElementsFormatter(private vararg val elementsToSkip: Class<out PsiElement>) : ElementFormatter { override fun condition(element: PsiElement): Boolean = elementsToSkip.any { it.isAssignableFrom(element::class.java) } override fun filter(element: PsiElement): Boolean? = condition(element) override fun format(element: PsiElement): String = "" }
apache-2.0
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerState.kt
5
4759
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.StoragePathMacros import com.intellij.openapi.fileEditor.impl.EditorsSplitters import com.intellij.openapi.observable.properties.AtomicProperty import com.intellij.openapi.project.Project import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.ComponentUtil import com.intellij.ui.ExperimentalUI import org.jdom.Element import org.jetbrains.annotations.ApiStatus import java.util.* @ApiStatus.Internal interface ToolWindowManagerState : PersistentStateComponent<Element> { var layout: DesktopLayout val noStateLoaded: Boolean val oldLayout: DesktopLayout? var layoutToRestoreLater: DesktopLayout? val recentToolWindows: LinkedList<String> val scheduledLayout: AtomicProperty<DesktopLayout?> val isEditorComponentActive: Boolean var frame: ProjectFrameHelper? } private const val EDITOR_ELEMENT = "editor" private const val ACTIVE_ATTR_VALUE = "active" private const val LAYOUT_TO_RESTORE = "layout-to-restore" private const val RECENT_TW_TAG = "recentWindows" @ApiStatus.Internal @State(name = "ToolWindowManager", storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)]) class ToolWindowManagerStateImpl(private val project: Project) : ToolWindowManagerState { private val isNewUi = ExperimentalUI.isNewUI() override var layout = DesktopLayout() override var noStateLoaded = false private set override var oldLayout: DesktopLayout? = null private set override var layoutToRestoreLater: DesktopLayout? = null override val recentToolWindows = LinkedList<String>() override val scheduledLayout = AtomicProperty<DesktopLayout?>(null) private val focusManager: IdeFocusManager get() = IdeFocusManager.getInstance(project)!! override val isEditorComponentActive: Boolean get() { ApplicationManager.getApplication().assertIsDispatchThread() return ComponentUtil.getParentOfType(EditorsSplitters::class.java, focusManager.focusOwner) != null } override var frame: ProjectFrameHelper? = null override fun getState(): Element? { if (frame == null) { return null } val element = Element("state") if (isEditorComponentActive) { element.addContent(Element(EDITOR_ELEMENT).setAttribute(ACTIVE_ATTR_VALUE, "true")) } // save layout of tool windows writeLayout(layout, element, isV2 = isNewUi) oldLayout?.let { writeLayout(it, element, isV2 = !isNewUi) } layoutToRestoreLater?.writeExternal(LAYOUT_TO_RESTORE)?.let { element.addContent(it) } if (recentToolWindows.isNotEmpty()) { val recentState = Element(RECENT_TW_TAG) recentToolWindows.forEach { recentState.addContent(Element("value").addContent(it)) } element.addContent(recentState) } return element } override fun loadState(state: Element) { var layoutIsScheduled = false for (element in state.children) { if (JDOMUtil.isEmpty(element)) { // make sure that layoutIsScheduled is not set if empty layout for some reason is provided continue } when (element.name) { DesktopLayout.TAG -> { val layout = DesktopLayout() layout.readExternal(element, isNewUi = false) if (isNewUi) { oldLayout = layout } else { scheduledLayout.set(layout) layoutIsScheduled = true } } "layoutV2" -> { val layout = DesktopLayout() layout.readExternal(element, isNewUi = true) if (isNewUi) { scheduledLayout.set(layout) layoutIsScheduled = true } else { oldLayout = layout } } LAYOUT_TO_RESTORE -> { layoutToRestoreLater = DesktopLayout().also { it.readExternal(element, isNewUi) } } RECENT_TW_TAG -> { recentToolWindows.clear() element.content.forEach { recentToolWindows.add(it.value) } } } } if (!layoutIsScheduled) { noStateLoaded() } } override fun noStateLoaded() { noStateLoaded = true } private fun writeLayout(layout: DesktopLayout, parent: Element, isV2: Boolean) { parent.addContent(layout.writeExternal(if (isV2) "layoutV2" else DesktopLayout.TAG) ?: return) } }
apache-2.0
GunoH/intellij-community
plugins/kotlin/code-insight/utils/src/org/jetbrains/kotlin/idea/codeinsight/utils/ControlFlowUtils.kt
2
1987
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.codeinsight.utils import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* /** * Consider a property initialization `val f: (Int) -> Unit = { println(it) }`. The type annotation `(Int) -> Unit` in this case is required * in order for the code to type check because otherwise the compiler cannot infer the type of `it`. */ tailrec fun KtCallableDeclaration.isExplicitTypeReferenceNeededForTypeInference(typeRef: KtTypeReference? = typeReference): Boolean { if (this !is KtDeclarationWithInitializer) return false val initializer = initializer if (initializer == null || typeRef == null) return false if (initializer !is KtLambdaExpression && initializer !is KtNamedFunction) return false val typeElement = typeRef.typeElement ?: return false if (typeRef.hasModifier(KtTokens.SUSPEND_KEYWORD)) return true return when (typeElement) { is KtFunctionType -> { if (typeElement.receiver != null) return true if (typeElement.returnTypeReference?.typeElement?.typeArgumentsAsTypes?.isNotEmpty() == true) return true if (typeElement.parameters.isEmpty()) return false val valueParameters = when (initializer) { is KtLambdaExpression -> initializer.valueParameters is KtNamedFunction -> initializer.valueParameters else -> emptyList() } valueParameters.isEmpty() || valueParameters.any { it.typeReference == null } } is KtUserType -> { val typeAlias = typeElement.referenceExpression?.mainReference?.resolve() as? KtTypeAlias ?: return false return isExplicitTypeReferenceNeededForTypeInference(typeAlias.getTypeReference()) } else -> false } }
apache-2.0
vovagrechka/fucking-everything
alraune/alraune/src/main/java/alraune/RP_Debug_PageBecameStale.kt
1
2380
package alraune import alraune.operations.* import pieces100.* import vgrechka.* import java.io.File class RP_Debug_PageBecameStale : RemoteProcedureBase<RP_Debug_PageBecameStale.Params>(RP_Debug_PageBecameStale.Params::class) { class Params { var initialContent by notNullOnce<String>() var currentContent by notNullOnce<String>() } override fun dance() { checkIsLocalDebug_elseBitch() rctx0.al.suspiciouslyLargeXStreamedServantsAllowed = true clog("--- initialContent = ${args.initialContent.substring(0, 50)}") clog("--- currentContent = ${args.currentContent.substring(0, 50)}") // 9d5550db-2fdb-4c90-a04c-67937b9b6c8d val button = button().id(nextJsIdent()).add("Staleness diff") btfEval(""" ${'$'}(document.body).append(${jsStringLiteral(button.render())}) ${jsOnDomidClick_prevent(button.attrs.id, jsCallBackendServantHandle(freakingServant(::serveStalenessDiffButtonClick)))} """) } fun serveStalenessDiffButtonClick() { fun fart(content: String): String { val file = AlDebug.tempFile(uuid()) stripIgnoredStuffForPageSha1ing(content) pipe TextPile::prettyPrintHtml pipe {file.writeText(it)} return file.path } btfEval("console.log('So, you are now stale, little motherfucker?')") runLocalMergeTool_noBlock(fart(args.initialContent), fart(args.currentContent)) } object Test1 { @JvmStatic fun main(args: Array<String>) { if (isWindowsOS()) runLocalMergeTool_noBlock( "C:\\Program Files (x86)\\WinMerge\\Contributors.txt", "C:\\Program Files (x86)\\WinMerge\\Files.txt") else runLocalMergeTool_noBlock( "/home/into/pro/febig/fe-private/alraune-private/src-for-alraune/alraune/operations/AlCtl_BackShitUp.kt", "/home/into/pro/febig/fe-private/alraune-private/src-for-alraune/alraune/operations/AlCtl_BackShitUp_Obsolete.kt") } } object Test2 { @JvmStatic fun main(args: Array<String>) { val untidy = File("c:\\tmp\\alraune\\cd84aa22-37c1-4b38-8e5a-20a9d0946677").readText() val tidy = TextPile.prettyPrintHtml(untidy) clog(tidy) } } }
apache-2.0
jwren/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/quickfix/AbstractQuickFixMultiModuleTest.kt
1
7240
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.daemon.quickFix.ActionHint import com.intellij.codeInsight.daemon.quickFix.LightQuickFixTestCase import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.TestDialog import com.intellij.openapi.ui.TestDialogManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.IdeaTestUtil import com.intellij.testFramework.UsefulTestCase import junit.framework.ComparisonFailure import junit.framework.TestCase import org.jetbrains.kotlin.idea.inspections.findExistingEditor import org.jetbrains.kotlin.idea.multiplatform.setupMppProjectFromDirStructure import org.jetbrains.kotlin.idea.stubs.AbstractMultiModuleTest import org.jetbrains.kotlin.idea.test.* import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils import org.jetbrains.kotlin.idea.test.KotlinTestUtils import org.jetbrains.kotlin.idea.test.TestMetadataUtil import org.junit.Assert import java.io.File import java.nio.file.Paths abstract class AbstractQuickFixMultiModuleTest : AbstractMultiModuleTest(), QuickFixTest { protected fun testDataFile(fileName: String): File = File(testDataPath, fileName) protected fun testDataFile(): File = testDataFile(fileName()) protected open fun fileName(): String = KotlinTestUtils.getTestDataFileName(this::class.java, this.name) ?: (getTestName(false) + ".kt") override fun getTestDataDirectory(): File { return File(TestMetadataUtil.getTestDataPath(this::class.java)) } fun doTest(unused: String) { setupMppProjectFromDirStructure(testDataFile()) val directiveFileText = project.findFileWithCaret().text withCustomCompilerOptions(directiveFileText, project, module) { doQuickFixTest(fileName()) } } private fun VirtualFile.toIOFile(): File? { val paths = mutableListOf<String>() var vFile: VirtualFile? = this while (vFile != null) { vFile.sourceIOFile()?.let { return File(it, paths.reversed().joinToString("/")) } paths.add(vFile.name) vFile = vFile.parent } return null } private fun doQuickFixTest(dirPath: String) { val actionFile = project.findFileWithCaret() val virtualFile = actionFile.virtualFile!! val mainFile = virtualFile.toIOFile()?.takeIf(File::exists) ?: error("unable to lookup source io file") configureByExistingFile(virtualFile) val actionFileText = actionFile.text val actionFileName = actionFile.name val inspections = parseInspectionsToEnable(virtualFile.path, actionFileText).toTypedArray() enableInspectionTools(*inspections) project.executeCommand("") { var expectedErrorMessage = "" try { val actionHint = ActionHint.parse(actionFile, actionFileText) val text = actionHint.expectedText val actionShouldBeAvailable = actionHint.shouldPresent() expectedErrorMessage = InTextDirectivesUtils.findListWithPrefixes( actionFileText, "// SHOULD_FAIL_WITH: " ).joinToString(separator = "\n") val dialogOption = when (InTextDirectivesUtils.findStringWithPrefixes(actionFileText, "// DIALOG_OPTION: ")) { "OK" -> TestDialog.OK "NO" -> TestDialog.NO "CANCEL" -> TestDialog { Messages.CANCEL } else -> TestDialog.DEFAULT } val oldDialogOption = TestDialogManager.setTestDialog(dialogOption) TypeAccessibilityChecker.testLog = StringBuilder() val log = try { AbstractQuickFixMultiFileTest.doAction( mainFile, text, file, editor, actionShouldBeAvailable, actionFileName, this::availableActions, this::doHighlighting, InTextDirectivesUtils.isDirectiveDefined(actionFile.text, "// SHOULD_BE_AVAILABLE_AFTER_EXECUTION") ) TypeAccessibilityChecker.testLog.toString() } finally { TestDialogManager.setTestDialog(oldDialogOption) TypeAccessibilityChecker.testLog = null } if (actionFile is KtFile) { DirectiveBasedActionUtils.checkForUnexpectedErrors(actionFile) } if (actionShouldBeAvailable) { compareToExpected(dirPath) } UsefulTestCase.assertEmpty(expectedErrorMessage) val logFile = Paths.get(testDataPath, dirPath, "log.log").toFile() if (log.isNotEmpty()) { KotlinTestUtils.assertEqualsToFile(logFile, log) } else { TestCase.assertFalse(logFile.exists()) } } catch (e: ComparisonFailure) { throw e } catch (e: AssertionError) { throw e } catch (e: Throwable) { if (expectedErrorMessage.isEmpty()) { e.printStackTrace() TestCase.fail(getTestName(true)) } else { Assert.assertEquals("Wrong exception message", expectedErrorMessage, e.message) compareToExpected(dirPath) } } } } private fun compareToExpected(directory: String) { val projectDirectory = File(testDataPath, directory) val afterFiles = projectDirectory.walkTopDown().filter { it.path.endsWith(".after") }.toList() for (editedFile in project.allKotlinFiles()) { val afterFileInTmpProject = editedFile.containingDirectory?.findFile(editedFile.name + ".after") ?: continue val afterFileInTestData = afterFiles.filter { it.name == afterFileInTmpProject.name }.single { it.readText() == File(afterFileInTmpProject.virtualFile.path).readText() } setActiveEditor(editedFile.findExistingEditor() ?: createEditor(editedFile.virtualFile)) try { checkResultByFile(afterFileInTestData.relativeTo(File(testDataPath)).path) } catch (e: ComparisonFailure) { KotlinTestUtils.assertEqualsToFile(afterFileInTestData, editor) } } } private val availableActions: List<IntentionAction> get() { doHighlighting() return LightQuickFixTestCase.getAvailableActions(editor, file) } override fun getTestProjectJdk() = IdeaTestUtil.getMockJdk18() }
apache-2.0
jwren/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/KotlinSmartStepTargetFilterer.kt
4
4131
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto import com.intellij.debugger.engine.DebugProcessImpl import com.intellij.debugger.impl.DebuggerUtilsEx import com.intellij.psi.PsiMethod import org.jetbrains.kotlin.asJava.LightClassUtil import org.jetbrains.kotlin.idea.debugger.DebuggerUtils.trimIfMangledInBytecode import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtPropertyAccessor import java.util.* class KotlinSmartStepTargetFilterer( private val targets: List<KotlinMethodSmartStepTarget>, private val debugProcess: DebugProcessImpl ) { private val functionCounter = mutableMapOf<String, Int>() private val targetWasVisited = BooleanArray(targets.size) { false } fun visitInlineFunction(function: KtNamedFunction) { val descriptor = function.descriptor ?: return val label = KotlinMethodSmartStepTarget.calcLabel(descriptor) val currentCount = functionCounter.increment(label) - 1 val matchedSteppingTargetIndex = targets.indexOfFirst { it.getDeclaration() === function && it.ordinal == currentCount } if (matchedSteppingTargetIndex < 0) return targetWasVisited[matchedSteppingTargetIndex] = true } fun visitOrdinaryFunction(owner: String, name: String, signature: String) { val currentCount = functionCounter.increment("$owner.$name$signature") - 1 for ((i, target) in targets.withIndex()) { if (target.shouldBeVisited(owner, name, signature, currentCount)) { targetWasVisited[i] = true break } } } private fun KotlinMethodSmartStepTarget.shouldBeVisited(owner: String, name: String, signature: String, currentCount: Int): Boolean { val actualName = name.trimIfMangledInBytecode(methodInfo.isNameMangledInBytecode) if (methodInfo.isInlineClassMember) { return matches( owner, actualName, // Inline class constructor argument is injected as the first // argument in inline class' functions. This doesn't correspond // with the PSI, so we delete the first argument from the signature signature.getSignatureWithoutFirstArgument(), currentCount ) } return matches(owner, actualName, signature, currentCount) } private fun KotlinMethodSmartStepTarget.matches(owner: String, name: String, signature: String, currentCount: Int): Boolean { if (methodInfo.name == name && ordinal == currentCount) { val lightClassMethod = getDeclaration()?.getLightClassMethod() ?: return false return lightClassMethod.matches(owner, name, signature, debugProcess) } return false } fun getUnvisitedTargets(): List<KotlinMethodSmartStepTarget> = targets.filterIndexed { i, _ -> !targetWasVisited[i] } fun reset() { Arrays.fill(targetWasVisited, false) functionCounter.clear() } } private fun String.getSignatureWithoutFirstArgument() = removeRange(indexOf('(') + 1..indexOf(';')) private fun KtDeclaration.getLightClassMethod(): PsiMethod? = when (this) { is KtNamedFunction -> LightClassUtil.getLightClassMethod(this) is KtPropertyAccessor -> LightClassUtil.getLightClassPropertyMethods(property).getter else -> null } private fun PsiMethod.matches(className: String, methodName: String, signature: String, debugProcess: DebugProcessImpl): Boolean = DebuggerUtilsEx.methodMatches( this, className.replace("/", "."), methodName, signature, debugProcess ) private fun MutableMap<String, Int>.increment(key: String): Int { val newValue = (get(key) ?: 0) + 1 put(key, newValue) return newValue }
apache-2.0
jwren/intellij-community
plugins/kotlin/completion/tests/testData/basic/multifile/NotImportedExtensionFunction/NotImportedExtensionFunction.dependency.kt
13
210
package second fun String?.helloFun() { } fun String.helloWithParams(i : Int) : String { return "" } fun <T: CharSequence> T.helloFunGeneric() { } fun Int.helloFake() { } fun dynamic.helloDynamic() { }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/highlighter/suppress/Class.kt
7
275
@Suppress("<warning descr="Redundant suppression">MoveVariableDeclarationIntoWhen</warning>") class A // NO_CHECK_INFOS // TOOL: com.intellij.codeInspection.RedundantSuppressInspection // TOOL: org.jetbrains.kotlin.idea.inspections.MoveVariableDeclarationIntoWhenInspection
apache-2.0
appmattus/layercache
layercache-android/src/main/kotlin/com/appmattus/layercache/DiskLruCacheWrapper.kt
1
2725
/* * Copyright 2020 Appmattus Limited * * 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.appmattus.layercache import com.jakewharton.disklrucache.DiskLruCache import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File /** * Wrapper around DiskLruCache (https://github.com/jakeWharton/DiskLruCache/) */ internal class DiskLruCacheWrapper(private val cache: DiskLruCache) : Cache<String, String> { override suspend fun evict(key: String) { withContext(Dispatchers.IO) { @Suppress("BlockingMethodInNonBlockingContext") cache.remove(key) } } override suspend fun get(key: String): String? { return withContext(Dispatchers.IO) { @Suppress("BlockingMethodInNonBlockingContext") cache.get(key)?.getString(0) } } override suspend fun set(key: String, value: String) { withContext(Dispatchers.IO) { @Suppress("BlockingMethodInNonBlockingContext") cache.edit(key).apply { set(0, value) commit() } } } override suspend fun evictAll() { withContext(Dispatchers.IO) { // Although setting maxSize to zero will cause the cache to be emptied this happens in a separate thread, // by calling flush immediately we ensure this happens in the same call @Suppress("BlockingMethodInNonBlockingContext") cache.maxSize.let { cache.maxSize = 0 cache.flush() cache.maxSize = it } } } } /** * Create a Cache from a DiskLruCache * @property diskLruCache A DiskLruCache */ @Suppress("unused", "USELESS_CAST") fun Cache.Companion.fromDiskLruCache(diskLruCache: DiskLruCache) = DiskLruCacheWrapper(diskLruCache) as Cache<String, String> /** * Create a Cache from a newly created DiskLruCache * @property directory Directory to create cache in * @property maxSize Maximum number of bytes */ @Suppress("unused", "USELESS_CAST") fun Cache.Companion.createDiskLruCache(directory: File, maxSize: Long) = fromDiskLruCache(DiskLruCache.open(directory, 1, 1, maxSize))
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/formatter/WhenEntry.kt
10
612
fun a() { when { true && true -> {} false -> { } else -> { } } } fun b() { val sealed: Sealed = Sealed.Foo() when (val a = sealed) { is Sealed.Foo -> println("Foo") is Sealed.A -> println("A") Sealed.A() -> print(1) else -> { } } } fun c() { val sealed: Sealed = Sealed.Foo() when (sealed) { is Sealed.Foo -> println("Foo") is Sealed.A -> println("A") Sealed.A() -> print(1) else -> { } } } // SET_TRUE: ALIGN_IN_COLUMNS_CASE_BRANCH
apache-2.0
smmribeiro/intellij-community
platform/vcs-impl/src/com/intellij/vcs/commit/ShowNotificationCommitResultHandler.kt
5
3957
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.commit import com.intellij.notification.NotificationType import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.util.text.StringUtil.isEmpty import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_CANCELED import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_FAILED import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_FINISHED import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_FINISHED_WITH_WARNINGS import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.changes.CommitResultHandler import com.intellij.vcs.commit.AbstractCommitter.Companion.collectErrors import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls private fun hasOnlyWarnings(exceptions: List<VcsException>) = exceptions.all { it.isWarning } class ShowNotificationCommitResultHandler(private val committer: AbstractCommitter) : CommitResultHandler { private val notifier = VcsNotifier.getInstance(committer.project) override fun onSuccess(commitMessage: String) = reportResult() override fun onCancel() { notifier.notifyMinorWarning(COMMIT_CANCELED, "", message("vcs.commit.canceled")) } override fun onFailure(errors: List<VcsException>) = reportResult() private fun reportResult() { val message = getCommitSummary() val allExceptions = committer.exceptions if (allExceptions.isEmpty()) { notifier.notifySuccess(COMMIT_FINISHED, "", message) return } val errors = collectErrors(allExceptions) val errorsSize = errors.size val warningsSize = allExceptions.size - errorsSize val notificationActions = allExceptions.filterIsInstance<CommitExceptionWithActions>().flatMap { it.actions } val title: @NlsContexts.NotificationTitle String val displayId: @NonNls String val notificationType: NotificationType if (errorsSize > 0) { displayId = COMMIT_FAILED title = message("message.text.commit.failed.with.error", errorsSize) notificationType = NotificationType.ERROR } else { displayId = COMMIT_FINISHED_WITH_WARNINGS title = message("message.text.commit.finished.with.warning", warningsSize) notificationType = NotificationType.WARNING } val notification = VcsNotifier.IMPORTANT_ERROR_NOTIFICATION.createNotification(title, message, notificationType) notification.setDisplayId(displayId) notificationActions.forEach { notification.addAction(it) } VcsNotifier.addShowDetailsAction(committer.project, notification) notification.notify(committer.project) } @NlsContexts.NotificationContent private fun getCommitSummary() = HtmlBuilder().apply { append(getFileSummaryReport()) val commitMessage = committer.commitMessage if (!isEmpty(commitMessage)) { append(": ").append(commitMessage) // NON-NLS } val feedback = committer.feedback if (feedback.isNotEmpty()) { br() appendWithSeparators(HtmlChunk.br(), feedback.map(HtmlChunk::text)) } val exceptions = committer.exceptions if (!hasOnlyWarnings(exceptions)) { br() appendWithSeparators(HtmlChunk.br(), exceptions.map { HtmlChunk.text(it.message) }) } }.toString() private fun getFileSummaryReport(): @Nls String { val failed = committer.failedToCommitChanges.size val committed = committer.changes.size - failed if (failed > 0) { return message("vcs.commit.files.committed.and.files.failed.to.commit", committed, failed) } return message("vcs.commit.files.committed", committed) } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/emptyRange/unsignedLong.kt
9
42
// WITH_STDLIB val range = 1UL<caret>..0UL
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/compiler/loadJava/compiledKotlin/fromLoadJava/kotlinSignature/propagation/return/SubclassOfCollection.kt
10
166
// FULL_JDK // JAVAC_EXPECTED_FILE package test public interface SubclassOfCollection<E>: MutableCollection<E> { override fun iterator() : MutableIterator<E> }
apache-2.0
chesslave/chesslave
backend/src/main/java/io/chesslave/eyes/MoveRecogniserByPositionDiff.kt
2
1291
package io.chesslave.eyes import io.chesslave.app.log import io.chesslave.model.Move import io.chesslave.model.Position import io.chesslave.model.moves class MoveRecogniserByPositionDiff { /** * Detects the move by analyzing the differences between the two positions. * * @return the detected move or null if none move was done * @throws Exception if the detection fails */ fun detect(previous: Position, current: Position): Move? { if (previous == current) { return null } val from = previous.toSet().diff(current.toSet()) val to = current.toSet().diff(previous.toSet()) log.info("changed squares: from=$from, to=$to") if (to.length() != 1) { throw UnexpectedMoveException( String.format("cannot detect move (from: %s, to: %s)", previous, current)) } val movedPiece = to.get()._2 val fromSquare = from.find { it._2 == movedPiece }.map { it._1 }.get() val toSquare = to.get()._1 // TODO: validate move outer return previous.moves(fromSquare) .filter { it.to == toSquare } .getOrElseThrow { UnexpectedMoveException("invalid move $fromSquare:$toSquare (from: $previous, to: $current)") } } }
gpl-2.0
Cognifide/gradle-aem-plugin
src/main/kotlin/com/cognifide/gradle/aem/common/instance/service/pkg/PackageFilter.kt
1
934
package com.cognifide.gradle.aem.common.instance.service.pkg import com.fasterxml.jackson.annotation.JsonIgnoreProperties import org.apache.commons.lang3.builder.EqualsBuilder import org.apache.commons.lang3.builder.HashCodeBuilder @JsonIgnoreProperties(ignoreUnknown = true) class PackageFilter private constructor() { lateinit var root: String lateinit var rules: List<PackageFilterRule> override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as PackageFilter return EqualsBuilder() .append(root, other.root) .append(rules, other.rules) .isEquals } override fun hashCode() = HashCodeBuilder() .append(root) .append(rules) .toHashCode() override fun toString() = "PackageFilter(root='$root', rules=$rules)" }
apache-2.0
cy6erGn0m/kotlin-frontend-plugin
kotlin-frontend/src/main/kotlin/org/jetbrains/kotlin/gradle/frontend/rollup/RollupBundler.kt
1
1707
package org.jetbrains.kotlin.gradle.frontend.rollup import org.gradle.api.* import org.gradle.api.file.* import org.jetbrains.kotlin.gradle.frontend.* object RollupBundler : Bundler<RollupExtension> { override val bundlerId = "rollup" override fun createConfig(project: Project) = RollupExtension(project) override fun apply(project: Project, packageManager: PackageManager, packagesTask: Task, bundleTask: Task, runTask: Task, stopTask: Task) { packageManager.require( listOf("rollup", "rollup-plugin-node-resolve", "rollup-plugin-commonjs") .map { Dependency(it, "*", Dependency.DevelopmentScope) }) val config = project.tasks.create("rollup-config", GenerateRollupConfigTask::class.java) { task -> task.description = "Generate rollup config" task.group = RollupGroup } val bundle = project.tasks.create("rollup-bundle", RollupBundleTask::class.java) { task -> task.description = "Bundle all scripts and resources with rollup" task.group = RollupGroup } bundle.dependsOn(config, packagesTask) bundleTask.dependsOn(bundle) } override fun outputFiles(project: Project): FileCollection { return listOf( project.tasks.withType(GenerateRollupConfigTask::class.java).map { it.outputs.files }, project.tasks.withType(RollupBundleTask::class.java).map { it.outputs.files } ).flatten() .filterNotNull() .takeIf { it.isNotEmpty() } ?.reduce { a, b -> a + b } ?: project.files() } const val RollupGroup = "Rollup" }
apache-2.0
webianks/BlueChat
app/src/main/java/com/webianks/bluechat/BluetoothChatService.kt
1
16512
package com.webianks.bluechat import android.bluetooth.BluetoothAdapter import android.content.Context import android.util.Log import android.bluetooth.BluetoothSocket import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothServerSocket import java.io.IOException import java.io.InputStream import java.io.OutputStream import android.os.Bundle import android.os.Handler import java.util.* /** * Created by ramankit on 20/7/17. */ class BluetoothChatService(context: Context, handler: Handler){ // Member fields private var mAdapter: BluetoothAdapter? = null private var mHandler: Handler? = null private var mSecureAcceptThread: AcceptThread? = null private var mInsecureAcceptThread: AcceptThread? = null private var mConnectThread: ConnectThread? = null private var mConnectedThread: ConnectedThread? = null private var mState: Int = 0 private var mNewState: Int = 0 private val TAG: String = javaClass.simpleName // Unique UUID for this application private val MY_UUID_SECURE = UUID.fromString("29621b37-e817-485a-a258-52da5261421a") private val MY_UUID_INSECURE = UUID.fromString("d620cd2b-e0a4-435b-b02e-40324d57195b") // Name for the SDP record when creating server socket private val NAME_SECURE = "BluetoothChatSecure" private val NAME_INSECURE = "BluetoothChatInsecure" // Constants that indicate the current connection state companion object { val STATE_NONE = 0 // we're doing nothing val STATE_LISTEN = 1 // now listening for incoming connections val STATE_CONNECTING = 2 // now initiating an outgoing connection val STATE_CONNECTED = 3 // now connected to a remote device } init { mAdapter = BluetoothAdapter.getDefaultAdapter() mState = STATE_NONE mNewState = mState mHandler = handler } /** * Return the current connection state. */ @Synchronized fun getState(): Int { return mState } /** * Start the chat service. Specifically start AcceptThread to begin a * session in listening (server) mode. Called by the Activity onResume() */ @Synchronized fun start() { Log.d(TAG, "start") // Cancel any thread attempting to make a connection if (mConnectThread != null) { mConnectThread?.cancel() mConnectThread = null } // Cancel any thread currently running a connection if (mConnectedThread != null) { mConnectedThread?.cancel() mConnectedThread = null } // Start the thread to listen on a BluetoothServerSocket if (mSecureAcceptThread == null) { mSecureAcceptThread = AcceptThread(true) mSecureAcceptThread?.start() } if (mInsecureAcceptThread == null) { mInsecureAcceptThread = AcceptThread(false) mInsecureAcceptThread?.start() } // Update UI title //updateUserInterfaceTitle() } /** * Start the ConnectThread to initiate a connection to a remote device. * @param device The BluetoothDevice to connect * * * @param secure Socket Security type - Secure (true) , Insecure (false) */ @Synchronized fun connect(device: BluetoothDevice?, secure: Boolean) { Log.d(TAG, "connect to: " + device) // Cancel any thread attempting to make a connection if (mState == STATE_CONNECTING) { if (mConnectThread != null) { mConnectThread?.cancel() mConnectThread = null } } // Cancel any thread currently running a connection if (mConnectedThread != null) { mConnectedThread?.cancel() mConnectedThread = null } // Start the thread to connect with the given device mConnectThread = ConnectThread(device, secure) mConnectThread?.start() // Update UI title //updateUserInterfaceTitle() } /** * Start the ConnectedThread to begin managing a Bluetooth connection * @param socket The BluetoothSocket on which the connection was made * * * @param device The BluetoothDevice that has been connected */ @Synchronized fun connected(socket: BluetoothSocket?, device: BluetoothDevice?, socketType: String) { Log.d(TAG, "connected, Socket Type:" + socketType) // Cancel the thread that completed the connection if (mConnectThread != null) { mConnectThread?.cancel() mConnectThread = null } // Cancel any thread currently running a connection if (mConnectedThread != null) { mConnectedThread?.cancel() mConnectedThread = null } // Cancel the accept thread because we only want to connect to one device if (mSecureAcceptThread != null) { mSecureAcceptThread?.cancel() mSecureAcceptThread = null } if (mInsecureAcceptThread != null) { mInsecureAcceptThread?.cancel() mInsecureAcceptThread = null } // Start the thread to manage the connection and perform transmissions mConnectedThread = ConnectedThread(socket, socketType) mConnectedThread?.start() // Send the name of the connected device back to the UI Activity val msg = mHandler?.obtainMessage(Constants.MESSAGE_DEVICE_NAME) val bundle = Bundle() bundle.putString(Constants.DEVICE_NAME, device?.name) msg?.data = bundle mHandler?.sendMessage(msg) // Update UI title //updateUserInterfaceTitle() } /** * Stop all threads */ @Synchronized fun stop() { Log.d(TAG, "stop") if (mConnectThread != null) { mConnectThread?.cancel() mConnectThread = null } if (mConnectedThread != null) { mConnectedThread?.cancel() mConnectedThread = null } if (mSecureAcceptThread != null) { mSecureAcceptThread?.cancel() mSecureAcceptThread = null } if (mInsecureAcceptThread != null) { mInsecureAcceptThread?.cancel() mInsecureAcceptThread = null } mState = STATE_NONE // Update UI title //updateUserInterfaceTitle() } /** * Write to the ConnectedThread in an unsynchronized manner * @param out The bytes to write * * * @see ConnectedThread.write */ fun write(out: ByteArray) { // Create temporary object var r: ConnectedThread? = null // Synchronize a copy of the ConnectedThread synchronized(this) { if (mState != STATE_CONNECTED) return r = mConnectedThread } // Perform the write unsynchronized r?.write(out) } /** * Indicate that the connection attempt failed and notify the UI Activity. */ private fun connectionFailed() { // Send a failure message back to the Activity val msg = mHandler?.obtainMessage(Constants.MESSAGE_TOAST) val bundle = Bundle() bundle.putString(Constants.TOAST, "Unable to connect device") msg?.data = bundle mHandler?.sendMessage(msg) mState = STATE_NONE // Update UI title //updateUserInterfaceTitle() // Start the service over to restart listening mode [email protected]() } /** * Indicate that the connection was lost and notify the UI Activity. */ private fun connectionLost() { // Send a failure message back to the Activity val msg = mHandler?.obtainMessage(Constants.MESSAGE_TOAST) val bundle = Bundle() bundle.putString(Constants.TOAST, "Device connection was lost") msg?.data = bundle mHandler?.sendMessage(msg) mState = STATE_NONE // Update UI title // updateUserInterfaceTitle() // Start the service over to restart listening mode [email protected]() } /** * This thread runs while listening for incoming connections. It behaves * like a server-side client. It runs until a connection is accepted * (or until cancelled). */ private inner class AcceptThread(secure: Boolean) : Thread() { // The local server socket private val mmServerSocket: BluetoothServerSocket? private val mSocketType: String init { var tmp: BluetoothServerSocket? = null mSocketType = if (secure) "Secure" else "Insecure" // Create a new listening server socket try { if (secure) { tmp = mAdapter?.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID_SECURE) } else { tmp = mAdapter?.listenUsingInsecureRfcommWithServiceRecord( NAME_INSECURE, MY_UUID_INSECURE) } } catch (e: IOException) { Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e) } mmServerSocket = tmp mState = STATE_LISTEN } override fun run() { Log.d(TAG, "Socket Type: " + mSocketType + "BEGIN mAcceptThread" + this) name = "AcceptThread" + mSocketType var socket: BluetoothSocket? // Listen to the server socket if we're not connected while (mState != STATE_CONNECTED) { try { // This is a blocking call and will only return on a // successful connection or an exception socket = mmServerSocket?.accept() } catch (e: IOException) { Log.e(TAG, "Socket Type: " + mSocketType + "accept() failed", e) break } // If a connection was accepted if (socket != null) { synchronized(this@BluetoothChatService) { when (mState) { STATE_LISTEN, STATE_CONNECTING -> // Situation normal. Start the connected thread. connected(socket, socket?.remoteDevice, mSocketType) STATE_NONE, STATE_CONNECTED -> // Either not ready or already connected. Terminate new socket. try { socket?.close() } catch (e: IOException) { Log.e(TAG, "Could not close unwanted socket", e) } else -> { } } } } } Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType) } fun cancel() { Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this) try { mmServerSocket?.close() } catch (e: IOException) { Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e) } } } /** * This thread runs while attempting to make an outgoing connection * with a device. It runs straight through; the connection either * succeeds or fails. */ private inner class ConnectThread(private val mmDevice: BluetoothDevice?, secure: Boolean) : Thread() { private val mmSocket: BluetoothSocket? private val mSocketType: String init { var tmp: BluetoothSocket? = null mSocketType = if (secure) "Secure" else "Insecure" // Get a BluetoothSocket for a connection with the // given BluetoothDevice try { if (secure) { tmp = mmDevice?.createRfcommSocketToServiceRecord( MY_UUID_SECURE) } else { tmp = mmDevice?.createInsecureRfcommSocketToServiceRecord( MY_UUID_INSECURE) } } catch (e: IOException) { Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e) } mmSocket = tmp mState = STATE_CONNECTING } override fun run() { Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType) name = "ConnectThread" + mSocketType // Always cancel discovery because it will slow down a connection mAdapter?.cancelDiscovery() // Make a connection to the BluetoothSocket try { // This is a blocking call and will only return on a // successful connection or an exception mmSocket?.connect() } catch (e: IOException) { // Close the socket try { mmSocket?.close() } catch (e2: IOException) { Log.e(TAG, "unable to close() " + mSocketType + " socket during connection failure", e2) } connectionFailed() return } // Reset the ConnectThread because we're done synchronized(this@BluetoothChatService) { mConnectThread = null } // Start the connected thread connected(mmSocket, mmDevice, mSocketType) } fun cancel() { try { mmSocket?.close() } catch (e: IOException) { Log.e(TAG, "close() of connect $mSocketType socket failed", e) } } } /** * This thread runs during a connection with a remote device. * It handles all incoming and outgoing transmissions. */ private inner class ConnectedThread(private val mmSocket: BluetoothSocket?, socketType: String) : Thread() { private val mmInStream: InputStream? private val mmOutStream: OutputStream? init { Log.d(TAG, "create ConnectedThread: " + socketType) var tmpIn: InputStream? = null var tmpOut: OutputStream? = null // Get the BluetoothSocket input and output streams try { tmpIn = mmSocket?.inputStream tmpOut = mmSocket?.outputStream } catch (e: IOException) { Log.e(TAG, "temp sockets not created", e) } mmInStream = tmpIn mmOutStream = tmpOut mState = STATE_CONNECTED } override fun run() { Log.i(TAG, "BEGIN mConnectedThread") val buffer = ByteArray(1024) var bytes: Int // Keep listening to the InputStream while connected while (mState == STATE_CONNECTED) { try { // Read from the InputStream bytes = mmInStream?.read(buffer) ?: 0 // Send the obtained bytes to the UI Activity mHandler?.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer) ?.sendToTarget() } catch (e: IOException) { Log.e(TAG, "disconnected", e) connectionLost() break } } } /** * Write to the connected OutStream. * @param buffer The bytes to write */ fun write(buffer: ByteArray) { try { mmOutStream?.write(buffer) // Share the sent message back to the UI Activity mHandler?.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer) ?.sendToTarget() } catch (e: IOException) { Log.e(TAG, "Exception during write", e) } } fun cancel() { try { mmSocket?.close() } catch (e: IOException) { Log.e(TAG, "close() of connect socket failed", e) } } } }
mit
jbmlaird/DiscogsBrowser
app/src/test/java/bj/vinylbrowser/singlelist/SingleListPresenterTest.kt
1
9335
package bj.vinylbrowser.singlelist import android.content.Context import bj.vinylbrowser.R import bj.vinylbrowser.model.collection.CollectionRelease import bj.vinylbrowser.model.common.RecyclerViewModel import bj.vinylbrowser.model.listing.Listing import bj.vinylbrowser.model.order.Order import bj.vinylbrowser.model.wantlist.Want import bj.vinylbrowser.network.DiscogsInteractor import bj.vinylbrowser.order.OrderFactory import bj.vinylbrowser.utils.FilterHelper import bj.vinylbrowser.utils.schedulerprovider.TestSchedulerProvider import com.nhaarman.mockito_kotlin.* import io.reactivex.Observable import io.reactivex.Single import io.reactivex.SingleTransformer import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.schedulers.TestScheduler import junit.framework.Assert.assertEquals import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentMatchers.any import org.mockito.junit.MockitoJUnitRunner import java.util.* /** * Created by Josh Laird on 22/05/2017. */ @RunWith(MockitoJUnitRunner::class) class SingleListPresenterTest { val username = "bjlairy" val errorWantlistString = "Unable to load Wantlist" val wantlistNoneString = "Nothing in your Wantlist yet" val errorCollectionString = "Unable to load Collection" val collectionNoneString = "Nothing in your Collection yet" val errorOrdersString = "Unable to load orders" val ordersNoneString = "Not sold anything" val errorSellingString = "Unable to load selling" val sellingNoneString = "Not selling anything" var singleListPresenter: SingleListPresenter = mock() val context: Context = mock() val view: SingleListContract.View = mock() val discogsInteractor: DiscogsInteractor = mock() var testScheduler = TestScheduler() val controller: SingleListEpxController = mock() val compositeDisposable: CompositeDisposable = mock() val filterHelper: FilterHelper = mock() @Before fun setup() { testScheduler = TestScheduler() singleListPresenter = SingleListPresenter(context, view, discogsInteractor, TestSchedulerProvider(testScheduler), controller, compositeDisposable, filterHelper) } @After fun tearDown() { verifyNoMoreInteractions(context, view, discogsInteractor, controller, compositeDisposable) } @Test fun setupFilterSubscriptionNoItems_setsUpFilterSubscription() { val filterText = "yeson" whenever(compositeDisposable.add(any<Disposable>(Disposable::class.java))).thenReturn(true) whenever(view.filterIntent()).thenReturn(Observable.just<CharSequence>(filterText)) singleListPresenter.setupFilterSubscription() testScheduler.triggerActions() verify(compositeDisposable, times(1)).add(any<Disposable>(Disposable::class.java)) verify(view, times(1)).filterIntent() verify(filterHelper, times(1)).setFilterText(filterText) } @Test fun setupFilterSubscriptionItemsNoFilter_showsItems() { val recyclerViewModels = ArrayList<RecyclerViewModel>() recyclerViewModels.add(OrderFactory.buildOneOrderWithItems(1)) singleListPresenter.setItems(recyclerViewModels) val filterText = "yeson" whenever(compositeDisposable.add(any<Disposable>(Disposable::class.java))).thenReturn(true) whenever(view.filterIntent()).thenReturn(Observable.just<CharSequence>(filterText)) // Don't filter whenever(filterHelper.filterByFilterText()).thenReturn(SingleTransformer { o -> o }) singleListPresenter.setupFilterSubscription() testScheduler.triggerActions() verify(compositeDisposable, times(1)).add(any<Disposable>(Disposable::class.java)) verify(view, times(1)).filterIntent() verify(filterHelper).filterByFilterText() verify(filterHelper, times(1)).setFilterText(filterText) verify(controller).setItems(recyclerViewModels) } @Test fun unsubDispose_unsubsDisposes() { singleListPresenter.unsubscribe() singleListPresenter.dispose() verify(compositeDisposable, times(1)).clear() verify(compositeDisposable, times(1)).dispose() } @Test fun getDataWantlistError_showsError() { val error = Single.error<List<Want>>(Throwable()) whenever(discogsInteractor.fetchWantlist(username)).thenReturn(error) whenever(context.getString(R.string.error_wantlist)).thenReturn(errorWantlistString) whenever(context.getString(R.string.wantlist_none)).thenReturn(wantlistNoneString) // Test filter in filter class - don't filter here singleListPresenter.getData(R.string.drawer_item_wantlist, username) testScheduler.triggerActions() verify(discogsInteractor, times(1)).fetchWantlist(username) assertEquals(context.getString(R.string.error_wantlist), errorWantlistString) verify(context, times(2)).getString(R.string.error_wantlist) assertEquals(context.getString(R.string.wantlist_none), wantlistNoneString) verify(context, times(1)).getString(R.string.wantlist_none) verify(controller, times(1)).setError(errorWantlistString) } @Test fun getDataCollectionError_showsError() { val error = Single.error<List<CollectionRelease>>(Throwable()) whenever(discogsInteractor.fetchCollection(username)).thenReturn(error) whenever(context.getString(R.string.error_collection)).thenReturn(errorCollectionString) whenever(context.getString(R.string.collection_none)).thenReturn(collectionNoneString) singleListPresenter.getData(R.string.drawer_item_collection, username) testScheduler.triggerActions() verify(discogsInteractor, times(1)).fetchCollection(username) assertEquals(context.getString(R.string.error_collection), errorCollectionString) verify(context, times(2)).getString(R.string.error_collection) assertEquals(context.getString(R.string.collection_none), collectionNoneString) verify(context, times(1)).getString(R.string.collection_none) verify(controller, times(1)).setError(errorCollectionString) } @Test fun getDataOrdersError_showsError() { val error = Single.error<List<Order>>(Throwable()) whenever(discogsInteractor.fetchOrders()).thenReturn(error) whenever(context.getString(R.string.error_orders)).thenReturn(errorOrdersString) whenever(context.getString(R.string.orders_none)).thenReturn(ordersNoneString) singleListPresenter.getData(R.string.orders, username) testScheduler.triggerActions() verify(discogsInteractor, times(1)).fetchOrders() assertEquals(context.getString(R.string.error_orders), errorOrdersString) verify(context, times(2)).getString(R.string.error_orders) assertEquals(context.getString(R.string.orders_none), ordersNoneString) verify(context, times(1)).getString(R.string.orders_none) verify(controller, times(1)).setError(errorOrdersString) } @Test fun getDataSellingError_showsError() { val error = Single.error<List<Listing>>(Throwable()) whenever(discogsInteractor.fetchSelling(username)).thenReturn(error) whenever(context.getString(R.string.error_selling)).thenReturn(errorSellingString) whenever(context.getString(R.string.selling_none)).thenReturn(sellingNoneString) whenever(filterHelper.filterForSale()).thenReturn(SingleTransformer { o -> o }) singleListPresenter.getData(R.string.selling, username) testScheduler.triggerActions() verify(discogsInteractor, times(1)).fetchSelling(username) assertEquals(context.getString(R.string.error_selling), errorSellingString) verify(context, times(2)).getString(R.string.error_selling) assertEquals(context.getString(R.string.selling_none), sellingNoneString) verify(context, times(1)).getString(R.string.selling_none) verify(controller, times(1)).setError(errorSellingString) } @Test fun getDataNoItems_displaysEmptyList() { val emptyList = emptyList<Listing>() whenever(discogsInteractor.fetchSelling(username)).thenReturn(Single.just<List<Listing>>(emptyList)) whenever(context.getString(R.string.error_selling)).thenReturn(errorSellingString) whenever(context.getString(R.string.selling_none)).thenReturn(sellingNoneString) whenever(filterHelper.filterForSale()).thenReturn(SingleTransformer { o -> o }) whenever(filterHelper.filterByFilterText()).thenReturn(SingleTransformer { o -> o }) singleListPresenter.getData(R.string.selling, username) testScheduler.triggerActions() verify(discogsInteractor, times(1)).fetchSelling(username) assertEquals(context.getString(R.string.error_selling), errorSellingString) verify(context, times(2)).getString(R.string.error_selling) assertEquals(context.getString(R.string.selling_none), sellingNoneString) verify(filterHelper, times(1)).filterByFilterText() verify(context, times(1)).getString(R.string.selling_none) verify(controller).setItems(emptyList) } }
mit
ThiagoGarciaAlves/intellij-community
uast/uast-common/src/org/jetbrains/uast/declarations/UMethod.kt
1
3479
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast import com.intellij.psi.PsiAnnotationMethod import com.intellij.psi.PsiMethod import com.intellij.psi.PsiType import org.jetbrains.uast.internal.acceptList import org.jetbrains.uast.internal.log import org.jetbrains.uast.visitor.UastTypedVisitor import org.jetbrains.uast.visitor.UastVisitor /** * A method visitor to be used in [UastVisitor]. */ interface UMethod : UDeclaration, PsiMethod { override val psi: PsiMethod /** * Returns the body expression (which can be also a [UBlockExpression]). */ val uastBody: UExpression? /** * Returns the method parameters. */ val uastParameters: List<UParameter> /** * Returns true, if the method overrides a method of a super class. */ val isOverride: Boolean override fun getName(): String override fun getReturnType(): PsiType? override fun isConstructor(): Boolean @Deprecated("Use uastBody instead.", ReplaceWith("uastBody")) override fun getBody() = psi.body override fun accept(visitor: UastVisitor) { if (visitor.visitMethod(this)) return annotations.acceptList(visitor) uastParameters.acceptList(visitor) uastBody?.accept(visitor) visitor.afterVisitMethod(this) } override fun asRenderString() = buildString { if (annotations.isNotEmpty()) { annotations.joinTo(buffer = this, separator = "\n", postfix = "\n", transform = UAnnotation::asRenderString) } append(psi.renderModifiers()) append("fun ").append(name) uastParameters.joinTo(this, prefix = "(", postfix = ")") { parameter -> val annotationsText = if (parameter.annotations.isNotEmpty()) parameter.annotations.joinToString(separator = " ", postfix = " ") { it.asRenderString() } else "" annotationsText + parameter.name + ": " + parameter.type.canonicalText } psi.returnType?.let { append(" : " + it.canonicalText) } val body = uastBody append(when (body) { is UBlockExpression -> " " + body.asRenderString() else -> " = " + ((body ?: UastEmptyExpression(this@UMethod)).asRenderString()) }) } override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D) = visitor.visitMethod(this, data) override fun asLogString() = log("name = $name") } interface UAnnotationMethod : UMethod, PsiAnnotationMethod { override val psi: PsiAnnotationMethod /** * Returns the default value of this annotation method. */ val uastDefaultValue: UExpression? override fun getDefaultValue() = psi.defaultValue override fun accept(visitor: UastVisitor) { if (visitor.visitMethod(this)) return annotations.acceptList(visitor) uastParameters.acceptList(visitor) uastBody?.accept(visitor) uastDefaultValue?.accept(visitor) visitor.afterVisitMethod(this) } override fun asLogString() = log("name = $name") }
apache-2.0
7449/Album
scan/src/main/java/com/gallery/scan/args/ScanEntityFactory.kt
1
681
package com.gallery.scan.args import android.database.Cursor import com.gallery.scan.task.ScanTask /** * 自定义实体工厂 * 调用[cursorMoveToNextGeneric]可避免泛型强制转换 * [ScanTask] */ interface ScanEntityFactory { companion object { fun action(action: (cursor: Cursor) -> Any) = object : ScanEntityFactory { override fun cursorMoveToNext(cursor: Cursor): Any { return action.invoke(cursor) } } } fun cursorMoveToNext(cursor: Cursor): Any @Suppress("UNCHECKED_CAST") fun <E> cursorMoveToNextGeneric(cursor: Cursor): E = cursorMoveToNext(cursor) as E }
mpl-2.0
mscharhag/blog-examples
kotlin-koin-example/src/main/kotlin/com/mscharhag/koin/Address.kt
1
110
package com.mscharhag.koin class Address( street: String, city: String, zip: String )
apache-2.0
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/NetworkUtil.kt
1
2485
package ch.rmy.android.http_shortcuts.utils import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED import android.net.wifi.WifiManager import android.os.Build import android.os.PowerManager import androidx.core.content.getSystemService import ch.rmy.android.framework.extensions.showToast import ch.rmy.android.framework.extensions.startActivity import ch.rmy.android.http_shortcuts.R import javax.inject.Inject class NetworkUtil @Inject constructor( private val context: Context, private val activityProvider: ActivityProvider, ) { fun isNetworkConnected(): Boolean = context.getSystemService<ConnectivityManager>() ?.activeNetworkInfo ?.isConnected ?: false fun isNetworkPerformanceRestricted() = isDataSaverModeEnabled() || isBatterySaverModeEnabled() private fun isBatterySaverModeEnabled(): Boolean = context.getSystemService<PowerManager>() ?.isPowerSaveMode ?: false private fun isDataSaverModeEnabled(): Boolean = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { context.getSystemService<ConnectivityManager>() ?.run { isActiveNetworkMetered && restrictBackgroundStatus == RESTRICT_BACKGROUND_STATUS_ENABLED } ?: false } else { false } fun getCurrentSsid(): String? = context.applicationContext.getSystemService<WifiManager>() ?.connectionInfo ?.ssid ?.trim('"') fun getIPV4Address(): String? = context.applicationContext.getSystemService<WifiManager>() ?.connectionInfo ?.ipAddress ?.takeUnless { it == 0 } ?.let(::formatIPV4Address) private fun formatIPV4Address(ip: Int): String = "${ip shr 0 and 0xFF}.${ip shr 8 and 0xFF}.${ip shr 16 and 0xFF}.${ip shr 24 and 0xFF}" fun showWifiPicker() { try { Intent(WifiManager.ACTION_PICK_WIFI_NETWORK) .putExtra("extra_prefs_show_button_bar", true) .putExtra("wifi_enable_next_on_connect", true) .startActivity(activityProvider.getActivity()) } catch (e: ActivityNotFoundException) { context.showToast(R.string.error_not_supported) } } }
mit
timrijckaert/BetterBottomBar
library/src/main/kotlin/be/rijckaert/tim/library/BetterBottomBarDefaultBehavior.kt
1
1797
package be.rijckaert.tim.library import android.support.design.widget.BottomNavigationView import android.support.design.widget.CoordinatorLayout import android.view.View class BetterBottomBarDefaultBehavior : CoordinatorLayout.Behavior<BottomNavigationView>() { private var totalDyConsumed = -1 override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout?, child: BottomNavigationView, directTargetChild: View?, target: View?, nestedScrollAxes: Int): Boolean = true override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, child: BottomNavigationView, target: View?, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int) { super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed) if (dyConsumed > 0 && totalDyConsumed < 0) { totalDyConsumed = 0 animateBottomBar(child, coordinatorLayout, ScrollDirection.UP) } else if (dyConsumed < 0 && totalDyConsumed > 0) { totalDyConsumed = 0 animateBottomBar(child, coordinatorLayout, ScrollDirection.DOWN) } totalDyConsumed += dyConsumed } private fun animateBottomBar(view: View, container: View, direction: ScrollDirection) { val yPos = calculateY(view.height, container.height, direction) view.animate().y(yPos).start() } private fun calculateY(measuredHeightView: Int, measuredHeightContainer: Int, scrollDirection: ScrollDirection): Float = measuredHeightContainer.plus((measuredHeightView.times(scrollDirection.directionFactor))).toFloat() private enum class ScrollDirection(val directionFactor: Int = 1) { UP(), DOWN(-1); } }
mit
mubaris/yes
yes.kt
1
156
fun main(args: Array<String>) { val output = if (args.isNotEmpty()) args.joinToString(" ") else "y" while (true) { println(output) } }
mit
iotv/android
app/src/main/kotlin/io/iotv/app/MP4ChunkedUploader.kt
1
1421
package io.iotv.app import android.util.Log import okhttp3.MediaType import okhttp3.RequestBody import okio.Buffer import okio.BufferedSink import okio.Okio import java.io.FileDescriptor import java.io.FileInputStream import java.io.IOException class MP4ChunkedUploader(val fileDescriptor: FileDescriptor) { val inputStream = FileInputStream(fileDescriptor) val bufferedSource = Okio.buffer(Okio.source(inputStream)) } class MP4ChunkRequestBody(val buffer: Buffer): RequestBody() { companion object { val TAG = "MP4ChunkRequestBody" // FIXME: Perhaps generate the boundary so it doesn't happen to interfere with a file? // Since a file containing \n--boundary would split the message if we don't parse this // properly. It'd probably be smarter to just migrate to protobuf tbh val MULTIPART_RELATED_TYPE = MediaType.parse("multipart/related; boundary=\"boundary\"")!! } override fun contentType(): MediaType { return MULTIPART_RELATED_TYPE } override fun writeTo(sink: BufferedSink?) { try { sink!!.writeUtf8("--boundary\nContent-Type: application/json; charset=utf8\n\n{}\n--boundary") sink.writeAll(buffer) sink.writeUtf8("\n--boundary--\n") } catch (e: IOException) { Log.e(TAG, "IOException in writeTo while writing request body") throw e } } }
mit
h3xstream/find-sec-bugs
findsecbugs-samples-kotlin/src/test/kotlin/com/h3xstream/findsecbugs/deserialisation/TypeProvider.kt
2
191
package com.h3xstream.findsecbugs.deserialisation import java.io.Serializable import java.lang.reflect.Type interface TypeProvider : Serializable { val type: Type val source: Any }
lgpl-3.0
ZoranPandovski/al-go-rithms
dynamic_programing/kotlin/LongestCommonSubsequence.kt
1
1254
class LongestCommonSubsequence { /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ fun lcs(X: CharArray, Y: CharArray, m: Int, n: Int): Int { val L = Array(m + 1) { IntArray(n + 1) } /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (i in 0..m) { for (j in 0..n) { if (i == 0 || j == 0) L[i][j] = 0 else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1 else L[i][j] = max(L[i - 1][j], L[i][j - 1]) } } return L[m][n] } /* Utility function to get max of 2 integers */ fun max(a: Int, b: Int): Int { return if (a > b) a else b } companion object { @JvmStatic fun main(args: Array<String>) { val lcs = LongestCommonSubsequence() val s1 = "asdpoij" val s2 = "asdpfwefg" val X = s1.toCharArray() val Y = s2.toCharArray() val m = X.size val n = Y.size val result = lcs.lcs(X, Y, m, n) println(result) } } }
cc0-1.0
atlarge-research/opendc-simulator
opendc-stdlib/src/main/kotlin/com/atlarge/opendc/model/topology/TopologyBuilder.kt
1
1637
/* * MIT License * * Copyright (c) 2017 atlarge-research * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.atlarge.opendc.model.topology /** * A builder for [Topology] instances. * * @author Fabian Mastenbroek ([email protected]) */ interface TopologyBuilder : TopologyFactory { /** * Construct a [Topology] from the given block and return it. * * @param block The block to construct the topology. * @return The topology that has been built. */ fun construct(block: MutableTopology.() -> Unit): MutableTopology = create().apply(block) }
mit
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/usecase/NoteFindWithProperty.kt
1
381
package com.orgzly.android.usecase import com.orgzly.android.data.DataRepository class NoteFindWithProperty(val name: String, val value: String) : UseCase() { override fun run(dataRepository: DataRepository): UseCaseResult { val note = dataRepository.findNoteHavingProperty(name, value) return UseCaseResult( userData = note ) } }
gpl-3.0
SDILogin/RouteTracker
app/src/main/java/me/sdidev/simpleroutetracker/snapshot/SnapshotManager.kt
1
255
package me.sdidev.simpleroutetracker.snapshot import io.reactivex.Single import me.sdidev.simpleroutetracker.core.Route interface SnapshotManager { fun store(storeRequest: StoreRequest): Single<Image> fun restore(route: Route): Single<Image> }
mit
orgzly/orgzly-android
app/src/androidTest/java/com/orgzly/android/query/QueryUtilsTest.kt
1
1056
package com.orgzly.android.query import com.orgzly.android.query.user.DottedQueryParser import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(value = Parameterized::class) class QueryUtilsTest(private val param: Parameter) { data class Parameter(val query: String, val bookName: String?) companion object { @JvmStatic @Parameterized.Parameters(name = "{index}: query {0} should return book name {1}") fun data(): Collection<Parameter> { return listOf( Parameter("b.foo", "foo"), Parameter("b.foo b.bar", "foo"), Parameter("foo or b.bar", "bar"), Parameter("", null) ) } } @Test fun testExtractFirstBookNameFromQuery() { val condition = DottedQueryParser().parse(param.query).condition val result = QueryUtils.extractFirstBookNameFromQuery(condition) assertEquals(param.bookName, result) } }
gpl-3.0
hazuki0x0/YuzuBrowser
module/search/src/main/java/jp/hazuki/yuzubrowser/search/model/provider/SearchSettings.kt
1
924
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.search.model.provider import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class SearchSettings( @Json(name = "sel") val selectedId: Int, @Json(name = "idc") val idCount: Int, @Json(name = "item") val items: List<SearchUrl> )
apache-2.0
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/ui/main/ActivityForResult.kt
1
2546
package com.orgzly.android.ui.main import android.app.Activity import android.content.Intent import android.net.Uri import android.util.Log import androidx.annotation.StringRes import androidx.core.app.ComponentActivity import com.orgzly.BuildConfig import com.orgzly.R import com.orgzly.android.savedsearch.FileSavedSearchStore import com.orgzly.android.util.LogUtils abstract class ActivityForResult(val activity: ComponentActivity) { fun startSavedSearchesExportFileChooser() { val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply { addCategory(Intent.CATEGORY_OPENABLE) type = "application/json" putExtra(Intent.EXTRA_TITLE, FileSavedSearchStore.FILE_NAME) } activity.startActivityForResult(intent, REQUEST_CODE_SAVED_SEARCHES_EXPORT) } fun startSavedSearchesImportFileChooser() { startFileChooser(R.string.import_, REQUEST_CODE_SAVED_SEARCHES_IMPORT) } private fun startFileChooser(@StringRes titleResId: Int, code: Int) { val intent = Intent(Intent.ACTION_GET_CONTENT).apply { addCategory(Intent.CATEGORY_OPENABLE) type = "*/*" } val chooserIntent = Intent.createChooser(intent, activity.getString(titleResId)) activity.startActivityForResult(chooserIntent, code) } fun onResult(requestCode: Int, resultCode: Int, intent: Intent?) { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, requestCode, resultCode, intent) if (resultCode != Activity.RESULT_OK) { Log.w(TAG, "Activity result not OK") return } if (intent == null) { Log.w(TAG, "Activity result has no intent") return } when (requestCode) { REQUEST_CODE_SAVED_SEARCHES_EXPORT -> { intent.data?.let { uri -> onSearchQueriesExport(uri) } } REQUEST_CODE_SAVED_SEARCHES_IMPORT -> { intent.data?.let { uri -> onSearchQueriesImport(uri) } } else -> { Log.e(TAG, "Unknown request code $requestCode intent $intent") } } } abstract fun onSearchQueriesExport(uri: Uri) abstract fun onSearchQueriesImport(uri: Uri) companion object { private val TAG = ActivityForResult::class.java.name const val REQUEST_CODE_SAVED_SEARCHES_EXPORT = 3 const val REQUEST_CODE_SAVED_SEARCHES_IMPORT = 4 } }
gpl-3.0
Litote/kmongo
kmongo-id/src/main/kotlin/org/litote/kmongo/id/IdGenerator.kt
1
1878
/* * 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.id import org.litote.kmongo.Id import java.util.ServiceLoader import kotlin.reflect.KClass import kotlin.reflect.full.valueParameters /** * A generator of Ids. */ interface IdGenerator { companion object { var defaultGenerator: IdGenerator get() = defaultIdGenerator set(value) { defaultIdGenerator = value } @Volatile private var defaultIdGenerator: IdGenerator = ServiceLoader.load(IdGeneratorProvider::class.java) .iterator().asSequence().maxByOrNull { it.priority }?.generator ?: UUIDStringIdGenerator } /** * The class of the id. */ val idClass: KClass<out Id<*>> /** * The class of the wrapped id. */ val wrappedIdClass: KClass<out Any> /** * Generate a new id. */ fun <T> generateNewId(): Id<T> /** * Create a new id from its String representation. */ fun create(s: String): Id<*> = idClass .constructors .firstOrNull { it.valueParameters.size == 1 && it.valueParameters.first().type.classifier == String::class } ?.call(s) ?: error("no constructor with a single string arg found for $idClass}") }
apache-2.0
EMResearch/EvoMaster
core/src/test/kotlin/org/evomaster/core/database/extract/postgres/SqlDateColumnTest.kt
1
2715
package org.evomaster.core.database.extract.postgres import org.evomaster.client.java.controller.db.SqlScriptRunner import org.evomaster.client.java.controller.internal.db.SchemaExtractor import org.evomaster.core.database.DbActionTransformer import org.evomaster.core.database.SqlInsertBuilder import org.evomaster.core.search.gene.datetime.DateGene import org.evomaster.core.search.gene.numeric.IntegerGene import org.evomaster.core.search.gene.sql.SqlPrimaryKeyGene import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import java.sql.Date /** * Created by jgaleotti on 29-May-19. */ class SqlDateColumnTest : ExtractTestBasePostgres() { override fun getSchemaLocation() = "/sql_schema/date_column_db.sql" @Test fun testExtraction() { val schema = SchemaExtractor.extract(connection) val builder = SqlInsertBuilder(schema) val actions = builder.createSqlInsertionAction("logins", setOf("userId", "lastLogin")) val genes = actions[0].seeTopGenes() assertEquals(2, genes.size) assertTrue(genes[0] is SqlPrimaryKeyGene) assertTrue(genes[1] is DateGene) } @Test fun testInsertion() { val schema = SchemaExtractor.extract(connection) val builder = SqlInsertBuilder(schema) val actions = builder.createSqlInsertionAction("logins", setOf("userId", "lastLogin")) val genes = actions[0].seeTopGenes() val userIdValue = ((genes[0] as SqlPrimaryKeyGene).gene as IntegerGene).value val lastLoginDayValue = (genes[1] as DateGene).day.value val lastLoginMonthValue = (genes[1] as DateGene).month.value val lastLoginYearValue = (genes[1] as DateGene).year.value val query = "Select * from logins where userId=%s".format(userIdValue) val queryResultBeforeInsertion = SqlScriptRunner.execCommand(connection, query) assertTrue(queryResultBeforeInsertion.isEmpty) val dbCommandDto = DbActionTransformer.transform(actions) SqlScriptRunner.execInsert(connection, dbCommandDto.insertions) val queryResultAfterInsertion = SqlScriptRunner.execCommand(connection, query) assertFalse(queryResultAfterInsertion.isEmpty) val row = queryResultAfterInsertion.seeRows()[0] val lastLoginActualValue = row.getValueByName("lastLogin") assertTrue(lastLoginActualValue is Date) lastLoginActualValue as Date assertEquals(lastLoginYearValue, lastLoginActualValue.toLocalDate().year) assertEquals(lastLoginMonthValue, lastLoginActualValue.toLocalDate().monthValue) assertEquals(lastLoginDayValue, lastLoginActualValue.toLocalDate().dayOfMonth) } }
lgpl-3.0
RSDT/Japp
app/src/main/java/nl/rsdt/japp/jotial/auth/Authentication.kt
1
3757
package nl.rsdt.japp.jotial.auth import android.app.Activity import android.content.Intent import com.google.gson.annotations.SerializedName import nl.rsdt.japp.R import nl.rsdt.japp.application.Japp import nl.rsdt.japp.application.JappPreferences import nl.rsdt.japp.application.activities.LoginActivity import nl.rsdt.japp.jotial.net.apis.AuthApi import retrofit2.Call import retrofit2.Callback /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 13-7-2016 * Description... */ class Authentication : Callback<Authentication.KeyObject> { private var callback: OnAuthenticationCompletedCallback? = null private var username: String = "" private var password: String = "" fun executeAsync() { val api = Japp.getApi(AuthApi::class.java) api.login(LoginBody(username, password)).enqueue(this) } override fun onResponse(call: Call<KeyObject>, response: retrofit2.Response<KeyObject>) { if (response.code() == 200) { val key = response.body()?.key /** * Change the key in the release_preferences. */ val pEditor = JappPreferences.visiblePreferences.edit() pEditor.putString(JappPreferences.ACCOUNT_KEY, key) pEditor.apply() callback?.onAuthenticationCompleted(AuthenticationResult(key, 200, Japp.getString(R.string.login_succes))) } else { val message: String = if (response.code() == 404) { Japp.getString(R.string.wrong_data) } else { Japp.getString(R.string.error_on_login) } callback?.onAuthenticationCompleted(AuthenticationResult("", response.code(), message)) } } override fun onFailure(call: Call<KeyObject>, t: Throwable) { callback?.onAuthenticationCompleted(AuthenticationResult("", 0, Japp.getString(R.string.error_on_login))) } class AuthenticationResult(val key: String?, val code: Int, val message: String) { val isSucceeded: Boolean get() = key != null && !key.isEmpty() } /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 2-9-2016 * Description... */ inner class LoginBody(private val gebruiker: String, private val ww: String) inner class KeyObject { @SerializedName("SLEUTEL") public val key: String = "" } inner class ValidateObject { @SerializedName("exists") private val exists: Boolean = false fun exists(): Boolean { return exists } } class Builder { internal var buffer = Authentication() fun setCallback(callback: OnAuthenticationCompletedCallback): Builder { buffer.callback = callback return this } fun setUsername(username: String): Builder { buffer.username = username return this } fun setPassword(password: String): Builder { buffer.password = AeSimpleSHA1.trySHA1(password) return this } fun create(): Authentication { return buffer } } interface OnAuthenticationCompletedCallback { fun onAuthenticationCompleted(result: AuthenticationResult) } companion object { val REQUEST_TAG = "Authentication" /** * TODO: don't use final here */ fun validate(activity: Activity) { val api = Japp.getApi(AuthApi::class.java) } fun startLoginActivity(activity: Activity) { val intent = Intent(activity, LoginActivity::class.java) activity.startActivity(intent) activity.finish() } } }
apache-2.0
square/sqldelight
sample/android/src/main/java/com/example/sqldelight/hockey/ui/TeamRow.kt
1
694
package com.example.sqldelight.hockey.ui import android.content.Context import android.util.AttributeSet import android.widget.LinearLayout import android.widget.TextView import com.example.sqldelight.hockey.R import com.example.sqldelight.hockey.data.Team import com.example.sqldelight.hockey.platform.defaultFormatter class TeamRow( context: Context, attrs: AttributeSet ) : LinearLayout(context, attrs) { fun populate(team: Team) { findViewById<TextView>(R.id.team_name).text = team.name findViewById<TextView>(R.id.coach_name).text = team.coach findViewById<TextView>(R.id.founded).text = context.getString(R.string.founded, defaultFormatter.format(team.founded)) } }
apache-2.0
EMResearch/EvoMaster
e2e-tests/spring-rest-openapi-v3/src/main/kotlin/com/foo/rest/examples/spring/openapi/v3/wiremock/harvestresponse/WmHarvestResponseApplication.kt
1
575
package com.foo.rest.examples.spring.openapi.v3.wiremock.harvestresponse import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration @SpringBootApplication(exclude = [SecurityAutoConfiguration::class]) open class WmHarvestResponseApplication { companion object { @JvmStatic fun main(args: Array<String>) { SpringApplication.run(WmHarvestResponseApplication::class.java, *args) } } }
lgpl-3.0
vjache/klips
src/test/java/org/klips/engine/rete/MyEdge.kt
1
449
package org.klips.engine.rete class MyEdge<A,B,C>(val triple:Triple<A,B,C>){ constructor(a:A, b:B, c:C):this(Triple(a,b,c)) override fun equals(other: Any?): Boolean { if (other !is MyEdge<*, *, *>) return false return other.triple.equals(this.triple) } override fun hashCode(): Int { return MyEdge::class.java.hashCode() + triple.hashCode() } override fun toString() = triple.third.toString() }
apache-2.0
KotlinPorts/pooled-client
postgresql-async/src/main/kotlin/com/github/mauricio/async/db/postgresql/parsers/NoticeParser.kt
2
1051
/* * Copyright 2013 Maurício Linhares * * Maurício Linhares licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.github.mauricio.async.db.postgresql.parsers import com.github.mauricio.async.db.postgresql.messages.backend.ServerMessage import com.github.mauricio.async.db.postgresql.messages.backend.NoticeMessage import java.nio.charset.Charset class NoticeParser(charset: Charset) : InformationParser(charset) { override fun createMessage(fields: Map<Char, String>): ServerMessage = NoticeMessage(fields) }
apache-2.0
VerifAPS/verifaps-lib
util/src/main/kotlin/edu/kit/iti/formal/util/CodeWriter.kt
1
2355
package edu.kit.iti.formal.util import java.io.StringWriter import java.io.Writer /** * CodeWriter class. * * @author weigla (15.06.2014) * @version 2 */ open class CodeWriter(var stream: Writer = StringWriter()) : Appendable by stream { var uppercaseKeywords = true var ident = " " protected var identDepth = 0 fun write(x: String): CodeWriter { stream.write(x) return this } fun appendIdent(): CodeWriter { for (i in 0 until identDepth) { write(ident) } return this } fun increaseIndent(): CodeWriter { identDepth++ return this } fun decreaseIndent(): CodeWriter { identDepth = Math.max(identDepth - 1, 0) return this } open fun keyword(keyword: String): CodeWriter { return printf(if (uppercaseKeywords) keyword.toUpperCase() else keyword.toLowerCase()) } fun nl(): CodeWriter { write("\n") appendIdent() return this } fun println(arg: String): CodeWriter = print(arg).nl() fun print(args: String): CodeWriter = write(args) fun print(vararg args: Any): CodeWriter { args.forEach { write(it.toString()) } return this } fun printf(fmt: String, vararg args: Any): CodeWriter { return write(String.format(fmt, *args)) } fun block(text: String = "", nl: Boolean = false, function: CodeWriter.() -> Unit): CodeWriter { printf(text) if (nl) nl() increaseIndent() function() decreaseIndent() if (nl) nl() return this } fun appendReformat(text: String): CodeWriter { text.splitToSequence('\n').forEach { nl().printf(it) } return this } fun cblock(head: String, tail: String, function: CodeWriter.() -> Unit): CodeWriter { printf(head) increaseIndent() nl() function() decreaseIndent() nl() printf(tail) return this } operator fun CharSequence.unaryPlus(): CharSequence { [email protected](this@unaryPlus) return this@unaryPlus } companion object{ fun with(fn : CodeWriter.() -> Unit) : String { val cw = CodeWriter() fn(cw) return cw.stream.toString() } } }
gpl-3.0
rharter/windy-city-devcon-android
app/src/main/kotlin/com/gdgchicagowest/windycitydevcon/features/speakerlist/DividerItemDecoration.kt
1
1610
package com.gdgchicagowest.windycitydevcon.features.sessions import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import android.support.v7.widget.RecyclerView import android.view.View internal class DividerItemDecoration(private val context: Context) : RecyclerView.ItemDecoration() { private val divider: Drawable init { val a = context.obtainStyledAttributes(intArrayOf(android.R.attr.listDivider)) divider = a.getDrawable(0) a.recycle() } override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { val childCount = parent.childCount for (i in 0..childCount) { val view = parent.getChildAt(i) if (view != null) { val holder = parent.getChildViewHolder(view) if (holder.adapterPosition != 0) { val left = 0 val top = holder.itemView.top val right = parent.width val bottom = top + divider.intrinsicHeight divider.setBounds(left, top, right, bottom) divider.draw(c) } } } } override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { val holder = parent.getChildViewHolder(view) if (holder is SessionAdapter.ViewHolder) { if (holder.adapterPosition != 0) { outRect.set(0, divider.intrinsicHeight, 0, 0) } } } }
apache-2.0
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/teams/details/TeamDetailsFragment.kt
1
9885
package ca.josephroque.bowlingcompanion.teams.details import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.Android import ca.josephroque.bowlingcompanion.common.fragments.BaseFragment import ca.josephroque.bowlingcompanion.common.fragments.ListFragment import ca.josephroque.bowlingcompanion.common.interfaces.IFloatingActionButtonHandler import ca.josephroque.bowlingcompanion.common.interfaces.IIdentifiable import ca.josephroque.bowlingcompanion.database.DatabaseManager import ca.josephroque.bowlingcompanion.games.GameControllerFragment import ca.josephroque.bowlingcompanion.games.SeriesProvider import ca.josephroque.bowlingcompanion.leagues.League import ca.josephroque.bowlingcompanion.series.Series import ca.josephroque.bowlingcompanion.statistics.interfaces.IStatisticsContext import ca.josephroque.bowlingcompanion.statistics.provider.StatisticsProvider import ca.josephroque.bowlingcompanion.teams.Team import ca.josephroque.bowlingcompanion.teams.teammember.TeamMember import ca.josephroque.bowlingcompanion.teams.teammember.TeamMemberDialog import ca.josephroque.bowlingcompanion.teams.teammember.TeamMembersListFragment import ca.josephroque.bowlingcompanion.utils.Analytics import ca.josephroque.bowlingcompanion.utils.BCError import ca.josephroque.bowlingcompanion.utils.safeLet import kotlinx.android.synthetic.main.view_screen_header.view.* import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.Deferred import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.launch /** * Copyright (C) 2018 Joseph Roque * * A fragment representing the details of a single team and its members. */ class TeamDetailsFragment : BaseFragment(), IFloatingActionButtonHandler, ListFragment.ListFragmentDelegate, TeamMemberDialog.TeamMemberDialogDelegate, TeamMembersListFragment.TeamMemberListFragmentDelegate, IStatisticsContext { companion object { @Suppress("unused") private const val TAG = "TeamDetailsFragment" private const val ARG_TEAM = "${TAG}_team" fun newInstance(team: Team): TeamDetailsFragment { val fragment = TeamDetailsFragment() fragment.arguments = Bundle().apply { putParcelable(ARG_TEAM, team) } return fragment } } override val statisticsProviders: List<StatisticsProvider> by lazy { val team = team return@lazy if (team != null) { arrayListOf(StatisticsProvider.TeamStatistics(team)) } else { emptyList<StatisticsProvider>() } } private var team: Team? = null private var allTeamMembersReady: Boolean = false set(value) { if (field != value) { field = value launch(Android) { fabProvider?.invalidateFab() } } } // MARK: Lifecycle functions override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { team = arguments?.getParcelable(ARG_TEAM) val view = inflater.inflate(R.layout.fragment_team_details, container, false) setupHeader(view) val team = team if (savedInstanceState == null && team != null) { val fragment = TeamMembersListFragment.newInstance(team) childFragmentManager.beginTransaction().apply { add(R.id.fragment_container, fragment) commit() } } return view } override fun onStart() { super.onStart() fabProvider?.invalidateFab() } // MARK: BaseFragment override fun updateToolbarTitle() { team?.let { navigationActivity?.setToolbarTitle(it.name) } } // MARK: IFloatingActionButtonHandler override fun getFabImage(): Int? = if (allTeamMembersReady) R.drawable.ic_ball else null override fun onFabClick() { safeLet(context, team) { context, team -> val needsNewPracticeSeries = team.members.any { it.league?.isPractice == true && it.series == null } if (needsNewPracticeSeries) { League.showPracticeGamesPicker(context, ::launchAttemptToBowl) } else { launchAttemptToBowl() } } } // MARK: ListFragmentDelegate override fun onItemSelected(item: IIdentifiable, longPress: Boolean) { if (item is TeamMember) { val fragment = TeamMemberDialog.newInstance(item) fragmentNavigation?.pushDialogFragment(fragment) } } override fun onItemDeleted(item: IIdentifiable) { // Intentionally left blank } // MARK: TeamMemberDialogDelegate override fun onFinishTeamMember(teamMember: TeamMember) { childFragmentManager.fragments .filter { it != null && it.isVisible } .forEach { val list = it as? TeamMembersListFragment ?: return list.refreshList(teamMember) team = team?.replaceTeamMember(teamMember) } } // MARK: TeamMemberListFragmentDelegate override fun onTeamMembersReadyChanged(ready: Boolean) { allTeamMembersReady = ready } override fun onTeamMembersReordered(order: List<Long>) { team?.let { team = Team(it.id, it.name, it.members, order) } Analytics.trackReorderTeamMembers() } // MARK: Private functions private fun setupHeader(rootView: View) { rootView.tv_header_title.setText(R.string.team_members) rootView.tv_header_caption.setText(R.string.team_members_select_league) } private fun launchAttemptToBowl(practiceNumberOfGames: Int = 1) { val context = context ?: return launch(Android) { val error = attemptToBowl(practiceNumberOfGames).await() if (error != null) { error.show(context) return@launch } val team = [email protected] if (team != null) { val fragment = GameControllerFragment.newInstance(SeriesProvider.TeamSeries(team)) fragmentNavigation?.pushFragment(fragment) } else { BCError().show(context) } } } private fun attemptToBowl(practiceNumberOfGames: Int): Deferred<BCError?> { return async(CommonPool) { val context = [email protected] ?: return@async BCError() val team = [email protected] ?: return@async BCError() if (allTeamMembersReady) { allTeamMembersReady = false val teamMemberSeries: MutableMap<TeamMember, Series> = HashMap() // Create series in the database for each team member, if one does not exist, // or retrieve the existing series if it does. val database = DatabaseManager.getWritableDatabase(context).await() try { team.members.forEach { val league = it.league!! when { league.isEvent -> { val eventSeries = league.fetchSeries(context).await() assert(eventSeries.size == 1) teamMemberSeries[it] = eventSeries.first() } it.series == null -> { if (!database.inTransaction()) { database.beginTransaction() } val (newSeries, seriesError) = league.createNewSeries( context = context, openDatabase = database, numberOfPracticeGamesOverride = practiceNumberOfGames ).await() if (newSeries != null) { teamMemberSeries[it] = newSeries } else if (seriesError != null) { return@async seriesError } } else -> { teamMemberSeries[it] = it.series } } } if (database.inTransaction()) { database.setTransactionSuccessful() } } finally { if (database.inTransaction()) { database.endTransaction() } } // Replace immutable [TeamMember] instances with updated series val membersWithSeries = team.members.map { return@map TeamMember( teamId = it.teamId, bowlerName = it.bowlerName, bowlerId = it.bowlerId, league = it.league, series = teamMemberSeries[it] ) } // Replace team with updated members [email protected] = Team( id = team.id, name = team.name, members = membersWithSeries, initialOrder = team.order ) } return@async null } } }
mit
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/overall/StrikeMiddleHitsStatistic.kt
1
2429
package ca.josephroque.bowlingcompanion.statistics.impl.overall import android.os.Parcel import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator import ca.josephroque.bowlingcompanion.games.Game import ca.josephroque.bowlingcompanion.games.lane.arePinsCleared import ca.josephroque.bowlingcompanion.games.lane.isMiddleHit import ca.josephroque.bowlingcompanion.statistics.PercentageStatistic import ca.josephroque.bowlingcompanion.statistics.StatisticsCategory import ca.josephroque.bowlingcompanion.statistics.immutable.StatFrame /** * Copyright (C) 2018 Joseph Roque * * Percentage of middle hits which were strikes */ class StrikeMiddleHitsStatistic(override var numerator: Int = 0, override var denominator: Int = 0) : PercentageStatistic { companion object { @Suppress("unused") @JvmField val CREATOR = parcelableCreator(::StrikeMiddleHitsStatistic) const val Id = R.string.statistic_strike_middle_hits } override val titleId = Id override val id = Id.toLong() override val category = StatisticsCategory.Overall override val secondaryGraphDataLabelId = R.string.statistic_total_shots_at_middle override fun isModifiedBy(frame: StatFrame) = true // MARK: Statistic override fun modify(frame: StatFrame) { // This function has a similar construction to `FirstBallStatistic.modify(StatFrame) // and the two should remain aligned // Every frame adds 1 possible hit denominator += if (frame.pinState[0].isMiddleHit) 1 else 0 numerator += if (frame.pinState[0].arePinsCleared) 1 else 0 if (frame.zeroBasedOrdinal == Game.LAST_FRAME) { // In the 10th frame, for each time the first or second ball cleared the lane, // check if the statistic is modified if (frame.pinState[0].arePinsCleared) { denominator += if (frame.pinState[1].isMiddleHit) 1 else 0 numerator += if (frame.pinState[1].arePinsCleared) 1 else 0 } if (frame.pinState[1].arePinsCleared) { denominator += if (frame.pinState[2].isMiddleHit) 1 else 0 numerator += if (frame.pinState[2].arePinsCleared) 1 else 0 } } } // MARK: Constructors private constructor(p: Parcel): this(numerator = p.readInt(), denominator = p.readInt()) }
mit
yuzumone/bergamio
app/src/main/kotlin/net/yuzumone/bergamio/activity/AuthActivity.kt
1
2459
package net.yuzumone.bergamio.activity import android.content.Intent import android.databinding.DataBindingUtil import android.net.Uri import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.Toast import net.yuzumone.bergamio.BuildConfig import net.yuzumone.bergamio.R import net.yuzumone.bergamio.databinding.ActivityAuthBinding import net.yuzumone.bergamio.util.PreferenceUtil import java.util.regex.Pattern class AuthActivity : AppCompatActivity() { private lateinit var binding: ActivityAuthBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_auth) setSupportActionBar(binding.toolbar) val clientId = BuildConfig.DEVELOPER_ID val redirect = BuildConfig.REDIRECT_URI val uri = "https://api.iijmio.jp/mobile/d/v1/authorization/" + "?response_type=token&state=state&client_id=$clientId&redirect_uri=$redirect" binding.buttonAuth.setOnClickListener { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri)) startActivity(intent) } } override fun onNewIntent(intent: Intent?) { if (intent == null || intent.data == null) { return } val fragment = intent.data.fragment val token = getToken(fragment) val expire = getExpire(fragment) if (token != "" && expire != 0L) { storeData(token, expire) val mainActivityIntent = Intent(this, MainActivity::class.java) startActivity(mainActivityIntent) finish() } else { Toast.makeText(this, getString(R.string.auth_miss), Toast.LENGTH_LONG).show() } } private fun getToken(string: String): String { val p = Pattern.compile("(access_token=)(\\w+)") val m = p.matcher(string) return if (m.find()) { m.group(2) } else { "" } } private fun getExpire(string: String): Long { val p = Pattern.compile("(expires_in=)(\\d+)") val m = p.matcher(string) return if (m.find()) { m.group(2).toLong() } else { 0L } } private fun storeData(token: String, expire: Long) { val pref = PreferenceUtil(this) pref.token = token pref.expire = expire } }
apache-2.0
AsynkronIT/protoactor-kotlin
proto-remote/src/main/kotlin/actor/proto/remote/Remote.kt
1
3392
package actor.proto.remote import actor.proto.EventStream import actor.proto.MessageEnvelope import actor.proto.PID import actor.proto.ProcessRegistry import actor.proto.Props import actor.proto.fromProducer import actor.proto.mailbox.newMpscUnboundedArrayMailbox import actor.proto.requestAwait import actor.proto.send import actor.proto.spawnNamed import io.grpc.Server import io.grpc.netty.NettyServerBuilder import mu.KotlinLogging import java.time.Duration import java.util.concurrent.TimeUnit private val logger = KotlinLogging.logger {} object Remote { private lateinit var _server: Server private val Kinds: HashMap<String, Props> = HashMap() lateinit var endpointManagerPid: PID lateinit var activatorPid: PID fun getKnownKinds(): Set<String> = Kinds.keys fun registerKnownKind(kind: String, props: Props) { Kinds.put(kind, props) } fun getKnownKind(kind: String): Props { return Kinds.getOrElse(kind) { throw Exception("No Props found for kind '$kind'") } } fun start(hostname: String, port: Int, config: RemoteConfig = RemoteConfig()) { ProcessRegistry.registerHostResolver { pid -> RemoteProcess(pid) } val serverBuilder = NettyServerBuilder.forPort(port).addService(EndpointReader()) config.keepAliveTime?.let { serverBuilder.permitKeepAliveTime(config.keepAliveTime / 2, TimeUnit.MILLISECONDS) } config.keepAliveWithoutCalls?.let { serverBuilder.permitKeepAliveWithoutCalls(config.keepAliveWithoutCalls) } _server = serverBuilder.build().start() val boundPort: Int = _server.port val boundAddress: String = "$hostname:$boundPort" val address: String = "${config.advertisedHostname ?: hostname}:${config.advertisedPort ?: boundPort}" ProcessRegistry.address = address spawnEndpointManager(config) spawnActivator() logger.info("Starting Proto.Actor server on $boundAddress") } private fun spawnActivator() { val props = fromProducer { Activator() } activatorPid = spawnNamed(props, "activator") } private fun spawnEndpointManager(config: RemoteConfig) { val props = fromProducer { EndpointManager(config) } .withMailbox { newMpscUnboundedArrayMailbox(200) } endpointManagerPid = spawnNamed(props, "endpointmanager") EventStream.subscribe({ if (it is EndpointTerminatedEvent) { send(endpointManagerPid, it) } }) } fun activatorForAddress(address: String): PID = PID(address, "activator") suspend fun spawn(address: String, kind: String, timeout: Duration): PID = spawnNamed(address, "", kind, timeout) suspend fun spawnNamed(address: String, name: String, kind: String, timeout: Duration): PID { val activator: PID = activatorForAddress(address) val req = ActorPidRequest(kind, name) val res = requestAwait<RemoteProtos.ActorPidResponse>(activator, req, timeout) return res.pid } fun sendMessage(pid: PID, msg: Any, serializerId: Int) { val (message, sender) = when (msg) { is MessageEnvelope -> Pair(msg.message, msg.sender) else -> Pair(msg, null) } val env: RemoteDeliver = RemoteDeliver(message, pid, sender, serializerId) send(endpointManagerPid, env) } }
apache-2.0
RP-Kit/RPKit
bukkit/rpk-monsters-bukkit/src/main/kotlin/com/rpkit/monsters/bukkit/listener/EntityDamageByEntityListener.kt
1
5684
/* * 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.monsters.bukkit.listener import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.expression.RPKExpressionService import com.rpkit.core.service.Services import com.rpkit.monsters.bukkit.RPKMonstersBukkit import com.rpkit.monsters.bukkit.monsterlevel.RPKMonsterLevelService import com.rpkit.monsters.bukkit.monsterstat.RPKMonsterStatServiceImpl import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import com.rpkit.stats.bukkit.stat.RPKStatService import com.rpkit.stats.bukkit.stat.RPKStatVariableService import org.bukkit.entity.Arrow import org.bukkit.entity.LivingEntity import org.bukkit.entity.Player import org.bukkit.entity.Projectile import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.entity.EntityDamageByEntityEvent class EntityDamageByEntityListener(private val plugin: RPKMonstersBukkit) : Listener { @EventHandler fun onEntityDamageByEntity(event: EntityDamageByEntityEvent) { if (plugin.config.getBoolean("monsters.${event.entityType}.ignored", plugin.config.getBoolean("monsters.default.ignored"))) { return } var attacker: LivingEntity? = null var defender: LivingEntity? = null val damager = event.damager val attackType = if (damager is Projectile) { val shooter = damager.shooter if (shooter is LivingEntity) { attacker = shooter } if (damager is Arrow) { "bow" } else { "projectile" } } else { if (damager is LivingEntity) { attacker = damager } "melee" } val entity = event.entity if (entity is LivingEntity) { defender = entity } val attack = if (attacker != null) { if (attacker is Player) { getPlayerStat(attacker, attackType, "attack") } else { getEntityStat(attacker, attackType, "attack") } } else { 1.0 } val defence = if (defender != null) { if (defender is Player) { getPlayerStat(defender, attackType, "defence") } else { getEntityStat(defender, attackType, "defence") } } else { 1.0 } if (attacker != null && defender != null) { event.damage = getDamage(event.damage, attack, defence) } if (defender != null) { if (defender !is Player) { val monsterStatService = Services[RPKMonsterStatServiceImpl::class.java] ?: return monsterStatService.setMonsterNameplate(defender, health = defender.health - event.finalDamage) } } } private fun getPlayerStat(player: Player, type: String, stat: String): Double { val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return 0.0 val characterService = Services[RPKCharacterService::class.java] ?: return 0.0 val statService = Services[RPKStatService::class.java] ?: return 0.0 val statVariableService = Services[RPKStatVariableService::class.java] ?: return 0.0 val expressionService = Services[RPKExpressionService::class.java] ?: return 0.0 val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(player) ?: return 0.0 val character = characterService.getPreloadedActiveCharacter(minecraftProfile) ?: return 0.0 val expression = expressionService.createExpression(plugin.config.getString("stats.$type.$stat") ?: return 0.0) val statVariables = statVariableService.statVariables return expression.parseDouble(statService.stats.associate { it.name.value to it.get(character, statVariables) }) ?: 0.0 } private fun getEntityStat(entity: LivingEntity, type: String, stat: String): Double { val monsterLevelService = Services[RPKMonsterLevelService::class.java] ?: return 0.0 val expressionService = Services[RPKExpressionService::class.java] ?: return 0.0 val expression = expressionService.createExpression(plugin.config.getString("monsters.${entity.type}.stats.$type.$stat") ?: plugin.config.getString("monsters.default.stats.$type.$stat") ?: return 0.0) return expression.parseDouble(mapOf( "level" to monsterLevelService.getMonsterLevel(entity).toDouble(), "monsterType" to "\"${entity.type}\"" )) ?: 0.0 } private fun getDamage(originalDamage: Double, attack: Double, defence: Double): Double { val expressionService = Services[RPKExpressionService::class.java] ?: return 0.0 val expression = expressionService.createExpression(plugin.config.getString("damage") ?: return 0.0) return expression.parseDouble(mapOf( "damage" to originalDamage, "attack" to attack, "defence" to defence )) ?: 0.0 } }
apache-2.0
afollestad/icon-request
library/src/main/java/com/afollestad/iconrequest/extensions/Logger.kt
1
246
/* * Licensed under Apache-2.0 * * Designed and developed by Aidan Follestad (@afollestad) */ package com.afollestad.iconrequest.extensions import android.util.Log fun String.log( tag: String? = null ) = Log.d(tag ?: "IconRequest", this)
apache-2.0
cketti/k-9
app/ui/legacy/src/main/java/com/fsck/k9/ui/account/AccountFallbackImageProvider.kt
1
803
package com.fsck.k9.ui.account import android.content.Context import android.graphics.drawable.Drawable import androidx.core.content.ContextCompat import androidx.core.graphics.BlendModeColorFilterCompat import androidx.core.graphics.BlendModeCompat import com.fsck.k9.ui.R /** * Provides a [Drawable] for the account using the account's color as background color. */ class AccountFallbackImageProvider(private val context: Context) { fun getDrawable(color: Int): Drawable { val drawable = ContextCompat.getDrawable(context, R.drawable.drawer_account_fallback) ?: error("Error loading drawable") return drawable.mutate().apply { colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(color, BlendModeCompat.DST_OVER) } } }
apache-2.0
zhengjiong/ZJ_KotlinStudy
src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/55.HelloKotlin-函数式编程3.kt
1
736
package com.zj.example.kotlin.shengshiyuan.helloworld /** * * CreateTime: 18/5/29 10:25 * @author 郑炯 */ fun main(args: Array<String>) { val arr1 = arrayOf("hello", "world", "helloworld", "welcome") //输出所有包含"h"的字符串 arr1.filter { it.contains("h") }.forEach { println(it) } println("---------------------------------------------") //输出长度大于5的字符串 arr1.filter { it.length > 5 }.forEach { println(it) } println("---------------------------------------------") //将以字母d结尾的字符串,转换成大写的并输出 arr1.filter { it.endsWith("d", ignoreCase = true) }.map { it.toUpperCase() }.forEach { println(it) } } class HelloKotlin55 { }
mit
quarck/CalendarNotification
app/src/main/java/com/github/quarck/calnotify/dismissedeventsstorage/DismissedEventsStorageImplInterface.kt
1
1640
// // Calendar Notifications Plus // Copyright (C) 2016 Sergey Parshin ([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, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // package com.github.quarck.calnotify.dismissedeventsstorage import android.database.sqlite.SQLiteDatabase import com.github.quarck.calnotify.calendar.EventAlertRecord interface DismissedEventsStorageImplInterface { fun createDb(db: SQLiteDatabase) fun addEventImpl(db: SQLiteDatabase, type: EventDismissType, changeTime: Long, event: EventAlertRecord) fun addEventsImpl(db: SQLiteDatabase, type: EventDismissType, changeTime: Long, events: Collection<EventAlertRecord>) fun deleteEventImpl(db: SQLiteDatabase, entry: DismissedEventAlertRecord) fun deleteEventImpl(db: SQLiteDatabase, event: EventAlertRecord) fun clearHistoryImpl(db: SQLiteDatabase) fun getEventsImpl(db: SQLiteDatabase): List<DismissedEventAlertRecord> fun dropAll(db: SQLiteDatabase) }
gpl-3.0
sugarmanz/Pandroid
app/src/main/java/com/jeremiahzucker/pandroid/ui/base/BasePresenter.kt
1
284
package com.jeremiahzucker.pandroid.ui.base /** * Created by Jeremiah Zucker on 8/28/2017. */ interface BasePresenter<T> { /** * Binds presenter with View. */ fun attach(view: T) /** * Unbinds present when View is destroyed. */ fun detach() }
mit
JakeWharton/RxBinding
rxbinding/src/main/java/com/jakewharton/rxbinding4/widget/AdapterDataChangeObservable.kt
1
1597
@file:JvmName("RxAdapter") @file:JvmMultifileClass package com.jakewharton.rxbinding4.widget import android.database.DataSetObserver import android.widget.Adapter import androidx.annotation.CheckResult import com.jakewharton.rxbinding4.InitialValueObservable import io.reactivex.rxjava3.core.Observer import io.reactivex.rxjava3.android.MainThreadDisposable import com.jakewharton.rxbinding4.internal.checkMainThread /** * Create an observable of data change events for `adapter`. * * *Note:* A value will be emitted immediately on subscribe. */ @CheckResult fun <T : Adapter> T.dataChanges(): InitialValueObservable<T> { return AdapterDataChangeObservable(this) } private class AdapterDataChangeObservable<T : Adapter>( private val adapter: T ) : InitialValueObservable<T>() { override fun subscribeListener(observer: Observer<in T>) { if (!checkMainThread(observer)) { return } val disposableDataSetObserver = ObserverDisposable(initialValue, observer) initialValue.registerDataSetObserver(disposableDataSetObserver.dataSetObserver) observer.onSubscribe(disposableDataSetObserver) } override val initialValue get() = adapter private class ObserverDisposable<T : Adapter>( private val adapter: T, observer: Observer<in T> ) : MainThreadDisposable() { @JvmField val dataSetObserver = object : DataSetObserver() { override fun onChanged() { if (!isDisposed) { observer.onNext(adapter) } } } override fun onDispose() { adapter.unregisterDataSetObserver(dataSetObserver) } } }
apache-2.0
nfrankel/kaadin
kaadin-core/src/test/kotlin/ch/frankel/kaadin/datainput/TextAreaTest.kt
1
2302
/* * Copyright 2016 Nicolas Fränkel * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.frankel.kaadin.datainput import ch.frankel.kaadin.* import com.vaadin.data.util.* import com.vaadin.ui.* import org.assertj.core.api.Assertions.assertThat import org.testng.annotations.Test class TextAreaTest { @Test fun `text area should be added to layout`() { val layout = horizontalLayout { textArea() } assertThat(layout.componentCount).isEqualTo(1) val component = layout.getComponent(0) assertThat(component).isNotNull.isInstanceOf(TextArea::class.java) } @Test(dependsOnMethods = ["text area should be added to layout"]) fun `text area value can be initialized`() { val text = "Hello world" val layout = horizontalLayout { textArea(value = text) } val component = layout.getComponent(0) as TextArea assertThat(component.value).isEqualTo(text) } @Test(dependsOnMethods = ["text area should be added to layout"]) fun `text area value can be initialized via property`() { val text = "Hello world" val property = ObjectProperty(text) val layout = horizontalLayout { textArea(dataSource = property) } val component = layout.getComponent(0) as TextArea assertThat(component.value).isEqualTo(text) } @Test(dependsOnMethods = ["text area should be added to layout"]) fun `text area should be configurable`() { val text = "Hello world" val layout = horizontalLayout { textArea { value = text } } val component = layout.getComponent(0) as TextArea assertThat(component.value).isEqualTo(text) } }
apache-2.0
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/modules/AutoroleModule.kt
1
1422
package net.perfectdreams.loritta.morenitta.modules import net.perfectdreams.loritta.morenitta.utils.extensions.filterOnlyGiveableRoles import net.dv8tion.jda.api.entities.Member import net.perfectdreams.loritta.morenitta.dao.servers.moduleconfigs.AutoroleConfig import java.util.concurrent.TimeUnit object AutoroleModule { fun giveRoles(member: Member, autoroleConfig: AutoroleConfig) { val guild = member.guild // Transform all role IDs to a role list val roles = autoroleConfig.roles .asSequence() .mapNotNull { guild.getRoleById(it) } .distinct() .filterOnlyGiveableRoles() .toList() val filteredRoles = roles.filter { !member.roles.contains(it) } if (filteredRoles.isNotEmpty()) { if (filteredRoles.size == 1) { if (autoroleConfig.giveRolesAfter != null) guild.addRoleToMember(member, filteredRoles[0]).reason("Autorole").queueAfter(autoroleConfig.giveRolesAfter!!, TimeUnit.SECONDS) else guild.addRoleToMember(member, filteredRoles[0]).reason("Autorole").queue() } else { if (autoroleConfig.giveRolesAfter != null) guild.modifyMemberRoles(member, member.roles.toMutableList().apply { this.addAll(filteredRoles) }).reason("Autorole").queueAfter(autoroleConfig.giveRolesAfter!!, TimeUnit.SECONDS) else guild.modifyMemberRoles(member, member.roles.toMutableList().apply { this.addAll(filteredRoles) }).reason("Autorole").queue() } } } }
agpl-3.0
owntracks/android
project/app/src/main/java/org/owntracks/android/location/LocationAvailability.kt
1
104
package org.owntracks.android.location data class LocationAvailability(val locationAvailable: Boolean)
epl-1.0
shyiko/ktlint
ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/internal/ThreadSafeEditorConfigCache.kt
1
1062
package com.pinterest.ktlint.core.internal import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.read import kotlin.concurrent.write import org.ec4j.core.Cache import org.ec4j.core.EditorConfigLoader import org.ec4j.core.Resource import org.ec4j.core.model.EditorConfig /** * In-memory [Cache] implementation that could be safely accessed from any [Thread]. */ internal class ThreadSafeEditorConfigCache : Cache { private val readWriteLock = ReentrantReadWriteLock() private val inMemoryMap = HashMap<Resource, EditorConfig>() override fun get( editorConfigFile: Resource, loader: EditorConfigLoader ): EditorConfig { readWriteLock.read { return inMemoryMap[editorConfigFile] ?: readWriteLock.write { val result = loader.load(editorConfigFile) inMemoryMap[editorConfigFile] = result result } } } fun clear() = readWriteLock.write { inMemoryMap.clear() } }
mit
vanniktech/Emoji
emoji/src/androidMain/kotlin/com/vanniktech/emoji/internal/EmojiSearchPopup.kt
1
3035
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.vanniktech.emoji.internal import android.graphics.Bitmap import android.graphics.Point import android.graphics.drawable.BitmapDrawable import android.view.Gravity import android.view.View import android.view.View.MeasureSpec import android.view.WindowManager import android.widget.EditText import android.widget.PopupWindow import com.vanniktech.emoji.Emoji import com.vanniktech.emoji.EmojiTheming import com.vanniktech.emoji.R import com.vanniktech.emoji.search.SearchEmojiResult internal fun interface EmojiSearchDelegate { fun onEmojiClicked(emoji: Emoji) } internal class EmojiSearchPopup( private val rootView: View, private val editText: EditText, private val theming: EmojiTheming, ) { private var popupWindow: PopupWindow? = null internal fun show( emojis: List<SearchEmojiResult>, delegate: EmojiSearchDelegate?, ) { if (emojis.isNotEmpty()) { val context = editText.context val recyclerView = View.inflate(context, R.layout.emoji_popup_search, null) as MaxHeightSearchRecyclerView recyclerView.tint(theming) val adapter = EmojiAdapter( theming = theming, emojiSearchDialogDelegate = { delegate?.onEmojiClicked(it) dismiss() }, ) recyclerView.adapter = adapter val editTextLocation = Utils.locationOnScreen(editText) adapter.update(emojis, marginStart = editTextLocation.x) val resources = context.resources recyclerView.measure( MeasureSpec.makeMeasureSpec(rootView.width, MeasureSpec.EXACTLY), 0, // Internals will already limit this. ) val height = recyclerView.measuredHeight val desiredLocation = Point( rootView.x.toInt(), editTextLocation.y - height, ) popupWindow = PopupWindow(recyclerView, WindowManager.LayoutParams.MATCH_PARENT, height).apply { isFocusable = false isOutsideTouchable = true inputMethodMode = PopupWindow.INPUT_METHOD_NOT_NEEDED setBackgroundDrawable(BitmapDrawable(resources, null as Bitmap?)) // To avoid borders and overdraw. showAtLocation(rootView, Gravity.NO_GRAVITY, desiredLocation.x, desiredLocation.y) Utils.fixPopupLocation(this, desiredLocation) } } else { dismiss() } } internal fun dismiss() { popupWindow?.dismiss() popupWindow = null } }
apache-2.0
kmizu/kollection
src/main/kotlin/com/github/kmizu/kollection/KOption.kt
1
2119
package com.github.kmizu.kollection sealed class KOption<out T>(): Iterable<T>, KFoldable<T>, KLinearSequence<T> { class Some<T>(val value: T) : KOption<T>() { override fun equals(other: Any?): Boolean = when(other){ is Some<*> -> value == other.value else -> false } override fun hashCode(): Int = value?.hashCode() ?: 0 } object None : KOption<Nothing>() { override fun equals(other: Any?): Boolean = super.equals(other) } /** * Extract the value from this Option. * Note that this method should not be used as soon as possible since it is dangerous. */ fun get(): T = when(this) { is Some<T> -> this.value is None -> throw IllegalArgumentException("None") } override fun <U> foldLeft(z: U, function: (U, T) -> U): U = when(this) { is Some<T> -> function(z, this.value) is None -> z } override fun <U> foldRight(z: U, function: (T, U) -> U): U = when(this) { is Some<T> -> function(this.value, z) is None -> z } override val hd: T get() = when(this) { is Some<T> -> this.value is None -> throw IllegalArgumentException("None") } override val tl: KOption<T> get() = when(this) { is Some<T> -> None is None -> throw IllegalArgumentException("None") } override val isEmpty: Boolean get() = when(this) { is Some<T> -> false is None -> true } fun <U> map(function: (T) -> U): KOption<U> = when(this) { is Some<T> -> Some(function(this.value)) is None -> None } fun <U> flatMap(function: (T) -> KOption<U>): KOption<U> = when(this) { is Some<T> -> function(this.value) is None -> None } fun filter(function: (T) -> Boolean): KOption<T> = when(this) { is Some<T> -> if(function(this.value)) this else None is None -> None } override fun toString(): String = when(this){ is Some<*> -> "Some(${value})" is None -> "None" } }
mit
ScaCap/spring-auto-restdocs
spring-auto-restdocs-dokka-json/src/test/kotlin/capital/scalable/dokka/json/JsonFileGeneratorTest.kt
1
3259
/*- * #%L * Spring Auto REST Docs Dokka JSON * %% * Copyright (C) 2015 - 2021 Scalable Capital GmbH * %% * 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. * #L% */ package capital.scalable.dokka.json import com.intellij.openapi.util.io.FileUtil import org.jetbrains.dokka.DocumentationModule import org.jetbrains.dokka.DokkaConsoleLogger import org.jetbrains.dokka.Platform import org.jetbrains.dokka.contentRootFromPath import org.jetbrains.dokka.tests.ModelConfig import org.jetbrains.dokka.tests.verifyJavaModel import org.jetbrains.dokka.tests.verifyModel import org.jetbrains.kotlin.cli.common.config.KotlinSourceRoot import org.junit.Test import java.io.File import kotlin.test.assertTrue class JsonFileGeneratorTest { private val analysisPlatform = Platform.common private val root: File = FileUtil.createTempDirectory("dokka-json", "file-generator-test") @Test fun `buildPages should generate JSON files for Kotlin classes and nested classes`() { val inputFile = "KotlinDataClass.kt" val expectedFiles = listOf("testdata/KotlinDataClass", "testdata/KotlinDataClass.NestedClass") verifyOutput(inputFile, verifier(expectedFiles)) } @Test fun `buildPages should generate JSON files for Java classes and nested classes`() { val inputFile = "JavaClass.java" val expectedFiles = listOf("JavaClass", "JavaClass.NestedJavaClass") verifyJavaOutput(inputFile, verifier(expectedFiles)) } private fun verifyOutput(inputFile: String, verifier: (DocumentationModule) -> Unit) { verifyModel( ModelConfig( roots = arrayOf( KotlinSourceRoot("testdata/$inputFile", false) ), analysisPlatform = analysisPlatform ), verifier = verifier ) } private fun verifyJavaOutput(inputFile: String, verifier: (DocumentationModule) -> Unit) { verifyJavaModel( "testdata/$inputFile", verifier = verifier ) } private fun verifier(expectedFiles: List<String>): (DocumentationModule) -> Unit { val fileGenerator = initFileGenerator() val rootPath = File(root.path) return { fileGenerator.buildPages(listOf(it)) expectedFiles.forEach { fileName -> val file = rootPath.resolve("$fileName.json") assertTrue("Expected file $fileName.json was not generated") { file.exists() } } } } private fun initFileGenerator(): JsonFileGenerator { val fileGenerator = JsonFileGenerator(root) fileGenerator.formatService = JsonFormatService(DokkaConsoleLogger) return fileGenerator } }
apache-2.0
nt-ca-aqe/library-app
library-integration-slack/src/main/kotlin/library/integration/slack/core/BookEvent.kt
1
144
package library.integration.slack.core /** * Mark interface that should be implemented from every core book event type */ interface BookEvent
apache-2.0
vanniktech/Emoji
emoji/src/androidMain/kotlin/com/vanniktech/emoji/internal/Utils.kt
1
5209
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.vanniktech.emoji.internal import android.app.Activity import android.content.Context import android.content.ContextWrapper import android.content.res.Configuration import android.graphics.Point import android.graphics.Rect import android.util.TypedValue import android.view.View import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputMethodManager import android.widget.EditText import android.widget.PopupWindow import androidx.annotation.AttrRes import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.core.content.ContextCompat import com.vanniktech.emoji.EmojiAndroidProvider import com.vanniktech.emoji.EmojiManager import kotlin.math.roundToInt private const val DONT_UPDATE_FLAG = -1 internal object Utils { internal fun dpToPx(context: Context, dp: Float): Int { return ( TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, dp, context.resources.displayMetrics, ) + 0.5f ).roundToInt() } private fun getOrientation(context: Context): Int { return context.resources.configuration.orientation } internal fun getProperWidth(activity: Activity): Int { val rect = windowVisibleDisplayFrame(activity) return if (getOrientation(activity) == Configuration.ORIENTATION_PORTRAIT) rect.right else getScreenWidth(activity) } internal fun shouldOverrideRegularCondition(context: Context, editText: EditText): Boolean { return if (editText.imeOptions and EditorInfo.IME_FLAG_NO_EXTRACT_UI == 0) { getOrientation(context) == Configuration.ORIENTATION_LANDSCAPE } else { false } } internal fun getProperHeight(activity: Activity): Int { return windowVisibleDisplayFrame(activity).bottom } private fun getScreenWidth(context: Activity): Int { return dpToPx(context, context.resources.configuration.screenWidthDp.toFloat()) } internal fun locationOnScreen(view: View): Point { val location = IntArray(2) view.getLocationOnScreen(location) return Point(location[0], location[1]) } private fun windowVisibleDisplayFrame(context: Activity): Rect { val result = Rect() context.window.decorView.getWindowVisibleDisplayFrame(result) return result } internal fun asActivity(context: Context): Activity { var result: Context? = context while (result is ContextWrapper) { if (result is Activity) { return result } result = result.baseContext } error("The passed Context is not an Activity.") } internal fun fixPopupLocation(popupWindow: PopupWindow, desiredLocation: Point) { popupWindow.contentView.post { val actualLocation = locationOnScreen(popupWindow.contentView) if (!(actualLocation.x == desiredLocation.x && actualLocation.y == desiredLocation.y)) { val differenceX = actualLocation.x - desiredLocation.x val differenceY = actualLocation.y - desiredLocation.y val fixedOffsetX = if (actualLocation.x > desiredLocation.x) { desiredLocation.x - differenceX } else { desiredLocation.x + differenceX } val fixedOffsetY = if (actualLocation.y > desiredLocation.y) { desiredLocation.y - differenceY } else { desiredLocation.y + differenceY } popupWindow.update(fixedOffsetX, fixedOffsetY, DONT_UPDATE_FLAG, DONT_UPDATE_FLAG) } } } @ColorInt internal fun resolveColor(context: Context, @AttrRes resource: Int, @ColorRes fallback: Int): Int { val value = TypedValue() context.theme.resolveAttribute(resource, value, true) val resolvedColor = if (value.resourceId != 0) { ContextCompat.getColor(context, value.resourceId) } else { value.data } return if (resolvedColor != 0) { resolvedColor } else { ContextCompat.getColor(context, fallback) } } } internal inline val Context.inputMethodManager get() = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager internal fun EditText.showKeyboardAndFocus() { post { requestFocus() context.inputMethodManager.showSoftInput(this, 0) } } internal fun EditText.hideKeyboardAndFocus() { post { clearFocus() context.inputMethodManager.hideSoftInputFromWindow(windowToken, 0) } } internal fun EmojiManager.emojiDrawableProvider(): EmojiAndroidProvider { val emojiProvider = emojiProvider() require(emojiProvider is EmojiAndroidProvider) { "Your provider needs to implement EmojiDrawableProvider" } return emojiProvider }
apache-2.0
danrien/projectBlue
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/connection/waking/PokeServer.kt
2
295
package com.lasthopesoftware.bluewater.client.connection.waking import com.namehillsoftware.handoff.promises.Promise import org.joda.time.Duration interface PokeServer { fun promiseWakeSignal(machineAddress: MachineAddress, timesToSendSignal: Int, durationBetween: Duration): Promise<Unit> }
lgpl-3.0
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/form/field/GeometryFieldState.kt
1
887
package mil.nga.giat.mage.form.field import com.google.android.gms.maps.model.LatLng import mil.nga.giat.mage.form.FormField import mil.nga.giat.mage.observation.ObservationLocation class GeometryFieldState( definition: FormField<ObservationLocation>, val defaultMapZoom: Float? = null, val defaultMapCenter: LatLng? = null ) : FieldState<ObservationLocation, FieldValue.Location>( definition, validator = ::isValid, errorFor = ::errorMessage, hasValue = ::hasValue ) private fun errorMessage(definition: FormField<ObservationLocation>, value: FieldValue.Location?): String { return "Please enter a value" } private fun isValid(definition: FormField<ObservationLocation>, value: FieldValue.Location?): Boolean { return !definition.required || value != null } private fun hasValue(value: FieldValue.Location?): Boolean { return value?.location != null }
apache-2.0
ruuvi/Android_RuuvitagScanner
app/src/main/java/com/ruuvi/station/util/extensions/Activity.kt
1
1697
package com.ruuvi.station.util.extensions import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Build import android.view.inputmethod.InputMethodManager import androidx.appcompat.app.AppCompatActivity import com.ruuvi.station.BuildConfig import com.ruuvi.station.R fun AppCompatActivity.SendFeedback(){ val intent = Intent(Intent.ACTION_SENDTO) intent.data = Uri.parse("mailto:") intent.putExtra(Intent.EXTRA_EMAIL, arrayOf( "[email protected]" )); intent.putExtra(Intent.EXTRA_SUBJECT, "Ruuvi Station Android Feedback") val body = """ Device: ${Build.MANUFACTURER} ${Build.MODEL} Android version: ${Build.VERSION.RELEASE} App: ${applicationInfo.loadLabel(packageManager)} ${BuildConfig.VERSION_NAME}""" intent.putExtra(Intent.EXTRA_TEXT, body) startActivity(Intent.createChooser(intent, getString(R.string.send_email))) } fun AppCompatActivity.OpenUrl(url: String){ val webIntent = Intent(Intent.ACTION_VIEW) webIntent.data = Uri.parse(url) startActivity(webIntent) } fun AppCompatActivity.hideKeyboard() { val imm: InputMethodManager = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(window.decorView.windowToken, 0) } fun AppCompatActivity.getMainMenuItems(signed: Boolean) = arrayOf( getString(R.string.menu_add_new_sensor), getString(R.string.menu_app_settings), getString(R.string.menu_about_help), getString(R.string.menu_send_feedback), getString(R.string.menu_get_more_sensors), if (signed) getString(R.string.sign_out) else getString(R.string.sign_in) )
mit
collinx/susi_android
app/src/main/java/org/fossasia/susi/ai/chat/ChatPresenter.kt
1
18364
package org.fossasia.susi.ai.chat import android.os.Handler import android.util.Log import org.fossasia.susi.ai.MainApplication import org.fossasia.susi.ai.R import org.fossasia.susi.ai.chat.contract.IChatPresenter import org.fossasia.susi.ai.chat.contract.IChatView import org.fossasia.susi.ai.data.ChatModel import org.fossasia.susi.ai.data.UtilModel import org.fossasia.susi.ai.data.contract.IChatModel import org.fossasia.susi.ai.data.db.DatabaseRepository import org.fossasia.susi.ai.data.db.contract.IDatabaseRepository import org.fossasia.susi.ai.helper.* import org.fossasia.susi.ai.rest.clients.BaseUrl import org.fossasia.susi.ai.rest.responses.others.LocationResponse import org.fossasia.susi.ai.rest.responses.susi.MemoryResponse import org.fossasia.susi.ai.rest.responses.susi.SusiResponse import retrofit2.Response import java.util.* import java.util.concurrent.atomic.AtomicBoolean /** * Presentation Layer for Chat View. * * The P in MVP * Created by chiragw15 on 9/7/17. */ class ChatPresenter(chatActivity: ChatActivity): IChatPresenter, IChatModel.OnRetrievingMessagesFinishedListener, IChatModel.OnLocationFromIPReceivedListener, IChatModel.OnMessageFromSusiReceivedListener, IDatabaseRepository.onDatabaseUpdateListener{ var chatView: IChatView?= null var chatModel: IChatModel = ChatModel() var utilModel: UtilModel = UtilModel(chatActivity) var databaseRepository: IDatabaseRepository = DatabaseRepository() lateinit var locationHelper: LocationHelper val nonDeliveredMessages = LinkedList<Pair<String, Long>>() var newMessageIndex: Long = 0 var micCheck = false var latitude: Double = 0.0 var longitude: Double = 0.0 var source = Constant.IP var isDetectionOn = false var check = false var atHome = true var backPressedOnce = false @Volatile var queueExecuting = AtomicBoolean(false) override fun onAttach(chatView: IChatView) { this.chatView = chatView } override fun setUp() { //find total number of messages and find new message index newMessageIndex = databaseRepository.getMessageCount() + 1 PrefManager.putLong(Constant.MESSAGE_COUNT, newMessageIndex) micCheck = utilModel.checkMicInput() chatView?.setupAdapter(databaseRepository.getAllMessages()) getPermissions() } override fun checkPreferences() { micCheck = utilModel.getBooleanPref(Constant.MIC_INPUT, true) chatView?.checkMicPref(utilModel.getBooleanPref(Constant.MIC_INPUT, true)) chatView?.checkEnterKeyPref(utilModel.getBooleanPref(Constant.ENTER_SEND, false)) } override fun micCheck(): Boolean { return micCheck } override fun micCheck(boolean: Boolean) { micCheck = boolean } override fun check(boolean: Boolean) { check = boolean } //initiates hotword detection override fun initiateHotwordDetection() { if (chatView!!.checkPermission(utilModel.permissionsToGet()[2]) && chatView!!.checkPermission(utilModel.permissionsToGet()[1])) { if ( utilModel.isArmDevice() && utilModel.checkMicInput() ) { utilModel.copyAssetstoSD() chatView?.initHotword() startHotwordDetection() } else { utilModel.putBooleanPref(Constant.HOTWORD_DETECTION, false) if(utilModel.getBooleanPref(Constant.NOTIFY_USER, true)){ chatView?.showToast(utilModel.getString(R.string.error_hotword)) utilModel.putBooleanPref(Constant.NOTIFY_USER, false) } } } } override fun hotwordDetected() { chatView?.promptSpeechInput() } override fun startHotwordDetection() { if (!isDetectionOn && utilModel.getBooleanPref(Constant.HOTWORD_DETECTION, false)) { chatView?.startRecording() isDetectionOn = true } } override fun stopHotwordDetection() { if (isDetectionOn) { chatView?.stopRecording() isDetectionOn = false } } override fun startSpeechInput() { check = true chatView?.promptSpeechInput() } override fun disableMicInput(boolean: Boolean) { if(boolean) { micCheck = false PrefManager.putBoolean(Constant.MIC_INPUT, false) } else { micCheck = utilModel.checkMicInput() PrefManager.putBoolean(Constant.MIC_INPUT, utilModel.checkMicInput()) chatView?.checkMicPref(micCheck) } } //Retrieves old Messages override fun retrieveOldMessages(firstRun: Boolean) { if(firstRun and NetworkUtils.isNetworkConnected()) { chatView?.showRetrieveOldMessageProgress() val thread = object : Thread() { override fun run() { chatModel.retrieveOldMessages(this@ChatPresenter) } } thread.start() } } override fun onRetrieveSuccess(response: Response<MemoryResponse>?) { if (response != null && response.isSuccessful && response.body() != null) { val allMessages = response.body().cognitionsList if (allMessages.isEmpty()) { chatView?.showToast("No messages found") } else { var c: Long for (i in allMessages.size - 1 downTo 0) { val query = allMessages[i].query val queryDate = allMessages[i].queryDate val answerDate = allMessages[i].answerDate val urlList = ParseSusiResponseHelper.extractUrls(query) val isHavingLink = !urlList.isEmpty() newMessageIndex = PrefManager.getLong(Constant.MESSAGE_COUNT, 0) if (newMessageIndex == 0L) { databaseRepository.updateDatabase(newMessageIndex, "", true, DateTimeHelper.getDate(queryDate), DateTimeHelper.getTime(queryDate), false, "", null, false, null, "", "", this) } else { val prevDate = DateTimeHelper.getDate(allMessages[i + 1].queryDate) if (DateTimeHelper.getDate(queryDate) != prevDate) { databaseRepository.updateDatabase(newMessageIndex, "", true, DateTimeHelper.getDate(queryDate), DateTimeHelper.getTime(queryDate), false, "", null, false, null, "", "", this) } } c = newMessageIndex databaseRepository.updateDatabase(newMessageIndex, query, false, DateTimeHelper.getDate(queryDate), DateTimeHelper.getTime(queryDate), true, "", null, isHavingLink, null, "", "", this) if(allMessages[i].answers.isEmpty()) { databaseRepository.updateDatabase(c, utilModel.getString(R.string.error_internet_connectivity), false, DateTimeHelper.date, DateTimeHelper.currentTime, false, Constant.ANSWER, null, false, null, "", "", this) continue } val actionSize = allMessages[i].answers[0].actions.size for (j in 0..actionSize - 1) { val psh = ParseSusiResponseHelper() psh.parseSusiResponse(allMessages[i], j, utilModel.getString(R.string.error_occurred_try_again)) try { databaseRepository.updateDatabase(c, psh.answer, false, DateTimeHelper.getDate(answerDate), DateTimeHelper.getTime(answerDate), false, psh.actionType, psh.mapData, psh.isHavingLink, psh.datumList, psh.webSearch, allMessages[i].answers[0].skills[0], this) } catch (e: Exception) { databaseRepository.updateDatabase(c, utilModel.getString(R.string.error_internet_connectivity), false, DateTimeHelper.date, DateTimeHelper.currentTime, false, Constant.ANSWER, null, false, null, "", "", this) } } } } } chatView?.hideRetrieveOldMessageProgress() } override fun updateMessageCount() { newMessageIndex++ PrefManager.putLong(Constant.MESSAGE_COUNT, newMessageIndex) } override fun onRetrieveFailure() { chatView?.hideRetrieveOldMessageProgress() } //Gets Location of user using his IP Address override fun getLocationFromIP() { chatModel.getLocationFromIP(this) } override fun onLocationSuccess(response: Response<LocationResponse>) { if (response.isSuccessful && response.body() != null) { try { val loc = response.body().loc val s = loc.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() latitude = s[0].toDouble() longitude = s[1].toDouble() source = Constant.IP } catch (e: Exception) { e.printStackTrace() } } } //Gets Location of user using gps and network override fun getLocationFromLocationService() { locationHelper = LocationHelper(MainApplication.getInstance().applicationContext) getLocation() } fun getLocation() { locationHelper.getLocation() if (locationHelper.canGetLocation()) { latitude = locationHelper.latitude longitude = locationHelper.longitude source = locationHelper.source } } //get undelivered messages from database override fun getUndeliveredMessages() { nonDeliveredMessages.clear() val nonDelivered = databaseRepository.getUndeliveredMessages() nonDelivered.mapTo(nonDeliveredMessages) { Pair(it.content, it.id) } } //sends message to susi override fun sendMessage(query: String, actual: String) { addToNonDeliveredList(query, actual) computeThread().start() } override fun addToNonDeliveredList(query: String, actual: String) { val urlList = ParseSusiResponseHelper.extractUrls(query) val isHavingLink = !urlList.isEmpty() newMessageIndex = PrefManager.getLong(Constant.MESSAGE_COUNT, 0) if (newMessageIndex == 0L) { databaseRepository.updateDatabase(newMessageIndex, "", true, DateTimeHelper.date, DateTimeHelper.currentTime, false, "", null, false, null, "", "", this) } else { val s = databaseRepository.getAMessage(newMessageIndex-1).date if (DateTimeHelper.date != s) { databaseRepository.updateDatabase(newMessageIndex, "", true, DateTimeHelper.date, DateTimeHelper.currentTime, false, "", null, false, null, "", "", this) } } nonDeliveredMessages.add(Pair(query, newMessageIndex)) databaseRepository.updateDatabase(newMessageIndex, actual, false, DateTimeHelper.date, DateTimeHelper.currentTime, true, "", null, isHavingLink, null, "", "", this) getLocationFromLocationService() } override fun startComputingThread() { computeThread().start() } private inner class computeThread : Thread() { override fun run() { if(queueExecuting.compareAndSet(false,true)) { computeOtherMessage() } } } @Synchronized fun computeOtherMessage() { Log.v("chirag","chirag run") if (!nonDeliveredMessages.isEmpty()) { if (NetworkUtils.isNetworkConnected()) { chatView?.showWaitingDots() val tz = TimeZone.getDefault() val now = Date() val timezoneOffset = -1 * (tz.getOffset(now.time) / 60000) val query = nonDeliveredMessages.first.first val language = if (PrefManager.getString(Constant.LANGUAGE, Constant.DEFAULT).equals(Constant.DEFAULT)) Locale.getDefault().language else PrefManager.getString(Constant.LANGUAGE, Constant.DEFAULT) chatModel.getSusiMessage(timezoneOffset, longitude, latitude, source, language, query, this) } else run { queueExecuting.set(false) chatView?.hideWaitingDots() chatView?.displaySnackbar(utilModel.getString(R.string.no_internet_connection)) } } else { queueExecuting.set(false) } } override fun onSusiMessageReceivedFailure(t: Throwable) { chatView?.hideWaitingDots() if(nonDeliveredMessages.isEmpty()) return val id = nonDeliveredMessages.first.second val query = nonDeliveredMessages.first.first nonDeliveredMessages.pop() if (!NetworkUtils.isNetworkConnected()) { nonDeliveredMessages.addFirst(Pair(query, id)) chatView?.displaySnackbar(utilModel.getString(R.string.no_internet_connection)) } else { databaseRepository.updateDatabase(id, utilModel.getString(R.string.error_internet_connectivity), false, DateTimeHelper.date, DateTimeHelper.currentTime, false, Constant.ANSWER, null, false, null, "", "", this) } BaseUrl.updateBaseUrl(t) computeOtherMessage() } override fun onSusiMessageReceivedSuccess(response: Response<SusiResponse>?) { if(nonDeliveredMessages.isEmpty()) return val id = nonDeliveredMessages.first.second val query = nonDeliveredMessages.first.first nonDeliveredMessages.pop() if (response != null && response.isSuccessful && response.body() != null) { val susiResponse = response.body() if(response.body().answers.isEmpty()) { databaseRepository.updateDatabase(id, utilModel.getString(R.string.error_internet_connectivity), false, DateTimeHelper.date, DateTimeHelper.currentTime, false, Constant.ANSWER, null, false, null, "", "", this) return } val actionSize = response.body().answers[0].actions.size val date = response.body().answerDate for (i in 0..actionSize - 1) { val delay = response.body().answers[0].actions[i].delay val actionNo = i val handler = Handler() handler.postDelayed({ val psh = ParseSusiResponseHelper() psh.parseSusiResponse(susiResponse, actionNo, utilModel.getString(R.string.error_occurred_try_again)) val setMessage = psh.answer if (psh.actionType == Constant.ANSWER && (PrefManager.checkSpeechOutputPref() && check || PrefManager.checkSpeechAlwaysPref())){ var speechReply = setMessage if (psh.isHavingLink) { speechReply = setMessage.substring(0, setMessage.indexOf("http")) } chatView?.voiceReply(speechReply, susiResponse.answers[0].actions[i].language) } try { databaseRepository.updateDatabase(id, setMessage, false, DateTimeHelper.getDate(date), DateTimeHelper.getTime(date), false, psh.actionType, psh.mapData, psh.isHavingLink, psh.datumList, psh.webSearch, susiResponse.answers[0].skills[0], this) } catch (e: Exception) { databaseRepository.updateDatabase(id, utilModel.getString(R.string.error_internet_connectivity), false, DateTimeHelper.date, DateTimeHelper.currentTime, false, Constant.ANSWER, null, false, null, "", "", this) } }, delay) } chatView?.hideWaitingDots() } else { if (!NetworkUtils.isNetworkConnected()) { nonDeliveredMessages.addFirst(Pair(query, id)) chatView?.displaySnackbar(utilModel.getString(R.string.no_internet_connection)) } else { databaseRepository.updateDatabase(id, utilModel.getString(R.string.error_internet_connectivity), false, DateTimeHelper.date, DateTimeHelper.currentTime, false, Constant.ANSWER, null, false, null, "", "", this) } chatView?.hideWaitingDots() } computeOtherMessage() } override fun onDatabaseUpdateSuccess() { chatView?.databaseUpdated() } //Asks for permissions from user fun getPermissions() { val permissionsRequired = utilModel.permissionsToGet() val permissionsGranted = arrayOfNulls<String>(3) var c = 0 for(permission in permissionsRequired) { if(!(chatView?.checkPermission(permission) as Boolean)) { permissionsGranted[c] = permission c++ } } if(c > 0) { chatView?.askForPermission(permissionsGranted) } if(!(chatView?.checkPermission(permissionsRequired[1]) as Boolean)) { PrefManager.putBoolean(Constant.MIC_INPUT, utilModel.checkMicInput()) } } override fun exitChatActivity() { if (atHome) { if (backPressedOnce) { chatView?.finishActivity() return } backPressedOnce = true chatView?.showToast(utilModel.getString(R.string.exit)) Handler().postDelayed({ backPressedOnce = false }, 2000) } else if (!atHome) { atHome = true } } override fun onDetach() { locationHelper.removeListener() databaseRepository.closeDatabase() chatView = null } }
apache-2.0
Ph1b/MaterialAudiobookPlayer
app/src/main/kotlin/de/ph1b/audiobook/misc/recyclerComponent/CompositeListAdapter.kt
1
1350
package de.ph1b.audiobook.misc.recyclerComponent import android.view.ViewGroup import androidx.annotation.CallSuper import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView /** * An adapter that is designed for composition instead of inheritance. * * Instead of handling the view type and items manually, add a [AdapterComponent] for each view type. */ open class CompositeListAdapter<T : Any>( itemCallback: DiffUtil.ItemCallback<T> ) : ListAdapter<T, RecyclerView.ViewHolder>(itemCallback) { private val helper = CompositeAdapterHelper<T> { getItem(it) } @CallSuper override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { helper.onBindViewHolder(holder, position).also { onViewHolderBound(holder) } } final override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return helper.onCreateViewHolder(parent, viewType) } open fun onViewHolderBound(holder: RecyclerView.ViewHolder) {} final override fun getItemViewType(position: Int): Int = helper.getItemViewType(position) fun <U : T, VH : RecyclerView.ViewHolder> addComponent(component: AdapterComponent<U, VH>) { @Suppress("UNCHECKED_CAST") helper.addComponent(component as AdapterComponent<T, VH>) } }
lgpl-3.0
Ph1b/MaterialAudiobookPlayer
data/src/main/kotlin/de/ph1b/audiobook/data/repo/internals/migrations/Migration28to29.kt
2
1370
package de.ph1b.audiobook.data.repo.internals.migrations import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import androidx.sqlite.db.SupportSQLiteDatabase import org.json.JSONObject import timber.log.Timber import java.io.File class Migration28to29 : IncrementalMigration(28) { override fun migrate(db: SupportSQLiteDatabase) { db.query("TABLE_BOOK", arrayOf("BOOK_JSON", "BOOK_ID")) .use { cursor -> while (cursor.moveToNext()) { val book = JSONObject(cursor.getString(0)) val chapters = book.getJSONArray("chapters") for (i in 0 until chapters.length()) { val chapter = chapters.getJSONObject(i) val fileName = File(chapter.getString("path")).name val dotIndex = fileName.lastIndexOf(".") val chapterName = if (dotIndex > 0) { fileName.substring(0, dotIndex) } else { fileName } chapter.put("name", chapterName) } val cv = ContentValues() Timber.d("so saving book=$book") cv.put("BOOK_JSON", book.toString()) db.update( "TABLE_BOOK", SQLiteDatabase.CONFLICT_FAIL, cv, "BOOK_ID" + "=?", arrayOf(cursor.getLong(1).toString()) ) } } } }
lgpl-3.0
spark/photon-tinker-android
mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepEnsureConnectionToCloud.kt
1
1162
package io.particle.mesh.setup.flow.setupsteps import io.particle.firmwareprotos.ctrl.cloud.Cloud.ConnectionStatus import io.particle.mesh.setup.flow.* import io.particle.mesh.setup.flow.context.SetupContexts import kotlinx.coroutines.delay import mu.KotlinLogging class StepEnsureConnectionToCloud : MeshSetupStep() { private val log = KotlinLogging.logger {} override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) { // FIXME: these delays should probably live in the flows themselves, // using a "StepDelay" setup step delay(1000) var millis = 0 val limitMillis = 1000 * 45 // 45 seconds while (millis < limitMillis) { delay(5000) millis += 5000 val reply = ctxs.requireTargetXceiver().sendGetConnectionStatus().throwOnErrorOrAbsent() log.info { "reply=$reply" } if (reply.status == ConnectionStatus.CONNECTED) { ctxs.targetDevice.updateDeviceConnectedToCloudLD(true) return } } throw MeshSetupFlowException(message = "Error ensuring connection to cloud") } }
apache-2.0
chat-sdk/chat-sdk-android
chat-sdk-vendor/src/main/java/smartadapter/viewevent/swipe/AutoRemoveItemSwipeEventBinder.kt
1
1282
package smartadapter.viewevent.swipe /* * Created by Manne Öhlund on 2019-08-17. * Copyright (c) All rights reserved. */ import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import smartadapter.SmartRecyclerAdapter import smartadapter.SmartViewHolderType import smartadapter.viewevent.model.ViewEvent import smartadapter.viewholder.SmartAdapterHolder import smartadapter.viewholder.SmartViewHolder /** * Automatically removes an item in [SmartRecyclerAdapter] when swiped. * * @see BasicSwipeEventBinder * * @see SmartAdapterHolder */ class AutoRemoveItemSwipeEventBinder( override val identifier: Any = AutoRemoveItemSwipeEventBinder::class, override var swipeFlags: SwipeFlags = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT, override var viewHolderTypes: List<SmartViewHolderType> = listOf(SmartViewHolder::class), override var longPressDragEnabled: Boolean = false, override var eventListener: (ViewEvent.OnItemSwiped) -> Unit ) : BasicSwipeEventBinder( eventListener = eventListener ) { override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { super.onSwiped(viewHolder, direction) smartRecyclerAdapter.removeItem(viewHolder.adapterPosition) } }
apache-2.0
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/ui/preferences/DockPreferences.kt
1
3822
/* * Copyright 2022, Lawnchair * * 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.lawnchair.ui.preferences import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import androidx.navigation.NavGraphBuilder import app.lawnchair.preferences.getAdapter import app.lawnchair.preferences.preferenceManager import app.lawnchair.preferences2.preferenceManager2 import app.lawnchair.qsb.providers.QsbSearchProvider import app.lawnchair.ui.preferences.components.DividerColumn import app.lawnchair.ui.preferences.components.ExpandAndShrink import app.lawnchair.ui.preferences.components.NavigationActionPreference import app.lawnchair.ui.preferences.components.PreferenceGroup import app.lawnchair.ui.preferences.components.PreferenceLayout import app.lawnchair.ui.preferences.components.SliderPreference import app.lawnchair.ui.preferences.components.SwitchPreference import com.android.launcher3.R object DockRoutes { const val SEARCH_PROVIDER = "searchProvider" } fun NavGraphBuilder.dockGraph(route: String) { preferenceGraph(route, { DockPreferences() }) { subRoute -> searchProviderGraph(subRoute(DockRoutes.SEARCH_PROVIDER)) } } @Composable fun DockPreferences() { val prefs = preferenceManager() val prefs2 = preferenceManager2() PreferenceLayout(label = stringResource(id = R.string.dock_label)) { PreferenceGroup(heading = stringResource(id = R.string.search_bar_label)) { val hotseatQsbAdapter = prefs2.hotseatQsb.getAdapter() SwitchPreference( adapter = hotseatQsbAdapter, label = stringResource(id = R.string.hotseat_qsb_label), ) ExpandAndShrink(visible = hotseatQsbAdapter.state.value) { DividerColumn { SwitchPreference( adapter = prefs2.themedHotseatQsb.getAdapter(), label = stringResource(id = R.string.apply_accent_color_label), ) SliderPreference( label = stringResource(id = R.string.corner_radius_label), adapter = prefs.hotseatQsbCornerRadius.getAdapter(), step = 0.1F, valueRange = 0F..1F, showAsPercentage = true, ) val hotseatQsbProviderAdapter by preferenceManager2().hotseatQsbProvider.getAdapter() NavigationActionPreference( label = stringResource(R.string.search_provider), destination = subRoute(DockRoutes.SEARCH_PROVIDER), subtitle = stringResource( id = QsbSearchProvider.values() .first { it == hotseatQsbProviderAdapter } .name, ), ) } } } PreferenceGroup(heading = stringResource(id = R.string.grid)) { SliderPreference( label = stringResource(id = R.string.dock_icons), adapter = prefs.hotseatColumns.getAdapter(), step = 1, valueRange = 3..10, ) } } }
gpl-3.0
DenverM80/ds3_autogen
ds3-autogen-go/src/main/kotlin/com/spectralogic/ds3autogen/go/generators/request/PartsRequestPayloadGenerator.kt
1
1563
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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.spectralogic.ds3autogen.go.generators.request import com.spectralogic.ds3autogen.api.models.Arguments import com.spectralogic.ds3autogen.go.models.request.Variable /** * The Go generator for request handlers that have a CompleteMultipartUpload * request payload not specified within the contract. */ class PartsRequestPayloadGenerator : RequestPayloadGenerator() { /** * Retrieves the CompleteMultipartUpload request payload */ override fun getPayloadConstructorArg(): Arguments { return Arguments("[]Part", "parts") } /** * Retrieves the struct assignment for the CompleteMultipartUpload request payload */ override fun getStructAssignmentVariable(): Variable { return Variable("content", "buildPartsListStream(parts)") } }
apache-2.0
android/trackr
app/src/test/java/com/example/android/trackr/TestApplication.kt
1
842
/* * Copyright (C) 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.android.trackr import android.app.Application class TestApplication : Application() { override fun onCreate() { super.onCreate() setTheme(R.style.Theme_MaterialComponents) } }
apache-2.0
tmarsteel/compiler-fiddle
src/compiler/reportings/PurityViolationReporting.kt
1
2942
/* * Copyright 2018 Tobias Marstaller * * This program 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. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package compiler.reportings import compiler.ast.Executable import compiler.ast.type.FunctionModifier import compiler.binding.BoundAssignmentStatement import compiler.binding.BoundExecutable import compiler.binding.BoundFunction import compiler.binding.expression.BoundIdentifierExpression import compiler.binding.expression.BoundInvocationExpression abstract class PurityViolationReporting protected constructor(val violation: BoundExecutable<Executable<*>>, function: BoundFunction, message: String) : Reporting(Level.ERROR, message, violation.declaration.sourceLocation) class ReadInPureContextReporting internal constructor(readingExpression: BoundIdentifierExpression, function: BoundFunction) : PurityViolationReporting( readingExpression, function, "pure function ${function.name} cannot read ${readingExpression.identifier} (is not within the pure boundary)" ) class ImpureInvocationInPureContextReporting internal constructor(invcExpr: BoundInvocationExpression, function: BoundFunction) : PurityViolationReporting( invcExpr, function, "pure function ${function.name} cannot invoke impure function ${invcExpr.dispatchedFunction!!.name}" ) class ModifyingInvocationInReadonlyContextReporting internal constructor(invcExpr: BoundInvocationExpression, function: BoundFunction) : PurityViolationReporting( invcExpr, function, "readonly function ${function.name} cannot invoke modifying function ${invcExpr.dispatchedFunction!!.name}" ) class StateModificationOutsideOfPurityBoundaryReporting internal constructor(assignment: BoundAssignmentStatement, function: BoundFunction) : PurityViolationReporting( assignment, function, { val functionType = if (FunctionModifier.PURE in function.modifiers) FunctionModifier.PURE else FunctionModifier.READONLY val functionTypeAsString = functionType.name[0].toUpperCase() + functionType.name.substring(1).toLowerCase() val boundaryType = if (functionType == FunctionModifier.PURE) "purity" else "readonlyness" "$functionTypeAsString function ${function.name} cannot assign state outside of its $boundaryType boundary" }() )
lgpl-3.0
amith01994/intellij-community
plugins/settings-repository/src/BaseRepositoryManager.kt
6
6583
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeAndWaitIfNeed import com.intellij.openapi.fileTypes.StdFileTypes import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.merge.MergeDialogCustomizer import com.intellij.openapi.vcs.merge.MergeProvider2 import com.intellij.openapi.vcs.merge.MultipleFileMergeDialog import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.LightVirtualFile import com.intellij.util.PathUtilRt import java.io.File import java.io.FileInputStream import java.io.InputStream import java.io.OutputStream import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.read import kotlin.concurrent.write public abstract class BaseRepositoryManager(protected val dir: File) : RepositoryManager { protected val lock: ReentrantReadWriteLock = ReentrantReadWriteLock() override fun processChildren(path: String, filter: (name: String) -> Boolean, processor: (name: String, inputStream: InputStream) -> Boolean) { var files: Array<out File>? = null lock.read { files = File(dir, path).listFiles({ file, name -> filter(name) }) } if (files == null || files!!.isEmpty()) { return } for (file in files!!) { if (file.isDirectory() || file.isHidden()) { continue; } // we ignore empty files as well - delete if corrupted if (file.length() == 0L) { if (file.exists()) { try { LOG.warn("File $path is empty (length 0), will be removed") delete(file, path) } catch (e: Exception) { LOG.error(e) } } continue; } if (!processor(file.name, file.inputStream())) { break; } } } override fun deleteRepository() { FileUtil.delete(dir) } protected open fun isPathIgnored(path: String): Boolean = false override fun read(path: String): InputStream? { if (isPathIgnored(path)) { if (LOG.isDebugEnabled()) { LOG.debug("$path is ignored") } return null } var fileToDelete: File? = null lock.read { val file = File(dir, path) // we ignore empty files as well - delete if corrupted if (file.length() == 0L) { fileToDelete = file } else { return FileInputStream(file) } } try { lock.write { if (fileToDelete!!.exists() && fileToDelete!!.length() == 0L) { LOG.warn("File $path is empty (length 0), will be removed") delete(fileToDelete!!, path) } } } catch (e: Exception) { LOG.error(e) } return null } override fun write(path: String, content: ByteArray, size: Int): Boolean { if (isPathIgnored(path)) { if (LOG.isDebugEnabled()) { LOG.debug("$path is ignored") } return false } if (LOG.isDebugEnabled()) { LOG.debug("Write $path") } try { lock.write { val file = File(dir, path) FileUtil.writeToFile(file, content, 0, size) addToIndex(file, path, content, size) } } catch (e: Exception) { LOG.error(e) return false } return true } /** * path relative to repository root */ protected abstract fun addToIndex(file: File, path: String, content: ByteArray, size: Int) override fun delete(path: String) { if (LOG.isDebugEnabled()) { LOG.debug("Remove $path") } lock.write { val file = File(dir, path) // delete could be called for non-existent file if (file.exists()) { delete(file, path) } } } private fun delete(file: File, path: String) { val isFile = file.isFile() file.removeWithParentsIfEmpty(dir, isFile) deleteFromIndex(path, isFile) } protected abstract fun deleteFromIndex(path: String, isFile: Boolean) override fun has(path: String) = lock.read { File(dir, path).exists() } } fun File.removeWithParentsIfEmpty(root: File, isFile: Boolean = true) { FileUtil.delete(this) if (isFile) { // remove empty directories var parent = this.getParentFile() while (parent != null && parent != root && parent.delete()) { parent = parent.getParentFile() } } } var conflictResolver: ((files: List<VirtualFile>, mergeProvider: MergeProvider2) -> Unit)? = null fun resolveConflicts(files: List<VirtualFile>, mergeProvider: MergeProvider2): List<VirtualFile> { if (ApplicationManager.getApplication()!!.isUnitTestMode()) { if (conflictResolver == null) { throw CannotResolveConflictInTestMode() } else { conflictResolver!!(files, mergeProvider) } return files } var processedFiles: List<VirtualFile>? = null invokeAndWaitIfNeed { val fileMergeDialog = MultipleFileMergeDialog(null, files, mergeProvider, object : MergeDialogCustomizer() { override fun getMultipleFileDialogTitle() = "Settings Repository: Files Merged with Conflicts" }) fileMergeDialog.show() processedFiles = fileMergeDialog.getProcessedFiles() } return processedFiles!! } class RepositoryVirtualFile(private val path: String) : LightVirtualFile(PathUtilRt.getFileName(path), StdFileTypes.XML, "", CharsetToolkit.UTF8_CHARSET, 1L) { var content: ByteArray? = null private set override fun getPath() = path override fun setBinaryContent(content: ByteArray, newModificationStamp: Long, newTimeStamp: Long, requestor: Any?) { $content = content } override fun getOutputStream(requestor: Any?, newModificationStamp: Long, newTimeStamp: Long): OutputStream { throw IllegalStateException("You must use setBinaryContent") } override fun setContent(requestor: Any?, content: CharSequence, fireEvent: Boolean) { throw IllegalStateException("You must use setBinaryContent") } }
apache-2.0
denysnovoa/radarrsonarr
app/src/main/java/com/denysnovoa/nzbmanager/radarr/movie/release/view/MovieReleaseView.kt
1
406
package com.denysnovoa.nzbmanager.radarr.movie.release.view import com.denysnovoa.nzbmanager.radarr.movie.release.view.model.MovieReleaseViewModel interface MovieReleaseView { fun showMovieReleases(movieReleases: List<MovieReleaseViewModel>) fun showErrorSearchReleases() fun showLoading() fun hideLoading() fun showItemClicked() fun showDownloadOk() fun showErrorDownload() }
apache-2.0
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/util/FlagUtils.kt
1
484
package app.lawnchair.util fun Int.hasFlag(flag: Int): Boolean { return (this and flag) == flag } fun Int.addFlag(flag: Int): Int { return this or flag } fun Int.removeFlag(flag: Int): Int { return this and flag.inv() } fun Int.toggleFlag(flag: Int): Int { return if (hasFlag(flag)) removeFlag(flag) else addFlag(flag) } fun Int.setFlag(flag: Int, value: Boolean): Int { return if (value) { addFlag(flag) } else { removeFlag(flag) } }
gpl-3.0
Zhuinden/simple-stack
samples/legacy-samples/simple-stack-example-multistack-view/src/main/java/com/zhuinden/simplestackdemomultistack/core/navigation/NavUtil.kt
1
251
package com.zhuinden.simplestackdemomultistack.core.navigation import android.view.View import com.zhuinden.simplestack.Backstack val View.backstack: Backstack get() = Backstack.getKey<MultistackViewKey>(context).selectBackstack(context)
apache-2.0