repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
ingokegel/intellij-community
platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/project/ProjectRootManagerBridge.kt
1
14433
// 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.workspaceModel.ide.impl.legacyBridge.project import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.project.RootsChangeRescanningInfo import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.RootProvider import com.intellij.openapi.roots.RootProvider.RootSetChangedListener import com.intellij.openapi.roots.impl.OrderRootsCache import com.intellij.openapi.roots.impl.ProjectRootManagerComponent import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryTable import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar.APPLICATION_LEVEL import com.intellij.openapi.util.EmptyRunnable import com.intellij.util.containers.BidirectionalMultiMap import com.intellij.util.containers.MultiMap import com.intellij.util.indexing.BuildableRootsChangeRescanningInfo import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.WorkspaceModelChangeListener import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryNameGenerator import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.OrderRootsCacheBridge import com.intellij.workspaceModel.storage.VersionedStorageChange import com.intellij.workspaceModel.storage.bridgeEntities.api.* import java.util.function.Supplier class ProjectRootManagerBridge(project: Project) : ProjectRootManagerComponent(project) { companion object { private const val LIBRARY_NAME_DELIMITER = ":" @JvmStatic private val LOG = logger<ProjectRootManagerBridge>() } private val globalLibraryTableListener = GlobalLibraryTableListener() private val jdkChangeListener = JdkChangeListener() init { if (!project.isDefault) { val bus = project.messageBus.connect(this) WorkspaceModelTopics.getInstance(project).subscribeAfterModuleLoading(bus, object : WorkspaceModelChangeListener { override fun changed(event: VersionedStorageChange) { if (myProject.isDisposed) return // Roots changed event should be fired for the global libraries linked with module val moduleChanges = event.getChanges(ModuleEntity::class.java) for (change in moduleChanges) { change.oldEntity?.let { removeTrackedLibrariesAndJdkFromEntity(it) } change.newEntity?.let { addTrackedLibraryAndJdkFromEntity(it) } } } }) bus.subscribe(ProjectJdkTable.JDK_TABLE_TOPIC, jdkChangeListener) } } override fun getActionToRunWhenProjectJdkChanges(): Runnable { return Runnable { super.getActionToRunWhenProjectJdkChanges().run() if (jdkChangeListener.hasProjectSdkDependency()) fireRootsChanged(BuildableRootsChangeRescanningInfo.newInstance().addInheritedSdk()) } } override fun projectClosed() { super.projectClosed() unsubscribeListeners() } override fun dispose() { super.dispose() unsubscribeListeners() } override fun getOrderRootsCache(project: Project): OrderRootsCache { return OrderRootsCacheBridge(project, project) } fun isFiringEvent(): Boolean = isFiringEvent private fun unsubscribeListeners() { if (project.isDefault) return val libraryTablesRegistrar = LibraryTablesRegistrar.getInstance() val globalLibraryTable = libraryTablesRegistrar.libraryTable globalLibraryTableListener.getLibraryLevels().forEach { libraryLevel -> val libraryTable = when (libraryLevel) { APPLICATION_LEVEL -> globalLibraryTable else -> libraryTablesRegistrar.getLibraryTableByLevel(libraryLevel, project) } libraryTable?.libraryIterator?.forEach { (it as? RootProvider)?.removeRootSetChangedListener(globalLibraryTableListener) } libraryTable?.removeListener(globalLibraryTableListener) } globalLibraryTableListener.clear() jdkChangeListener.unsubscribeListeners() } fun setupTrackedLibrariesAndJdks() { val currentStorage = WorkspaceModel.getInstance(project).entityStorage.current for (moduleEntity in currentStorage.entities(ModuleEntity::class.java)) { addTrackedLibraryAndJdkFromEntity(moduleEntity) } } private fun addTrackedLibraryAndJdkFromEntity(moduleEntity: ModuleEntity) { ApplicationManager.getApplication().assertWriteAccessAllowed() LOG.debug { "Add tracked global libraries and JDK from ${moduleEntity.name}" } val libraryTablesRegistrar = LibraryTablesRegistrar.getInstance() moduleEntity.dependencies.forEach { when { it is ModuleDependencyItem.Exportable.LibraryDependency && it.library.tableId is LibraryTableId.GlobalLibraryTableId -> { val libraryName = it.library.name val libraryLevel = it.library.tableId.level val libraryTable = libraryTablesRegistrar.getLibraryTableByLevel(libraryLevel, project) ?: return@forEach if (globalLibraryTableListener.isEmpty(libraryLevel)) libraryTable.addListener(globalLibraryTableListener) globalLibraryTableListener.addTrackedLibrary(moduleEntity, libraryTable, libraryName) } it is ModuleDependencyItem.SdkDependency || it is ModuleDependencyItem.InheritedSdkDependency -> { jdkChangeListener.addTrackedJdk(it, moduleEntity) } } } } private fun removeTrackedLibrariesAndJdkFromEntity(moduleEntity: ModuleEntity) { LOG.debug { "Removed tracked global libraries and JDK from ${moduleEntity.name}" } val libraryTablesRegistrar = LibraryTablesRegistrar.getInstance() moduleEntity.dependencies.forEach { when { it is ModuleDependencyItem.Exportable.LibraryDependency && it.library.tableId is LibraryTableId.GlobalLibraryTableId -> { val libraryName = it.library.name val libraryLevel = it.library.tableId.level val libraryTable = libraryTablesRegistrar.getLibraryTableByLevel(libraryLevel, project) ?: return@forEach globalLibraryTableListener.unTrackLibrary(moduleEntity, libraryTable, libraryName) if (globalLibraryTableListener.isEmpty(libraryLevel)) libraryTable.removeListener(globalLibraryTableListener) } it is ModuleDependencyItem.SdkDependency || it is ModuleDependencyItem.InheritedSdkDependency -> { jdkChangeListener.removeTrackedJdk(it, moduleEntity) } } } } private fun fireRootsChanged(info: RootsChangeRescanningInfo) { if (myProject.isOpen) { makeRootsChange(EmptyRunnable.INSTANCE, info) } } // Listener for global libraries linked to module private inner class GlobalLibraryTableListener : LibraryTable.Listener, RootSetChangedListener { private val librariesPerModuleMap = BidirectionalMultiMap<ModuleId, String>() private var insideRootsChange = false fun addTrackedLibrary(moduleEntity: ModuleEntity, libraryTable: LibraryTable, libraryName: String) { val library = libraryTable.getLibraryByName(libraryName) val libraryIdentifier = getLibraryIdentifier(libraryTable, libraryName) if (!librariesPerModuleMap.containsValue(libraryIdentifier)) { (library as? RootProvider)?.addRootSetChangedListener(this) } librariesPerModuleMap.put(moduleEntity.persistentId, libraryIdentifier) } fun unTrackLibrary(moduleEntity: ModuleEntity, libraryTable: LibraryTable, libraryName: String) { val library = libraryTable.getLibraryByName(libraryName) val libraryIdentifier = getLibraryIdentifier(libraryTable, libraryName) librariesPerModuleMap.remove(moduleEntity.persistentId, libraryIdentifier) if (!librariesPerModuleMap.containsValue(libraryIdentifier)) { (library as? RootProvider)?.removeRootSetChangedListener(this) } } fun isEmpty(libraryLevel: String) = librariesPerModuleMap.values.none { it.startsWith("$libraryLevel$LIBRARY_NAME_DELIMITER") } fun getLibraryLevels() = librariesPerModuleMap.values.mapTo(HashSet()) { it.substringBefore(LIBRARY_NAME_DELIMITER) } override fun afterLibraryAdded(newLibrary: Library) { if (librariesPerModuleMap.containsValue(getLibraryIdentifier(newLibrary))) fireRootsChanged(BuildableRootsChangeRescanningInfo.newInstance().addLibrary(newLibrary)) } override fun afterLibraryRemoved(library: Library) { if (librariesPerModuleMap.containsValue(getLibraryIdentifier(library))) fireRootsChanged(RootsChangeRescanningInfo.NO_RESCAN_NEEDED) } override fun afterLibraryRenamed(library: Library, oldName: String?) { val libraryTable = library.table val newName = library.name if (libraryTable != null && oldName != null && newName != null) { val affectedModules = librariesPerModuleMap.getKeys(getLibraryIdentifier(libraryTable, oldName)) if (affectedModules.isNotEmpty()) { val libraryTableId = LibraryNameGenerator.getLibraryTableId(libraryTable.tableLevel) WorkspaceModel.getInstance(myProject).updateProjectModel { builder -> //maybe it makes sense to simplify this code by reusing code from PEntityStorageBuilder.updateSoftReferences affectedModules.mapNotNull { builder.resolve(it) }.forEach { module -> val updated = module.dependencies.map { when { it is ModuleDependencyItem.Exportable.LibraryDependency && it.library.tableId == libraryTableId && it.library.name == oldName -> it.copy(library = LibraryId(newName, libraryTableId)) else -> it } } as MutableList<ModuleDependencyItem> builder.modifyEntity(module) { dependencies = updated } } } } } } override fun rootSetChanged(wrapper: RootProvider) { if (insideRootsChange) return insideRootsChange = true try { fireRootsChanged(BuildableRootsChangeRescanningInfo.newInstance().addLibrary(wrapper as Library)) } finally { insideRootsChange = false } } private fun getLibraryIdentifier(library: Library) = "${library.table.tableLevel}$LIBRARY_NAME_DELIMITER${library.name}" private fun getLibraryIdentifier(libraryTable: LibraryTable, libraryName: String) = "${libraryTable.tableLevel}$LIBRARY_NAME_DELIMITER$libraryName" fun clear() = librariesPerModuleMap.clear() } private inner class JdkChangeListener : ProjectJdkTable.Listener, RootSetChangedListener { private val sdkDependencies = MultiMap.createSet<ModuleDependencyItem, ModuleId>() private val watchedSdks = HashSet<RootProvider>() override fun jdkAdded(jdk: Sdk) { if (hasDependencies(jdk)) { if (watchedSdks.add(jdk.rootProvider)) { jdk.rootProvider.addRootSetChangedListener(this) } fireRootsChanged(BuildableRootsChangeRescanningInfo.newInstance().addSdk(jdk)) } } override fun jdkNameChanged(jdk: Sdk, previousName: String) { val sdkDependency = ModuleDependencyItem.SdkDependency(previousName, jdk.sdkType.name) val affectedModules = sdkDependencies.get(sdkDependency) if (affectedModules.isNotEmpty()) { WorkspaceModel.getInstance(myProject).updateProjectModel { builder -> for (moduleId in affectedModules) { val module = moduleId.resolve(builder) ?: continue val updated = module.dependencies.map { when (it) { is ModuleDependencyItem.SdkDependency -> ModuleDependencyItem.SdkDependency(jdk.name, jdk.sdkType.name) else -> it } } as MutableList<ModuleDependencyItem> builder.modifyEntity(module) { dependencies = updated } } } } } override fun jdkRemoved(jdk: Sdk) { if (watchedSdks.remove(jdk.rootProvider)) { jdk.rootProvider.removeRootSetChangedListener(this) } if (hasDependencies(jdk)) { fireRootsChanged(RootsChangeRescanningInfo.NO_RESCAN_NEEDED) } } override fun rootSetChanged(wrapper: RootProvider) { LOG.assertTrue(wrapper is Supplier<*>, "Unexpected root provider $wrapper does not implement Supplier<Sdk>") fireRootsChanged(BuildableRootsChangeRescanningInfo.newInstance().addSdk((wrapper as Supplier<Sdk>).get())) } fun addTrackedJdk(sdkDependency: ModuleDependencyItem, moduleEntity: ModuleEntity) { val sdk = findSdk(sdkDependency) if (sdk != null && watchedSdks.add(sdk.rootProvider)) { sdk.rootProvider.addRootSetChangedListener(this) } sdkDependencies.putValue(sdkDependency, moduleEntity.persistentId) } fun removeTrackedJdk(sdkDependency: ModuleDependencyItem, moduleEntity: ModuleEntity) { sdkDependencies.remove(sdkDependency, moduleEntity.persistentId) val sdk = findSdk(sdkDependency) if (sdk != null && !hasDependencies(sdk) && watchedSdks.remove(sdk.rootProvider)) { sdk.rootProvider.removeRootSetChangedListener(this) } } fun hasProjectSdkDependency(): Boolean { return sdkDependencies.get(ModuleDependencyItem.InheritedSdkDependency).isNotEmpty() } private fun findSdk(sdkDependency: ModuleDependencyItem): Sdk? = when (sdkDependency) { is ModuleDependencyItem.InheritedSdkDependency -> projectSdk is ModuleDependencyItem.SdkDependency -> ProjectJdkTable.getInstance().findJdk(sdkDependency.sdkName, sdkDependency.sdkType) else -> null } private fun hasDependencies(jdk: Sdk): Boolean { return sdkDependencies.get(ModuleDependencyItem.SdkDependency(jdk.name, jdk.sdkType.name)).isNotEmpty() || jdk.name == projectSdkName && jdk.sdkType.name == projectSdkTypeName && hasProjectSdkDependency() } fun unsubscribeListeners() { watchedSdks.forEach { it.removeRootSetChangedListener(this) } watchedSdks.clear() } } }
apache-2.0
a3e876f5044fa0554eaa00781caa0079
43.687307
146
0.736992
5.335675
false
false
false
false
googlearchive/android-PdfRendererBasic
kotlinApp/Application/src/androidTest/java/com/example/android/pdfrendererbasic/PdfRendererBasicFragmentTests.kt
1
4653
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.pdfrendererbasic import android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE import android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT import android.support.test.espresso.Espresso.onView import android.support.test.espresso.action.ViewActions.click import android.support.test.espresso.matcher.ViewMatchers.withId import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import android.widget.Button import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Tests for PdfRendererBasic sample. */ @RunWith(AndroidJUnit4::class) class PdfRendererBasicFragmentTests { private lateinit var fragment: PdfRendererBasicFragment private lateinit var btnPrevious: Button private lateinit var btnNext: Button @Rule @JvmField val activityTestRule = ActivityTestRule(MainActivity::class.java) @Before fun before() { activityTestRule.activity.supportFragmentManager.beginTransaction() fragment = activityTestRule.activity.supportFragmentManager .findFragmentByTag(FRAGMENT_PDF_RENDERER_BASIC) as PdfRendererBasicFragment } @Test fun testActivityTitle() { // The title of the activity should be "PdfRendererBasic (1/10)" at first val expectedActivityTitle = activityTestRule.activity.getString( R.string.app_name_with_index, 1, fragment.getPageCount()) assertEquals(expectedActivityTitle, activityTestRule.activity.title) } @Test fun testButtons_previousDisabledAtFirst() { setUpButtons() // Check that the previous button is disabled at first assertFalse(btnPrevious.isEnabled) // The next button should be enabled assertTrue(btnNext.isEnabled) } @Test fun testButtons_bothEnabledInMiddle() { setUpButtons() turnPages(1) // Two buttons should be both enabled assertTrue(btnPrevious.isEnabled) assertTrue(btnNext.isEnabled) } @Test fun testButtons_nextDisabledLastPage() { setUpButtons() val pageCount = fragment.getPageCount() // Click till it reaches the last page turnPages(pageCount - 1) // Check the page count val expectedActivityTitle = activityTestRule.activity.getString( R.string.app_name_with_index, pageCount, pageCount) assertEquals(expectedActivityTitle, activityTestRule.activity.title) // The previous button should be enabled assertTrue(btnPrevious.isEnabled) // Check that the next button is disabled assertFalse(btnNext.isEnabled) } @Test fun testOrientationChangePreserveState() { activityTestRule.activity.requestedOrientation = SCREEN_ORIENTATION_PORTRAIT setUpButtons() turnPages(1) val pageCount = fragment.getPageCount() val expectedActivityTitle = activityTestRule.activity .getString(R.string.app_name_with_index, 2, pageCount) assertEquals(expectedActivityTitle, activityTestRule.activity.title) activityTestRule.activity.requestedOrientation = SCREEN_ORIENTATION_LANDSCAPE // Check that the title is the same after orientation change assertEquals(expectedActivityTitle, activityTestRule.activity.title) } /** * Prepares references to the buttons "Previous" and "Next". */ private fun setUpButtons() { val view = fragment.view ?: return btnPrevious = view.findViewById(R.id.previous) btnNext = view.findViewById(R.id.next) } /** * Click the "Next" button to turn the pages. * * @param count The number of times to turn pages. */ private fun turnPages(count: Int) { for (i in 0 until count) { onView(withId(R.id.next)).perform(click()) } } }
apache-2.0
18747e838b680f920ce80c56a954ed22
36.224
91
0.715023
4.653
false
true
false
false
brianwernick/AndroidMarkup
library/src/main/kotlin/com/devbrackets/android/androidmarkup/parser/core/MarkupParser.kt
1
14051
package com.devbrackets.android.androidmarkup.parser.core import android.graphics.Typeface import android.text.Spannable import android.text.Spanned import android.text.style.StyleSpan import com.devbrackets.android.androidmarkup.text.style.ListSpan import java.util.* /** * An abstract base class that supports the Markup editing in the * [com.devbrackets.android.androidmarkup.widget.MarkupEditText] * * * For the simplification of examples the pipe character "|" will represent selection points, * the underscore character "_" will represent the current span, and a the asterisk character "*" * will represent any characters between the span endpoints and the selection points. */ abstract class MarkupParser { /** * Converts the specified markup text in to a Spanned * for use in the [com.devbrackets.android.androidmarkup.widget.MarkupEditText] * * @param text The markup text to convert to a spanned * @return The resulting spanned */ abstract fun toSpanned(text: String): Spanned /** * Converts the specified spanned in to the corresponding markup. The outputs from * this and [.toSpanned] should be interchangeable. * * @param spanned The Spanned to convert to markup * @return The markup representing the Spanned */ abstract fun fromSpanned(spanned: Spanned): String open fun updateSpan(spannable: Spannable, spanType: Int, startIndex: Int, endIndex: Int): Boolean { when (spanType) { SpanType.BOLD -> { style(spannable, startIndex, endIndex, Typeface.BOLD) return true } SpanType.ITALIC -> { style(spannable, startIndex, endIndex, Typeface.ITALIC) return true } SpanType.ORDERED_LIST -> { list(spannable, startIndex, endIndex, true) return true } SpanType.UNORDERED_LIST -> { list(spannable, startIndex, endIndex, false) return true } } return false } protected fun style(spannable: Spannable, selectionStart: Int, selectionEnd: Int, style: Int) { val overlappingSpans = getOverlappingStyleSpans(spannable, selectionStart, selectionEnd, style) var modifiedSpan = false for (span in overlappingSpans) { val spanStart = spannable.getSpanStart(span) val spanEnd = spannable.getSpanEnd(span) if (spanStart == selectionStart && spanEnd == selectionEnd) { modifiedSpan = true spannable.removeSpan(span) continue } modifiedSpan = modifiedSpan or handleSpanStartBeforeSelection(spannable, span, spanStart, spanEnd, selectionStart, selectionEnd) modifiedSpan = modifiedSpan or handleSpanStartAfterSelection(spannable, span, spanStart, spanEnd, selectionStart, selectionEnd) } if (!modifiedSpan) { spannable.setSpan(StyleSpan(style), selectionStart, selectionEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } optimizeSpans(spannable, getOverlappingStyleSpans(spannable, selectionStart - 1, selectionEnd + 1, style)) } protected fun list(spannable: Spannable, selectionStart: Int, selectionEnd: Int, ordered: Boolean) { var selectionStart = selectionStart var selectionEnd = selectionEnd val overlappingSpans = getOverlappingListSpans(spannable, selectionStart, selectionEnd) //Updates the selectionStart to the new line if (selectionStart != 0) { val previousNewline = findPreviousChar(spannable, selectionStart, '\n') selectionStart = if (previousNewline == -1) 0 else previousNewline } //Updates the selectionEnd to the new line if (selectionEnd != spannable.length - 1) { val nextNewline = findNextChar(spannable, selectionEnd, '\n') selectionEnd = if (nextNewline == -1) spannable.length - 1 else nextNewline } var modifiedSpan = false for (span in overlappingSpans) { val spanStart = spannable.getSpanStart(span) val spanEnd = spannable.getSpanEnd(span) if (spanStart == selectionStart && spanEnd == selectionEnd) { modifiedSpan = true spannable.removeSpan(span) continue } modifiedSpan = modifiedSpan or handleSpanStartBeforeSelection(spannable, span, spanStart, spanEnd, selectionStart, selectionEnd) modifiedSpan = modifiedSpan or handleSpanStartAfterSelection(spannable, span, spanStart, spanEnd, selectionStart, selectionEnd) } if (!modifiedSpan) { spannable.setSpan(ListSpan(if (ordered) ListSpan.Type.NUMERICAL else ListSpan.Type.BULLET), selectionStart, selectionEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } optimizeSpans(spannable, getOverlappingListSpans(spannable, selectionStart - 1, selectionEnd + 1)) } /** * If the specified Span starts before or equal to the selection, then we need to update the span end * only if the span ending is less than the `selectionEnd`. If the span ending is * greater than or equal to the `selectionEnd` then the selected area will have the style * removed. * * * The cases that need to be handled below are: * * 1. * The selection start is contained within or equal to the span start and the selection end goes beyond the * span end. (e.g. __|___***| will result in __|______| or |___***| will result in |______|) * * 1. * The selection start is equal to the span start and the span end is contained within the * span. (e.g. |______|__ will result in |******|__) * * 1. * Both the selection start and end are contained within the span. * (e.g. __|______|__ will result in __|******|__) * * 1. * The selection start is contained within the span and the selection end is equal to the * span end. (e.g. __|______| will result in __|******|) */ protected fun handleSpanStartBeforeSelection(spannable: Spannable, span: Any, spanStart: Int, spanEnd: Int, selectionStart: Int, selectionEnd: Int): Boolean { if (spanStart > selectionStart) { //handled by handleSpanStartAfterSelection return false } //Handles the first case listed above if (spanEnd < selectionEnd) { spannable.setSpan(span, spanStart, selectionEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) return true } //Handles the second case listed above if (selectionStart == spanStart && spanEnd > selectionEnd) { spannable.setSpan(span, selectionEnd, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) return true } //Handles the third case listed above if (spanEnd > selectionEnd) { spannable.setSpan(span, spanStart, selectionStart, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) val duplicate = duplicateSpan(span) if (duplicate != null) { spannable.setSpan(duplicate, selectionEnd, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } return true } //Handles the final case listed above spannable.setSpan(span, spanStart, selectionStart, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) return true } /** * If the specified Span starts after the `selectionStart`, then we need to update the span start * to the selection. Additionally, if the Span ends before the `selectionEnd`, we need to * update the span end as well. * * * The cases that need to be handled below are: * * 1. * The selection start is before the `spanStart` and the `selectionEnd` * is after the span end. (e.g. |***___***| will result in |_________|) * * 1. * The selection start is before the `spanStart` and the `selectionEnd` * is before or equal to the span end. (e.g. (|***___| will result in |______| or |***___|___ * will result in |______|___) */ protected fun handleSpanStartAfterSelection(spannable: Spannable, span: Any, spanStart: Int, spanEnd: Int, selectionStart: Int, selectionEnd: Int): Boolean { if (spanStart <= selectionStart) { //handled by handleSpanStartBeforeSelection return false } //Handles the first case listed above if (spanEnd < selectionEnd) { spannable.setSpan(span, selectionStart, selectionEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) return true } //Handles the final case listed above spannable.setSpan(span, selectionStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) return true } protected fun getOverlappingStyleSpans(spannable: Spannable, selectionStart: Int, selectionEnd: Int, style: Int): List<StyleSpan> { var selectionStart = selectionStart var selectionEnd = selectionEnd //Makes sure the start and end are contained in the spannable selectionStart = if (selectionStart < 0) 0 else selectionStart selectionEnd = if (selectionEnd >= spannable.length) spannable.length - 1 else selectionEnd val spans = LinkedList(Arrays.asList(*spannable.getSpans(selectionStart, selectionEnd, StyleSpan::class.java))) //Filters out the non-matching types val iterator = spans.iterator() while (iterator.hasNext()) { val span = iterator.next() if (span.style != style) { iterator.remove() } } return spans } protected fun getOverlappingListSpans(spannable: Spannable, selectionStart: Int, selectionEnd: Int): List<ListSpan> { var selectionStart = selectionStart var selectionEnd = selectionEnd //Makes sure the start and end are contained in the spannable selectionStart = if (selectionStart < 0) 0 else selectionStart selectionEnd = if (selectionEnd >= spannable.length) spannable.length - 1 else selectionEnd return LinkedList(Arrays.asList(*spannable.getSpans(selectionStart, selectionEnd, ListSpan::class.java))) } /** * Optimizes the spans by joining any overlapping or abutting spans of * the same type. This assumes that the specified `spans` * are of the same type. * * NOTE: this method is O(n^2) for `spans` * * @param spannable The spannable that the `spans` are associated with * * @param spans The spans to optimize */ protected fun optimizeSpans(spannable: Spannable, spans: List<*>) { val removeSpans = HashSet<Any>() for (span in spans) { if (removeSpans.contains(span)) { continue } for (compareSpan in spans) { if (span !== compareSpan && !removeSpans.contains(compareSpan) && compareAndMerge(spannable, span!!, compareSpan!!)) { removeSpans.add(compareSpan) } } } // Actually remove any spans that were merged (the compareSpan items) for (span in removeSpans) { spannable.removeSpan(span) } } /** * @param spannable The spannable that the spans to check for overlaps are associated with * * @param lhs The first span object to determine if it overlaps with `rhs`. * If the spans are merged, this will be the span left associated with the * `spannable` * * @param rhs The second span object to determine if it overlaps with `lhs`. * If the spans are merged, this will be the span removed from the * `spannable` * * @return True if the spans have been merged */ protected fun compareAndMerge(spannable: Spannable, lhs: Any, rhs: Any): Boolean { val lhsStart = spannable.getSpanStart(lhs) val lhsEnd = spannable.getSpanEnd(lhs) val rhsStart = spannable.getSpanStart(rhs) val rhsEnd = spannable.getSpanEnd(rhs) if (lhsStart < rhsStart && rhsStart <= lhsEnd) { val end = if (lhsEnd > rhsEnd) lhsEnd else rhsEnd spannable.setSpan(lhs, lhsStart, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) return true } else if (lhsStart >= rhsStart && lhsStart <= rhsEnd) { val end = if (lhsEnd > rhsEnd) lhsEnd else rhsEnd spannable.setSpan(lhs, rhsStart, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) return true } return false } /** * Used to duplicate spans when splitting an existing span in to two. * This would occur when the selection is only a partial of the styled * text and the styling is removed. * * @param span The span to duplicate * @return The duplicate span or null */ protected fun duplicateSpan(span: Any): Any? { if (span is StyleSpan) { return StyleSpan(span.style) } return null } protected fun findPreviousChar(spannable: Spannable, start: Int, character: Char): Int { var start = start if (start < 0) { return -1 } if (start >= spannable.length) { start = spannable.length - 1 } for (i in start downTo 0) { if (spannable[i] == character) { return i } } return -1 } protected fun findNextChar(spannable: Spannable, start: Int, character: Char): Int { var start = start if (start < 0) { start = 0 } if (start >= spannable.length) { return -1 } for (i in start..spannable.length - 1) { if (spannable[i] == character) { return i } } return -1 } }
apache-2.0
328d58945ccd782aa6eb93d4b1b5c262
36.873315
167
0.620027
4.811986
false
false
false
false
sys1yagi/longest-streak-android
app/src/main/java/com/sys1yagi/longeststreakandroid/fragment/AccountSetupFragment.kt
1
6115
package com.sys1yagi.longeststreakandroid.fragment import android.os.Bundle import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.cookpad.android.rxt4a.schedulers.AndroidSchedulers import com.sys1yagi.fragmentcreator.annotation.Args import com.sys1yagi.fragmentcreator.annotation.FragmentCreator import com.sys1yagi.longeststreakandroid.LongestStreakApplication import com.sys1yagi.longeststreakandroid.R import com.sys1yagi.longeststreakandroid.api.GithubService import com.sys1yagi.longeststreakandroid.databinding.FragmentAccountSetupBinding import com.sys1yagi.longeststreakandroid.db.EventLog import com.sys1yagi.longeststreakandroid.db.OrmaDatabase import com.sys1yagi.longeststreakandroid.db.Settings import com.sys1yagi.longeststreakandroid.model.Event import com.sys1yagi.longeststreakandroid.tool.KeyboardManager import com.trello.rxlifecycle.components.support.RxFragment import org.threeten.bp.DateTimeException import org.threeten.bp.ZoneId import retrofit2.Response import rx.schedulers.Schedulers import javax.inject.Inject @FragmentCreator class AccountSetupFragment : RxFragment() { @Inject lateinit var githubService: GithubService lateinit var database: OrmaDatabase @Args(require = false) var isEditMode: Boolean = false lateinit var binding: FragmentAccountSetupBinding // workaround for fragment-creator fun setIsEditMode(isEditMode: Boolean) { this.isEditMode = isEditMode } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AccountSetupFragmentCreator.read(this) (context.applicationContext as LongestStreakApplication).component.inject(this) database = (context.applicationContext as LongestStreakApplication).database } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = FragmentAccountSetupBinding.inflate(inflater); return binding.root } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (Settings.alreadyInitialized(database)) { Settings.getRecord(database).let { binding.editName.setText(it.name) binding.editEmail.setText(it.email) binding.editZoneId.setText(it.zoneId) } } binding.registerButton.setOnClickListener { v -> if (verifyName(binding) && verifyEmail(binding) && verifyZoneId(binding)) { val settings = saveAccount( binding.editName.text.toString(), binding.editEmail.text.toString(), binding.editZoneId.text.toString() ) syncEvents(settings, { openMainFragment(it) }, { it.printStackTrace() showForm() }) } } KeyboardManager.show(context) } fun showLoading(){ binding.settingsForm.visibility = View.GONE binding.loadingContainer.visibility = View.VISIBLE binding.loading.start() } fun showForm(){ binding.settingsForm.visibility = View.VISIBLE binding.loadingContainer.visibility = View.GONE binding.loading.stop() } fun syncEvents(settings: Settings, callback: (Settings) -> Unit, error: (Throwable) -> Unit): Unit { showLoading() database.deleteFromEventLog().execute() githubService.userAllEvents(settings.name) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .compose(bindToLifecycle<List<Event>>()) .subscribe( { events -> events.forEach { database.insertIntoEventLog(EventLog.toEventLog(settings.name, it)) } }, { error.invoke(it) }, { callback.invoke(settings) } ) } fun openMainFragment(settings: Settings) { if (isEditMode) { fragmentManager.popBackStack() } else { fragmentManager.beginTransaction() .replace(R.id.content_frame, MainFragmentCreator.newBuilder().build()) .commit() } } fun saveAccount(name: String, email: String, zoneId: String): Settings { val (settings, saveAction) = Settings.getRecordAndAction(database) settings.name = name settings.email = email settings.zoneId = zoneId return saveAction.invoke(settings) } fun verifyName(binding: FragmentAccountSetupBinding): Boolean { if (TextUtils.isEmpty(binding.editName.text)) { binding.formName.error = "name is empty" return false } else { binding.formName.isErrorEnabled = false return true } } fun verifyEmail(binding: FragmentAccountSetupBinding): Boolean { if (TextUtils.isEmpty(binding.editEmail.text)) { binding.formEmail.error = "email is empty" return false } else { binding.formEmail.isErrorEnabled = false return true } } fun verifyZoneId(binding: FragmentAccountSetupBinding): Boolean { val zoneId = binding.editZoneId.text.toString() try { ZoneId.of(zoneId) } catch(e: DateTimeException) { binding.formZoneId.error = "zoneId is invalid : ${zoneId}" return false } binding.formZoneId.isErrorEnabled = false return true } }
mit
f03c5bf5fe62649304c7f2c98aea2d7f
34.970588
104
0.618643
5.164696
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/onboarding/dialogs/OnboardAdventurePickerDialogController.kt
1
5146
package io.ipoli.android.onboarding.dialogs import android.annotation.SuppressLint import android.graphics.drawable.GradientDrawable import android.os.Bundle import android.support.v7.app.AlertDialog import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import io.ipoli.android.R import io.ipoli.android.common.view.BaseDialogController import io.ipoli.android.common.view.colorRes import io.ipoli.android.common.view.recyclerview.BaseRecyclerViewAdapter import io.ipoli.android.common.view.recyclerview.RecyclerViewViewModel import io.ipoli.android.common.view.recyclerview.SimpleViewHolder import io.ipoli.android.common.view.stringRes import kotlinx.android.synthetic.main.dialog_onboard_pick_avatar.view.* import kotlinx.android.synthetic.main.item_onboard_adventure.view.* import kotlinx.android.synthetic.main.view_dialog_header.view.* class OnboardAdventurePickerDialogController(args: Bundle? = null) : BaseDialogController(args) { private val selectedAdventures = mutableSetOf<Adventure>() private var listener: (List<Adventure>) -> Unit = {} constructor(listener: (List<Adventure>) -> Unit) : this() { this.listener = listener } override fun onHeaderViewCreated(headerView: View?) { headerView!!.dialogHeaderTitle.setText(R.string.choose_adventure) headerView.dialogHeaderIcon.setImageResource(R.drawable.logo) val background = headerView.dialogHeaderIcon.background as GradientDrawable background.setColor(colorRes(R.color.md_light_text_100)) } @SuppressLint("InflateParams") override fun onCreateContentView(inflater: LayoutInflater, savedViewState: Bundle?): View { val view = inflater.inflate(R.layout.dialog_onboard_pick_avatar, null) view.avatarList.layoutManager = LinearLayoutManager(view.context) val adapter = AdventureAdapter() view.avatarList.adapter = adapter adapter.updateAll( listOf( AdventureViewModel( stringRes(R.string.challenge_category_health_name), stringRes(R.string.challenge_category_health_description), Adventure.HEALTH ), AdventureViewModel( stringRes(R.string.adventure_fitness), stringRes(R.string.adventure_fitness_description), Adventure.FITNESS ), AdventureViewModel( stringRes(R.string.adventure_learning), stringRes(R.string.adventure_learning_description), Adventure.LEARNING ), AdventureViewModel( stringRes(R.string.adventure_work), stringRes(R.string.adventure_work_description), Adventure.WORK ), AdventureViewModel( stringRes(R.string.adventure_chores), stringRes(R.string.adventure_chores_description), Adventure.CHORES ), AdventureViewModel( stringRes(R.string.adventure_family_time), stringRes(R.string.adventure_family_time_description), Adventure.FAMILY_TIME ) ) ) return view } override fun onCreateDialog( dialogBuilder: AlertDialog.Builder, contentView: View, savedViewState: Bundle? ): AlertDialog = dialogBuilder .setPositiveButton("Done") { _, _ -> listener(selectedAdventures.toList()) } .create() data class AdventureViewModel( val name: String, val shortDescription: String, val type: Adventure ) : RecyclerViewViewModel { override val id: String get() = name } inner class AdventureAdapter : BaseRecyclerViewAdapter<AdventureViewModel>(R.layout.item_onboard_adventure) { override fun onBindViewModel(vm: AdventureViewModel, view: View, holder: SimpleViewHolder) { view.adventureName.text = vm.name view.adventureShortDescription.text = vm.shortDescription view.adventureCheckBox.setOnCheckedChangeListener { _, isChecked -> if (isChecked) selectedAdventures.add(vm.type) else selectedAdventures.remove(vm.type) } view.setOnClickListener { view.adventureCheckBox.setOnCheckedChangeListener(null) val newChecked = !view.adventureCheckBox.isChecked view.adventureCheckBox.isChecked = newChecked if (newChecked) selectedAdventures.add(vm.type) else selectedAdventures.remove(vm.type) view.adventureCheckBox.setOnCheckedChangeListener { _, isChecked -> if (isChecked) selectedAdventures.add(vm.type) else selectedAdventures.remove(vm.type) } } } } enum class Adventure { HEALTH, FITNESS, LEARNING, WORK, CHORES, FAMILY_TIME } }
gpl-3.0
fd596d6f291206b4558b3537f86b1468
39.849206
106
0.648271
5.000972
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/TreeMultiparentEntity.kt
1
3330
// 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.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child interface TreeMultiparentRootEntity : WorkspaceEntityWithSymbolicId { val data: String val children: List<@Child TreeMultiparentLeafEntity> override val symbolicId: TreeMultiparentSymbolicId get() = TreeMultiparentSymbolicId(data) //region generated code @GeneratedCodeApiVersion(1) interface Builder : TreeMultiparentRootEntity, WorkspaceEntity.Builder<TreeMultiparentRootEntity>, ObjBuilder<TreeMultiparentRootEntity> { override var entitySource: EntitySource override var data: String override var children: List<TreeMultiparentLeafEntity> } companion object : Type<TreeMultiparentRootEntity, Builder>() { operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): TreeMultiparentRootEntity { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: TreeMultiparentRootEntity, modification: TreeMultiparentRootEntity.Builder.() -> Unit) = modifyEntity( TreeMultiparentRootEntity.Builder::class.java, entity, modification) //endregion interface TreeMultiparentLeafEntity : WorkspaceEntity { val data: String val mainParent: TreeMultiparentRootEntity? val leafParent: TreeMultiparentLeafEntity? val children: List<@Child TreeMultiparentLeafEntity> //region generated code @GeneratedCodeApiVersion(1) interface Builder : TreeMultiparentLeafEntity, WorkspaceEntity.Builder<TreeMultiparentLeafEntity>, ObjBuilder<TreeMultiparentLeafEntity> { override var entitySource: EntitySource override var data: String override var mainParent: TreeMultiparentRootEntity? override var leafParent: TreeMultiparentLeafEntity? override var children: List<TreeMultiparentLeafEntity> } companion object : Type<TreeMultiparentLeafEntity, Builder>() { operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): TreeMultiparentLeafEntity { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: TreeMultiparentLeafEntity, modification: TreeMultiparentLeafEntity.Builder.() -> Unit) = modifyEntity( TreeMultiparentLeafEntity.Builder::class.java, entity, modification) //endregion data class TreeMultiparentSymbolicId(val data: String) : SymbolicEntityId<TreeMultiparentRootEntity> { override val presentableName: String get() = data }
apache-2.0
86279f2e572eafcf3b09d0235b7566dc
37.72093
140
0.770571
5.615514
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/stash/ui/GitUnstashAsDialog.kt
2
3692
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.stash.ui import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.vcs.changes.ui.CurrentBranchComponent import com.intellij.ui.DocumentAdapter import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.JBTextField import com.intellij.ui.dsl.builder.bindSelected import com.intellij.ui.dsl.builder.bindText import com.intellij.ui.dsl.builder.panel import com.intellij.vcs.branch.BranchPresentation import git4idea.GitUtil import git4idea.i18n.GitBundle import git4idea.ui.StashInfo import git4idea.validators.validateName import javax.swing.JComponent import javax.swing.event.DocumentEvent internal class GitUnstashAsDialog(private val project: Project, private val stashInfo: StashInfo) : DialogWrapper(project) { private lateinit var branchTextField: JBTextField private lateinit var popStashCheckbox: JBCheckBox private lateinit var keepIndexCheckbox: JBCheckBox var popStash: Boolean = false private set var keepIndex: Boolean = false private set var branch: String = "" private set init { title = GitBundle.message("stash.unstash.changes.in.root.dialog.title", stashInfo.root.presentableName) init() updateOkButtonText() } override fun createCenterPanel(): JComponent { return panel { row(GitBundle.message("stash.unstash.changes.current.branch.label")) { label(CurrentBranchComponent.getCurrentBranch(project, stashInfo.root)?.let { BranchPresentation.getPresentableText(it) } ?: "") } row(GitBundle.message("unstash.branch.label")) { branchTextField = textField() .bindText(::branch) .validationOnInput { if (it.text.isBlank()) return@validationOnInput null val repository = GitUtil.getRepositoryManager(project).getRepositoryForRootQuick(stashInfo.root) ?: return@validationOnInput null validateName(listOf(repository), it.text) } .applyToComponent { document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { onBranchChanged() } }) } .focused() .component } row { popStashCheckbox = checkBox(GitBundle.message("unstash.pop.stash")) .applyToComponent { toolTipText = GitBundle.message("unstash.pop.stash.tooltip") addActionListener { onPopStashChanged() } } .bindSelected(::popStash) .component } row { keepIndexCheckbox = checkBox(GitBundle.message("unstash.reinstate.index")) .applyToComponent { toolTipText = GitBundle.message("unstash.reinstate.index.tooltip") } .bindSelected(::popStash) .component } } } private fun onBranchChanged() { updateEnabled() updateOkButtonText() } private fun onPopStashChanged() { updateOkButtonText() } private fun updateEnabled() { val hasBranch = branchTextField.text.isNotBlank() popStashCheckbox.isEnabled = !hasBranch keepIndexCheckbox.isEnabled = !hasBranch } private fun updateOkButtonText() { val buttonText = when { branchTextField.text.isNotBlank() -> { GitBundle.message("unstash.button.branch") } popStashCheckbox.isSelected -> GitBundle.message("unstash.button.pop") else -> GitBundle.message("unstash.button.apply") } setOKButtonText(buttonText) } }
apache-2.0
e36c6067a0cf63051ea53a311c0b7b80
33.504673
136
0.693933
4.546798
false
false
false
false
toss/android-delegationadapter
library-kotlin/src/main/kotlin/im/toss/delegationadapter/kotlin/ListItemAdapterDelegate.kt
1
2644
package im.toss.delegationadapter.kotlin import android.support.annotation.LayoutRes import android.view.ViewGroup import com.hannesdorfmann.adapterdelegates3.AbsListItemAdapterDelegate /** * More simple way to create [AbsListItemAdapterDelegate] with less boiler plate code * @param <T> The type of the item that is managed by this AdapterDelegate. </T> */ class ListItemAdapterDelegate<I : T, T> constructor( @LayoutRes val layoutId: Int, val typeChecker: ((T) -> Boolean)? = null, val onViewHolderCreate: ViewHolderCreateListener? = null, val viewBinder: ((ItemViewHolder<I>, I) -> Unit)? = null, val viewBinderLong: ((ItemViewHolder<I>, I, List<Any>?) -> Unit)? = null ) : AbsListItemAdapterDelegate<I, T, ItemViewHolder<I>>() { override fun isForViewType(item: T, items: List<T>, position: Int): Boolean { return typeChecker?.invoke(item) ?: false } override fun onCreateViewHolder(parent: ViewGroup): ItemViewHolder<I> { val viewHolder = ItemViewHolder.create<I>(parent, layoutId) onViewHolderCreate?.onViewHolderCreate(viewHolder) return viewHolder } override fun onBindViewHolder(item: I, viewHolder: ItemViewHolder<I>, payloads: List<Any>) { viewHolder.item = item viewBinderLong?.invoke(viewHolder, item, payloads) ?: viewBinder?.invoke(viewHolder, item) } class Builder<I : T, T> { private var layoutId: Int = 0 private var typeChecker: ((T) -> Boolean)? = null private var onViewHolderCreate: ViewHolderCreateListener? = null private var viewBinder: ((ItemViewHolder<I>, I) -> Unit)? = null private var viewBinderLong: ((ItemViewHolder<I>, I, List<Any>?) -> Unit)? = null fun typeChecker(typeChecker: (T) -> Boolean): Builder<I, T> { this.typeChecker = typeChecker return this } fun layout(@LayoutRes layoutId: Int): Builder<I, T> { this.layoutId = layoutId return this } fun binder(binder: (ItemViewHolder<I>, I) -> Unit): Builder<I, T> { this.viewBinder = binder return this } fun binder(binder: (ItemViewHolder<I>, I, List<Any>?) -> Unit): Builder<I, T> { this.viewBinderLong = binder return this } fun onViewHolderCreate(callback: ViewHolderCreateListener): Builder<I, T> { this.onViewHolderCreate = callback return this } fun build(): ListItemAdapterDelegate<I, T> { return ListItemAdapterDelegate( layoutId = layoutId, typeChecker = typeChecker, viewBinder = viewBinder, viewBinderLong = viewBinderLong, onViewHolderCreate = onViewHolderCreate ) } } }
apache-2.0
5f695756ddc070a911360172b770469d
32.468354
94
0.68003
4.144201
false
false
false
false
onnerby/musikcube
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/albums/adapter/AlbumBrowseAdapter.kt
2
4071
package io.casey.musikcube.remote.ui.albums.adapter import android.content.SharedPreferences import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.request.RequestOptions import io.casey.musikcube.remote.R import io.casey.musikcube.remote.injection.GlideApp import io.casey.musikcube.remote.service.websocket.model.IAlbum import io.casey.musikcube.remote.ui.shared.extension.fallback import io.casey.musikcube.remote.ui.shared.extension.getColorCompat import io.casey.musikcube.remote.ui.shared.extension.titleEllipsizeMode import io.casey.musikcube.remote.ui.shared.mixin.PlaybackMixin import io.casey.musikcube.remote.ui.shared.util.AlbumArtLookup.getUrl import io.casey.musikcube.remote.ui.shared.util.Size class AlbumBrowseAdapter(private val listener: EventListener, private val playback: PlaybackMixin, val prefs: SharedPreferences) : RecyclerView.Adapter<AlbumBrowseAdapter.ViewHolder>() { interface EventListener { fun onItemClicked(album: IAlbum) fun onActionClicked(view: View, album: IAlbum) } private var model: List<IAlbum> = listOf() private val ellipsizeMode = titleEllipsizeMode(prefs) internal fun setModel(model: List<IAlbum>) { this.model = model notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val inflater = LayoutInflater.from(parent.context) val view = inflater.inflate(R.layout.simple_list_item, parent, false) val action = view.findViewById<View>(R.id.action) view.setOnClickListener { v -> listener.onItemClicked(v.tag as IAlbum) } action.setOnClickListener { v -> listener.onActionClicked(v, v.tag as IAlbum) } return ViewHolder(view, playback, ellipsizeMode) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(model[position]) } override fun getItemCount(): Int = model.size class ViewHolder internal constructor( itemView: View, val playback: PlaybackMixin, ellipsizeMode: TextUtils.TruncateAt) : RecyclerView.ViewHolder(itemView) { private val title = itemView.findViewById<TextView>(R.id.title) private val subtitle = itemView.findViewById<TextView>(R.id.subtitle) private val artwork = itemView.findViewById<ImageView>(R.id.artwork) private val action = itemView.findViewById<View>(R.id.action) init { title.ellipsize = ellipsizeMode } internal fun bind(album: IAlbum) { val playing = playback.service.playingTrack val playingId = playing.albumId var titleColor = R.color.theme_foreground var subtitleColor = R.color.theme_disabled_foreground if (playingId != -1L && album.id == playingId) { titleColor = R.color.theme_green subtitleColor = R.color.theme_yellow } artwork.visibility = View.VISIBLE GlideApp .with(itemView.context) .load(getUrl(album, Size.Large)) .apply(OPTIONS) .into(artwork) title.text = fallback(album.value, "-") title.setTextColor(getColorCompat(titleColor)) subtitle.text = fallback(album.albumArtist, "-") subtitle.setTextColor(getColorCompat(subtitleColor)) itemView.tag = album action.tag = album } companion object { val OPTIONS = RequestOptions() .placeholder(R.drawable.ic_art_placeholder) .error(R.drawable.ic_art_placeholder) .diskCacheStrategy(DiskCacheStrategy.RESOURCE) } } }
bsd-3-clause
17ef8548b596cfa325c2fe9f50066d18
37.056075
87
0.676492
4.620885
false
false
false
false
senyuyuan/Gluttony
gluttony/src/main/java/dao/yuan/sen/gluttony/sqlite_module/operator/sqlite_save.kt
1
2065
package dao.yuan.sen.gluttony.sqlite_module.operator import android.database.sqlite.SQLiteDatabase import com.google.gson.Gson import dao.yuan.sen.gluttony.Gluttony import dao.yuan.sen.gluttony.sqlite_module.annotation.PrimaryKey import dao.yuan.sen.gluttony.sqlite_module.e import org.jetbrains.anko.db.* import kotlin.reflect.declaredMemberProperties import kotlin.reflect.defaultType import kotlin.reflect.primaryConstructor /** * Created by Administrator on 2016/11/28. */ inline fun <T : Any> SQLiteDatabase.testCreateTable(data: T) { val mClass = data.javaClass.kotlin val name = "${mClass.simpleName}" val parameters = mClass.primaryConstructor!!.parameters val tablePairs = parameters.associate { val pair = it.name!! to it.type.let { when (it) { Boolean::class.defaultType, String::class.defaultType -> TEXT Int::class.defaultType -> INTEGER Float::class.defaultType, Double::class.defaultType -> REAL else -> TEXT } } if (it.annotations.map { it.annotationClass }.contains(PrimaryKey::class)) pair.copy(second = pair.second + PRIMARY_KEY + UNIQUE).apply { e("reflect_columns", "$first:$second") } else pair.apply { e("reflect_columns", "$first:$second") } }.toList().toTypedArray() this.createTable(name, true, *tablePairs) } fun <T : Any> T.save(): Long { val mClass = this.javaClass.kotlin val name = "${mClass.simpleName}" val properties = mClass.declaredMemberProperties val valuePairs = properties.associate { e("reflect_values", "${it.name}:${it.get(this).toString()}") it.name to it.get(this).let { when (it) { true -> "true" false -> "false" is String, is Int, is Float, is Double -> it else -> Gson().toJson(it) } } }.toList().toTypedArray() return Gluttony.database.use { testCreateTable(this@save) insert(name, *valuePairs) } }
apache-2.0
f4a4062939ce5e96138e6d1950810b19
30.769231
186
0.634867
4.171717
false
false
false
false
dhis2/dhis2-android-sdk
core/src/androidTest/java/org/hisp/dhis/android/core/trackedentity/internal/BasePayloadGeneratorMockIntegration.kt
1
12523
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.trackedentity.internal import org.hisp.dhis.android.core.arch.call.executors.internal.D2CallExecutor import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore import org.hisp.dhis.android.core.common.ObjectWithUid import org.hisp.dhis.android.core.common.State import org.hisp.dhis.android.core.data.relationship.RelationshipSamples import org.hisp.dhis.android.core.data.trackedentity.TrackedEntityDataValueSamples import org.hisp.dhis.android.core.data.trackedentity.TrackedEntityInstanceSamples import org.hisp.dhis.android.core.enrollment.Enrollment import org.hisp.dhis.android.core.enrollment.EnrollmentInternalAccessor import org.hisp.dhis.android.core.enrollment.internal.EnrollmentStore import org.hisp.dhis.android.core.enrollment.internal.EnrollmentStoreImpl import org.hisp.dhis.android.core.event.Event import org.hisp.dhis.android.core.event.internal.EventStore import org.hisp.dhis.android.core.event.internal.EventStoreImpl import org.hisp.dhis.android.core.maintenance.D2Error import org.hisp.dhis.android.core.maintenance.internal.ForeignKeyCleanerImpl import org.hisp.dhis.android.core.organisationunit.internal.OrganisationUnitStore.create import org.hisp.dhis.android.core.program.internal.ProgramStageStore import org.hisp.dhis.android.core.program.internal.ProgramStore import org.hisp.dhis.android.core.program.internal.ProgramStoreInterface import org.hisp.dhis.android.core.relationship.RelationshipConstraintType import org.hisp.dhis.android.core.relationship.RelationshipHelper import org.hisp.dhis.android.core.relationship.RelationshipItem import org.hisp.dhis.android.core.relationship.internal.RelationshipItemStoreImpl import org.hisp.dhis.android.core.relationship.internal.RelationshipStoreImpl import org.hisp.dhis.android.core.relationship.internal.RelationshipTypeStore import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstance import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceInternalAccessor import org.hisp.dhis.android.core.trackedentity.TrackedEntityType import org.hisp.dhis.android.core.utils.integration.mock.BaseMockIntegrationTestMetadataEnqueable import org.junit.After import org.junit.BeforeClass open class BasePayloadGeneratorMockIntegration : BaseMockIntegrationTestMetadataEnqueable() { protected val teiId = "teiId" protected val enrollment1Id = "enrollment1Id" protected val enrollment2Id = "enrollment2Id" protected val enrollment3Id = "enrollment3Id" protected val event1Id = "event1Id" protected val event2Id = "event2Id" protected val event3Id = "event3Id" protected val singleEventId = "singleEventId" @After @Throws(D2Error::class) fun tearDown() { d2.wipeModule().wipeData() } protected fun storeTrackerData() { val orgUnit = create(databaseAdapter).selectFirst() val teiType = TrackedEntityTypeStore.create(databaseAdapter).selectFirst() val program = d2.programModule().programs().one().blockingGet() val programStage = ProgramStageStore.create(databaseAdapter).selectFirst() val dataValue1 = TrackedEntityDataValueSamples.get().toBuilder().event(event1Id).build() val event1 = Event.builder() .uid(event1Id) .enrollment(enrollment1Id) .organisationUnit(orgUnit!!.uid()) .program(program.uid()) .programStage(programStage!!.uid()) .syncState(State.TO_UPDATE) .aggregatedSyncState(State.TO_UPDATE) .trackedEntityDataValues(listOf(dataValue1)) .build() val enrollment1 = EnrollmentInternalAccessor.insertEvents(Enrollment.builder(), listOf(event1)) .uid(enrollment1Id) .program(program.uid()) .organisationUnit(orgUnit.uid()) .syncState(State.TO_POST) .aggregatedSyncState(State.TO_POST) .trackedEntityInstance(teiId) .build() val dataValue2 = TrackedEntityDataValueSamples.get().toBuilder().event(event2Id).build() val event2 = Event.builder() .uid(event2Id) .enrollment(enrollment2Id) .organisationUnit(orgUnit.uid()) .program(program.uid()) .programStage(programStage.uid()) .syncState(State.SYNCED_VIA_SMS) .aggregatedSyncState(State.SYNCED_VIA_SMS) .trackedEntityDataValues(listOf(dataValue2)) .build() val enrollment2 = EnrollmentInternalAccessor.insertEvents(Enrollment.builder(), listOf(event2)) .uid(enrollment2Id) .program(program.uid()) .organisationUnit(orgUnit.uid()) .syncState(State.TO_POST) .aggregatedSyncState(State.TO_POST) .trackedEntityInstance(teiId) .build() val dataValue3 = TrackedEntityDataValueSamples.get().toBuilder().event(event3Id).build() val event3 = Event.builder() .uid(event3Id) .enrollment(enrollment3Id) .organisationUnit(orgUnit.uid()) .program(program.uid()) .programStage(programStage.uid()) .syncState(State.ERROR) .aggregatedSyncState(State.ERROR) .trackedEntityDataValues(listOf(dataValue3)) .build() val enrollment3 = EnrollmentInternalAccessor.insertEvents(Enrollment.builder(), listOf(event3)) .uid(enrollment3Id) .program(program.uid()) .organisationUnit(orgUnit.uid()) .syncState(State.TO_POST) .aggregatedSyncState(State.SYNCED) .trackedEntityInstance(teiId) .build() val tei = TrackedEntityInstanceInternalAccessor.insertEnrollments( TrackedEntityInstance.builder(), listOf(enrollment1, enrollment2, enrollment3) ) .uid(teiId) .trackedEntityType(teiType!!.uid()) .organisationUnit(orgUnit.uid()) .syncState(State.TO_POST) .aggregatedSyncState(State.TO_POST) .build() val singleEventDataValue = TrackedEntityDataValueSamples.get().toBuilder().event(singleEventId).build() val singleEvent = Event.builder() .uid(singleEventId) .organisationUnit(orgUnit.uid()) .program(program.uid()) .programStage(programStage.uid()) .syncState(State.TO_POST) .aggregatedSyncState(State.TO_POST) .trackedEntityDataValues(listOf(singleEventDataValue)) .build() teiStore.insert(tei) enrollmentStore.insert(enrollment1) enrollmentStore.insert(enrollment2) enrollmentStore.insert(enrollment3) eventStore.insert(event1) eventStore.insert(event2) eventStore.insert(event3) eventStore.insert(singleEvent) teiDataValueStore.insert(dataValue1) teiDataValueStore.insert(dataValue2) teiDataValueStore.insert(dataValue3) teiDataValueStore.insert(singleEventDataValue) } protected fun storeSimpleTrackedEntityInstance(teiUid: String, state: State) { val orgUnit = create(databaseAdapter).selectFirst() val teiType = TrackedEntityTypeStore.create(databaseAdapter).selectFirst() TrackedEntityInstanceStoreImpl.create(databaseAdapter).insert( TrackedEntityInstanceSamples.get().toBuilder() .uid(teiUid) .trackedEntityType(teiType!!.uid()) .organisationUnit(orgUnit!!.uid()) .syncState(state) .aggregatedSyncState(state) .build() ) } @Throws(D2Error::class) protected fun storeRelationship( relationshipUid: String, from: String, to: String ) { storeRelationship(relationshipUid, RelationshipHelper.teiItem(from), RelationshipHelper.teiItem(to)) } @Throws(D2Error::class) protected fun storeRelationship( relationshipUid: String, from: RelationshipItem, to: RelationshipItem ) { val relationshipType = RelationshipTypeStore.create(databaseAdapter).selectFirst() val executor = D2CallExecutor.create(databaseAdapter) executor.executeD2CallTransactionally<Any?> { RelationshipStoreImpl.create(databaseAdapter).insert( RelationshipSamples.get230(relationshipUid, from, to).toBuilder() .relationshipType(relationshipType!!.uid()) .syncState(State.TO_POST) .build() ) RelationshipItemStoreImpl.create(databaseAdapter).insert( from.toBuilder() .relationship(ObjectWithUid.create(relationshipUid)) .relationshipItemType(RelationshipConstraintType.FROM) .build() ) RelationshipItemStoreImpl.create(databaseAdapter).insert( to.toBuilder() .relationship(ObjectWithUid.create(relationshipUid)) .relationshipItemType(RelationshipConstraintType.TO) .build() ) ForeignKeyCleanerImpl.create(databaseAdapter).cleanForeignKeyErrors() null } } protected fun getEnrollments(trackedEntityInstance: TrackedEntityInstance): List<Enrollment> { return TrackedEntityInstanceInternalAccessor.accessEnrollments(trackedEntityInstance) } protected fun getEvents(enrollment: Enrollment): List<Event> { return EnrollmentInternalAccessor.accessEvents(enrollment) } protected companion object { internal lateinit var oldTrackerPayloadGenerator: OldTrackerImporterPayloadGenerator internal lateinit var teiStore: TrackedEntityInstanceStore internal lateinit var teiDataValueStore: TrackedEntityDataValueStore internal lateinit var eventStore: EventStore internal lateinit var enrollmentStore: EnrollmentStore internal lateinit var trackedEntityTypeStore: IdentifiableObjectStore<TrackedEntityType> internal lateinit var programStore: ProgramStoreInterface @BeforeClass @JvmStatic @Throws(Exception::class) fun setUp() { setUpClass() oldTrackerPayloadGenerator = objects.d2DIComponent.oldTrackerImporterPayloadGenerator() teiStore = TrackedEntityInstanceStoreImpl.create(databaseAdapter) teiDataValueStore = TrackedEntityDataValueStoreImpl.create(databaseAdapter) eventStore = EventStoreImpl.create(databaseAdapter) enrollmentStore = EnrollmentStoreImpl.create(databaseAdapter) trackedEntityTypeStore = TrackedEntityTypeStore.create(databaseAdapter) programStore = ProgramStore.create(databaseAdapter) } } }
bsd-3-clause
ecff9d2e5ccdd7ef96c8f4fb05ee8e49
44.871795
111
0.703426
4.838872
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinUQualifiedReferenceExpression.kt
4
1545
// 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.uast.kotlin import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.internal.DelegatedMultiResolve @ApiStatus.Internal class KotlinUQualifiedReferenceExpression( override val sourcePsi: KtDotQualifiedExpression, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), UQualifiedReferenceExpression, DelegatedMultiResolve, KotlinUElementWithType, KotlinEvaluatableUElement { override val receiver by lz { baseResolveProviderService.baseKotlinConverter.convertOrEmpty(sourcePsi.receiverExpression, this) } override val selector by lz { baseResolveProviderService.baseKotlinConverter.convertOrEmpty(sourcePsi.selectorExpression, this) } override val accessType = UastQualifiedExpressionAccessType.SIMPLE override fun resolve(): PsiElement? = sourcePsi.selectorExpression?.let { baseResolveProviderService.resolveToDeclaration(it) } override val resolvedName: String? get() = (resolve() as? PsiNamedElement)?.name override val referenceNameElement: UElement? get() = when (val selector = selector) { is UCallExpression -> selector.methodIdentifier else -> super.referenceNameElement } }
apache-2.0
79cf9b9507830f46925ed43b1935f082
47.28125
158
0.79288
5.478723
false
false
false
false
kingargyle/serenity-android
serenity-app/src/main/kotlin/us/nineworlds/serenity/ui/video/player/ExoplayerPresenter.kt
1
6855
package us.nineworlds.serenity.ui.video.player import android.view.View import com.birbit.android.jobqueue.JobManager import com.google.android.exoplayer2.ExoPlaybackException import com.google.android.exoplayer2.Player import com.google.android.exoplayer2.ui.PlayerControlView import moxy.InjectViewState import moxy.MvpPresenter import moxy.viewstate.strategy.SkipStrategy import moxy.viewstate.strategy.StateStrategyType import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode.MAIN import toothpick.Toothpick import us.nineworlds.serenity.common.android.mediacodec.MediaCodecInfoUtil import us.nineworlds.serenity.common.annotations.InjectionConstants import us.nineworlds.serenity.common.annotations.OpenForTesting import us.nineworlds.serenity.common.rest.SerenityClient import us.nineworlds.serenity.core.logger.Logger import us.nineworlds.serenity.core.model.VideoContentInfo import us.nineworlds.serenity.core.util.AndroidHelper import us.nineworlds.serenity.events.video.OnScreenDisplayEvent import us.nineworlds.serenity.injection.ForVideoQueue import us.nineworlds.serenity.jobs.video.StartPlaybackJob import us.nineworlds.serenity.jobs.video.StopPlaybackJob import us.nineworlds.serenity.jobs.video.UpdatePlaybackPostionJob import us.nineworlds.serenity.jobs.video.WatchedStatusJob import us.nineworlds.serenity.ui.video.player.ExoplayerContract.ExoplayerPresenter import us.nineworlds.serenity.ui.video.player.ExoplayerContract.ExoplayerView import java.util.LinkedList import javax.inject.Inject @OpenForTesting @InjectViewState @StateStrategyType(SkipStrategy::class) class ExoplayerPresenter : MvpPresenter<ExoplayerView>(), ExoplayerPresenter, PlayerControlView.VisibilityListener, Player.EventListener { @Inject lateinit var logger: Logger @field:[Inject ForVideoQueue] internal lateinit var videoQueue: LinkedList<VideoContentInfo> @Inject internal lateinit var serenityClient: SerenityClient @Inject internal lateinit var eventBus: EventBus @Inject internal lateinit var jobManager: JobManager @Inject internal lateinit var androidHelper: AndroidHelper internal lateinit var video: VideoContentInfo private var onScreenControllerShowing: Boolean = false override fun attachView(view: ExoplayerView?) { Toothpick.inject(this, Toothpick.openScope(InjectionConstants.APPLICATION_SCOPE)) super.attachView(view) eventBus.register(this) } override fun detachView(view: ExoplayerView?) { super.detachView(view) eventBus.unregister(this) } override fun updateWatchedStatus() { jobManager.addJobInBackground(WatchedStatusJob(video.id())) } override fun onSeekProcessed() { } override fun onPositionDiscontinuity(reason: Int) { } override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) { } override fun onPlayerError(error: ExoPlaybackException) { logger.error("Play back error", Exception(error)) } override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) { if (Player.STATE_ENDED == playbackState) { stopPlaying(video.resumeOffset.toLong()) viewState.playbackEnded() return } } override fun onLoadingChanged(isLoading: Boolean) { } override fun onRepeatModeChanged(repeatMode: Int) { } override fun videoId(): String = video.id() override fun stopPlaying(currentPostion: Long) { jobManager.addJobInBackground(StopPlaybackJob(video.id(), currentPostion)) } override fun startPlaying() { jobManager.addJobInBackground(StartPlaybackJob(video.id())) } override fun onVisibilityChange(visibility: Int) { if (visibility == View.GONE) { logger.debug("Controller View was hidden") onScreenControllerShowing = false } if (visibility == View.VISIBLE) { logger.debug("Controller View was shown") onScreenControllerShowing = true } } override fun isHudShowing(): Boolean = onScreenControllerShowing @Subscribe(threadMode = MAIN) fun onOnScreenDisplayEvent(event: OnScreenDisplayEvent) { if (event.isShowing) { viewState.hideController() } else { viewState.showController() } } override fun updateServerPlaybackPosition(currentPostion: Long) { video.resumeOffset = currentPostion.toInt() jobManager.addJobInBackground(UpdatePlaybackPostionJob(video)) } override fun playBackFromVideoQueue(autoresume: Boolean) { if (videoQueue.isEmpty()) { return } this.video = videoQueue.poll() if (!autoresume && video.isPartiallyWatched) { viewState.showResumeDialog(video) return } playVideo() } override fun playVideo() { val videoUrl: String = transcoderUrl() viewState.initializePlayer(videoUrl, video.resumeOffset) } internal fun isDirectPlaySupportedForContainer(video: VideoContentInfo): Boolean { val mediaCodecInfoUtil = MediaCodecInfoUtil() video.container?.let { video.container = if (video.container.contains("mp4")) { "mp4" } else { video.container } val isVideoContainerSupported = mediaCodecInfoUtil.isExoPlayerContainerSupported("video/${video.container.substringBefore(",")}") var isAudioCodecSupported = selectCodec(mediaCodecInfoUtil.findCorrectAudioMimeType("audio/${video.audioCodec}")) val isVideoSupported = selectCodec(mediaCodecInfoUtil.findCorrectVideoMimeType("video/${video.videoCodec}")) isAudioCodecSupported = if (androidHelper.isNvidiaShield || androidHelper.isBravia) { when (video.audioCodec.toLowerCase()) { "eac3", "ac3", "dts", "truehd" -> true else -> isAudioCodecSupported } } else { isAudioCodecSupported } logger.debug("Audio Codec: ${video.audioCodec} support returned $isAudioCodecSupported") logger.debug("Video Codec: ${video.videoCodec} support returned $isVideoSupported") logger.debug("Video Container: ${video.container} support returned $isVideoContainerSupported") if (isVideoSupported && isAudioCodecSupported && isVideoContainerSupported!!) { return true } } return false } private fun transcoderUrl(): String { logger.debug("ExoPlayerPresenter: Container: ${video.container} Audio: ${video.audioCodec}") if (isDirectPlaySupportedForContainer(video)) { logger.debug("ExoPlayerPresenter: Direct playing ${video.directPlayUrl}") return video.directPlayUrl } val transcodingUrl = serenityClient.createTranscodeUrl(video.id(), video.resumeOffset) logger.debug("ExoPlayerPresenter: Transcoding Url: $transcodingUrl") return transcodingUrl } private fun selectCodec(mimeType: String): Boolean = MediaCodecInfoUtil().isCodecSupported(mimeType) }
mit
504a419e884277cddf15484b6a8024f4
31.037383
105
0.757549
4.57
false
false
false
false
securityfirst/Umbrella_android
app/src/main/java/org/secfirst/umbrella/feature/reader/view/rss/RssController.kt
1
4808
package org.secfirst.umbrella.feature.reader.view.rss import android.app.AlertDialog import android.os.Bundle import android.os.Parcelable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.core.content.ContextCompat import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import com.bluelinelabs.conductor.RouterTransaction import kotlinx.android.synthetic.main.add_rss_dialog.view.* import kotlinx.android.synthetic.main.rss_view.* import kotlinx.android.synthetic.main.rss_view.view.* import org.jetbrains.anko.design.longSnackbar import org.secfirst.umbrella.R import org.secfirst.umbrella.UmbrellaApplication import org.secfirst.umbrella.component.SwipeToDeleteCallback import org.secfirst.umbrella.data.database.reader.RSS import org.secfirst.umbrella.feature.base.view.BaseController import org.secfirst.umbrella.feature.reader.DaggerReanderComponent import org.secfirst.umbrella.feature.reader.interactor.ReaderBaseInteractor import org.secfirst.umbrella.feature.reader.presenter.ReaderBasePresenter import org.secfirst.umbrella.feature.reader.view.ReaderView import org.secfirst.umbrella.misc.initRecyclerView import javax.inject.Inject class RssController : BaseController(), ReaderView { @Inject internal lateinit var presenter: ReaderBasePresenter<ReaderView, ReaderBaseInteractor> private lateinit var rssAdapter: RssAdapter private lateinit var rssDialogView: View private lateinit var alertDialog: AlertDialog private var stateRecycler: Parcelable? = null private val onClick: (RSS) -> Unit = this::onClickOpenArticle override fun onInject() { DaggerReanderComponent.builder() .application(UmbrellaApplication.instance) .build() .inject(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle?): View { val view = inflater.inflate(R.layout.rss_view, container, false) rssDialogView = inflater.inflate(R.layout.add_rss_dialog, container, false) alertDialog = AlertDialog .Builder(activity) .setView(rssDialogView) .create() presenter.onAttach(this) initDeleteChecklistItem(view) rssAdapter = RssAdapter(onClick) view.rssRecycleView.initRecyclerView(rssAdapter) rssAdapter.removeAll() presenter.submitFetchRss() rssDialogView.rssOk.setOnClickListener { addRss() } rssDialogView.rssCancel.setOnClickListener { alertDialog.dismiss() } view.addRss.setOnClickListener { alertDialog.show() } return view } private fun onClickOpenArticle(rss: RSS) { parentController?.router?.pushController(RouterTransaction.with(ArticleController(rss))) } private fun addRss() { presenter.submitInsertRss(RSS(rssDialogView.rssEditText.text.toString())) alertDialog.dismiss() } override fun showRss(rss: RSS) { rssAdapter.add(rss) } override fun showRssError() { val snackBar = rssView?.longSnackbar(context.resources.getString(R.string.rss_message_error)) val snackView = snackBar?.view snackView?.setBackgroundColor(ContextCompat.getColor(context, R.color.umbrella_purple_dark)) val textView = snackView?.findViewById<TextView>(com.google.android.material.R.id.snackbar_text) textView?.setTextColor(ContextCompat.getColor(context, R.color.white)) } override fun showNewestRss(rss: RSS) = rssAdapter.add(rss) override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) stateRecycler = rssRecycleView?.layoutManager?.onSaveInstanceState() outState.putParcelable(EXTRA_RECYCLER_STATE, stateRecycler) } override fun onRestoreInstanceState(saveInstanceState: Bundle) { super.onRestoreInstanceState(saveInstanceState) stateRecycler = saveInstanceState.getParcelable(EXTRA_RECYCLER_STATE) } private fun initDeleteChecklistItem(view: View) { val swipeHandler = object : SwipeToDeleteCallback(context) { override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val position = viewHolder.adapterPosition val rssSelected = rssAdapter.getAt(position) presenter.submitDeleteRss(rssSelected) rssAdapter.removeAt(position) } } val itemTouchHelper = ItemTouchHelper(swipeHandler) itemTouchHelper.attachToRecyclerView(view.rssRecycleView) } companion object { private const val EXTRA_RECYCLER_STATE = "extra_recycler_state" } }
gpl-3.0
f9b506109e2f9f86256ecaafcc494d89
39.754237
110
0.736897
4.750988
false
false
false
false
sreich/ore-infinium
core/src/com/ore/infinium/HotbarInventoryView.kt
1
13906
/** MIT License Copyright (c) 2016 Shaun Reich <[email protected]> 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.ore.infinium import com.artemis.ComponentMapper import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.scenes.scene2d.Actor import com.badlogic.gdx.scenes.scene2d.InputEvent import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.scenes.scene2d.Touchable import com.badlogic.gdx.scenes.scene2d.ui.Image import com.badlogic.gdx.scenes.scene2d.ui.Table import com.badlogic.gdx.scenes.scene2d.ui.Tooltip import com.badlogic.gdx.scenes.scene2d.utils.ClickListener import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable import com.badlogic.gdx.utils.Scaling import com.kotcrab.vis.ui.VisUI import com.kotcrab.vis.ui.widget.Tooltip.TooltipStyle import com.kotcrab.vis.ui.widget.VisImage import com.kotcrab.vis.ui.widget.VisLabel import com.kotcrab.vis.ui.widget.VisTable import com.ore.infinium.components.BlockComponent import com.ore.infinium.components.ItemComponent import com.ore.infinium.components.SpriteComponent import com.ore.infinium.systems.client.ClientNetworkSystem import com.ore.infinium.systems.client.TileRenderSystem import com.ore.infinium.util.isInvalidEntity import com.ore.infinium.util.isValidEntity import com.ore.infinium.util.opt import com.ore.infinium.util.system import ktx.actors.KtxInputListener class HotbarInventoryView(private val stage: Stage, //the model for this view private val inventory: HotbarInventory, //the main player inventory, for drag and drop dragAndDrop: DragAndDrop, private val world: OreWorld) : Inventory.SlotListener { private val container: VisTable private val slots = mutableListOf<SlotElement>() private lateinit var tileRenderSystem: TileRenderSystem private lateinit var mItem: ComponentMapper<ItemComponent> private lateinit var mBlock: ComponentMapper<BlockComponent> private lateinit var mSprite: ComponentMapper<SpriteComponent> private val tooltip: Tooltip<VisTable> private val tooltipLabel: VisLabel init { world.artemisWorld.inject(this) //attach to the inventory model inventory.addListener(this) container = VisTable().apply { setFillParent(true) top().left().setSize(800f, 100f) padLeft(10f).padTop(10f) defaults().space(4f) } stage.addActor(container) val dragImage = VisImage() dragImage.setSize(32f, 32f) repeat(Inventory.maxHotbarSlots) { val element = SlotElement(this, it) slots.add(element) container.add(element.slotTable).size(50f, 50f) setHotbarSlotVisible(it, false) dragAndDrop.addSource(HotbarDragSource(element.slotTable, it, dragImage, this)) dragAndDrop.addTarget(HotbarDragTarget(element.slotTable, it, this)) } val style = VisUI.getSkin().get("default", TooltipStyle::class.java) tooltipLabel = VisLabel() val tooltipTable = VisTable().apply { add(tooltipLabel) background = style.background } tooltip = Tooltip<VisTable>(tooltipTable) } private fun deselectPreviousSlot() { slots[inventory.previousSelectedSlot].slotTable.color = Color.WHITE } override fun slotItemCountChanged(index: Int, inventory: Inventory) { val cItem = mItem.get(inventory.itemEntity(index)) slots[index].itemCount.setText(cItem.stackSize.toString()) } override fun slotItemChanged(index: Int, inventory: Inventory) { val slot = slots[index] val itemEntity = inventory.itemEntity(index) if (isInvalidEntity(itemEntity)) { setHotbarSlotVisible(index, false) return } val cItem = mItem.get(itemEntity) slots[index].itemCount.setText(cItem.stackSize.toString()) val cSprite = mSprite.get(itemEntity) val region = textureForInventoryItem(itemEntity, cSprite.textureName!!) val slotImage = slot.itemImage slotImage.drawable = TextureRegionDrawable(region) slotImage.setSize(region.regionWidth.toFloat(), region.regionHeight.toFloat()) slotImage.setScaling(Scaling.fit) setHotbarSlotVisible(index, true) //do not exceed the max size/resort to horrible upscaling. prefer native size of each inventory sprite. //.maxSize(region.getRegionWidth(), region.getRegionHeight()).expand().center(); } //fixme this is also duped in the InventoryView, but not sure where else to put it...the current way is a hack anyway fun textureForInventoryItem(itemEntity: Int, textureName: String): TextureRegion { var region: TextureRegion? if (mBlock.opt(itemEntity) != null) { //fixme this concat is pretty...iffy region = tileRenderSystem.tilesAtlas.findRegion("$textureName-00") if (region == null) { //try again but without -00 region = tileRenderSystem.tilesAtlas.findRegion(textureName) } } else { region = world.atlas.findRegion(textureName) } assert(region != null) { "textureregion for inventory item entity id: $itemEntity, was not found!" } return region!! } override fun slotItemRemoved(index: Int, inventory: Inventory) { setHotbarSlotVisible(index, false) } override fun slotItemSelected(index: Int, inventory: Inventory) { deselectPreviousSlot() slots[index].slotTable.color = Color.TAN } //FIXME: do the same for InventoryView /** * hides/shows the text and image for this index. For e.g. * when an item leaves, or init time */ private fun setHotbarSlotVisible(index: Int, visible: Boolean) { if (!visible) { slots[index].itemImage.drawable = null slots[index].itemCount.setText(null) } slots[index].itemCount.isVisible = visible slots[index].itemImage.isVisible = visible } private class HotbarDragSource(slotTable: Table, private val index: Int, private val dragImage: Image, private val hotbarInventoryView: HotbarInventoryView) : DragAndDrop.Source( slotTable) { override fun dragStart(event: InputEvent, x: Float, y: Float, pointer: Int): DragAndDrop.Payload? { //invalid drag start, ignore. if (isInvalidEntity(hotbarInventoryView.inventory.itemEntity(index))) { return null } val payload = DragAndDrop.Payload() val dragWrapper = InventorySlotDragWrapper(sourceInventory = hotbarInventoryView.inventory, dragSourceIndex = index) payload.`object` = dragWrapper payload.dragActor = dragImage payload.validDragActor = dragImage payload.invalidDragActor = dragImage return payload } } private class HotbarDragTarget(slotTable: VisTable, private val index: Int, private val inventoryView: HotbarInventoryView) : DragAndDrop.Target( slotTable) { override fun drag(source: DragAndDrop.Source, payload: DragAndDrop.Payload?, x: Float, y: Float, pointer: Int): Boolean { payload ?: return false if (isValidDrop(payload)) { BaseInventoryView.setSlotColor(payload, actor, Color.LIME) return true } else { BaseInventoryView.setSlotColor(payload, actor, Color.RED) //reject return false } } private fun isValidDrop(payload: DragAndDrop.Payload): Boolean { val dragWrapper = payload.`object` as InventorySlotDragWrapper if (dragWrapper.dragSourceIndex == index && dragWrapper.sourceInventory.inventoryType == inventoryView.inventory.inventoryType) { //trying to drop on the same slot, on the same inventory return false } if (isInvalidEntity(inventoryView.inventory.itemEntity(index))) { //only make it green if the slot is empty return true } return false } override fun reset(source: DragAndDrop.Source?, payload: DragAndDrop.Payload?) { payload ?: error("payload is null. bad state") BaseInventoryView.setSlotColor(payload, actor, Color.WHITE) //restore selection, it was just dropped.. inventoryView.slotItemSelected(inventoryView.inventory.selectedSlot, inventoryView.inventory) } override fun drop(source: DragAndDrop.Source, payload: DragAndDrop.Payload, x: Float, y: Float, pointer: Int) { val dragWrapper = payload.`object` as InventorySlotDragWrapper val hotbarInventory = inventoryView.inventory //ensure the dest is empty before attempting any drag & drop! if (!isValidDrop(payload)) { return } val itemEntity = dragWrapper.sourceInventory.itemEntity(dragWrapper.dragSourceIndex) //grab item from source, copy it into dest hotbarInventory.setSlot(this.index, itemEntity) //fixme? inventory.previousSelectedSlot = index; val clientNetworkSystem = inventoryView.world.artemisWorld.system<ClientNetworkSystem>() clientNetworkSystem.sendInventoryMove(sourceInventoryType = dragWrapper.sourceInventory.inventoryType, sourceIndex = dragWrapper.dragSourceIndex, destInventoryType = inventoryView.inventory.inventoryType, destIndex = index) //remove the source item now that the move is complete dragWrapper.sourceInventory.takeItem(dragWrapper.dragSourceIndex) //select new index hotbarInventory.selectSlot(index) } } private class SlotInputListener internal constructor(private val inventory: HotbarInventoryView, private val index: Int) : KtxInputListener() { override fun enter(event: InputEvent, x: Float, y: Float, pointer: Int, fromActor: Actor?) { val itemEntity = inventory.inventory.itemEntity(index) if (isValidEntity(itemEntity)) { inventory.tooltip.enter(event, x, y, pointer, fromActor) } super.enter(event, x, y, pointer, fromActor) } override fun mouseMoved(event: InputEvent, x: Float, y: Float): Boolean { inventory.tooltip.mouseMoved(event, x, y) val itemEntity = inventory.inventory.itemEntity(index) if (isValidEntity(itemEntity)) { val cItem = inventory.mItem.get(itemEntity) val cSprite = inventory.mSprite.get(itemEntity) inventory.tooltipLabel.setText(cItem.name) } return super.mouseMoved(event, x, y) } override fun exit(event: InputEvent, x: Float, y: Float, pointer: Int, toActor: Actor?) { inventory.tooltip.exit(event, x, y, pointer, toActor) super.exit(event, x, y, pointer, toActor) } } private class SlotClickListener(private val inventory: HotbarInventoryView, private val index: Int) : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { inventory.deselectPreviousSlot() inventory.inventory.selectSlot(index) } } private inner class SlotElement(inventoryView: HotbarInventoryView, index: Int) { val itemImage = VisImage() val slotTable = VisTable() val itemCount = VisLabel() init { with(slotTable) { touchable = Touchable.enabled add(itemImage) addListener(SlotClickListener(inventoryView, index)) addListener(SlotInputListener(inventoryView, index)) background("grey-panel") row() add(itemCount).bottom().fill() } } } }
mit
29ad71fc2d1ff9925315396ee1f90036
36.994536
121
0.639796
4.736376
false
false
false
false
phylame/jem
commons/src/main/kotlin/jclp/text/TextObject.kt
1
3638
/* * Copyright 2015-2017 Peng Wan <[email protected]> * * This file is part of Jem. * * 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 jclp.text import jclp.DisposableSupport import jclp.io.Flob import jclp.io.LineIterator import jclp.io.writeLines import jclp.release import jclp.retain import java.io.Writer import java.nio.charset.Charset const val TEXT_HTML = "html" const val TEXT_PLAIN = "plain" interface Text : Iterable<String> { val type: String fun isEmpty(): Boolean override fun toString(): String override fun iterator(): Iterator<String> = LineSplitter(toString()) fun writeTo(output: Writer) { output.write(toString()) } } fun Text.isNotEmpty(): Boolean = !isEmpty() inline fun Text.ifNotEmpty(block: (Text) -> Unit) { if (isNotEmpty()) block(this) } open class TextWrapper(protected val text: Text) : Text { override val type get() = text.type override fun isEmpty() = text.isEmpty() override fun toString() = text.toString() override fun iterator() = text.iterator() override fun writeTo(output: Writer) = text.writeTo(output) override fun equals(other: Any?) = text == other override fun hashCode() = text.hashCode() } private class StringText(val text: CharSequence, override val type: String) : Text { override fun isEmpty() = text.isEmpty() override fun toString() = text.toString() } fun textOf(text: CharSequence, type: String = TEXT_PLAIN): Text { require(type.isNotEmpty()) { "'type' cannot be empty" } return StringText(text, type) } fun emptyText(type: String = TEXT_PLAIN) = textOf("", type) abstract class IteratorText(final override val type: String) : Text { init { require(type.isNotEmpty()) { "'type' cannot be empty" } } override fun isEmpty() = iterator().hasNext() abstract override fun iterator(): Iterator<String> override fun toString() = joinToString(System.lineSeparator()) override fun writeTo(output: Writer) { output.writeLines(iterator()) } } fun textOf(iterator: Iterator<String>, type: String = TEXT_PLAIN) = object : IteratorText(type) { override fun iterator() = iterator } private class FlobText(val flob: Flob, val charset: Charset, override val type: String) : DisposableSupport(), Text { init { flob.retain() } override fun isEmpty() = text.value.isEmpty() override fun toString(): String = text.value override fun iterator() = if (!text.isInitialized()) { LineIterator(openReader(), true) } else { LineSplitter(text.value) } private fun openReader() = flob.openStream().bufferedReader(charset) private val text = lazy { openReader().use { it.readText() } } override fun writeTo(output: Writer) { openReader().use { it.copyTo(output) } } override fun dispose() { flob.release() } } fun textOf(flob: Flob, charset: Charset? = null, type: String = TEXT_PLAIN): Text { require(type.isNotEmpty()) { "'type' cannot be empty" } return FlobText(flob, charset ?: Charset.defaultCharset(), type) }
apache-2.0
3c93843ae39a637e5a9f1d3d0ee4a181
26.149254
117
0.679769
3.958651
false
false
false
false
flesire/ontrack
ontrack-service/src/main/java/net/nemerosa/ontrack/service/labels/LabelProviderJob.kt
1
2294
package net.nemerosa.ontrack.service.labels import net.nemerosa.ontrack.job.* import net.nemerosa.ontrack.job.orchestrator.JobOrchestratorSupplier import net.nemerosa.ontrack.model.labels.LabelProviderService import net.nemerosa.ontrack.model.security.SecurityService import net.nemerosa.ontrack.model.security.callAsAdmin import net.nemerosa.ontrack.model.structure.Project import net.nemerosa.ontrack.model.structure.StructureService import net.nemerosa.ontrack.model.support.OntrackConfigProperties import org.springframework.stereotype.Component import java.util.stream.Stream /** * Orchestrates the collection of labels for all projects. */ @Component class LabelProviderJob( private val securityService: SecurityService, private val structureService: StructureService, private val labelProviderService: LabelProviderService, private val ontrackConfigProperties: OntrackConfigProperties ) : JobOrchestratorSupplier { companion object { val LABEL_PROVIDER_JOB_TYPE = JobCategory.CORE .getType("label-provider").withName("Label Provider") } override fun collectJobRegistrations(): Stream<JobRegistration> { return securityService.callAsAdmin { structureService.projectList .map { createLabelProviderJobRegistration(it) } .stream() } } private fun createLabelProviderJobRegistration(project: Project): JobRegistration { return JobRegistration .of(createLabelProviderJob(project)) .withSchedule(Schedule.everyMinutes(60)) // Hourly } private fun createLabelProviderJob(project: Project): Job { return object : Job { override fun getKey(): JobKey = LABEL_PROVIDER_JOB_TYPE.getKey(project.name) override fun getTask() = JobRun { securityService.asAdmin { labelProviderService.collectLabels(project) } } override fun getDescription(): String = "Collection of automated labels for project ${project.name}" override fun isDisabled(): Boolean = project.isDisabled || !ontrackConfigProperties.isJobLabelProviderEnabled } } }
mit
b0e9d61d835d1e02a4c56bcb7298b7bd
36.016129
121
0.696164
5.273563
false
true
false
false
elpassion/mainframer-intellij-plugin
src/main/kotlin/com/elpassion/mainframerplugin/task/edit/TaskEditDialog.kt
1
1259
package com.elpassion.mainframerplugin.task.edit import com.elpassion.mainframerplugin.common.BuildCommandValidator import com.elpassion.mainframerplugin.common.MainframerPathValidator import com.elpassion.mainframerplugin.common.StringsBundle import com.elpassion.mainframerplugin.common.validateForm import com.elpassion.mainframerplugin.task.TaskData import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import javax.swing.JComponent class TaskEditDialog(project: Project) : DialogWrapper(project) { val form = TaskEditForm(project) init { isModal = true title = StringsBundle.getMessage("task.settings.dialog.title") init() } override fun createCenterPanel(): JComponent = form.panel override fun doValidate() = with(form) { validateForm(MainframerPathValidator(mainframerToolField), BuildCommandValidator(buildCommandField)) } fun restoreTaskData(data: TaskData) { form.mainframerToolField.text = data.mainframerPath form.buildCommandField.text = data.buildCommand } fun createTaskDataFromForms() = TaskData( buildCommand = form.buildCommandField.text, mainframerPath = form.mainframerToolField.text) }
apache-2.0
322aeac4198076c9a79609f9fe924138
34
108
0.767276
4.768939
false
false
false
false
neilellis/kontrol
webserver/src/main/kotlin/kontrol/webserver/SimpleWebServer.kt
1
1205
/* * Copyright 2014 Cazcade Limited (http://cazcade.com) * * 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 kontrol.webserver /** * @todo document. * @author <a href="http://uk.linkedin.com/in/neilellis">Neil Ellis</a> */ public class SimpleWebServer(port: Int = 8080, hostname: String? = null, val action: (IHTTPSession) -> Response) : NanoHTTPD(hostname, port) { override fun serve(session: IHTTPSession): Response { return action(session) } } fun main(args: Array<String>): Unit { val server = SimpleWebServer { Response(text = "Hello World! ${it.headers}") }; server.startServer() Thread.sleep(300 * 1000) server.stopServer() }
apache-2.0
984c346650bd6ff7f9f597d6c168333c
29.897436
142
0.697095
3.84984
false
false
false
false
google/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/problems/SplitEditorProblemsTest.kt
3
5668
// 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.java.codeInsight.daemon.problems import com.intellij.codeInsight.codeVision.CodeVisionHost import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.ex.FileEditorProviderManager import com.intellij.openapi.fileEditor.impl.FileEditorManagerExImpl import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl import com.intellij.openapi.fileEditor.impl.FileEditorProviderManagerImpl import com.intellij.openapi.fileEditor.impl.text.TextEditorImpl import com.intellij.openapi.wm.IdeFocusManager import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiJavaCodeReferenceElement import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl import com.intellij.testFramework.registerComponentInstance import com.intellij.ui.docking.DockManager import com.intellij.util.ArrayUtilRt import javax.swing.SwingConstants internal class SplitEditorProblemsTest : ProjectProblemsViewTest() { private var manager: FileEditorManagerImpl? = null override fun setUp() { super.setUp() project.putUserData(CodeVisionHost.isCodeVisionTestKey, true) manager = FileEditorManagerExImpl(project).also { it.initDockableContentFactory() } project.registerComponentInstance(FileEditorManager::class.java, manager!!, testRootDisposable) (FileEditorProviderManager.getInstance() as FileEditorProviderManagerImpl).clearSelectedProviders() } override fun tearDown() { try { project.putUserData(CodeVisionHost.isCodeVisionTestKey, null) } catch (e: Throwable) { addSuppressedException(e) } finally { super.tearDown() } } fun testClassRenameInTwoDetachedWindows() { val parentClass = myFixture.addClass(""" package bar; public class Parent1 { } """.trimIndent()) val childClass = myFixture.addClass(""" package foo; import bar.Parent1; public final class Child extends Parent1 { } """.trimIndent()) val editorManager = manager!! editorManager.openFileInNewWindow(childClass.containingFile.virtualFile).first[0] val parentEditor = (editorManager.openFileInNewWindow(parentClass.containingFile.virtualFile).first[0] as TextEditorImpl).editor rehighlight(parentEditor) WriteCommandAction.runWriteCommandAction(project) { val factory = JavaPsiFacade.getInstance(project).elementFactory parentClass.nameIdentifier?.replace(factory.createIdentifier("Parent")) } rehighlight(parentEditor) assertSize(2, getProblems(parentEditor)) DockManager.getInstance(project).containers.forEach { it.closeAll() } } fun testRenameClassChangeUsageAndUndoAllInSplitEditor() { val parentClass = myFixture.addClass(""" package bar; public class Parent1 { } """.trimIndent()) val childClass = myFixture.addClass(""" package foo; import bar.Parent1; public final class Child extends Parent1 { } """.trimIndent()) // open parent class and rehighlight val editorManager = manager!! val parentTextEditor = editorManager.openFile(parentClass.containingFile.virtualFile, true)[0] as TextEditorImpl val parentEditor = parentTextEditor.editor rehighlight(parentEditor) assertEmpty(getProblems(parentEditor)) // open child class in horizontal split, focus stays in parent editor val currentWindow = editorManager.currentWindow editorManager.createSplitter(SwingConstants.HORIZONTAL, currentWindow) val nextWindow = editorManager.getNextWindow(currentWindow) val childEditor = editorManager.openFileWithProviders(childClass.containingFile.virtualFile, false, nextWindow).first[0] // rename parent, check for errors WriteCommandAction.runWriteCommandAction(project) { val factory = JavaPsiFacade.getInstance(project).elementFactory parentClass.nameIdentifier?.replace(factory.createIdentifier("Parent")) } rehighlight(parentEditor) assertSize(2, getProblems(parentEditor)) // select child editor, remove parent from child extends list, check that number of problems changed IdeFocusManager.getInstance(project).requestFocus(childEditor.component, true) WriteCommandAction.runWriteCommandAction(project) { val factory = JavaPsiFacade.getInstance(project).elementFactory childClass.extendsList?.replace(factory.createReferenceList(PsiJavaCodeReferenceElement.EMPTY_ARRAY)) } rehighlight(parentEditor) assertSize(1, getProblems(parentEditor)) // undo child change WriteCommandAction.runWriteCommandAction(project) { UndoManager.getInstance(project).undo(childEditor) } rehighlight(parentEditor) assertSize(2, getProblems(parentEditor)) // undo parent rename, check that problems are gone IdeFocusManager.getInstance(project).requestFocus(parentEditor.component, true) WriteCommandAction.runWriteCommandAction(project) { UndoManager.getInstance(project).undo(parentTextEditor) } rehighlight(parentEditor) assertEmpty(getProblems(parentEditor)) } private fun rehighlight(editor: Editor) { val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) CodeInsightTestFixtureImpl.instantiateAndRun(psiFile!!, editor, ArrayUtilRt.EMPTY_INT_ARRAY, false) } }
apache-2.0
c986911829984421ab75b800cc653565
38.368056
132
0.770642
4.998236
false
true
false
false
RuneSuite/client
plugins-dev/src/main/java/org/runestar/client/plugins/dev/ReflectionChecksDebug.kt
1
2511
package org.runestar.client.plugins.dev import io.reactivex.rxjava3.core.Observable import org.runestar.client.api.plugins.DisposablePlugin import org.runestar.client.raw.access.XIterableNodeDeque import org.runestar.client.raw.access.XReflectionCheck import org.runestar.client.raw.CLIENT import org.runestar.client.api.plugins.PluginSettings import java.lang.reflect.Modifier class ReflectionChecksDebug : DisposablePlugin<PluginSettings>() { override val defaultSettings = PluginSettings() override fun onStart() { add(creations.subscribe(::onCreated)) } private val creations: Observable<XReflectionCheck> get() = XIterableNodeDeque.addFirst.exit .filter { it.instance == CLIENT.reflectionChecks } .map { it.arguments[0] as XReflectionCheck } private fun onCreated(rc: XReflectionCheck) { val msg = StringBuilder() msg.append(rc.id) msg.append(':') for (i in 0 until rc.size) { msg.append('\n') msg.append(messageForOperation(rc, i)) if (rc.creationErrors[i] != 0) { msg.append("\n\t") msg.append("Error while creating: ") msg.append(creationErrorType(rc.creationErrors[i]).name) } } logger.info(msg.toString()) } private fun creationErrorType(n: Int): Class<out Throwable> { return when (n) { -1 -> ClassNotFoundException::class.java -2 -> SecurityException::class.java -3 -> NullPointerException::class.java -4 -> Exception::class.java -5 -> Throwable::class.java else -> throw IllegalStateException() } } private fun messageForOperation(rc: XReflectionCheck, index: Int): String { return when (rc.operations[index]) { 0 -> "getInt <${rc.fields[index]}> = ${getInt(rc, index)}" 1 -> "setInt <${rc.fields[index]}>" 2 -> "getModifiers <${rc.fields[index]}>" 3 -> "invoke <${rc.methods[index]}>" 4 -> "getModifiers <${rc.methods[index]}>" else -> "Nothing" } } private fun getInt(rc: XReflectionCheck, index: Int): String { return try { val f = rc.fields[index] if (!Modifier.isPrivate(f.modifiers)) { f.isAccessible = true } f.getInt(null).toString() } catch (e: Exception) { e.javaClass.name } } }
mit
273ee446d8ea6438e958416b2e181305
33.888889
96
0.594584
4.277683
false
false
false
false
google/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ModuleResolutionFacadeImpl.kt
2
6337
// 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.caches.resolve import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.analyzer.AnalysisResult import org.jetbrains.kotlin.analyzer.ResolverForProject import org.jetbrains.kotlin.container.get import org.jetbrains.kotlin.container.getService import org.jetbrains.kotlin.container.tryGetService import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.diagnostics.DiagnosticSink import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.IdeaModuleInfo import org.jetbrains.kotlin.idea.project.ResolveElementCache import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.application.runWithCancellationCheck import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtPsiUtil import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.AbsentDescriptorHandler import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.lazy.ResolveSession internal class ModuleResolutionFacadeImpl( private val projectFacade: ProjectResolutionFacade, private val moduleInfo: IdeaModuleInfo ) : ResolutionFacade, ResolutionFacadeModuleDescriptorProvider { override val project: Project get() = projectFacade.project //TODO: ideally we would like to store moduleDescriptor once and for all // but there are some usages that use resolutionFacade and mutate the psi leading to recomputation of underlying structures override val moduleDescriptor: ModuleDescriptor get() = findModuleDescriptor(moduleInfo) override fun findModuleDescriptor(ideaModuleInfo: IdeaModuleInfo) = projectFacade.findModuleDescriptor(ideaModuleInfo) override fun analyze(element: KtElement, bodyResolveMode: BodyResolveMode): BindingContext { ResolveInDispatchThreadManager.assertNoResolveInDispatchThread() @OptIn(FrontendInternals::class) val resolveElementCache = getFrontendService(element, ResolveElementCache::class.java) return runWithCancellationCheck { resolveElementCache.resolveToElement(element, bodyResolveMode) } } override fun analyze(elements: Collection<KtElement>, bodyResolveMode: BodyResolveMode): BindingContext { ResolveInDispatchThreadManager.assertNoResolveInDispatchThread() if (elements.isEmpty()) return BindingContext.EMPTY @OptIn(FrontendInternals::class) val resolveElementCache = getFrontendService(elements.first(), ResolveElementCache::class.java) return runWithCancellationCheck { resolveElementCache.resolveToElements(elements, bodyResolveMode) } } override fun analyzeWithAllCompilerChecks(element: KtElement, callback: DiagnosticSink.DiagnosticsCallback?): AnalysisResult { ResolveInDispatchThreadManager.assertNoResolveInDispatchThread() return runWithCancellationCheck { projectFacade.getAnalysisResultsForElement(element, callback) } } override fun analyzeWithAllCompilerChecks( elements: Collection<KtElement>, callback: DiagnosticSink.DiagnosticsCallback? ): AnalysisResult { ResolveInDispatchThreadManager.assertNoResolveInDispatchThread() return runWithCancellationCheck { projectFacade.getAnalysisResultsForElements(elements, callback) } } override fun resolveToDescriptor(declaration: KtDeclaration, bodyResolveMode: BodyResolveMode): DeclarationDescriptor = runWithCancellationCheck { if (KtPsiUtil.isLocal(declaration)) { val bindingContext = analyze(declaration, bodyResolveMode) bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration] ?: getFrontendService(moduleInfo, AbsentDescriptorHandler::class.java).diagnoseDescriptorNotFound(declaration) } else { ResolveInDispatchThreadManager.assertNoResolveInDispatchThread() val resolveSession = projectFacade.resolverForElement(declaration).componentProvider.get<ResolveSession>() resolveSession.resolveToDescriptor(declaration) } } @FrontendInternals override fun <T : Any> getFrontendService(serviceClass: Class<T>): T = getFrontendService(moduleInfo, serviceClass) override fun <T : Any> getIdeService(serviceClass: Class<T>): T { return projectFacade.resolverForModuleInfo(moduleInfo).componentProvider.create(serviceClass) } @FrontendInternals override fun <T : Any> getFrontendService(element: PsiElement, serviceClass: Class<T>): T { return projectFacade.resolverForElement(element).componentProvider.getService(serviceClass) } @FrontendInternals override fun <T : Any> tryGetFrontendService(element: PsiElement, serviceClass: Class<T>): T? { return projectFacade.resolverForElement(element).componentProvider.tryGetService(serviceClass) } private fun <T : Any> getFrontendService(ideaModuleInfo: IdeaModuleInfo, serviceClass: Class<T>): T { return projectFacade.resolverForModuleInfo(ideaModuleInfo).componentProvider.getService(serviceClass) } @FrontendInternals override fun <T : Any> getFrontendService(moduleDescriptor: ModuleDescriptor, serviceClass: Class<T>): T { return projectFacade.resolverForDescriptor(moduleDescriptor).componentProvider.getService(serviceClass) } override fun getResolverForProject(): ResolverForProject<IdeaModuleInfo> { return projectFacade.getResolverForProject() } } fun ResolutionFacade.findModuleDescriptor(ideaModuleInfo: IdeaModuleInfo): ModuleDescriptor { return (this as ResolutionFacadeModuleDescriptorProvider).findModuleDescriptor(ideaModuleInfo) } interface ResolutionFacadeModuleDescriptorProvider { fun findModuleDescriptor(ideaModuleInfo: IdeaModuleInfo): ModuleDescriptor }
apache-2.0
f8300630120de519ae6ff297f590f759
45.940741
158
0.778602
5.878479
false
false
false
false
google/intellij-community
plugins/editorconfig/src/org/editorconfig/language/psi/reference/EditorConfigVirtualFileDescriptor.kt
14
1771
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.psi.reference import com.intellij.openapi.vfs.VirtualFile /** * Not that this descriptor might be somewhat resource-hungry * and should only be used locally inside a filtering function */ class EditorConfigVirtualFileDescriptor(val file: VirtualFile) { private val cachedChildMappings = mutableMapOf<VirtualFile, Int>() private val cachedParentMappings = mutableMapOf<VirtualFile, Int>() fun distanceToChild(child: VirtualFile): Int { val cached = cachedChildMappings[child] if (cached != null) return cached val distance = calculateDistanceBetween(file, child) cachedChildMappings[child] = distance return distance } fun distanceToParent(parent: VirtualFile): Int { val cached = cachedParentMappings[parent] if (cached != null) return cached val distance = calculateDistanceBetween(parent, file) cachedParentMappings[parent] = distance return distance } fun isChildOf(parent: VirtualFile) = distanceToParent(parent) >= 0 fun isParentOf(child: VirtualFile) = distanceToChild(child) >= 0 fun isStrictParentOf(child: VirtualFile) = distanceToChild(child) > 0 fun isStrictChildOf(parent: VirtualFile) = distanceToParent(parent) > 0 private fun calculateDistanceBetween(parentFile: VirtualFile, initialFile: VirtualFile): Int { var result = 0 val targetFolder = parentFile.parent var currentFolder = initialFile.parent while (currentFolder != null) { if (currentFolder == targetFolder) { return result } result += 1 currentFolder = currentFolder.parent } return -1 } }
apache-2.0
3d748e9484294f10681f2f26ba3906ab
34.42
140
0.738001
4.588083
false
false
false
false
google/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/impl/ModuleDefaultVcsRootPolicy.kt
1
1940
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.impl import com.intellij.openapi.application.runReadAction import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.project.stateStore import com.intellij.workspaceModel.ide.WorkspaceModel import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.ide.impl.virtualFile import com.intellij.workspaceModel.storage.bridgeEntities.api.ContentRootEntity open class ModuleDefaultVcsRootPolicy(project: Project) : DefaultVcsRootPolicy(project) { init { val busConnection = project.messageBus.connect() WorkspaceModelTopics.getInstance(project).subscribeAfterModuleLoading(busConnection, MyModulesListener()) } override fun getDefaultVcsRoots(): Collection<VirtualFile> { val result = mutableSetOf<VirtualFile>() val baseDir = myProject.baseDir if (baseDir != null) { result.add(baseDir) val directoryStorePath = myProject.stateStore.directoryStorePath if (directoryStorePath != null) { val ideaDir = LocalFileSystem.getInstance().findFileByNioFile(directoryStorePath) if (ideaDir != null) { result.add(ideaDir) } } } result += runReadAction { WorkspaceModel.getInstance(myProject).entityStorage.current .entities(ContentRootEntity::class.java) .mapNotNull { it.url.virtualFile } .filter { it.isInLocalFileSystem } .filter { it.isDirectory } } return result } private inner class MyModulesListener : ContentRootChangeListener(skipFileChanges = true) { override fun contentRootsChanged(removed: List<VirtualFile>, added: List<VirtualFile>) { scheduleMappedRootsUpdate() } } }
apache-2.0
48f11ecd39acc2b7aafc9ee891f3733e
37.058824
140
0.754124
4.778325
false
false
false
false
Leifzhang/AndroidRouter
RouterLib/src/main/java/com/kronos/router/model/RouterOptions.kt
2
1077
package com.kronos.router.model import android.app.Activity import android.os.Bundle import com.kronos.router.RouterCallback import com.kronos.router.interceptor.Interceptor /** * Created by zhangyang on 16/7/16. */ class RouterOptions { var openClass: Class<out Activity>? = null var callback: RouterCallback? = null private val _defaultParams: Bundle by lazy { Bundle() } var weight = 0 val interceptors by lazy { mutableListOf<Interceptor>() } var defaultParams: Bundle? get() = this._defaultParams set(defaultParams) { _defaultParams.putAll(defaultParams) } constructor() { } constructor(defaultParams: Bundle?) { this.defaultParams = defaultParams } fun putParams(key: String, value: String) { _defaultParams.putString(key, value) } fun addInterceptor(interceptor: Interceptor) { interceptors.add(interceptor) } fun addInterceptors(interceptor: List<Interceptor>) { interceptors.addAll(interceptor) } }
mit
10f299ca6a484474458a584257a1ebd9
20.56
57
0.660167
4.290837
false
false
false
false
JetBrains/intellij-community
plugins/settings-sync/src/com/intellij/settingsSync/config/SettingsSyncPluginsGroup.kt
1
1514
package com.intellij.settingsSync.config import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.components.SettingsCategory import com.intellij.settingsSync.SettingsSyncBundle.message import com.intellij.settingsSync.plugins.SettingsSyncPluginCategoryFinder import org.jetbrains.annotations.Nls internal const val BUNDLED_PLUGINS_ID = "bundled" internal class SettingsSyncPluginsGroup : SettingsSyncSubcategoryGroup { private val storedDescriptors = HashMap<String, SettingsSyncSubcategoryDescriptor>() override fun getDescriptors(): List<SettingsSyncSubcategoryDescriptor> { val descriptors = ArrayList<SettingsSyncSubcategoryDescriptor>() val bundledPluginsDescriptor = getOrCreateDescriptor(message("plugins.bundled"), BUNDLED_PLUGINS_ID) descriptors.add(bundledPluginsDescriptor) PluginManagerCore.getPlugins().forEach { if (!it.isBundled && SettingsSyncPluginCategoryFinder.getPluginCategory(it) == SettingsCategory.PLUGINS) { bundledPluginsDescriptor.isSubGroupEnd = true descriptors.add(getOrCreateDescriptor(it.name, it.pluginId.idString)) } } return descriptors } private fun getOrCreateDescriptor(name : @Nls String, id : String) : SettingsSyncSubcategoryDescriptor { return if (storedDescriptors.containsKey(id)) { storedDescriptors[id]!! } else { val descriptor = SettingsSyncSubcategoryDescriptor(name, id, true, false) storedDescriptors[id] = descriptor descriptor } } }
apache-2.0
31d538119822f88b2ed5d7407a2bfb34
39.945946
112
0.783355
4.9967
false
false
false
false
google/j2cl
transpiler/java/com/google/j2cl/transpiler/backend/kotlin/TypeRenderer.kt
1
3914
/* * Copyright 2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.j2cl.transpiler.backend.kotlin import com.google.j2cl.transpiler.ast.NewInstance import com.google.j2cl.transpiler.ast.Type import com.google.j2cl.transpiler.ast.TypeDeclaration import com.google.j2cl.transpiler.ast.TypeDeclaration.Kind import com.google.j2cl.transpiler.ast.TypeDescriptors.isJavaLangEnum import com.google.j2cl.transpiler.ast.TypeDescriptors.isJavaLangObject import com.google.j2cl.transpiler.backend.kotlin.ast.kotlinMembers import java.util.stream.Collectors fun Renderer.renderType(type: Type) { val typeDeclaration = type.declaration // Don't render KtNative types. We should never see them except readables. if (typeDeclaration.isKtNative) { render("// native class ") renderIdentifier(typeDeclaration.ktSimpleName) return } if (typeDeclaration.visibility.needsObjCNameAnnotation && !typeDeclaration.isLocal) { renderObjCNameAnnotation(typeDeclaration) } if (type.isClass && !typeDeclaration.isFinal) { if (typeDeclaration.isAbstract) render("abstract ") else render("open ") } if ( typeDeclaration.enclosingTypeDeclaration != null && type.kind == Kind.CLASS && !type.isStatic && !typeDeclaration.isLocal ) { render("inner ") } render( when (type.kind) { Kind.CLASS -> "class " Kind.ENUM -> "enum class " Kind.INTERFACE -> (if (typeDeclaration.isKtFunctionalInterface) "fun " else "") + "interface " } ) renderTypeDeclaration(typeDeclaration) renderSuperTypes(type) renderWhereClause(typeDeclaration.typeParameterDescriptors) renderTypeBody(type) } fun Renderer.renderTypeDeclaration(declaration: TypeDeclaration) { renderIdentifier(declaration.ktSimpleName) declaration.directlyDeclaredTypeParameterDescriptors .takeIf { it.isNotEmpty() } ?.let { parameters -> renderTypeParameters(parameters) } } private fun Renderer.renderSuperTypes(type: Type) { val superTypes = type.superTypesStream .filter { !isJavaLangObject(it) } .filter { !isJavaLangEnum(it) } .collect(Collectors.toList()) if (superTypes.isNotEmpty()) { val hasConstructors = type.constructors.isNotEmpty() render(": ") renderCommaSeparated(superTypes) { superType -> renderTypeDescriptor(superType.toNonNullable(), asSuperType = true) if (superType.isClass && !hasConstructors) render("()") } } } internal fun Renderer.renderTypeBody(type: Type) { copy( currentType = type, renderThisReferenceWithLabel = false, localNames = localNames + type.localNames ) .run { render(" ") renderInCurlyBrackets { if (type.isEnum) { renderEnumValues(type) } val kotlinMembers = type.kotlinMembers if (kotlinMembers.isNotEmpty()) { renderNewLine() renderSeparatedWithEmptyLine(kotlinMembers) { render(it) } } } } } private fun Renderer.renderEnumValues(type: Type) { renderNewLine() renderSeparatedWith(type.enumFields, ",\n") { field -> renderIdentifier(field.descriptor.name!!) val newInstance = field.initializer as NewInstance if (newInstance.arguments.isNotEmpty()) { renderInvocationArguments(newInstance) } newInstance.anonymousInnerClass?.let { renderTypeBody(it) } } render(";\n") }
apache-2.0
e9a0dbe91888ae859aab4aab05646425
30.564516
100
0.716403
4.177161
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/SimpleAnimator.kt
1
1504
// 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.EDT import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.asContextElement import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import kotlin.time.Duration import kotlin.time.DurationUnit import kotlin.time.toDuration internal abstract class SimpleAnimator { // frame - in 1..totalFrames abstract fun paintNow(frame: Int, totalFrames: Int) protected open fun paintCycleStart() {} suspend fun run(totalFrames: Int, cycle: Duration) { val cycleDuration = cycle.inWholeNanoseconds val duration = (cycleDuration / totalFrames).toDuration(DurationUnit.NANOSECONDS) withContext(Dispatchers.EDT + ModalityState.any().asContextElement()) { paintCycleStart() val startTime = System.nanoTime() var currentFrame = -1 while (true) { val cycleTime = System.nanoTime() - startTime if (cycleTime < 0) { break } val newFrame = ((cycleTime * totalFrames) / cycleDuration).toInt() if (newFrame == currentFrame) { continue } if (newFrame >= totalFrames) { break } currentFrame = newFrame paintNow(currentFrame, totalFrames) delay(duration) } } } }
apache-2.0
9c905ed7a3e4f5e326db3b7f3e41bbcb
29.693878
120
0.699468
4.585366
false
false
false
false
JetBrains/intellij-community
java/java-impl/src/com/intellij/lang/java/actions/ChangeMethodParameters.kt
1
3263
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.lang.java.actions import com.intellij.codeInsight.daemon.QuickFixBundle import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview import com.intellij.lang.jvm.actions.ChangeParametersRequest import com.intellij.lang.jvm.actions.ExpectedParameter import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* internal class ChangeMethodParameters( target: PsiMethod, @SafeFieldForPreview override val request: ChangeParametersRequest ) : CreateTargetAction<PsiMethod>(target, request) { override fun getText(): String { val helper = JvmPsiConversionHelper.getInstance(target.project) val parametersString = request.expectedParameters.joinToString(", ", "(", ")") { val psiType = helper.convertType(it.expectedTypes.first().theType) val name = it.semanticNames.first() "${psiType.presentableText} $name" } val shortenParameterString = StringUtil.shortenTextWithEllipsis(parametersString, 30, 5) return QuickFixBundle.message("change.method.parameters.text", shortenParameterString) } override fun getFamilyName(): String = QuickFixBundle.message("change.method.parameters.family") override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { val factory = PsiElementFactory.getInstance(project) val helper = JvmPsiConversionHelper.getInstance(target.project) tailrec fun updateParameters(curParameters: List<PsiParameter>, expParameters: List<ExpectedParameter>) { val currentHead = curParameters.firstOrNull() val expectedHead = expParameters.firstOrNull() if (expectedHead == null) { curParameters.forEach(PsiParameter::delete) return } if (expectedHead is ChangeParametersRequest.ExistingParameterWrapper) { if (expectedHead.existingParameter == currentHead) { return updateParameters(curParameters.subList(1, curParameters.size), expParameters.subList(1, expParameters.size)) } else throw UnsupportedOperationException("processing of existing params in different order is not implemented yet") } val name = expectedHead.semanticNames.first() val psiType = helper.convertType(expectedHead.expectedTypes.first().theType) val newParameter = factory.createParameter(name, psiType) // #addAnnotationToModifierList adds annotations to the start of the modifier list instead of its end, // reversing the list "nullifies" this behaviour, thus preserving the original annotations order for (annotationRequest in expectedHead.expectedAnnotations.reversed()) { CreateAnnotationAction.addAnnotationToModifierList(newParameter.modifierList!!, annotationRequest) } if (currentHead == null) target.parameterList.add(newParameter) else target.parameterList.addBefore(newParameter, currentHead) updateParameters(curParameters, expParameters.subList(1, expParameters.size)) } updateParameters(target.parameterList.parameters.toList(), request.expectedParameters) } }
apache-2.0
084c063cfc57cb38653f958018fb3919
49.984375
140
0.770457
5.004601
false
false
false
false
allotria/intellij-community
plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/xml/MavenBuildFileBuilder.kt
3
4982
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.importing.xml import org.jetbrains.idea.maven.utils.MavenArtifactScope class MavenBuildFileBuilder(val artifactId: String) { private var modelVersion: String = "4.0.0" private var groupId: String = "org.example" private var version: String = "1.0-SNAPSHOT" private var packaging: String? = null private val modules = ArrayList<Module>() private val dependencies = ArrayList<Dependency>() private val properties = ArrayList<Property>() private val plugins = ArrayList<Plugin>() fun withPomPackaging(): MavenBuildFileBuilder { packaging = "pom" return this } fun withModule(name: String): MavenBuildFileBuilder { modules.add(Module(name)) return this } fun withDependency(groupId: String, artifactId: String, version: String, scope: MavenArtifactScope? = null): MavenBuildFileBuilder { dependencies.add(Dependency(groupId, artifactId, version, scope)) return this } fun withProperty(name: String, value: String): MavenBuildFileBuilder { properties.add(Property(name, value)) return this } fun withPlugin(groupId: String, artifactId: String, buildAction: PluginBuilder.() -> Unit): MavenBuildFileBuilder { val pluginBuilder = PluginBuilder(groupId, artifactId) pluginBuilder.buildAction() plugins.add(pluginBuilder.build()) return this } fun generate(): String { val builder = XmlBuilder().apply { attribute("xmlns", "http://maven.apache.org/POM/4.0.0") attribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance") attribute("xsi:schemaLocation", "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd") block("project") { value("modelVersion", modelVersion) generateProjectInfo() generateModules() generateDependencies() generateProperties() generatePlugins() } } return builder.generate() } private fun XmlBuilder.generateProjectInfo() { value("groupId", groupId) value("artifactId", artifactId) value("version", version) } private fun XmlBuilder.generateModules() { packaging?.let { value("packaging", it) } if (modules.isEmpty()) return block("modules") { for (module in modules) { generateModule(module) } } } private fun XmlBuilder.generateModule(module: Module) { value("module", module.name) } private fun XmlBuilder.generateDependencies() { if (dependencies.isEmpty()) return block("dependencies") { for (dependency in dependencies) { generateDependency(dependency) } } } private fun XmlBuilder.generateDependency(dependency: Dependency) { block("dependency") { value("groupId", dependency.groupId) value("artifactId", dependency.artifactId) value("version", dependency.version) dependency.scope?.let { value("scope", it.name) } } } private fun XmlBuilder.generateProperties() { if (properties.isEmpty()) return block("properties") { for (property in properties) { generateProperty(property) } } } private fun XmlBuilder.generateProperty(property: Property) { value(property.name, property.value) } private fun XmlBuilder.generatePlugins() { if (plugins.isEmpty()) return block("build") { block("plugins") { for (plugin in plugins) { generatePlugin(plugin) } } } } private fun XmlBuilder.generatePlugin(plugin: Plugin) { block("plugin") { value("groupId", plugin.groupId) value("artifactId", plugin.artifactId) plugin.version?.let { value("version", it) } if (plugin.attributes.isEmpty()) return@block block("configuration") { for (attribute in plugin.attributes) { value(attribute.name, attribute.value) } } } } data class Module(val name: String) data class Dependency(val groupId: String, val artifactId: String, val version: String, val scope: MavenArtifactScope?) data class Property(val name: String, val value: String) data class Plugin(val groupId: String, val artifactId: String, val version: String?, val attributes: List<Attribute> = emptyList()) data class Attribute(val name: String, val value: String) class PluginBuilder(val groupId: String, val artifactId: String) { private var version: String? = null private val attributes = mutableListOf<Attribute>() fun version(version: String): PluginBuilder { this.version = version return this } fun attribute(name: String, value: String): PluginBuilder { attributes.add(Attribute(name, value)) return this } fun build() = Plugin(groupId, artifactId, version, attributes) } }
apache-2.0
77f02f58b77e0dfef250b984d0b39ab4
29.2
140
0.669611
4.393298
false
false
false
false
Skatteetaten/boober
src/test/kotlin/no/skatteetaten/aurora/boober/unit/AuroraConfigTest.kt
1
10625
package no.skatteetaten.aurora.boober.unit import assertk.all import assertk.assertThat import assertk.assertions.hasMessage import assertk.assertions.isEqualTo import assertk.assertions.isFailure import assertk.assertions.isInstanceOf import assertk.assertions.isNotNull import assertk.assertions.isNull import assertk.assertions.isTrue import assertk.assertions.messageContains import no.skatteetaten.aurora.boober.model.ApplicationDeploymentRef import no.skatteetaten.aurora.boober.model.AuroraConfig import no.skatteetaten.aurora.boober.model.AuroraConfigException import no.skatteetaten.aurora.boober.model.AuroraConfigFile import no.skatteetaten.aurora.boober.model.PreconditionFailureException import no.skatteetaten.aurora.boober.utils.AuroraConfigSamples.Companion.createAuroraConfig import no.skatteetaten.aurora.boober.utils.AuroraConfigSamples.Companion.getAuroraConfigSamples import no.skatteetaten.aurora.boober.utils.ResourceLoader import org.junit.jupiter.api.Test class AuroraConfigTest : ResourceLoader() { val aid = ApplicationDeploymentRef("utv", "simple") @Test fun `Should get all application ids for AuroraConfig`() { val auroraConfig = createAuroraConfig(aid) val refs = auroraConfig.getApplicationDeploymentRefs() assertThat(refs[0].application).isEqualTo("simple") assertThat(refs[0].environment).isEqualTo("utv") } @Test fun `Should update file`() { val auroraConfig = createAuroraConfig(aid) val updates = """{ "version": "4"}""" val updateFileResponse = auroraConfig.updateFile("booberdev/console.json", updates) val updatedAuroraConfig = updateFileResponse.second val version = updatedAuroraConfig.files .filter { it.configName == "booberdev/console.json" } .map { it.asJsonNode.get("version").asText() } .first() assertThat(version).isEqualTo("4") } @Test fun `Should fail when duplicate field`() { val auroraConfig = createAuroraConfig(aid) val updates = """ { "version": "2", "certificate": false, "version": "5" } """.trimIndent() val updateFileResponse = auroraConfig.updateFile("booberdev/console.json", updates) val updatedAuroraConfig = updateFileResponse.second assertThat { updatedAuroraConfig.files .filter { it.configName == "booberdev/console.json" } .map { it.asJsonNode } .first() }.isFailure().all { this.isInstanceOf(AuroraConfigException::class) messageContains("not valid errorMessage=Duplicate field 'version'") } } @Test fun `Should create file when updating nonexisting file`() { val auroraConfig = createAuroraConfig(aid) val updates = """{ "version": "4"}""" val fileName = "boobertest/console.json" assertThat(auroraConfig.files.find { it.name == fileName }).isNull() val updatedAuroraConfig = auroraConfig.updateFile(fileName, updates).second val version = updatedAuroraConfig.files .filter { it.configName == fileName } .map { it.asJsonNode.get("version").asText() } .first() assertThat(version).isEqualTo("4") } @Test fun `Returns files for application with include env`() { val auroraConfig = getAuroraConfigSamples() val filesForApplication = auroraConfig.getFilesForApplication(ApplicationDeploymentRef("utv", "easy")) assertThat(filesForApplication.size).isEqualTo(4) } @Test fun `Returns files for application`() { val auroraConfig = createAuroraConfig(aid) val filesForApplication = auroraConfig.getFilesForApplication(aid) assertThat(filesForApplication.size).isEqualTo(4) } @Test fun `Returns files for application with about override`() { val auroraConfig = createAuroraConfig(aid) val filesForApplication = auroraConfig.getFilesForApplication(aid, listOf(overrideFile("about.json"))) assertThat(filesForApplication.size).isEqualTo(5) } @Test fun `Returns files for application with app override`() { val auroraConfig = createAuroraConfig(aid) val filesForApplication = auroraConfig.getFilesForApplication(aid, listOf(overrideFile("simple.json"))) assertThat(filesForApplication.size).isEqualTo(5) } @Test fun `Returns files for application with app for env override`() { val auroraConfig = createAuroraConfig(aid) val filesForApplication = auroraConfig.getFilesForApplication(aid, listOf(overrideFile("${aid.environment}/${aid.application}.json"))) assertThat(filesForApplication.size).isEqualTo(5) } @Test fun `Fails when some files for application are missing`() { val referanseAid = ApplicationDeploymentRef("utv", "simple") val files = createMockFiles("about.json", "simple.json", "utv/about.json") val auroraConfig = AuroraConfig(files, "aos", "master") assertThat { auroraConfig.getFilesForApplication(referanseAid) }.isFailure().all { this.isInstanceOf(IllegalArgumentException::class) hasMessage("Should find applicationFile utv/simple.(json|yaml)") } } @Test fun `Includes base file in files for application when set`() { val aid = ApplicationDeploymentRef("utv", "easy") val auroraConfig = getAuroraConfigSamples() val filesForApplication = auroraConfig.getFilesForApplication(aid) assertThat(filesForApplication.size).isEqualTo(4) val applicationFile = filesForApplication.find { it.name == "utv/easy.json" } val baseFile = applicationFile?.asJsonNode?.get("baseFile")?.textValue() assertThat(filesForApplication.any { it.name == baseFile }).isTrue() } @Test fun `Throw error if baseFile is missing`() { val files = createMockFiles("about.json", "utv/simple.json", "utv/about.json") val auroraConfig = AuroraConfig(files, "aos", "master") assertThat { auroraConfig.getFilesForApplication( ApplicationDeploymentRef( "utv", "simple" ) ) }.isFailure().all { this.isInstanceOf(IllegalArgumentException::class) hasMessage("BaseFile simple.(json|yaml) missing for application: utv/simple") } } @Test fun `Should merge with remote and override file`() { val auroraConfig = getAuroraConfigSamples() val fileName = "utv/simple.json" assertThat(auroraConfig.files.find { it.name == fileName }).isNotNull() val fileContent = """{ "version" : 1 }""" val newAuroraConfig = AuroraConfig(listOf(AuroraConfigFile(fileName, contents = fileContent)), auroraConfig.name, "local") val merged = auroraConfig.merge(newAuroraConfig) assertThat(merged.files.find { it.name == fileName }?.contents).isEqualTo(fileContent) } @Test fun `Should merge with remote and add new file`() { val auroraConfig = getAuroraConfigSamples() val fileName = "new-app.json" assertThat(auroraConfig.files.find { it.name == fileName }).isNull() val fileContent = """{ "groupId" : "foo.bar" }""" val newAuroraConfig = AuroraConfig(listOf(AuroraConfigFile(fileName, contents = fileContent)), auroraConfig.name, "local") val merged = auroraConfig.merge(newAuroraConfig) assertThat(merged.files.find { it.name == fileName }?.contents).isEqualTo(fileContent) } @Test fun `Should keep existing config if local is empty`() { val auroraConfig = getAuroraConfigSamples() val newAuroraConfig = AuroraConfig(emptyList(), auroraConfig.name, "local") val merged = auroraConfig.merge(newAuroraConfig) assertThat(auroraConfig).isEqualTo(merged) } @Test fun `should get error when parsing unkonwn file type`() { val auroraConfigFile = AuroraConfigFile( name = "foo.yoda", contents = """ replicas:3 type: "deploy" certificate: false""".trimMargin() ) assertThat { auroraConfigFile.asJsonNode }.isFailure() .messageContains("Could not parse file with name=foo.yoda") } @Test fun `should get error when parsing yaml file with wrong first line`() { val auroraConfigFile = AuroraConfigFile( name = "foo.yaml", contents = """ replicas:3 type: "deploy" certificate: false""".trimMargin() ) assertThat { auroraConfigFile.asJsonNode }.isFailure() .messageContains("First line in file does not contains space after ':'") } @Test fun `Should fail when adding new file that already exist`() { val auroraConfig = createAuroraConfig(aid) val updates = """ { "version": "2", "certificate": false, "version": "5" } """.trimIndent() assertThat { auroraConfig.updateFile("about.json", updates) }.isFailure().all { this.isInstanceOf(PreconditionFailureException::class) messageContains("The fileName=about.json already exists in this AuroraConfig.") } } @Test fun `Should fail when adding old file that does not exist`() { val auroraConfig = createAuroraConfig(aid) val updates = """ { "version": "2", "certificate": false, "version": "5" } """.trimIndent() assertThat { auroraConfig.updateFile("about2.json", updates, "abc132") }.isFailure().all { this.isInstanceOf(PreconditionFailureException::class) messageContains("The fileName=about2.json does not exist with a version of (abc132).") } } fun createMockFiles(vararg files: String): List<AuroraConfigFile> { return files.map { AuroraConfigFile(it, "{}", false, false) } } fun overrideFile(fileName: String) = AuroraConfigFile( name = fileName, contents = "{}", override = true, isDefault = false ) }
apache-2.0
ed0ebbc813212df6cf8e6ee1e5cd97b4
32.730159
120
0.634918
4.814227
false
true
false
false
Skatteetaten/boober
src/main/kotlin/no/skatteetaten/aurora/boober/controller/v1/VaultControllerV1.kt
1
8977
package no.skatteetaten.aurora.boober.controller.v1 import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import no.skatteetaten.aurora.boober.controller.internal.Response import no.skatteetaten.aurora.boober.controller.v1.VaultOperation.reencrypt import no.skatteetaten.aurora.boober.controller.v1.VaultWithAccessResource.Companion.fromEncryptedFileVault import no.skatteetaten.aurora.boober.controller.v1.VaultWithAccessResource.Companion.fromVaultWithAccess import no.skatteetaten.aurora.boober.service.UnauthorizedAccessException import no.skatteetaten.aurora.boober.service.vault.EncryptedFileVault import no.skatteetaten.aurora.boober.service.vault.VaultService import no.skatteetaten.aurora.boober.service.vault.VaultWithAccess import org.springframework.beans.factory.annotation.Value import org.springframework.http.HttpHeaders import org.springframework.http.MediaType import org.springframework.util.AntPathMatcher import org.springframework.util.DigestUtils import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestHeader import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import java.util.Base64 import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import javax.validation.Valid // TODO: Should we have a seperate controller that handles the case where vault is turned off? @RestController @RequestMapping("/v1/vault/{vaultCollection}") class VaultControllerV1( private val vaultService: VaultService, @Value("\${vault.operations.enabled:false}") private val operationsEnabled: Boolean ) { @PostMapping("/") fun vaultOperation( @PathVariable vaultCollection: String, @RequestBody @Valid operationPayload: VaultOperationPayload ) { if (!operationsEnabled) { throw UnauthorizedAccessException("Vault operations has been disabled") } when (operationPayload.operationName) { reencrypt -> vaultService.reencryptVaultCollection( vaultCollection, operationPayload.parameters["encryptionKey"] as String ) } } @GetMapping fun listVaults(@PathVariable vaultCollection: String): Response { val resources = vaultService.findAllVaultsWithUserAccessInVaultCollection(vaultCollection) return Response(items = resources.map(::fromVaultWithAccess)) } @PutMapping fun save( @PathVariable vaultCollection: String, @RequestBody @Valid vaultPayload: AuroraSecretVaultPayload ): Response { val vault = vaultService.import( vaultCollection, vaultPayload.name, vaultPayload.permissions, vaultPayload.secretsDecoded ) return Response(items = listOf(vault).map(::fromEncryptedFileVault)) } @GetMapping("/{vault}") fun getVault(@PathVariable vaultCollection: String, @PathVariable vault: String): Response { val resources = listOf(vaultService.findVault(vaultCollection, vault)) .map(::fromEncryptedFileVault) return Response(items = resources) } @GetMapping("/{vault}/**") fun getVaultFile( @PathVariable vaultCollection: String, @PathVariable vault: String, request: HttpServletRequest, response: HttpServletResponse ) { val fileName = getVaultFileNameFromRequestUri(vaultCollection, vault, request) val vaultFile = vaultService.findFileInVault(vaultCollection, vault, fileName) writeVaultFileResponse(vaultFile, response) } @PutMapping("/{vault}/**") fun updateVaultFile( @PathVariable vaultCollection: String, @PathVariable("vault") vaultName: String, @RequestBody payload: VaultFileResource, @RequestHeader(value = HttpHeaders.IF_MATCH, required = false) ifMatchHeader: String?, request: HttpServletRequest, response: HttpServletResponse ) { val fileContents: ByteArray = payload.decodedContents val fileName = getVaultFileNameFromRequestUri(vaultCollection, vaultName, request) vaultService.createOrUpdateFileInVault( vaultCollectionName = vaultCollection, vaultName = vaultName, fileName = fileName, fileContents = fileContents, previousSignature = clearQuotes(ifMatchHeader) ) writeVaultFileResponse(fileContents, response) } @DeleteMapping("/{vault}/**") fun deleteVaultFile( @PathVariable vaultCollection: String, @PathVariable("vault") vaultName: String, request: HttpServletRequest ): Response { val fileName = getVaultFileNameFromRequestUri(vaultCollection, vaultName, request) vaultService.deleteFileInVault(vaultCollection, vaultName, fileName)?.let(::fromEncryptedFileVault) return Response() } @DeleteMapping("/{vault}") fun delete(@PathVariable vaultCollection: String, @PathVariable vault: String): Response { vaultService.deleteVault(vaultCollection, vault) return Response() } private fun getVaultFileNameFromRequestUri( vaultCollection: String, vault: String, request: HttpServletRequest ): String { val path = "/v1/vault/$vaultCollection/$vault/**" return AntPathMatcher().extractPathWithinPattern(path, request.requestURI) } /** * Since the request path of the vaultFile can contain any file name (like somefile.txt, otherfile.xml) we need * to take full control of the response to make sure we still always set content-type to application/json and do * not rely on any of the default conventions of spring. */ private fun writeVaultFileResponse(vaultFile: ByteArray, response: HttpServletResponse) { val body = Response(items = listOf(VaultFileResource.fromDecodedBytes(vaultFile))) val eTagHex: String = DigestUtils.md5DigestAsHex(vaultFile) response.contentType = MediaType.APPLICATION_JSON_VALUE response.characterEncoding = "UTF8" response.setHeader(HttpHeaders.ETAG, "$eTagHex") jacksonObjectMapper().writeValue(response.writer, body) response.writer.flush() response.writer.close() } } object B64 { private val decoder = Base64.getDecoder() private val encoder = Base64.getEncoder() fun encode(value: ByteArray): String { return encoder.encodeToString(value) } fun decode(value: String): ByteArray { return try { decoder.decode(value) } catch (e: Exception) { throw IllegalArgumentException("Provided content does not appear to be Base64 encoded.") } } } /* @param secrets: A map of fileNames to Base64 encoded content */ data class AuroraSecretVaultPayload( val name: String, val permissions: List<String>, val secrets: Map<String, String>? ) { val secretsDecoded: Map<String, ByteArray> @JsonIgnore get() = secrets?.map { Pair(it.key, B64.decode(it.value)) }?.toMap() ?: emptyMap() } /* @param secrets: A map of fileNames to Base64 encoded content */ data class VaultWithAccessResource( val name: String, val hasAccess: Boolean, val secrets: Map<String, String>?, val permissions: List<String>? ) { companion object { fun fromEncryptedFileVault(it: EncryptedFileVault): VaultWithAccessResource { return VaultWithAccessResource(it.name, true, encodeSecrets(it.secrets), it.permissions) } fun fromVaultWithAccess(it: VaultWithAccess): VaultWithAccessResource { return VaultWithAccessResource( name = it.vaultName, hasAccess = it.hasAccess, secrets = encodeSecrets(it.vault?.secrets), permissions = it.vault?.permissions ) } private fun encodeSecrets(secrets: Map<String, ByteArray>?): Map<String, String>? { return secrets?.map { Pair(it.key, B64.encode(it.value)) }?.toMap() } } } data class VaultFileResource(val contents: String) { val decodedContents: ByteArray @JsonIgnore get() = B64.decode(contents) companion object { fun fromDecodedBytes(decodedBytes: ByteArray): VaultFileResource { return VaultFileResource(B64.encode(decodedBytes)) } } } enum class VaultOperation { reencrypt } data class VaultOperationPayload(val operationName: VaultOperation, val parameters: Map<String, Any>)
apache-2.0
83caaac0cee73f9ff2bb367027368e15
36.560669
116
0.713713
4.680396
false
false
false
false
WeAthFoLD/Momentum
Runtime/src/main/kotlin/momentum/rt/render/ShaderProgram.kt
1
2593
package momentum.rt.render import com.google.gson.Gson import momentum.rt.resource.AssetLoader import momentum.rt.resource.ResourceManager import org.lwjgl.opengl.GL20.* import org.lwjgl.opengl.GL11.* import java.io.InputStream import java.io.InputStreamReader import java.io.Reader import java.util.* class ShaderProgram private constructor (val programID: Int) { enum class ErrorType { COMPILE, LINK } class ProgramCreationException(val errorType: ErrorType, val log: String) : RuntimeException("GL program creation failed in $errorType stage, log: $log") object Loader : AssetLoader<ShaderProgram> { val gson = Gson() data class ShaderInfo(val vertex: String, val fragment: String) override fun load(manager: ResourceManager, path: String, stream: InputStream): ShaderProgram { val target = gson.fromJson(InputStreamReader(stream), ShaderInfo::class.java) val folder = ResourceManager.getFolder(path) val opt = ResourceManager.CacheOption.NotCache val vertex_source: String = manager.load(ResourceManager.makePath(folder, target.vertex), opt) val fragment_source: String = manager.load(ResourceManager.makePath(folder, target.fragment), opt) return ShaderProgram.create(vertex_source, fragment_source) } } companion object { @JvmStatic fun create(vertexShader: String, fragmentShader: String): ShaderProgram { val programID = glCreateProgram() linkShader(programID, GL_VERTEX_SHADER, vertexShader) linkShader(programID, GL_FRAGMENT_SHADER, fragmentShader) glLinkProgram(programID) val status = glGetProgrami(programID, GL_LINK_STATUS) if (status == GL_FALSE) { val log = glGetProgramInfoLog(programID, glGetProgrami(programID, GL_INFO_LOG_LENGTH)) throw ProgramCreationException(ErrorType.LINK, log) } return ShaderProgram(programID) } private fun linkShader(program: Int, shaderType: Int, source: String) { val shader = glCreateShader(shaderType) glShaderSource(shader, source) glCompileShader(shader) val res = glGetShaderi(shader, GL_COMPILE_STATUS) if (res == GL_FALSE) { val log = glGetShaderInfoLog(shader, glGetShaderi(shader, GL_INFO_LOG_LENGTH)) throw ProgramCreationException(ErrorType.COMPILE, log) } glAttachShader(program, shader) } } }
mit
64e1e7c7c3cecc12e9a13105b4abf46f
36.57971
110
0.667181
4.749084
false
false
false
false
Kotlin/kotlinx.coroutines
reactive/kotlinx-coroutines-reactor/src/Flux.kt
1
4152
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.reactor import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import kotlinx.coroutines.reactive.* import org.reactivestreams.* import reactor.core.* import reactor.core.publisher.* import reactor.util.context.* import kotlin.coroutines.* /** * Creates a cold reactive [Flux] that runs the given [block] in a coroutine. * Every time the returned flux is subscribed, it starts a new coroutine in the specified [context]. * The coroutine emits ([Subscriber.onNext]) values with [send][ProducerScope.send], completes ([Subscriber.onComplete]) * when the coroutine completes, or, in case the coroutine throws an exception or the channel is closed, * emits the error ([Subscriber.onError]) and closes the channel with the cause. * Unsubscribing cancels the running coroutine. * * Invocations of [send][ProducerScope.send] are suspended appropriately when subscribers apply back-pressure and to * ensure that [onNext][Subscriber.onNext] is not invoked concurrently. * * **Note: This is an experimental api.** Behaviour of publishers that work as children in a parent scope with respect * to cancellation and error handling may change in the future. * * @throws IllegalArgumentException if the provided [context] contains a [Job] instance. */ public fun <T> flux( context: CoroutineContext = EmptyCoroutineContext, @BuilderInference block: suspend ProducerScope<T>.() -> Unit ): Flux<T> { require(context[Job] === null) { "Flux context cannot contain job in it." + "Its lifecycle should be managed via Disposable handle. Had $context" } return Flux.from(reactorPublish(GlobalScope, context, block)) } private fun <T> reactorPublish( scope: CoroutineScope, context: CoroutineContext = EmptyCoroutineContext, @BuilderInference block: suspend ProducerScope<T>.() -> Unit ): Publisher<T> = Publisher onSubscribe@{ subscriber: Subscriber<in T>? -> if (subscriber !is CoreSubscriber) { subscriber.reject(IllegalArgumentException("Subscriber is not an instance of CoreSubscriber, context can not be extracted.")) return@onSubscribe } val currentContext = subscriber.currentContext() val reactorContext = context.extendReactorContext(currentContext) val newContext = scope.newCoroutineContext(context + reactorContext) val coroutine = PublisherCoroutine(newContext, subscriber, REACTOR_HANDLER) subscriber.onSubscribe(coroutine) // do it first (before starting coroutine), to avoid unnecessary suspensions coroutine.start(CoroutineStart.DEFAULT, coroutine, block) } private val REACTOR_HANDLER: (Throwable, CoroutineContext) -> Unit = { cause, ctx -> if (cause !is CancellationException) { try { Operators.onOperatorError(cause, ctx[ReactorContext]?.context ?: Context.empty()) } catch (e: Throwable) { cause.addSuppressed(e) handleCoroutineException(ctx, cause) } } } /** The proper way to reject the subscriber, according to * [the reactive spec](https://github.com/reactive-streams/reactive-streams-jvm/blob/v1.0.3/README.md#1.9) */ private fun <T> Subscriber<T>?.reject(t: Throwable) { if (this == null) throw NullPointerException("The subscriber can not be null") onSubscribe(object: Subscription { override fun request(n: Long) { // intentionally left blank } override fun cancel() { // intentionally left blank } }) onError(t) } /** * @suppress */ @Deprecated( message = "CoroutineScope.flux is deprecated in favour of top-level flux", level = DeprecationLevel.HIDDEN, replaceWith = ReplaceWith("flux(context, block)") ) // Since 1.3.0, will be error in 1.3.1 and hidden in 1.4.0. Binary compatibility with Spring public fun <T> CoroutineScope.flux( context: CoroutineContext = EmptyCoroutineContext, @BuilderInference block: suspend ProducerScope<T>.() -> Unit ): Flux<T> = Flux.from(reactorPublish(this, context, block))
apache-2.0
412d5d9e7258809cba56ef04c26ed927
41.367347
133
0.71869
4.402969
false
false
false
false
genonbeta/TrebleShot
app/src/main/java/org/monora/uprotocol/client/android/database/model/Transfer.kt
1
1653
/* * Copyright (C) 2021 Veli Tasalı * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.monora.uprotocol.client.android.database.model import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.ForeignKey.CASCADE import androidx.room.PrimaryKey import kotlinx.parcelize.Parcelize import org.monora.uprotocol.core.protocol.Direction import org.monora.uprotocol.core.transfer.TransferItem @Parcelize @Entity( tableName = "transfer", foreignKeys = [ ForeignKey( entity = UClient::class, parentColumns = ["uid"], childColumns = ["clientUid"], onDelete = CASCADE ), ] ) data class Transfer( @PrimaryKey val id: Long, @ColumnInfo(index = true) val clientUid: String, val direction: Direction, var location: String, var accepted: Boolean = false, val dateCreated: Long = System.currentTimeMillis(), ) : Parcelable
gpl-2.0
eb94b975808cc9c3b9132271ee9ac9c9
32.714286
110
0.737288
4.302083
false
false
false
false
DeflatedPickle/Quiver
core/src/main/kotlin/com/deflatedpickle/quiver/frontend/widget/quiverwidgetinator.kt
1
894
/* Copyright (c) 2021 DeflatedPickle under the MIT license */ package com.deflatedpickle.quiver.frontend.widget import com.alexandriasoftware.swing.JSplitButton import com.deflatedpickle.monocons.MonoIcon import com.deflatedpickle.undulation.extensions.add import org.jdesktop.swingx.JXButton import javax.swing.JPopupMenu fun openButton(enabled: Boolean, open: () -> Unit, openFolder: () -> Unit) = JSplitButton(" ", MonoIcon.FOLDER_OPEN_FILE).apply { popupMenu = JPopupMenu("Open Alternatives").apply { this.add("Open Folder", MonoIcon.FOLDER_OPEN) { openFolder() } } toolTipText = "Open File" isEnabled = enabled addButtonClickedActionListener { open() } } fun editButton(enabled: Boolean, action: () -> Unit) = JXButton(MonoIcon.PENCIL).apply { toolTipText = "Edit" isEnabled = enabled addActionListener { action() } }
mit
2e50687ddadcde468f34a3605d257c8e
28.8
130
0.711409
3.921053
false
false
false
false
leafclick/intellij-community
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/BreakpointsStatisticsCollector.kt
1
4445
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.xdebugger.impl.breakpoints import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.beans.newBooleanMetric import com.intellij.internal.statistic.beans.newCounterMetric import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.eventLog.validator.ValidationResultType import com.intellij.internal.statistic.eventLog.validator.rules.EventContext import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomWhiteListRule import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector import com.intellij.internal.statistic.utils.getPluginInfo import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.xdebugger.breakpoints.SuspendPolicy import com.intellij.xdebugger.breakpoints.XBreakpointType import com.intellij.xdebugger.breakpoints.XLineBreakpoint import com.intellij.xdebugger.impl.XDebuggerManagerImpl import com.intellij.xdebugger.impl.XDebuggerUtilImpl class BreakpointsStatisticsCollector : ProjectUsagesCollector() { override fun getGroupId(): String = "debugger.breakpoints" override fun getVersion(): Int = 2 override fun requiresReadAccess(): Boolean = true override fun getMetrics(project: Project): MutableSet<MetricEvent> { val breakpointManager = XDebuggerManagerImpl.getInstance(project).breakpointManager as XBreakpointManagerImpl val res = XBreakpointUtil.breakpointTypes() .filter { it.isSuspendThreadSupported() } .filter { breakpointManager.getBreakpointDefaults(it).getSuspendPolicy() != it.getDefaultSuspendPolicy() } .map { ProgressManager.checkCanceled() val data = FeatureUsageData() data.addData("suspendPolicy", breakpointManager.getBreakpointDefaults(it).getSuspendPolicy().toString()) addType(it, data) newBooleanMetric("not.default.suspend", true, data) } .toMutableSet() if (breakpointManager.allGroups.isNotEmpty()) { res.add(newBooleanMetric("using.groups", true)) } val breakpoints = breakpointManager.allBreakpoints.filter { !breakpointManager.isDefaultBreakpoint(it) } res.add(newCounterMetric("total", breakpoints.size)) res.add(newCounterMetric("total.disabled", breakpoints.count { !it.isEnabled() })) res.add(newCounterMetric("total.non.suspending", breakpoints.count { it.getSuspendPolicy() == SuspendPolicy.NONE })) if (breakpoints.any { !XDebuggerUtilImpl.isEmptyExpression(it.getConditionExpression()) }) { res.add(newBooleanMetric("using.condition", true)) } if (breakpoints.any { !XDebuggerUtilImpl.isEmptyExpression(it.getLogExpressionObject()) }) { res.add(newBooleanMetric("using.log.expression", true)) } if (breakpoints.any { it is XLineBreakpoint<*> && it.isTemporary }) { res.add(newBooleanMetric("using.temporary", true)) } if (breakpoints.any { breakpointManager.dependentBreakpointManager.isMasterOrSlave(it) }) { res.add(newBooleanMetric("using.dependent", true)) } if (breakpoints.any { it.isLogMessage() }) { res.add(newBooleanMetric("using.log.message", true)) } if (breakpoints.any { it.isLogStack() }) { res.add(newBooleanMetric("using.log.stack", true)) } return res } } fun addType(type: XBreakpointType<*, *>, data: FeatureUsageData) { val info = getPluginInfo(type.javaClass) data.addPluginInfo(info) data.addData("type", if (info.isDevelopedByJetBrains()) type.getId() else "custom") } class BreakpointsUtilValidator : CustomWhiteListRule() { override fun acceptRuleId(ruleId: String?): Boolean { return "breakpoint" == ruleId } override fun doValidate(data: String, context: EventContext): ValidationResultType { if ("custom".equals(data)) return ValidationResultType.ACCEPTED for (breakpoint in XBreakpointType.EXTENSION_POINT_NAME.extensions) { if (StringUtil.equals(breakpoint.getId(), data)) { val info = getPluginInfo(breakpoint.javaClass) return if (info.isDevelopedByJetBrains()) ValidationResultType.ACCEPTED else ValidationResultType.REJECTED } } return ValidationResultType.REJECTED } }
apache-2.0
4c5fa7b6b76067786ae209eb22f0a2fa
41.75
140
0.76063
4.591942
false
false
false
false
zdary/intellij-community
platform/platform-tests/testSrc/com/intellij/openapi/application/impl/AppUIExecutorTest.kt
3
18206
// 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.openapi.application.impl import com.intellij.openapi.Disposable import com.intellij.openapi.application.* import com.intellij.openapi.application.constraints.ConstrainedExecution import com.intellij.openapi.editor.Document import com.intellij.openapi.fileTypes.PlainTextFileType import com.intellij.openapi.util.Disposer import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFileFactory import com.intellij.testFramework.LightPlatformTestCase import com.intellij.util.ThrowableRunnable import com.intellij.util.ui.UIUtil import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import org.jetbrains.concurrency.asDeferred import java.util.concurrent.LinkedBlockingQueue import java.util.function.Consumer import javax.swing.SwingUtilities import kotlin.coroutines.CoroutineContext /** * @author eldar */ class AppUIExecutorTest : LightPlatformTestCase() { override fun runTestRunnable(testRunnable: ThrowableRunnable<Throwable>) { SwingUtilities.invokeLater { testRunnable.run() } UIUtil.dispatchAllInvocationEvents() } private object SwingDispatcher : CoroutineDispatcher() { override fun dispatch(context: CoroutineContext, block: Runnable) = SwingUtilities.invokeLater(block) } private fun Deferred<Any>.joinNonBlocking(onceJoined: () -> Unit = { }) { var countDown = 5 object : Runnable { override fun run() { if (isCompleted) { try { @Suppress("EXPERIMENTAL_API_USAGE") getCompleted() } catch (ignored: CancellationException) { } onceJoined() } else { if (countDown-- <= 0) fail("Too many EDT reschedules") SwingUtilities.invokeLater(this) } } }.run() } fun `test submitted task is not executed once expired`() { val queue = LinkedBlockingQueue<String>() val disposable = object : Disposable.Parent { override fun beforeTreeDispose() { queue.add("disposable.beforeTreeDispose()") } override fun dispose() { queue.add("disposable.dispose()") } }.also { Disposer.register(testRootDisposable, it) } val executor = AppUIExecutor.onUiThread(ModalityState.any()).later().expireWith(disposable) queue.add("before submit") val promise = executor.submit { queue.add("run") }.onProcessed(Consumer { queue.add("promise processed") }) queue.add("after submit") Disposer.dispose(disposable) promise.asDeferred().joinNonBlocking { assertOrderedEquals(queue, "before submit", "after submit", "disposable.beforeTreeDispose()", "promise processed", "disposable.dispose()") } } fun `test coroutine onUiThread`() { val executor = AppUIExecutor.onUiThread(ModalityState.any()) GlobalScope.async(executor.coroutineDispatchingContext()) { ApplicationManager.getApplication().assertIsDispatchThread() }.joinNonBlocking() } fun `test coroutine withExpirable`() { val queue = LinkedBlockingQueue<String>() val disposable = Disposable { queue.add("disposed") }.also { Disposer.register(testRootDisposable, it) } val executor = AppUIExecutor.onUiThread(ModalityState.any()) .expireWith(disposable) GlobalScope.async(SwingDispatcher) { queue.add("start") launch(executor.coroutineDispatchingContext()) { ApplicationManager.getApplication().assertIsDispatchThread() queue.add("coroutine start") Disposer.dispose(disposable) try { queue.add("coroutine before yield") yield() queue.add("coroutine after yield") } catch (e: Exception) { ApplicationManager.getApplication().assertIsDispatchThread() queue.add("coroutine yield caught ${e.javaClass.simpleName}") throw e } queue.add("coroutine end") }.join() queue.add("end") assertOrderedEquals(queue, "start", "coroutine start", "disposed", "coroutine before yield", "coroutine yield caught JobCancellationException", "end") }.joinNonBlocking() } private fun createDocument(): Document { val file = PsiFileFactory.getInstance(project).createFileFromText("a.txt", PlainTextFileType.INSTANCE, "") return file.viewProvider.document!! } @ExperimentalCoroutinesApi fun `test withDocumentsCommitted`() { val executor = AppUIExecutor.onUiThread(ModalityState.NON_MODAL) .withDocumentsCommitted(project) val transactionExecutor = AppUIExecutor.onUiThread(ModalityState.NON_MODAL) .inTransaction(project) GlobalScope.async(SwingDispatcher) { val pdm = PsiDocumentManager.getInstance(project) val commitChannel = Channel<Unit>() val job = launch(executor.coroutineDispatchingContext()) { commitChannel.receive() assertFalse(pdm.hasUncommitedDocuments()) val document = runWriteAction { createDocument().apply { insertString(0, "a") assertTrue(pdm.hasUncommitedDocuments()) } } commitChannel.receive() assertFalse(pdm.hasUncommitedDocuments()) assertEquals("a", document.text) runWriteAction { document.insertString(1, "b") assertTrue(pdm.hasUncommitedDocuments()) } commitChannel.receive() assertFalse(pdm.hasUncommitedDocuments()) assertEquals("ab", document.text) commitChannel.close() } withContext(transactionExecutor.coroutineDispatchingContext() + job) { while (true) { runWriteAction { pdm.commitAllDocuments() } if (!commitChannel.isClosedForSend) { commitChannel.send(Unit) } else { return@withContext } } } coroutineContext.cancelChildren() }.joinNonBlocking() } fun `test custom simple constraints`() { var scheduled = false val executor = AppUIExecutor.onUiThread() .withConstraint(object : ConstrainedExecution.ContextConstraint { override fun isCorrectContext(): Boolean = scheduled override fun schedule(runnable: Runnable) { scheduled = true runnable.run() scheduled = false } override fun toString() = "test" }) GlobalScope.async(executor.coroutineDispatchingContext()) { assertTrue(scheduled) yield() assertTrue(scheduled) }.joinNonBlocking() } fun `test custom expirable constraints disposed before suspending`() { val queue = LinkedBlockingQueue<String>() var scheduled = false val disposable = Disposable { queue.add("disposable.dispose()") }.also { Disposer.register(testRootDisposable, it) } val executor = AppUIExecutor.onUiThread() .withConstraint(object : ConstrainedExecution.ContextConstraint { override fun isCorrectContext(): Boolean = scheduled override fun schedule(runnable: Runnable) { if (Disposer.isDisposed(disposable)) { queue.add("refuse to run already disposed") return } scheduled = true runnable.run() scheduled = false } override fun toString() = "test" }, disposable) queue.add("start") GlobalScope.async(SwingDispatcher) { launch(executor.coroutineDispatchingContext()) { queue.add("coroutine start") assertTrue(scheduled) yield() assertTrue(scheduled) queue.add("disposing") Disposer.dispose(disposable) try { queue.add("before yield disposed") yield() queue.add("after yield disposed") } catch (e: Throwable) { queue.add("coroutine yield caught ${e.javaClass.simpleName}") throw e } queue.add("coroutine end") }.join() queue.add("end") assertOrderedEquals(queue, "start", "coroutine start", "disposing", "disposable.dispose()", "before yield disposed", "coroutine yield caught JobCancellationException", "end") }.joinNonBlocking() } fun `test custom expirable constraints disposed before resuming`() { val queue = LinkedBlockingQueue<String>() var scheduled = false var shouldDisposeBeforeSend = false val disposable = object : Disposable.Parent { override fun beforeTreeDispose() { queue.add("disposable.beforeTreeDispose()") } override fun dispose() { queue.add("disposable.dispose()") } }.also { Disposer.register(testRootDisposable, it) } val uiExecutor = AppUIExecutor.onUiThread() val executor = uiExecutor .withConstraint(object : ConstrainedExecution.ContextConstraint { override fun isCorrectContext(): Boolean = scheduled override fun schedule(runnable: Runnable) { if (Disposer.isDisposed(disposable)) { queue.add("refuse to run already disposed") return } scheduled = true runnable.run() scheduled = false } override fun toString() = "test" }, disposable) GlobalScope.async(SwingDispatcher) { queue.add("start") val channel = Channel<Unit>() val job = launch(executor.coroutineDispatchingContext()) { queue.add("coroutine start") assertTrue(scheduled) channel.receive() assertTrue(scheduled) try { shouldDisposeBeforeSend = true queue.add("before yield") channel.receive() queue.add("after yield disposed") } catch (e: Throwable) { queue.add("coroutine yield caught ${e.javaClass.simpleName}") throw e } queue.add("coroutine end") channel.close() } launch(uiExecutor.coroutineDispatchingContext() + job) { try { while (true) { if (shouldDisposeBeforeSend) { queue.add("disposing") Disposer.dispose(disposable) } channel.send(Unit) } } catch (e: Throwable) { throw e } } job.join() queue.add("end") assertOrderedEquals(queue,( "start\n" + "coroutine start\n" + "before yield\n" + "disposing\n" + "disposable.beforeTreeDispose()\n" + "refuse to run already disposed\n" + "disposable.dispose()\n" + "coroutine yield caught JobCancellationException\n" + "end").split("\n")) }.joinNonBlocking() } fun `test custom expirable constraints disposed during dispatching`() = doTestCustomExpirableConstraintsDisposedDuringDispatching(expectedLog = arrayOf( "[context: !outer + !inner] start", "[context: outer + inner] coroutine start", "[context: outer + inner] before receive", "disposing constraint", "constraintDisposable.beforeTreeDispose()", "constraintDisposable.dispose()", "refuse to run already disposed", "[context: !outer + inner] coroutine yield caught JobCancellationException", "[context: !outer + !inner] end") ) { queue, constraintDisposable, _ -> queue.add("disposing constraint") Disposer.dispose(constraintDisposable) } fun `test custom expirable constraints disposed during dispatching through both disposables`() = doTestCustomExpirableConstraintsDisposedDuringDispatching(expectedLog = arrayOf( "[context: !outer + !inner] start", "[context: outer + inner] coroutine start", "[context: outer + inner] before receive", "disposing anotherDisposable", "anotherDisposable.beforeTreeDispose()", "anotherDisposable.dispose()", "disposing constraint", "constraintDisposable.beforeTreeDispose()", "constraintDisposable.dispose()", "refuse to run already disposed", "[context: !outer + inner] coroutine yield caught JobCancellationException", "[context: !outer + !inner] end") ) { queue, constraintDisposable, anotherDisposable -> queue.add("disposing anotherDisposable") Disposer.dispose(anotherDisposable) queue.add("disposing constraint") Disposer.dispose(constraintDisposable) } fun `test custom expirable constraints disposed another disposable`() = doTestCustomExpirableConstraintsDisposedDuringDispatching(expectedLog = arrayOf( "[context: !outer + !inner] start", "[context: outer + inner] coroutine start", "[context: outer + inner] before receive", "disposing anotherDisposable", "anotherDisposable.beforeTreeDispose()", "anotherDisposable.dispose()", "[context: outer + inner] coroutine yield caught JobCancellationException", "[context: !outer + !inner] end") ) { queue, _, anotherDisposable -> queue.add("disposing anotherDisposable") Disposer.dispose(anotherDisposable) } private fun doTestCustomExpirableConstraintsDisposedDuringDispatching(expectedLog: Array<String>, doDispose: (queue: LinkedBlockingQueue<String>, constraintDisposable: Disposable.Parent, anotherDisposable: Disposable.Parent) -> Unit) { val queue = LinkedBlockingQueue<String>() var outerScheduled = false var innerScheduled = false var shouldDisposeOnDispatch = false fun emit(s: String) { fun Boolean.toFlagString(name: String) = if (this) name else "!$name" val contextState = "context: ${outerScheduled.toFlagString("outer")} + ${innerScheduled.toFlagString("inner")}" queue += "[$contextState] $s" } val constraintDisposable = object : Disposable.Parent { override fun beforeTreeDispose() { queue.add("constraintDisposable.beforeTreeDispose()") } override fun dispose() { queue.add("constraintDisposable.dispose()") } }.also { Disposer.register(testRootDisposable, it) } val anotherDisposable = object : Disposable.Parent { override fun beforeTreeDispose() { queue.add("anotherDisposable.beforeTreeDispose()") } override fun dispose() { queue.add("anotherDisposable.dispose()") } }.also { Disposer.register(testRootDisposable, it) } val uiExecutor = AppUIExecutor.onUiThread() val executor = uiExecutor .withConstraint(object : ConstrainedExecution.ContextConstraint { override fun isCorrectContext(): Boolean = outerScheduled override fun schedule(runnable: Runnable) { if (shouldDisposeOnDispatch) { doDispose(queue, constraintDisposable, anotherDisposable) } if (Disposer.isDisposed(constraintDisposable)) { queue.add("refuse to run already disposed") return } outerScheduled = true runnable.run() outerScheduled = false } override fun toString() = "test outer" }, constraintDisposable) .withConstraint(object : ConstrainedExecution.ContextConstraint { override fun isCorrectContext(): Boolean = innerScheduled override fun schedule(runnable: Runnable) { innerScheduled = true runnable.run() innerScheduled = false } override fun toString() = "test inner" }) .expireWith(anotherDisposable) GlobalScope.async(SwingDispatcher) { emit("start") val channel = Channel<Unit>() val job = launch(executor.coroutineDispatchingContext()) { emit("coroutine start") assertTrue(outerScheduled) channel.receive() assertTrue(outerScheduled) try { shouldDisposeOnDispatch = true emit("before receive") channel.receive() emit("after receive disposed") yield() emit("after yield disposed") } catch (e: Throwable) { emit("coroutine yield caught ${e.javaClass.simpleName}") throw e } emit("coroutine end") channel.close() } launch(uiExecutor.coroutineDispatchingContext() + job) { try { while (true) { channel.send(Unit) } } catch (e: Throwable) { throw e } } job.join() emit("end") assertOrderedEquals(queue, *expectedLog) }.joinNonBlocking() } fun `test use write-safe context if called from write-unsafe context`() { GlobalScope.async(SwingDispatcher) { launch(AppUIExecutor.onWriteThread().coroutineDispatchingContext()) { (TransactionGuard.getInstance() as TransactionGuardImpl).assertWriteActionAllowed() } launch(AppUIExecutor.onUiThread().coroutineDispatchingContext()) { (TransactionGuard.getInstance() as TransactionGuardImpl).assertWriteActionAllowed() } launch(AppUIExecutor.onUiThread(ModalityState.any()).coroutineDispatchingContext()) { assertFalse("Passing write-unsafe modality should not lead to write-safety checks", TransactionGuard.getInstance().isWritingAllowed) } }.joinNonBlocking() } }
apache-2.0
93c0d81cb0f76cfb4238607c32cd9a1d
32.224453
140
0.618477
5.255774
false
true
false
false
leafclick/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/issue/quickfix/GradleSettingsQuickFix.kt
1
2655
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.issue.quickfix import com.intellij.build.issue.BuildIssueQuickFix import com.intellij.ide.actions.ShowSettingsUtilImpl import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.externalSystem.issue.quickfix.ReimportQuickFix.Companion.requestImport import com.intellij.openapi.options.ex.ConfigurableVisitor import com.intellij.openapi.options.newEditor.SettingsDialogFactory import com.intellij.openapi.project.Project import org.jetbrains.annotations.ApiStatus import org.jetbrains.plugins.gradle.service.settings.GradleConfigurable import org.jetbrains.plugins.gradle.settings.GradleProjectSettings import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.util.GradleConstants import java.util.concurrent.CompletableFuture import java.util.function.BiPredicate @ApiStatus.Experimental class GradleSettingsQuickFix(private val myProjectPath: String, private val myRequestImport: Boolean, private val myConfigurationChangeDetector: BiPredicate<GradleProjectSettings, GradleProjectSettings>?, private val myFilter: String?) : BuildIssueQuickFix { override val id: String = "fix_gradle_settings" override fun runQuickFix(project: Project, dataProvider: DataProvider): CompletableFuture<*> { val projectSettings = GradleSettings.getInstance(project).getLinkedProjectSettings(myProjectPath) ?: return CompletableFuture.completedFuture(false) val future = CompletableFuture<Boolean>() ApplicationManager.getApplication().invokeLater { val oldSettings: GradleProjectSettings? oldSettings = projectSettings.clone() val groups = ShowSettingsUtilImpl.getConfigurableGroups(project, true) val configurable = ConfigurableVisitor.findByType(GradleConfigurable::class.java, groups.toList()) val dialogWrapper = SettingsDialogFactory.getInstance().create(project, groups, configurable, myFilter) val result = dialogWrapper.showAndGet() future.complete(result && myConfigurationChangeDetector != null && myConfigurationChangeDetector.test(oldSettings, projectSettings)) } return future.thenCompose { isSettingsChanged -> if (isSettingsChanged!! && myRequestImport) requestImport(project, myProjectPath, GradleConstants.SYSTEM_ID) else CompletableFuture.completedFuture(null) } } }
apache-2.0
14d7f8568c4629ce2a7f3362f9293c83
54.3125
140
0.790207
5.205882
false
true
false
false
blokadaorg/blokada
android5/app/src/libre/kotlin/ui/StatsViewModel.kt
1
6532
/* * This file is part of Blokada. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * Copyright © 2021 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package ui import androidx.lifecycle.* import engine.EngineService import kotlinx.coroutines.launch import model.* import service.EnvironmentService import service.PersistenceService import service.StatsService import ui.utils.cause import utils.FlavorSpecific import utils.Logger class StatsViewModel : ViewModel(), FlavorSpecific { enum class Sorting { RECENT, TOP } enum class Filter { ALL, BLOCKED, ALLOWED } private val log = Logger("Stats") private val persistence = PersistenceService private val engine = EngineService private val statistics = StatsService private var sorting = Sorting.RECENT private var filter = Filter.ALL private var searchTerm: String? = null private val _stats = MutableLiveData<Stats>() val stats: LiveData<Stats> = _stats.distinctUntilChanged() val history = _stats.map { applyFilters(it.entries) } private val _allowed = MutableLiveData<Allowed>() val allowed = _allowed.map { it.value } private val _denied = MutableLiveData<Denied>() val denied = _denied.map { it.value } init { viewModelScope.launch { _allowed.value = persistence.load(Allowed::class) _denied.value = persistence.load(Denied::class) statistics.setup() } } fun refresh() { viewModelScope.launch { try { _stats.value = statistics.getStats() _allowed.value = _allowed.value _denied.value = _denied.value } catch (ex: Exception) { log.e("Could not load stats".cause(ex)) } } } fun clear() { statistics.clear() refresh() } fun get(forName: String): HistoryEntry? { return history.value?.firstOrNull { it.name == forName } } fun getFilter() = filter fun getSorting() = sorting fun getSearch() = searchTerm // Mocked getters to be compatible with NotLibre flavor fun getDevice() = EnvironmentService.getDeviceAlias() fun device(device: String?) = {} fun filter(filter: Filter) { this.filter = filter updateLiveData() } fun sort(sort: Sorting) { this.sorting = sort updateLiveData() } fun search(search: String?) { this.searchTerm = search updateLiveData() } fun allow(name: String) { _allowed.value?.let { current -> viewModelScope.launch { try { val new = current.allow(name) persistence.save(new) _allowed.value = new updateLiveData() engine.reloadBlockLists() } catch (ex: Exception) { log.e("Could not allow host $name".cause(ex)) persistence.save(current) } } } } fun unallow(name: String) { _allowed.value?.let { current -> viewModelScope.launch { try { val new = current.unallow(name) persistence.save(new) _allowed.value = new updateLiveData() engine.reloadBlockLists() } catch (ex: Exception) { log.e("Could not unallow host $name".cause(ex)) persistence.save(current) } } } } fun deny(name: String) { _denied.value?.let { current -> viewModelScope.launch { try { val new = current.deny(name) persistence.save(new) _denied.value = new updateLiveData() engine.reloadBlockLists() } catch (ex: Exception) { log.e("Could not deny host $name".cause(ex)) persistence.save(current) } } } } fun undeny(name: String) { _denied.value?.let { current -> viewModelScope.launch { try { val new = current.undeny(name) persistence.save(new) _denied.value = new updateLiveData() engine.reloadBlockLists() } catch (ex: Exception) { log.e("Could not undeny host $name".cause(ex)) persistence.save(current) } } } } fun isAllowed(name: String): Boolean { return _allowed.value?.value?.contains(name) ?: false } fun isDenied(name: String): Boolean { return _denied.value?.value?.contains(name) ?: false } private fun updateLiveData() { viewModelScope.launch { // This will cause to emit new event and to refresh the public LiveData _stats.value = _stats.value } } private fun applyFilters(history: List<HistoryEntry>): List<HistoryEntry> { var entries = history // Apply search term searchTerm?.run { entries = history.filter { it.name.contains(this, ignoreCase = true) } } // Apply filtering when (filter) { Filter.BLOCKED -> { // Show blocked and denied hosts only entries = entries.filter { it.type == HistoryEntryType.blocked || it.type == HistoryEntryType.blocked_denied } } Filter.ALLOWED -> { // Show allowed and bypassed hosts only entries = entries.filter { it.type != HistoryEntryType.blocked && it.type != HistoryEntryType.blocked_denied } } else -> {} } // Apply sorting return when(sorting) { Sorting.TOP -> { // Sorted by the number of requests entries.sortedByDescending { it.requests } } Sorting.RECENT -> { // Sorted by recent entries.sortedByDescending { it.time } } } } }
mpl-2.0
41d22c419bf36c6eec29f7a4d3ec41ab
27.902655
126
0.53315
4.852155
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/mapping/inlineReifiedFun.kt
1
465
// IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.reflect.* import kotlin.reflect.jvm.* import kotlin.test.assertEquals inline fun <reified T> f() = 1 fun g() {} class Foo { inline fun <reified T> h(t: T) = 1 } fun box(): String { assertEquals(::g as Any?, ::g.javaMethod!!.kotlinFunction) val h = Foo::class.members.single { it.name == "h" } as KFunction<*> assertEquals(h, h.javaMethod!!.kotlinFunction as Any?) return "OK" }
apache-2.0
969f083049e911157131b0f6edd6cfeb
19.217391
72
0.649462
3.321429
false
false
false
false
tommy-kw/AndroidDesignSupportLibrarySample
ViewPager/app/src/main/java/tokyo/tommykw/viewpager/app/Logger.kt
3
1374
package tokyo.tommykw.viewpager.app import android.os.SystemClock import android.util.Log import java.util.ArrayList import kotlin.properties.Delegates /** * Created by tommy on 15/12/22. */ class Logger(val tag: String, val label: String) { private val logTag by lazy { tag } private val logLabel by lazy { label } private var splits = ArrayList<Long>() private var splitLabels = ArrayList<String>() private var disabled = false fun reset() { disabled = !Log.isLoggable(logTag, Log.VERBOSE) if (disabled) return if (splits == null) { splits = ArrayList() splitLabels = ArrayList() } else { splits.clear() splitLabels.clear() } } fun addSplit(splitLabel: String) { if (disabled) return splits.add(SystemClock.elapsedRealtime()) splitLabels.add(splitLabel) } fun dump() { if (disabled) return Log.d(logTag, logLabel + ":begin") val first = splits[0] var now = first for (i in 1..splits.size - 1) { now = splits[i] val prev = splits[i - 1] val splitLabel = splitLabels[i] Log.d(logTag, logTag + ": " + (now - prev) + " ms, " + splitLabel) } Log.d(logTag, logLabel + ": end, " + (now - first) + " ms") } }
apache-2.0
ae33346cadfa7dcde60223f34c7d3dca
26.48
81
0.566958
3.859551
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/data/network/PersistentCookieStore.kt
2
2452
package eu.kanade.tachiyomi.data.network import android.content.Context import okhttp3.Cookie import okhttp3.HttpUrl import java.net.URI import java.util.concurrent.ConcurrentHashMap class PersistentCookieStore(context: Context) { private val cookieMap = ConcurrentHashMap<String, List<Cookie>>() private val prefs = context.getSharedPreferences("cookie_store", Context.MODE_PRIVATE) init { for ((key, value) in prefs.all) { @Suppress("UNCHECKED_CAST") val cookies = value as? Set<String> if (cookies != null) { try { val url = HttpUrl.parse("http://$key") val nonExpiredCookies = cookies.map { Cookie.parse(url, it) } .filter { !it.hasExpired() } cookieMap.put(key, nonExpiredCookies) } catch (e: Exception) { // Ignore } } } } fun addAll(url: HttpUrl, cookies: List<Cookie>) { synchronized(this) { val key = url.uri().host // Append or replace the cookies for this domain. val cookiesForDomain = cookieMap[key].orEmpty().toMutableList() for (cookie in cookies) { // Find a cookie with the same name. Replace it if found, otherwise add a new one. val pos = cookiesForDomain.indexOfFirst { it.name() == cookie.name() } if (pos == -1) { cookiesForDomain.add(cookie) } else { cookiesForDomain[pos] = cookie } } cookieMap.put(key, cookiesForDomain) // Get cookies to be stored in disk val newValues = cookiesForDomain.asSequence() .filter { it.persistent() && !it.hasExpired() } .map { it.toString() } .toSet() prefs.edit().putStringSet(key, newValues).apply() } } fun removeAll() { synchronized(this) { prefs.edit().clear().apply() cookieMap.clear() } } fun get(url: HttpUrl) = get(url.uri().host) fun get(uri: URI) = get(uri.host) private fun get(url: String): List<Cookie> { return cookieMap[url].orEmpty().filter { !it.hasExpired() } } private fun Cookie.hasExpired() = System.currentTimeMillis() >= expiresAt() }
gpl-3.0
7cd15c8bfa467910ae183652853e8352
31.706667
98
0.53956
4.600375
false
false
false
false
JetBrains/kotlin-native
backend.native/tests/runtime/basic/hypot.kt
4
1458
/* * Copyright 2010-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. */ import kotlin.test.* import kotlin.math.* fun main() { val hf = hypot(Float.NEGATIVE_INFINITY, Float.NaN) println("float hypot: $hf ${hf.toRawBits().toString(16)}") println("Float.NaN: ${Float.NaN.toRawBits().toString(16)}") println("Float.+Inf: ${Float.POSITIVE_INFINITY} ${Float.POSITIVE_INFINITY.toRawBits().toString(16)}") println("Float.-Inf: ${Float.NEGATIVE_INFINITY} ${Float.NEGATIVE_INFINITY.toRawBits().toUInt().toString(16)}") println(Float.POSITIVE_INFINITY == Float.NEGATIVE_INFINITY) assertEquals(Float.POSITIVE_INFINITY, hypot(Float.NEGATIVE_INFINITY, Float.NaN)) val hd = hypot(Double.NEGATIVE_INFINITY, Double.NaN) println("Double hypot: $hd ${hd.toRawBits().toString(16)}") println("Double.NaN: ${Double.NaN.toRawBits().toString(16)}") println("Double.+Inf: ${Double.POSITIVE_INFINITY} ${Double.POSITIVE_INFINITY.toRawBits().toString(16)}") println("Double.-Inf: ${Double.NEGATIVE_INFINITY} ${Double.NEGATIVE_INFINITY.toRawBits().toUInt().toString(16)}") println(Double.POSITIVE_INFINITY == Double.NEGATIVE_INFINITY) assertEquals(Double.POSITIVE_INFINITY, hypot(Double.NEGATIVE_INFINITY, Double.NaN)) println("hypot NaN, 0: ${hypot(Double.NaN, 0.0).toRawBits().toString(16)}") assertTrue(hypot(Double.NaN, 0.0).isNaN()) }
apache-2.0
950f90b0c2616ccbe3b59a6ffcb19e4d
51.107143
117
0.709877
3.691139
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/planner/steps/vm/migrate/kvm/KvmMigrateVirtualMachineFactory.kt
2
3283
package com.github.kerubistan.kerub.planner.steps.vm.migrate.kvm import com.github.kerubistan.kerub.model.Expectation import com.github.kerubistan.kerub.model.collection.VirtualMachineDataCollection import com.github.kerubistan.kerub.model.dynamic.VirtualStorageBlockDeviceAllocation import com.github.kerubistan.kerub.model.dynamic.VirtualStorageFsAllocation import com.github.kerubistan.kerub.model.expectations.VirtualMachineAvailabilityExpectation import com.github.kerubistan.kerub.model.services.IscsiService import com.github.kerubistan.kerub.model.services.NfsService import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.planner.issues.problems.Problem import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStepFactory import com.github.kerubistan.kerub.planner.steps.vm.common.allNetworksAvailable import com.github.kerubistan.kerub.planner.steps.vm.common.getVirtualNetworkConnections import com.github.kerubistan.kerub.planner.steps.vm.match import io.github.kerubistan.kroki.collections.concat import kotlin.reflect.KClass /** * Takes each running virtual machines and running hosts except the one the VM is running on * and generates steps if the host matches the requirements of the VM. */ object KvmMigrateVirtualMachineFactory : AbstractOperationalStepFactory<KvmMigrateVirtualMachine>() { override val problemHints = setOf<KClass<out Problem>>() override val expectationHints = setOf<KClass<out Expectation>>(VirtualMachineAvailabilityExpectation::class) override fun produce(state: OperationalState): List<KvmMigrateVirtualMachine> = state.index.runningHosts.map { hostData -> state.index.runningVms.mapNotNull { vmData -> val virtualNetworkConnections by lazy { getVirtualNetworkConnections(vmData.stat, hostData) } if (match(hostData, vmData.stat) && allStorageShared(vmData, state) && allNetworksAvailable(vmData.stat, virtualNetworkConnections)) { val sourceId = vmData.dynamic?.hostId if (sourceId != hostData.stat.id) { KvmMigrateVirtualMachine( vm = vmData.stat, source = requireNotNull(state.hosts[sourceId]).stat, target = hostData.stat ) } else null } else null } }.concat() private fun allStorageShared(vm: VirtualMachineDataCollection, state: OperationalState): Boolean = vm.stat.virtualStorageLinks.all { link -> val storage = requireNotNull(state.vStorage[link.virtualStorageId]) // this attached have an allocation that is shared with some protocol // OR if it is read only, then it is ok if we have a copy of it on the // target server storage.dynamic?.allocations?.any { allocation -> val storageHost = requireNotNull(state.hosts[allocation.hostId]) when (allocation) { is VirtualStorageBlockDeviceAllocation -> storageHost.config?.services?.any { service -> service is IscsiService && service.vstorageId == storage.stat.id } ?: false is VirtualStorageFsAllocation -> storageHost.config?.services?.any { service -> service is NfsService && service.directory == allocation.mountPoint } ?: false else -> TODO("Hey this is totally unexpected: $allocation") } } ?: false } }
apache-2.0
7f75790c0ab552645c8181b3c44f11c1
46.594203
109
0.764545
4.280313
false
false
false
false
jwren/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/actions/InsertEmptyTableAction.kt
2
10652
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.editor.tables.actions import com.intellij.codeInsight.hint.HintManager import com.intellij.codeInsight.hint.HintManagerImpl import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.executeCommand import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorModificationUtil import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import com.intellij.refactoring.suggested.startOffset import com.intellij.ui.IdeBorderFactory import com.intellij.ui.LightweightHint import com.intellij.ui.components.JBLabel import com.intellij.util.DocumentUtil import com.intellij.util.ui.UIUtil import net.miginfocom.swing.MigLayout import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.editor.tables.TableModificationUtils import org.intellij.plugins.markdown.editor.tables.TableUtils import org.intellij.plugins.markdown.lang.MarkdownFileType import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableCell import org.intellij.plugins.markdown.ui.actions.MarkdownActionPlaces import java.awt.Component import java.awt.Dimension import java.awt.Point import java.awt.event.ActionEvent import java.awt.event.KeyEvent import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.* import kotlin.math.floor /** * Note: we count table rows including header. So, this action assumes that this is a 1x1 table: * ``` * | | * |-----| * ``` * And this is 2x1: * ``` * | | * |-----| * | | * ``` */ internal class InsertEmptyTableAction: DumbAwareAction() { init { addTextOverride(MarkdownActionPlaces.INSERT_POPUP) { MarkdownBundle.message("action.Markdown.InsertEmptyTable.insert.popup.text") } } override fun actionPerformed(event: AnActionEvent) { val project = event.project ?: return val editor = event.getRequiredData(CommonDataKeys.EDITOR) val file = event.getRequiredData(CommonDataKeys.PSI_FILE) val hintComponent = TableGridComponent { rows, columns -> actuallyInsertTable(project, editor, file, rows, columns) } val hint = LightweightHint(hintComponent) hintComponent.parentHint = hint hint.setForceShowAsPopup(true) val hintManager = HintManagerImpl.getInstanceImpl() val position = hintManager.getHintPosition(hint, editor, HintManager.DEFAULT) hint.setFocusRequestor(hintComponent) hintManager.showEditorHint( hint, editor, position, HintManager.HIDE_BY_ESCAPE or HintManager.UPDATE_BY_SCROLLING, 0, true ) } override fun update(event: AnActionEvent) { val project = event.project val editor = event.getData(CommonDataKeys.EDITOR) val file = event.getData(CommonDataKeys.PSI_FILE) event.presentation.isEnabledAndVisible = project != null && editor != null && file?.fileType == MarkdownFileType.INSTANCE } private fun actuallyInsertTable(project: Project, editor: Editor, file: PsiFile, rows: Int, columns: Int) { runWriteAction { executeCommand(project) { val caret = editor.caretModel.currentCaret val document = editor.document val caretOffset = caret.offset val currentLine = document.getLineNumber(caret.offset) val text = TableModificationUtils.buildEmptyTable(rows, columns) val content = when { currentLine != 0 && !DocumentUtil.isLineEmpty(document, currentLine - 1) -> "\n$text" else -> text } EditorModificationUtil.insertStringAtCaret(editor, content) PsiDocumentManager.getInstance(project).commitDocument(document) val table = TableUtils.findTable(file, caretOffset) val offsetToMove = table?.let { PsiTreeUtil.findChildOfType(it, MarkdownTableCell::class.java) }?.startOffset if (offsetToMove != null) { caret.moveToOffset(offsetToMove) } } } } private class TableGridComponent( private var rows: Int = 4, private var columns: Int = 4, private val expandFactor: Int = 2, private val selectedCallback: (Int, Int) -> Unit ): JPanel(MigLayout("insets 8")) { lateinit var parentHint: LightweightHint private val cells = arrayListOf<ArrayList<Cell>>() private var selectedCellRow = 0 private var selectedCellColumn = 0 private val gridPanel = JPanel(MigLayout("insets 0, gap 3")) private val label = JBLabel() private val mouseListener = MyMouseListener() private val childMouseListener = MyForwardingMouseListener(gridPanel) init { for (rowIndex in 0 until rows) { cells.add(generateSequence(this::createCell).take(columns).toCollection(ArrayList(columns))) } fillGrid() add(gridPanel, "wrap") add(label, "align center") gridPanel.addMouseMotionListener(mouseListener) gridPanel.addMouseListener(mouseListener) registerAction(KeyEvent.VK_RIGHT, "selectRight", ArrowAction { 0 to 1 }) registerAction(KeyEvent.VK_LEFT, "selectLeft", ArrowAction { 0 to -1 }) registerAction(KeyEvent.VK_UP, "selectUp", ArrowAction { -1 to 0 }) registerAction(KeyEvent.VK_DOWN, "selectDown", ArrowAction { 1 to 0 }) registerAction(KeyEvent.VK_ENTER, "confirmSelection", object: AbstractAction() { override fun actionPerformed(event: ActionEvent) { indicesSelected(selectedCellRow, selectedCellColumn) } }) updateSelection(0, 0) } private fun indicesSelected(selectedRow: Int, selectedColumn: Int) { parentHint.hide() selectedCallback.invoke(selectedRow, selectedColumn + 1) } private fun registerAction(key: Int, actionKey: String, action: Action) { val inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW) inputMap.put(KeyStroke.getKeyStroke(key, 0), actionKey) actionMap.put(actionKey, action) } private fun fillGrid() { for (row in 0 until rows) { for (column in 0 until columns) { val cell = cells[row][column] when { column == columns - 1 && row != rows - 1 -> gridPanel.add(cell, "wrap") else -> gridPanel.add(cell) } } } } private fun expandGrid(expandRows: Boolean, expandColumns: Boolean) { gridPanel.removeAll() if (expandRows) { repeat(expandFactor) { cells.add(generateSequence(this::createCell).take(columns).toCollection(ArrayList(columns))) } rows += expandFactor } if (expandColumns) { for (row in cells) { repeat(expandFactor) { row.add(createCell()) } } columns += expandFactor } fillGrid() } private fun updateSelection(selectedRow: Int, selectedColumn: Int) { selectedCellRow = selectedRow selectedCellColumn = selectedColumn @Suppress("HardCodedStringLiteral") label.text = "${selectedRow + 1}×${selectedColumn + 1}" for (row in 0 until rows) { for (column in 0 until columns) { cells[row][column].isSelected = row <= selectedCellRow && column <= selectedCellColumn } } repaint() val shouldExpandRows = rows < maxRows && selectedRow + 1 == rows val shouldExpandColumns = columns < maxColumns && selectedColumn + 1 == columns if (shouldExpandRows || shouldExpandColumns) { expandGrid(expandRows = shouldExpandRows, expandColumns = shouldExpandColumns) parentHint.pack() parentHint.component.revalidate() parentHint.component.repaint() } } private fun createCell(): Cell { return Cell().apply { addMouseListener(childMouseListener) addMouseMotionListener(childMouseListener) } } private inner class ArrowAction(private val calcDiff: () -> Pair<Int, Int>): AbstractAction() { override fun actionPerformed(event: ActionEvent) { val (rowDiff, columnDiff) = calcDiff.invoke() var row = selectedCellRow + rowDiff var column = selectedCellColumn + columnDiff row = row.coerceAtMost(rows - 1).coerceAtLeast(0) column = column.coerceAtMost(columns - 1).coerceAtLeast(0) updateSelection(row, column) } } private class MyForwardingMouseListener(private val targetComponent: Component): MouseAdapter() { private fun dispatch(event: MouseEvent) { val translated = SwingUtilities.convertMouseEvent(event.component, event, targetComponent) targetComponent.dispatchEvent(translated) } override fun mouseMoved(event: MouseEvent) = dispatch(event) override fun mouseClicked(event: MouseEvent) = dispatch(event) } private inner class MyMouseListener: MouseAdapter() { private fun obtainIndices(point: Point): Pair<Int, Int> { val panelWidth = gridPanel.width.toFloat() val panelHeight = gridPanel.height.toFloat() val tileWidth = panelWidth / columns val tileHeight = panelHeight / rows val column = floor(point.x.toFloat() / tileWidth).toInt().coerceIn(0, columns - 1) val row = floor(point.y.toFloat() / tileHeight).toInt().coerceIn(0, rows - 1) return row to column } override fun mouseMoved(event: MouseEvent) { val (row, column) = obtainIndices(event.point) updateSelection(row, column) } override fun mouseClicked(event: MouseEvent) { if (SwingUtilities.isLeftMouseButton(event)) { val (row, column) = obtainIndices(event.point) updateSelection(row, column) indicesSelected(row, column) } } } private class Cell: JPanel() { init { background = UIUtil.getTextFieldBackground() size = Dimension(15, 15) preferredSize = size border = IdeBorderFactory.createBorder() } var isSelected = false set(value) { field = value background = when { value -> UIUtil.getFocusedFillColor() else -> UIUtil.getEditorPaneBackground() } } } companion object { private const val maxRows = 10 private const val maxColumns = 10 } } }
apache-2.0
b5c6296b776a9b9db9387110d56da335
35.854671
158
0.686321
4.522718
false
false
false
false
JetBrains/kotlin-native
Interop/Runtime/src/native/kotlin/kotlinx/cinterop/ObjectiveCImpl.kt
1
8498
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE") package kotlinx.cinterop import kotlin.native.* import kotlin.native.internal.ExportTypeInfo import kotlin.native.internal.ExportForCppRuntime import kotlin.native.internal.TypedIntrinsic import kotlin.native.internal.IntrinsicType import kotlin.native.internal.FilterExceptions interface ObjCObject interface ObjCClass : ObjCObject interface ObjCClassOf<T : ObjCObject> : ObjCClass // TODO: T should be added to ObjCClass and all meta-classes instead. typealias ObjCObjectMeta = ObjCClass interface ObjCProtocol : ObjCObject @ExportTypeInfo("theForeignObjCObjectTypeInfo") @kotlin.native.internal.Frozen internal open class ForeignObjCObject : kotlin.native.internal.ObjCObjectWrapper abstract class ObjCObjectBase protected constructor() : ObjCObject { @Target(AnnotationTarget.CONSTRUCTOR) @Retention(AnnotationRetention.SOURCE) annotation class OverrideInit } abstract class ObjCObjectBaseMeta protected constructor() : ObjCObjectBase(), ObjCObjectMeta {} fun optional(): Nothing = throw RuntimeException("Do not call me!!!") @Deprecated( "Add @OverrideInit to constructor to make it override Objective-C initializer", level = DeprecationLevel.ERROR ) @TypedIntrinsic(IntrinsicType.OBJC_INIT_BY) external fun <T : ObjCObjectBase> T.initBy(constructorCall: T): T @kotlin.native.internal.ExportForCompiler private fun ObjCObjectBase.superInitCheck(superInitCallResult: ObjCObject?) { if (superInitCallResult == null) throw RuntimeException("Super initialization failed") if (superInitCallResult.objcPtr() != this.objcPtr()) throw UnsupportedOperationException("Super initializer has replaced object") } internal fun <T : Any?> Any?.uncheckedCast(): T = @Suppress("UNCHECKED_CAST") (this as T) // Note: if this is called for non-frozen object on a wrong worker, the program will terminate. @SymbolName("Kotlin_Interop_refFromObjC") external fun <T> interpretObjCPointerOrNull(objcPtr: NativePtr): T? @ExportForCppRuntime inline fun <T : Any> interpretObjCPointer(objcPtr: NativePtr): T = interpretObjCPointerOrNull<T>(objcPtr)!! @SymbolName("Kotlin_Interop_refToObjC") external fun Any?.objcPtr(): NativePtr @SymbolName("Kotlin_Interop_createKotlinObjectHolder") external fun createKotlinObjectHolder(any: Any?): NativePtr // Note: if this is called for non-frozen underlying ref on a wrong worker, the program will terminate. inline fun <reified T : Any> unwrapKotlinObjectHolder(holder: Any?): T { return unwrapKotlinObjectHolderImpl(holder!!.objcPtr()) as T } @PublishedApi @SymbolName("Kotlin_Interop_unwrapKotlinObjectHolder") external internal fun unwrapKotlinObjectHolderImpl(ptr: NativePtr): Any class ObjCObjectVar<T>(rawPtr: NativePtr) : CVariable(rawPtr) { @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") @Suppress("DEPRECATION") companion object : CVariable.Type(pointerSize.toLong(), pointerSize) } class ObjCNotImplementedVar<T : Any?>(rawPtr: NativePtr) : CVariable(rawPtr) { @Deprecated("Use sizeOf<T>() or alignOf<T>() instead.") @Suppress("DEPRECATION") companion object : CVariable.Type(pointerSize.toLong(), pointerSize) } var <T : Any?> ObjCNotImplementedVar<T>.value: T get() = TODO() set(_) = TODO() typealias ObjCStringVarOf<T> = ObjCNotImplementedVar<T> typealias ObjCBlockVar<T> = ObjCNotImplementedVar<T> @TypedIntrinsic(IntrinsicType.OBJC_CREATE_SUPER_STRUCT) @PublishedApi internal external fun createObjCSuperStruct(receiver: NativePtr, superClass: NativePtr): NativePtr @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.BINARY) annotation class ExternalObjCClass(val protocolGetter: String = "", val binaryName: String = "") @Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER) @Retention(AnnotationRetention.BINARY) annotation class ObjCMethod(val selector: String, val encoding: String, val isStret: Boolean = false) @Target(AnnotationTarget.CONSTRUCTOR) @Retention(AnnotationRetention.BINARY) annotation class ObjCConstructor(val initSelector: String, val designated: Boolean) @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.BINARY) annotation class ObjCFactory(val selector: String, val encoding: String, val isStret: Boolean = false) @Target(AnnotationTarget.FILE) @Retention(AnnotationRetention.BINARY) annotation class InteropStubs() @PublishedApi @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.SOURCE) internal annotation class ObjCMethodImp(val selector: String, val encoding: String) @PublishedApi @TypedIntrinsic(IntrinsicType.OBJC_GET_SELECTOR) internal external fun objCGetSelector(selector: String): COpaquePointer @kotlin.native.internal.ExportForCppRuntime("Kotlin_Interop_getObjCClass") private fun getObjCClassByName(name: NativePtr): NativePtr { val result = objc_lookUpClass(name) if (result == nativeNullPtr) { val className = interpretCPointer<ByteVar>(name)!!.toKString() val message = """Objective-C class '$className' not found. |Ensure that the containing framework or library was linked.""".trimMargin() throw RuntimeException(message) } return result } @kotlin.native.internal.ExportForCompiler private fun allocObjCObject(clazz: NativePtr): NativePtr { val rawResult = objc_allocWithZone(clazz) if (rawResult == nativeNullPtr) { throw OutOfMemoryError("Unable to allocate Objective-C object") } // Note: `objc_allocWithZone` returns retained pointer, and thus it must be balanced by the caller. return rawResult } @TypedIntrinsic(IntrinsicType.OBJC_GET_OBJC_CLASS) @kotlin.native.internal.ExportForCompiler private external fun <T : ObjCObject> getObjCClass(): NativePtr @PublishedApi @TypedIntrinsic(IntrinsicType.OBJC_GET_MESSENGER) internal external fun getMessenger(superClass: NativePtr): COpaquePointer? @PublishedApi @TypedIntrinsic(IntrinsicType.OBJC_GET_MESSENGER_STRET) internal external fun getMessengerStret(superClass: NativePtr): COpaquePointer? internal class ObjCWeakReferenceImpl : kotlin.native.ref.WeakReferenceImpl() { @SymbolName("Konan_ObjCInterop_getWeakReference") external override fun get(): Any? } @SymbolName("Konan_ObjCInterop_initWeakReference") private external fun ObjCWeakReferenceImpl.init(objcPtr: NativePtr) @kotlin.native.internal.ExportForCppRuntime internal fun makeObjCWeakReferenceImpl(objcPtr: NativePtr): ObjCWeakReferenceImpl { val result = ObjCWeakReferenceImpl() result.init(objcPtr) return result } // Konan runtme: @Deprecated("Use plain Kotlin cast of String to NSString", level = DeprecationLevel.ERROR) @SymbolName("Kotlin_Interop_CreateNSStringFromKString") external fun CreateNSStringFromKString(str: String?): NativePtr @Deprecated("Use plain Kotlin cast of NSString to String", level = DeprecationLevel.ERROR) @SymbolName("Kotlin_Interop_CreateKStringFromNSString") external fun CreateKStringFromNSString(ptr: NativePtr): String? @PublishedApi @SymbolName("Kotlin_Interop_CreateObjCObjectHolder") internal external fun createObjCObjectHolder(ptr: NativePtr): Any? // Objective-C runtime: @SymbolName("objc_retainAutoreleaseReturnValue") external fun objc_retainAutoreleaseReturnValue(ptr: NativePtr): NativePtr @SymbolName("Kotlin_objc_autoreleasePoolPush") external fun objc_autoreleasePoolPush(): NativePtr @SymbolName("Kotlin_objc_autoreleasePoolPop") external fun objc_autoreleasePoolPop(ptr: NativePtr) @SymbolName("Kotlin_objc_allocWithZone") @FilterExceptions private external fun objc_allocWithZone(clazz: NativePtr): NativePtr @SymbolName("Kotlin_objc_retain") external fun objc_retain(ptr: NativePtr): NativePtr @SymbolName("Kotlin_objc_release") external fun objc_release(ptr: NativePtr) @SymbolName("Kotlin_objc_lookUpClass") external fun objc_lookUpClass(name: NativePtr): NativePtr
apache-2.0
283cfc4ba75445f6d356eac27c461ab3
36.436123
127
0.787244
4.263924
false
false
false
false
pbreault/adb-idea
src/main/kotlin/com/developerphil/adbidea/ui/ModuleChooserDialogHelper.kt
1
2871
package com.developerphil.adbidea.ui import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ui.configuration.ChooseModulesDialog import com.intellij.ui.table.JBTable import com.intellij.util.ui.UIUtil import org.jetbrains.android.facet.AndroidFacet import java.awt.Component import java.awt.Dimension import java.awt.geom.Dimension2D import javax.swing.JTable object ModuleChooserDialogHelper { fun showDialogForFacets(project: Project, facets: List<AndroidFacet>): AndroidFacet? { val modules = facets.map { it.module } val previousModuleName = getSavedModuleName(project) val previousSelectedModule = modules.firstOrNull { it.name == previousModuleName } val selectedModule = showDialog(project, modules, previousSelectedModule) ?: return null saveModuleName(project, selectedModule.name) return facets[modules.indexOf(selectedModule)] } private fun showDialog(project: Project, modules: List<Module>, previousSelectedModule: Module?): Module? { with(ChooseModulesDialog(project, modules, "Choose Module", "")) { setSingleSelectionMode() getSizeForTableContainer(preferredFocusedComponent)?.let { setSize(it.width, it.height) } previousSelectedModule?.let { selectElements(listOf(it)) } return showAndGetResult().firstOrNull() } } // Fix an issue where the modules dialog is not wide enough to display the whole module name. // This code is lifted from com.intellij.openapi.ui.impl.DialogWrapperPeerImpl.MyDialog.getSizeForTableContainer private fun getSizeForTableContainer(component: Component?): Dimension? { if (component == null) return null val tables = UIUtil.uiTraverser(component).filter(JTable::class.java) if (!tables.isNotEmpty) return null val size = component.preferredSize for (table in tables) { val tableSize = table.preferredSize size.width = size.width.coerceAtLeast(tableSize.width) size.height = size.height.coerceAtLeast(tableSize.height + size.height - table.parent.height) } size.width = 1000.coerceAtMost(600.coerceAtLeast(size.width)) size.height = 800.coerceAtMost(size.height) return size } private fun saveModuleName(project: Project, moduleName: String) { PropertiesComponent.getInstance(project).setValue(SELECTED_MODULE_PROPERTY, moduleName) } private fun getSavedModuleName(project: Project): String? { return PropertiesComponent.getInstance(project).getValue(SELECTED_MODULE_PROPERTY) } } private val SELECTED_MODULE_PROPERTY = ModuleChooserDialogHelper::class.java.canonicalName + "-SELECTED_MODULE"
apache-2.0
655166dc529337628161a952dc4448bf
43.875
116
0.726576
4.645631
false
false
false
false
androidx/androidx
tv/tv-foundation/src/androidTest/java/androidx/tv/foundation/lazy/grid/LazyCustomKeysTest.kt
3
13095
/* * 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.tv.foundation.lazy.grid import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.assertHeightIsEqualTo import androidx.compose.ui.test.assertTopPositionInRootIsEqualTo import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) class LazyCustomKeysTest { @get:Rule val rule = createComposeRule() val itemSize = with(rule.density) { 100.toDp() } val columns = 2 @Test fun itemsWithKeysAreLaidOutCorrectly() { val list = listOf(MyClass(0), MyClass(1), MyClass(2)) rule.setContent { TvLazyVerticalGrid(TvGridCells.Fixed(columns)) { items(list, key = { it.id }) { Item("${it.id}") } } } assertItems("0", "1", "2") } @Test fun removing_statesAreMoved() { var list by mutableStateOf(listOf(MyClass(0), MyClass(1), MyClass(2))) rule.setContent { TvLazyVerticalGrid(TvGridCells.Fixed(columns)) { items(list, key = { it.id }) { Item(remember { "${it.id}" }) } } } rule.runOnIdle { list = listOf(list[0], list[2]) } assertItems("0", "2") } @Test fun reordering_statesAreMoved_list() { testReordering { grid -> items(grid, key = { it.id }) { Item(remember { "${it.id}" }) } } } @Test fun reordering_statesAreMoved_list_indexed() { testReordering { grid -> itemsIndexed(grid, key = { _, item -> item.id }) { _, item -> Item(remember { "${item.id}" }) } } } @Test fun reordering_statesAreMoved_array() { testReordering { grid -> val array = grid.toTypedArray() items(array, key = { it.id }) { Item(remember { "${it.id}" }) } } } @Test fun reordering_statesAreMoved_array_indexed() { testReordering { grid -> val array = grid.toTypedArray() itemsIndexed(array, key = { _, item -> item.id }) { _, item -> Item(remember { "${item.id}" }) } } } @Test fun reordering_statesAreMoved_itemsWithCount() { testReordering { grid -> items(grid.size, key = { grid[it].id }) { Item(remember { "${grid[it].id}" }) } } } @Test fun fullyReplacingTheList() { var list by mutableStateOf(listOf(MyClass(0), MyClass(1), MyClass(2))) var counter = 0 rule.setContent { TvLazyVerticalGrid(TvGridCells.Fixed(columns)) { items(list, key = { it.id }) { Item(remember { counter++ }.toString()) } } } rule.runOnIdle { list = listOf(MyClass(3), MyClass(4), MyClass(5), MyClass(6)) } assertItems("3", "4", "5", "6") } @Test fun keepingOneItem() { var list by mutableStateOf(listOf(MyClass(0), MyClass(1), MyClass(2))) var counter = 0 rule.setContent { TvLazyVerticalGrid(TvGridCells.Fixed(columns)) { items(list, key = { it.id }) { Item(remember { counter++ }.toString()) } } } rule.runOnIdle { list = listOf(MyClass(1)) } assertItems("1") } @Test fun keepingOneItemAndAddingMore() { var list by mutableStateOf(listOf(MyClass(0), MyClass(1), MyClass(2))) var counter = 0 rule.setContent { TvLazyVerticalGrid(TvGridCells.Fixed(columns)) { items(list, key = { it.id }) { Item(remember { counter++ }.toString()) } } } rule.runOnIdle { list = listOf(MyClass(1), MyClass(3)) } assertItems("1", "3") } @Test fun mixingKeyedItemsAndNot() { testReordering { list -> item { Item("${list.first().id}") } items(list.subList(fromIndex = 1, toIndex = list.size), key = { it.id }) { Item(remember { "${it.id}" }) } } } @Test fun updatingTheDataSetIsCorrectlyApplied() { val state = mutableStateOf(emptyList<Int>()) rule.setContent { LaunchedEffect(Unit) { state.value = listOf(4, 1, 3) } val list = state.value TvLazyVerticalGrid(TvGridCells.Fixed(columns), Modifier.fillMaxSize()) { items(list, key = { it }) { Item(it.toString()) } } } assertItems("4", "1", "3") rule.runOnIdle { state.value = listOf(2, 4, 6, 1, 3, 5) } assertItems("2", "4", "6", "1", "3", "5") } @Test fun reordering_usingMutableStateListOf() { val list = mutableStateListOf(MyClass(0), MyClass(1), MyClass(2)) rule.setContent { TvLazyVerticalGrid(TvGridCells.Fixed(columns)) { items(list, key = { it.id }) { Item(remember { "${it.id}" }) } } } rule.runOnIdle { list.add(list.removeAt(1)) } assertItems("0", "2", "1") } @Test fun keysInLazyListItemInfoAreCorrect() { val list = listOf(MyClass(0), MyClass(1), MyClass(2)) lateinit var state: TvLazyGridState rule.setContent { state = rememberTvLazyGridState() TvLazyVerticalGrid(TvGridCells.Fixed(columns), state = state) { items(list, key = { it.id }) { Item(remember { "${it.id}" }) } } } rule.runOnIdle { assertThat( state.visibleKeys ).isEqualTo(listOf(0, 1, 2)) } } @Test fun keysInLazyListItemInfoAreCorrectAfterReordering() { var list by mutableStateOf(listOf(MyClass(0), MyClass(1), MyClass(2))) lateinit var state: TvLazyGridState rule.setContent { state = rememberTvLazyGridState() TvLazyVerticalGrid(columns = TvGridCells.Fixed(columns), state = state) { items(list, key = { it.id }) { Item(remember { "${it.id}" }) } } } rule.runOnIdle { list = listOf(list[0], list[2], list[1]) } rule.runOnIdle { assertThat( state.visibleKeys ).isEqualTo(listOf(0, 2, 1)) } } @Test fun addingItemsBeforeWithoutKeysIsMaintainingTheIndex() { var list by mutableStateOf((10..15).toList()) lateinit var state: TvLazyGridState rule.setContent { state = rememberTvLazyGridState() TvLazyVerticalGrid(TvGridCells.Fixed(columns), Modifier.size(itemSize * 2.5f), state) { items(list) { Item(remember { "$it" }) } } } rule.runOnIdle { list = (0..15).toList() } rule.runOnIdle { assertThat(state.firstVisibleItemIndex).isEqualTo(0) } } @Test fun addingItemsBeforeKeepingThisItemFirst() { var list by mutableStateOf((10..15).toList()) lateinit var state: TvLazyGridState rule.setContent { state = rememberTvLazyGridState() TvLazyVerticalGrid(TvGridCells.Fixed(columns), Modifier.size(itemSize * 2.5f), state) { items(list, key = { it }) { Item(remember { "$it" }) } } } rule.runOnIdle { list = (0..15).toList() } rule.runOnIdle { assertThat(state.firstVisibleItemIndex).isEqualTo(10) assertThat( state.visibleKeys ).isEqualTo(listOf(10, 11, 12, 13, 14, 15)) } } @Test fun addingItemsRightAfterKeepingThisItemFirst() { var list by mutableStateOf((0..5).toList() + (10..15).toList()) lateinit var state: TvLazyGridState rule.setContent { state = rememberTvLazyGridState(5) TvLazyVerticalGrid(TvGridCells.Fixed(columns), Modifier.size(itemSize * 2.5f), state) { items(list, key = { it }) { Item(remember { "$it" }) } } } rule.runOnIdle { list = (0..15).toList() } rule.runOnIdle { assertThat(state.firstVisibleItemIndex).isEqualTo(4) assertThat( state.visibleKeys ).isEqualTo(listOf(4, 5, 6, 7, 8, 9)) } } @Test fun addingItemsBeforeWhileCurrentItemIsNotInTheBeginning() { var list by mutableStateOf((10..30).toList()) lateinit var state: TvLazyGridState rule.setContent { state = rememberTvLazyGridState(10) // key 20 is the first item TvLazyVerticalGrid(TvGridCells.Fixed(columns), Modifier.size(itemSize * 2.5f), state) { items(list, key = { it }) { Item(remember { "$it" }) } } } rule.runOnIdle { list = (0..30).toList() } rule.runOnIdle { assertThat(state.firstVisibleItemIndex).isEqualTo(20) assertThat( state.visibleKeys ).isEqualTo(listOf(20, 21, 22, 23, 24, 25)) } } @Test fun removingTheCurrentItemMaintainsTheIndex() { var list by mutableStateOf((0..20).toList()) lateinit var state: TvLazyGridState rule.setContent { state = rememberTvLazyGridState(8) TvLazyVerticalGrid(TvGridCells.Fixed(columns), Modifier.size(itemSize * 2.5f), state) { items(list, key = { it }) { Item(remember { "$it" }) } } } rule.runOnIdle { list = (0..20) - 8 } rule.runOnIdle { assertThat(state.firstVisibleItemIndex).isEqualTo(8) assertThat(state.visibleKeys).isEqualTo(listOf(9, 10, 11, 12, 13, 14)) } } private fun testReordering(content: TvLazyGridScope.(List<MyClass>) -> Unit) { var list by mutableStateOf(listOf(MyClass(0), MyClass(1), MyClass(2))) rule.setContent { TvLazyVerticalGrid(TvGridCells.Fixed(columns)) { content(list) } } rule.runOnIdle { list = listOf(list[0], list[2], list[1]) } assertItems("0", "2", "1") } private fun assertItems(vararg tags: String) { var currentTop = 0.dp var column = 0 tags.forEach { rule.onNodeWithTag(it) .assertTopPositionInRootIsEqualTo(currentTop) .assertHeightIsEqualTo(itemSize) ++column if (column == columns) { currentTop += itemSize column = 0 } } } @Composable private fun Item(tag: String) { Spacer( Modifier.testTag(tag).size(itemSize) ) } private class MyClass(val id: Int) } val TvLazyGridState.visibleKeys: List<Any> get() = layoutInfo.visibleItemsInfo.map { it.key }
apache-2.0
899c42c5e3ed0e9867012799f99e017c
27.100858
99
0.53593
4.470809
false
true
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/formatting/visualLayer/VisualFormattingLayerServiceImpl.kt
2
11652
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.formatting.visualLayer import com.intellij.application.options.CodeStyle import com.intellij.codeInspection.incorrectFormatting.FormattingChanges import com.intellij.codeInspection.incorrectFormatting.detectFormattingChanges import com.intellij.formatting.visualLayer.VisualFormattingLayerElement.* import com.intellij.openapi.components.Service import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.impl.LineSet import com.intellij.psi.PsiDocumentManager import kotlin.math.min @Service class VisualFormattingLayerServiceImpl : VisualFormattingLayerService() { override fun applyVisualFormattingLayerElementsToEditor(editor: Editor, elements: List<VisualFormattingLayerElement>) { editor.inlayModel.execute(false) { editor.inlayModel .getInlineElementsInRange(0, Int.MAX_VALUE, InlayPresentation::class.java) .forEach { it.dispose() } editor.inlayModel .getBlockElementsInRange(0, Int.MAX_VALUE, InlayPresentation::class.java) .forEach { it.dispose() } elements.asSequence() .filterIsInstance<InlineInlay>() .forEach { it.applyToEditor(editor) } elements.asSequence() .filterIsInstance<BlockInlay>() .forEach { it.applyToEditor(editor) } } editor.foldingModel.runBatchFoldingOperation( { editor.foldingModel .allFoldRegions .filter { it.getUserData(visualFormattingElementKey) == true } .forEach { it.dispose() } elements.asSequence() .filterIsInstance<Folding>() .forEach { it.applyToEditor(editor) } }, true, false) } override fun collectVisualFormattingLayerElements(editor: Editor): List<VisualFormattingLayerElement> { val project = editor.project ?: return emptyList() val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return emptyList() val codeStyleSettings = editor.visualFormattingLayerCodeStyleSettings ?: return emptyList() var formattingChanges: FormattingChanges? = null CodeStyle.doWithTemporarySettings(file.project, codeStyleSettings, Runnable { if (file.isValid) { formattingChanges = detectFormattingChanges(file) } }) if (formattingChanges == null) { return emptyList() } val tabSize = codeStyleSettings.getTabSize(file.fileType) return formattingChanges!!.mismatches .flatMap { mismatch -> formattingElements(editor.document, formattingChanges!!.postFormatText, mismatch, tabSize) } .filterNotNull() .toList() } private fun formattingElements(document: Document, formattedText: CharSequence, mismatch: FormattingChanges.WhitespaceMismatch, tabSize: Int): Sequence<VisualFormattingLayerElement?> = sequence { val originalText = document.text val replacementLines = LineSet.createLineSet(formattedText) val originalFirstLine = document.getLineNumber(mismatch.preFormatRange.startOffset) val replacementFirstLine = replacementLines.findLineIndex(mismatch.postFormatRange.startOffset) val n = document.getLineNumber(mismatch.preFormatRange.endOffset) - originalFirstLine + 1 val m = mismatch.postFormatRange.let { replacementLines.findLineIndex(it.endOffset) - replacementLines.findLineIndex(it.startOffset) } + 1 // This case needs soft wraps to visually split the existing line. // Not supported by API yet, so we will just skip it for now. if (1 == n && n < m) { return@sequence } // Fold first (N - M + 1) lines into one line of the replacement... if (n > m) { val originalStartOffset = mismatch.preFormatRange.startOffset val originalEndOffset = min(document.getLineEndOffset(originalFirstLine + n - m), mismatch.preFormatRange.endOffset) val originalLineStartOffset = document.getLineStartOffset(originalFirstLine) val replacementStartOffset = mismatch.postFormatRange.startOffset val replacementEndOffset = min(replacementLines.getLineEnd(replacementFirstLine), mismatch.postFormatRange.endOffset) val replacementLineStartOffset = replacementLines.getLineStart(replacementFirstLine) yieldAll(inlayOrFold(originalText, originalLineStartOffset, originalStartOffset, originalEndOffset, formattedText, replacementLineStartOffset, replacementStartOffset, replacementEndOffset, tabSize)) } // ...or skip the first line by folding and add block inlay for (M - N) lines if (n <= m) { val originalStartOffset = mismatch.preFormatRange.startOffset // This breaks down when (1 = N < M), but we've filtered out this case in the beginning val originalEndOffset = min(document.getLineEndOffset(originalFirstLine), mismatch.preFormatRange.endOffset) val originalLineStartOffset = document.getLineStartOffset(originalFirstLine) val replacementStartOffset = mismatch.postFormatRange.startOffset val replacementEndOffset = min(replacementLines.getLineEnd(replacementFirstLine), mismatch.postFormatRange.endOffset) val replacementLineStartOffset = replacementLines.getLineStart(replacementFirstLine) yieldAll(inlayOrFold(originalText, originalLineStartOffset, originalStartOffset, originalEndOffset, formattedText, replacementLineStartOffset, replacementStartOffset, replacementEndOffset, tabSize)) // add block inlay for M - N lines after firstLine, might be empty. yield(blockInlay(document.getLineStartOffset(originalFirstLine + 1), m - n)) } /* Now we have processed some lines. Both original whitespace and replacement have similar number lines left to process. This number depends on (N < M) but is always equal to MIN(N, M) - 1. See diagram for clarifying: N > M N <= M ┌─────┐ ─────┐ Fold/Inlay ┌─────┐ │ 1 │ │ ┌────────► │ 1 │ ├─────┤ │ │ ┌─────── ├─────┤ │ │ Fold │ │ │ │ │ │N - M│ │ ┌─────┐ ┌─────┐ │ │ Block │M - N│ │ │ ├─► │ 1 │ │ 1 │ ─┘ │ Inlay │ │ ├─────┤ ─────┘ ├─────┤ ├─────┤ ◄──┴─────── ├─────┤ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │Fold/Inlay│ │ │ │ Fold/Inlay │ │ │M - 1│ line by │M - 1│ │N - 1│ line by │N - 1│ │ │ line │ │ │ │ line │ │ │ │ ───────► │ │ │ │ ──────────► │ │ │ │ │ │ │ │ │ │ └─────┘ └─────┘ └─────┘ └─────┘ */ // Fold the rest lines one by one val linesToProcess = min(n, m) - 1 for (i in 1..linesToProcess) { val originalLine = originalFirstLine + n - linesToProcess + i - 1 // goes up until last line inclusively val replacementLine = replacementFirstLine + m - linesToProcess + i - 1 // goes up until last replacement line inclusively val originalLineStartOffset = document.getLineStartOffset(originalLine) val originalEndOffset = min(document.getLineEndOffset(originalLine), mismatch.preFormatRange.endOffset) val replacementLineStartOffset = replacementLines.getLineStart(replacementLine) val replacementEndOffset = min(replacementLines.getLineEnd(replacementLine), mismatch.postFormatRange.endOffset) yieldAll(inlayOrFold(originalText, originalLineStartOffset, originalLineStartOffset, originalEndOffset, formattedText, replacementLineStartOffset, replacementLineStartOffset, replacementEndOffset, tabSize)) } } // Visually replaces whitespace (or its absence) with a proper one private fun inlayOrFold(original: CharSequence, originalLineStartOffset: Int, originalStartOffset: Int, originalEndOffset: Int, formatted: CharSequence, replacementLineStartOffset: Int, replacementStartOffset: Int, replacementEndOffset: Int, tabSize: Int) = sequence { val (originalColumns, originalContainsTabs) = countColumnsWithinLine(original, originalLineStartOffset, originalStartOffset, originalEndOffset, tabSize) val (replacementColumns, _) = countColumnsWithinLine(formatted, replacementLineStartOffset, replacementStartOffset, replacementEndOffset, tabSize) val columnsDelta = replacementColumns - originalColumns when { columnsDelta > 0 -> yield(InlineInlay(originalEndOffset, columnsDelta)) columnsDelta < 0 -> { val originalLength = originalEndOffset - originalStartOffset if (originalContainsTabs) { yield(Folding(originalStartOffset, originalLength)) if (replacementColumns > 0) { yield(InlineInlay(originalEndOffset, replacementColumns)) } } else { yield(Folding(originalStartOffset, -columnsDelta)) } } } } private fun blockInlay(offset: Int, lines: Int): VisualFormattingLayerElement? { if (lines == 0) return null return BlockInlay(offset, lines) } } private fun countColumnsWithinLine(sequence: CharSequence, lineStartOffset: Int, fromOffset: Int, untilOffset: Int, tabSize: Int): Pair<Int, Boolean> { val (startColumn, _) = countColumns(sequence, lineStartOffset, fromOffset, 0, tabSize) return countColumns(sequence, fromOffset, untilOffset, startColumn, tabSize) } private fun countColumns(sequence: CharSequence, fromOffset: Int, untilOffset: Int, startColumn: Int, tabSize: Int): Pair<Int, Boolean> { var cols = 0 var tabStopOffset = startColumn % tabSize var containsTabs = false for (offset in fromOffset until untilOffset) { when (sequence[offset]) { '\t' -> { cols += tabSize - tabStopOffset tabStopOffset = 0 containsTabs = true } '\n' -> { break } else -> { cols += 1 tabStopOffset = (tabStopOffset + 1) % tabSize } } } return Pair(cols, containsTabs) }
apache-2.0
44790e725652ed2c594908b6dd5ba9dd
46.063291
142
0.619957
4.946341
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ConvertCollectionLiteralToIntArrayOfFix.kt
2
1985
// 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.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.util.asSafely import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticWithParameters1 import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.psi.KtCollectionLiteralExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern /** * Tests: * [org.jetbrains.kotlin.idea.quickfix.QuickFixTestGenerated.ConvertCollectionLiteralToIntArrayOf] */ class ConvertCollectionLiteralToIntArrayOfFix(element: KtCollectionLiteralExpression) : KotlinQuickFixAction<KtCollectionLiteralExpression>(element) { override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return element.text.takeIf { it.first() == '[' && it.last() == ']' }?.drop(1)?.dropLast(1)?.let { content -> element.replace(KtPsiFactory(project).createExpressionByPattern("intArrayOf($0)", content)) } } override fun getText(): String = KotlinBundle.message("replace.with.arrayof") override fun getFamilyName(): String = text companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? = diagnostic .takeIf { "Collection literals outside of annotations" == (it as? DiagnosticWithParameters1<*, *>)?.a } ?.psiElement ?.let { it as? KtCollectionLiteralExpression } ?.let(::ConvertCollectionLiteralToIntArrayOfFix) } }
apache-2.0
9db490d1f6c2e517a2d200e78f5f5dea
47.414634
120
0.760705
4.771635
false
false
false
false
GunoH/intellij-community
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/attach/dialog/items/list/AttachListCells.kt
2
3256
package com.intellij.xdebugger.impl.ui.attach.dialog.items.list import com.intellij.ui.SimpleColoredComponent import com.intellij.ui.SimpleTextAttributes import com.intellij.util.ui.JBUI import com.intellij.xdebugger.XDebuggerBundle import com.intellij.xdebugger.impl.ui.attach.dialog.extensions.XAttachDialogUiInvisiblePresentationGroup import com.intellij.xdebugger.impl.ui.attach.dialog.extensions.XAttachTreeDebuggersPresentationProvider import com.intellij.xdebugger.impl.ui.attach.dialog.items.AttachColumnSettingsState import com.intellij.xdebugger.impl.ui.attach.dialog.items.AttachNodeContainer import com.intellij.xdebugger.impl.ui.attach.dialog.items.AttachTableCell internal class ExecutableListCell(state: AttachColumnSettingsState, val node: AttachToProcessListItem) : AttachTableCell(state, 0, XDebuggerBundle.message( "xdebugger.attach.executable.column.name")), AttachNodeContainer<AttachToProcessListItem> { override fun getTextToDisplay(): String = node.item.executableText override fun getTextStartOffset(component: SimpleColoredComponent): Int = (getIcon()?.iconWidth ?: JBUI.scale(16)) + JBUI.scale(8) override fun getAttachNode(): AttachToProcessListItem = node override fun getTextAttributes(): SimpleTextAttributes = node.item.executableTextAttributes ?: super.getTextAttributes() } class PidListCell(private val pid: Int, state: AttachColumnSettingsState) : AttachTableCell(state, 1, XDebuggerBundle.message( "xdebugger.attach.pid.column.name")) { override fun getTextToDisplay(): String { return pid.toString() } } internal class DebuggersListCell(private val node: AttachToProcessListItem, state: AttachColumnSettingsState) : AttachTableCell(state, 2, XDebuggerBundle.message( "xdebugger.attach.debuggers.column.name")) { override fun getTextToDisplay(): String = node.item.getGroups().filter { it !is XAttachDialogUiInvisiblePresentationGroup }.sortedBy { it.order }.joinToString(", ") { (it as? XAttachTreeDebuggersPresentationProvider)?.getDebuggersShortName() ?: it.groupName } } internal class CommandLineListCell(private val node: AttachToProcessListItem, state: AttachColumnSettingsState) : AttachTableCell(state, 3, XDebuggerBundle.message( "xdebugger.attach.command.line.column.name")) { override fun getTextToDisplay(): String = node.item.commandLineText override fun getTextAttributes(): SimpleTextAttributes = node.item.commandLineTextAttributes ?: super.getTextAttributes() }
apache-2.0
2f88c02d88482648891dcd2b75283e17
62.843137
218
0.61855
5.845601
false
false
false
false
GunoH/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/findUsages/KotlinFindUsagesSupportFirImpl.kt
1
8820
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.findUsages import com.intellij.ide.IdeBundle import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.PsiReference import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.Processor import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.analyzeInModalWindow import org.jetbrains.kotlin.analysis.api.calls.* import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtClassifierSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtConstructorSymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtNamedSymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithKind import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.core.util.showYesNoCancelDialog import org.jetbrains.kotlin.idea.refactoring.CHECK_SUPER_METHODS_YES_NO_DIALOG import org.jetbrains.kotlin.idea.refactoring.formatPsiClass import org.jetbrains.kotlin.idea.references.KtInvokeFunctionReference import org.jetbrains.kotlin.idea.util.withResolvedCall import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.SpecialNames import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType class KotlinFindUsagesSupportFirImpl : KotlinFindUsagesSupport { override fun processCompanionObjectInternalReferences( companionObject: KtObjectDeclaration, referenceProcessor: Processor<PsiReference> ): Boolean { val klass = companionObject.getStrictParentOfType<KtClass>() ?: return true return !klass.anyDescendantOfType(fun(element: KtElement): Boolean { if (element == companionObject) return false return withResolvedCall(element) { call -> if (callReceiverRefersToCompanionObject(call, companionObject)) { element.references.any { // We get both a simple named reference and an invoke function // reference for all function calls. We want the named reference. // // TODO: with FE1.0 the check for reference type is not needed. // With FE1.0 two references that point to the same PSI are // obtained and one is filtered out by the reference processor. // We should make FIR references behave the same. it !is KtInvokeFunctionReference && !referenceProcessor.process(it) } } else { false } } ?: false }) } private fun KtAnalysisSession.callReceiverRefersToCompanionObject(call: KtCall, companionObject: KtObjectDeclaration): Boolean { if (call !is KtCallableMemberCall<*, *>) return false val dispatchReceiver = call.partiallyAppliedSymbol.dispatchReceiver val extensionReceiver = call.partiallyAppliedSymbol.extensionReceiver val companionObjectSymbol = companionObject.getSymbol() return (dispatchReceiver as? KtImplicitReceiverValue)?.symbol == companionObjectSymbol || (extensionReceiver as? KtImplicitReceiverValue)?.symbol == companionObjectSymbol } override fun isDataClassComponentFunction(element: KtParameter): Boolean { // TODO: implement this return false } override fun getTopMostOverriddenElementsToHighlight(target: PsiElement): List<PsiElement> { // TODO: implement this return emptyList() } override fun tryRenderDeclarationCompactStyle(declaration: KtDeclaration): String { // TODO: implement this return (declaration as? KtNamedDeclaration)?.name ?: "SUPPORT FOR FIR" } override fun isKotlinConstructorUsage(psiReference: PsiReference, ktClassOrObject: KtClassOrObject): Boolean { val element = psiReference.element if (element !is KtElement) return false fun adaptSuperCall(psi: KtElement): KtElement? { if (psi !is KtNameReferenceExpression) return null val userType = psi.parent as? KtUserType ?: return null val typeReference = userType.parent as? KtTypeReference ?: return null return typeReference.parent as? KtConstructorCalleeExpression } val psiToResolve = adaptSuperCall(element) ?: element return withResolvedCall(psiToResolve) { call -> when (call) { is KtFunctionCall<*> -> { val constructorSymbol = call.symbol as? KtConstructorSymbol ?: return@withResolvedCall false val constructedClassSymbol = constructorSymbol.getContainingSymbol() as? KtClassifierSymbol ?: return@withResolvedCall false constructedClassSymbol == ktClassOrObject.getClassOrObjectSymbol() } else -> false } } ?: false } override fun getSuperMethods(declaration: KtDeclaration, ignore: Collection<PsiElement>?): List<PsiElement> { // TODO: implement this return emptyList() } override fun checkSuperMethods(declaration: KtDeclaration, ignore: Collection<PsiElement>?, @Nls actionString: String): List<PsiElement> { if (!declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return listOf(declaration) data class AnalyzedModel( val declaredClassRender: String, val overriddenDeclarationsAndRenders: Map<PsiElement, String> ) fun getClassDescription(overriddenElement: PsiElement, containingSymbol: KtSymbolWithKind?): String = when (overriddenElement) { is KtNamedFunction, is KtProperty, is KtParameter -> (containingSymbol as? KtNamedSymbol)?.name?.asString() ?: "Unknown" //TODO render symbols is PsiMethod -> { val psiClass = overriddenElement.containingClass ?: error("Invalid element: ${overriddenElement.text}") formatPsiClass(psiClass, markAsJava = true, inCode = false) } else -> error("Unexpected element: ${overriddenElement.getElementTextWithContext()}") }.let { " $it\n" } val analyzeResult = analyzeInModalWindow(declaration, KotlinBundle.message("find.usages.progress.text.declaration.superMethods")) { (declaration.getSymbol() as? KtCallableSymbol)?.let { callableSymbol -> callableSymbol.originalContainingClassForOverride?.let { containingClass -> val overriddenSymbols = callableSymbol.getAllOverriddenSymbols() val renderToPsi = overriddenSymbols.mapNotNull { it.psi?.let { psi -> psi to getClassDescription(psi, it.originalContainingClassForOverride) } } val filteredDeclarations = if (ignore != null) renderToPsi.filter { !ignore.contains(it.first) } else renderToPsi val renderedClass = containingClass.name?.asString() ?: SpecialNames.ANONYMOUS_STRING //TODO render class AnalyzedModel(renderedClass, filteredDeclarations.toMap()) } } } ?: return listOf(declaration) if (analyzeResult.overriddenDeclarationsAndRenders.isEmpty()) return listOf(declaration) val message = KotlinBundle.message( "override.declaration.x.overrides.y.in.class.list", analyzeResult.declaredClassRender, "\n${analyzeResult.overriddenDeclarationsAndRenders.values.joinToString(separator = "")}", actionString ) val exitCode = showYesNoCancelDialog( CHECK_SUPER_METHODS_YES_NO_DIALOG, declaration.project, message, IdeBundle.message("title.warning"), Messages.getQuestionIcon(), Messages.YES ) return when (exitCode) { Messages.YES -> analyzeResult.overriddenDeclarationsAndRenders.keys.toList() Messages.NO -> listOf(declaration) else -> emptyList() } } override fun sourcesAndLibraries(delegate: GlobalSearchScope, project: Project): GlobalSearchScope { return delegate } }
apache-2.0
620fecd7e2bb8bf389adc616f3ff4b9a
47.461538
159
0.679252
5.404412
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/refactoring/inline/AbstractInlineTest.kt
1
4375
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.refactoring.inline import com.intellij.codeInsight.TargetElementUtil import com.intellij.codeInsight.TargetElementUtil.ELEMENT_NAME_ACCEPTED import com.intellij.codeInsight.TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED import com.intellij.lang.refactoring.InlineActionHandler import com.intellij.openapi.util.io.FileUtil import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.util.CommonRefactoringUtil import com.intellij.testFramework.LightProjectDescriptor import junit.framework.TestCase import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings import org.jetbrains.kotlin.idea.test.* import com.intellij.openapi.application.runWriteAction import java.io.File abstract class AbstractInlineTest : KotlinLightCodeInsightFixtureTestCase() { protected fun doTest(unused: String) { val testDataFile = dataFile() val afterFile = dataFile("${fileName()}.after") val mainFileName = testDataFile.name val mainFileBaseName = FileUtil.getNameWithoutExtension(mainFileName) val extraFiles = testDataFile.parentFile.listFiles { _, name -> name != mainFileName && name.startsWith("$mainFileBaseName.") && (name.endsWith(".kt") || name.endsWith(".java")) } ?: emptyArray() val allFiles = (extraFiles + testDataFile).associateBy { myFixture.configureByFile(it.name) } val fileWithCaret = allFiles.values.singleOrNull { "<caret>" in it.readText() } ?: error("Must have one <caret>") val file = myFixture.configureByFile(fileWithCaret.name) withCustomCompilerOptions(file.text, project, module) { val afterFileExists = afterFile.exists() val targetElement = TargetElementUtil.findTargetElement( myFixture.editor, ELEMENT_NAME_ACCEPTED or REFERENCED_ELEMENT_ACCEPTED ) val handler = if (targetElement != null) InlineActionHandler.EP_NAME.extensions.firstOrNull { it.canInlineElement(targetElement) } else null val expectedErrors = InTextDirectivesUtils.findLinesWithPrefixesRemoved(myFixture.file.text, "// ERROR: ") val inlinePropertyKeepValue = InTextDirectivesUtils.getPrefixedBoolean(myFixture.file.text, "// INLINE_PROPERTY_KEEP: ") val settings = KotlinRefactoringSettings.instance val oldInlinePropertyKeepValue = settings.INLINE_PROPERTY_KEEP if (handler != null) { try { inlinePropertyKeepValue?.let { settings.INLINE_PROPERTY_KEEP = it } runWriteAction { handler.inlineElement(project, editor, targetElement) } for ((extraPsiFile, extraFile) in allFiles) { KotlinTestUtils.assertEqualsToFile(File("${extraFile.path}.after"), extraPsiFile.text) } } catch (e: CommonRefactoringUtil.RefactoringErrorHintException) { TestCase.assertFalse("Refactoring not available: ${e.message}", afterFileExists) TestCase.assertEquals("Expected errors", 1, expectedErrors.size) TestCase.assertEquals("Error message", expectedErrors[0].replace("\\n", "\n"), e.message) } catch (e: BaseRefactoringProcessor.ConflictsInTestsException) { TestCase.assertFalse("Conflicts: ${e.message}", afterFileExists) TestCase.assertEquals("Expected errors", 1, expectedErrors.size) TestCase.assertEquals("Error message", expectedErrors[0].replace("\\n", "\n"), e.message) } finally { settings.INLINE_PROPERTY_KEEP = oldInlinePropertyKeepValue } } else { TestCase.assertFalse("No refactoring handler available", afterFileExists) } } } override fun getProjectDescriptor(): LightProjectDescriptor = KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstance() } abstract class AbstractInlineTestWithSomeDescriptors : AbstractInlineTest() { override fun getProjectDescriptor(): LightProjectDescriptor = getProjectDescriptorFromFileDirective() }
apache-2.0
ed7bcc30d84be8cb8feb87082f920ea9
54.379747
132
0.689371
5.510076
false
true
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiserStartupActivity.kt
1
4223
// 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.updateSettings.impl.pluginsAdvertisement import com.intellij.ide.IdeBundle import com.intellij.ide.plugins.DEPENDENCY_SUPPORT_FEATURE import com.intellij.ide.plugins.advertiser.PluginData import com.intellij.ide.plugins.advertiser.PluginFeatureCacheService import com.intellij.ide.plugins.advertiser.PluginFeatureMap import com.intellij.ide.plugins.marketplace.MarketplaceRequests import com.intellij.notification.NotificationType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.fileTypes.FileTypeFactory import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.ui.EditorNotifications import com.intellij.util.concurrency.annotations.RequiresBackgroundThread internal class PluginsAdvertiserStartupActivity : StartupActivity.Background { @RequiresBackgroundThread fun checkSuggestedPlugins(project: Project, includeIgnored: Boolean) { val application = ApplicationManager.getApplication() if (application.isUnitTestMode || application.isHeadlessEnvironment) { return } val customPlugins = loadPluginsFromCustomRepositories() if (project.isDisposed) { return } val extensionsService = PluginFeatureCacheService.getInstance() val extensions = extensionsService.extensions val unknownFeatures = UnknownFeaturesCollector.getInstance(project).unknownFeatures.toMutableList() unknownFeatures.addAll(PluginAdvertiserService.getInstance().collectDependencyUnknownFeatures(project, includeIgnored)) if (extensions != null && unknownFeatures.isEmpty()) { if (includeIgnored) { ProgressManager.checkCanceled() ApplicationManager.getApplication().invokeLater(Runnable { notificationGroup.createNotification(IdeBundle.message("plugins.advertiser.no.suggested.plugins"), NotificationType.INFORMATION) .setDisplayId("advertiser.no.plugins") .notify(project) }, ModalityState.NON_MODAL, project.disposed) } return } try { if (extensions == null || extensions.outdated) { @Suppress("DEPRECATION") val extensionsMap = getFeatureMapFromMarketPlace(customPlugins.map { it.pluginId.idString }.toSet(), FileTypeFactory.FILE_TYPE_FACTORY_EP.name) extensionsService.extensions?.update(extensionsMap) ?: run { extensionsService.extensions = PluginFeatureMap(extensionsMap) } if (project.isDisposed) { return } EditorNotifications.getInstance(project).updateAllNotifications() } if (extensionsService.dependencies == null || extensionsService.dependencies!!.outdated) { val dependencyMap = getFeatureMapFromMarketPlace(customPlugins.map { it.pluginId.idString }.toSet(), DEPENDENCY_SUPPORT_FEATURE) extensionsService.dependencies?.update(dependencyMap) ?: run { extensionsService.dependencies = PluginFeatureMap(dependencyMap) } } ProgressManager.checkCanceled() PluginAdvertiserService.getInstance().run( project, customPlugins, unknownFeatures, includeIgnored ) } catch (e: Exception) { if (e !is ControlFlowException) { LOG.info(e) } } } @RequiresBackgroundThread override fun runActivity(project: Project) { checkSuggestedPlugins(project, false) } } private fun getFeatureMapFromMarketPlace(customPluginIds: Set<String>, featureType: String): Map<String, MutableSet<PluginData>> { val params = mapOf("featureType" to featureType) return MarketplaceRequests.getInstance() .getFeatures(params) .groupBy( { it.implementationName!! }, { feature -> feature.toPluginData { customPluginIds.contains(it) } } ).mapValues { it.value.filterNotNull().toHashSet() } }
apache-2.0
bb4dd2ce1253fc335aa3ad7814e67b91
40.401961
138
0.739522
5.112591
false
false
false
false
chris-wu2015/KotlinExtension
src/main/java/com/alphago/extension/dialogCompat.kt
1
5127
package com.alphago.extension import android.app.Activity import android.content.DialogInterface import android.database.Cursor import android.graphics.drawable.Drawable import android.support.v4.app.Fragment import android.support.v7.app.AlertDialog import android.view.KeyEvent import android.view.View import android.widget.ListAdapter /** * @author Chris * @Desc AlertDialogCompat * @Date 2017/1/10 010 */ open class DialogCompatBuilder(val ctx: Activity) { val builder: AlertDialog.Builder = AlertDialog.Builder(ctx) protected var dialog: AlertDialog? = null fun dismiss() { dialog?.dismiss() } fun show(): AlertDialog { val alertDialog = builder.create() alertDialog.show() dialog = alertDialog return alertDialog } fun title(title: CharSequence): DialogCompatBuilder { builder.setTitle(title) return this } fun title(resource: Int): DialogCompatBuilder { builder.setTitle(resource) return this } fun message(title: CharSequence): DialogCompatBuilder { builder.setMessage(title) return this } fun message(resource: Int): DialogCompatBuilder { builder.setMessage(resource) return this } fun icon(icon: Int): DialogCompatBuilder { builder.setIcon(icon) return this } fun icon(icon: Drawable): DialogCompatBuilder { builder.setIcon(icon) return this } fun customTitle(title: View): DialogCompatBuilder { builder.setCustomTitle(title) return this } fun customView(view: View, initEvent: (View.(dialog: DialogInterface) -> Unit)? = null) : DialogCompatBuilder { builder.setView(view) initEvent?.invoke(view, dialog!!) return this } fun cancellable(value: Boolean = true): DialogCompatBuilder { builder.setCancelable(value) return this } fun onCancel(f: () -> Unit): DialogCompatBuilder { builder.setOnCancelListener { f() } return this } fun onKey(f: (keyCode: Int, e: KeyEvent) -> Boolean): DialogCompatBuilder { builder.setOnKeyListener({ dialog, keyCode, event -> f(keyCode, event) }) return this } fun neutralButton(textResource: Int = android.R.string.ok, f: DialogInterface.() -> Unit = { dismiss() }): DialogCompatBuilder { neutralButton(ctx.getString(textResource), f) return this } fun neutralButton(title: String, f: DialogInterface.() -> Unit = { dismiss() }) : DialogCompatBuilder { builder.setNeutralButton(title, { dialog, which -> dialog.f() }) return this } fun positiveButton(textResource: Int = android.R.string.ok, f: DialogInterface.() -> Unit) : DialogCompatBuilder { positiveButton(ctx.getString(textResource), f) return this } fun positiveButton(title: String, f: DialogInterface.() -> Unit): DialogCompatBuilder { builder.setPositiveButton(title, { dialog, which -> dialog.f() }) return this } fun negativeButton(textResource: Int = android.R.string.cancel, f: DialogInterface.() -> Unit = { dismiss() }): DialogCompatBuilder { negativeButton(ctx.getString(textResource), f) return this } fun negativeButton(title: String, f: DialogInterface.() -> Unit = { dismiss() }) : DialogCompatBuilder { builder.setNegativeButton(title, { dialog, which -> dialog.f() }) return this } fun items(itemsId: Int, f: (which: Int) -> Unit): DialogCompatBuilder { items(ctx.resources!!.getTextArray(itemsId), f) return this } fun items(items: List<CharSequence>, f: (which: Int) -> Unit): DialogCompatBuilder { items(items.toTypedArray(), f) return this } fun items(items: Array<CharSequence>, f: (which: Int) -> Unit): DialogCompatBuilder { builder.setItems(items, { dialog, which -> f(which) }) return this } fun adapter(adapter: ListAdapter, f: (which: Int) -> Unit): DialogCompatBuilder { builder.setAdapter(adapter, { dialog, which -> f(which) }) return this } fun adapter(cursor: Cursor, labelColumn: String, f: (which: Int) -> Unit) : DialogCompatBuilder { builder.setCursor(cursor, { dialog, which -> f(which) }, labelColumn) return this } } fun Fragment.dialog(): DialogCompatBuilder = activity.dialog() fun Fragment.dialog(init: DialogCompatBuilder.() -> DialogCompatBuilder): DialogCompatBuilder { return activity.dialog(init) } fun android.app.Fragment.dialog() = activity.dialog() fun android.app.Fragment.dialog(init: DialogCompatBuilder.() -> DialogCompatBuilder): DialogCompatBuilder { return activity.dialog(init) } fun Activity.dialog(): DialogCompatBuilder = DialogCompatBuilder(this) fun Activity.dialog(init: DialogCompatBuilder.() -> DialogCompatBuilder): DialogCompatBuilder { return DialogCompatBuilder(this).init() }
apache-2.0
a7c5e06838c2ce13a29abb7bf874f064
28.80814
94
0.647162
4.56545
false
false
false
false
flicus/vertx-telegram-bot-api
kotlin/src/main/kotlin/kt/schors/vertx/telegram/bot/api/types/Chat.kt
1
699
package kt.schors.vertx.telegram.bot.api.types import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty data class Chat @JsonCreator constructor( @JsonProperty("id") var id: Int? = null, @JsonProperty("type") var type: String? = null, @JsonProperty("title") var title: String? = null, @JsonProperty("username") var username: String? = null, @JsonProperty("first_name") var firstName: String? = null, @JsonProperty("last_name") var lastName: String? = null, @JsonProperty("all_members_are_administrators") var allAdmins: Boolean? = null )
mit
8320b1076e7811846f06c608262d3bfa
30.818182
55
0.640916
4.185629
false
false
false
false
agrawalsuneet/FourFoldLoader
fourfoldloader/src/main/java/com/agrawalsuneet/fourfoldloader/basicviews/FourSquaresBaseLayout.kt
1
5363
package com.agrawalsuneet.fourfoldloader.basicviews import android.content.Context import android.util.AttributeSet import android.view.Gravity import android.view.ViewTreeObserver import android.view.animation.AccelerateInterpolator import android.view.animation.Interpolator import android.widget.LinearLayout import com.agrawalsuneet.fourfoldloader.R /** * Created by suneet on 10/20/17. */ abstract class FourSquaresBaseLayout : LinearLayout, LoaderContract { var squareLenght = 100 var firstSquareColor = resources.getColor(R.color.red) var secondSquareColor = resources.getColor(R.color.green) var thirdSquareColor = resources.getColor(R.color.blue) var forthSquareColor = resources.getColor(R.color.grey) var startLoadingDefault = false var animationDuration = 500 var interpolator: Interpolator = AccelerateInterpolator() //private variables var isLoading: Boolean = false protected set protected var firstSquare: SquareView? = null protected lateinit var secondSquare: SquareView protected lateinit var thirdSquare: SquareView protected lateinit var forthSquare: SquareView protected lateinit var topLinearLayout: LinearLayout protected lateinit var bottomLinearLayout: LinearLayout constructor(context: Context) : super(context) {} constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { initAttributes(attrs!!) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { initAttributes(attrs!!) } constructor(context: Context, squareLenght: Int, firstSquareColor: Int, secondSquareColor: Int, thirdSquareColor: Int, forthSquareColor: Int, startLoadingDefault: Boolean) : super(context) { this.squareLenght = squareLenght this.firstSquareColor = firstSquareColor this.secondSquareColor = secondSquareColor this.thirdSquareColor = thirdSquareColor this.forthSquareColor = forthSquareColor this.startLoadingDefault = startLoadingDefault initView() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) setMeasuredDimension(2 * squareLenght, 2 * squareLenght) } override fun initAttributes(attrs: AttributeSet) { val typedArray = context.obtainStyledAttributes(attrs, R.styleable.FourFoldLoader, 0, 0) squareLenght = typedArray.getDimensionPixelSize(R.styleable.FourFoldLoader_fourfold_squareLength, 100) firstSquareColor = typedArray.getColor(R.styleable.FourFoldLoader_fourfold_firstSquareColor, resources.getColor(R.color.red)) secondSquareColor = typedArray.getColor(R.styleable.FourFoldLoader_fourfold_secondSquareColor, resources.getColor(R.color.green)) thirdSquareColor = typedArray.getColor(R.styleable.FourFoldLoader_fourfold_thirdSquareColor, resources.getColor(R.color.blue)) forthSquareColor = typedArray.getColor(R.styleable.FourFoldLoader_fourfold_forthSquareColor, resources.getColor(R.color.grey)) animationDuration = typedArray.getInteger(R.styleable.FourFoldLoader_fourfold_animDuration, 500) startLoadingDefault = typedArray.getBoolean(R.styleable.FourFoldLoader_fourfold_startLoadingDefault, false) typedArray.recycle() } open protected fun initView() { if (isLoading) { return } removeAllViews() removeAllViewsInLayout() isLoading = false this.orientation = LinearLayout.VERTICAL firstSquare = SquareView(context, firstSquareColor, squareLenght) secondSquare = SquareView(context, secondSquareColor, squareLenght) thirdSquare = SquareView(context, thirdSquareColor, squareLenght) forthSquare = SquareView(context, forthSquareColor, squareLenght) topLinearLayout = LinearLayout(context) topLinearLayout.gravity = Gravity.END topLinearLayout.orientation = LinearLayout.HORIZONTAL topLinearLayout.addView(firstSquare) topLinearLayout.addView(secondSquare) bottomLinearLayout = LinearLayout(context) bottomLinearLayout.gravity = Gravity.END bottomLinearLayout.orientation = LinearLayout.HORIZONTAL bottomLinearLayout.addView(forthSquare) bottomLinearLayout.addView(thirdSquare) val llParams = LinearLayout.LayoutParams(2 * squareLenght, squareLenght) llParams.gravity = Gravity.END addView(topLinearLayout, llParams) addView(bottomLinearLayout, llParams) requestLayout() if (startLoadingDefault) { val viewTreeObserver = this.viewTreeObserver val loaderView = this viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { startLoading() val vto = loaderView.viewTreeObserver vto.removeOnGlobalLayoutListener(this) } }) startLoadingDefault = false } } abstract fun startLoading() abstract fun stopLoading() }
apache-2.0
669464e2e1ba89ab287132678d2ab250
33.831169
115
0.712847
5.064212
false
false
false
false
FirebaseExtended/make-it-so-android
app/src/main/java/com/example/makeitso/theme/Theme.kt
1
1359
/* Copyright 2022 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.example.makeitso.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors(primary = BrightOrange, primaryVariant = MediumOrange, secondary = DarkOrange) private val LightColorPalette = lightColors(primary = BrightOrange, primaryVariant = MediumOrange, secondary = DarkOrange) @Composable fun MakeItSoTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable() () -> Unit) { val colors = if (darkTheme) DarkColorPalette else LightColorPalette MaterialTheme(colors = colors, typography = Typography, shapes = Shapes, content = content) }
apache-2.0
8f29a5fe2083572513d0264481ffc0d7
36.75
98
0.80206
4.686207
false
false
false
false
UweTrottmann/SeriesGuide
app/src/main/java/com/battlelancer/seriesguide/dataliberation/DataLiberationActivity.kt
1
1867
package com.battlelancer.seriesguide.dataliberation import android.content.Context import android.content.Intent import android.os.Bundle import android.view.MenuItem import androidx.fragment.app.Fragment import com.battlelancer.seriesguide.R import com.battlelancer.seriesguide.ui.BaseActivity /** * Hosts a [DataLiberationFragment]. */ class DataLiberationActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_singlepane) setupActionBar() if (savedInstanceState == null) { val showAutoBackup = intent.getBooleanExtra( EXTRA_SHOW_AUTOBACKUP, false ) val f: Fragment = if (showAutoBackup) { AutoBackupFragment() } else { DataLiberationFragment() } supportFragmentManager.beginTransaction() .add(R.id.content_frame, f) .commit() } } override fun setupActionBar() { super.setupActionBar() supportActionBar?.apply { setHomeAsUpIndicator(R.drawable.ic_clear_24dp) setDisplayHomeAsUpEnabled(true) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { onBackPressedDispatcher.onBackPressed() true } else -> false } } companion object { private const val EXTRA_SHOW_AUTOBACKUP = "EXTRA_SHOW_AUTOBACKUP" @JvmStatic fun intentToShowAutoBackup(context: Context): Intent { return Intent(context, DataLiberationActivity::class.java) .putExtra(EXTRA_SHOW_AUTOBACKUP, true) } } }
apache-2.0
14e2326fcbdbc8b3ae88e97a3a881ea3
27.723077
73
0.612748
5.018817
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/command/profession/ProfessionUnsetCommand.kt
1
6096
/* * 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.professions.bukkit.command.profession import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import com.rpkit.professions.bukkit.RPKProfessionsBukkit import com.rpkit.professions.bukkit.profession.RPKProfessionName import com.rpkit.professions.bukkit.profession.RPKProfessionService import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class ProfessionUnsetCommand(val plugin: RPKProfessionsBukkit) : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (!sender.hasPermission("rpkit.professions.command.profession.unset")) { sender.sendMessage(plugin.messages["no-permission-profession-unset"]) return true } var argsOffset = 0 val target = if (sender.hasPermission("rpkit.professions.command.profession.unset.other")) { when { args.size > 1 -> { val player = plugin.server.getPlayer(args[0]) if (player == null) { sender.sendMessage(plugin.messages["profession-unset-invalid-player-not-online"]) return true } else { argsOffset = 1 player } } sender is Player -> sender else -> { sender.sendMessage(plugin.messages["profession-unset-invalid-player-please-specify-from-console"]) return true } } } else { if (sender is Player) { sender } else { sender.sendMessage(plugin.messages["profession-unset-invalid-player-please-specify-from-console"]) return true } } if (args.isEmpty()) { sender.sendMessage(plugin.messages["profession-unset-usage"]) return true } val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] if (minecraftProfileService == null) { sender.sendMessage(plugin.messages["no-minecraft-profile-service"]) return true } val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(target) if (minecraftProfile == null) { if (target == sender) { sender.sendMessage(plugin.messages["no-minecraft-profile-self"]) } else { sender.sendMessage(plugin.messages["no-minecraft-profile-other", mapOf( "player" to target.name )]) } return true } val characterService = Services[RPKCharacterService::class.java] if (characterService == null) { sender.sendMessage(plugin.messages["no-character-service"]) return true } val character = characterService.getPreloadedActiveCharacter(minecraftProfile) if (character == null) { if (target == sender) { sender.sendMessage(plugin.messages["no-character-self"]) } else { sender.sendMessage(plugin.messages["no-character-other", mapOf( "player" to target.name )]) } return true } val professionService = Services[RPKProfessionService::class.java] if (professionService == null) { sender.sendMessage(plugin.messages["no-profession-service"]) return true } val profession = professionService.getProfession(RPKProfessionName(args[argsOffset])) if (profession == null) { sender.sendMessage(plugin.messages["profession-unset-invalid-profession"]) return true } professionService.getProfessions(character).thenAcceptAsync { characterProfessions -> if (!characterProfessions.contains(profession)) { sender.sendMessage(plugin.messages["profession-unset-invalid-not-using-profession"]) return@thenAcceptAsync } if (target == sender) { val professionChangeCooldown = professionService.getProfessionChangeCooldown(character).join() if (!professionChangeCooldown.isZero) { sender.sendMessage(plugin.messages["profession-unset-invalid-on-cooldown", mapOf( "cooldown_days" to professionChangeCooldown.toDays().toString(), "cooldown_hours" to (professionChangeCooldown.toHours() % 24).toString(), "cooldown_minutes" to (professionChangeCooldown.toMinutes() % 60).toString(), "cooldown_seconds" to (professionChangeCooldown.seconds % 60).toString() )]) return@thenAcceptAsync } } professionService.removeProfession(character, profession).thenRun { sender.sendMessage( plugin.messages["profession-unset-valid", mapOf( "profession" to profession.name.value )] ) } } return true } }
apache-2.0
7a967d1ca21eb64ff0c6e0f72ac851b6
43.49635
118
0.605151
5.237113
false
false
false
false
android/user-interface-samples
CanonicalLayouts/list-detail-compose/app/src/main/java/com/example/listdetailcompose/ui/ListDetail.kt
1
6019
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.listdetailcompose.ui import androidx.activity.compose.BackHandler import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.movableContentOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveableStateHolder import androidx.compose.ui.Modifier import androidx.window.layout.DisplayFeature import com.google.accompanist.adaptive.FoldAwareConfiguration import com.google.accompanist.adaptive.TwoPane import com.google.accompanist.adaptive.TwoPaneStrategy /** * A higher-order component displaying an opinionated list-detail format. * * The [list] slot is the primary content, and is in a parent relationship with the content * displayed in [detail]. * * This relationship implies that different detail screens may be swapped out for each other, and * should be distinguished by passing a [detailKey] to control when a different detail is being * shown (to reset instance state. * * When there is enough space to display both list and detail, pass `true` to [showListAndDetail] * to show both the list and the detail at the same time. This content is displayed in a [TwoPane] * with the given [twoPaneStrategy]. * * When there is not enough space to display both list and detail, which slot is displayed is based * on [isDetailOpen]. Internally, this state is changed in an opinionated way via [setIsDetailOpen]. * For instance, when showing just the detail screen, a back button press will call * [setIsDetailOpen] passing `false`. */ @Composable fun ListDetail( isDetailOpen: Boolean, setIsDetailOpen: (Boolean) -> Unit, showListAndDetail: Boolean, detailKey: Any, list: @Composable (isDetailVisible: Boolean) -> Unit, detail: @Composable (isListVisible: Boolean) -> Unit, twoPaneStrategy: TwoPaneStrategy, displayFeatures: List<DisplayFeature>, modifier: Modifier = Modifier, ) { val currentIsDetailOpen by rememberUpdatedState(isDetailOpen) val currentShowListAndDetail by rememberUpdatedState(showListAndDetail) val currentDetailKey by rememberUpdatedState(detailKey) // Determine whether to show the list and/or the detail. // This is a function of current app state, and the width size class. val showList by remember { derivedStateOf { currentShowListAndDetail || !currentIsDetailOpen } } val showDetail by remember { derivedStateOf { currentShowListAndDetail || currentIsDetailOpen } } // Validity check: we should always be showing something check(showList || showDetail) val listSaveableStateHolder = rememberSaveableStateHolder() val detailSaveableStateHolder = rememberSaveableStateHolder() val start = remember { movableContentOf { // Set up a SaveableStateProvider so the list state will be preserved even while it // is hidden if the detail is showing instead. listSaveableStateHolder.SaveableStateProvider(0) { Box( modifier = Modifier .userInteractionNotification { // When interacting with the list, consider the detail to no longer be // open in the case of resize. setIsDetailOpen(false) } ) { list(showDetail) } } } } val end = remember { movableContentOf { // Set up a SaveableStateProvider against the selected word index to save detail // state while switching between details. // If this behavior isn't desired, this can be replaced with a key on the // selectedWordIndex. detailSaveableStateHolder.SaveableStateProvider(currentDetailKey) { Box( modifier = Modifier .userInteractionNotification { // When interacting with the detail, consider the detail to be // open in the case of resize. setIsDetailOpen(true) } ) { detail(showList) } } // If showing just the detail, allow a back press to hide the detail to return to // the list. if (!showList) { BackHandler { setIsDetailOpen(false) } } } } Box(modifier = modifier) { if (showList && showDetail) { TwoPane( first = { start() }, second = { end() }, strategy = twoPaneStrategy, displayFeatures = displayFeatures, foldAwareConfiguration = FoldAwareConfiguration.VerticalFoldsOnly, modifier = Modifier.fillMaxSize(), ) } else if (showList) { start() } else { end() } } }
apache-2.0
abe170641146350806e19004c222c163
37.583333
100
0.640804
5.079325
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/tables/UserSettings.kt
1
868
package net.perfectdreams.loritta.morenitta.tables import net.perfectdreams.loritta.morenitta.utils.locale.Gender import net.perfectdreams.loritta.cinnamon.pudding.tables.Backgrounds import net.perfectdreams.loritta.cinnamon.pudding.tables.ProfileDesigns import org.jetbrains.exposed.dao.id.LongIdTable object UserSettings : LongIdTable() { val aboutMe = text("about_me").nullable() val gender = enumeration("gender", Gender::class) val activeProfileDesign = optReference("active_profile_design", ProfileDesigns) val activeBackground = optReference("active_background", Backgrounds) val doNotSendXpNotificationsInDm = bool("do_not_send_xp_notifications_in_dm").default(false) val discordAccountFlags = integer("discord_account_flags").default(0) val discordPremiumType = integer("discord_premium_type").nullable() var language = text("language").nullable() }
agpl-3.0
a062ceac891ba3c273eeb136e710c72a
50.117647
93
0.808756
3.875
false
false
false
false
stokito/IdeaSingletonInspection
src/main/java/com/github/stokito/IdeaSingletonInspection/smells/InstanceGetters.kt
1
1856
package com.github.stokito.IdeaSingletonInspection.smells import com.github.stokito.IdeaSingletonInspection.PsiTreeUtils import com.github.stokito.IdeaSingletonInspection.quickFixes.QuickFixes import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassType import com.intellij.psi.PsiMethod import com.intellij.psi.PsiModifier.PUBLIC import com.intellij.psi.PsiModifier.STATIC class InstanceGetters : Smell() { override fun check(aClass: PsiClass) { val instanceGetters = PsiTreeUtils.getInstanceGetters(aClass) for (instanceGetter in instanceGetters) { checkInstanceGetterHasPublicAndStaticModifiers(instanceGetter) checkInstanceGetterReturnItselfClass(aClass, instanceGetter) } } private fun checkInstanceGetterHasPublicAndStaticModifiers(instanceGetter: PsiMethod) { val modifiers = instanceGetter.modifierList if (!(modifiers.hasModifierProperty(PUBLIC) && modifiers.hasModifierProperty(STATIC))) { holder!!.registerProblem(instanceGetter, "getInstance() must be public and static", QuickFixes.INSTANCE_GETTERS_MODIFIERS) } } private fun checkInstanceGetterReturnItselfClass(aClass: PsiClass, instanceGetter: PsiMethod) { if (instanceGetter.returnType is PsiClassType) { val returnClassType = (instanceGetter.returnType as PsiClassType?)!! val instanceGetterReturnClass = returnClassType.resolve() if (aClass != instanceGetterReturnClass) { holder!!.registerProblem(instanceGetter, "getInstance() return class isn't equals to singleton itself class", QuickFixes.INSTANCE_GETTERS_RETURN_TYPE) } } else { holder!!.registerProblem(instanceGetter, "getInstance() must return itself class", QuickFixes.INSTANCE_GETTERS_RETURN_TYPE) } } }
apache-2.0
e3f3ced3833e66ffa8978a633d67dccc
46.589744
166
0.741379
4.833333
false
false
false
false
Yalantis/Context-Menu.Android
sample/src/main/java/com/yalantis/contextmenu/sample/SampleActivity.kt
1
5229
package com.yalantis.contextmenu.sample import android.graphics.BitmapFactory import android.graphics.drawable.BitmapDrawable import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.widget.Toast import com.yalantis.contextmenu.R import com.yalantis.contextmenu.lib.ContextMenuDialogFragment import com.yalantis.contextmenu.lib.MenuObject import com.yalantis.contextmenu.lib.MenuParams import kotlinx.android.synthetic.main.toolbar.* class SampleActivity : AppCompatActivity() { private lateinit var contextMenuDialogFragment: ContextMenuDialogFragment override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sample) initToolbar() initMenuFragment() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { item?.let { when (it.itemId) { R.id.context_menu -> { showContextMenuDialogFragment() } } } return super.onOptionsItemSelected(item) } override fun onBackPressed() { if (::contextMenuDialogFragment.isInitialized && contextMenuDialogFragment.isAdded) { contextMenuDialogFragment.dismiss() } else { finish() } } private fun initToolbar() { setSupportActionBar(toolbar) supportActionBar?.apply { setHomeButtonEnabled(true) setDisplayHomeAsUpEnabled(true) setDisplayShowTitleEnabled(false) } toolbar.apply { setNavigationIcon(R.drawable.ic_arrow_back) setNavigationOnClickListener { onBackPressed() } } tvToolbarTitle.text = "Samantha" } /** * If you want to change the side you need to add 'gravity' parameter, * by default it is MenuGravity.END. * * For example: * * MenuParams( * actionBarSize = resources.getDimension(R.dimen.tool_bar_height).toInt(), * menuObjects = getMenuObjects(), * isClosableOutside = false, * gravity = MenuGravity.START * ) */ private fun initMenuFragment() { val menuParams = MenuParams( actionBarSize = resources.getDimension(R.dimen.tool_bar_height).toInt(), menuObjects = getMenuObjects(), isClosableOutside = false ) contextMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams).apply { menuItemClickListener = { view, position -> Toast.makeText( this@SampleActivity, "Clicked on position: $position", Toast.LENGTH_SHORT ).show() } menuItemLongClickListener = { view, position -> Toast.makeText( this@SampleActivity, "Long clicked on position: $position", Toast.LENGTH_SHORT ).show() } } } /** * You can use any (drawable, resource, bitmap, color) as image: * menuObject.drawable = ... * menuObject.setResourceValue(...) * menuObject.setBitmapValue(...) * menuObject.setColorValue(...) * * You can set image ScaleType: * menuObject.scaleType = ScaleType.FIT_XY * * You can use any [resource, drawable, color] as background: * menuObject.setBgResourceValue(...) * menuObject.setBgDrawable(...) * menuObject.setBgColorValue(...) * * You can use any (color) as text color: * menuObject.textColor = ... * * You can set any (color) as divider color: * menuObject.dividerColor = ... */ private fun getMenuObjects() = mutableListOf<MenuObject>().apply { val close = MenuObject().apply { setResourceValue(R.drawable.icn_close) } val send = MenuObject("Send message").apply { setResourceValue(R.drawable.icn_1) } val like = MenuObject("Like profile").apply { setBitmapValue(BitmapFactory.decodeResource(resources, R.drawable.icn_2)) } val addFriend = MenuObject("Add to friends").apply { drawable = BitmapDrawable( resources, BitmapFactory.decodeResource(resources, R.drawable.icn_3) ) } val addFavorite = MenuObject("Add to favorites").apply { setResourceValue(R.drawable.icn_4) } val block = MenuObject("Block user").apply { setResourceValue(R.drawable.icn_5) } add(close) add(send) add(like) add(addFriend) add(addFavorite) add(block) } private fun showContextMenuDialogFragment() { if (supportFragmentManager.findFragmentByTag(ContextMenuDialogFragment.TAG) == null) { contextMenuDialogFragment.show(supportFragmentManager, ContextMenuDialogFragment.TAG) } } }
apache-2.0
0804cf2931e2fc4faf2236c0ca5334ef
31.886792
97
0.611972
4.919097
false
false
false
false
kmizu/kollection
src/main/kotlin/com/github/kmizu/kollection/type_classes/KMonoid.kt
1
2507
package com.github.kmizu.kollection.type_classes import com.github.kmizu.kollection.KList import com.github.kmizu.kollection.KList.* import com.github.kmizu.kollection.concat interface KMonoid<T> { companion object { val BYTE: KMonoid<Byte> = object : KMonoid<Byte> { override fun mzero(): Byte = 0 override fun mplus(a: Byte, b: Byte): Byte = (a + b).toByte() } val SHORT: KMonoid<Short> = object : KMonoid<Short> { override fun mzero(): Short = 0 override fun mplus(a: Short, b: Short): Short = (a + b).toShort() } val INT: KMonoid<Int> = object : KMonoid<Int> { override fun mzero(): Int = 0 override fun mplus(a: Int, b: Int): Int = a + b } val CHAR: KMonoid<Char> = object : KMonoid<Char> { override fun mzero(): Char = 0.toChar() override fun mplus(a: Char, b: Char): Char = (a + b.toInt()).toChar() } val LONG: KMonoid<Long> = object : KMonoid<Long> { override fun mzero(): Long = 0 override fun mplus(a: Long, b: Long): Long = a + b } val FLOAT: KMonoid<Float> = object : KMonoid<Float> { override fun mzero(): Float = 0.0f override fun mplus(a: Float, b: Float): Float = a + b } val DOUBLE: KMonoid<Double> = object : KMonoid<Double> { override fun mzero(): Double = 0.0 override fun mplus(a: Double, b: Double): Double = a + b } val BOOLEAN: KMonoid<Boolean> = object : KMonoid<Boolean> { override fun mzero(): Boolean = false override fun mplus(a: Boolean, b: Boolean): Boolean = a || b } val UNIT: KMonoid<Unit> = object : KMonoid<Unit> { override fun mzero(): Unit = Unit override fun mplus(a: Unit, b: Unit): Unit = Unit } fun <A, B> PAIR(m1: KMonoid<A>, m2: KMonoid<B>): KMonoid<Pair<A, B>> = object : KMonoid<Pair<A, B>> { override fun mzero(): Pair<A, B> = Pair(m1.mzero(), m2.mzero()) override fun mplus(a: Pair<A, B>, b: Pair<A, B>): Pair<A, B> = Pair(m1.mplus(a.first, b.first), m2.mplus(a.second, b.second)) } fun <A> KLIST(): KMonoid<KList<A>> = object : KMonoid<KList<A>> { override fun mzero(): KList<A> = Nil override fun mplus(a: KList<A>, b: KList<A>): KList<A> = a concat b } } fun mzero(): T fun mplus(a: T, b: T): T }
mit
0566994226b4e7b837b8ae65bdf1460c
42.241379
137
0.546071
3.32053
false
false
false
false
eugeis/ee
ee-lang/src/main/kotlin/ee/lang/gen/doc/MarkdownPojos.kt
1
5768
package ee.lang.gen.doc import ee.common.ext.* import ee.lang.* fun <T : CompilationUnitI<*>> T.toMarkdownClassImpl(c: GenerationContext, derived: String = LangDerivedKind.IMPL): String { return """ # ${parent().name()} ${parent().name()}is a module and artifact mcr-opcua ## ${namespace()} ${namespace()} is a package ##${isIfc().ifElse("interface ", "class")} ${name()} ${doc().toPlainUml(c,generateComments= true)} ## Properties ${props().joinSurroundIfNotEmptyToString(nL, prefix = nL, postfix = nL) { it.toPlainUmlMember(c, genProps = true) }} ## Operations ${operations().joinSurroundIfNotEmptyToString(nL, prefix = nL, postfix = nL) { it.toPlainOperUml(c, genOperations = true) }} ## PlantUml diagram ```plantuml ${toPlainUmlClassImpl(c, startStopUml = true)} ``` """ } fun <T : CommentI<*>> T.toPlainUml(c: GenerationContext, generateComments: Boolean, startNoteUml: Boolean = true): String = (generateComments && isNotEMPTY()).then { "${startNoteUml(startNoteUml)} ${name()} " } fun <T : AttributeI<*>> T.toPlainUmlMember(c: GenerationContext, genProps: Boolean = true): String = (genProps && isNotEMPTY()).then { "${c.n(this)} : ${c.n(type())}" } fun OperationI<*>.toPlainOperUml(c: GenerationContext, genOperations: Boolean = true): String = (genOperations && isNotEMPTY()).then { // "${it.name()}: ${it.type()} "${c.n(this)}" } fun <T : AttributeI<*>> T.toPlainUmlNotNative(c: GenerationContext, genNative: Boolean = true): String = (genNative && isNotEMPTY()).then { "${c.n(name())}" } fun <T : AttributeI<*>> T.toPlainUmlNotNativeType(c: GenerationContext, genNative: Boolean = true): String = (genNative && isNotEMPTY()).then { if ("${c.n(type())}" == "Map") { "${c.n(type().isMulti().ifElse("${c.n(type().generics().first().name())}", "${c.n(type().generics().last().name())}alue"))} " } else if ("${c.n(type())}" == "List") { "${c.n(type())}" } else "${c.n(type())}" } fun <T : ItemI<*>> T.toKotlinPacketOperation(c: GenerationContext, genOperations: Boolean = true): String = (genOperations && isNotEMPTY()).then { "${c.n(name())}" } fun <T : CompilationUnitI<*>> T.toPlainUmlClassImpl(c: GenerationContext, derived: String = LangDerivedKind.IMPL, startStopUml: Boolean = true, genProps: Boolean = true, generateComments:Boolean=true, genOperations: Boolean =true, genNoNative:Boolean=true): String { return """ ${startUml(startStopUml)} ${name().isNotEmpty().then { """ ${isIfc().ifElse("interface ", "class")} ${name()} { {method} ${nL} ${operations().joinSurroundIfNotEmptyToString(nL, prefix = " ", postfix = ""){" ${it.toKotlinPacketOperation(c,genOperations = true)}()" }} {field} ${nL} ${props().joinSurroundIfNotEmptyToString(nL, prefix = "", postfix = "") { it.toPlainUmlMember(c, genProps) }} } """}} ${doc().toPlainUml(c, generateComments)} ${stopUml(startStopUml)} """ } fun <T : CompilationUnitI<*>> T.toPlainUmlClassDetails( c: GenerationContext, derived: String = LangDerivedKind.IMPL, startStopUml: Boolean = true, genProps: Boolean = true, genproperty:Boolean=true, generateComments:Boolean=true, genOperations: Boolean =true, genNoNative:Boolean=true): String { val propTypes = propsNoNative().map { it.type() }.filterIsInstance(CompilationUnitI::class.java).toSet() return """ ${startUml(startStopUml)} package ${namespace()}{ ${name().isNotEmpty().then { """ ${isIfc().ifElse("interface ", "class")} ${name()} { {field} ${nL} ${props().joinSurroundIfNotEmptyToString(nL, prefix = "", postfix = "") { it.toPlainUmlMember(c, genProps) }} ${operations().isNotEmpty().then { """-- {method} ${nL} ${operations().joinSurroundIfNotEmptyToString(nL, prefix = " ", postfix = ""){" ${it.toKotlinPacketOperation(c,genOperations = true)}()"}} """}} """}} } ${doc().toPlainUml(c, generateComments)} ${propTypes.joinSurroundIfNotEmptyToString(nL, prefix = " ", postfix = " ") { it.toPlainUmlClassImpl(c, derived, false) }} ${propsNoNative().joinSurroundIfNotEmptyToString(nL, prefix = " ", postfix = "") { "${nL} ${it.toPlainUmlNotNativeType(c).isNotEmpty().then { " ${name()} -- ${it.toPlainUmlNotNativeType(c,genOperations)} : ${it.toPlainUmlNotNative(c,genOperations)} ${nL}" }} " } } ${stopUml(startStopUml)} """ } fun <T : CompilationUnitI<*>> T.toPlainUmlSuperClass( c: GenerationContext, derived: String = LangDerivedKind.IMPL, startStopUml: Boolean = true, genProps: Boolean = true, genproperty:Boolean=true, generateComments:Boolean=true, genOperations: Boolean =true, genNoNative:Boolean=true): String { return """ ${ if (superUnit().name() == "@@EMPTY@@") {""}else "${startUml(startStopUml)}"} ${propsNoNative().joinSurroundIfNotEmptyToString(nL, prefix = " ", postfix = "") { if (superUnit().name()== "@@EMPTY@@") {""}else "${it.toPlainUmlNotNativeType(c).isNotEmpty().then { "${superUnit().name()} <|-- ${it.toPlainUmlNotNativeType(c, genOperations)} : ${it.toPlainUmlNotNative(c, genOperations)}" }}" } } ${ if (superUnit().name() == "@@EMPTY@@") {""}else "${stopUml(startStopUml)}"} """ } private fun stopUml(startStopUml: Boolean) = startStopUml.then("@enduml") private fun startUml(startStopUml: Boolean) = startStopUml.then("@startuml") private fun startNoteUml(startNoteUml: Boolean) = startNoteUml.then("note top:")
apache-2.0
84497e07906c3093ae29c4c5587474c0
38.506849
238
0.613731
3.652945
false
false
false
false
carlphilipp/chicago-commutes
android-app/src/main/kotlin/fr/cph/chicago/core/listener/OpenMapDirectionOnClickListener.kt
1
1729
/** * Copyright 2021 Carl-Philipp Harmant * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package fr.cph.chicago.core.listener import android.content.Intent import android.net.Uri import android.view.View import fr.cph.chicago.util.Util import timber.log.Timber class OpenMapDirectionOnClickListener(latitude: Double, longitude: Double) : GoogleMapListener(latitude, longitude) { companion object { private val util = Util } override fun onClick(v: View) { try { val uri = "http://maps.google.com/?f=d&daddr=$latitude,$longitude&dirflg=w" val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uri)) intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity") intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) if (intent.resolveActivity(v.context.packageManager) != null) { v.context.startActivity(intent) } else { util.showSnackBar(v, "Could not find Google Map on device", true) } } catch (e: Exception) { Timber.e(e) util.showSnackBar(v, "Could not find Google Map on device", true) } } }
apache-2.0
3ebfe72eb93d7f0262a512f04c9c298e
33.58
117
0.671486
4.02093
false
false
false
false
RyanAndroidTaylor/Rapido
rapidocommon/src/main/java/com/izeni/rapidocommon/transaction/TransactionErrorHandler.kt
1
1863
package com.izeni.rapidocommon.transaction import android.app.Activity import android.os.Handler import android.widget.Toast import com.afollestad.materialdialogs.MaterialDialog import com.izeni.rapidocommon.e /** * Created by ner on 11/20/16. */ object TransactionErrorHandler { private var context: Activity? = null fun attach(context: Activity) { this.context = context } fun detach(context: Activity) { if (this.context == context) this.context = null } fun handleError(error: Throwable?) { context?.let { Handler(it.mainLooper).post { when (error) { is LogThrowable -> e(error.message) is ToastThrowable -> showToast(error.message ?: "Message not specified") is DialogThrowable -> showDialog(error.title, error.message ?: "Message not specified") else -> error?.printStackTrace() } } } } fun showToast(message: String) { context?.let { Toast.makeText(it, message, Toast.LENGTH_LONG).show() } } fun showDialog(title: String, message: String) { context?.let { MaterialDialog.Builder(it) .title(title) .content(message) .positiveText("Ok") .show() } } } class LogThrowable(message: String): Throwable(message) class ToastThrowable(message: String): Throwable(message) class DialogThrowable(val title: String, message: String): Throwable(message) fun throwLogMessage(message: String): Nothing = throw LogThrowable(message) fun throwToastMessage(message: String): Nothing = throw ToastThrowable(message) fun throwDialogMessage(title: String, message: String): Nothing = throw DialogThrowable(title, message)
mit
be16d294156155446f73c6091f6358c7
28.587302
107
0.624799
4.566176
false
false
false
false
halawata13/ArtichForAndroid
app/src/main/java/net/halawata/artich/model/list/GNewsList.kt
2
4119
package net.halawata.artich.model.list import android.content.Context import net.halawata.artich.entity.GNewsArticle import net.halawata.artich.model.DatabaseHelper import net.halawata.artich.model.Log import net.halawata.artich.model.mute.GNewsMute import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserFactory import java.io.StringReader import java.net.MalformedURLException import java.net.URL import kotlin.collections.ArrayList class GNewsList: MediaList { override val dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz" override fun parse(content: String): ArrayList<GNewsArticle>? { val factory = XmlPullParserFactory.newInstance() val parser = factory.newPullParser() parser.setInput(StringReader(content)) var eventType = parser.eventType val articles = ArrayList<GNewsArticle>() var id: Long = 0 var title = "" var url = "" var pubDate = "" try { while (eventType != XmlPullParser.END_DOCUMENT) { // item タグ開始が来るまでスキップ if (eventType != XmlPullParser.START_TAG || parser.name != "item") { eventType = parser.next() continue } while (eventType != XmlPullParser.END_TAG || parser.name != "item") { if (eventType == XmlPullParser.START_TAG && parser.name == "title") { while (eventType != XmlPullParser.END_TAG || parser.name != "title") { if (eventType == XmlPullParser.TEXT) { title = parser.text } eventType = parser.next() } } if (eventType == XmlPullParser.START_TAG && parser.name == "link") { while (eventType != XmlPullParser.END_TAG || parser.name != "link") { if (eventType == XmlPullParser.TEXT) { url = parser.text } eventType = parser.next() } } if (eventType == XmlPullParser.START_TAG && parser.name == "pubDate") { while (eventType != XmlPullParser.END_TAG || parser.name != "pubDate") { if (eventType == XmlPullParser.TEXT) { pubDate = formatDate(parser.text) ?: "" } eventType = parser.next() } } eventType = parser.next() } extractUrl(url)?.let { val article = GNewsArticle( id = id++, title = title, url = it, pubDate = pubDate ) articles.add(article) } eventType = parser.next() } } catch (ex: Exception) { Log.e(ex.message) } articles.sortByDescending { article -> article.pubDate } return articles } fun filter(data: ArrayList<GNewsArticle>, context: Context): ArrayList<GNewsArticle> { val filtered = ArrayList<GNewsArticle>() val helper = DatabaseHelper(context) val mute = GNewsMute(helper) val muteList = mute.getMuteList() data.forEach { item -> try { val url = URL(item.url) if (!muteList.contains(url.host)) { filtered.add(item) } } catch (ex: MalformedURLException) { Log.e(ex.message) } } return filtered } private fun extractUrl(urlString: String): String? { val regex = Regex("&url=(\\S+$)") val result = regex.find(urlString) return result?.groupValues?.get(1) } }
mit
a1e1e6414915686f3bdb4f5bece5d414
31.744
96
0.487906
5.207379
false
false
false
false
mozilla-mobile/focus-android
app/src/main/java/org/mozilla/focus/activity/InstallFirefoxActivity.kt
1
2913
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.activity import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.ActivityInfo import android.os.Bundle import android.webkit.WebView import androidx.core.net.toUri import mozilla.components.service.glean.private.NoExtras import mozilla.components.support.utils.Browsers import mozilla.components.support.utils.ext.resolveActivityCompat import org.mozilla.focus.GleanMetrics.OpenWith import org.mozilla.focus.telemetry.TelemetryWrapper import org.mozilla.focus.utils.AppConstants /** * Helper activity that will open the Google Play store by following a redirect URL. */ class InstallFirefoxActivity : Activity() { private var webView: WebView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) webView = WebView(this) setContentView(webView) webView!!.loadUrl(REDIRECT_URL) } override fun onPause() { super.onPause() if (webView != null) { webView!!.onPause() } finish() } override fun onDestroy() { super.onDestroy() if (webView != null) { webView!!.destroy() } } companion object { private const val REDIRECT_URL = "https://app.adjust.com/gs1ao4" fun resolveAppStore(context: Context): ActivityInfo? { val resolveInfo = context.packageManager.resolveActivityCompat(createStoreIntent(), 0) if (resolveInfo?.activityInfo == null) { return null } return if (!resolveInfo.activityInfo.exported) { // We are not allowed to launch this activity. null } else { resolveInfo.activityInfo } } private fun createStoreIntent(): Intent { return Intent( Intent.ACTION_VIEW, ("market://details?id=" + Browsers.KnownBrowser.FIREFOX.packageName).toUri(), ) } fun open(context: Context) { if (AppConstants.isKlarBuild) { // Redirect to Google Play directly context.startActivity(createStoreIntent()) } else { // Start this activity to load the redirect URL in a WebView. val intent = Intent(context, InstallFirefoxActivity::class.java) context.startActivity(intent) } OpenWith.installFirefox.record(NoExtras()) TelemetryWrapper.installFirefoxEvent() } } }
mpl-2.0
52db484f8fd8cbf11c9f512d27b72eab
29.030928
98
0.628905
4.690821
false
false
false
false
macrat/RuuMusic
wear/src/main/java/jp/blanktar/ruumusic/wear/PlaylistAdapter.kt
1
2498
package jp.blanktar.ruumusic.wear import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView class PlaylistAdapter : androidx.recyclerview.widget.RecyclerView.Adapter<PlaylistAdapter.ViewHolder>() { private var directory: Directory? = null private var isRoot: Boolean = false var onParentClickListener: (() -> Unit)? = null var onDirectoryClickListener: ((String) -> Unit)? = null var onMusicClickListener: ((String) -> Unit)? = null fun changeDirectory(dir: Directory, isRoot_: Boolean) { val rootReuse = !isRoot && !isRoot_ notifyItemRangeRemoved(if (rootReuse) 1 else 0, itemCount) directory = dir isRoot = isRoot_ notifyItemRangeInserted(if (rootReuse) 1 else 0, itemCount) } override fun getItemViewType(position: Int) = if (!isRoot && position == 0) 0 else 1 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlaylistAdapter.ViewHolder { val holder = if (viewType == 0) { ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.list_item_upper, parent, false)) } else { ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false)) } holder.itemView.setOnClickListener { _ -> if (!isRoot && holder.adapterPosition == 0) { onParentClickListener?.invoke() } else if (holder.adapterPosition < directory!!.directories.size + if (isRoot) 0 else 1) { onDirectoryClickListener?.invoke(directory!!.path + directory!!.all[holder.adapterPosition - if (isRoot) 0 else 1]) } else { onMusicClickListener?.invoke(directory!!.path + directory!!.all[holder.adapterPosition - if (isRoot) 0 else 1]) } } return holder } override fun onBindViewHolder(holder: PlaylistAdapter.ViewHolder, position: Int) { holder.text?.text = directory!!.all[position - if (isRoot) 0 else 1] } override fun getItemCount(): Int { if (directory != null) { return directory!!.directories.size + directory!!.musics.size + if (isRoot) 0 else 1 } else { return 0 } } class ViewHolder(view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view) { val text: TextView? = view.findViewById<TextView>(R.id.text) } }
mit
4107364788a4be96209f5f838e309173
39.290323
131
0.657326
4.509025
false
false
false
false
Kennyc1012/BottomSheet
library/src/main/java/com/kennyc/bottomsheet/menu/BottomSheetMenuItem.kt
1
8788
package com.kennyc.bottomsheet.menu /* * Copyright (C) 2010 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. */ import android.content.Context import android.content.Intent import android.graphics.drawable.Drawable import android.view.ActionProvider import android.view.ContextMenu.ContextMenuInfo import android.view.MenuItem import android.view.SubMenu import android.view.View import androidx.annotation.DrawableRes import androidx.core.content.res.ResourcesCompat internal class BottomSheetMenuItem /** * Creates a MenuItem * * @param context Context of the MenuItem * @param group Group id of the MenuItem * @param id Id of the MenuItem * @param categoryOrder Category order of the MenuItem * @param ordering Ordering of the MenuItem * @param title Title of the MenuItem */ (private val context: Context, private val group: Int, private val id: Int, private val categoryOrder: Int, private val ordering: Int, private var title: CharSequence?) : MenuItem { private var titleCondensed: CharSequence? = null private var mIntent: Intent? = null private var shortcutNumericChar: Char = ' ' private var shortcutAlphabeticChar: Char = ' ' private var iconDrawable: Drawable? = null private var iconResId = NO_ICON private var clickListener: MenuItem.OnMenuItemClickListener? = null private var flags = ENABLED /** * Creates a MenuItem * * @param context Context of the MenuItem * @param title Title of the MenuItem * @param icon Drawable resource of the MenuItem */ constructor(context: Context, title: CharSequence, @DrawableRes icon: Int) : this(context, 0, 0, 0, 0, title) { setIcon(icon) } /** * Creates a MenuItem * * @param context Context of the MenuItem * @param title Title of the MenuItem * @param icon Drawable of the MenuItem */ constructor(context: Context, title: CharSequence, icon: Drawable?) : this(context, 0, 0, 0, 0, title) { setIcon(icon) } /** * Creates a MenuItem * * @param context Context of the MenuItem * @param id Id of the MenuItem * @param title Title of the MenuItem * @param icon Drawable resource of the MenuItem */ constructor(context: Context, id: Int, title: CharSequence, @DrawableRes icon: Int) : this(context, 0, id, 0, 0, title) { setIcon(icon) } /** * Creates a MenuItem * * @param context Context of the MenuItem * @param id Id of the MenuItem * @param title Title of the MenuItem * @param icon Drawable of the MenuItem */ constructor(context: Context, id: Int, title: CharSequence, icon: Drawable?) : this(context, 0, id, 0, 0, title) { setIcon(icon) } override fun getAlphabeticShortcut(): Char { return shortcutAlphabeticChar } override fun getGroupId(): Int { return group } override fun getIcon(): Drawable? { return iconDrawable } override fun getIntent(): Intent? { return mIntent } override fun getItemId(): Int { return id } override fun getMenuInfo(): ContextMenuInfo? { return null } override fun getNumericShortcut(): Char { return shortcutNumericChar } override fun getOrder(): Int { return ordering } override fun getSubMenu(): SubMenu? { return null } override fun getTitle(): CharSequence? { return title } override fun getTitleCondensed(): CharSequence? { return if (titleCondensed != null) titleCondensed else title } override fun hasSubMenu(): Boolean { return false } override fun isCheckable(): Boolean { return flags and CHECKABLE != 0 } override fun isChecked(): Boolean { return flags and CHECKED != 0 } override fun isEnabled(): Boolean { return flags and ENABLED != 0 } override fun isVisible(): Boolean { return flags and HIDDEN == 0 } override fun setAlphabeticShortcut(alphaChar: Char): MenuItem { shortcutAlphabeticChar = alphaChar return this } override fun setCheckable(checkable: Boolean): MenuItem { flags = flags and CHECKABLE.inv() or if (checkable) CHECKABLE else 0 return this } fun setExclusiveCheckable(exclusive: Boolean): BottomSheetMenuItem { flags = flags and EXCLUSIVE.inv() or if (exclusive) EXCLUSIVE else 0 return this } override fun setChecked(checked: Boolean): MenuItem { flags = flags and CHECKED.inv() or if (checked) CHECKED else 0 return this } override fun setEnabled(enabled: Boolean): MenuItem { flags = flags and ENABLED.inv() or if (enabled) ENABLED else 0 return this } override fun setIcon(icon: Drawable?): MenuItem { iconDrawable = icon iconResId = NO_ICON return this } override fun setIcon(iconRes: Int): MenuItem { if (iconRes != NO_ICON) { iconResId = iconRes iconDrawable = ResourcesCompat.getDrawable(context.resources, iconResId, context.theme) } return this } override fun setIntent(intent: Intent): MenuItem { mIntent = intent return this } override fun setNumericShortcut(numericChar: Char): MenuItem { shortcutNumericChar = numericChar return this } override fun setOnMenuItemClickListener(menuItemClickListener: MenuItem.OnMenuItemClickListener): MenuItem { clickListener = menuItemClickListener return this } override fun setShortcut(numericChar: Char, alphaChar: Char): MenuItem { shortcutNumericChar = numericChar shortcutAlphabeticChar = alphaChar return this } override fun setTitle(title: CharSequence): MenuItem { this.title = title return this } override fun setTitle(title: Int): MenuItem { this.title = context.resources.getString(title) return this } override fun setTitleCondensed(title: CharSequence?): MenuItem { titleCondensed = title return this } override fun setVisible(visible: Boolean): MenuItem { flags = flags and HIDDEN or if (visible) 0 else HIDDEN return this } operator fun invoke(): Boolean { if (clickListener != null && clickListener!!.onMenuItemClick(this)) { return true } if (mIntent != null) { context.startActivity(mIntent) return true } return false } override fun setShowAsAction(show: Int) { // Do nothing. ActionMenuItems always show as action buttons. } override fun setActionView(actionView: View): MenuItem { throw UnsupportedOperationException() } override fun getActionView(): View? { return null } override fun setActionView(resId: Int): MenuItem { throw UnsupportedOperationException() } override fun getActionProvider(): ActionProvider? { return null } override fun setActionProvider(actionProvider: ActionProvider): MenuItem { throw UnsupportedOperationException() } override fun setShowAsActionFlags(actionEnum: Int): MenuItem { setShowAsAction(actionEnum) return this } override fun expandActionView(): Boolean { return false } override fun collapseActionView(): Boolean { return false } override fun isActionViewExpanded(): Boolean { return false } override fun setOnActionExpandListener(listener: MenuItem.OnActionExpandListener): MenuItem { // No need to save the listener; ActionMenuItem does not support collapsing items. return this } companion object { private const val NO_ICON = 0 private const val CHECKABLE = 0x00000001 private const val CHECKED = 0x00000002 private const val EXCLUSIVE = 0x00000004 private const val HIDDEN = 0x00000008 private const val ENABLED = 0x00000010 } }
apache-2.0
4f9e4a6681df87072cf48ffb64a0888a
25.795732
125
0.651229
4.871397
false
false
false
false
fython/PackageTracker
mobile/src/main/kotlin/info/papdt/express/helper/ui/common/SimpleRecyclerViewAdapter.kt
1
2107
package info.papdt.express.helper.ui.common import android.content.Context import androidx.recyclerview.widget.RecyclerView import android.view.View import java.util.ArrayList abstract class SimpleRecyclerViewAdapter(protected var mRecyclerView: RecyclerView) : RecyclerView.Adapter<SimpleRecyclerViewAdapter.ClickableViewHolder>() { var context: Context? = null private set protected var mListeners: MutableList<RecyclerView.OnScrollListener> = ArrayList() init { this.mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(rv: RecyclerView, newState: Int) { for (listener in mListeners) { listener.onScrollStateChanged(rv, newState) } } override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) { for (listener in mListeners) { listener.onScrolled(rv, dx, dy) } } }) } fun addOnScrollListener(listener: RecyclerView.OnScrollListener) { mListeners.add(listener) } interface OnItemClickListener { fun onItemClick(position: Int, holder: ClickableViewHolder) } interface OnItemLongClickListener { fun onItemLongClick(position: Int, holder: ClickableViewHolder): Boolean } private var itemClickListener: OnItemClickListener? = null private var itemLongClickListener: OnItemLongClickListener? = null fun setOnItemClickListener(listener: OnItemClickListener) { this.itemClickListener = listener } fun setOnItemLongClickListener(listener: OnItemLongClickListener) { this.itemLongClickListener = listener } fun bindContext(context: Context) { this.context = context } override fun onBindViewHolder(holder: ClickableViewHolder, position: Int) { holder.parentView.setOnClickListener { if (itemClickListener != null) { itemClickListener!!.onItemClick(position, holder) } } holder.parentView.setOnLongClickListener { if (itemLongClickListener != null) { itemLongClickListener!!.onItemLongClick(position, holder) } else { false } } } open inner class ClickableViewHolder(val parentView: View) : RecyclerView.ViewHolder(parentView) }
gpl-3.0
6c03458cffd44012a29c123c5b97db39
26.736842
97
0.768866
4.353306
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/FeedBridge.kt
1
6866
/* * Copyright 2021, 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 import android.content.Context import android.content.Intent import android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE import android.content.pm.ApplicationInfo.FLAG_SYSTEM import android.content.pm.PackageManager import android.net.Uri import android.os.Process import android.util.Log import app.lawnchair.preferences.PreferenceManager import app.lawnchair.util.SingletonHolder import app.lawnchair.util.ensureOnMainThread import app.lawnchair.util.useApplicationContext import com.android.launcher3.BuildConfig import com.android.launcher3.R import com.android.launcher3.Utilities class FeedBridge(private val context: Context) { private val shouldUseFeed = context.applicationInfo.flags and (FLAG_DEBUGGABLE or FLAG_SYSTEM) == 0 private val prefs by lazy { PreferenceManager.getInstance(context) } private val bridgePackages by lazy { listOf( PixelBridgeInfo("com.google.android.apps.nexuslauncher", R.integer.bridge_signature_hash), BridgeInfo("app.lawnchair.lawnfeed", R.integer.lawnfeed_signature_hash) ) } fun resolveBridge(): BridgeInfo? { val customBridge = customBridgeOrNull() return when { customBridge != null -> customBridge !shouldUseFeed -> null else -> bridgePackages.firstOrNull { it.isAvailable() } } } private fun customBridgeOrNull(): CustomBridgeInfo? { val feedProvider = prefs.feedProvider.get() return if (feedProvider.isNotBlank()) { val bridge = CustomBridgeInfo(feedProvider) if (bridge.isAvailable()) bridge else null } else { null } } private fun customBridgeAvailable() = customBridgeOrNull()?.isAvailable() == true fun isInstalled(): Boolean { return customBridgeAvailable() || !shouldUseFeed || bridgePackages.any { it.isAvailable() } } fun resolveSmartspace(): String { return bridgePackages.firstOrNull { it.supportsSmartspace }?.packageName ?: "com.google.android.googlequicksearchbox" } open inner class BridgeInfo(val packageName: String, signatureHashRes: Int) { protected open val signatureHash = if (signatureHashRes > 0) context.resources.getInteger(signatureHashRes) else 0 open val supportsSmartspace = false fun isAvailable(): Boolean { val info = context.packageManager.resolveService( Intent(overlayAction) .setPackage(packageName) .setData( Uri.parse( StringBuilder(packageName.length + 18) .append("app://") .append(packageName) .append(":") .append(Process.myUid()) .toString() ) .buildUpon() .appendQueryParameter("v", 7.toString()) .appendQueryParameter("cv", 9.toString()) .build() ), 0 ) return info != null && isSigned() } open fun isSigned(): Boolean { when { BuildConfig.DEBUG -> return true Utilities.ATLEAST_P -> { val info = context.packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES) val signingInfo = info.signingInfo if (signingInfo.hasMultipleSigners()) return false return signingInfo.signingCertificateHistory.any { it.hashCode() == signatureHash } } else -> { val info = context.packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES) return if (info.signatures.any { it.hashCode() != signatureHash }) false else info.signatures.isNotEmpty() } } } } private inner class CustomBridgeInfo(packageName: String) : BridgeInfo(packageName, 0) { override val signatureHash = whitelist[packageName]?.toInt() ?: -1 override fun isSigned(): Boolean { if (signatureHash == -1 && Utilities.ATLEAST_P) { val info = context.packageManager .getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES) val signingInfo = info.signingInfo if (signingInfo.hasMultipleSigners()) return false signingInfo.signingCertificateHistory.forEach { val hash = Integer.toHexString(it.hashCode()) Log.d(TAG, "Feed provider $packageName(0x$hash) isn't whitelisted") } } return signatureHash != -1 && super.isSigned() } } private inner class PixelBridgeInfo(packageName: String, signatureHashRes: Int) : BridgeInfo(packageName, signatureHashRes) { override val supportsSmartspace get() = isAvailable() } companion object : SingletonHolder<FeedBridge, Context>( ensureOnMainThread( useApplicationContext(::FeedBridge) ) ) { private const val TAG = "FeedBridge" private const val overlayAction = "com.android.launcher3.WINDOW_OVERLAY" private val whitelist = mapOf<String, Long>( "ua.itaysonlab.homefeeder" to 0x887456ed, // HomeFeeder, t.me/homefeeder "launcher.libre.dev" to 0x2e9dbab5 // Librechair, t.me/librechair ) fun getAvailableProviders(context: Context) = context.packageManager .queryIntentServices( Intent(overlayAction).setData(Uri.parse("app://${context.packageName}")), PackageManager.GET_META_DATA ) .map { it.serviceInfo.applicationInfo } .distinct() .filter { getInstance(context).CustomBridgeInfo(it.packageName).isSigned() } @JvmStatic fun useBridge(context: Context) = getInstance(context).let { it.shouldUseFeed || it.customBridgeAvailable() } } }
gpl-3.0
80a67982b43a46b45cfc437c81ba3464
39.627219
126
0.614477
4.993455
false
false
false
false
josesamuel/remoter
remoter/src/main/java/remoter/compiler/kbuilder/CharSequenceParamBuilder.kt
1
4150
package remoter.compiler.kbuilder import com.squareup.kotlinpoet.FunSpec import javax.lang.model.element.Element import javax.lang.model.element.ExecutableElement import javax.lang.model.element.VariableElement import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror /** * A [ParamBuilder] for [CharSequence] type parameters */ internal class CharSequenceParamBuilder(remoterInterfaceElement: Element, bindingManager: KBindingManager) : ParamBuilder(remoterInterfaceElement, bindingManager) { override fun writeParamsToProxy(param: VariableElement, paramType: ParamType, methodBuilder: FunSpec.Builder) { if (param.asType().kind == TypeKind.ARRAY) { logError("CharSequence[] cannot be marshalled") } else { if (param.isNullable()) { methodBuilder.beginControlFlow("if(" + param.simpleName + " != null)") methodBuilder.addStatement("$DATA.writeInt(1)") methodBuilder.addStatement("android.text.TextUtils.writeToParcel(" + param.simpleName + ", $DATA, 0)") methodBuilder.endControlFlow() methodBuilder.beginControlFlow("else") methodBuilder.addStatement("$DATA.writeInt(0)") methodBuilder.endControlFlow() } else { methodBuilder.addStatement("$DATA.writeInt(1)") methodBuilder.addStatement("android.text.TextUtils.writeToParcel(" + param.simpleName + ", $DATA, 0)") } } } override fun readResultsFromStub(methodElement: ExecutableElement, resultType: TypeMirror, methodBuilder: FunSpec.Builder) { if (resultType.kind == TypeKind.ARRAY) { logError("CharSequence[] cannot be marshalled") } else { methodBuilder.beginControlFlow("if($RESULT!= null)") methodBuilder.addStatement("$REPLY.writeInt(1)") methodBuilder.addStatement("android.text.TextUtils.writeToParcel($RESULT, $REPLY, 0)") methodBuilder.endControlFlow() methodBuilder.beginControlFlow("else") methodBuilder.addStatement("$REPLY.writeInt(0)") methodBuilder.endControlFlow() } } override fun readResultsFromProxy(methodType: ExecutableElement, methodBuilder: FunSpec.Builder) { val resultType = methodType.getReturnAsKotlinType() val resultMirror = methodType.getReturnAsTypeMirror() if (resultMirror.kind == TypeKind.ARRAY) { logError("CharSequence[] cannot be marshalled") } else { methodBuilder.beginControlFlow("if($REPLY.readInt() != 0)") methodBuilder.addStatement("$RESULT = android.text.TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel($REPLY)") methodBuilder.endControlFlow() methodBuilder.beginControlFlow("else") if (resultType.isNullable) { methodBuilder.addStatement("$RESULT = null") } else { methodBuilder.addStatement("throw %T(\"Unexpected null result\")", NullPointerException::class) } methodBuilder.endControlFlow() } } override fun writeParamsToStub(methodType: ExecutableElement, param: VariableElement, paramType: ParamType, paramName: String, methodBuilder: FunSpec.Builder) { super.writeParamsToStub(methodType, param, paramType, paramName, methodBuilder) if (param.asType().kind == TypeKind.ARRAY) { logError("CharSequence[] cannot be marshalled") } else { methodBuilder.beginControlFlow("if($DATA.readInt() != 0)") methodBuilder.addStatement("$paramName = android.text.TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel($DATA)") methodBuilder.endControlFlow() methodBuilder.beginControlFlow("else") if (param.isNullable()) { methodBuilder.addStatement("$paramName = null") } else { methodBuilder.addStatement("throw %T(\"Not expecting null\")", NullPointerException::class.java) } methodBuilder.endControlFlow() } } }
apache-2.0
99a272b1a7947a9eb003f58bb4a70bdf
48.404762
164
0.656627
5.453351
false
false
false
false
Kotlin/dokka
core/src/main/kotlin/pages/ContentNodes.kt
1
15929
package org.jetbrains.dokka.pages import org.jetbrains.dokka.links.DRI import org.jetbrains.dokka.model.DisplaySourceSet import org.jetbrains.dokka.model.WithChildren import org.jetbrains.dokka.model.properties.PropertyContainer import org.jetbrains.dokka.model.properties.WithExtraProperties data class DCI(val dri: Set<DRI>, val kind: Kind) { override fun toString() = "$dri[$kind]" } interface ContentNode : WithExtraProperties<ContentNode>, WithChildren<ContentNode> { val dci: DCI val sourceSets: Set<DisplaySourceSet> val style: Set<Style> fun hasAnyContent(): Boolean fun withSourceSets(sourceSets: Set<DisplaySourceSet>): ContentNode override val children: List<ContentNode> get() = emptyList() } /** Simple text */ data class ContentText( val text: String, override val dci: DCI, override val sourceSets: Set<DisplaySourceSet>, override val style: Set<Style> = emptySet(), override val extra: PropertyContainer<ContentNode> = PropertyContainer.empty() ) : ContentNode { override fun withNewExtras(newExtras: PropertyContainer<ContentNode>): ContentText = copy(extra = newExtras) override fun withSourceSets(sourceSets: Set<DisplaySourceSet>): ContentText = copy(sourceSets = sourceSets) override fun hasAnyContent(): Boolean = text.isNotBlank() } data class ContentBreakLine( override val sourceSets: Set<DisplaySourceSet>, override val dci: DCI = DCI(emptySet(), ContentKind.Empty), override val style: Set<Style> = emptySet(), override val extra: PropertyContainer<ContentNode> = PropertyContainer.empty() ) : ContentNode { override fun withNewExtras(newExtras: PropertyContainer<ContentNode>): ContentBreakLine = copy(extra = newExtras) override fun withSourceSets(sourceSets: Set<DisplaySourceSet>): ContentBreakLine = copy(sourceSets = sourceSets) override fun hasAnyContent(): Boolean = true } /** Headers */ data class ContentHeader( override val children: List<ContentNode>, val level: Int, override val dci: DCI, override val sourceSets: Set<DisplaySourceSet>, override val style: Set<Style>, override val extra: PropertyContainer<ContentNode> = PropertyContainer.empty() ) : ContentComposite { constructor(level: Int, c: ContentComposite) : this(c.children, level, c.dci, c.sourceSets, c.style, c.extra) override fun withNewExtras(newExtras: PropertyContainer<ContentNode>): ContentHeader = copy(extra = newExtras) override fun transformChildren(transformer: (ContentNode) -> ContentNode): ContentHeader = copy(children = children.map(transformer)) override fun withSourceSets(sourceSets: Set<DisplaySourceSet>): ContentHeader = copy(sourceSets = sourceSets) } interface ContentCode : ContentComposite /** Code blocks */ data class ContentCodeBlock( override val children: List<ContentNode>, val language: String, override val dci: DCI, override val sourceSets: Set<DisplaySourceSet>, override val style: Set<Style>, override val extra: PropertyContainer<ContentNode> = PropertyContainer.empty() ) : ContentCode { override fun withNewExtras(newExtras: PropertyContainer<ContentNode>): ContentCodeBlock = copy(extra = newExtras) override fun transformChildren(transformer: (ContentNode) -> ContentNode): ContentCodeBlock = copy(children = children.map(transformer)) override fun withSourceSets(sourceSets: Set<DisplaySourceSet>): ContentCodeBlock = copy(sourceSets = sourceSets) } data class ContentCodeInline( override val children: List<ContentNode>, val language: String, override val dci: DCI, override val sourceSets: Set<DisplaySourceSet>, override val style: Set<Style>, override val extra: PropertyContainer<ContentNode> = PropertyContainer.empty() ) : ContentCode { override fun withNewExtras(newExtras: PropertyContainer<ContentNode>): ContentCodeInline = copy(extra = newExtras) override fun transformChildren(transformer: (ContentNode) -> ContentNode): ContentCodeInline = copy(children = children.map(transformer)) override fun withSourceSets(sourceSets: Set<DisplaySourceSet>): ContentCodeInline = copy(sourceSets = sourceSets) } /** Union type replacement */ interface ContentLink : ContentComposite /** All links to classes, packages, etc. that have te be resolved */ data class ContentDRILink( override val children: List<ContentNode>, val address: DRI, override val dci: DCI, override val sourceSets: Set<DisplaySourceSet>, override val style: Set<Style> = emptySet(), override val extra: PropertyContainer<ContentNode> = PropertyContainer.empty() ) : ContentLink { override fun withNewExtras(newExtras: PropertyContainer<ContentNode>): ContentDRILink = copy(extra = newExtras) override fun transformChildren(transformer: (ContentNode) -> ContentNode): ContentDRILink = copy(children = children.map(transformer)) override fun withSourceSets(sourceSets: Set<DisplaySourceSet>): ContentDRILink = copy(sourceSets = sourceSets) } /** All links that do not need to be resolved */ data class ContentResolvedLink( override val children: List<ContentNode>, val address: String, override val dci: DCI, override val sourceSets: Set<DisplaySourceSet>, override val style: Set<Style> = emptySet(), override val extra: PropertyContainer<ContentNode> = PropertyContainer.empty() ) : ContentLink { override fun withNewExtras(newExtras: PropertyContainer<ContentNode>): ContentResolvedLink = copy(extra = newExtras) override fun transformChildren(transformer: (ContentNode) -> ContentNode): ContentResolvedLink = copy(children = children.map(transformer)) override fun withSourceSets(sourceSets: Set<DisplaySourceSet>): ContentResolvedLink = copy(sourceSets = sourceSets) } /** Embedded resources like images */ data class ContentEmbeddedResource( override val children: List<ContentNode> = emptyList(), val address: String, val altText: String?, override val dci: DCI, override val sourceSets: Set<DisplaySourceSet>, override val style: Set<Style> = emptySet(), override val extra: PropertyContainer<ContentNode> = PropertyContainer.empty() ) : ContentLink { override fun withNewExtras(newExtras: PropertyContainer<ContentNode>): ContentEmbeddedResource = copy(extra = newExtras) override fun transformChildren(transformer: (ContentNode) -> ContentNode): ContentEmbeddedResource = copy(children = children.map(transformer)) override fun withSourceSets(sourceSets: Set<DisplaySourceSet>): ContentEmbeddedResource = copy(sourceSets = sourceSets) } /** Logical grouping of [ContentNode]s */ interface ContentComposite : ContentNode { override val children: List<ContentNode> // overwrite to make it abstract once again override val sourceSets: Set<DisplaySourceSet> get() = children.flatMap { it.sourceSets }.toSet() fun transformChildren(transformer: (ContentNode) -> ContentNode): ContentComposite override fun hasAnyContent(): Boolean = children.any { it.hasAnyContent() } } /** Tables */ data class ContentTable( val header: List<ContentGroup>, val caption: ContentGroup? = null, override val children: List<ContentGroup>, override val dci: DCI, override val sourceSets: Set<DisplaySourceSet>, override val style: Set<Style>, override val extra: PropertyContainer<ContentNode> = PropertyContainer.empty() ) : ContentComposite { override fun withNewExtras(newExtras: PropertyContainer<ContentNode>): ContentTable = copy(extra = newExtras) override fun transformChildren(transformer: (ContentNode) -> ContentNode): ContentTable = copy(children = children.map(transformer).map { it as ContentGroup }) override fun withSourceSets(sourceSets: Set<DisplaySourceSet>): ContentTable = copy(sourceSets = sourceSets) } /** Lists */ data class ContentList( override val children: List<ContentNode>, val ordered: Boolean, override val dci: DCI, override val sourceSets: Set<DisplaySourceSet>, override val style: Set<Style>, override val extra: PropertyContainer<ContentNode> = PropertyContainer.empty() ) : ContentComposite { override fun withNewExtras(newExtras: PropertyContainer<ContentNode>): ContentList = copy(extra = newExtras) override fun transformChildren(transformer: (ContentNode) -> ContentNode): ContentList = copy(children = children.map(transformer)) override fun withSourceSets(sourceSets: Set<DisplaySourceSet>): ContentList = copy(sourceSets = sourceSets) } /** Default group, eg. for blocks of Functions, Properties, etc. **/ data class ContentGroup( override val children: List<ContentNode>, override val dci: DCI, override val sourceSets: Set<DisplaySourceSet>, override val style: Set<Style>, override val extra: PropertyContainer<ContentNode> = PropertyContainer.empty() ) : ContentComposite { override fun withNewExtras(newExtras: PropertyContainer<ContentNode>): ContentGroup = copy(extra = newExtras) override fun transformChildren(transformer: (ContentNode) -> ContentNode): ContentGroup = copy(children = children.map(transformer)) override fun withSourceSets(sourceSets: Set<DisplaySourceSet>): ContentGroup = copy(sourceSets = sourceSets) } /** * @property groupID is used for finding and copying [ContentDivergentInstance]s when merging [ContentPage]s */ data class ContentDivergentGroup( override val children: List<ContentDivergentInstance>, override val dci: DCI, override val style: Set<Style>, override val extra: PropertyContainer<ContentNode>, val groupID: GroupID, val implicitlySourceSetHinted: Boolean = true ) : ContentComposite { data class GroupID(val name: String) override val sourceSets: Set<DisplaySourceSet> get() = children.flatMap { it.sourceSets }.distinct().toSet() override fun withNewExtras(newExtras: PropertyContainer<ContentNode>): ContentDivergentGroup = copy(extra = newExtras) override fun transformChildren(transformer: (ContentNode) -> ContentNode): ContentDivergentGroup = copy(children = children.map(transformer).map { it as ContentDivergentInstance }) override fun withSourceSets(sourceSets: Set<DisplaySourceSet>): ContentDivergentGroup = this } /** Instance of a divergent content */ data class ContentDivergentInstance( val before: ContentNode?, val divergent: ContentNode, val after: ContentNode?, override val dci: DCI, override val sourceSets: Set<DisplaySourceSet>, override val style: Set<Style>, override val extra: PropertyContainer<ContentNode> = PropertyContainer.empty() ) : ContentComposite { override val children: List<ContentNode> get() = listOfNotNull(before, divergent, after) override fun withNewExtras(newExtras: PropertyContainer<ContentNode>): ContentDivergentInstance = copy(extra = newExtras) override fun transformChildren(transformer: (ContentNode) -> ContentNode): ContentDivergentInstance = copy( before = before?.let(transformer), divergent = divergent.let(transformer), after = after?.let(transformer) ) override fun withSourceSets(sourceSets: Set<DisplaySourceSet>): ContentDivergentInstance = copy(sourceSets = sourceSets) } data class PlatformHintedContent( val inner: ContentNode, override val sourceSets: Set<DisplaySourceSet> ) : ContentComposite { override val children = listOf(inner) override val dci: DCI get() = inner.dci override val extra: PropertyContainer<ContentNode> get() = inner.extra override val style: Set<Style> get() = inner.style override fun withNewExtras(newExtras: PropertyContainer<ContentNode>) = throw UnsupportedOperationException("This method should not be called on this PlatformHintedContent") override fun transformChildren(transformer: (ContentNode) -> ContentNode): PlatformHintedContent = copy(inner = transformer(inner)) override fun withSourceSets(sourceSets: Set<DisplaySourceSet>): PlatformHintedContent = copy(sourceSets = sourceSets) } interface Style interface Kind /** * [ContentKind] represents a grouping of content of one kind that can can be rendered * as part of a composite page (one tab/block within a class's page, for instance). */ enum class ContentKind : Kind { /** * Marks all sorts of signatures. Can contain sub-kinds marked as [SymbolContentKind] * * Some examples: * - primary constructor: `data class CoroutineName(name: String) : AbstractCoroutineContextElement` * - constructor: `fun CoroutineName(name: String)` * - function: `open override fun toString(): String` * - property: `val name: String` */ Symbol, Comment, Constructors, Functions, Parameters, Properties, Classlikes, Packages, Sample, Main, BriefComment, Empty, Source, TypeAliases, Cover, Inheritors, SourceSetDependentHint, Extensions, Annotations, /** * Deprecation details block with related information such as message/replaceWith/level. */ Deprecation; companion object { private val platformTagged = setOf( Constructors, Functions, Properties, Classlikes, Packages, Source, TypeAliases, Inheritors, Extensions ) fun shouldBePlatformTagged(kind: Kind): Boolean = kind in platformTagged } } /** * Content kind for [ContentKind.Symbol] content, which is essentially about signatures */ enum class SymbolContentKind : Kind { /** * Marks constructor/function parameters, everything in-between parentheses. * * For function `fun foo(bar: String, baz: Int, qux: Boolean)`, * the parameters would be the whole of `bar: String, baz: Int, qux: Boolean` */ Parameters, /** * Marks a single parameter in a function. Most likely to be a child of [Parameters]. * * In function `fun foo(bar: String, baz: Int, qux: Boolean)` there would be 3 [Parameter] instances: * - `bar: String, ` * - `baz: Int, ` * - `qux: Boolean` */ Parameter, } enum class TokenStyle : Style { Keyword, Punctuation, Function, Operator, Annotation, Number, String, Boolean, Constant } enum class TextStyle : Style { Bold, Italic, Strong, Strikethrough, Paragraph, Block, Span, Monospace, Indented, Cover, UnderCoverText, BreakableAfter, Breakable, InlineComment, Quotation, FloatingRight, Var, Underlined } enum class ContentStyle : Style { RowTitle, TabbedContent, WithExtraAttributes, RunnableSample, InDocumentationAnchor, Caption, Wrapped, Indented, KDocTag, Footnote } enum class ListStyle : Style { /** * Represents a list of groups of [DescriptionTerm] and [DescriptionDetails]. * Common uses for this element are to implement a glossary or to display * metadata (a list of key-value pairs). Formatting example: see `<dl>` html tag. */ DescriptionList, /** * If used within [DescriptionList] context, specifies a term in a description * or definition list, usually followed by [DescriptionDetails] for one or more * terms. Formatting example: see `<dt>` html tag */ DescriptionTerm, /** * If used within [DescriptionList] context, provides the definition or other * related text associated with [DescriptionTerm]. Formatting example: see `<dd>` html tag */ DescriptionDetails } object CommentTable : Style object MultimoduleTable : Style fun ContentNode.hasStyle(style: Style) = this.style.contains(style)
apache-2.0
9ddb55093c1fd1a776af154ffe0bb2e5
36.48
118
0.721451
4.581248
false
false
false
false
semonte/intellij-community
platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.kt
2
40057
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.impl import com.intellij.ProjectTopics import com.intellij.configurationStore.SchemeManagerIprProvider import com.intellij.configurationStore.save import com.intellij.execution.* import com.intellij.execution.configurations.* import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ExecutionUtil import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.Disposable 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.diagnostic.logger import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.options.SchemeManager import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.UnknownFeaturesCollector import com.intellij.openapi.util.Key import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.NaturalComparator import com.intellij.util.IconUtil import com.intellij.util.SmartList import com.intellij.util.containers.* import gnu.trove.THashMap import org.jdom.Element import java.util.* import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.locks.ReentrantReadWriteLock import javax.swing.Icon import kotlin.concurrent.read import kotlin.concurrent.write private val SELECTED_ATTR = "selected" internal val METHOD = "method" private val OPTION = "option" // open for Upsource (UpsourceRunManager overrides to disable loadState (empty impl)) @State(name = "RunManager", defaultStateAsResource = true, storages = arrayOf(Storage(StoragePathMacros.WORKSPACE_FILE))) open class RunManagerImpl(internal val project: Project) : RunManagerEx(), PersistentStateComponent<Element>, Disposable { companion object { @JvmField val CONFIGURATION = "configuration" private val RECENT = "recent_temporary" @JvmField val NAME_ATTR = "name" internal val LOG = logger<RunManagerImpl>() @JvmStatic fun getInstanceImpl(project: Project) = RunManager.getInstance(project) as RunManagerImpl @JvmStatic fun canRunConfiguration(environment: ExecutionEnvironment): Boolean { return environment.runnerAndConfigurationSettings?.let { canRunConfiguration(it, environment.executor) } ?: false } @JvmStatic fun canRunConfiguration(configuration: RunnerAndConfigurationSettings, executor: Executor): Boolean { try { configuration.checkSettings(executor) } catch (ignored: IndexNotReadyException) { return Registry.`is`("dumb.aware.run.configurations") } catch (ignored: RuntimeConfigurationError) { return false } catch (ignored: RuntimeConfigurationException) { } return true } } private val lock = ReentrantReadWriteLock() private val idToType = LinkedHashMap<String, ConfigurationType>() private val templateIdToConfiguration = THashMap<String, RunnerAndConfigurationSettingsImpl>() // template configurations are not included here private val idToSettings = LinkedHashMap<String, RunnerAndConfigurationSettings>() // When readExternal not all configuration may be loaded, so we need to remember the selected configuration // so that when it is eventually loaded, we can mark is as a selected. private var selectedConfigurationId: String? = null private val iconCache = TimedIconCache() private val _config by lazy { RunManagerConfig(PropertiesComponent.getInstance(project)) } private var isCustomOrderApplied = true set(value) { if (field != value) { field = value if (!value) { immutableSortedSettingsList = null } } } private val customOrder = ObjectIntHashMap<String>() private val recentlyUsedTemporaries = ArrayList<RunnerAndConfigurationSettings>() private val schemeManagerProvider = SchemeManagerIprProvider("configuration") @Suppress("LeakingThis") private val workspaceSchemeManager = SchemeManagerFactory.getInstance(project).create("workspace", RunConfigurationSchemeManager(this, false), streamProvider = schemeManagerProvider, autoSave = false) @Suppress("LeakingThis") private var projectSchemeManager = if (isUseProjectSchemeManager()) SchemeManagerFactory.getInstance(project).create("runConfigurations", RunConfigurationSchemeManager(this, true), isUseOldFileNameSanitize = true) else null private val isFirstLoadState = AtomicBoolean() private val stringIdToBeforeRunProvider by lazy { val result = ContainerUtil.newConcurrentMap<String, BeforeRunTaskProvider<*>>() for (provider in BeforeRunTaskProvider.EXTENSION_POINT_NAME.getExtensions(project)) { result.put(provider.id.toString(), provider) } result } private val eventPublisher: RunManagerListener get() = project.messageBus.syncPublisher(RunManagerListener.TOPIC) init { initializeConfigurationTypes(ConfigurationType.CONFIGURATION_TYPE_EP.extensions) project.messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) { selectedConfiguration?.let { iconCache.remove(it.uniqueID) } } }) } // separate method needed for tests fun initializeConfigurationTypes(factories: Array<ConfigurationType>) { val types = factories.toMutableList() types.sortBy { it.displayName } types.add(UnknownConfigurationType.INSTANCE) for (type in types) { idToType.put(type.id, type) } } override fun createConfiguration(name: String, factory: ConfigurationFactory): RunnerAndConfigurationSettings { val template = getConfigurationTemplate(factory) return createConfiguration(factory.createConfiguration(name, template.configuration), template) } override fun createConfiguration(runConfiguration: RunConfiguration, factory: ConfigurationFactory) = createConfiguration(runConfiguration, getConfigurationTemplate(factory)) private fun createConfiguration(configuration: RunConfiguration, template: RunnerAndConfigurationSettingsImpl): RunnerAndConfigurationSettings { val settings = RunnerAndConfigurationSettingsImpl(this, configuration, false) settings.importRunnerAndConfigurationSettings(template) if (!settings.isShared) { shareConfiguration(settings, template.isShared) } return settings } override fun dispose() { lock.write { templateIdToConfiguration.clear() } } override fun getConfig() = _config override val configurationFactories by lazy { idToType.values.toTypedArray() } override val configurationFactoriesWithoutUnknown: List<ConfigurationType> get() = idToType.values.filterSmart { it !is UnknownConfigurationType } /** * Template configuration is not included */ override fun getConfigurationsList(type: ConfigurationType): List<RunConfiguration> { var result: MutableList<RunConfiguration>? = null for (settings in allSettings) { val configuration = settings.configuration if (type.id == configuration.type.id) { if (result == null) { result = SmartList<RunConfiguration>() } result.add(configuration) } } return result ?: emptyList() } override val allConfigurationsList: List<RunConfiguration> get() = allSettings.mapSmart { it.configuration } fun getSettings(configuration: RunConfiguration) = allSettings.firstOrNull { it.configuration === configuration } as? RunnerAndConfigurationSettingsImpl override fun getConfigurationSettingsList(type: ConfigurationType) = allSettings.filterSmart { it.type.id == type.id } override fun getStructure(type: ConfigurationType): Map<String, List<RunnerAndConfigurationSettings>> { val result = LinkedHashMap<String?, MutableList<RunnerAndConfigurationSettings>>() val typeList = SmartList<RunnerAndConfigurationSettings>() val settings = getConfigurationSettingsList(type) for (setting in settings) { val folderName = setting.folderName if (folderName == null) { typeList.add(setting) } else { result.getOrPut(folderName) { SmartList() }.add(setting) } } result.put(null, Collections.unmodifiableList(typeList)) return Collections.unmodifiableMap(result) } override fun getConfigurationTemplate(factory: ConfigurationFactory): RunnerAndConfigurationSettingsImpl { val key = "${factory.type.id}.${factory.name}" return lock.read { templateIdToConfiguration.get(key) } ?: lock.write { templateIdToConfiguration.getOrPut(key) { val template = createTemplateSettings(factory) (template.configuration as? UnknownRunConfiguration)?.let { it.isDoNotStore = true } workspaceSchemeManager.addScheme(template) template } } } internal fun createTemplateSettings(factory: ConfigurationFactory) = RunnerAndConfigurationSettingsImpl(this, factory.createTemplateConfiguration(project, this), isTemplate = true, singleton = factory.isConfigurationSingletonByDefault) override fun addConfiguration(settings: RunnerAndConfigurationSettings, isShared: Boolean) { (settings as RunnerAndConfigurationSettingsImpl).isShared = isShared addConfiguration(settings) } override fun addConfiguration(settings: RunnerAndConfigurationSettings) { val newId = settings.uniqueID var existingId: String? = null lock.write { immutableSortedSettingsList = null // https://youtrack.jetbrains.com/issue/IDEA-112821 // we should check by instance, not by id (todo is it still relevant?) existingId = if (idToSettings.get(newId) === settings) newId else findExistingConfigurationId(settings) existingId?.let { if (newId != it) { idToSettings.remove(it) } } idToSettings.put(newId, settings) if (selectedConfigurationId != null && selectedConfigurationId == existingId) { selectedConfigurationId = newId } if (existingId == null) { refreshUsagesList(settings) settings.schemeManager?.addScheme(settings as RunnerAndConfigurationSettingsImpl) } else { (if (settings.isShared) workspaceSchemeManager else projectSchemeManager)?.removeScheme(settings as RunnerAndConfigurationSettingsImpl) } } if (existingId == null) { if (settings.isTemporary) { checkRecentsLimit() } eventPublisher.runConfigurationAdded(settings) } else { eventPublisher.runConfigurationChanged(settings, existingId) } } private val RunnerAndConfigurationSettings.schemeManager: SchemeManager<RunnerAndConfigurationSettingsImpl>? get() = if (isShared) projectSchemeManager else workspaceSchemeManager override fun refreshUsagesList(profile: RunProfile) { if (profile !is RunConfiguration) { return } getSettings(profile)?.let { refreshUsagesList(it) } } private fun refreshUsagesList(settings: RunnerAndConfigurationSettings) { if (settings.isTemporary) { lock.write { recentlyUsedTemporaries.remove(settings) recentlyUsedTemporaries.add(0, settings) trimUsagesListToLimit() } } } // call only under write lock private fun trimUsagesListToLimit() { while (recentlyUsedTemporaries.size > config.recentsLimit) { recentlyUsedTemporaries.removeAt(recentlyUsedTemporaries.size - 1) } } fun checkRecentsLimit() { var removed: MutableList<RunnerAndConfigurationSettings>? = null lock.write { trimUsagesListToLimit() var excess = idToSettings.values.count { it.isTemporary } - config.recentsLimit if (excess <= 0) { return } for (settings in idToSettings.values) { if (settings.isTemporary && !recentlyUsedTemporaries.contains(settings)) { if (removed == null) { removed = SmartList<RunnerAndConfigurationSettings>() } removed!!.add(settings) if (--excess <= 0) { break } } } } removed?.let { removeConfigurations(it) } } // comparator is null if want just to save current order (e.g. if want to keep order even after reload) // yes, on hot reload, because our ProjectRunConfigurationManager doesn't use SchemeManager and change of some RC file leads to reload of all configurations fun setOrder(comparator: Comparator<RunnerAndConfigurationSettings>?) { lock.write { val sorted = idToSettings.values.filterTo(ArrayList(idToSettings.size)) { it.type !is UnknownConfigurationType } if (comparator != null) { sorted.sortWith(comparator) } customOrder.clear() customOrder.ensureCapacity(sorted.size) sorted.mapIndexed { index, settings -> customOrder.put(settings.uniqueID, index) } immutableSortedSettingsList = null isCustomOrderApplied = false } } override var selectedConfiguration: RunnerAndConfigurationSettings? get() = selectedConfigurationId?.let { lock.read { idToSettings.get(it) } } set(value) { if (value?.uniqueID == selectedConfigurationId) { return } selectedConfigurationId = value?.uniqueID eventPublisher.runConfigurationSelected() } @Volatile private var immutableSortedSettingsList: List<RunnerAndConfigurationSettings>? = emptyList() fun requestSort() { lock.write { if (customOrder.isEmpty) { sortAlphabetically() } else { isCustomOrderApplied = false } immutableSortedSettingsList = null allSettings } } override val allSettings: List<RunnerAndConfigurationSettings> get() { immutableSortedSettingsList?.let { return it } lock.write { immutableSortedSettingsList?.let { return it } if (idToSettings.isEmpty()) { immutableSortedSettingsList = emptyList() return immutableSortedSettingsList!! } // IDEA-63663 Sort run configurations alphabetically if clean checkout if (!isCustomOrderApplied && !customOrder.isEmpty) { val list = idToSettings.values.toTypedArray() val folderNames = SmartList<String>() for (settings in list) { val folderName = settings.folderName if (folderName != null && !folderNames.contains(folderName)) { folderNames.add(folderName) } } folderNames.sortWith(NaturalComparator.INSTANCE) folderNames.add(null) list.sortWith(Comparator { o1, o2 -> if (o1.folderName != o2.folderName) { val i1 = folderNames.indexOf(o1.folderName) val i2 = folderNames.indexOf(o2.folderName) if (i1 != i2) { return@Comparator i1 - i2 } } val temporary1 = o1.isTemporary val temporary2 = o2.isTemporary when { temporary1 == temporary2 -> { val index1 = customOrder.get(o1.uniqueID) val index2 = customOrder.get(o2.uniqueID) if (index1 == -1 && index2 == -1) { o1.name.compareTo(o2.name) } else { index1 - index2 } } temporary1 -> 1 else -> -1 } }) isCustomOrderApplied = true idToSettings.clear() for (settings in list) { idToSettings.put(settings.uniqueID, settings) } } val result = Collections.unmodifiableList(idToSettings.values.toList()) immutableSortedSettingsList = result return result } } private fun sortAlphabetically() { if (idToSettings.isEmpty()) { return } val list = idToSettings.values.sortedWith(Comparator { o1, o2 -> val temporary1 = o1.isTemporary val temporary2 = o2.isTemporary when { temporary1 == temporary2 -> o1.uniqueID.compareTo(o2.uniqueID) temporary1 -> 1 else -> -1 } }) idToSettings.clear() for (settings in list) { idToSettings.put(settings.uniqueID, settings) } } override fun getState(): Element { val element = Element("state") workspaceSchemeManager.save() lock.read { // backward compatibility - write templates in the end schemeManagerProvider.writeState(element, Comparator { n1, n2 -> val w1 = if (n1.startsWith("<template> of ")) 1 else 0 val w2 = if (n2.startsWith("<template> of ")) 1 else 0 if (w1 != w2) { w1 - w2 } else { n1.compareTo(n2) } }) selectedConfiguration?.let { element.setAttribute(SELECTED_ATTR, it.uniqueID) } if (idToSettings.size > 1) { var order: MutableList<String>? = null for (settings in idToSettings.values) { if (settings.type is UnknownConfigurationType) { continue } if (order == null) { order = ArrayList(idToSettings.size) } order.add(settings.uniqueID) } if (order != null) { @Suppress("DEPRECATION") com.intellij.openapi.util.JDOMExternalizableStringList.writeList(order, element) } } val recentList = SmartList<String>() for (settings in recentlyUsedTemporaries) { if (settings.type is UnknownConfigurationType) { continue } recentList.add(settings.uniqueID) } if (!recentList.isEmpty()) { val recent = Element(RECENT) element.addContent(recent) @Suppress("DEPRECATION") com.intellij.openapi.util.JDOMExternalizableStringList.writeList(recentList, recent) } } return element } fun writeContext(element: Element) { for (setting in allSettings) { if (setting.isTemporary) { element.addContent((setting as RunnerAndConfigurationSettingsImpl).writeScheme()) } } selectedConfiguration?.let { element.setAttribute(SELECTED_ATTR, it.uniqueID) } } fun writeConfigurations(parentNode: Element, settings: Collection<RunnerAndConfigurationSettings>) { settings.forEach { parentNode.addContent((it as RunnerAndConfigurationSettingsImpl).writeScheme()) } } internal fun writeBeforeRunTasks(settings: RunnerAndConfigurationSettings, configuration: RunConfiguration): Element? { var tasks = if (settings.isTemplate) configuration.beforeRunTasks else getEffectiveBeforeRunTasks(configuration, ownIsOnlyEnabled = false, isDisableTemplateTasks = false) if (!tasks.isEmpty() && !settings.isTemplate) { val templateTasks = getTemplateBeforeRunTasks(getConfigurationTemplate(configuration.factory).configuration) if (!templateTasks.isEmpty()) { var index = 0 for (templateTask in templateTasks) { if (!templateTask.isEnabled) { continue } if (templateTask == tasks.get(index)) { index++ } else { break } } if (index > 0) { tasks = tasks.subList(index, tasks.size) } } } if (tasks.isEmpty() && settings.isNewSerializationAllowed) { return null } val methodElement = Element(METHOD) for (task in tasks) { val child = Element(OPTION) child.setAttribute(NAME_ATTR, task.providerId.toString()) task.writeExternal(child) methodElement.addContent(child) } return methodElement } override fun noStateLoaded() { isFirstLoadState.set(false) projectSchemeManager?.loadSchemes() } override fun loadState(parentNode: Element) { val oldSelectedConfigurationId: String? val isFirstLoadState = isFirstLoadState.compareAndSet(true, false) if (isFirstLoadState) { oldSelectedConfigurationId = null } else { oldSelectedConfigurationId = selectedConfigurationId clear(false) } schemeManagerProvider.load(parentNode) { var name = it.getAttributeValue("name") if (name == "<template>" || name == null) { // scheme name must be unique it.getAttributeValue("type")?.let { if (name == null) { name = "<template>" } name += " of type ${it}" } } name } workspaceSchemeManager.reload() val order = ArrayList<String>() @Suppress("DEPRECATION") com.intellij.openapi.util.JDOMExternalizableStringList.readList(order, parentNode) lock.write { customOrder.clear() customOrder.ensureCapacity(order.size) order.mapIndexed { index, id -> customOrder.put(id, index) } // ProjectRunConfigurationManager will not call requestSort if no shared configurations requestSort() recentlyUsedTemporaries.clear() val recentNode = parentNode.getChild(RECENT) if (recentNode != null) { val list = SmartList<String>() @Suppress("DEPRECATION") com.intellij.openapi.util.JDOMExternalizableStringList.readList(list, recentNode) for (id in list) { idToSettings.get(id)?.let { recentlyUsedTemporaries.add(it) } } } immutableSortedSettingsList = null selectedConfigurationId = parentNode.getAttributeValue(SELECTED_ATTR) } if (isFirstLoadState) { projectSchemeManager?.loadSchemes() } fireBeforeRunTasksUpdated() if (!isFirstLoadState && oldSelectedConfigurationId != null && oldSelectedConfigurationId != selectedConfigurationId) { eventPublisher.runConfigurationSelected() } } fun readContext(parentNode: Element) { var selectedConfigurationId = parentNode.getAttributeValue(SELECTED_ATTR) for (element in parentNode.children) { val config = loadConfiguration(element, false) if (selectedConfigurationId == null && element.getAttributeValue(SELECTED_ATTR).toBoolean()) { selectedConfigurationId = config.uniqueID } } this.selectedConfigurationId = selectedConfigurationId eventPublisher.runConfigurationSelected() } override fun hasSettings(settings: RunnerAndConfigurationSettings) = lock.read { idToSettings.get(settings.uniqueID) == settings } private fun findExistingConfigurationId(settings: RunnerAndConfigurationSettings): String? { for ((key, value) in idToSettings) { if (value === settings) { return key } } return null } // used by MPS, don't delete fun clearAll() { clear(true) idToType.clear() initializeConfigurationTypes(emptyArray()) } private fun clear(allConfigurations: Boolean) { val removedConfigurations = lock.write { immutableSortedSettingsList = null val configurations = if (allConfigurations) { val configurations = idToSettings.values.toList() idToSettings.clear() selectedConfigurationId = null configurations } else { val configurations = SmartList<RunnerAndConfigurationSettings>() val iterator = idToSettings.values.iterator() for (configuration in iterator) { if (configuration.isTemporary || !configuration.isShared) { iterator.remove() configurations.add(configuration) } } selectedConfigurationId?.let { if (idToSettings.containsKey(it)) { selectedConfigurationId = null } } configurations } templateIdToConfiguration.clear() recentlyUsedTemporaries.clear() configurations } iconCache.clear() val eventPublisher = eventPublisher removedConfigurations.forEach { eventPublisher.runConfigurationRemoved(it) } } fun loadConfiguration(element: Element, isShared: Boolean): RunnerAndConfigurationSettings { val settings = RunnerAndConfigurationSettingsImpl(this) LOG.runAndLogException { settings.readExternal(element, isShared) } addConfiguration(element, settings) return settings } internal fun addConfiguration(element: Element, settings: RunnerAndConfigurationSettingsImpl) { if (settings.isTemplate) { val factory = settings.factory lock.write { templateIdToConfiguration.put("${factory.type.id}.${factory.name}", settings) } } else { addConfiguration(settings) if (element.getAttributeValue(SELECTED_ATTR).toBoolean()) { // to support old style selectedConfiguration = settings } } } internal fun readStepsBeforeRun(child: Element, settings: RunnerAndConfigurationSettings): List<BeforeRunTask<*>> { var result: MutableList<BeforeRunTask<*>>? = null for (methodElement in child.getChildren(OPTION)) { val key = methodElement.getAttributeValue(NAME_ATTR) val provider = stringIdToBeforeRunProvider.getOrPut(key) { UnknownBeforeRunTaskProvider(key) } val beforeRunTask = (if (provider is RunConfigurationBeforeRunProvider) provider.createTask(settings.configuration, this) else provider.createTask(settings.configuration)) ?: continue beforeRunTask.readExternal(methodElement) if (result == null) { result = SmartList() } result.add(beforeRunTask) } return result ?: emptyList() } override fun getConfigurationType(typeName: String) = idToType.get(typeName) @JvmOverloads fun getFactory(typeName: String?, _factoryName: String?, checkUnknown: Boolean = false): ConfigurationFactory? { var type = idToType.get(typeName) if (type == null) { if (checkUnknown && typeName != null) { UnknownFeaturesCollector.getInstance(project).registerUnknownRunConfiguration(typeName) } type = idToType.get(UnknownConfigurationType.NAME) ?: return null } if (type is UnknownConfigurationType) { return type.getConfigurationFactories().get(0) } val factoryName = _factoryName ?: type.configurationFactories.get(0).name return type.configurationFactories.firstOrNull { it.name == factoryName } } override fun setTemporaryConfiguration(tempConfiguration: RunnerAndConfigurationSettings?) { if (tempConfiguration == null) { return } tempConfiguration.isTemporary = true addConfiguration(tempConfiguration) if (Registry.`is`("select.run.configuration.from.context")) { selectedConfiguration = tempConfiguration } } fun getSharedConfigurations(): List<RunnerAndConfigurationSettings> { var result: MutableList<RunnerAndConfigurationSettings>? = null for (configuration in allSettings) { if (configuration.isShared) { if (result == null) { result = ArrayList<RunnerAndConfigurationSettings>() } result.add(configuration) } } return result ?: emptyList() } override val tempConfigurationsList: List<RunnerAndConfigurationSettings> get() = allSettings.filterSmart { it.isTemporary } override fun makeStable(settings: RunnerAndConfigurationSettings) { settings.isTemporary = false doMakeStable(settings) fireRunConfigurationChanged(settings) } private fun doMakeStable(settings: RunnerAndConfigurationSettings) { lock.write { recentlyUsedTemporaries.remove(settings) immutableSortedSettingsList = null if (!customOrder.isEmpty) { isCustomOrderApplied = false } } } override fun <T : BeforeRunTask<*>> getBeforeRunTasks(taskProviderId: Key<T>): List<T> { val tasks = SmartList<T>() val checkedTemplates = SmartList<RunnerAndConfigurationSettings>() lock.read { for (settings in allSettings) { val configuration = settings.configuration for (task in getBeforeRunTasks(configuration)) { if (task.isEnabled && task.providerId === taskProviderId) { @Suppress("UNCHECKED_CAST") tasks.add(task as T) } else { val template = getConfigurationTemplate(configuration.factory) if (!checkedTemplates.contains(template)) { checkedTemplates.add(template) for (templateTask in getBeforeRunTasks(template.configuration)) { if (templateTask.isEnabled && templateTask.providerId === taskProviderId) { @Suppress("UNCHECKED_CAST") tasks.add(templateTask as T) } } } } } } } return tasks } override fun getConfigurationIcon(settings: RunnerAndConfigurationSettings, withLiveIndicator: Boolean): Icon { val uniqueId = settings.uniqueID if (selectedConfiguration?.uniqueID == uniqueId) { iconCache.checkValidity(uniqueId) } var icon = iconCache.get(uniqueId, settings, project) if (withLiveIndicator) { val runningDescriptors = ExecutionManagerImpl.getInstance(project).getRunningDescriptors { it === settings } when { runningDescriptors.size == 1 -> icon = ExecutionUtil.getLiveIndicator(icon) runningDescriptors.size > 1 -> icon = IconUtil.addText(icon, runningDescriptors.size.toString()) } } return icon } fun getConfigurationById(id: String) = lock.read { idToSettings.get(id) } override fun findConfigurationByName(name: String?): RunnerAndConfigurationSettings? { if (name == null) { return null } return allSettings.firstOrNull { it.name == name } } override fun <T : BeforeRunTask<*>> getBeforeRunTasks(settings: RunConfiguration, taskProviderId: Key<T>): List<T> { if (settings is WrappingRunConfiguration<*>) { return getBeforeRunTasks(settings.peer, taskProviderId) } var result: MutableList<T>? = null for (task in getBeforeRunTasks(settings)) { if (task.providerId === taskProviderId) { if (result == null) { result = SmartList<T>() } @Suppress("UNCHECKED_CAST") result.add(task as T) } } return result ?: emptyList() } override fun getBeforeRunTasks(configuration: RunConfiguration) = getEffectiveBeforeRunTasks(configuration) private fun getEffectiveBeforeRunTasks(configuration: RunConfiguration, ownIsOnlyEnabled: Boolean = true, isDisableTemplateTasks: Boolean = false, newTemplateTasks: List<BeforeRunTask<*>>? = null, newOwnTasks: List<BeforeRunTask<*>>? = null): List<BeforeRunTask<*>> { if (configuration is WrappingRunConfiguration<*>) { return getBeforeRunTasks(configuration.peer) } val ownTasks: List<BeforeRunTask<*>> = newOwnTasks ?: configuration.beforeRunTasks val templateConfiguration = getConfigurationTemplate(configuration.factory).configuration if (templateConfiguration is UnknownRunConfiguration) { return emptyList() } val templateTasks = newTemplateTasks ?: if (templateConfiguration === configuration) { getHardcodedBeforeRunTasks(configuration) } else { getTemplateBeforeRunTasks(templateConfiguration) } // if no own tasks, no need to write if (newTemplateTasks == null && ownTasks.isEmpty()) { return if (isDisableTemplateTasks) emptyList() else templateTasks.filterSmart { !ownIsOnlyEnabled || it.isEnabled } } return getEffectiveBeforeRunTaskList(ownTasks, templateTasks, ownIsOnlyEnabled, isDisableTemplateTasks = isDisableTemplateTasks) } private fun getEffectiveBeforeRunTaskList(ownTasks: List<BeforeRunTask<*>>, templateTasks: List<BeforeRunTask<*>>, ownIsOnlyEnabled: Boolean, isDisableTemplateTasks: Boolean): MutableList<BeforeRunTask<*>> { val idToSet = ownTasks.mapSmartSet { it.providerId } val result = ownTasks.filterSmartMutable { !ownIsOnlyEnabled || it.isEnabled } var i = 0 for (templateTask in templateTasks) { if (templateTask.isEnabled && !idToSet.contains(templateTask.providerId)) { val effectiveTemplateTask = if (isDisableTemplateTasks) { val clone = templateTask.clone() clone.isEnabled = false clone } else { templateTask } result.add(i, effectiveTemplateTask) i++ } } return result } private fun getTemplateBeforeRunTasks(templateConfiguration: RunConfiguration): List<BeforeRunTask<*>> { return templateConfiguration.beforeRunTasks.nullize() ?: getHardcodedBeforeRunTasks(templateConfiguration) } private fun getHardcodedBeforeRunTasks(configuration: RunConfiguration): List<BeforeRunTask<*>> { var result: MutableList<BeforeRunTask<*>>? = null for (provider in Extensions.getExtensions(BeforeRunTaskProvider.EXTENSION_POINT_NAME, project)) { val task = provider.createTask(configuration) if (task != null && task.isEnabled) { configuration.factory.configureBeforeRunTaskDefaults(provider.id, task) if (task.isEnabled) { if (result == null) { result = SmartList<BeforeRunTask<*>>() } result.add(task) } } } return result.orEmpty() } fun shareConfiguration(settings: RunnerAndConfigurationSettings, value: Boolean) { if (settings.isShared == value) { return } if (value && settings.isTemporary) { doMakeStable(settings) } (settings as RunnerAndConfigurationSettingsImpl).isShared = value fireRunConfigurationChanged(settings) } override fun setBeforeRunTasks(configuration: RunConfiguration, tasks: List<BeforeRunTask<*>>, addEnabledTemplateTasksIfAbsent: Boolean) { if (configuration is UnknownRunConfiguration) { return } val result: List<BeforeRunTask<*>> if (addEnabledTemplateTasksIfAbsent) { // copy to be sure that list is immutable result = tasks.mapSmart { it } } else { val templateConfiguration = getConfigurationTemplate(configuration.factory).configuration val templateTasks = if (templateConfiguration === configuration) { getHardcodedBeforeRunTasks(configuration) } else { getTemplateBeforeRunTasks(templateConfiguration) } if (templateConfiguration === configuration) { // we must update all existing configuration tasks to ensure that effective tasks (own + template) are the same as before template configuration change // see testTemplates test lock.read { for (otherSettings in allSettings) { val otherConfiguration = otherSettings.configuration if (otherConfiguration !is WrappingRunConfiguration<*> && otherConfiguration.factory === templateConfiguration.factory) { otherConfiguration.beforeRunTasks = getEffectiveBeforeRunTasks(otherConfiguration, ownIsOnlyEnabled = false, isDisableTemplateTasks = true, newTemplateTasks = tasks) } } } } if (tasks == templateTasks) { result = emptyList() } else { result = getEffectiveBeforeRunTaskList(tasks, templateTasks = templateTasks, ownIsOnlyEnabled = false, isDisableTemplateTasks = true) } } configuration.beforeRunTasks = result fireBeforeRunTasksUpdated() } fun removeNotExistingSharedConfigurations(existing: Set<String>) { var removed: MutableList<RunnerAndConfigurationSettings>? = null lock.write { val iterator = idToSettings.values.iterator() for (settings in iterator) { if (!settings.isTemplate && settings.isShared && !existing.contains(settings.uniqueID)) { if (removed == null) { immutableSortedSettingsList = null removed = SmartList<RunnerAndConfigurationSettings>() } removed!!.add(settings) iterator.remove() } } } if (removed != null) { val publisher = eventPublisher removed?.forEach { publisher.runConfigurationRemoved(it) } } } fun fireBeginUpdate() { eventPublisher.beginUpdate() } fun fireEndUpdate() { eventPublisher.endUpdate() } fun fireRunConfigurationChanged(settings: RunnerAndConfigurationSettings) { eventPublisher.runConfigurationChanged(settings, null) } @Suppress("OverridingDeprecatedMember") override fun addRunManagerListener(listener: RunManagerListener) { project.messageBus.connect().subscribe(RunManagerListener.TOPIC, listener) } fun fireBeforeRunTasksUpdated() { eventPublisher.beforeRunTasksChanged() } override fun removeConfiguration(settings: RunnerAndConfigurationSettings?) { if (settings != null) { removeConfigurations(listOf(settings)) } } fun removeConfigurations(toRemove: Collection<RunnerAndConfigurationSettings>) { if (toRemove.isEmpty()) { return } val changedSettings = SmartList<RunnerAndConfigurationSettings>() val removed = SmartList<RunnerAndConfigurationSettings>() var selectedConfigurationWasRemoved = false lock.write { immutableSortedSettingsList = null val iterator = idToSettings.values.iterator() for (settings in iterator) { if (toRemove.contains(settings)) { if (selectedConfigurationId == settings.uniqueID) { selectedConfigurationWasRemoved = true } iterator.remove() settings.schemeManager?.removeScheme(settings as RunnerAndConfigurationSettingsImpl) recentlyUsedTemporaries.remove(settings) removed.add(settings) iconCache.remove(settings.uniqueID) } else { var isChanged = false val otherConfiguration = settings.configuration val newList = otherConfiguration.beforeRunTasks.nullize()?.toMutableSmartList() ?: continue val beforeRunTaskIterator = newList.iterator() for (task in beforeRunTaskIterator) { if (task is RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask && toRemove.firstOrNull { task.isMySettings(it) } != null) { beforeRunTaskIterator.remove() isChanged = true changedSettings.add(settings) } } if (isChanged) { otherConfiguration.beforeRunTasks = newList } } } } if (selectedConfigurationWasRemoved) { selectedConfiguration = null } removed.forEach { eventPublisher.runConfigurationRemoved(it) } changedSettings.forEach { eventPublisher.runConfigurationChanged(it, null) } } } private fun isUseProjectSchemeManager() = Registry.`is`("runManager.use.schemeManager", false)
apache-2.0
7a5f57ab0683d06473b9f8e13498574b
33.562554
225
0.683301
5.274822
false
true
false
false
mrkirby153/KirBot
src/main/kotlin/me/mrkirby153/KirBot/command/executors/fun/CommandReactionRole.kt
1
6722
package me.mrkirby153.KirBot.command.executors.`fun` import com.mrkirby153.bfs.model.Model import me.mrkirby153.KirBot.Bot import me.mrkirby153.KirBot.command.CommandException import me.mrkirby153.KirBot.command.annotations.Command import me.mrkirby153.KirBot.command.annotations.CommandDescription import me.mrkirby153.KirBot.command.args.CommandContext import me.mrkirby153.KirBot.database.models.guild.ReactionRole import me.mrkirby153.KirBot.module.ModuleManager import me.mrkirby153.KirBot.modules.ReactionRoles import me.mrkirby153.KirBot.user.CLEARANCE_MOD import me.mrkirby153.KirBot.utils.Context import me.mrkirby153.KirBot.utils.FuzzyMatchException import me.mrkirby153.KirBot.utils.GREEN_TICK import me.mrkirby153.KirBot.utils.RED_TICK import me.mrkirby153.KirBot.utils.checkPermissions import me.mrkirby153.KirBot.utils.embed.b import me.mrkirby153.KirBot.utils.embed.embed import me.mrkirby153.KirBot.utils.embed.inlineCode import me.mrkirby153.KirBot.utils.embed.link import me.mrkirby153.KirBot.utils.escapeMarkdown import me.mrkirby153.KirBot.utils.findMessage import me.mrkirby153.KirBot.utils.kirbotGuild import me.mrkirby153.KirBot.utils.sanitize import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.sharding.ShardManager import java.awt.Color import javax.inject.Inject class CommandReactionRole @Inject constructor(private val reactionRoles: ReactionRoles, private val shardManager: ShardManager) { val emojiRegex = Regex("<a?:.*:([0-9]*)>") @Command(name = "list", clearance = CLEARANCE_MOD, parent = "reaction-role", permissions = [Permission.MESSAGE_EMBED_LINKS]) @CommandDescription("Lists the reaction roles configured on the server") fun listRoles(context: Context, cmdContext: CommandContext) { val roles = Model.where(ReactionRole::class.java, "guild_id", context.guild.id).get() if (roles.isEmpty()) { context.channel.sendMessage("No reaction roles are configured!").queue() return } var msg = "" roles.forEach { role -> val roleStr = buildString { append(b("Emote: ")) append("${role.displayString} ") appendln(inlineCode { role.id }) appendln("${b("Role: ")} ${role.role?.name?.escapeMarkdown() ?: "???"}") appendln("${b("Channel: ")} ${role.channel?.asMention ?: "???"}") appendln("${b("Message ID: ")} ${role.messageId}") appendln( "Jump to Message".link( "https://discordapp.com/channels/${role.guildId}/${role.channelId}/${role.messageId}")) appendln() } if (msg.length + roleStr.length >= 2040) { context.channel.sendMessage(embed { description { append(msg) } color = Color.BLUE }.build()).queue() } else { msg += roleStr } } context.channel.sendMessage(embed { description { append(msg) } color = Color.BLUE }.build()).queue() } @Command(name = "add", clearance = CLEARANCE_MOD, parent = "reaction-role", arguments = ["<mid:string>", "<emoji:string>", "<role:string...>"]) @CommandDescription("Adds a reaction role") fun addRole(context: Context, cmdContext: CommandContext) { val messageRaw = cmdContext.getNotNull<String>("mid") val emojiRaw = cmdContext.getNotNull<String>("emoji") val roleRaw = cmdContext.getNotNull<String>("role") val role = try { context.guild.kirbotGuild.matchRole(roleRaw) ?: throw CommandException( "No roles were found") } catch (e: FuzzyMatchException) { when (e) { is FuzzyMatchException.TooManyMatchesException -> throw CommandException( "Too many roles for that search query. Try a more specific query") is FuzzyMatchException.NoMatchesException -> throw CommandException( "No roles found for the given query") else -> throw CommandException(e.localizedMessage) } } // Check if we can use the custom emoji var custom = false var effectiveEmote = emojiRaw if (emojiRegex.matches(emojiRaw)) { custom = true val id = emojiRegex.find(emojiRaw)?.groups?.get(1)?.value ?: throw CommandException( "Regex match failed. This shouldn't happen") var found = false shardManager.guilds.forEach { guild -> if (id in guild.emotes.map { it.id }) found = true } effectiveEmote = id if (!found) { throw CommandException("Cannot use that emote for reaction roles") } } context.channel.sendMessage("Looking up message...").queue { msg -> findMessage(messageRaw).handle { message, throwable -> if (throwable != null) { if (throwable is NoSuchElementException) { msg.editMessage("$RED_TICK The given message was not found!").queue() } else { msg.editMessage("$RED_TICK ${throwable.localizedMessage}").queue() } return@handle } else { if(!message.channel.checkPermissions(Permission.MESSAGE_ADD_REACTION)) { context.send().error("I cannot add reactions to the given message. You will have to add it manually").queue() } reactionRoles.addReactionRole(message, role, effectiveEmote, custom) msg.editMessage("$GREEN_TICK Added $emojiRaw as a reaction role for ${b( role.name.sanitize())}").queue() } } } } @Command(name = "remove", clearance = CLEARANCE_MOD, parent = "reaction-role", arguments = ["<id:string>"]) @CommandDescription("Removes a reaction role from the server") fun removeRole(context: Context, cmdContext: CommandContext) { val id = cmdContext.getNotNull<String>("id") try { reactionRoles.removeReactionRole(id, context.guild) context.send().success("Reaction role has been removed").queue() } catch (e: IllegalArgumentException) { throw CommandException(e.localizedMessage) } } }
mit
b83c6be43f340b0cf9ab9aaa8bcfdd10
42.941176
133
0.598929
4.707283
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UINavigationActivity.kt
1
1850
package com.yy.codex.uikit import android.content.Intent import android.os.Bundle /** * Created by PonyCui_Home on 2017/1/23. */ open class UINavigationActivity: UIActivity() { var navigationController: UINavigationController? = null set(value) { value?.let { it.setRootViewController(nextViewController() ?: rootViewController()) field = it viewController = it } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) navigationController = createNavigationController() } open fun createNavigationController(): UINavigationController { return UINavigationController(this) } private fun nextViewController(): UIViewController? { if (intent is Intent) { val toViewControllerHashCode = intent.getIntExtra("com.yy.codex.uikit.UINavigationController_ActivityBase.toViewController.hashCode", 0) val fromViewControllerHashCode = UINavigationController_ActivityBase.linkingReversingContexts[toViewControllerHashCode] val toViewController = UINavigationController_ActivityBase.hashedViewControllers[toViewControllerHashCode] ?: return null val fromViewController = UINavigationController_ActivityBase.hashedViewControllers[fromViewControllerHashCode] ?: return null val backBarButtonItem = fromViewController.navigationItem.backBarButtonItem ?: return toViewController backBarButtonItem.isSystemBackItem = false toViewController.navigationItem.setLeftBarButtonItem(backBarButtonItem) return toViewController } else { return null } } open fun rootViewController(): UIViewController { return UIViewController(this) } }
gpl-3.0
615c15c664b1e0f3858611961aca0792
36.02
148
0.702162
5.589124
false
false
false
false
michael-johansen/workshop-jb
src/syntax/operatorOverloading.kt
2
1744
package syntax.operatorOverloading fun compareStrings(s1: String?, s2: String?) { s1 == s2 // is compiled to s1?.equals(s2) ?: s2 === null } interface C { operator fun compareTo(other: C): Int } fun test(c1: C, c2: C) { c1 < c2 // is compiled to c1.compareTo(c2) < 0 c1 >= c2 // is compiled to c1.compareTo(c2) >= 0 } interface A interface B { //unary operations operator fun plus() operator fun minus() operator fun inc(): B operator fun dec(): B //binary operations operator fun plus(a: A): B operator fun minus(a: A): B operator fun times(a: A): B operator fun div(a: A): B operator fun mod(a: A): B operator fun rangeTo(a: A): B } @Suppress("UNUSED_CHANGED_VALUE", "UNUSED_VALUE") fun binaryAndUnaryOperations(a: A, b: B) { +b -b b + a b - a b * a b / a b % a b..a var b1 = b b1++ b1-- b1 += a // is compiled to b1 = b1 + a } interface D { operator fun plusAssign(a: A) operator fun minusAssign(a: A) operator fun timesAssign(a: A) operator fun divAssign(a: A) operator fun modAssign(a: A) } fun assignmentOperations(d: D, a: A) { d += a // is compiled to d.plusAssign(a) } interface MyCollection<E> { operator fun contains(e: E): Boolean } fun conventionForIn(c: MyCollection<A>, a: A) { a in c // is compiled to c.contains(a) a !in c // is compiled to !c.contains(a) } interface MyMap<K, V> { operator fun get(k: K): V operator fun set(k: K, v: V) } fun conventionForGet(map: MyMap<A, B>, a: A, b: B) { map[a] // is compiled to map.get(a) map[a] = b // is compiled to map.set(a, b) }
mit
dc9ad7c37c9d0f0d3ed1b50aa404010c
15.941748
52
0.567661
2.971039
false
false
false
false
toastkidjp/Yobidashi_kt
image/src/main/java/jp/toastkid/image/list/ImageLoader.kt
1
2220
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.image.list import android.content.ContentResolver import android.database.Cursor import android.net.Uri import android.provider.MediaStore import jp.toastkid.image.Image /** * @author toastkidjp */ class ImageLoader( private val contentResolver: ContentResolver, private val externalContentUri: Uri = ResolvingUriFinder().invoke() ) { operator fun invoke(sort: Sort, bucket: String): List<Image> { return extractImages( contentResolver.query( externalContentUri, columns, "bucket_display_name = ?", arrayOf(bucket), sort.imageSort ) ) } fun filterBy(name: String?): List<Image> { return extractImages( contentResolver.query( externalContentUri, columns, "${MediaStore.Images.Media.DISPLAY_NAME} LIKE ?", arrayOf("%$name%"), Sort.NAME.imageSort ) ) } private fun extractImages(cursor: Cursor?): MutableList<Image> { val images = mutableListOf<Image>() val dataIndex = cursor?.getColumnIndex(MediaStore.Images.Media.DATA) ?: 0 val displayNameIndex = cursor?.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME) ?: 0 while (cursor?.moveToNext() == true) { images.add(Image(cursor.getString(dataIndex), cursor.getString(displayNameIndex))) } cursor?.close() return images } companion object { private val columns = arrayOf( MediaStore.Images.Media.DATA, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.BUCKET_DISPLAY_NAME, MediaStore.Images.Media.DATE_TAKEN ) } }
epl-1.0
4dab2a012f6ecdb67d315d2c24b0c2e1
31.188406
96
0.596847
4.944321
false
false
false
false
openMF/android-client
mifosng-android/src/main/java/com/mifos/mifosxdroid/online/surveysubmit/SurveySubmitFragment.kt
1
4626
/* * This project is licensed under the open source MPL V2. * See https://github.com/openMF/android-client/blob/master/LICENSE.md */ package com.mifos.mifosxdroid.online.surveysubmit import android.app.Activity import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import android.widget.Toast import butterknife.BindView import butterknife.ButterKnife import butterknife.OnClick import com.mifos.mifosxdroid.R import com.mifos.mifosxdroid.core.MifosBaseActivity import com.mifos.mifosxdroid.core.MifosBaseFragment import com.mifos.mifosxdroid.online.Communicator import com.mifos.mifosxdroid.online.SurveyQuestionActivity import com.mifos.objects.survey.Scorecard import javax.inject.Inject /** * Created by Nasim Banu on 28,January,2016. */ class SurveySubmitFragment : MifosBaseFragment(), Communicator, SurveySubmitMvpView { @JvmField @BindView(R.id.btn_submit) var btn_submit: Button? = null @JvmField @BindView(R.id.survey_submit_textView) var tv_submit: TextView? = null @JvmField @Inject var mSurveySubmitPresenter: SurveySubmitPresenter? = null private var mDetachFragment: DisableSwipe? = null private var mScorecard: Scorecard? = null private var mSurveyId = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (activity as MifosBaseActivity?)!!.activityComponent.inject(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_survey_last, container, false) ButterKnife.bind(this, view) mSurveySubmitPresenter!!.attachView(this) return view } override fun passScoreCardData(scorecard: Scorecard, surveyId: Int) { mScorecard = scorecard mSurveyId = surveyId if (isAdded) { val submitText = resources.getString(R.string.attempt_question) + mScorecard!!.scorecardValues.size tv_submit!!.text = submitText btn_submit!!.text = resources.getString(R.string.submit_survey) } } @OnClick(R.id.btn_submit) fun submitScore() { if (mScorecard!!.scorecardValues.size >= 1) { mDetachFragment!!.disableSwipe() btn_submit!!.text = resources.getString(R.string.submitting_surveys) btn_submit!!.isEnabled = false btn_submit!!.visibility = View.GONE mSurveySubmitPresenter!!.submitSurvey(mSurveyId, mScorecard) } else { Toast.makeText(getContext(), resources .getString(R.string.please_attempt_atleast_one_question), Toast.LENGTH_SHORT) .show() } } override fun showSurveySubmittedSuccessfully(scorecard: Scorecard?) { Toast.makeText(getContext(), resources.getString(R.string.scorecard_created_successfully), Toast.LENGTH_LONG).show() tv_submit!!.text = resources.getString(R.string.survey_successfully_submitted) btn_submit!!.visibility = View.GONE } override fun showError(errorMessage: Int) { Toast.makeText(getContext(), resources.getString(errorMessage), Toast.LENGTH_LONG).show() tv_submit!!.text = resources.getString(R.string.error_submitting_survey) btn_submit!!.visibility = View.GONE } override fun showProgressbar(b: Boolean) { if (b) { showMifosProgressBar() } else { hideMifosProgressBar() } } override fun onDestroyView() { super.onDestroyView() mSurveySubmitPresenter!!.detachView() } override fun onAttach(context: Context) { super.onAttach(context) (context as SurveyQuestionActivity).fragmentCommunicator = this val activity = context as Activity mDetachFragment = try { activity as DisableSwipe } catch (e: ClassCastException) { throw ClassCastException(activity.toString() + " must implement OnAnswerSelectedListener") } } interface DisableSwipe { fun disableSwipe() } companion object { @JvmStatic fun newInstance(): SurveySubmitFragment { val fragment = SurveySubmitFragment() val bundle = Bundle() fragment.arguments = bundle return fragment } } }
mpl-2.0
621a0d926108e7ed1668d52997de67bb
33.022059
98
0.669909
4.63992
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/libanki/Tags.kt
1
12305
/**************************************************************************************** * Copyright (c) 2011 Norbert Nagold <[email protected]> * * Copyright (c) 2012 Kostas Spyropoulos <[email protected]> * * Copyright (c) 2014 Houssam Salem <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.libanki import android.content.ContentValues import android.text.TextUtils import com.ichi2.libanki.backend.model.TagUsnTuple import com.ichi2.libanki.utils.TimeManager import org.json.JSONObject import java.util.* import java.util.regex.Pattern /** * Anki maintains a cache of used tags so it can quickly present a list of tags * for autocomplete and in the browser. For efficiency, deletions are not * tracked, so unused tags can only be removed from the list with a DB check. * * This module manages the tag cache and tags for notes. * * This class differs from the python version by keeping the in-memory tag cache as a TreeMap * instead of a JSONObject. It is much more convenient to work with a TreeMap in Java, but there * may be a performance penalty in doing so (on startup and shutdown). */ class Tags /** * Registry save/load * *********************************************************** */(private val col: Collection) : TagManager() { private val mTags = TreeMap<String, Int?>() private var mChanged = false override fun load(json: String) { val tags = JSONObject(json) for (t in tags.keys()) { mTags[t] = tags.getInt(t) } mChanged = false } override fun flush() { if (mChanged) { val tags = JSONObject() for ((key, value) in mTags) { tags.put(key, value) } val contentValues = ContentValues() contentValues.put("tags", Utils.jsonToString(tags)) // TODO: the database update call here sets mod = true. Verify if this is intended. col.db.update("col", contentValues) mChanged = false } } /* * Registering and fetching tags * *********************************************************** */ /** {@inheritDoc} */ override fun register(tags: Iterable<String>, usn: Int?, clear_first: Boolean) { // boolean found = false; for (t in tags) { if (!mTags.containsKey(t)) { mTags[t] = usn ?: col.usn() mChanged = true } } // if (found) { // runHook("newTag"); // TODO // } } override fun all(): List<String> { return ArrayList(mTags.keys) } /** Add any missing tags from notes to the tags list. */ override fun registerNotes(nids: kotlin.collections.Collection<Long>?) { // when called with a null argument, the old list is cleared first. val lim: String if (nids != null) { lim = " WHERE id IN " + Utils.ids2str(nids) } else { lim = "" mTags.clear() mChanged = true } val tags: MutableList<String?> = ArrayList(col.noteCount()) col.db.query("SELECT DISTINCT tags FROM notes$lim").use { cursor -> while (cursor.moveToNext()) { tags.add(cursor.getString(0)) } } val tagSet = HashSet(split(TextUtils.join(" ", tags))) register(tagSet) } override fun allItems(): Set<TagUsnTuple> { return mTags.entries.map { (key, value): Map.Entry<String, Int?> -> TagUsnTuple( key, value!! ) }.toSet() } override fun save() { mChanged = true } /** {@inheritDoc} */ override fun byDeck(did: DeckId, children: Boolean): ArrayList<String> { val tags: List<String?> = if (children) { val values: kotlin.collections.Collection<Long> = col.decks.children(did).values val dids = ArrayList<Long>(values.size) dids.add(did) dids.addAll(values) col.db.queryStringList( "SELECT DISTINCT n.tags FROM cards c, notes n WHERE c.nid = n.id AND c.did IN " + Utils.ids2str( dids ) ) } else { col.db.queryStringList( "SELECT DISTINCT n.tags FROM cards c, notes n WHERE c.nid = n.id AND c.did = ?", did ) } // Cast to set to remove duplicates // Use methods used to get all tags to parse tags here as well. return ArrayList(HashSet(split(TextUtils.join(" ", tags)))) } /* * Bulk addition/removal from notes * *********************************************************** */ /** {@inheritDoc} */ override fun bulkAdd(ids: List<Long>, tags: String, add: Boolean) { val newTags: List<String> = split(tags) if (newTags.isEmpty()) { return } // cache tag names if (add) { register(newTags) } // find notes missing the tags val l: String = if (add) { "tags not " } else { "tags " } val lim = StringBuilder() for (t in newTags) { if (lim.isNotEmpty()) { lim.append(" or ") } val replaced = t.replace("*", "%") lim.append(l).append("like '% ").append(replaced).append(" %'") } val res = ArrayList<Array<Any>>( col.db.queryScalar( "select count() from notes where id in " + Utils.ids2str(ids) + " and (" + lim + ")" ) ) col .db .query( "select id, tags from notes where id in " + Utils.ids2str(ids) + " and (" + lim + ")" ).use { cur -> if (add) { while (cur.moveToNext()) { res.add( arrayOf( addToStr(tags, cur.getString(1)), TimeManager.time.intTime(), col.usn(), cur.getLong(0) ) ) } } else { while (cur.moveToNext()) { res.add( arrayOf( remFromStr(tags, cur.getString(1)), TimeManager.time.intTime(), col.usn(), cur.getLong(0) ) ) } } } // update tags col.db.executeMany("update notes set tags=:t,mod=:n,usn=:u where id = :id", res) } /* * String-based utilities * *********************************************************** */ /** {@inheritDoc} */ override fun split(tags: String): ArrayList<String> { val list = ArrayList<String>(tags.length) for (s in tags.replace('\u3000', ' ').split("\\s".toRegex()).toTypedArray()) { if (s.isNotEmpty()) { list.add(s) } } return list } /** {@inheritDoc} */ override fun join(tags: kotlin.collections.Collection<String>): String { return if (tags.isEmpty()) { "" } else { val joined = tags.joinToString(" ") String.format(Locale.US, " %s ", joined) } } /** Add tags if they don't exist, and canonify */ fun addToStr(addtags: String, tags: String): String { val currentTags: MutableList<String> = split(tags) for (tag in split(addtags)) { if (!inList(tag, currentTags)) { currentTags.add(tag) } } return join(canonify(currentTags)) } // submethod of remFromStr in anki private fun wildcard(pat: String, str: String): Boolean { val patReplaced = Pattern.quote(pat).replace("\\*", ".*") return Pattern.compile(patReplaced, Pattern.CASE_INSENSITIVE or Pattern.UNICODE_CASE) .matcher(str).matches() } /** {@inheritDoc} */ override fun remFromStr(deltags: String, tags: String): String { val currentTags: MutableList<String> = split(tags) for (tag in split(deltags)) { val remove: MutableList<String> = ArrayList() // Usually not a lot of tags are removed simultaneously. // So don't put initial capacity for (tx in currentTags) { if (tag.equals(tx, ignoreCase = true) || wildcard(tag, tx)) { remove.add(tx) } } // remove them for (r in remove) { currentTags.remove(r) } } return join(currentTags) } /* * List-based utilities * *********************************************************** */ /** {@inheritDoc} */ override fun canonify(tagList: List<String>): TreeSet<String> { // NOTE: The python version creates a list of tags, puts them into a set, then sorts them. The TreeSet // used here already guarantees uniqueness and sort order, so we return it as-is without those steps. val strippedTags = TreeSet(java.lang.String.CASE_INSENSITIVE_ORDER) for (t in tagList) { var s = sCanonify.matcher(t).replaceAll("") for (existingTag in mTags.keys) { if (s.equals(existingTag, ignoreCase = true)) { s = existingTag } } strippedTags.add(s) } return strippedTags } /** {@inheritDoc} */ override fun inList(tag: String, tags: Iterable<String>): Boolean { for (t in tags) { if (t.equals(tag, ignoreCase = true)) { return true } } return false } /** * Sync handling * *********************************************************** */ override fun beforeUpload() { var changed = false for ((key, value) in mTags) { if (value != 0) { mTags[key] = 0 changed = true } } if (changed) { save() } } /* * *********************************************************** * The methods below are not in LibAnki. * *********************************************************** */ /** Add a tag to the collection. We use this method instead of exposing mTags publicly. */ override fun add(tag: String, usn: Int?) { mTags[tag] = usn } /** Whether any tags have a usn of -1 */ override fun minusOneValue(): Boolean { return mTags.containsValue(-1) } companion object { private val sCanonify = Pattern.compile("[\"']") } }
gpl-3.0
25c0b70640463b8ec96d1c42609a6daf
35.405325
112
0.470622
4.747299
false
false
false
false
CarrotCodes/Pellet
logging/src/main/kotlin/dev.pellet/logging/PelletLogElements.kt
1
1304
package dev.pellet.logging public class PelletLogElements( startingElements: Map<String, PelletLogElement> = mapOf() ) { private val elements = startingElements.toMutableMap() fun add(key: String, element: PelletLogElement): PelletLogElements { elements += key to element return this } fun add(key: String, string: String?): PelletLogElements { elements += key to logElement(string) return this } fun add(key: String, number: Number?): PelletLogElements { elements += key to logElement(number) return this } fun add(key: String, boolean: Boolean?): PelletLogElements { elements += key to logElement(boolean) return this } fun add(key: String, throwable: Throwable?): PelletLogElements { val throwableString = throwable?.stackTraceToString() return add(key, throwableString) } fun add(key: String, loggable: PelletLoggable): PelletLogElements { elements += key to logElement(loggable) return this } fun all(): Map<String, PelletLogElement> { return elements } } public fun logElements( builder: PelletLogElements.() -> Unit ): () -> PelletLogElements { return { PelletLogElements(mapOf()).apply(builder) } }
apache-2.0
f53586b260216fcdead79e749c6d7b0b
25.612245
72
0.64954
4.405405
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/crossing_type/AddCrossingType.kt
1
3019
package de.westnordost.streetcomplete.quests.crossing_type import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression import de.westnordost.streetcomplete.data.meta.updateCheckDateForKey import de.westnordost.streetcomplete.data.meta.updateWithCheckDate import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.osm.mapdata.Element import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.PEDESTRIAN class AddCrossingType : OsmElementQuestType<CrossingType> { /* Always ask for deprecated/meaningless values (island, unknown, yes) Only ask again for crossing types that are known to this quest so to be conservative with existing data */ private val crossingFilter by lazy { """ nodes with highway = crossing and foot != no and ( !crossing or crossing ~ island|unknown|yes or ( crossing ~ traffic_signals|uncontrolled|zebra|marked|unmarked and crossing older today -8 years ) ) """.toElementFilterExpression()} private val excludedWaysFilter by lazy { """ ways with highway and access ~ private|no """.toElementFilterExpression()} override val commitMessage = "Add crossing type" override val wikiLink = "Key:crossing" override val icon = R.drawable.ic_quest_pedestrian_crossing override val questTypeAchievements = listOf(PEDESTRIAN) override fun getTitle(tags: Map<String, String>) = R.string.quest_crossing_type_title override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> { val excludedWayNodeIds = mutableSetOf<Long>() mapData.ways .filter { excludedWaysFilter.matches(it) } .flatMapTo(excludedWayNodeIds) { it.nodeIds } return mapData.nodes .filter { crossingFilter.matches(it) && it.id !in excludedWayNodeIds } } override fun isApplicableTo(element: Element): Boolean? = if (!crossingFilter.matches(element)) false else null override fun createForm() = AddCrossingTypeForm() override fun applyAnswerTo(answer: CrossingType, changes: StringMapChangesBuilder) { val previous = changes.getPreviousValue("crossing") if(previous == "island") { changes.modify("crossing", answer.osmValue) changes.addOrModify("crossing:island", "yes") } else { if (answer == CrossingType.MARKED && previous in listOf("zebra", "marked", "uncontrolled")) { changes.updateCheckDateForKey("crossing") } else { changes.updateWithCheckDate("crossing", answer.osmValue) } } } }
gpl-3.0
b79241d56db6804256dda25fea51865d
39.253333
105
0.696257
4.916938
false
false
false
false
youkai-app/Youkai
app/src/main/kotlin/app/youkai/data/service/RequestBuilder.kt
1
2907
package app.youkai.data.service import app.youkai.util.ext.append class RequestBuilder<T>(val id: String, val call: (String, Map<String, String>, Map<String, String>) -> T) { private val INCLUDE: String = "include" private val FIELDS: String = "fields" private val FILTER: String = "filter" private val SORT: String = "sort" private val PAGE: String = "page" private val DELIMITER: String = "," private val headerMap = mutableMapOf<String, String>() private val queryMap = mutableMapOf<String, String>() fun get(): T { return call(id, headerMap, queryMap) } fun withHeader(header: String, value: String): RequestBuilder<T> { headerMap.put(header, value) return this } /** * Adds a query: include=relationship[1],relationship[2] ... * Related documentation: @see http://jsonapi.org/format/#fetching-includes * @param relationship The names of top-level relationships. * Note: not the type of the relationship's returned object. */ fun include(vararg relationship: String): RequestBuilder<T> { queryMap.append(INCLUDE, relationship.joinToString(DELIMITER), DELIMITER) return this } /** * Adds a query: include=relationship.nestedRelationship[1],relationship.nestedRelationship[2] ... * Related documentation: @see http://jsonapi.org/format/#fetching-includes * @param relationship The name of the relationship top-level relationship. * Note: not the type of the relationship's returned object. * @param nestedRelationship The names of sub-relationships to [relationship] */ fun includeNested(relationship: String, vararg nestedRelationship: String): RequestBuilder<T> { if (nestedRelationship.isEmpty()) throw IllegalArgumentException("includeNested() should only be used when relationships of relationships are required.") nestedRelationship.forEach { queryMap.append(INCLUDE, "$relationship.$it", DELIMITER) } return this } fun fields(context: String, vararg queryParameter: String): RequestBuilder<T> { queryMap.append("$FIELDS[$context]", queryParameter.joinToString(DELIMITER), DELIMITER) return this } fun filter(context: String, vararg queryParameter: String): RequestBuilder<T> { queryMap.append("$FILTER[$context]", queryParameter.joinToString(DELIMITER), DELIMITER) return this } fun sort(queryParameter: String, descending: Boolean = false): RequestBuilder<T> { queryMap.append(SORT, if (descending) "-$queryParameter" else queryParameter, DELIMITER) return this } fun page(context: String, vararg queryParameter: Int): RequestBuilder<T> { queryMap.append("$PAGE[$context]", queryParameter.joinToString(DELIMITER), DELIMITER) return this } }
gpl-3.0
ea6839aba6a9951987aef56d8a370b54
39.388889
131
0.679739
4.621622
false
false
false
false
ChrisZhong/organization-model
chazm-model/src/main/kotlin/runtimemodels/chazm/model/parser/entity/ParseAttribute.kt
2
1506
package runtimemodels.chazm.model.parser.entity import runtimemodels.chazm.api.entity.Attribute import runtimemodels.chazm.api.entity.AttributeId import runtimemodels.chazm.api.organization.Organization import runtimemodels.chazm.model.entity.EntityFactory import runtimemodels.chazm.model.entity.impl.DefaultAttributeId import runtimemodels.chazm.model.parser.attribute import runtimemodels.chazm.model.parser.build import javax.inject.Inject import javax.inject.Singleton import javax.xml.namespace.QName import javax.xml.stream.XMLStreamException import javax.xml.stream.events.StartElement @Singleton internal class ParseAttribute @Inject constructor( private val entityFactory: EntityFactory ) { fun canParse(qName: QName): Boolean = ATTRIBUTE_ELEMENT == qName.localPart operator fun invoke(element: StartElement, organization: Organization, attributes: MutableMap<String, AttributeId>) { val id = DefaultAttributeId(element attribute NAME_ATTRIBUTE) try { val type = Attribute.Type.valueOf(element attribute TYPE_ATTRIBUTE) build(id, attributes, element, { entityFactory.build(it, type) }, organization::add) } catch (e: IllegalArgumentException) { throw XMLStreamException(e) } } companion object { private const val ATTRIBUTE_ELEMENT = "Attribute" //$NON-NLS-1$ private const val NAME_ATTRIBUTE = "name" //$NON-NLS-1$ private const val TYPE_ATTRIBUTE = "type" //$NON-NLS-1$ } }
apache-2.0
d3d86066835bce833382a86910ebb35b
39.702703
121
0.752324
4.429412
false
false
false
false
sabi0/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/inference/MethodCallConstraint.kt
2
1370
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.processors.inference import com.intellij.psi.PsiSubstitutor import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession import com.intellij.psi.impl.source.resolve.graphInference.constraints.ConstraintFormula import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression class MethodCallConstraint(private val callRef: GrReferenceExpression, val candidate: MethodCandidate) : ConstraintFormula { val method = candidate.method override fun reduce(session: InferenceSession, constraints: MutableList<ConstraintFormula>): Boolean { processArguments(constraints) return true } private fun processArguments(constraints: MutableList<ConstraintFormula>) { val argInfos = candidate.argumentMapping argInfos.forEach { argument, pair -> val leftType = pair.second ?: return@forEach if (argument.type != null) { constraints.add(TypeConstraint(leftType, argument.type, callRef)) } if (argument.expression != null) { constraints.add(ExpressionConstraint(argument.expression, leftType)) } } } override fun apply(substitutor: PsiSubstitutor, cache: Boolean) {} }
apache-2.0
28d7531454e0a91270a8c204da31f032
41.84375
140
0.772263
4.659864
false
false
false
false
ns2j/nos2jdbc-tutorial
nos2jdbc-tutorial-kotlin-spring/src/main/kotlin/nos2jdbc/tutorial/kotlinspring/service/LunchFeeService.kt
1
1584
package nos2jdbc.tutorial.kotlinspring.service import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import nos2jdbc.tutorial.kotlinspring.gen.service.LunchFeeServiceBase import nos2jdbc.tutorial.kotlinspring.entity.nonauto.Ym import nos2jdbc.tutorial.kotlinspring.entity.nonauto.MemberKey import nos2jdbc.tutorial.kotlinspring.entity.nonauto.rollup.Key @Service @Transactional class LunchFeeService: LunchFeeServiceBase() { fun getYm() : List<Ym> { sqlFilePathPrefix = "sql/"; return selectBySqlFile(Ym::class.java, "sum.sql").getResultList(); } fun getMember() : List<MemberKey> { sqlFilePathPrefix = "sql/"; return selectBySqlFile(MemberKey::class.java, "sum.sql").getResultList(); } fun getRollup() : List<Key> { sqlFilePathPrefix = "sql/"; return selectBySqlFile(Key::class.java, "rollup.sql").getResultList(); } fun getRollup2() : List<Key> { sqlFilePathPrefix = "sql/"; return selectBySqlFile(Key::class.java, "rollup2.sql").getResultList(); } fun getRollup3() : List<Key> { sqlFilePathPrefix = "sql/"; return selectBySqlFile(Key::class.java, "rollup3.sql").getResultList(); } fun getCube() : List<Key> { sqlFilePathPrefix = "sql/"; return selectBySqlFile(Key::class.java, "cube.sql").getResultList(); } fun getCubeWithJoin() : List<Key> { sqlFilePathPrefix = "sql/"; return selectBySqlFile(Key::class.java, "cube_with_join.sql").getResultList(); } }
apache-2.0
f46e12f525a0e5cbdc0ba7043857419a
36.738095
86
0.690657
3.64977
false
false
false
false
timusus/Shuttle
app/src/main/java/com/simplecity/amp_library/ui/screens/nowplaying/PlayerPresenter.kt
1
10454
package com.simplecity.amp_library.ui.screens.nowplaying import android.app.Activity import android.content.Context import android.content.IntentFilter import com.cantrowitz.rxbroadcast.RxBroadcast import com.simplecity.amp_library.ShuttleApplication import com.simplecity.amp_library.playback.MediaManager import com.simplecity.amp_library.playback.PlaybackMonitor import com.simplecity.amp_library.playback.constants.InternalIntents import com.simplecity.amp_library.ui.common.Presenter import com.simplecity.amp_library.ui.screens.songs.menu.SongMenuPresenter import com.simplecity.amp_library.utils.LogUtils import com.simplecity.amp_library.utils.SettingsManager import com.simplecity.amp_library.utils.ShuttleUtils import com.simplecity.amp_library.utils.menu.song.SongsMenuCallbacks import com.simplecity.amp_library.utils.playlists.FavoritesPlaylistManager import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import java.util.concurrent.TimeUnit import javax.inject.Inject class PlayerPresenter @Inject constructor( private val context: Context, private val mediaManager: MediaManager, private val playbackMonitor: PlaybackMonitor, private val settingsManager: SettingsManager, private val favoritesPlaylistManager: FavoritesPlaylistManager, private val songMenuPresenter: SongMenuPresenter ) : Presenter<PlayerView>(), SongsMenuCallbacks by songMenuPresenter { private var startSeekPos: Long = 0 private var lastSeekEventTime: Long = 0 private var currentPlaybackTime: Long = 0 private var currentPlaybackTimeVisible: Boolean = false private var isFavoriteDisposable: Disposable? = null override fun bindView(view: PlayerView) { super.bindView(view) songMenuPresenter.bindView(view) updateTrackInfo() updateShuffleMode() updatePlaystate() updateRepeatMode() addDisposable( playbackMonitor.progressObservable //.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { progress -> view.setSeekProgress((progress!! * 1000).toInt()) }, { error -> LogUtils.logException(TAG, "PlayerPresenter: Error updating seek progress", error) }) ) addDisposable( playbackMonitor.currentTimeObservable //.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { pos -> refreshTimeText(pos!! / 1000) }, { error -> LogUtils.logException(TAG, "PlayerPresenter: Error refreshing time text", error) }) ) addDisposable( Flowable.interval(500, TimeUnit.MILLISECONDS) .onBackpressureDrop() .observeOn(AndroidSchedulers.mainThread()) .subscribe( { setCurrentTimeVisibility(mediaManager.isPlaying || !currentPlaybackTimeVisible) }, { error -> LogUtils.logException(TAG, "PlayerPresenter: Error emitting current time", error) }) ) val filter = IntentFilter() filter.addAction(InternalIntents.META_CHANGED) filter.addAction(InternalIntents.QUEUE_CHANGED) filter.addAction(InternalIntents.PLAY_STATE_CHANGED) filter.addAction(InternalIntents.SHUFFLE_CHANGED) filter.addAction(InternalIntents.REPEAT_CHANGED) filter.addAction(InternalIntents.SERVICE_CONNECTED) addDisposable( RxBroadcast.fromBroadcast(context, filter) .toFlowable(BackpressureStrategy.LATEST) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { intent -> when (intent.action) { InternalIntents.META_CHANGED -> updateTrackInfo() InternalIntents.QUEUE_CHANGED -> updateTrackInfo() InternalIntents.PLAY_STATE_CHANGED -> { updateTrackInfo() updatePlaystate() } InternalIntents.SHUFFLE_CHANGED -> { updateTrackInfo() updateShuffleMode() } InternalIntents.REPEAT_CHANGED -> updateRepeatMode() InternalIntents.SERVICE_CONNECTED -> { updateTrackInfo() updatePlaystate() updateShuffleMode() updateRepeatMode() } } }, { error -> LogUtils.logException(TAG, "PlayerPresenter: Error sending broadcast", error) } ) ) } override fun unbindView(view: PlayerView) { super.unbindView(view) songMenuPresenter.unbindView(view) } private fun refreshTimeText(playbackTime: Long) { if (playbackTime != currentPlaybackTime) { view?.currentTimeChanged(playbackTime) if (settingsManager.displayRemainingTime()) { view?.totalTimeChanged(-(mediaManager.duration / 1000 - playbackTime)) } } currentPlaybackTime = playbackTime } private fun setCurrentTimeVisibility(visible: Boolean) { if (visible != currentPlaybackTimeVisible) { view?.currentTimeVisibilityChanged(visible) } currentPlaybackTimeVisible = visible } private fun updateFavorite(isFavorite: Boolean) { view?.favoriteChanged(isFavorite) } fun updateTrackInfo() { view?.trackInfoChanged(mediaManager.song) view?.queueChanged(mediaManager.queuePosition + 1, mediaManager.queue.size) view?.currentTimeChanged(mediaManager.position / 1000) updateRemainingTime() isFavoriteDisposable?.dispose() isFavoriteDisposable = favoritesPlaylistManager.isFavorite(mediaManager.song) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { isFavorite -> updateFavorite(isFavorite) }, { error -> LogUtils.logException(TAG, "updateTrackInfo error", error) } ) addDisposable(isFavoriteDisposable!!) } private fun updatePlaystate() { view?.playbackChanged(mediaManager.isPlaying) } private fun updateShuffleMode() { view?.repeatChanged(mediaManager.repeatMode) view?.shuffleChanged(mediaManager.shuffleMode) } private fun updateRepeatMode() { view?.repeatChanged(mediaManager.repeatMode) } fun togglePlayback() { mediaManager.togglePlayback() } fun toggleFavorite() { mediaManager.toggleFavorite() } fun skip() { mediaManager.next() } fun prev(force: Boolean) { mediaManager.previous(force) } fun toggleShuffle() { mediaManager.toggleShuffleMode() updateShuffleMode() } fun toggleRepeat() { mediaManager.cycleRepeat() updateRepeatMode() } fun seekTo(progress: Int) { mediaManager.seekTo(mediaManager.duration * progress / 1000) } fun scanForward(repeatCount: Int, delta: Long) { var delta = delta if (repeatCount == 0) { startSeekPos = mediaManager.position lastSeekEventTime = 0 } else { if (delta < 5000) { // seek at 10x speed for the first 5 seconds delta *= 10 } else { // seek at 40x after that delta = 50000 + (delta - 5000) * 40 } var newpos = startSeekPos + delta val duration = mediaManager.duration if (newpos >= duration) { // move to next track mediaManager.next() startSeekPos -= duration // is OK to go negative newpos -= duration } if (delta - lastSeekEventTime > 250 || repeatCount < 0) { mediaManager.seekTo(newpos) lastSeekEventTime = delta } } } fun scanBackward(repeatCount: Int, delta: Long) { var delta = delta if (repeatCount == 0) { startSeekPos = mediaManager.position lastSeekEventTime = 0 } else { if (delta < 5000) { // seek at 10x speed for the first 5 seconds delta *= 10 } else { // seek at 40x after that delta = 50000 + (delta - 5000) * 40 } var newpos = startSeekPos - delta if (newpos < 0) { // move to previous track mediaManager.previous(true) val duration = mediaManager.duration startSeekPos += duration newpos += duration } if (delta - lastSeekEventTime > 250 || repeatCount < 0) { mediaManager.seekTo(newpos) lastSeekEventTime = delta } } } fun showLyrics() { view?.showLyricsDialog() } fun editTagsClicked(activity: Activity) { if (!ShuttleUtils.isUpgraded(activity.applicationContext as ShuttleApplication, settingsManager)) { view?.showUpgradeDialog() } else { view?.presentTagEditorDialog(mediaManager.song!!) } } fun songInfoClicked() { val song = mediaManager.song if (song != null) { view?.presentSongInfoDialog(song) } } fun updateRemainingTime() { if (settingsManager.displayRemainingTime()) { view?.totalTimeChanged(-((mediaManager.duration - mediaManager.position) / 1000)) } else { view?.totalTimeChanged(mediaManager.duration / 1000) } } fun shareClicked() { view?.shareSong(mediaManager.song!!) } companion object { private const val TAG = "PlayerPresenter" } }
gpl-3.0
448fc53adabf1a9592e4bab48882eced
33.963211
116
0.597666
5.237475
false
false
false
false
ademar111190/goodreads
app/src/main/java/ademar/goodreads/core/manager/SearchManager.kt
1
2890
package ademar.goodreads.core.manager import ademar.goodreads.core.ext.observatory import ademar.goodreads.core.injector.AppComponent import ademar.goodreads.core.model.Work import ademar.goodreads.core.service.Services import android.util.LongSparseArray import mobi.porquenao.gol.Gol import rx.Subscription import rx.android.schedulers.AndroidSchedulers.mainThread import rx.schedulers.Schedulers.io import rx.subjects.PublishSubject import java.util.* import javax.inject.Inject class SearchManager { @Inject lateinit var services: Services val works = ArrayList<Work>() val worksMap = LongSparseArray<Work>() val publish: PublishSubject<Work> = PublishSubject.create<Work>() var total = 0 var page = 1 var query: CharSequence = "" private var subscription: Subscription? = null init { AppComponent.Initialize.get().inject(this) } fun clear() { subscription?.unsubscribe() worksMap.clear() works.clear() total = 0 page = 1 query = "" } fun search(query: CharSequence, listener: (Boolean) -> Unit) { clear() this.query = query.trim() subscription = services.searchService .search(this.query) .subscribeOn(io()) .observeOn(mainThread()) .unsubscribeOn(io()) .observatory() .onSuccess { searchResponse -> val search = searchResponse.search total = search.total page++ search.works.forEach { work -> worksMap.put(work.id, work) works.add(work) publish.onNext(work) } listener.invoke(true) } .onError { throwable -> Gol.getDefault().error(throwable) listener.invoke(false) } .subscribe() } fun next(listener: (Boolean) -> Unit) { subscription = services.searchService .search(query, page) .subscribeOn(io()) .observeOn(mainThread()) .unsubscribeOn(io()) .observatory() .onSuccess { searchResponse -> val search = searchResponse.search page++ search.works.forEach { work -> worksMap.put(work.id, work) works.add(work) publish.onNext(work) } listener.invoke(true) } .onError { throwable -> Gol.getDefault().error(throwable) listener.invoke(false) } .subscribe() } }
mit
b7e27574cc9680eaa414fbc86cc2f579
29.421053
69
0.522837
5.179211
false
false
false
false
andrei-heidelbacher/metanalysis
analyzers/chronolens-decapsulations/src/main/kotlin/org/chronolens/decapsulations/java/JavaAnalyzer.kt
1
4168
/* * Copyright 2018-2021 Andrei Heidelbacher <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.chronolens.decapsulations.java import org.chronolens.core.model.Function import org.chronolens.core.model.SourceNode import org.chronolens.core.model.SourceNode.Companion.MEMBER_SEPARATOR import org.chronolens.core.model.SourceTree import org.chronolens.core.model.Type import org.chronolens.core.model.Variable import org.chronolens.core.model.parentId import org.chronolens.decapsulations.DecapsulationAnalyzer internal class JavaAnalyzer : DecapsulationAnalyzer() { override fun canProcess(sourcePath: String): Boolean = sourcePath.endsWith(".java") private fun getFieldName(signature: String): String? = listOf("is", "get", "set") .filter { signature.startsWith(it) } .map { signature.removePrefix(it).substringBefore('(') } .firstOrNull { it.firstOrNull()?.isUpperCase() == true } ?.let { "${it[0].toLowerCase()}${it.substring(1)}" } override fun getField(sourceTree: SourceTree, nodeId: String): String? { val node = sourceTree[nodeId] ?: return null return when (node) { is Variable -> nodeId is Function -> { val fieldName = getFieldName(node.signature) ?: return null val fieldId = "${nodeId.parentId}$MEMBER_SEPARATOR$fieldName" // TODO: figure out if should check only for non-nullable type. if (sourceTree[fieldId] is Variable?) fieldId else null } else -> null } } private fun getVisibility(modifiers: Set<String>): Int = when { PRIVATE_MODIFIER in modifiers -> PRIVATE_LEVEL PROTECTED_MODIFIER in modifiers -> PROTECTED_LEVEL PUBLIC_MODIFIER in modifiers -> PUBLIC_LEVEL else -> PACKAGE_LEVEL } private val SourceNode?.isInterface: Boolean get() = this is Type && INTERFACE_MODIFIER in modifiers private fun SourceTree.parentNodeIsInterface(nodeId: String): Boolean { val parentId = nodeId.parentId ?: return false return get(parentId)?.isInterface ?: false } override fun getVisibility(sourceTree: SourceTree, nodeId: String): Int { val node = sourceTree[nodeId] return when (node) { is Type -> getVisibility(node.modifiers) is Function -> if (sourceTree.parentNodeIsInterface(nodeId)) PUBLIC_LEVEL else getVisibility(node.modifiers) is Variable -> getVisibility(node.modifiers) else -> throw AssertionError("'$nodeId' has no visibility!") } } override fun isConstant(sourceTree: SourceTree, nodeId: String): Boolean { val node = sourceTree[nodeId] as? Variable? ?: return false val modifiers = node.modifiers return (STATIC_MODIFIER in modifiers && FINAL_MODIFIER in modifiers) || sourceTree.parentNodeIsInterface(nodeId) } companion object { internal const val PRIVATE_MODIFIER: String = "private" internal const val PROTECTED_MODIFIER: String = "protected" internal const val PUBLIC_MODIFIER: String = "public" internal const val INTERFACE_MODIFIER: String = "interface" internal const val STATIC_MODIFIER: String = "static" internal const val FINAL_MODIFIER: String = "final" internal const val PRIVATE_LEVEL: Int = 1 internal const val PACKAGE_LEVEL: Int = 2 internal const val PROTECTED_LEVEL: Int = 3 internal const val PUBLIC_LEVEL: Int = 4 } }
apache-2.0
1ac18c0631c9e8176f88ccadf96c6598
40.68
79
0.669866
4.688414
false
false
false
false
Light-Team/ModPE-IDE-Source
data/src/main/kotlin/com/brackeys/ui/data/repository/explorer/ExplorerRepositoryImpl.kt
1
4435
/* * Copyright 2021 Brackeys IDE contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.brackeys.ui.data.repository.explorer import com.brackeys.ui.data.storage.keyvalue.SettingsManager import com.brackeys.ui.data.utils.FileSorter import com.brackeys.ui.domain.providers.coroutines.DispatcherProvider import com.brackeys.ui.domain.repository.explorer.ExplorerRepository import com.brackeys.ui.filesystem.base.Filesystem import com.brackeys.ui.filesystem.base.model.FileModel import com.brackeys.ui.filesystem.base.model.FileTree import com.brackeys.ui.filesystem.base.model.PropertiesModel import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.withContext class ExplorerRepositoryImpl( private val dispatcherProvider: DispatcherProvider, private val settingsManager: SettingsManager, private val filesystem: Filesystem ) : ExplorerRepository { override suspend fun fetchFiles(fileModel: FileModel?): FileTree { return withContext(dispatcherProvider.io()) { val fileTree = filesystem.provideDirectory(fileModel ?: filesystem.defaultLocation()) fileTree.copy(children = fileTree.children .filter { if (it.isHidden) settingsManager.filterHidden else true } .sortedWith(FileSorter.getComparator(settingsManager.sortMode.toInt())) .sortedBy { !it.isFolder == settingsManager.foldersOnTop } ) } } override suspend fun createFile(fileModel: FileModel): FileModel { return withContext(dispatcherProvider.io()) { filesystem.createFile(fileModel) } } override suspend fun renameFile(fileModel: FileModel, fileName: String): FileModel { return withContext(dispatcherProvider.io()) { filesystem.renameFile(fileModel, fileName) } } override suspend fun propertiesOf(fileModel: FileModel): PropertiesModel { return withContext(dispatcherProvider.io()) { filesystem.propertiesOf(fileModel) } } @ExperimentalCoroutinesApi override suspend fun deleteFiles(source: List<FileModel>): Flow<FileModel> { return callbackFlow { source.forEach { val fileModel = filesystem.deleteFile(it) offer(fileModel) delay(20) } close() }.flowOn(dispatcherProvider.io()) } @ExperimentalCoroutinesApi override suspend fun copyFiles(source: List<FileModel>, destPath: String): Flow<FileModel> { return callbackFlow { val dest = filesystem.provideFile(destPath) source.forEach { val fileModel = filesystem.copyFile(it, dest) offer(fileModel) delay(20) } close() }.flowOn(dispatcherProvider.io()) } @ExperimentalCoroutinesApi override suspend fun cutFiles(source: List<FileModel>, destPath: String): Flow<FileModel> { return callbackFlow { val dest = filesystem.provideFile(destPath) source.forEach { fileModel -> filesystem.copyFile(fileModel, dest) filesystem.deleteFile(fileModel) offer(fileModel) delay(20) } close() }.flowOn(dispatcherProvider.io()) } override suspend fun compressFiles(source: List<FileModel>, dest: FileModel): Flow<FileModel> { return filesystem.compress(source, dest) .flowOn(dispatcherProvider.io()) } override suspend fun extractAll(source: FileModel, dest: FileModel): Flow<FileModel> { return filesystem.extractAll(source, dest) .flowOn(dispatcherProvider.io()) } }
apache-2.0
3d4a0637ec86c8c7b72ab10a34c6bcb3
36.91453
99
0.683427
4.977553
false
false
false
false
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/project/PlaceButton.kt
1
2028
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.project import javafx.event.EventHandler import javafx.scene.control.Button import javafx.scene.control.Tooltip import javafx.scene.image.ImageView import javafx.scene.input.DragEvent import javafx.scene.input.TransferMode import uk.co.nickthecoder.paratask.gui.DropFiles import uk.co.nickthecoder.paratask.misc.FileOperations import uk.co.nickthecoder.paratask.tools.places.DirectoryTool import uk.co.nickthecoder.paratask.tools.places.Place import java.io.File open class PlaceButton(val projectWindow: ProjectWindow, val place: Place) : Button() { init { onAction = EventHandler { onAction() } graphic = ImageView(place.resource.icon) text = place.label tooltip = Tooltip(place.path) if (place.isDirectory()) { DropFiles(TransferMode.ANY) { event, files -> onDroppedFiles(event, files) }.applyTo(this) } } fun onAction() { if (place.isDirectory()) { val dt = DirectoryTool() dt.directoriesP.value = listOf(place.file) projectWindow.tabs.addTool(dt) } } fun onDroppedFiles(event: DragEvent, files: List<File>) { val dir = place.file if (dir != null && dir.isDirectory) { FileOperations.instance.fileOperation(files, dir, event.transferMode) } } }
gpl-3.0
ec01d56f992f67e3ecbdae129ecdb6de
32.245902
102
0.717949
4.138776
false
false
false
false
calintat/Units
app/src/main/java/com/calintat/units/recycler/Adapter.kt
1
1316
package com.calintat.units.recycler import android.content.Context import android.support.v7.widget.RecyclerView import android.view.ViewGroup import com.calintat.units.api.MeasurementUnit import com.calintat.units.ui.ListItem import org.jetbrains.anko.AnkoContext class Adapter(private val context: Context) : RecyclerView.Adapter<ViewHolder>() { internal var units = emptyList<MeasurementUnit>() internal var input = Double.NaN // in base unit set(value) { field = value; notifyDataSetChanged() } internal lateinit var onClick: (Int) -> Unit internal lateinit var onLongClick: (String) -> Unit override fun getItemCount() = units.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { val unit = units[position] val output = unit.baseToSelf(context, input) holder.num.text = "${output.toFloat()}" holder.str.setText(unit.label) holder.sym.setText(unit.shortLabel) holder.itemView.setOnClickListener { onClick(position) } holder.itemView.setOnLongClickListener { onLongClick(output.toString()); true } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(ListItem().createView(AnkoContext.create(parent.context, parent))) } }
apache-2.0
7be67c1c61cccc379d48dfcdcf67a49f
28.266667
92
0.721125
4.553633
false
false
false
false
rsiebert/TVHClient
data/src/main/java/org/tvheadend/data/entity/EpgProgram.kt
1
7066
package org.tvheadend.data.entity import androidx.room.ColumnInfo import androidx.room.Ignore data class EpgProgram( override var eventId: Int = 0, override var nextEventId: Int = 0, override var channelId: Int = 0, override var start: Long = 0, override var stop: Long = 0, override var title: String? = null, override var subtitle: String? = null, override var summary: String? = null, override var description: String? = null, override var credits: String? = null, override var category: String? = null, override var keyword: String? = null, override var serieslinkId: Int = 0, override var episodeId: Int = 0, override var seasonId: Int = 0, override var brandId: Int = 0, override var contentType: Int = 0, override var ageRating: Int = 0, override var starRating: Int = 0, override var copyrightYear: Int = 0, override var firstAired: Long = 0, override var seasonNumber: Int = 0, override var seasonCount: Int = 0, override var episodeNumber: Int = 0, override var episodeCount: Int = 0, override var partNumber: Int = 0, override var partCount: Int = 0, override var episodeOnscreen: String? = null, override var image: String? = null, override var dvrId: Int = 0, override var serieslinkUri: String? = null, override var episodeUri: String? = null, override var modifiedTime: Long = 0, override var connectionId: Int = 0, override var channelName: String? = null, override var channelIcon: String? = null, override var recording: Recording? = null, override val progress: Int = 0 ) : ProgramInterface { override val duration: Int get() = ((stop - start) / 1000 / 60).toInt() } internal data class EpgProgramEntity( @ColumnInfo(name = "id") override var eventId: Int = 0, @Ignore override var nextEventId: Int = 0, @ColumnInfo(name = "channel_id") override var channelId: Int = 0, override var start: Long = 0, override var stop: Long = 0, override var title: String? = null, override var subtitle: String? = null, @Ignore override var summary: String? = null, @Ignore override var description: String? = null, @Ignore override var credits: String? = null, @Ignore override var category: String? = null, @Ignore override var keyword: String? = null, @Ignore override var serieslinkId: Int = 0, @Ignore override var episodeId: Int = 0, @Ignore override var seasonId: Int = 0, @Ignore override var brandId: Int = 0, @ColumnInfo(name = "content_type") override var contentType: Int = 0, @Ignore override var ageRating: Int = 0, @Ignore override var starRating: Int = 0, @Ignore override var copyrightYear: Int = 0, @Ignore override var firstAired: Long = 0, @Ignore override var seasonNumber: Int = 0, @Ignore override var seasonCount: Int = 0, @Ignore override var episodeNumber: Int = 0, @Ignore override var episodeCount: Int = 0, @Ignore override var partNumber: Int = 0, @Ignore override var partCount: Int = 0, @Ignore override var episodeOnscreen: String? = null, @Ignore override var image: String? = null, @Ignore override var dvrId: Int = 0, @Ignore override var serieslinkUri: String? = null, @Ignore override var episodeUri: String? = null, @Ignore override var modifiedTime: Long = 0, @ColumnInfo(name = "connection_id") override var connectionId: Int = 0, @Ignore override var channelName: String? = null, @Ignore override var channelIcon: String? = null, @Ignore override var recording: Recording? = null, @Ignore override val duration: Int = 0, @Ignore override val progress: Int = 0 ) : ProgramInterface { companion object { fun from(program: EpgProgram): EpgProgramEntity { return EpgProgramEntity( program.eventId, program.nextEventId, program.channelId, program.start, program.stop, program.title, program.subtitle, program.summary, program.description, program.credits, program.category, program.keyword, program.serieslinkId, program.episodeId, program.seasonId, program.brandId, program.contentType, program.ageRating, program.starRating, program.copyrightYear, program.firstAired, program.seasonNumber, program.seasonCount, program.episodeNumber, program.episodeCount, program.partNumber, program.partCount, program.episodeOnscreen, program.image, program.dvrId, program.serieslinkUri, program.episodeUri, program.modifiedTime, program.connectionId, program.channelName, program.channelIcon, program.recording, program.duration, program.progress ) } } fun toEpgProgram(): EpgProgram { return EpgProgram(eventId, nextEventId, channelId, start, stop, title, subtitle, summary, description, credits, category, keyword, serieslinkId, episodeId, seasonId, brandId, contentType, ageRating, starRating, copyrightYear, firstAired, seasonNumber, seasonCount, episodeNumber, episodeCount, partNumber, partCount, episodeOnscreen, image, dvrId, serieslinkUri, episodeUri, modifiedTime, connectionId, channelName, channelIcon, recording) } }
gpl-3.0
fa996a1431d5916fb7b6265721139539
37.612022
455
0.515992
5.410413
false
false
false
false
nemerosa/ontrack
ontrack-kdsl-acceptance/src/test/java/net/nemerosa/ontrack/kdsl/acceptance/tests/github/ingestion/ACCDSLGitHubIngestionTagging.kt
1
8781
package net.nemerosa.ontrack.kdsl.acceptance.tests.github.ingestion import net.nemerosa.ontrack.json.parseAsJson import net.nemerosa.ontrack.kdsl.acceptance.tests.support.resourceAsText import net.nemerosa.ontrack.kdsl.acceptance.tests.support.uid import net.nemerosa.ontrack.kdsl.spec.extension.general.label import net.nemerosa.ontrack.kdsl.spec.extension.git.gitCommitProperty import net.nemerosa.ontrack.kdsl.spec.extension.github.gitHub import net.nemerosa.ontrack.kdsl.spec.extension.github.ingestion.setBranchGitHubIngestionConfig import org.junit.jupiter.api.Test import kotlin.test.assertEquals class ACCDSLGitHubIngestionTagging : AbstractACCDSLGitHubIngestionTestSupport() { /** * Tests the tagging based on the commit property * * Scenario: * * * ingestion configuration based on defaults * * create a build with the commit property * * send a tag payload whose commit targets the build * * checks the build has been labelled */ @Test fun `Tagging on commit property by default`() { val projectName = uid("p") val project = ontrack.createProject(projectName, "") val branch = project.createBranch("main", "") // Configuration: create a GitHub configuration val gitHubConfiguration = fakeGitHubConfiguration() ontrack.gitHub.createConfig(gitHubConfiguration) // Build val build = branch.createBuild("1", "").apply { gitCommitProperty = "tag-commit" } // Pushing the ingestion config branch.setBranchGitHubIngestionConfig("") // Tag event val pushTagPayload = resourceAsText("/github/ingestion/tagging/push_tag.json") .replace("#repository", projectName) .replace("#ref", "refs/tags/2.1.0") .replace("#head_commit", "tag-commit") .replace("#base_ref", "refs/heads/${branch.name}") .parseAsJson() val pushTagPayloadUuid = sendPayloadToHook(gitHubConfiguration, "push", pushTagPayload) // At the end, waits for all payloads to be processed waitUntilPayloadIsProcessed(pushTagPayloadUuid) // Checks the promoted build is labelled with the tag assertEquals("2.1.0", build.label) } /** * Tests the tagging based on the latest promotion. * * Scenario: * * * ingestion configuration based on promotion * * create a promoted build * * create an extra build * * send a tag payload whose commit targets the latest build * * checks the promoted build has been labelled */ @Test fun `Tagging on promotion`() { val projectName = uid("p") val project = ontrack.createProject(projectName, "") val branch = project.createBranch("main", "") branch.createPromotionLevel("BRONZE", "") // Configuration: create a GitHub configuration val gitHubConfiguration = fakeGitHubConfiguration() ontrack.gitHub.createConfig(gitHubConfiguration) // Promoted build val promoted = branch.createBuild("1", "").apply { promote("BRONZE") gitCommitProperty = "any-commit" } // Build targeted by the tag val annotated = branch.createBuild("2", "").apply { gitCommitProperty = "tag-commit" } // Pushing the ingestion config branch.setBranchGitHubIngestionConfig( """ tagging: strategies: - type: promotion config: name: BRONZE """ ) // Tag event val pushTagPayload = resourceAsText("/github/ingestion/tagging/push_tag.json") .replace("#repository", projectName) .replace("#ref", "refs/tags/2.1.0") .replace("#head_commit", "tag-commit") .replace("#base_ref", "refs/heads/${branch.name}") .parseAsJson() val pushTagPayloadUuid = sendPayloadToHook(gitHubConfiguration, "push", pushTagPayload) // At the end, waits for all payloads to be processed waitUntilPayloadIsProcessed(pushTagPayloadUuid) // Checks the promoted build is labelled with the tag assertEquals("2.1.0", promoted.label) assertEquals(null, annotated.label) } /** * Tests the tagging based on the latest promotion with no prior tag commit * * Scenario: * * * ingestion configuration based on promotion * * create a promoted build * * create an extra build * * send a tag payload whose commit is not referred to by Ontrack * * checks the promoted build has been labelled */ @Test fun `Tagging on promotion without prior commit`() { val projectName = uid("p") val project = ontrack.createProject(projectName, "") val branch = project.createBranch("main", "") branch.createPromotionLevel("BRONZE", "") // Configuration: create a GitHub configuration val gitHubConfiguration = fakeGitHubConfiguration() ontrack.gitHub.createConfig(gitHubConfiguration) // Promoted build val promoted = branch.createBuild("1", "").apply { promote("BRONZE") gitCommitProperty = "any-commit" } // Build targeted by the tag val newest = branch.createBuild("2", "") // Pushing the ingestion config branch.setBranchGitHubIngestionConfig( """ tagging: strategies: - type: promotion config: name: BRONZE """ ) // Tag event val pushTagPayload = resourceAsText("/github/ingestion/tagging/push_tag.json") .replace("#repository", projectName) .replace("#ref", "refs/tags/2.1.0") .replace("#head_commit", "tag-commit") .replace("#base_ref", "refs/heads/${branch.name}") .parseAsJson() val pushTagPayloadUuid = sendPayloadToHook(gitHubConfiguration, "push", pushTagPayload) // At the end, waits for all payloads to be processed waitUntilPayloadIsProcessed(pushTagPayloadUuid) // Checks the promoted build is labelled with the tag assertEquals("2.1.0", promoted.label) assertEquals(null, newest.label) } /** * Tests the tagging based on the latest promotion with no prior tag commit and no default strategy * * Scenario: * * * ingestion configuration based on promotion * * create a promoted build * * create an extra build * * send a tag payload whose commit is not referred to by Ontrack * * checks the promoted build has been labelled */ @Test fun `Tagging on promotion without prior commit and no default strategy`() { val projectName = uid("p") val project = ontrack.createProject(projectName, "") val branch = project.createBranch("main", "") branch.createPromotionLevel("BRONZE", "") // Configuration: create a GitHub configuration val gitHubConfiguration = fakeGitHubConfiguration() ontrack.gitHub.createConfig(gitHubConfiguration) // Promoted build val promoted = branch.createBuild("1", "").apply { promote("BRONZE") gitCommitProperty = "any-commit" } // Build targeted by the tag val newest = branch.createBuild("2", "") // Pushing the ingestion config branch.setBranchGitHubIngestionConfig( """ tagging: commit-property: false strategies: - type: promotion config: name: BRONZE """ ) // Tag event val pushTagPayload = resourceAsText("/github/ingestion/tagging/push_tag.json") .replace("#repository", projectName) .replace("#ref", "refs/tags/2.1.0") .replace("#head_commit", "tag-commit") .replace("#base_ref", "refs/heads/${branch.name}") .parseAsJson() val pushTagPayloadUuid = sendPayloadToHook(gitHubConfiguration, "push", pushTagPayload) // At the end, waits for all payloads to be processed waitUntilPayloadIsProcessed(pushTagPayloadUuid) // Checks the promoted build is labelled with the tag assertEquals("2.1.0", promoted.label) assertEquals(null, newest.label) } }
mit
f3edd7710f66037930a56fa4f1543659
34.554656
103
0.601298
4.958216
false
true
false
false
d9n/intellij-rust
src/test/kotlin/org/rust/lang/core/completion/RsTypeAwareCompletionTest.kt
1
2012
package org.rust.lang.core.completion import java.io.File class RsTypeAwareCompletionTest : RsCompletionTestBase() { fun testMethodCallExpr() = checkSingleCompletion("S.transmogrify()", """ struct S; impl S { fn transmogrify(&self) {} } fn main() { S.trans/*caret*/ } """) fun testMethodCallExprWithParens() = checkSingleCompletion("x.transmogrify", """ struct S { transmogrificator: i32 } impl S { fn transmogrify(&self) {} } fn main() { let x: S = unimplemented!(); x.trans/*caret*/() } """) fun testMethodCallExprRef() = checkSingleCompletion("self.transmogrify()", """ struct S; impl S { fn transmogrify(&self) {} fn foo(&self) { self.trans/*caret*/ } } """) fun testMethodCallExprEnum() = checkSingleCompletion("self.quux()", """ enum E { X } impl E { fn quux(&self) {} fn bar(&self) { self.qu/*caret*/ } } """) fun testFieldExpr() = checkSingleCompletion("transmogrificator", """ struct S { transmogrificator: f32 } fn main() { let s = S { transmogrificator: 92}; s.trans/*caret*/ } """) fun testStaticMethod() = checkSingleCompletion("S::create()", """ struct S; impl S { fn create() -> S { S } } fn main() { let _ = S::cr/*caret*/; } """) fun testSelfMethod() = checkSingleCompletion("frobnicate()", """ trait Foo { fn frobnicate(&self); fn bar(&self) { self.frob/*caret*/ } } """) fun `test default method`() = checkSingleCompletion("frobnicate()", """ trait Frob { fn frobnicate(&self) { } } struct S; impl Frob for S {} fn foo(s: S) { s.frob/*caret*/ } """) }
mit
37375011c881eaf52314e72ea7a0b501
21.863636
84
0.483598
4.122951
false
true
false
false
nickbutcher/plaid
core/src/main/java/io/plaidapp/core/data/pocket/PocketUtils.kt
1
1888
/* * Copyright 2019 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.plaidapp.core.data.pocket import android.content.Context import android.content.Intent import android.content.pm.PackageManager /** * Adapted from https://github.com/Pocket/Pocket-AndroidWear-SDK/blob/master/library/src/com * /pocket/util/PocketUtil.java */ object PocketUtils { private const val PACKAGE = "com.ideashower.readitlater.pro" private const val MIME_TYPE = "text/plain" private const val EXTRA_SOURCE_PACKAGE = "source" private const val EXTRA_TWEET_STATUS_ID = "tweetStatusId" @JvmOverloads fun addToPocket( context: Context, url: String?, tweetStatusId: String? = null ) { val intent = Intent(Intent.ACTION_SEND).apply { `package` = PACKAGE type = MIME_TYPE putExtra(Intent.EXTRA_TEXT, url) tweetStatusId?.also { putExtra(EXTRA_TWEET_STATUS_ID, tweetStatusId) } putExtra(EXTRA_SOURCE_PACKAGE, context.packageName) } context.startActivity(intent) } fun isPocketInstalled(context: Context): Boolean { return try { context.packageManager.getPackageInfo(PACKAGE, 0) } catch (e: PackageManager.NameNotFoundException) { null } != null } }
apache-2.0
acd6e1b41a6eb28d2039eb84f8fe2f3c
30.466667
92
0.671081
4.2049
false
false
false
false